@naarang/ccc 2.1.0-beta.1 → 2.1.0-beta.2

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.
Files changed (2) hide show
  1. package/dist/index.js +13 -13
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -8,14 +8,14 @@ var GQ0=Object.create;var{getPrototypeOf:HQ0,defineProperty:$V,getOwnPropertyNam
8
8
  `;else if(Array.isArray(Z.headers))Z.headers.push(T,y)}this._recordFromReq.set(Z,{span:O,attributes:z,startTime:Y})}onRequestHeaders({request:Z,socket:J}){let X=this._recordFromReq.get(Z);if(!X)return;let $=this.getConfig(),{span:Y}=X,{remoteAddress:Q,remotePort:W}=J,K={[m1.ATTR_NETWORK_PEER_ADDRESS]:Q,[m1.ATTR_NETWORK_PEER_PORT]:W};if($.headersToSpanAttributes?.requestHeaders){let z=new Set($.headersToSpanAttributes.requestHeaders.map((H)=>H.toLowerCase())),G=this.parseRequestHeaders(Z);for(let[H,V]of G.entries())if(z.has(H)){let F=Array.isArray(V)?V.join(", "):V;K[`http.request.header.${H}`]=F}}Y.setAttributes(K)}onResponseHeaders({request:Z,response:J}){let X=this._recordFromReq.get(Z);if(!X)return;let{span:$,attributes:Y}=X,Q={[m1.ATTR_HTTP_RESPONSE_STATUS_CODE]:J.statusCode},W=this.getConfig();(0,nY.safeExecuteInTheMiddle)(()=>W.responseHook?.($,{request:Z,response:J}),(z)=>z&&this._diag.error("caught responseHook error: ",z),!0);let K=new Set;if(W.headersToSpanAttributes?.responseHeaders)W.headersToSpanAttributes?.responseHeaders.forEach((z)=>K.add(z.toLowerCase()));for(let z=0;z<J.headers.length;z=z+2){let G=J.headers[z].toString().toLowerCase(),H=J.headers[z+1];if(K.has(G))Q[`http.response.header.${G}`]=H.toString();if(G==="content-length"){let V=Number(H.toString());if(!isNaN(V))Q["http.response.header.content-length"]=V}}$.setAttributes(Q),$.setStatus({code:J.statusCode>=400?T6.SpanStatusCode.ERROR:T6.SpanStatusCode.UNSET}),X.attributes=Object.assign(Y,Q)}onDone({request:Z}){let J=this._recordFromReq.get(Z);if(!J)return;let{span:X,attributes:$,startTime:Y}=J;X.end(),this._recordFromReq.delete(Z),this.recordRequestDuration($,Y)}onError({request:Z,error:J}){let X=this._recordFromReq.get(Z);if(!X)return;let{span:$,attributes:Y,startTime:Q}=X;$.recordException(J),$.setStatus({code:T6.SpanStatusCode.ERROR,message:J.message}),$.end(),this._recordFromReq.delete(Z),Y[m1.ATTR_ERROR_TYPE]=J.message,this.recordRequestDuration(Y,Q)}recordRequestDuration(Z,J){let X={};[m1.ATTR_HTTP_RESPONSE_STATUS_CODE,m1.ATTR_HTTP_REQUEST_METHOD,m1.ATTR_SERVER_ADDRESS,m1.ATTR_SERVER_PORT,m1.ATTR_URL_SCHEME,m1.ATTR_ERROR_TYPE].forEach((Q)=>{if(Q in Z)X[Q]=Z[Q]});let Y=(0,oK.hrTimeToMilliseconds)((0,oK.hrTimeDuration)(J,(0,oK.hrTime)()))/1000;this._httpClientDurationHistogram.record(Y,X)}getRequestMethod(Z){let J={CONNECT:!0,OPTIONS:!0,HEAD:!0,GET:!0,POST:!0,PUT:!0,PATCH:!0,DELETE:!0,TRACE:!0};if(Z.toUpperCase()in J)return Z.toUpperCase();return"_OTHER"}}tc.UndiciInstrumentation=sc});var Jl=L((oL)=>{Object.defineProperty(oL,"__esModule",{value:!0});oL.UndiciInstrumentation=void 0;var Gk0=Zl();Object.defineProperty(oL,"UndiciInstrumentation",{enumerable:!0,get:function(){return Gk0.UndiciInstrumentation}})});var aK=L((Yl)=>{Object.defineProperty(Yl,"__esModule",{value:!0});Yl.ExpressLayerType=void 0;var _k0;(function(Z){Z.ROUTER="router",Z.MIDDLEWARE="middleware",Z.REQUEST_HANDLER="request_handler"})(_k0=Yl.ExpressLayerType||(Yl.ExpressLayerType={}))});var rK=L((Ql)=>{Object.defineProperty(Ql,"__esModule",{value:!0});Ql.AttributeNames=void 0;var Ok0;(function(Z){Z.EXPRESS_TYPE="express.type",Z.EXPRESS_NAME="express.name"})(Ok0=Ql.AttributeNames||(Ql.AttributeNames={}))});var sL=L((Wl)=>{Object.defineProperty(Wl,"__esModule",{value:!0});Wl._LAYERS_STORE_PROPERTY=Wl.kLayerPatched=void 0;Wl.kLayerPatched=Symbol("express-layer-patched");Wl._LAYERS_STORE_PROPERTY="__ot_middlewares"});var Fl=L((Hl)=>{Object.defineProperty(Hl,"__esModule",{value:!0});Hl.getActualMatchedRoute=Hl.getConstructedRoute=Hl.getLayerPath=Hl.asErrorAndMessage=Hl.isLayerIgnored=Hl.getLayerMetadata=Hl.getRouterPath=Hl.storeLayerPath=void 0;var tL=aK(),TX=rK(),IZ=sL(),jk0=(Z,J)=>{if(Array.isArray(Z[IZ._LAYERS_STORE_PROPERTY])===!1)Object.defineProperty(Z,IZ._LAYERS_STORE_PROPERTY,{enumerable:!1,value:[]});if(J===void 0)return{isLayerPathStored:!1};return Z[IZ._LAYERS_STORE_PROPERTY].push(J),{isLayerPathStored:!0}};Hl.storeLayerPath=jk0;var Mk0=(Z,J)=>{let X=J.handle?.stack?.[0];if(X?.route?.path)return`${Z}${X.route.path}`;if(X?.handle?.stack)return Hl.getRouterPath(Z,X);return Z};Hl.getRouterPath=Mk0;var Ak0=(Z,J,X)=>{if(J.name==="router"){let $=Hl.getRouterPath("",J),Y=$?$:X||Z||"/";return{attributes:{[TX.AttributeNames.EXPRESS_NAME]:Y,[TX.AttributeNames.EXPRESS_TYPE]:tL.ExpressLayerType.ROUTER},name:`router - ${Y}`}}else if(J.name==="bound dispatch"||J.name==="handle")return{attributes:{[TX.AttributeNames.EXPRESS_NAME]:(Z||X)??"request handler",[TX.AttributeNames.EXPRESS_TYPE]:tL.ExpressLayerType.REQUEST_HANDLER},name:`request handler${J.path?` - ${Z||X}`:""}`};else return{attributes:{[TX.AttributeNames.EXPRESS_NAME]:J.name,[TX.AttributeNames.EXPRESS_TYPE]:tL.ExpressLayerType.MIDDLEWARE},name:`middleware - ${J.name}`}};Hl.getLayerMetadata=Ak0;var Tk0=(Z,J)=>{if(typeof J==="string")return J===Z;else if(J instanceof RegExp)return J.test(Z);else if(typeof J==="function")return J(Z);else throw TypeError("Pattern is in unsupported datatype")},qk0=(Z,J,X)=>{if(Array.isArray(X?.ignoreLayersType)&&X?.ignoreLayersType?.includes(J))return!0;if(Array.isArray(X?.ignoreLayers)===!1)return!1;try{for(let $ of X.ignoreLayers)if(Tk0(Z,$))return!0}catch($){}return!1};Hl.isLayerIgnored=qk0;var Ck0=(Z)=>Z instanceof Error?[Z,Z.message]:[String(Z),String(Z)];Hl.asErrorAndMessage=Ck0;var Nk0=(Z)=>{let J=Z[0];if(Array.isArray(J))return J.map((X)=>zl(X)||"").join(",");return zl(J)};Hl.getLayerPath=Nk0;var zl=(Z)=>{if(typeof Z==="string")return Z;if(Z instanceof RegExp||typeof Z==="number")return Z.toString();return};function Gl(Z){let X=(Array.isArray(Z[IZ._LAYERS_STORE_PROPERTY])?Z[IZ._LAYERS_STORE_PROPERTY]:[]).filter(($)=>$!=="/"&&$!=="/*");if(X.length===1&&X[0]==="*")return"*";return X.join("").replace(/\/{2,}/g,"/")}Hl.getConstructedRoute=Gl;function Rk0(Z){let J=Array.isArray(Z[IZ._LAYERS_STORE_PROPERTY])?Z[IZ._LAYERS_STORE_PROPERTY]:[];if(J.length===0)return;if(J.every((Q)=>Q==="/"))return Z.originalUrl==="/"?"/":void 0;let X=Gl(Z);if(X==="*")return X;if(X.includes("/")&&(X.includes(",")||X.includes("\\")||X.includes("*")||X.includes("[")))return X;let $=X.startsWith("/")?X:`/${X}`;return $.length>0&&(Z.originalUrl===$||Z.originalUrl.startsWith($)||Pk0($))?$:void 0}Hl.getActualMatchedRoute=Rk0;function Pk0(Z){return Z.includes(":")||Z.includes("*")}});var Ll=L((Bl)=>{Object.defineProperty(Bl,"__esModule",{value:!0});Bl.PACKAGE_NAME=Bl.PACKAGE_VERSION=void 0;Bl.PACKAGE_VERSION="0.57.0";Bl.PACKAGE_NAME="@opentelemetry/instrumentation-express"});var Tl=L((Ml)=>{Object.defineProperty(Ml,"__esModule",{value:!0});Ml.ExpressInstrumentation=void 0;var Dl=H1(),E8=f(),_l=aK(),Ol=rK(),W5=Fl(),wl=Ll(),qX=H0(),hk0=p0(),sK=sL();class jl extends qX.InstrumentationBase{constructor(Z={}){super(wl.PACKAGE_NAME,wl.PACKAGE_VERSION,Z)}init(){return[new qX.InstrumentationNodeModuleDefinition("express",[">=4.0.0 <6"],(Z)=>{let J=typeof Z?.Router?.prototype?.route==="function",X=J?Z.Router.prototype:Z.Router;if((0,qX.isWrapped)(X.route))this._unwrap(X,"route");if(this._wrap(X,"route",this._getRoutePatch()),(0,qX.isWrapped)(X.use))this._unwrap(X,"use");if(this._wrap(X,"use",this._getRouterUsePatch()),(0,qX.isWrapped)(Z.application.use))this._unwrap(Z.application,"use");return this._wrap(Z.application,"use",this._getAppUsePatch(J)),Z},(Z)=>{if(Z===void 0)return;let X=typeof Z?.Router?.prototype?.route==="function"?Z.Router.prototype:Z.Router;this._unwrap(X,"route"),this._unwrap(X,"use"),this._unwrap(Z.application,"use")})]}_getRoutePatch(){let Z=this;return function(J){return function(...$){let Y=J.apply(this,$),Q=this.stack[this.stack.length-1];return Z._applyPatch(Q,(0,W5.getLayerPath)($)),Y}}}_getRouterUsePatch(){let Z=this;return function(J){return function(...$){let Y=J.apply(this,$),Q=this.stack[this.stack.length-1];return Z._applyPatch(Q,(0,W5.getLayerPath)($)),Y}}}_getAppUsePatch(Z){let J=this;return function(X){return function(...Y){let Q=Z?this.router:this._router,W=X.apply(this,Y);if(Q){let K=Q.stack[Q.stack.length-1];J._applyPatch(K,(0,W5.getLayerPath)(Y))}return W}}}_applyPatch(Z,J){let X=this;if(Z[sK.kLayerPatched]===!0)return;Z[sK.kLayerPatched]=!0,this._wrap(Z,"handle",($)=>{if($.length===4)return $;let Y=function(Q,W){let{isLayerPathStored:K}=(0,W5.storeLayerPath)(Q,J),z=(0,W5.getConstructedRoute)(Q),G=(0,W5.getActualMatchedRoute)(Q),H={[hk0.ATTR_HTTP_ROUTE]:G},V=(0,W5.getLayerMetadata)(z,Z,J),F=V.attributes[Ol.AttributeNames.EXPRESS_TYPE],B=(0,Dl.getRPCMetadata)(E8.context.active());if(B?.type===Dl.RPCType.HTTP)B.route=G;if((0,W5.isLayerIgnored)(V.name,F,X.getConfig())){if(F===_l.ExpressLayerType.MIDDLEWARE)Q[sK._LAYERS_STORE_PROPERTY].pop();return $.apply(this,arguments)}if(E8.trace.getSpan(E8.context.active())===void 0)return $.apply(this,arguments);let U=X._getSpanName({request:Q,layerType:F,route:z},V.name),D=X.tracer.startSpan(U,{attributes:Object.assign(H,V.attributes)}),_=E8.context.active(),O=E8.trace.setSpan(_,D),{requestHook:w}=X.getConfig();if(w)(0,qX.safeExecuteInTheMiddle)(()=>w(D,{request:Q,layerType:F,route:z}),(y)=>{if(y)E8.diag.error("express instrumentation: request hook failed",y)},!0);let j=!1;if(V.attributes[Ol.AttributeNames.EXPRESS_TYPE]===_l.ExpressLayerType.ROUTER)D.end(),j=!0,O=_;let q=()=>{if(j===!1)j=!0,D.end()},R=Array.from(arguments),T=R.findIndex((y)=>typeof y==="function");if(T>=0)arguments[T]=function(){let y=arguments[0],i=![void 0,null,"route","router"].includes(y);if(!j&&i){let[O0,d0]=(0,W5.asErrorAndMessage)(y);D.recordException(O0),D.setStatus({code:E8.SpanStatusCode.ERROR,message:d0})}if(j===!1)j=!0,Q.res?.removeListener("finish",q),D.end();if(!(Q.route&&i)&&K)Q[sK._LAYERS_STORE_PROPERTY].pop();let s=R[T];return E8.context.bind(_,s).apply(this,arguments)};try{return E8.context.bind(O,$).apply(this,arguments)}catch(y){let[i,s]=(0,W5.asErrorAndMessage)(y);throw D.recordException(i),D.setStatus({code:E8.SpanStatusCode.ERROR,message:s}),y}finally{if(!j)W.once("finish",q)}};for(let Q in $)Object.defineProperty(Y,Q,{get(){return $[Q]},set(W){$[Q]=W}});return Y})}_getSpanName(Z,J){let{spanNameHook:X}=this.getConfig();if(!(X instanceof Function))return J;try{return X(Z,J)??J}catch($){return E8.diag.error("express instrumentation: error calling span name rewrite hook",$),J}}}Ml.ExpressInstrumentation=jl});var ql=L((aY)=>{Object.defineProperty(aY,"__esModule",{value:!0});aY.AttributeNames=aY.ExpressLayerType=aY.ExpressInstrumentation=void 0;var fk0=Tl();Object.defineProperty(aY,"ExpressInstrumentation",{enumerable:!0,get:function(){return fk0.ExpressInstrumentation}});var bk0=aK();Object.defineProperty(aY,"ExpressLayerType",{enumerable:!0,get:function(){return bk0.ExpressLayerType}});var gk0=rK();Object.defineProperty(aY,"AttributeNames",{enumerable:!0,get:function(){return gk0.AttributeNames}})});var kl=L((Jj1,Sl)=>{Sl.exports=Il;function Il(Z,J,X){if(Z instanceof RegExp)Z=El(Z,X);if(J instanceof RegExp)J=El(J,X);var $=yl(Z,J,X);return $&&{start:$[0],end:$[1],pre:X.slice(0,$[0]),body:X.slice($[0]+Z.length,$[1]),post:X.slice($[1]+J.length)}}function El(Z,J){var X=J.match(Z);return X?X[0]:null}Il.range=yl;function yl(Z,J,X){var $,Y,Q,W,K,z=X.indexOf(Z),G=X.indexOf(J,z+1),H=z;if(z>=0&&G>0){if(Z===J)return[z,G];$=[],Q=X.length;while(H>=0&&!K){if(H==z)$.push(H),z=X.indexOf(Z,H+1);else if($.length==1)K=[$.pop(),G];else{if(Y=$.pop(),Y<Q)Q=Y,W=G;G=X.indexOf(J,H+1)}H=z<G&&z>=0?z:G}if($.length)K=[Q,W]}return K}});var dl=L((Xj1,ml)=>{var xl=kl();ml.exports=ik0;var vl="\x00SLASH"+Math.random()+"\x00",hl="\x00OPEN"+Math.random()+"\x00",J2="\x00CLOSE"+Math.random()+"\x00",fl="\x00COMMA"+Math.random()+"\x00",bl="\x00PERIOD"+Math.random()+"\x00";function Z2(Z){return parseInt(Z,10)==Z?parseInt(Z,10):Z.charCodeAt(0)}function lk0(Z){return Z.split("\\\\").join(vl).split("\\{").join(hl).split("\\}").join(J2).split("\\,").join(fl).split("\\.").join(bl)}function pk0(Z){return Z.split(vl).join("\\").split(hl).join("{").split(J2).join("}").split(fl).join(",").split(bl).join(".")}function gl(Z){if(!Z)return[""];var J=[],X=xl("{","}",Z);if(!X)return Z.split(",");var{pre:$,body:Y,post:Q}=X,W=$.split(",");W[W.length-1]+="{"+Y+"}";var K=gl(Q);if(Q.length)W[W.length-1]+=K.shift(),W.push.apply(W,K);return J.push.apply(J,W),J}function ik0(Z){if(!Z)return[];if(Z.substr(0,2)==="{}")Z="\\{\\}"+Z.substr(2);return rY(lk0(Z),!0).map(pk0)}function nk0(Z){return"{"+Z+"}"}function ok0(Z){return/^-?0\d/.test(Z)}function ak0(Z,J){return Z<=J}function rk0(Z,J){return Z>=J}function rY(Z,J){var X=[],$=xl("{","}",Z);if(!$)return[Z];var Y=$.pre,Q=$.post.length?rY($.post,!1):[""];if(/\$$/.test($.pre))for(var W=0;W<Q.length;W++){var K=Y+"{"+$.body+"}"+Q[W];X.push(K)}else{var z=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test($.body),G=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test($.body),H=z||G,V=$.body.indexOf(",")>=0;if(!H&&!V){if($.post.match(/,(?!,).*\}/))return Z=$.pre+"{"+$.body+J2+$.post,rY(Z);return[Z]}var F;if(H)F=$.body.split(/\.\./);else if(F=gl($.body),F.length===1){if(F=rY(F[0],!1).map(nk0),F.length===1)return Q.map(function(O0){return $.pre+F[0]+O0})}var B;if(H){var U=Z2(F[0]),D=Z2(F[1]),_=Math.max(F[0].length,F[1].length),O=F.length==3?Math.abs(Z2(F[2])):1,w=ak0,j=D<U;if(j)O*=-1,w=rk0;var q=F.some(ok0);B=[];for(var R=U;w(R,D);R+=O){var T;if(G){if(T=String.fromCharCode(R),T==="\\")T=""}else if(T=String(R),q){var y=_-T.length;if(y>0){var i=Array(y+1).join("0");if(R<0)T="-"+i+T.slice(1);else T=i+T}}B.push(T)}}else{B=[];for(var s=0;s<F.length;s++)B.push.apply(B,rY(F[s],!1))}for(var s=0;s<B.length;s++)for(var W=0;W<Q.length;W++){var K=Y+B[s]+Q[W];if(!J||H||K)X.push(K)}}return X}});var G2=L((jp)=>{Object.defineProperty(jp,"__esModule",{value:!0});jp.SpanNames=jp.TokenKind=jp.AllowedOperationTypes=void 0;var lx0;(function(Z){Z.QUERY="query",Z.MUTATION="mutation",Z.SUBSCRIPTION="subscription"})(lx0=jp.AllowedOperationTypes||(jp.AllowedOperationTypes={}));var px0;(function(Z){Z.SOF="<SOF>",Z.EOF="<EOF>",Z.BANG="!",Z.DOLLAR="$",Z.AMP="&",Z.PAREN_L="(",Z.PAREN_R=")",Z.SPREAD="...",Z.COLON=":",Z.EQUALS="=",Z.AT="@",Z.BRACKET_L="[",Z.BRACKET_R="]",Z.BRACE_L="{",Z.PIPE="|",Z.BRACE_R="}",Z.NAME="Name",Z.INT="Int",Z.FLOAT="Float",Z.STRING="String",Z.BLOCK_STRING="BlockString",Z.COMMENT="Comment"})(px0=jp.TokenKind||(jp.TokenKind={}));var ix0;(function(Z){Z.EXECUTE="graphql.execute",Z.PARSE="graphql.parse",Z.RESOLVE="graphql.resolve",Z.VALIDATE="graphql.validate",Z.SCHEMA_VALIDATE="graphql.validateSchema",Z.SCHEMA_PARSE="graphql.parseSchema"})(ix0=jp.SpanNames||(jp.SpanNames={}))});var V2=L((Mp)=>{Object.defineProperty(Mp,"__esModule",{value:!0});Mp.AttributeNames=void 0;var nx0;(function(Z){Z.SOURCE="graphql.source",Z.FIELD_NAME="graphql.field.name",Z.FIELD_PATH="graphql.field.path",Z.FIELD_TYPE="graphql.field.type",Z.OPERATION_TYPE="graphql.operation.type",Z.OPERATION_NAME="graphql.operation.name",Z.VARIABLES="graphql.variables.",Z.ERROR_VALIDATION_NAME="graphql.validation.error"})(nx0=Mp.AttributeNames||(Mp.AttributeNames={}))});var Qz=L((Ap)=>{Object.defineProperty(Ap,"__esModule",{value:!0});Ap.OTEL_GRAPHQL_DATA_SYMBOL=Ap.OTEL_PATCHED_SYMBOL=void 0;Ap.OTEL_PATCHED_SYMBOL=Symbol.for("opentelemetry.patched");Ap.OTEL_GRAPHQL_DATA_SYMBOL=Symbol.for("opentelemetry.graphql_data")});var Np=L((qp)=>{Object.defineProperty(qp,"__esModule",{value:!0});qp.OPERATION_NOT_SUPPORTED=void 0;var hj1=Qz();qp.OPERATION_NOT_SUPPORTED="Operation$operationName$not supported"});var cp=L((mp)=>{Object.defineProperty(mp,"__esModule",{value:!0});mp.wrapFieldResolver=mp.wrapFields=mp.getSourceFromLocation=mp.getOperation=mp.endSpan=mp.addSpanSource=mp.addInputVariableAttributes=mp.isPromise=void 0;var NX=f(),B7=G2(),CX=V2(),J9=Qz(),Rp=Object.values(B7.AllowedOperationTypes),ax0=(Z)=>{return typeof Z?.then==="function"};mp.isPromise=ax0;var rx0=(Z)=>{return typeof Z=="object"&&Z!==null};function F2(Z,J,X){if(Array.isArray(X))X.forEach(($,Y)=>{F2(Z,`${J}.${Y}`,$)});else if(X instanceof Object)Object.entries(X).forEach(([$,Y])=>{F2(Z,`${J}.${$}`,Y)});else Z.setAttribute(`${CX.AttributeNames.VARIABLES}${String(J)}`,X)}function sx0(Z,J){Object.entries(J).forEach(([X,$])=>{F2(Z,X,$)})}mp.addInputVariableAttributes=sx0;function yp(Z,J,X,$,Y){let Q=hp(J,X,$,Y);Z.setAttribute(CX.AttributeNames.SOURCE,Q)}mp.addSpanSource=yp;function tx0(Z,J,X,$,Y){let Q=Sp(X,Y);if(Q)return{field:Q,spanAdded:!1};let K=J().flatResolveSpans?xp(X):kp(X,Y);return Q={span:ex0(Z,J,X,$,Y,K)},Xv0(X,Y,Q),{field:Q,spanAdded:!0}}function ex0(Z,J,X,$,Y,Q){let W={[CX.AttributeNames.FIELD_NAME]:$.fieldName,[CX.AttributeNames.FIELD_PATH]:Y.join("."),[CX.AttributeNames.FIELD_TYPE]:$.returnType.toString()},K=Z.startSpan(`${B7.SpanNames.RESOLVE} ${W[CX.AttributeNames.FIELD_PATH]}`,{attributes:W},Q?NX.trace.setSpan(NX.context.active(),Q):void 0),z=X[J9.OTEL_GRAPHQL_DATA_SYMBOL].source,G=$.fieldNodes.find((H)=>H.kind==="Field");if(G)yp(K,z.loc,J().allowValues,G.loc?.start,G.loc?.end);return K}function Zv0(Z,J){if(J)Z.recordException(J);Z.end()}mp.endSpan=Zv0;function Jv0(Z,J){if(!Z||!Array.isArray(Z.definitions))return;if(J)return Z.definitions.filter((X)=>Rp.indexOf(X?.operation)!==-1).find((X)=>J===X?.name?.value);else return Z.definitions.find((X)=>Rp.indexOf(X?.operation)!==-1)}mp.getOperation=Jv0;function Xv0(Z,J,X){return Z[J9.OTEL_GRAPHQL_DATA_SYMBOL].fields[J.join(".")]=X}function Sp(Z,J){return Z[J9.OTEL_GRAPHQL_DATA_SYMBOL].fields[J.join(".")]}function kp(Z,J){for(let X=J.length-1;X>0;X--){let $=Sp(Z,J.slice(0,X));if($)return $.span}return xp(Z)}function xp(Z){return Z[J9.OTEL_GRAPHQL_DATA_SYMBOL].span}function $v0(Z,J){let X=[],$=J;while($){let Y=$.key;if(Z&&typeof Y==="number")Y="*";X.push(String(Y)),$=$.prev}return X.reverse()}function Yv0(Z){return vp(`
9
9
  `,Z)}function Pp(Z){return vp(" ",Z)}function vp(Z,J){let X="";for(let $=0;$<J;$++)X+=Z;return X}var Qv0=[B7.TokenKind.FLOAT,B7.TokenKind.STRING,B7.TokenKind.INT,B7.TokenKind.BLOCK_STRING];function hp(Z,J=!1,X,$){let Y="";if(Z?.startToken){let Q=typeof X==="number"?X:Z.start,W=typeof $==="number"?$:Z.end,K=Z.startToken.next,z=1;while(K){if(K.start<Q){K=K.next,z=K?.line;continue}if(K.end>W){K=K.next,z=K?.line;continue}let G=K.value||K.kind,H="";if(!J&&Qv0.indexOf(K.kind)>=0)G="*";if(K.kind===B7.TokenKind.STRING)G=`"${G}"`;if(K.kind===B7.TokenKind.EOF)G="";if(K.line>z)Y+=Yv0(K.line-z),z=K.line,H=Pp(K.column-1);else if(K.line===K.prev?.line)H=Pp(K.start-(K.prev?.end||0));if(Y+=H+G,K)K=K.next}}return Y}mp.getSourceFromLocation=hp;function fp(Z,J,X){if(!Z||Z[J9.OTEL_PATCHED_SYMBOL])return;let $=Z.getFields();Z[J9.OTEL_PATCHED_SYMBOL]=!0,Object.keys($).forEach((Y)=>{let Q=$[Y];if(!Q)return;if(Q.resolve)Q.resolve=gp(J,X,Q.resolve);if(Q.type){let W=bp(Q.type);for(let K of W)fp(K,J,X)}})}mp.wrapFields=fp;function bp(Z){if("ofType"in Z)return bp(Z.ofType);if(Wv0(Z))return Z.getTypes();if(Kv0(Z))return[Z];return[]}function Wv0(Z){return"getTypes"in Z&&typeof Z.getTypes==="function"}function Kv0(Z){return"getFields"in Z&&typeof Z.getFields==="function"}var Ep=(Z,J,X)=>{if(!X)return;Z.recordException(J),Z.setStatus({code:NX.SpanStatusCode.ERROR,message:J.message}),Z.end()},Ip=(Z,J)=>{if(!J)return;Z.end()};function gp(Z,J,X,$=!1){if(Y[J9.OTEL_PATCHED_SYMBOL]||typeof X!=="function")return X;function Y(Q,W,K,z){if(!X)return;let G=J();if(G.ignoreTrivialResolveSpans&&$&&(rx0(Q)||typeof Q==="function")){if(typeof Q[z.fieldName]!=="function")return X.call(this,Q,W,K,z)}if(!K[J9.OTEL_GRAPHQL_DATA_SYMBOL])return X.call(this,Q,W,K,z);let H=$v0(G.mergeItems,z&&z.path),V=H.filter((U)=>typeof U==="string").length,F,B=!1;if(G.depth>=0&&G.depth<V)F=kp(K,H);else{let{field:U,spanAdded:D}=tx0(Z,J,K,z,H);F=U.span,B=D}return NX.context.with(NX.trace.setSpan(NX.context.active(),F),()=>{try{let U=X.call(this,Q,W,K,z);if(mp.isPromise(U))return U.then((D)=>{return Ip(F,B),D},(D)=>{throw Ep(F,D,B),D});else return Ip(F,B),U}catch(U){throw Ep(F,U,B),U}})}return Y[J9.OTEL_PATCHED_SYMBOL]=!0,Y}mp.wrapFieldResolver=gp});var ip=L((lp)=>{Object.defineProperty(lp,"__esModule",{value:!0});lp.PACKAGE_NAME=lp.PACKAGE_VERSION=void 0;lp.PACKAGE_VERSION="0.56.0";lp.PACKAGE_NAME="@opentelemetry/instrumentation-graphql"});var tp=L((rp)=>{Object.defineProperty(rp,"__esModule",{value:!0});rp.GraphQLInstrumentation=void 0;var X9=f(),p6=H0(),Y3=G2(),Wz=V2(),B2=Qz(),Lv0=Np(),M4=cp(),np=ip(),op={mergeItems:!1,depth:-1,allowValues:!1,ignoreResolveSpans:!1},Kz=[">=14.0.0 <17"];class ap extends p6.InstrumentationBase{constructor(Z={}){super(np.PACKAGE_NAME,np.PACKAGE_VERSION,{...op,...Z})}setConfig(Z={}){super.setConfig({...op,...Z})}init(){let Z=new p6.InstrumentationNodeModuleDefinition("graphql",Kz);return Z.files.push(this._addPatchingExecute()),Z.files.push(this._addPatchingParser()),Z.files.push(this._addPatchingValidate()),Z}_addPatchingExecute(){return new p6.InstrumentationNodeModuleFile("graphql/execution/execute.js",Kz,(Z)=>{if((0,p6.isWrapped)(Z.execute))this._unwrap(Z,"execute");return this._wrap(Z,"execute",this._patchExecute(Z.defaultFieldResolver)),Z},(Z)=>{if(Z)this._unwrap(Z,"execute")})}_addPatchingParser(){return new p6.InstrumentationNodeModuleFile("graphql/language/parser.js",Kz,(Z)=>{if((0,p6.isWrapped)(Z.parse))this._unwrap(Z,"parse");return this._wrap(Z,"parse",this._patchParse()),Z},(Z)=>{if(Z)this._unwrap(Z,"parse")})}_addPatchingValidate(){return new p6.InstrumentationNodeModuleFile("graphql/validation/validate.js",Kz,(Z)=>{if((0,p6.isWrapped)(Z.validate))this._unwrap(Z,"validate");return this._wrap(Z,"validate",this._patchValidate()),Z},(Z)=>{if(Z)this._unwrap(Z,"validate")})}_patchExecute(Z){let J=this;return function($){return function(){let Q;if(arguments.length>=2){let z=arguments;Q=J._wrapExecuteArgs(z[0],z[1],z[2],z[3],z[4],z[5],z[6],z[7],Z)}else{let z=arguments[0];Q=J._wrapExecuteArgs(z.schema,z.document,z.rootValue,z.contextValue,z.variableValues,z.operationName,z.fieldResolver,z.typeResolver,Z)}let W=(0,M4.getOperation)(Q.document,Q.operationName),K=J._createExecuteSpan(W,Q);return Q.contextValue[B2.OTEL_GRAPHQL_DATA_SYMBOL]={source:Q.document?Q.document||Q.document[B2.OTEL_GRAPHQL_DATA_SYMBOL]:void 0,span:K,fields:{}},X9.context.with(X9.trace.setSpan(X9.context.active(),K),()=>{return(0,p6.safeExecuteInTheMiddle)(()=>{return $.apply(this,[Q])},(z,G)=>{J._handleExecutionResult(K,z,G)})})}}}_handleExecutionResult(Z,J,X){let $=this.getConfig();if(X===void 0||J){(0,M4.endSpan)(Z,J);return}if((0,M4.isPromise)(X))X.then((Y)=>{if(typeof $.responseHook!=="function"){(0,M4.endSpan)(Z);return}this._executeResponseHook(Z,Y)},(Y)=>{(0,M4.endSpan)(Z,Y)});else{if(typeof $.responseHook!=="function"){(0,M4.endSpan)(Z);return}this._executeResponseHook(Z,X)}}_executeResponseHook(Z,J){let{responseHook:X}=this.getConfig();if(!X)return;(0,p6.safeExecuteInTheMiddle)(()=>{X(Z,J)},($)=>{if($)this._diag.error("Error running response hook",$);(0,M4.endSpan)(Z,void 0)},!0)}_patchParse(){let Z=this;return function(X){return function(Y,Q){return Z._parse(this,X,Y,Q)}}}_patchValidate(){let Z=this;return function(X){return function(Y,Q,W,K,z){return Z._validate(this,X,Y,Q,W,z,K)}}}_parse(Z,J,X,$){let Y=this.getConfig(),Q=this.tracer.startSpan(Y3.SpanNames.PARSE);return X9.context.with(X9.trace.setSpan(X9.context.active(),Q),()=>{return(0,p6.safeExecuteInTheMiddle)(()=>{return J.call(Z,X,$)},(W,K)=>{if(K){if(!(0,M4.getOperation)(K))Q.updateName(Y3.SpanNames.SCHEMA_PARSE);else if(K.loc)(0,M4.addSpanSource)(Q,K.loc,Y.allowValues)}(0,M4.endSpan)(Q,W)})})}_validate(Z,J,X,$,Y,Q,W){let K=this.tracer.startSpan(Y3.SpanNames.VALIDATE,{});return X9.context.with(X9.trace.setSpan(X9.context.active(),K),()=>{return(0,p6.safeExecuteInTheMiddle)(()=>{return J.call(Z,X,$,Y,W,Q)},(z,G)=>{if(!$.loc)K.updateName(Y3.SpanNames.SCHEMA_VALIDATE);if(G&&G.length)K.recordException({name:Wz.AttributeNames.ERROR_VALIDATION_NAME,message:JSON.stringify(G)});(0,M4.endSpan)(K,z)})})}_createExecuteSpan(Z,J){let X=this.getConfig(),$=this.tracer.startSpan(Y3.SpanNames.EXECUTE,{});if(Z){let{operation:Y,name:Q}=Z;$.setAttribute(Wz.AttributeNames.OPERATION_TYPE,Y);let W=Q?.value;if(W)$.setAttribute(Wz.AttributeNames.OPERATION_NAME,W),$.updateName(`${Y} ${W}`);else $.updateName(Y)}else{let Y=" ";if(J.operationName)Y=` "${J.operationName}" `;Y=Lv0.OPERATION_NOT_SUPPORTED.replace("$operationName$",Y),$.setAttribute(Wz.AttributeNames.OPERATION_NAME,Y)}if(J.document?.loc)(0,M4.addSpanSource)($,J.document.loc,X.allowValues);if(J.variableValues&&X.allowValues)(0,M4.addInputVariableAttributes)($,J.variableValues);return $}_wrapExecuteArgs(Z,J,X,$,Y,Q,W,K,z){if(!$)$={};if($[B2.OTEL_GRAPHQL_DATA_SYMBOL]||this.getConfig().ignoreResolveSpans)return{schema:Z,document:J,rootValue:X,contextValue:$,variableValues:Y,operationName:Q,fieldResolver:W,typeResolver:K};let G=W==null,H=W??z;if(W=(0,M4.wrapFieldResolver)(this.tracer,()=>this.getConfig(),H,G),Z)(0,M4.wrapFields)(Z.getQueryType(),this.tracer,()=>this.getConfig()),(0,M4.wrapFields)(Z.getMutationType(),this.tracer,()=>this.getConfig());return{schema:Z,document:J,rootValue:X,contextValue:$,variableValues:Y,operationName:Q,fieldResolver:W,typeResolver:K}}}rp.GraphQLInstrumentation=ap});var ep=L((U2)=>{Object.defineProperty(U2,"__esModule",{value:!0});U2.GraphQLInstrumentation=void 0;var Dv0=tp();Object.defineProperty(U2,"GraphQLInstrumentation",{enumerable:!0,get:function(){return Dv0.GraphQLInstrumentation}})});var zi=L((Wi)=>{Object.defineProperty(Wi,"__esModule",{value:!0});Wi.EVENT_LISTENERS_SET=void 0;Wi.EVENT_LISTENERS_SET=Symbol("opentelemetry.instrumentation.kafkajs.eventListenersSet")});var Vi=L((Gi)=>{Object.defineProperty(Gi,"__esModule",{value:!0});Gi.bufferTextMapGetter=void 0;Gi.bufferTextMapGetter={get(Z,J){if(!Z)return;let X=Object.keys(Z);for(let $ of X)if($===J||$.toLowerCase()===J)return Z[$]?.toString();return},keys(Z){return Z?Object.keys(Z):[]}}});var Ui=L((Fi)=>{Object.defineProperty(Fi,"__esModule",{value:!0});Fi.METRIC_MESSAGING_PROCESS_DURATION=Fi.METRIC_MESSAGING_CLIENT_SENT_MESSAGES=Fi.METRIC_MESSAGING_CLIENT_OPERATION_DURATION=Fi.METRIC_MESSAGING_CLIENT_CONSUMED_MESSAGES=Fi.MESSAGING_SYSTEM_VALUE_KAFKA=Fi.MESSAGING_OPERATION_TYPE_VALUE_SEND=Fi.MESSAGING_OPERATION_TYPE_VALUE_RECEIVE=Fi.MESSAGING_OPERATION_TYPE_VALUE_PROCESS=Fi.ATTR_MESSAGING_SYSTEM=Fi.ATTR_MESSAGING_OPERATION_TYPE=Fi.ATTR_MESSAGING_OPERATION_NAME=Fi.ATTR_MESSAGING_KAFKA_OFFSET=Fi.ATTR_MESSAGING_KAFKA_MESSAGE_TOMBSTONE=Fi.ATTR_MESSAGING_KAFKA_MESSAGE_KEY=Fi.ATTR_MESSAGING_DESTINATION_PARTITION_ID=Fi.ATTR_MESSAGING_DESTINATION_NAME=Fi.ATTR_MESSAGING_BATCH_MESSAGE_COUNT=void 0;Fi.ATTR_MESSAGING_BATCH_MESSAGE_COUNT="messaging.batch.message_count";Fi.ATTR_MESSAGING_DESTINATION_NAME="messaging.destination.name";Fi.ATTR_MESSAGING_DESTINATION_PARTITION_ID="messaging.destination.partition.id";Fi.ATTR_MESSAGING_KAFKA_MESSAGE_KEY="messaging.kafka.message.key";Fi.ATTR_MESSAGING_KAFKA_MESSAGE_TOMBSTONE="messaging.kafka.message.tombstone";Fi.ATTR_MESSAGING_KAFKA_OFFSET="messaging.kafka.offset";Fi.ATTR_MESSAGING_OPERATION_NAME="messaging.operation.name";Fi.ATTR_MESSAGING_OPERATION_TYPE="messaging.operation.type";Fi.ATTR_MESSAGING_SYSTEM="messaging.system";Fi.MESSAGING_OPERATION_TYPE_VALUE_PROCESS="process";Fi.MESSAGING_OPERATION_TYPE_VALUE_RECEIVE="receive";Fi.MESSAGING_OPERATION_TYPE_VALUE_SEND="send";Fi.MESSAGING_SYSTEM_VALUE_KAFKA="kafka";Fi.METRIC_MESSAGING_CLIENT_CONSUMED_MESSAGES="messaging.client.consumed.messages";Fi.METRIC_MESSAGING_CLIENT_OPERATION_DURATION="messaging.client.operation.duration";Fi.METRIC_MESSAGING_CLIENT_SENT_MESSAGES="messaging.client.sent.messages";Fi.METRIC_MESSAGING_PROCESS_DURATION="messaging.process.duration"});var _i=L((Li)=>{Object.defineProperty(Li,"__esModule",{value:!0});Li.PACKAGE_NAME=Li.PACKAGE_VERSION=void 0;Li.PACKAGE_VERSION="0.18.0";Li.PACKAGE_NAME="@opentelemetry/instrumentation-kafkajs"});var Ni=L((qi)=>{Object.defineProperty(qi,"__esModule",{value:!0});qi.KafkaJsInstrumentation=void 0;var n0=f(),i6=H0(),RX=p0(),Oi=zi(),wi=Vi(),e=Ui(),ji=_i();function zz(Z,J,X){return($)=>{Z.add(J,{...X,...$?{[RX.ATTR_ERROR_TYPE]:$}:{}})}}function Mi(Z,J,X){return($)=>{Z.record((Date.now()-J)/1000,{...X,...$?{[RX.ATTR_ERROR_TYPE]:$}:{}})}}var Ai=[0.005,0.01,0.025,0.05,0.075,0.1,0.25,0.5,0.75,1,2.5,5,7.5,10];class Ti extends i6.InstrumentationBase{constructor(Z={}){super(ji.PACKAGE_NAME,ji.PACKAGE_VERSION,Z)}_updateMetricInstruments(){this._clientDuration=this.meter.createHistogram(e.METRIC_MESSAGING_CLIENT_OPERATION_DURATION,{advice:{explicitBucketBoundaries:Ai}}),this._sentMessages=this.meter.createCounter(e.METRIC_MESSAGING_CLIENT_SENT_MESSAGES),this._consumedMessages=this.meter.createCounter(e.METRIC_MESSAGING_CLIENT_CONSUMED_MESSAGES),this._processDuration=this.meter.createHistogram(e.METRIC_MESSAGING_PROCESS_DURATION,{advice:{explicitBucketBoundaries:Ai}})}init(){let Z=(X)=>{if((0,i6.isWrapped)(X?.Kafka?.prototype.producer))this._unwrap(X.Kafka.prototype,"producer");if((0,i6.isWrapped)(X?.Kafka?.prototype.consumer))this._unwrap(X.Kafka.prototype,"consumer")};return new i6.InstrumentationNodeModuleDefinition("kafkajs",[">=0.3.0 <3"],(X)=>{return Z(X),this._wrap(X?.Kafka?.prototype,"producer",this._getProducerPatch()),this._wrap(X?.Kafka?.prototype,"consumer",this._getConsumerPatch()),X},Z)}_getConsumerPatch(){let Z=this;return(J)=>{return function(...$){let Y=J.apply(this,$);if((0,i6.isWrapped)(Y.run))Z._unwrap(Y,"run");return Z._wrap(Y,"run",Z._getConsumerRunPatch()),Z._setKafkaEventListeners(Y),Y}}}_setKafkaEventListeners(Z){if(Z[Oi.EVENT_LISTENERS_SET])return;if(Z.events?.REQUEST)Z.on(Z.events.REQUEST,this._recordClientDurationMetric.bind(this));Z[Oi.EVENT_LISTENERS_SET]=!0}_recordClientDurationMetric(Z){let[J,X]=Z.payload.broker.split(":");this._clientDuration.record(Z.payload.duration/1000,{[e.ATTR_MESSAGING_SYSTEM]:e.MESSAGING_SYSTEM_VALUE_KAFKA,[e.ATTR_MESSAGING_OPERATION_NAME]:`${Z.payload.apiName}`,[RX.ATTR_SERVER_ADDRESS]:J,[RX.ATTR_SERVER_PORT]:Number.parseInt(X,10)})}_getProducerPatch(){let Z=this;return(J)=>{return function(...$){let Y=J.apply(this,$);if((0,i6.isWrapped)(Y.sendBatch))Z._unwrap(Y,"sendBatch");if(Z._wrap(Y,"sendBatch",Z._getSendBatchPatch()),(0,i6.isWrapped)(Y.send))Z._unwrap(Y,"send");if(Z._wrap(Y,"send",Z._getSendPatch()),(0,i6.isWrapped)(Y.transaction))Z._unwrap(Y,"transaction");return Z._wrap(Y,"transaction",Z._getProducerTransactionPatch()),Z._setKafkaEventListeners(Y),Y}}}_getConsumerRunPatch(){let Z=this;return(J)=>{return function(...$){let Y=$[0];if(Y?.eachMessage){if((0,i6.isWrapped)(Y.eachMessage))Z._unwrap(Y,"eachMessage");Z._wrap(Y,"eachMessage",Z._getConsumerEachMessagePatch())}if(Y?.eachBatch){if((0,i6.isWrapped)(Y.eachBatch))Z._unwrap(Y,"eachBatch");Z._wrap(Y,"eachBatch",Z._getConsumerEachBatchPatch())}return J.call(this,Y)}}}_getConsumerEachMessagePatch(){let Z=this;return(J)=>{return function(...$){let Y=$[0],Q=n0.propagation.extract(n0.ROOT_CONTEXT,Y.message.headers,wi.bufferTextMapGetter),W=Z._startConsumerSpan({topic:Y.topic,message:Y.message,operationType:e.MESSAGING_OPERATION_TYPE_VALUE_PROCESS,ctx:Q,attributes:{[e.ATTR_MESSAGING_DESTINATION_PARTITION_ID]:String(Y.partition)}}),K=[Mi(Z._processDuration,Date.now(),{[e.ATTR_MESSAGING_SYSTEM]:e.MESSAGING_SYSTEM_VALUE_KAFKA,[e.ATTR_MESSAGING_OPERATION_NAME]:"process",[e.ATTR_MESSAGING_DESTINATION_NAME]:Y.topic,[e.ATTR_MESSAGING_DESTINATION_PARTITION_ID]:String(Y.partition)}),zz(Z._consumedMessages,1,{[e.ATTR_MESSAGING_SYSTEM]:e.MESSAGING_SYSTEM_VALUE_KAFKA,[e.ATTR_MESSAGING_OPERATION_NAME]:"process",[e.ATTR_MESSAGING_DESTINATION_NAME]:Y.topic,[e.ATTR_MESSAGING_DESTINATION_PARTITION_ID]:String(Y.partition)})],z=n0.context.with(n0.trace.setSpan(Q,W),()=>{return J.apply(this,$)});return Z._endSpansOnPromise([W],K,z)}}}_getConsumerEachBatchPatch(){return(Z)=>{let J=this;return function(...$){let Y=$[0],Q=J._startConsumerSpan({topic:Y.batch.topic,message:void 0,operationType:e.MESSAGING_OPERATION_TYPE_VALUE_RECEIVE,ctx:n0.ROOT_CONTEXT,attributes:{[e.ATTR_MESSAGING_BATCH_MESSAGE_COUNT]:Y.batch.messages.length,[e.ATTR_MESSAGING_DESTINATION_PARTITION_ID]:String(Y.batch.partition)}});return n0.context.with(n0.trace.setSpan(n0.context.active(),Q),()=>{let W=Date.now(),K=[],z=[zz(J._consumedMessages,Y.batch.messages.length,{[e.ATTR_MESSAGING_SYSTEM]:e.MESSAGING_SYSTEM_VALUE_KAFKA,[e.ATTR_MESSAGING_OPERATION_NAME]:"process",[e.ATTR_MESSAGING_DESTINATION_NAME]:Y.batch.topic,[e.ATTR_MESSAGING_DESTINATION_PARTITION_ID]:String(Y.batch.partition)})];Y.batch.messages.forEach((H)=>{let V=n0.propagation.extract(n0.ROOT_CONTEXT,H.headers,wi.bufferTextMapGetter),F=n0.trace.getSpan(V)?.spanContext(),B;if(F)B={context:F};K.push(J._startConsumerSpan({topic:Y.batch.topic,message:H,operationType:e.MESSAGING_OPERATION_TYPE_VALUE_PROCESS,link:B,attributes:{[e.ATTR_MESSAGING_DESTINATION_PARTITION_ID]:String(Y.batch.partition)}})),z.push(Mi(J._processDuration,W,{[e.ATTR_MESSAGING_SYSTEM]:e.MESSAGING_SYSTEM_VALUE_KAFKA,[e.ATTR_MESSAGING_OPERATION_NAME]:"process",[e.ATTR_MESSAGING_DESTINATION_NAME]:Y.batch.topic,[e.ATTR_MESSAGING_DESTINATION_PARTITION_ID]:String(Y.batch.partition)}))});let G=Z.apply(this,$);return K.unshift(Q),J._endSpansOnPromise(K,z,G)})}}}_getProducerTransactionPatch(){let Z=this;return(J)=>{return function(...$){let Y=Z.tracer.startSpan("transaction"),Q=J.apply(this,$);return Q.then((W)=>{let K=W.send;W.send=function(...F){return n0.context.with(n0.trace.setSpan(n0.context.active(),Y),()=>{return Z._getSendPatch()(K).apply(this,F).catch((U)=>{throw Y.setStatus({code:n0.SpanStatusCode.ERROR,message:U?.message}),Y.recordException(U),U})})};let z=W.sendBatch;W.sendBatch=function(...F){return n0.context.with(n0.trace.setSpan(n0.context.active(),Y),()=>{return Z._getSendBatchPatch()(z).apply(this,F).catch((U)=>{throw Y.setStatus({code:n0.SpanStatusCode.ERROR,message:U?.message}),Y.recordException(U),U})})};let G=W.commit;W.commit=function(...F){let B=G.apply(this,F).then(()=>{Y.setStatus({code:n0.SpanStatusCode.OK})});return Z._endSpansOnPromise([Y],[],B)};let H=W.abort;W.abort=function(...F){let B=H.apply(this,F);return Z._endSpansOnPromise([Y],[],B)}}).catch((W)=>{Y.setStatus({code:n0.SpanStatusCode.ERROR,message:W?.message}),Y.recordException(W),Y.end()}),Q}}}_getSendBatchPatch(){let Z=this;return(J)=>{return function(...$){let Q=$[0].topicMessages||[],W=[],K=[];Q.forEach((G)=>{G.messages.forEach((H)=>{W.push(Z._startProducerSpan(G.topic,H)),K.push(zz(Z._sentMessages,1,{[e.ATTR_MESSAGING_SYSTEM]:e.MESSAGING_SYSTEM_VALUE_KAFKA,[e.ATTR_MESSAGING_OPERATION_NAME]:"send",[e.ATTR_MESSAGING_DESTINATION_NAME]:G.topic,...H.partition!==void 0?{[e.ATTR_MESSAGING_DESTINATION_PARTITION_ID]:String(H.partition)}:{}}))})});let z=J.apply(this,$);return Z._endSpansOnPromise(W,K,z)}}}_getSendPatch(){let Z=this;return(J)=>{return function(...$){let Y=$[0],Q=Y.messages.map((z)=>{return Z._startProducerSpan(Y.topic,z)}),W=Y.messages.map((z)=>zz(Z._sentMessages,1,{[e.ATTR_MESSAGING_SYSTEM]:e.MESSAGING_SYSTEM_VALUE_KAFKA,[e.ATTR_MESSAGING_OPERATION_NAME]:"send",[e.ATTR_MESSAGING_DESTINATION_NAME]:Y.topic,...z.partition!==void 0?{[e.ATTR_MESSAGING_DESTINATION_PARTITION_ID]:String(z.partition)}:{}})),K=J.apply(this,$);return Z._endSpansOnPromise(Q,W,K)}}}_endSpansOnPromise(Z,J,X){return Promise.resolve(X).then(($)=>{return J.forEach((Y)=>Y()),$}).catch(($)=>{let Y,Q=RX.ERROR_TYPE_VALUE_OTHER;if(typeof $==="string"||$===void 0)Y=$;else if(typeof $==="object"&&Object.prototype.hasOwnProperty.call($,"message"))Y=$.message,Q=$.constructor.name;throw J.forEach((W)=>W(Q)),Z.forEach((W)=>{W.setAttribute(RX.ATTR_ERROR_TYPE,Q),W.setStatus({code:n0.SpanStatusCode.ERROR,message:Y})}),$}).finally(()=>{Z.forEach(($)=>$.end())})}_startConsumerSpan({topic:Z,message:J,operationType:X,ctx:$,link:Y,attributes:Q}){let W=X===e.MESSAGING_OPERATION_TYPE_VALUE_RECEIVE?"poll":X,K=this.tracer.startSpan(`${W} ${Z}`,{kind:X===e.MESSAGING_OPERATION_TYPE_VALUE_RECEIVE?n0.SpanKind.CLIENT:n0.SpanKind.CONSUMER,attributes:{...Q,[e.ATTR_MESSAGING_SYSTEM]:e.MESSAGING_SYSTEM_VALUE_KAFKA,[e.ATTR_MESSAGING_DESTINATION_NAME]:Z,[e.ATTR_MESSAGING_OPERATION_TYPE]:X,[e.ATTR_MESSAGING_OPERATION_NAME]:W,[e.ATTR_MESSAGING_KAFKA_MESSAGE_KEY]:J?.key?String(J.key):void 0,[e.ATTR_MESSAGING_KAFKA_MESSAGE_TOMBSTONE]:J?.key&&J.value===null?!0:void 0,[e.ATTR_MESSAGING_KAFKA_OFFSET]:J?.offset},links:Y?[Y]:[]},$),{consumerHook:z}=this.getConfig();if(z&&J)(0,i6.safeExecuteInTheMiddle)(()=>z(K,{topic:Z,message:J}),(G)=>{if(G)this._diag.error("consumerHook error",G)},!0);return K}_startProducerSpan(Z,J){let X=this.tracer.startSpan(`send ${Z}`,{kind:n0.SpanKind.PRODUCER,attributes:{[e.ATTR_MESSAGING_SYSTEM]:e.MESSAGING_SYSTEM_VALUE_KAFKA,[e.ATTR_MESSAGING_DESTINATION_NAME]:Z,[e.ATTR_MESSAGING_KAFKA_MESSAGE_KEY]:J.key?String(J.key):void 0,[e.ATTR_MESSAGING_KAFKA_MESSAGE_TOMBSTONE]:J.key&&J.value===null?!0:void 0,[e.ATTR_MESSAGING_DESTINATION_PARTITION_ID]:J.partition!==void 0?String(J.partition):void 0,[e.ATTR_MESSAGING_OPERATION_NAME]:"send",[e.ATTR_MESSAGING_OPERATION_TYPE]:e.MESSAGING_OPERATION_TYPE_VALUE_SEND}});J.headers=J.headers??{},n0.propagation.inject(n0.trace.setSpan(n0.context.active(),X),J.headers);let{producerHook:$}=this.getConfig();if($)(0,i6.safeExecuteInTheMiddle)(()=>$(X,{topic:Z,message:J}),(Y)=>{if(Y)this._diag.error("producerHook error",Y)},!0);return X}}qi.KafkaJsInstrumentation=Ti});var Ri=L((L2)=>{Object.defineProperty(L2,"__esModule",{value:!0});L2.KafkaJsInstrumentation=void 0;var fv0=Ni();Object.defineProperty(L2,"KafkaJsInstrumentation",{enumerable:!0,get:function(){return fv0.KafkaJsInstrumentation}})});var xi=L((Si)=>{Object.defineProperty(Si,"__esModule",{value:!0});Si.PACKAGE_NAME=Si.PACKAGE_VERSION=void 0;Si.PACKAGE_VERSION="0.53.0";Si.PACKAGE_NAME="@opentelemetry/instrumentation-lru-memoizer"});var di=L((gi)=>{Object.defineProperty(gi,"__esModule",{value:!0});gi.LruMemoizerInstrumentation=void 0;var vi=f(),hi=H0(),fi=xi();class bi extends hi.InstrumentationBase{constructor(Z={}){super(fi.PACKAGE_NAME,fi.PACKAGE_VERSION,Z)}init(){return[new hi.InstrumentationNodeModuleDefinition("lru-memoizer",[">=1.3 <3"],(Z)=>{let J=function(){let X=Z.apply(this,arguments);return function(){let $=[...arguments],Y=$.pop(),Q=typeof Y==="function"?vi.context.bind(vi.context.active(),Y):Y;return $.push(Q),X.apply(this,$)}};return J.sync=Z.sync,J},void 0)]}}gi.LruMemoizerInstrumentation=bi});var ui=L((D2)=>{Object.defineProperty(D2,"__esModule",{value:!0});D2.LruMemoizerInstrumentation=void 0;var dv0=di();Object.defineProperty(D2,"LruMemoizerInstrumentation",{enumerable:!0,get:function(){return dv0.LruMemoizerInstrumentation}})});var ai=L((ni)=>{Object.defineProperty(ni,"__esModule",{value:!0});ni.METRIC_DB_CLIENT_CONNECTIONS_USAGE=ni.DB_SYSTEM_VALUE_MONGODB=ni.ATTR_NET_PEER_PORT=ni.ATTR_NET_PEER_NAME=ni.ATTR_DB_SYSTEM=ni.ATTR_DB_STATEMENT=ni.ATTR_DB_OPERATION=ni.ATTR_DB_NAME=ni.ATTR_DB_MONGODB_COLLECTION=ni.ATTR_DB_CONNECTION_STRING=void 0;ni.ATTR_DB_CONNECTION_STRING="db.connection_string";ni.ATTR_DB_MONGODB_COLLECTION="db.mongodb.collection";ni.ATTR_DB_NAME="db.name";ni.ATTR_DB_OPERATION="db.operation";ni.ATTR_DB_STATEMENT="db.statement";ni.ATTR_DB_SYSTEM="db.system";ni.ATTR_NET_PEER_NAME="net.peer.name";ni.ATTR_NET_PEER_PORT="net.peer.port";ni.DB_SYSTEM_VALUE_MONGODB="mongodb";ni.METRIC_DB_CLIENT_CONNECTIONS_USAGE="db.client.connections.usage"});var si=L((ri)=>{Object.defineProperty(ri,"__esModule",{value:!0});ri.MongodbCommandType=void 0;var ev0;(function(Z){Z.CREATE_INDEXES="createIndexes",Z.FIND_AND_MODIFY="findAndModify",Z.IS_MASTER="isMaster",Z.COUNT="count",Z.AGGREGATE="aggregate",Z.UNKNOWN="unknown"})(ev0=ri.MongodbCommandType||(ri.MongodbCommandType={}))});var Zn=L((ti)=>{Object.defineProperty(ti,"__esModule",{value:!0});ti.PACKAGE_NAME=ti.PACKAGE_VERSION=void 0;ti.PACKAGE_VERSION="0.61.0";ti.PACKAGE_NAME="@opentelemetry/instrumentation-mongodb"});var Qn=L(($n)=>{Object.defineProperty($n,"__esModule",{value:!0});$n.MongoDBInstrumentation=void 0;var _1=f(),Y1=H0(),K5=ai(),U7=si(),Jn=Zn(),Xn={requireParentSpan:!0};class O2 extends Y1.InstrumentationBase{constructor(Z={}){super(Jn.PACKAGE_NAME,Jn.PACKAGE_VERSION,{...Xn,...Z})}setConfig(Z={}){super.setConfig({...Xn,...Z})}_updateMetricInstruments(){this._connectionsUsage=this.meter.createUpDownCounter(K5.METRIC_DB_CLIENT_CONNECTIONS_USAGE,{description:"The number of connections that are currently in state described by the state attribute.",unit:"{connection}"})}init(){let{v3PatchConnection:Z,v3UnpatchConnection:J}=this._getV3ConnectionPatches(),{v4PatchConnect:X,v4UnpatchConnect:$}=this._getV4ConnectPatches(),{v4PatchConnectionCallback:Y,v4PatchConnectionPromise:Q,v4UnpatchConnection:W}=this._getV4ConnectionPatches(),{v4PatchConnectionPool:K,v4UnpatchConnectionPool:z}=this._getV4ConnectionPoolPatches(),{v4PatchSessions:G,v4UnpatchSessions:H}=this._getV4SessionsPatches();return[new Y1.InstrumentationNodeModuleDefinition("mongodb",[">=3.3.0 <4"],void 0,void 0,[new Y1.InstrumentationNodeModuleFile("mongodb/lib/core/wireprotocol/index.js",[">=3.3.0 <4"],Z,J)]),new Y1.InstrumentationNodeModuleDefinition("mongodb",[">=4.0.0 <7"],void 0,void 0,[new Y1.InstrumentationNodeModuleFile("mongodb/lib/cmap/connection.js",[">=4.0.0 <6.4"],Y,W),new Y1.InstrumentationNodeModuleFile("mongodb/lib/cmap/connection.js",[">=6.4.0 <7"],Q,W),new Y1.InstrumentationNodeModuleFile("mongodb/lib/cmap/connection_pool.js",[">=4.0.0 <6.4"],K,z),new Y1.InstrumentationNodeModuleFile("mongodb/lib/cmap/connect.js",[">=4.0.0 <7"],X,$),new Y1.InstrumentationNodeModuleFile("mongodb/lib/sessions.js",[">=4.0.0 <7"],G,H)])]}_getV3ConnectionPatches(){return{v3PatchConnection:(Z)=>{if((0,Y1.isWrapped)(Z.insert))this._unwrap(Z,"insert");if(this._wrap(Z,"insert",this._getV3PatchOperation("insert")),(0,Y1.isWrapped)(Z.remove))this._unwrap(Z,"remove");if(this._wrap(Z,"remove",this._getV3PatchOperation("remove")),(0,Y1.isWrapped)(Z.update))this._unwrap(Z,"update");if(this._wrap(Z,"update",this._getV3PatchOperation("update")),(0,Y1.isWrapped)(Z.command))this._unwrap(Z,"command");if(this._wrap(Z,"command",this._getV3PatchCommand()),(0,Y1.isWrapped)(Z.query))this._unwrap(Z,"query");if(this._wrap(Z,"query",this._getV3PatchFind()),(0,Y1.isWrapped)(Z.getMore))this._unwrap(Z,"getMore");return this._wrap(Z,"getMore",this._getV3PatchCursor()),Z},v3UnpatchConnection:(Z)=>{if(Z===void 0)return;this._unwrap(Z,"insert"),this._unwrap(Z,"remove"),this._unwrap(Z,"update"),this._unwrap(Z,"command"),this._unwrap(Z,"query"),this._unwrap(Z,"getMore")}}}_getV4SessionsPatches(){return{v4PatchSessions:(Z)=>{if((0,Y1.isWrapped)(Z.acquire))this._unwrap(Z,"acquire");if(this._wrap(Z.ServerSessionPool.prototype,"acquire",this._getV4AcquireCommand()),(0,Y1.isWrapped)(Z.release))this._unwrap(Z,"release");return this._wrap(Z.ServerSessionPool.prototype,"release",this._getV4ReleaseCommand()),Z},v4UnpatchSessions:(Z)=>{if(Z===void 0)return;if((0,Y1.isWrapped)(Z.acquire))this._unwrap(Z,"acquire");if((0,Y1.isWrapped)(Z.release))this._unwrap(Z,"release")}}}_getV4AcquireCommand(){let Z=this;return(J)=>{return function(){let $=this.sessions.length,Y=J.call(this),Q=this.sessions.length;if($===Q)Z._connectionsUsage.add(1,{state:"used","pool.name":Z._poolName});else if($-1===Q)Z._connectionsUsage.add(-1,{state:"idle","pool.name":Z._poolName}),Z._connectionsUsage.add(1,{state:"used","pool.name":Z._poolName});return Y}}}_getV4ReleaseCommand(){let Z=this;return(J)=>{return function($){let Y=J.call(this,$);return Z._connectionsUsage.add(-1,{state:"used","pool.name":Z._poolName}),Z._connectionsUsage.add(1,{state:"idle","pool.name":Z._poolName}),Y}}}_getV4ConnectionPoolPatches(){return{v4PatchConnectionPool:(Z)=>{let J=Z.ConnectionPool.prototype;if((0,Y1.isWrapped)(J.checkOut))this._unwrap(J,"checkOut");return this._wrap(J,"checkOut",this._getV4ConnectionPoolCheckOut()),Z},v4UnpatchConnectionPool:(Z)=>{if(Z===void 0)return;this._unwrap(Z.ConnectionPool.prototype,"checkOut")}}}_getV4ConnectPatches(){return{v4PatchConnect:(Z)=>{if((0,Y1.isWrapped)(Z.connect))this._unwrap(Z,"connect");return this._wrap(Z,"connect",this._getV4ConnectCommand()),Z},v4UnpatchConnect:(Z)=>{if(Z===void 0)return;this._unwrap(Z,"connect")}}}_getV4ConnectionPoolCheckOut(){return(Z)=>{return function(X){let $=_1.context.bind(_1.context.active(),X);return Z.call(this,$)}}}_getV4ConnectCommand(){let Z=this;return(J)=>{return function($,Y){if(J.length===1){let W=J.call(this,$);if(W&&typeof W.then==="function")W.then(()=>Z.setPoolName($),()=>{return});return W}let Q=function(W,K){if(W||!K){Y(W,K);return}Z.setPoolName($),Y(W,K)};return J.call(this,$,Q)}}}_getV4ConnectionPatches(){return{v4PatchConnectionCallback:(Z)=>{if((0,Y1.isWrapped)(Z.Connection.prototype.command))this._unwrap(Z.Connection.prototype,"command");return this._wrap(Z.Connection.prototype,"command",this._getV4PatchCommandCallback()),Z},v4PatchConnectionPromise:(Z)=>{if((0,Y1.isWrapped)(Z.Connection.prototype.command))this._unwrap(Z.Connection.prototype,"command");return this._wrap(Z.Connection.prototype,"command",this._getV4PatchCommandPromise()),Z},v4UnpatchConnection:(Z)=>{if(Z===void 0)return;this._unwrap(Z.Connection.prototype,"command")}}}_getV3PatchOperation(Z){let J=this;return(X)=>{return function(Y,Q,W,K,z){let G=_1.trace.getSpan(_1.context.active()),H=J._checkSkipInstrumentation(G),V=typeof K==="function"?K:z;if(H||typeof V!=="function"||typeof W!=="object")if(typeof K==="function")return X.call(this,Y,Q,W,K);else return X.call(this,Y,Q,W,K,z);let F=J.tracer.startSpan(`mongodb.${Z}`,{kind:_1.SpanKind.CLIENT});J._populateV3Attributes(F,Q,Y,W[0],Z);let B=J._patchEnd(F,V);if(typeof K==="function")return X.call(this,Y,Q,W,B);else return X.call(this,Y,Q,W,K,B)}}}_getV3PatchCommand(){let Z=this;return(J)=>{return function($,Y,Q,W,K){let z=_1.trace.getSpan(_1.context.active()),G=Z._checkSkipInstrumentation(z),H=typeof W==="function"?W:K;if(G||typeof H!=="function"||typeof Q!=="object")if(typeof W==="function")return J.call(this,$,Y,Q,W);else return J.call(this,$,Y,Q,W,K);let V=O2._getCommandType(Q),F=V===U7.MongodbCommandType.UNKNOWN?"command":V,B=Z.tracer.startSpan(`mongodb.${F}`,{kind:_1.SpanKind.CLIENT}),U=V===U7.MongodbCommandType.UNKNOWN?void 0:V;Z._populateV3Attributes(B,Y,$,Q,U);let D=Z._patchEnd(B,H);if(typeof W==="function")return J.call(this,$,Y,Q,D);else return J.call(this,$,Y,Q,W,D)}}}_getV4PatchCommandCallback(){let Z=this;return(J)=>{return function($,Y,Q,W){let K=_1.trace.getSpan(_1.context.active()),z=Z._checkSkipInstrumentation(K),G=W,H=Object.keys(Y)[0];if(typeof Y!=="object"||Y.ismaster||Y.hello)return J.call(this,$,Y,Q,W);let V=void 0;if(!z)V=Z.tracer.startSpan(`mongodb.${H}`,{kind:_1.SpanKind.CLIENT}),Z._populateV4Attributes(V,this,$,Y,H);let F=Z._patchEnd(V,G,this.id,H);return J.call(this,$,Y,Q,F)}}}_getV4PatchCommandPromise(){let Z=this;return(J)=>{return function(...$){let[Y,Q]=$,W=_1.trace.getSpan(_1.context.active()),K=Z._checkSkipInstrumentation(W),z=Object.keys(Q)[0],G=()=>{return};if(typeof Q!=="object"||Q.ismaster||Q.hello)return J.apply(this,$);let H=void 0;if(!K)H=Z.tracer.startSpan(`mongodb.${z}`,{kind:_1.SpanKind.CLIENT}),Z._populateV4Attributes(H,this,Y,Q,z);let V=Z._patchEnd(H,G,this.id,z),F=J.apply(this,$);return F.then((B)=>V(null,B),(B)=>V(B)),F}}}_getV3PatchFind(){let Z=this;return(J)=>{return function($,Y,Q,W,K,z){let G=_1.trace.getSpan(_1.context.active()),H=Z._checkSkipInstrumentation(G),V=typeof K==="function"?K:z;if(H||typeof V!=="function"||typeof Q!=="object")if(typeof K==="function")return J.call(this,$,Y,Q,W,K);else return J.call(this,$,Y,Q,W,K,z);let F=Z.tracer.startSpan("mongodb.find",{kind:_1.SpanKind.CLIENT});Z._populateV3Attributes(F,Y,$,Q,"find");let B=Z._patchEnd(F,V);if(typeof K==="function")return J.call(this,$,Y,Q,W,B);else return J.call(this,$,Y,Q,W,K,B)}}}_getV3PatchCursor(){let Z=this;return(J)=>{return function($,Y,Q,W,K,z){let G=_1.trace.getSpan(_1.context.active()),H=Z._checkSkipInstrumentation(G),V=typeof K==="function"?K:z;if(H||typeof V!=="function")if(typeof K==="function")return J.call(this,$,Y,Q,W,K);else return J.call(this,$,Y,Q,W,K,z);let F=Z.tracer.startSpan("mongodb.getMore",{kind:_1.SpanKind.CLIENT});Z._populateV3Attributes(F,Y,$,Q.cmd,"getMore");let B=Z._patchEnd(F,V);if(typeof K==="function")return J.call(this,$,Y,Q,W,B);else return J.call(this,$,Y,Q,W,K,B)}}}static _getCommandType(Z){if(Z.createIndexes!==void 0)return U7.MongodbCommandType.CREATE_INDEXES;else if(Z.findandmodify!==void 0)return U7.MongodbCommandType.FIND_AND_MODIFY;else if(Z.ismaster!==void 0)return U7.MongodbCommandType.IS_MASTER;else if(Z.count!==void 0)return U7.MongodbCommandType.COUNT;else if(Z.aggregate!==void 0)return U7.MongodbCommandType.AGGREGATE;else return U7.MongodbCommandType.UNKNOWN}_populateV4Attributes(Z,J,X,$,Y){let Q,W;if(J){let z=typeof J.address==="string"?J.address.split(":"):"";if(z.length===2)Q=z[0],W=z[1]}let K;if($?.documents&&$.documents[0])K=$.documents[0];else if($?.cursors)K=$.cursors;else K=$;this._addAllSpanAttributes(Z,X.db,X.collection,Q,W,K,Y)}_populateV3Attributes(Z,J,X,$,Y){let Q,W;if(X&&X.s){if(Q=X.s.options?.host??X.s.host,W=(X.s.options?.port??X.s.port)?.toString(),Q==null||W==null){let H=X.description?.address;if(H){let V=H.split(":");Q=V[0],W=V[1]}}}let[K,z]=J.toString().split("."),G=$?.query??$?.q??$;this._addAllSpanAttributes(Z,K,z,Q,W,G,Y)}_addAllSpanAttributes(Z,J,X,$,Y,Q,W){if(Z.setAttributes({[K5.ATTR_DB_SYSTEM]:K5.DB_SYSTEM_VALUE_MONGODB,[K5.ATTR_DB_NAME]:J,[K5.ATTR_DB_MONGODB_COLLECTION]:X,[K5.ATTR_DB_OPERATION]:W,[K5.ATTR_DB_CONNECTION_STRING]:`mongodb://${$}:${Y}/${J}`}),$&&Y){Z.setAttribute(K5.ATTR_NET_PEER_NAME,$);let G=parseInt(Y,10);if(!isNaN(G))Z.setAttribute(K5.ATTR_NET_PEER_PORT,G)}if(!Q)return;let{dbStatementSerializer:K}=this.getConfig(),z=typeof K==="function"?K:this._defaultDbStatementSerializer.bind(this);(0,Y1.safeExecuteInTheMiddle)(()=>{let G=z(Q);Z.setAttribute(K5.ATTR_DB_STATEMENT,G)},(G)=>{if(G)this._diag.error("Error running dbStatementSerializer hook",G)},!0)}_getDefaultDbStatementReplacer(){let Z=new WeakSet;return(J,X)=>{if(typeof X!=="object"||!X)return"?";if(Z.has(X))return"[Circular]";return Z.add(X),X}}_defaultDbStatementSerializer(Z){let{enhancedDatabaseReporting:J}=this.getConfig();if(J)return JSON.stringify(Z);return JSON.stringify(Z,this._getDefaultDbStatementReplacer())}_handleExecutionResult(Z,J){let{responseHook:X}=this.getConfig();if(typeof X==="function")(0,Y1.safeExecuteInTheMiddle)(()=>{X(Z,{data:J})},($)=>{if($)this._diag.error("Error running response hook",$)},!0)}_patchEnd(Z,J,X,$){let Y=_1.context.active(),Q=this;return function(...K){let z=K[0];if(Z){if(z instanceof Error)Z?.setStatus({code:_1.SpanStatusCode.ERROR,message:z.message});else{let G=K[1];Q._handleExecutionResult(Z,G)}Z.end()}return _1.context.with(Y,()=>{if($==="endSessions")Q._connectionsUsage.add(-1,{state:"idle","pool.name":Q._poolName});return J.apply(this,K)})}}setPoolName(Z){let J=Z.hostAddress?.host,X=Z.hostAddress?.port,$=Z.dbName,Y=`mongodb://${J}:${X}/${$}`;this._poolName=Y}_checkSkipInstrumentation(Z){return this.getConfig().requireParentSpan===!0&&Z===void 0}}$n.MongoDBInstrumentation=O2});var Kn=L((Wn)=>{Object.defineProperty(Wn,"__esModule",{value:!0});Wn.MongodbCommandType=void 0;var Jh0;(function(Z){Z.CREATE_INDEXES="createIndexes",Z.FIND_AND_MODIFY="findAndModify",Z.IS_MASTER="isMaster",Z.COUNT="count",Z.UNKNOWN="unknown"})(Jh0=Wn.MongodbCommandType||(Wn.MongodbCommandType={}))});var zn=L((Gz)=>{Object.defineProperty(Gz,"__esModule",{value:!0});Gz.MongodbCommandType=Gz.MongoDBInstrumentation=void 0;var Xh0=Qn();Object.defineProperty(Gz,"MongoDBInstrumentation",{enumerable:!0,get:function(){return Xh0.MongoDBInstrumentation}});var $h0=Kn();Object.defineProperty(Gz,"MongodbCommandType",{enumerable:!0,get:function(){return $h0.MongodbCommandType}})});var M2=L((Bn)=>{Object.defineProperty(Bn,"__esModule",{value:!0});Bn.ATTR_NET_PEER_PORT=Bn.ATTR_NET_PEER_NAME=Bn.ATTR_DB_USER=Bn.ATTR_DB_SYSTEM=Bn.ATTR_DB_STATEMENT=Bn.ATTR_DB_OPERATION=Bn.ATTR_DB_NAME=Bn.ATTR_DB_MONGODB_COLLECTION=void 0;Bn.ATTR_DB_MONGODB_COLLECTION="db.mongodb.collection";Bn.ATTR_DB_NAME="db.name";Bn.ATTR_DB_OPERATION="db.operation";Bn.ATTR_DB_STATEMENT="db.statement";Bn.ATTR_DB_SYSTEM="db.system";Bn.ATTR_DB_USER="db.user";Bn.ATTR_NET_PEER_NAME="net.peer.name";Bn.ATTR_NET_PEER_PORT="net.peer.port"});var wn=L((_n)=>{Object.defineProperty(_n,"__esModule",{value:!0});_n.handleCallbackResponse=_n.handlePromiseResponse=_n.getAttributesFromCollection=void 0;var Ln=f(),_h0=H0(),Q3=M2();function Oh0(Z){return{[Q3.ATTR_DB_MONGODB_COLLECTION]:Z.name,[Q3.ATTR_DB_NAME]:Z.conn.name,[Q3.ATTR_DB_USER]:Z.conn.user,[Q3.ATTR_NET_PEER_NAME]:Z.conn.host,[Q3.ATTR_NET_PEER_PORT]:Z.conn.port}}_n.getAttributesFromCollection=Oh0;function Dn(Z,J={}){Z.recordException(J),Z.setStatus({code:Ln.SpanStatusCode.ERROR,message:`${J.message} ${J.code?`
10
10
  Mongoose Error Code: ${J.code}`:""}`})}function A2(Z,J,X,$=void 0){if(!X)return;(0,_h0.safeExecuteInTheMiddle)(()=>X(Z,{moduleVersion:$,response:J}),(Y)=>{if(Y)Ln.diag.error("mongoose instrumentation: responseHook error",Y)},!0)}function wh0(Z,J,X,$=void 0){if(!(Z instanceof Promise))return A2(J,Z,X,$),J.end(),Z;return Z.then((Y)=>{return A2(J,Y,X,$),Y}).catch((Y)=>{throw Dn(J,Y),Y}).finally(()=>J.end())}_n.handlePromiseResponse=wh0;function jh0(Z,J,X,$,Y,Q,W=void 0){let K=0;if(Y.length===2)K=1;else if(Y.length===3)K=2;return Y[K]=(z,G)=>{if(z)Dn($,z);else A2($,G,Q,W);return $.end(),Z(z,G)},J.apply(X,Y)}_n.handleCallbackResponse=jh0});var An=L((jn)=>{Object.defineProperty(jn,"__esModule",{value:!0});jn.PACKAGE_NAME=jn.PACKAGE_VERSION=void 0;jn.PACKAGE_VERSION="0.55.0";jn.PACKAGE_NAME="@opentelemetry/instrumentation-mongoose"});var In=L((Pn)=>{Object.defineProperty(Pn,"__esModule",{value:!0});Pn.MongooseInstrumentation=Pn._STORED_PARENT_SPAN=void 0;var F4=f(),qh0=H1(),T2=wn(),Tn=H0(),qn=An(),PX=M2(),Hz=["deleteOne","deleteMany","find","findOne","estimatedDocumentCount","countDocuments","distinct","where","$where","findOneAndUpdate","findOneAndDelete","findOneAndReplace"],Ch0=["remove","count","findOneAndRemove",...Hz],Nh0=["count","findOneAndRemove",...Hz],Rh0=[...Hz];function Cn(Z){if(!Z)return Hz;else if(Z.startsWith("6.")||Z.startsWith("5."))return Ch0;else if(Z.startsWith("7."))return Nh0;else return Rh0}function Nn(Z){return Z&&(Z.startsWith("5.")||Z.startsWith("6."))||!1}Pn._STORED_PARENT_SPAN=Symbol("stored-parent-span");class Rn extends Tn.InstrumentationBase{constructor(Z={}){super(qn.PACKAGE_NAME,qn.PACKAGE_VERSION,Z)}init(){return new Tn.InstrumentationNodeModuleDefinition("mongoose",[">=5.9.7 <9"],this.patch.bind(this),this.unpatch.bind(this))}patch(Z,J){let X=Z[Symbol.toStringTag]==="Module"?Z.default:Z;if(this._wrap(X.Model.prototype,"save",this.patchOnModelMethods("save",J)),X.Model.prototype.$save=X.Model.prototype.save,Nn(J))this._wrap(X.Model.prototype,"remove",this.patchOnModelMethods("remove",J));return this._wrap(X.Query.prototype,"exec",this.patchQueryExec(J)),this._wrap(X.Aggregate.prototype,"exec",this.patchAggregateExec(J)),Cn(J).forEach((Y)=>{this._wrap(X.Query.prototype,Y,this.patchAndCaptureSpanContext(Y))}),this._wrap(X.Model,"aggregate",this.patchModelAggregate()),this._wrap(X.Model,"insertMany",this.patchModelStatic("insertMany",J)),this._wrap(X.Model,"bulkWrite",this.patchModelStatic("bulkWrite",J)),X}unpatch(Z,J){let X=Z[Symbol.toStringTag]==="Module"?Z.default:Z,$=Cn(J);if(this._unwrap(X.Model.prototype,"save"),X.Model.prototype.$save=X.Model.prototype.save,Nn(J))this._unwrap(X.Model.prototype,"remove");this._unwrap(X.Query.prototype,"exec"),this._unwrap(X.Aggregate.prototype,"exec"),$.forEach((Y)=>{this._unwrap(X.Query.prototype,Y)}),this._unwrap(X.Model,"aggregate"),this._unwrap(X.Model,"insertMany"),this._unwrap(X.Model,"bulkWrite")}patchAggregateExec(Z){let J=this;return(X)=>{return function(Y){if(J.getConfig().requireParentSpan&&F4.trace.getSpan(F4.context.active())===void 0)return X.apply(this,arguments);let Q=this[Pn._STORED_PARENT_SPAN],W={},{dbStatementSerializer:K}=J.getConfig();if(K)W[PX.ATTR_DB_STATEMENT]=K("aggregate",{options:this.options,aggregatePipeline:this._pipeline});let z=J._startSpan(this._model.collection,this._model?.modelName,"aggregate",W,Q);return J._handleResponse(z,X,this,arguments,Y,Z)}}}patchQueryExec(Z){let J=this;return(X)=>{return function(Y){if(J.getConfig().requireParentSpan&&F4.trace.getSpan(F4.context.active())===void 0)return X.apply(this,arguments);let Q=this[Pn._STORED_PARENT_SPAN],W={},{dbStatementSerializer:K}=J.getConfig();if(K)W[PX.ATTR_DB_STATEMENT]=K(this.op,{condition:this._conditions,updates:this._update,options:this.options,fields:this._fields});let z=J._startSpan(this.mongooseCollection,this.model.modelName,this.op,W,Q);return J._handleResponse(z,X,this,arguments,Y,Z)}}}patchOnModelMethods(Z,J){let X=this;return($)=>{return function(Q,W){if(X.getConfig().requireParentSpan&&F4.trace.getSpan(F4.context.active())===void 0)return $.apply(this,arguments);let K={document:this};if(Q&&!(Q instanceof Function))K.options=Q;let z={},{dbStatementSerializer:G}=X.getConfig();if(G)z[PX.ATTR_DB_STATEMENT]=G(Z,K);let H=X._startSpan(this.constructor.collection,this.constructor.modelName,Z,z);if(Q instanceof Function)W=Q,Q=void 0;return X._handleResponse(H,$,this,arguments,W,J)}}}patchModelStatic(Z,J){let X=this;return($)=>{return function(Q,W,K){if(X.getConfig().requireParentSpan&&F4.trace.getSpan(F4.context.active())===void 0)return $.apply(this,arguments);if(typeof W==="function")K=W,W=void 0;let z={};switch(Z){case"insertMany":z.documents=Q;break;case"bulkWrite":z.operations=Q;break;default:z.document=Q;break}if(W!==void 0)z.options=W;let G={},{dbStatementSerializer:H}=X.getConfig();if(H)G[PX.ATTR_DB_STATEMENT]=H(Z,z);let V=X._startSpan(this.collection,this.modelName,Z,G);return X._handleResponse(V,$,this,arguments,K,J)}}}patchModelAggregate(){let Z=this;return(J)=>{return function(){let $=F4.trace.getSpan(F4.context.active()),Y=Z._callOriginalFunction(()=>J.apply(this,arguments));if(Y)Y[Pn._STORED_PARENT_SPAN]=$;return Y}}}patchAndCaptureSpanContext(Z){let J=this;return(X)=>{return function(){return this[Pn._STORED_PARENT_SPAN]=F4.trace.getSpan(F4.context.active()),J._callOriginalFunction(()=>X.apply(this,arguments))}}}_startSpan(Z,J,X,$,Y){return this.tracer.startSpan(`mongoose.${J}.${X}`,{kind:F4.SpanKind.CLIENT,attributes:{...$,...(0,T2.getAttributesFromCollection)(Z),[PX.ATTR_DB_OPERATION]:X,[PX.ATTR_DB_SYSTEM]:"mongoose"}},Y?F4.trace.setSpan(F4.context.active(),Y):void 0)}_handleResponse(Z,J,X,$,Y,Q=void 0){let W=this;if(Y instanceof Function)return W._callOriginalFunction(()=>(0,T2.handleCallbackResponse)(Y,J,X,Z,$,W.getConfig().responseHook,Q));else{let K=W._callOriginalFunction(()=>J.apply(X,$));return(0,T2.handlePromiseResponse)(K,Z,W.getConfig().responseHook,Q)}}_callOriginalFunction(Z){if(this.getConfig().suppressInternalInstrumentation)return F4.context.with((0,qh0.suppressTracing)(F4.context.active()),Z);else return Z()}}Pn.MongooseInstrumentation=Rn});var yn=L((q2)=>{Object.defineProperty(q2,"__esModule",{value:!0});q2.MongooseInstrumentation=void 0;var Ph0=In();Object.defineProperty(q2,"MongooseInstrumentation",{enumerable:!0,get:function(){return Ph0.MongooseInstrumentation}})});var C2=L((hn)=>{Object.defineProperty(hn,"__esModule",{value:!0});hn.METRIC_DB_CLIENT_CONNECTIONS_USAGE=hn.DB_SYSTEM_VALUE_MYSQL=hn.ATTR_NET_PEER_PORT=hn.ATTR_NET_PEER_NAME=hn.ATTR_DB_USER=hn.ATTR_DB_SYSTEM=hn.ATTR_DB_STATEMENT=hn.ATTR_DB_NAME=hn.ATTR_DB_CONNECTION_STRING=void 0;hn.ATTR_DB_CONNECTION_STRING="db.connection_string";hn.ATTR_DB_NAME="db.name";hn.ATTR_DB_STATEMENT="db.statement";hn.ATTR_DB_SYSTEM="db.system";hn.ATTR_DB_USER="db.user";hn.ATTR_NET_PEER_NAME="net.peer.name";hn.ATTR_NET_PEER_PORT="net.peer.port";hn.DB_SYSTEM_VALUE_MYSQL="mysql";hn.METRIC_DB_CLIENT_CONNECTIONS_USAGE="db.client.connections.usage"});var gn=L((bn)=>{Object.defineProperty(bn,"__esModule",{value:!0});bn.AttributeNames=void 0;var gh0;(function(Z){Z.MYSQL_VALUES="db.mysql.values"})(gh0=bn.AttributeNames||(bn.AttributeNames={}))});var cn=L((dn)=>{Object.defineProperty(dn,"__esModule",{value:!0});dn.getPoolName=dn.arrayStringifyHelper=dn.getSpanName=dn.getDbValues=dn.getDbStatement=dn.getConnectionAttributes=void 0;var $9=C2();function mh0(Z){let{host:J,port:X,database:$,user:Y}=dh0(Z),Q=parseInt(X,10);if(!isNaN(Q))return{[$9.ATTR_NET_PEER_NAME]:J,[$9.ATTR_NET_PEER_PORT]:Q,[$9.ATTR_DB_CONNECTION_STRING]:mn(J,X,$),[$9.ATTR_DB_NAME]:$,[$9.ATTR_DB_USER]:Y};return{[$9.ATTR_NET_PEER_NAME]:J,[$9.ATTR_DB_CONNECTION_STRING]:mn(J,X,$),[$9.ATTR_DB_NAME]:$,[$9.ATTR_DB_USER]:Y}}dn.getConnectionAttributes=mh0;function dh0(Z){let{host:J,port:X,database:$,user:Y}=Z&&Z.connectionConfig||Z||{};return{host:J,port:X,database:$,user:Y}}function mn(Z,J,X){let $=`jdbc:mysql://${Z||"localhost"}`;if(typeof J==="number")$+=`:${J}`;if(typeof X==="string")$+=`/${X}`;return $}function uh0(Z){if(typeof Z==="string")return Z;else return Z.sql}dn.getDbStatement=uh0;function ch0(Z,J){if(typeof Z==="string")return R2(J);else return R2(J||Z.values)}dn.getDbValues=ch0;function lh0(Z){let J=typeof Z==="object"?Z.sql:Z,X=J?.indexOf(" ");if(typeof X==="number"&&X!==-1)return J?.substring(0,X);return J}dn.getSpanName=lh0;function R2(Z){if(Z)return`[${Z.toString()}]`;return""}dn.arrayStringifyHelper=R2;function ph0(Z){let J=Z.config.connectionConfig,X="";if(X+=J.host?`host: '${J.host}', `:"",X+=J.port?`port: ${J.port}, `:"",X+=J.database?`database: '${J.database}', `:"",X+=J.user?`user: '${J.user}'`:"",!J.user)X=X.substring(0,X.length-2);return X.trim()}dn.getPoolName=ph0});var nn=L((ln)=>{Object.defineProperty(ln,"__esModule",{value:!0});ln.PACKAGE_NAME=ln.PACKAGE_VERSION=void 0;ln.PACKAGE_VERSION="0.54.0";ln.PACKAGE_NAME="@opentelemetry/instrumentation-mysql"});var sn=L((an)=>{Object.defineProperty(an,"__esModule",{value:!0});an.MySQLInstrumentation=void 0;var Y6=f(),EX=H0(),Vz=C2(),th0=gn(),IX=cn(),on=nn();class P2 extends EX.InstrumentationBase{static COMMON_ATTRIBUTES={[Vz.ATTR_DB_SYSTEM]:Vz.DB_SYSTEM_VALUE_MYSQL};constructor(Z={}){super(on.PACKAGE_NAME,on.PACKAGE_VERSION,Z)}_updateMetricInstruments(){this._connectionsUsage=this.meter.createUpDownCounter(Vz.METRIC_DB_CLIENT_CONNECTIONS_USAGE,{description:"The number of connections that are currently in state described by the state attribute.",unit:"{connection}"})}init(){return[new EX.InstrumentationNodeModuleDefinition("mysql",[">=2.0.0 <3"],(Z)=>{if((0,EX.isWrapped)(Z.createConnection))this._unwrap(Z,"createConnection");if(this._wrap(Z,"createConnection",this._patchCreateConnection()),(0,EX.isWrapped)(Z.createPool))this._unwrap(Z,"createPool");if(this._wrap(Z,"createPool",this._patchCreatePool()),(0,EX.isWrapped)(Z.createPoolCluster))this._unwrap(Z,"createPoolCluster");return this._wrap(Z,"createPoolCluster",this._patchCreatePoolCluster()),Z},(Z)=>{if(Z===void 0)return;this._unwrap(Z,"createConnection"),this._unwrap(Z,"createPool"),this._unwrap(Z,"createPoolCluster")})]}_patchCreateConnection(){return(Z)=>{let J=this;return function($){let Y=Z(...arguments);return J._wrap(Y,"query",J._patchQuery(Y)),Y}}}_patchCreatePool(){return(Z)=>{let J=this;return function($){let Y=Z(...arguments);return J._wrap(Y,"query",J._patchQuery(Y)),J._wrap(Y,"getConnection",J._patchGetConnection(Y)),J._wrap(Y,"end",J._patchPoolEnd(Y)),J._setPoolcallbacks(Y,J,""),Y}}}_patchPoolEnd(Z){return(J)=>{let X=this;return function(Y){let Q=Z._allConnections.length,W=Z._freeConnections.length,K=Q-W,z=(0,IX.getPoolName)(Z);X._connectionsUsage.add(-K,{state:"used",name:z}),X._connectionsUsage.add(-W,{state:"idle",name:z}),J.apply(Z,arguments)}}}_patchCreatePoolCluster(){return(Z)=>{let J=this;return function($){let Y=Z(...arguments);return J._wrap(Y,"getConnection",J._patchGetConnection(Y)),J._wrap(Y,"add",J._patchAdd(Y)),Y}}}_patchAdd(Z){return(J)=>{let X=this;return function(Y,Q){if(!X._enabled)return X._unwrap(Z,"add"),J.apply(Z,arguments);J.apply(Z,arguments);let W=Z._nodes;if(W){let K=typeof Y==="object"?"CLUSTER::"+Z._lastId:String(Y),z=W[K].pool;X._setPoolcallbacks(z,X,Y)}}}}_patchGetConnection(Z){return(J)=>{let X=this;return function(Y,Q,W){if(!X._enabled)return X._unwrap(Z,"getConnection"),J.apply(Z,arguments);if(arguments.length===1&&typeof Y==="function"){let K=X._getConnectionCallbackPatchFn(Y);return J.call(Z,K)}if(arguments.length===2&&typeof Q==="function"){let K=X._getConnectionCallbackPatchFn(Q);return J.call(Z,Y,K)}if(arguments.length===3&&typeof W==="function"){let K=X._getConnectionCallbackPatchFn(W);return J.call(Z,Y,Q,K)}return J.apply(Z,arguments)}}}_getConnectionCallbackPatchFn(Z){let J=this,X=Y6.context.active();return function($,Y){if(Y){if(!(0,EX.isWrapped)(Y.query))J._wrap(Y,"query",J._patchQuery(Y))}if(typeof Z==="function")Y6.context.with(X,Z,this,$,Y)}}_patchQuery(Z){return(J)=>{let X=this;return function($,Y,Q){if(!X._enabled)return X._unwrap(Z,"query"),J.apply(Z,arguments);let W=X.tracer.startSpan((0,IX.getSpanName)($),{kind:Y6.SpanKind.CLIENT,attributes:{...P2.COMMON_ATTRIBUTES,...(0,IX.getConnectionAttributes)(Z.config)}});if(W.setAttribute(Vz.ATTR_DB_STATEMENT,(0,IX.getDbStatement)($)),X.getConfig().enhancedDatabaseReporting){let G;if(Array.isArray(Y))G=Y;else if(arguments[2])G=[Y];W.setAttribute(th0.AttributeNames.MYSQL_VALUES,(0,IX.getDbValues)($,G))}let K=Array.from(arguments).findIndex((G)=>typeof G==="function"),z=Y6.context.active();if(K===-1){let G=Y6.context.with(Y6.trace.setSpan(Y6.context.active(),W),()=>{return J.apply(Z,arguments)});return Y6.context.bind(z,G),G.on("error",(H)=>W.setStatus({code:Y6.SpanStatusCode.ERROR,message:H.message})).on("end",()=>{W.end()})}else return X._wrap(arguments,K,X._patchCallbackQuery(W,z)),Y6.context.with(Y6.trace.setSpan(Y6.context.active(),W),()=>{return J.apply(Z,arguments)})}}}_patchCallbackQuery(Z,J){return(X)=>{return function($,Y,Q){if($)Z.setStatus({code:Y6.SpanStatusCode.ERROR,message:$.message});return Z.end(),Y6.context.with(J,()=>X(...arguments))}}}_setPoolcallbacks(Z,J,X){let $=X||(0,IX.getPoolName)(Z);Z.on("connection",(Y)=>{J._connectionsUsage.add(1,{state:"idle",name:$})}),Z.on("acquire",(Y)=>{J._connectionsUsage.add(-1,{state:"idle",name:$}),J._connectionsUsage.add(1,{state:"used",name:$})}),Z.on("release",(Y)=>{J._connectionsUsage.add(-1,{state:"used",name:$}),J._connectionsUsage.add(1,{state:"idle",name:$})})}}an.MySQLInstrumentation=P2});var tn=L((E2)=>{Object.defineProperty(E2,"__esModule",{value:!0});E2.MySQLInstrumentation=void 0;var eh0=sn();Object.defineProperty(E2,"MySQLInstrumentation",{enumerable:!0,get:function(){return eh0.MySQLInstrumentation}})});var I2=L(($o)=>{Object.defineProperty($o,"__esModule",{value:!0});$o.DB_SYSTEM_VALUE_MYSQL=$o.ATTR_NET_PEER_PORT=$o.ATTR_NET_PEER_NAME=$o.ATTR_DB_USER=$o.ATTR_DB_SYSTEM=$o.ATTR_DB_STATEMENT=$o.ATTR_DB_NAME=$o.ATTR_DB_CONNECTION_STRING=void 0;$o.ATTR_DB_CONNECTION_STRING="db.connection_string";$o.ATTR_DB_NAME="db.name";$o.ATTR_DB_STATEMENT="db.statement";$o.ATTR_DB_SYSTEM="db.system";$o.ATTR_DB_USER="db.user";$o.ATTR_NET_PEER_NAME="net.peer.name";$o.ATTR_NET_PEER_PORT="net.peer.port";$o.DB_SYSTEM_VALUE_MYSQL="mysql"});var S2=L((Qo)=>{Object.defineProperty(Qo,"__esModule",{value:!0});Qo.addSqlCommenterComment=void 0;var y2=f(),Gf0=H1();function Hf0(Z){let J=Z.indexOf("--");if(J>=0)return!0;if(Z.indexOf("/*")<0)return!1;let $=Z.indexOf("*/");return J<$}function Vf0(Z){return encodeURIComponent(Z).replace(/[!'()*]/g,(J)=>`%${J.charCodeAt(0).toString(16).toUpperCase()}`)}function Ff0(Z,J){if(typeof J!=="string"||J.length===0)return J;if(Hf0(J))return J;let X=new Gf0.W3CTraceContextPropagator,$={};X.inject(y2.trace.setSpan(y2.ROOT_CONTEXT,Z),$,y2.defaultTextMapSetter);let Y=Object.keys($).sort();if(Y.length===0)return J;let Q=Y.map((W)=>{let K=Vf0($[W]);return`${W}='${K}'`}).join(",");return`${J} /*${Q}*/`}Qo.addSqlCommenterComment=Ff0});var Go=L((Ko)=>{Object.defineProperty(Ko,"__esModule",{value:!0});Ko.getConnectionPrototypeToInstrument=Ko.once=Ko.getSpanName=Ko.getQueryText=Ko.getConnectionAttributes=void 0;var K3=I2(),Fz=H0(),k2=p0();function Bf0(Z,J,X){let{host:$,port:Y,database:Q,user:W}=Uf0(Z),K={};if(J&Fz.SemconvStability.OLD)K[K3.ATTR_DB_CONNECTION_STRING]=Lf0($,Y,Q),K[K3.ATTR_DB_NAME]=Q,K[K3.ATTR_DB_USER]=W;if(J&Fz.SemconvStability.STABLE)K[k2.ATTR_DB_NAMESPACE]=Q;let z=parseInt(Y,10);if(X&Fz.SemconvStability.OLD){if(K[K3.ATTR_NET_PEER_NAME]=$,!isNaN(z))K[K3.ATTR_NET_PEER_PORT]=z}if(X&Fz.SemconvStability.STABLE){if(K[k2.ATTR_SERVER_ADDRESS]=$,!isNaN(z))K[k2.ATTR_SERVER_PORT]=z}return K}Ko.getConnectionAttributes=Bf0;function Uf0(Z){let{host:J,port:X,database:$,user:Y}=Z&&Z.connectionConfig||Z||{};return{host:J,port:X,database:$,user:Y}}function Lf0(Z,J,X){let $=`jdbc:mysql://${Z||"localhost"}`;if(typeof J==="number")$+=`:${J}`;if(typeof X==="string")$+=`/${X}`;return $}function Df0(Z,J,X,$=!1,Y=_f0){let[Q,W]=typeof Z==="string"?[Z,X]:[Z.sql,Of0(Z)?X||Z.values:X];try{if($)return Y(Q);else if(J&&W)return J(Q,W);else return Q}catch(K){return"Could not determine the query due to an error in masking or formatting"}}Ko.getQueryText=Df0;function _f0(Z){return Z.replace(/\b\d+\b/g,"?").replace(/(["'])(?:(?=(\\?))\2.)*?\1/g,"?")}function Of0(Z){return"values"in Z}function wf0(Z){let J=typeof Z==="object"?Z.sql:Z,X=J?.indexOf(" ");if(typeof X==="number"&&X!==-1)return J?.substring(0,X);return J}Ko.getSpanName=wf0;var jf0=(Z)=>{let J=!1;return(...X)=>{if(J)return;return J=!0,Z(...X)}};Ko.once=jf0;function Mf0(Z){let J=Z.prototype,X=Object.getPrototypeOf(J);if(typeof X?.query==="function"&&typeof X?.execute==="function")return X;return J}Ko.getConnectionPrototypeToInstrument=Mf0});var Fo=L((Ho)=>{Object.defineProperty(Ho,"__esModule",{value:!0});Ho.PACKAGE_NAME=Ho.PACKAGE_VERSION=void 0;Ho.PACKAGE_VERSION="0.55.0";Ho.PACKAGE_NAME="@opentelemetry/instrumentation-mysql2"});var wo=L((_o)=>{Object.defineProperty(_o,"__esModule",{value:!0});_o.MySQL2Instrumentation=void 0;var Bo=f(),y8=H0(),x2=I2(),Uo=S2(),yX=Go(),Lo=Fo(),v2=p0(),h2=[">=1.4.2 <4"];class Do extends y8.InstrumentationBase{_netSemconvStability;_dbSemconvStability;constructor(Z={}){super(Lo.PACKAGE_NAME,Lo.PACKAGE_VERSION,Z);this._setSemconvStabilityFromEnv()}_setSemconvStabilityFromEnv(){this._netSemconvStability=(0,y8.semconvStabilityFromStr)("http",process.env.OTEL_SEMCONV_STABILITY_OPT_IN),this._dbSemconvStability=(0,y8.semconvStabilityFromStr)("database",process.env.OTEL_SEMCONV_STABILITY_OPT_IN)}init(){let Z;function J(Y){if(!Z&&Y.format)Z=Y.format}let X=(Y)=>{if((0,y8.isWrapped)(Y.query))this._unwrap(Y,"query");if(this._wrap(Y,"query",this._patchQuery(Z,!1)),(0,y8.isWrapped)(Y.execute))this._unwrap(Y,"execute");this._wrap(Y,"execute",this._patchQuery(Z,!0))},$=(Y)=>{this._unwrap(Y,"query"),this._unwrap(Y,"execute")};return[new y8.InstrumentationNodeModuleDefinition("mysql2",h2,(Y)=>{return J(Y),Y},()=>{},[new y8.InstrumentationNodeModuleFile("mysql2/promise.js",h2,(Y)=>{return J(Y),Y},()=>{}),new y8.InstrumentationNodeModuleFile("mysql2/lib/connection.js",h2,(Y)=>{let Q=(0,yX.getConnectionPrototypeToInstrument)(Y);return X(Q),Y},(Y)=>{if(Y===void 0)return;let Q=(0,yX.getConnectionPrototypeToInstrument)(Y);$(Q)})])]}_patchQuery(Z,J){return(X)=>{let $=this;return function(Y,Q,W){let K;if(Array.isArray(Q))K=Q;else if(arguments[2])K=[Q];let{maskStatement:z,maskStatementHook:G,responseHook:H}=$.getConfig(),V=(0,yX.getConnectionAttributes)(this.config,$._dbSemconvStability,$._netSemconvStability),F=(0,yX.getQueryText)(Y,Z,K,z,G);if($._dbSemconvStability&y8.SemconvStability.OLD)V[x2.ATTR_DB_SYSTEM]=x2.DB_SYSTEM_VALUE_MYSQL,V[x2.ATTR_DB_STATEMENT]=F;if($._dbSemconvStability&y8.SemconvStability.STABLE)V[v2.ATTR_DB_SYSTEM_NAME]=v2.DB_SYSTEM_NAME_VALUE_MYSQL,V[v2.ATTR_DB_QUERY_TEXT]=F;let B=$.tracer.startSpan((0,yX.getSpanName)(Y),{kind:Bo.SpanKind.CLIENT,attributes:V});if(!J&&$.getConfig().addSqlCommenterCommentToQueries)arguments[0]=Y=typeof Y==="string"?(0,Uo.addSqlCommenterComment)(B,Y):Object.assign(Y,{sql:(0,Uo.addSqlCommenterComment)(B,Y.sql)});let U=(0,yX.once)((D,_)=>{if(D)B.setStatus({code:Bo.SpanStatusCode.ERROR,message:D.message});else if(typeof H==="function")(0,y8.safeExecuteInTheMiddle)(()=>{H(B,{queryResults:_})},(O)=>{if(O)$._diag.warn("Failed executing responseHook",O)},!0);B.end()});if(arguments.length===1){if(typeof Y.onResult==="function")$._wrap(Y,"onResult",$._patchCallbackQuery(U));let D=X.apply(this,arguments);return D.once("error",(_)=>{U(_)}).once("result",(_)=>{U(void 0,_)}),D}if(typeof arguments[1]==="function")$._wrap(arguments,1,$._patchCallbackQuery(U));else if(typeof arguments[2]==="function")$._wrap(arguments,2,$._patchCallbackQuery(U));return X.apply(this,arguments)}}}_patchCallbackQuery(Z){return(J)=>{return function(X,$,Y){return Z(X,$),J(...arguments)}}}}_o.MySQL2Instrumentation=Do});var jo=L((f2)=>{Object.defineProperty(f2,"__esModule",{value:!0});f2.MySQL2Instrumentation=void 0;var Rf0=wo();Object.defineProperty(f2,"MySQL2Instrumentation",{enumerable:!0,get:function(){return Rf0.MySQL2Instrumentation}})});var Ro=L((Co)=>{Object.defineProperty(Co,"__esModule",{value:!0});Co.DB_SYSTEM_VALUE_REDIS=Co.ATTR_NET_PEER_PORT=Co.ATTR_NET_PEER_NAME=Co.ATTR_DB_SYSTEM=Co.ATTR_DB_STATEMENT=Co.ATTR_DB_CONNECTION_STRING=void 0;Co.ATTR_DB_CONNECTION_STRING="db.connection_string";Co.ATTR_DB_STATEMENT="db.statement";Co.ATTR_DB_SYSTEM="db.system";Co.ATTR_NET_PEER_NAME="net.peer.name";Co.ATTR_NET_PEER_PORT="net.peer.port";Co.DB_SYSTEM_VALUE_REDIS="redis"});var Io=L((Po)=>{Object.defineProperty(Po,"__esModule",{value:!0});Po.endSpan=void 0;var vf0=f(),hf0=(Z,J)=>{if(J)Z.recordException(J),Z.setStatus({code:vf0.SpanStatusCode.ERROR,message:J.message});Z.end()};Po.endSpan=hf0});var Bz=L((yo)=>{Object.defineProperty(yo,"__esModule",{value:!0});yo.defaultDbStatementSerializer=void 0;var ff0=[{regex:/^ECHO/i,args:0},{regex:/^(LPUSH|MSET|PFA|PUBLISH|RPUSH|SADD|SET|SPUBLISH|XADD|ZADD)/i,args:1},{regex:/^(HSET|HMSET|LSET|LINSERT)/i,args:2},{regex:/^(ACL|BIT|B[LRZ]|CLIENT|CLUSTER|CONFIG|COMMAND|DECR|DEL|EVAL|EX|FUNCTION|GEO|GET|HINCR|HMGET|HSCAN|INCR|L[TRLM]|MEMORY|P[EFISTU]|RPOP|S[CDIMORSU]|XACK|X[CDGILPRT]|Z[CDILMPRS])/i,args:-1}],bf0=(Z,J)=>{if(Array.isArray(J)&&J.length){let X=ff0.find(({regex:Y})=>{return Y.test(Z)})?.args??0,$=X>=0?J.slice(0,X):J;if(J.length>$.length)$.push(`[${J.length-X} other arguments]`);return`${Z} ${$.join(" ")}`}return Z};yo.defaultDbStatementSerializer=bf0});var vo=L((ko)=>{Object.defineProperty(ko,"__esModule",{value:!0});ko.PACKAGE_NAME=ko.PACKAGE_VERSION=void 0;ko.PACKAGE_VERSION="0.56.0";ko.PACKAGE_NAME="@opentelemetry/instrumentation-ioredis"});var co=L((mo)=>{Object.defineProperty(mo,"__esModule",{value:!0});mo.IORedisInstrumentation=void 0;var L7=f(),Uz=H0(),n6=Ro(),ho=H0(),z3=Io(),mf0=Bz(),fo=vo(),bo={requireParentSpan:!0};class go extends Uz.InstrumentationBase{constructor(Z={}){super(fo.PACKAGE_NAME,fo.PACKAGE_VERSION,{...bo,...Z})}setConfig(Z={}){super.setConfig({...bo,...Z})}init(){return[new Uz.InstrumentationNodeModuleDefinition("ioredis",[">=2.0.0 <6"],(Z,J)=>{let X=Z[Symbol.toStringTag]==="Module"?Z.default:Z;if((0,Uz.isWrapped)(X.prototype.sendCommand))this._unwrap(X.prototype,"sendCommand");if(this._wrap(X.prototype,"sendCommand",this._patchSendCommand(J)),(0,Uz.isWrapped)(X.prototype.connect))this._unwrap(X.prototype,"connect");return this._wrap(X.prototype,"connect",this._patchConnection()),Z},(Z)=>{if(Z===void 0)return;let J=Z[Symbol.toStringTag]==="Module"?Z.default:Z;this._unwrap(J.prototype,"sendCommand"),this._unwrap(J.prototype,"connect")})]}_patchSendCommand(Z){return(J)=>{return this._traceSendCommand(J,Z)}}_patchConnection(){return(Z)=>{return this._traceConnection(Z)}}_traceSendCommand(Z,J){let X=this;return function($){if(arguments.length<1||typeof $!=="object")return Z.apply(this,arguments);let Y=X.getConfig(),Q=Y.dbStatementSerializer||mf0.defaultDbStatementSerializer,W=L7.trace.getSpan(L7.context.active())===void 0;if(Y.requireParentSpan===!0&&W)return Z.apply(this,arguments);let K=X.tracer.startSpan($.name,{kind:L7.SpanKind.CLIENT,attributes:{[n6.ATTR_DB_SYSTEM]:n6.DB_SYSTEM_VALUE_REDIS,[n6.ATTR_DB_STATEMENT]:Q($.name,$.args)}}),{requestHook:z}=Y;if(z)(0,ho.safeExecuteInTheMiddle)(()=>z(K,{moduleVersion:J,cmdName:$.name,cmdArgs:$.args}),(V)=>{if(V)L7.diag.error("ioredis instrumentation: request hook failed",V)},!0);let{host:G,port:H}=this.options;K.setAttributes({[n6.ATTR_NET_PEER_NAME]:G,[n6.ATTR_NET_PEER_PORT]:H,[n6.ATTR_DB_CONNECTION_STRING]:`redis://${G}:${H}`});try{let V=Z.apply(this,arguments),F=$.resolve;$.resolve=function(U){(0,ho.safeExecuteInTheMiddle)(()=>Y.responseHook?.(K,$.name,$.args,U),(D)=>{if(D)L7.diag.error("ioredis instrumentation: response hook failed",D)},!0),(0,z3.endSpan)(K,null),F(U)};let B=$.reject;return $.reject=function(U){(0,z3.endSpan)(K,U),B(U)},V}catch(V){throw(0,z3.endSpan)(K,V),V}}}_traceConnection(Z){let J=this;return function(){let X=L7.trace.getSpan(L7.context.active())===void 0;if(J.getConfig().requireParentSpan===!0&&X)return Z.apply(this,arguments);let $=J.tracer.startSpan("connect",{kind:L7.SpanKind.CLIENT,attributes:{[n6.ATTR_DB_SYSTEM]:n6.DB_SYSTEM_VALUE_REDIS,[n6.ATTR_DB_STATEMENT]:"connect"}}),{host:Y,port:Q}=this.options;$.setAttributes({[n6.ATTR_NET_PEER_NAME]:Y,[n6.ATTR_NET_PEER_PORT]:Q,[n6.ATTR_DB_CONNECTION_STRING]:`redis://${Y}:${Q}`});try{let W=Z.apply(this,arguments);return(0,z3.endSpan)($,null),W}catch(W){throw(0,z3.endSpan)($,W),W}}}}mo.IORedisInstrumentation=go});var lo=L((b2)=>{Object.defineProperty(b2,"__esModule",{value:!0});b2.IORedisInstrumentation=void 0;var df0=co();Object.defineProperty(b2,"IORedisInstrumentation",{enumerable:!0,get:function(){return df0.IORedisInstrumentation}})});var Lz=L((po)=>{Object.defineProperty(po,"__esModule",{value:!0});po.PACKAGE_NAME=po.PACKAGE_VERSION=void 0;po.PACKAGE_VERSION="0.57.0";po.PACKAGE_NAME="@opentelemetry/instrumentation-redis"});var ao=L((no)=>{Object.defineProperty(no,"__esModule",{value:!0});no.getTracedCreateStreamTrace=no.getTracedCreateClient=no.endSpan=void 0;var G3=f(),lf0=(Z,J)=>{if(J)Z.setStatus({code:G3.SpanStatusCode.ERROR,message:J.message});Z.end()};no.endSpan=lf0;var pf0=(Z)=>{return function(){let X=Z.apply(this,arguments);return G3.context.bind(G3.context.active(),X)}};no.getTracedCreateClient=pf0;var if0=(Z)=>{return function(){if(!Object.prototype.hasOwnProperty.call(this,"stream"))Object.defineProperty(this,"stream",{get(){return this._patched_redis_stream},set(X){G3.context.bind(G3.context.active(),X),this._patched_redis_stream=X}});return Z.apply(this,arguments)}};no.getTracedCreateStreamTrace=if0});var Dz=L((ro)=>{Object.defineProperty(ro,"__esModule",{value:!0});ro.DB_SYSTEM_VALUE_REDIS=ro.DB_SYSTEM_NAME_VALUE_REDIS=ro.ATTR_NET_PEER_PORT=ro.ATTR_NET_PEER_NAME=ro.ATTR_DB_SYSTEM=ro.ATTR_DB_STATEMENT=ro.ATTR_DB_CONNECTION_STRING=void 0;ro.ATTR_DB_CONNECTION_STRING="db.connection_string";ro.ATTR_DB_STATEMENT="db.statement";ro.ATTR_DB_SYSTEM="db.system";ro.ATTR_NET_PEER_NAME="net.peer.name";ro.ATTR_NET_PEER_PORT="net.peer.port";ro.DB_SYSTEM_NAME_VALUE_REDIS="redis";ro.DB_SYSTEM_VALUE_REDIS="redis"});var Ja=L((eo)=>{Object.defineProperty(eo,"__esModule",{value:!0});eo.RedisInstrumentationV2_V3=void 0;var q6=H0(),_z=ao(),to=Lz(),H3=f(),V3=p0(),SZ=Dz(),Jb0=Bz();class g2 extends q6.InstrumentationBase{static COMPONENT="redis";_semconvStability;constructor(Z={}){super(to.PACKAGE_NAME,to.PACKAGE_VERSION,Z);this._semconvStability=Z.semconvStability?Z.semconvStability:(0,q6.semconvStabilityFromStr)("database",process.env.OTEL_SEMCONV_STABILITY_OPT_IN)}setConfig(Z={}){super.setConfig(Z),this._semconvStability=Z.semconvStability?Z.semconvStability:(0,q6.semconvStabilityFromStr)("database",process.env.OTEL_SEMCONV_STABILITY_OPT_IN)}init(){return[new q6.InstrumentationNodeModuleDefinition("redis",[">=2.6.0 <4"],(Z)=>{if((0,q6.isWrapped)(Z.RedisClient.prototype.internal_send_command))this._unwrap(Z.RedisClient.prototype,"internal_send_command");if(this._wrap(Z.RedisClient.prototype,"internal_send_command",this._getPatchInternalSendCommand()),(0,q6.isWrapped)(Z.RedisClient.prototype.create_stream))this._unwrap(Z.RedisClient.prototype,"create_stream");if(this._wrap(Z.RedisClient.prototype,"create_stream",this._getPatchCreateStream()),(0,q6.isWrapped)(Z.createClient))this._unwrap(Z,"createClient");return this._wrap(Z,"createClient",this._getPatchCreateClient()),Z},(Z)=>{if(Z===void 0)return;this._unwrap(Z.RedisClient.prototype,"internal_send_command"),this._unwrap(Z.RedisClient.prototype,"create_stream"),this._unwrap(Z,"createClient")})]}_getPatchInternalSendCommand(){let Z=this;return function(X){return function(Y){if(arguments.length!==1||typeof Y!=="object")return X.apply(this,arguments);let Q=Z.getConfig(),W=H3.trace.getSpan(H3.context.active())===void 0;if(Q.requireParentSpan===!0&&W)return X.apply(this,arguments);let K=Q?.dbStatementSerializer||Jb0.defaultDbStatementSerializer,z={};if(Z._semconvStability&q6.SemconvStability.OLD)Object.assign(z,{[SZ.ATTR_DB_SYSTEM]:SZ.DB_SYSTEM_VALUE_REDIS,[SZ.ATTR_DB_STATEMENT]:K(Y.command,Y.args)});if(Z._semconvStability&q6.SemconvStability.STABLE)Object.assign(z,{[V3.ATTR_DB_SYSTEM_NAME]:SZ.DB_SYSTEM_NAME_VALUE_REDIS,[V3.ATTR_DB_OPERATION_NAME]:Y.command,[V3.ATTR_DB_QUERY_TEXT]:K(Y.command,Y.args)});let G=Z.tracer.startSpan(`${g2.COMPONENT}-${Y.command}`,{kind:H3.SpanKind.CLIENT,attributes:z});if(this.connection_options){let V={};if(Z._semconvStability&q6.SemconvStability.OLD)Object.assign(V,{[SZ.ATTR_NET_PEER_NAME]:this.connection_options.host,[SZ.ATTR_NET_PEER_PORT]:this.connection_options.port});if(Z._semconvStability&q6.SemconvStability.STABLE)Object.assign(V,{[V3.ATTR_SERVER_ADDRESS]:this.connection_options.host,[V3.ATTR_SERVER_PORT]:this.connection_options.port});G.setAttributes(V)}if(this.address&&Z._semconvStability&q6.SemconvStability.OLD)G.setAttribute(SZ.ATTR_DB_CONNECTION_STRING,`redis://${this.address}`);let H=arguments[0].callback;if(H){let V=H3.context.active();arguments[0].callback=function(B,U){if(Q?.responseHook){let D=Q.responseHook;(0,q6.safeExecuteInTheMiddle)(()=>{D(G,Y.command,Y.args,U)},(_)=>{if(_)Z._diag.error("Error executing responseHook",_)},!0)}return(0,_z.endSpan)(G,B),H3.context.with(V,H,this,...arguments)}}try{return X.apply(this,arguments)}catch(V){throw(0,_z.endSpan)(G,V),V}}}}_getPatchCreateClient(){return function(J){return(0,_z.getTracedCreateClient)(J)}}_getPatchCreateStream(){return function(J){return(0,_z.getTracedCreateStreamTrace)(J)}}}eo.RedisInstrumentationV2_V3=g2});var Qa=L(($a)=>{Object.defineProperty($a,"__esModule",{value:!0});$a.getClientAttributes=void 0;var m2=p0(),SX=Dz(),Xa=H0();function Xb0(Z,J,X){let $={};if(X&Xa.SemconvStability.OLD)Object.assign($,{[SX.ATTR_DB_SYSTEM]:SX.DB_SYSTEM_VALUE_REDIS,[SX.ATTR_NET_PEER_NAME]:J?.socket?.host,[SX.ATTR_NET_PEER_PORT]:J?.socket?.port,[SX.ATTR_DB_CONNECTION_STRING]:$b0(Z,J?.url)});if(X&Xa.SemconvStability.STABLE)Object.assign($,{[m2.ATTR_DB_SYSTEM_NAME]:SX.DB_SYSTEM_NAME_VALUE_REDIS,[m2.ATTR_SERVER_ADDRESS]:J?.socket?.host,[m2.ATTR_SERVER_PORT]:J?.socket?.port});return $}$a.getClientAttributes=Xb0;function $b0(Z,J){if(typeof J!=="string"||!J)return;try{let X=new URL(J);return X.searchParams.delete("user_pwd"),X.username="",X.password="",X.href}catch(X){Z.error("failed to sanitize redis connection url",X)}return}});var Fa=L((Ha)=>{Object.defineProperty(Ha,"__esModule",{value:!0});Ha.RedisInstrumentationV4_V5=void 0;var o6=f(),O1=H0(),Wa=Qa(),Yb0=Bz(),Ka=Lz(),za=p0(),Qb0=Dz(),F3=Symbol("opentelemetry.instrumentation.redis.open_spans"),Ga=Symbol("opentelemetry.instrumentation.redis.multi_command_options");class Oz extends O1.InstrumentationBase{static COMPONENT="redis";_semconvStability;constructor(Z={}){super(Ka.PACKAGE_NAME,Ka.PACKAGE_VERSION,Z);this._semconvStability=Z.semconvStability?Z.semconvStability:(0,O1.semconvStabilityFromStr)("database",process.env.OTEL_SEMCONV_STABILITY_OPT_IN)}setConfig(Z={}){super.setConfig(Z),this._semconvStability=Z.semconvStability?Z.semconvStability:(0,O1.semconvStabilityFromStr)("database",process.env.OTEL_SEMCONV_STABILITY_OPT_IN)}init(){return[this._getInstrumentationNodeModuleDefinition("@redis/client"),this._getInstrumentationNodeModuleDefinition("@node-redis/client")]}_getInstrumentationNodeModuleDefinition(Z){let J=new O1.InstrumentationNodeModuleFile(`${Z}/dist/lib/commander.js`,["^1.0.0"],(Y,Q)=>{let W=Y.transformCommandArguments;if(!W)return this._diag.error("internal instrumentation error, missing transformCommandArguments function"),Y;let K=Q?.startsWith("1.0.")?"extendWithCommands":"attachCommands";if((0,O1.isWrapped)(Y?.[K]))this._unwrap(Y,K);return this._wrap(Y,K,this._getPatchExtendWithCommands(W)),Y},(Y)=>{if((0,O1.isWrapped)(Y?.extendWithCommands))this._unwrap(Y,"extendWithCommands");if((0,O1.isWrapped)(Y?.attachCommands))this._unwrap(Y,"attachCommands")}),X=new O1.InstrumentationNodeModuleFile(`${Z}/dist/lib/client/multi-command.js`,["^1.0.0","^5.0.0"],(Y)=>{let Q=Y?.default?.prototype;if((0,O1.isWrapped)(Q?.exec))this._unwrap(Q,"exec");if(this._wrap(Q,"exec",this._getPatchMultiCommandsExec()),(0,O1.isWrapped)(Q?.addCommand))this._unwrap(Q,"addCommand");return this._wrap(Q,"addCommand",this._getPatchMultiCommandsAddCommand()),Y},(Y)=>{let Q=Y?.default?.prototype;if((0,O1.isWrapped)(Q?.exec))this._unwrap(Q,"exec");if((0,O1.isWrapped)(Q?.addCommand))this._unwrap(Q,"addCommand")}),$=new O1.InstrumentationNodeModuleFile(`${Z}/dist/lib/client/index.js`,["^1.0.0","^5.0.0"],(Y)=>{let Q=Y?.default?.prototype;if(Q?.multi){if((0,O1.isWrapped)(Q?.multi))this._unwrap(Q,"multi");this._wrap(Q,"multi",this._getPatchRedisClientMulti())}if(Q?.MULTI){if((0,O1.isWrapped)(Q?.MULTI))this._unwrap(Q,"MULTI");this._wrap(Q,"MULTI",this._getPatchRedisClientMulti())}if((0,O1.isWrapped)(Q?.sendCommand))this._unwrap(Q,"sendCommand");return this._wrap(Q,"sendCommand",this._getPatchRedisClientSendCommand()),this._wrap(Q,"connect",this._getPatchedClientConnect()),Y},(Y)=>{let Q=Y?.default?.prototype;if((0,O1.isWrapped)(Q?.multi))this._unwrap(Q,"multi");if((0,O1.isWrapped)(Q?.MULTI))this._unwrap(Q,"MULTI");if((0,O1.isWrapped)(Q?.sendCommand))this._unwrap(Q,"sendCommand")});return new O1.InstrumentationNodeModuleDefinition(Z,["^1.0.0","^5.0.0"],(Y)=>{return Y},()=>{},[J,X,$])}_getPatchExtendWithCommands(Z){let J=this;return function($){return function(Q){if(Q?.BaseClass?.name!=="RedisClient")return $.apply(this,arguments);let W=Q.executor;return Q.executor=function(K,z){let G=Z(K,z).args;return J._traceClientCommand(W,this,arguments,G)},$.apply(this,arguments)}}}_getPatchMultiCommandsExec(){let Z=this;return function(X){return function(){let Y=X.apply(this,arguments);if(typeof Y?.then!=="function")return Z._diag.error("got non promise result when patching RedisClientMultiCommand.exec"),Y;return Y.then((Q)=>{let W=this[F3];return Z._endSpansWithRedisReplies(W,Q),Q}).catch((Q)=>{let W=this[F3];if(!W)Z._diag.error("cannot find open spans to end for redis multi command");else{let K=Q.constructor.name==="MultiErrorReply"?Q.replies:Array(W.length).fill(Q);Z._endSpansWithRedisReplies(W,K)}return Promise.reject(Q)})}}}_getPatchMultiCommandsAddCommand(){let Z=this;return function(X){return function(Y){return Z._traceClientCommand(X,this,arguments,Y)}}}_getPatchRedisClientMulti(){return function(J){return function(){let $=J.apply(this,arguments);return $[Ga]=this.options,$}}}_getPatchRedisClientSendCommand(){let Z=this;return function(X){return function(Y){return Z._traceClientCommand(X,this,arguments,Y)}}}_getPatchedClientConnect(){let Z=this;return function(X){return function(){let Y=this.options,Q=(0,Wa.getClientAttributes)(Z._diag,Y,Z._semconvStability),W=Z.tracer.startSpan(`${Oz.COMPONENT}-connect`,{kind:o6.SpanKind.CLIENT,attributes:Q});return o6.context.with(o6.trace.setSpan(o6.context.active(),W),()=>{return X.apply(this)}).then((z)=>{return W.end(),z}).catch((z)=>{return W.recordException(z),W.setStatus({code:o6.SpanStatusCode.ERROR,message:z.message}),W.end(),Promise.reject(z)})}}}_traceClientCommand(Z,J,X,$){if(o6.trace.getSpan(o6.context.active())===void 0&&this.getConfig().requireParentSpan)return Z.apply(J,X);let Q=J.options||J[Ga],W=$[0],K=$.slice(1),z=this.getConfig().dbStatementSerializer||Yb0.defaultDbStatementSerializer,G=(0,Wa.getClientAttributes)(this._diag,Q,this._semconvStability);if(this._semconvStability&O1.SemconvStability.STABLE)G[za.ATTR_DB_OPERATION_NAME]=W;try{let F=z(W,K);if(F!=null){if(this._semconvStability&O1.SemconvStability.OLD)G[Qb0.ATTR_DB_STATEMENT]=F;if(this._semconvStability&O1.SemconvStability.STABLE)G[za.ATTR_DB_QUERY_TEXT]=F}}catch(F){this._diag.error("dbStatementSerializer throw an exception",F,{commandName:W})}let H=this.tracer.startSpan(`${Oz.COMPONENT}-${W}`,{kind:o6.SpanKind.CLIENT,attributes:G}),V=o6.context.with(o6.trace.setSpan(o6.context.active(),H),()=>{return Z.apply(J,X)});if(typeof V?.then==="function")V.then((F)=>{this._endSpanWithResponse(H,W,K,F,void 0)},(F)=>{this._endSpanWithResponse(H,W,K,null,F)});else{let F=V;F[F3]=F[F3]||[],F[F3].push({span:H,commandName:W,commandArgs:K})}return V}_endSpansWithRedisReplies(Z,J){if(!Z)return this._diag.error("cannot find open spans to end for redis multi command");if(J.length!==Z.length)return this._diag.error("number of multi command spans does not match response from redis");for(let X=0;X<Z.length;X++){let{span:$,commandName:Y,commandArgs:Q}=Z[X],W=J[X],[K,z]=W instanceof Error?[null,W]:[W,void 0];this._endSpanWithResponse($,Y,Q,K,z)}}_endSpanWithResponse(Z,J,X,$,Y){let{responseHook:Q}=this.getConfig();if(!Y&&Q)try{Q(Z,J,X,$)}catch(W){this._diag.error("responseHook throw an exception",W)}if(Y)Z.recordException(Y),Z.setStatus({code:o6.SpanStatusCode.ERROR,message:Y?.message});Z.end()}}Ha.RedisInstrumentationV4_V5=Oz});var Oa=L((Da)=>{Object.defineProperty(Da,"__esModule",{value:!0});Da.RedisInstrumentation=void 0;var Wb0=H0(),Ba=Lz(),Kb0=Ja(),zb0=Fa(),Ua={requireParentSpan:!1};class La extends Wb0.InstrumentationBase{instrumentationV2_V3;instrumentationV4_V5;initialized=!1;constructor(Z={}){let J={...Ua,...Z};super(Ba.PACKAGE_NAME,Ba.PACKAGE_VERSION,J);this.instrumentationV2_V3=new Kb0.RedisInstrumentationV2_V3(this.getConfig()),this.instrumentationV4_V5=new zb0.RedisInstrumentationV4_V5(this.getConfig()),this.initialized=!0}setConfig(Z={}){let J={...Ua,...Z};if(super.setConfig(J),!this.initialized)return;this.instrumentationV2_V3.setConfig(J),this.instrumentationV4_V5.setConfig(J)}init(){}getModuleDefinitions(){return[...this.instrumentationV2_V3.getModuleDefinitions(),...this.instrumentationV4_V5.getModuleDefinitions()]}setTracerProvider(Z){if(super.setTracerProvider(Z),!this.initialized)return;this.instrumentationV2_V3.setTracerProvider(Z),this.instrumentationV4_V5.setTracerProvider(Z)}enable(){if(super.enable(),!this.initialized)return;this.instrumentationV2_V3.enable(),this.instrumentationV4_V5.enable()}disable(){if(super.disable(),!this.initialized)return;this.instrumentationV2_V3.disable(),this.instrumentationV4_V5.disable()}}Da.RedisInstrumentation=La});var wa=L((d2)=>{Object.defineProperty(d2,"__esModule",{value:!0});d2.RedisInstrumentation=void 0;var Gb0=Oa();Object.defineProperty(d2,"RedisInstrumentation",{enumerable:!0,get:function(){return Gb0.RedisInstrumentation}})});var ya=L((Ea)=>{Object.defineProperty(Ea,"__esModule",{value:!0});Ea.EVENT_LISTENERS_SET=void 0;Ea.EVENT_LISTENERS_SET=Symbol("opentelemetry.instrumentation.pg.eventListenersSet")});var p2=L((Sa)=>{Object.defineProperty(Sa,"__esModule",{value:!0});Sa.AttributeNames=void 0;var _b0;(function(Z){Z.PG_VALUES="db.postgresql.values",Z.PG_PLAN="db.postgresql.plan",Z.IDLE_TIMEOUT_MILLIS="db.postgresql.idle.timeout.millis",Z.MAX_CLIENT="db.postgresql.max.client"})(_b0=Sa.AttributeNames||(Sa.AttributeNames={}))});var i2=L((ka)=>{Object.defineProperty(ka,"__esModule",{value:!0});ka.METRIC_DB_CLIENT_CONNECTION_PENDING_REQUESTS=ka.METRIC_DB_CLIENT_CONNECTION_COUNT=ka.DB_SYSTEM_VALUE_POSTGRESQL=ka.DB_CLIENT_CONNECTION_STATE_VALUE_USED=ka.DB_CLIENT_CONNECTION_STATE_VALUE_IDLE=ka.ATTR_NET_PEER_PORT=ka.ATTR_NET_PEER_NAME=ka.ATTR_DB_USER=ka.ATTR_DB_SYSTEM=ka.ATTR_DB_STATEMENT=ka.ATTR_DB_NAME=ka.ATTR_DB_CONNECTION_STRING=ka.ATTR_DB_CLIENT_CONNECTION_STATE=ka.ATTR_DB_CLIENT_CONNECTION_POOL_NAME=void 0;ka.ATTR_DB_CLIENT_CONNECTION_POOL_NAME="db.client.connection.pool.name";ka.ATTR_DB_CLIENT_CONNECTION_STATE="db.client.connection.state";ka.ATTR_DB_CONNECTION_STRING="db.connection_string";ka.ATTR_DB_NAME="db.name";ka.ATTR_DB_STATEMENT="db.statement";ka.ATTR_DB_SYSTEM="db.system";ka.ATTR_DB_USER="db.user";ka.ATTR_NET_PEER_NAME="net.peer.name";ka.ATTR_NET_PEER_PORT="net.peer.port";ka.DB_CLIENT_CONNECTION_STATE_VALUE_IDLE="idle";ka.DB_CLIENT_CONNECTION_STATE_VALUE_USED="used";ka.DB_SYSTEM_VALUE_POSTGRESQL="postgresql";ka.METRIC_DB_CLIENT_CONNECTION_COUNT="db.client.connection.count";ka.METRIC_DB_CLIENT_CONNECTION_PENDING_REQUESTS="db.client.connection.pending_requests"});var o2=L((va)=>{Object.defineProperty(va,"__esModule",{value:!0});va.SpanNames=void 0;var yb0;(function(Z){Z.QUERY_PREFIX="pg.query",Z.CONNECT="pg.connect",Z.POOL_CONNECT="pg-pool.connect"})(yb0=va.SpanNames||(va.SpanNames={}))});var la=L((ua)=>{Object.defineProperty(ua,"__esModule",{value:!0});ua.sanitizedErrorMessage=ua.isObjectWithTextString=ua.getErrorMessage=ua.patchClientConnectCallback=ua.patchCallbackPGPool=ua.updateCounter=ua.getPoolName=ua.patchCallback=ua.handleExecutionResult=ua.handleConfigQuery=ua.shouldSkipInstrumentation=ua.getSemanticAttributesFromPoolConnection=ua.getSemanticAttributesFromConnection=ua.getConnectionString=ua.parseAndMaskConnectionString=ua.parseNormalizedOperationName=ua.getQuerySpanName=void 0;var D7=f(),jz=p2(),a6=p0(),R1=i2(),kZ=H0(),ha=o2();function fa(Z,J){if(!J)return ha.SpanNames.QUERY_PREFIX;let X=typeof J.name==="string"&&J.name?J.name:ba(J.text);return`${ha.SpanNames.QUERY_PREFIX}:${X}${Z?` ${Z}`:""}`}ua.getQuerySpanName=fa;function ba(Z){let J=Z.indexOf(" "),X=J===-1?Z:Z.slice(0,J);return X=X.toUpperCase(),X.endsWith(";")?X.slice(0,-1):X}ua.parseNormalizedOperationName=ba;function ga(Z){try{let J=new URL(Z);return J.username="",J.password="",J.toString()}catch(J){return"postgresql://localhost:5432/"}}ua.parseAndMaskConnectionString=ga;function a2(Z){if("connectionString"in Z&&Z.connectionString)return ga(Z.connectionString);let J=Z.host||"localhost",X=Z.port||5432,$=Z.database||"";return`postgresql://${J}:${X}/${$}`}ua.getConnectionString=a2;function Mz(Z){if(Number.isInteger(Z))return Z;return}function ma(Z,J){let X={};if(J&kZ.SemconvStability.OLD)X={...X,[R1.ATTR_DB_SYSTEM]:R1.DB_SYSTEM_VALUE_POSTGRESQL,[R1.ATTR_DB_NAME]:Z.database,[R1.ATTR_DB_CONNECTION_STRING]:a2(Z),[R1.ATTR_DB_USER]:Z.user,[R1.ATTR_NET_PEER_NAME]:Z.host,[R1.ATTR_NET_PEER_PORT]:Mz(Z.port)};if(J&kZ.SemconvStability.STABLE)X={...X,[a6.ATTR_DB_SYSTEM_NAME]:a6.DB_SYSTEM_NAME_VALUE_POSTGRESQL,[a6.ATTR_DB_NAMESPACE]:Z.namespace,[a6.ATTR_SERVER_ADDRESS]:Z.host,[a6.ATTR_SERVER_PORT]:Mz(Z.port)};return X}ua.getSemanticAttributesFromConnection=ma;function Sb0(Z,J){let X;try{X=Z.connectionString?new URL(Z.connectionString):void 0}catch(Y){X=void 0}let $={[jz.AttributeNames.IDLE_TIMEOUT_MILLIS]:Z.idleTimeoutMillis,[jz.AttributeNames.MAX_CLIENT]:Z.maxClient};if(J&kZ.SemconvStability.OLD)$={...$,[R1.ATTR_DB_SYSTEM]:R1.DB_SYSTEM_VALUE_POSTGRESQL,[R1.ATTR_DB_NAME]:X?.pathname.slice(1)??Z.database,[R1.ATTR_DB_CONNECTION_STRING]:a2(Z),[R1.ATTR_NET_PEER_NAME]:X?.hostname??Z.host,[R1.ATTR_NET_PEER_PORT]:Number(X?.port)||Mz(Z.port),[R1.ATTR_DB_USER]:X?.username??Z.user};if(J&kZ.SemconvStability.STABLE)$={...$,[a6.ATTR_DB_SYSTEM_NAME]:a6.DB_SYSTEM_NAME_VALUE_POSTGRESQL,[a6.ATTR_DB_NAMESPACE]:Z.namespace,[a6.ATTR_SERVER_ADDRESS]:X?.hostname??Z.host,[a6.ATTR_SERVER_PORT]:Number(X?.port)||Mz(Z.port)};return $}ua.getSemanticAttributesFromPoolConnection=Sb0;function kb0(Z){return Z.requireParentSpan===!0&&D7.trace.getSpan(D7.context.active())===void 0}ua.shouldSkipInstrumentation=kb0;function xb0(Z,J,X,$){let{connectionParameters:Y}=this,Q=Y.database,W=fa(Q,$),K=Z.startSpan(W,{kind:D7.SpanKind.CLIENT,attributes:ma(Y,X)});if(!$)return K;if($.text){if(X&kZ.SemconvStability.OLD)K.setAttribute(R1.ATTR_DB_STATEMENT,$.text);if(X&kZ.SemconvStability.STABLE)K.setAttribute(a6.ATTR_DB_QUERY_TEXT,$.text)}if(J.enhancedDatabaseReporting&&Array.isArray($.values))try{let z=$.values.map((G)=>{if(G==null)return"null";else if(G instanceof Buffer)return G.toString();else if(typeof G==="object"){if(typeof G.toPostgres==="function")return G.toPostgres();return JSON.stringify(G)}else return G.toString()});K.setAttribute(jz.AttributeNames.PG_VALUES,z)}catch(z){D7.diag.error("failed to stringify ",$.values,z)}if(typeof $.name==="string")K.setAttribute(jz.AttributeNames.PG_PLAN,$.name);return K}ua.handleConfigQuery=xb0;function da(Z,J,X){if(typeof Z.responseHook==="function")(0,kZ.safeExecuteInTheMiddle)(()=>{Z.responseHook(J,{data:X})},($)=>{if($)D7.diag.error("Error running response hook",$)},!0)}ua.handleExecutionResult=da;function vb0(Z,J,X,$,Y){return function(W,K){if(W){if(Object.prototype.hasOwnProperty.call(W,"code"))$[a6.ATTR_ERROR_TYPE]=W.code;if(W instanceof Error)J.recordException(Az(W));J.setStatus({code:D7.SpanStatusCode.ERROR,message:W.message})}else da(Z,J,K);Y(),J.end(),X.call(this,W,K)}}ua.patchCallback=vb0;function hb0(Z){let J="";return J+=(Z?.host?`${Z.host}`:"unknown_host")+":",J+=(Z?.port?`${Z.port}`:"unknown_port")+"/",J+=Z?.database?`${Z.database}`:"unknown_database",J.trim()}ua.getPoolName=hb0;function fb0(Z,J,X,$,Y){let{totalCount:Q,waitingCount:W,idleCount:K}=J,z=Q-K;return X.add(z-Y.used,{[R1.ATTR_DB_CLIENT_CONNECTION_STATE]:R1.DB_CLIENT_CONNECTION_STATE_VALUE_USED,[R1.ATTR_DB_CLIENT_CONNECTION_POOL_NAME]:Z}),X.add(K-Y.idle,{[R1.ATTR_DB_CLIENT_CONNECTION_STATE]:R1.DB_CLIENT_CONNECTION_STATE_VALUE_IDLE,[R1.ATTR_DB_CLIENT_CONNECTION_POOL_NAME]:Z}),$.add(W-Y.pending,{[R1.ATTR_DB_CLIENT_CONNECTION_POOL_NAME]:Z}),{used:z,idle:K,pending:W}}ua.updateCounter=fb0;function bb0(Z,J){return function($,Y,Q){if($){if($ instanceof Error)Z.recordException(Az($));Z.setStatus({code:D7.SpanStatusCode.ERROR,message:$.message})}Z.end(),J.call(this,$,Y,Q)}}ua.patchCallbackPGPool=bb0;function gb0(Z,J){return function($){if($){if($ instanceof Error)Z.recordException(Az($));Z.setStatus({code:D7.SpanStatusCode.ERROR,message:$.message})}Z.end(),J.apply(this,arguments)}}ua.patchClientConnectCallback=gb0;function mb0(Z){return typeof Z==="object"&&Z!==null&&"message"in Z?String(Z.message):void 0}ua.getErrorMessage=mb0;function db0(Z){return typeof Z==="object"&&typeof Z?.text==="string"}ua.isObjectWithTextString=db0;function Az(Z){let J=Z?.name??"PostgreSQLError",X=Z?.code??"UNKNOWN";return`PostgreSQL error of type '${J}' occurred (code: ${X})`}ua.sanitizedErrorMessage=Az});var na=L((pa)=>{Object.defineProperty(pa,"__esModule",{value:!0});pa.PACKAGE_NAME=pa.PACKAGE_VERSION=void 0;pa.PACKAGE_VERSION="0.61.0";pa.PACKAGE_NAME="@opentelemetry/instrumentation-pg"});var Xr=L((Zr)=>{Object.defineProperty(Zr,"__esModule",{value:!0});Zr.PgInstrumentation=void 0;var v4=H0(),o0=f(),oa=ya(),w1=la(),aa=S2(),ra=na(),sa=o2(),Tz=H1(),S8=p0(),L3=i2();function kX(Z){return Z[Symbol.toStringTag]==="Module"?Z.default:Z}class ea extends v4.InstrumentationBase{_connectionsCounter={used:0,idle:0,pending:0};_semconvStability;constructor(Z={}){super(ra.PACKAGE_NAME,ra.PACKAGE_VERSION,Z);this._semconvStability=(0,v4.semconvStabilityFromStr)("database",process.env.OTEL_SEMCONV_STABILITY_OPT_IN)}_updateMetricInstruments(){this._operationDuration=this.meter.createHistogram(S8.METRIC_DB_CLIENT_OPERATION_DURATION,{description:"Duration of database client operations.",unit:"s",valueType:o0.ValueType.DOUBLE,advice:{explicitBucketBoundaries:[0.001,0.005,0.01,0.05,0.1,0.5,1,5,10]}}),this._connectionsCounter={idle:0,pending:0,used:0},this._connectionsCount=this.meter.createUpDownCounter(L3.METRIC_DB_CLIENT_CONNECTION_COUNT,{description:"The number of connections that are currently in state described by the state attribute.",unit:"{connection}"}),this._connectionPendingRequests=this.meter.createUpDownCounter(L3.METRIC_DB_CLIENT_CONNECTION_PENDING_REQUESTS,{description:"The number of current pending requests for an open connection.",unit:"{connection}"})}init(){let Z=[">=8.0.3 <9"],J=[">=2.0.0 <4"],X=new v4.InstrumentationNodeModuleFile("pg/lib/native/client.js",Z,this._patchPgClient.bind(this),this._unpatchPgClient.bind(this)),$=new v4.InstrumentationNodeModuleFile("pg/lib/client.js",Z,this._patchPgClient.bind(this),this._unpatchPgClient.bind(this)),Y=new v4.InstrumentationNodeModuleDefinition("pg",Z,(W)=>{let K=kX(W);return this._patchPgClient(K.Client),W},(W)=>{let K=kX(W);return this._unpatchPgClient(K.Client),W},[$,X]),Q=new v4.InstrumentationNodeModuleDefinition("pg-pool",J,(W)=>{let K=kX(W);if((0,v4.isWrapped)(K.prototype.connect))this._unwrap(K.prototype,"connect");return this._wrap(K.prototype,"connect",this._getPoolConnectPatch()),K},(W)=>{let K=kX(W);if((0,v4.isWrapped)(K.prototype.connect))this._unwrap(K.prototype,"connect")});return[Y,Q]}_patchPgClient(Z){if(!Z)return;let J=kX(Z);if((0,v4.isWrapped)(J.prototype.query))this._unwrap(J.prototype,"query");if((0,v4.isWrapped)(J.prototype.connect))this._unwrap(J.prototype,"connect");return this._wrap(J.prototype,"query",this._getClientQueryPatch()),this._wrap(J.prototype,"connect",this._getClientConnectPatch()),Z}_unpatchPgClient(Z){let J=kX(Z);if((0,v4.isWrapped)(J.prototype.query))this._unwrap(J.prototype,"query");if((0,v4.isWrapped)(J.prototype.connect))this._unwrap(J.prototype,"connect");return Z}_getClientConnectPatch(){let Z=this;return(J)=>{return function($){if(w1.shouldSkipInstrumentation(Z.getConfig()))return J.call(this,$);let Y=Z.tracer.startSpan(sa.SpanNames.CONNECT,{kind:o0.SpanKind.CLIENT,attributes:w1.getSemanticAttributesFromConnection(this,Z._semconvStability)});if($){let W=o0.trace.getSpan(o0.context.active());if($=w1.patchClientConnectCallback(Y,$),W)$=o0.context.bind(o0.context.active(),$)}let Q=o0.context.with(o0.trace.setSpan(o0.context.active(),Y),()=>{return J.call(this,$)});return ta(Y,Q)}}}recordOperationDuration(Z,J){let X={},$=[S8.ATTR_DB_NAMESPACE,S8.ATTR_ERROR_TYPE,S8.ATTR_SERVER_PORT,S8.ATTR_SERVER_ADDRESS,S8.ATTR_DB_OPERATION_NAME];if(this._semconvStability&v4.SemconvStability.OLD)$.push(L3.ATTR_DB_SYSTEM);if(this._semconvStability&v4.SemconvStability.STABLE)$.push(S8.ATTR_DB_SYSTEM_NAME);$.forEach((Q)=>{if(Q in Z)X[Q]=Z[Q]});let Y=(0,Tz.hrTimeToMilliseconds)((0,Tz.hrTimeDuration)(J,(0,Tz.hrTime)()))/1000;this._operationDuration.record(Y,X)}_getClientQueryPatch(){let Z=this;return(J)=>{return this._diag.debug("Patching pg.Client.prototype.query"),function(...$){if(w1.shouldSkipInstrumentation(Z.getConfig()))return J.apply(this,$);let Y=(0,Tz.hrTime)(),Q=$[0],W=typeof Q==="string",K=w1.isObjectWithTextString(Q),z=W?{text:Q,values:Array.isArray($[1])?$[1]:void 0}:K?Q:void 0,G={[L3.ATTR_DB_SYSTEM]:L3.DB_SYSTEM_VALUE_POSTGRESQL,[S8.ATTR_DB_NAMESPACE]:this.database,[S8.ATTR_SERVER_PORT]:this.connectionParameters.port,[S8.ATTR_SERVER_ADDRESS]:this.connectionParameters.host};if(z?.text)G[S8.ATTR_DB_OPERATION_NAME]=w1.parseNormalizedOperationName(z?.text);let H=()=>{Z.recordOperationDuration(G,Y)},V=Z.getConfig(),F=w1.handleConfigQuery.call(this,Z.tracer,V,Z._semconvStability,z);if(V.addSqlCommenterCommentToQueries){if(W)$[0]=(0,aa.addSqlCommenterComment)(F,Q);else if(K&&!("name"in Q))$[0]={...Q,text:(0,aa.addSqlCommenterComment)(F,Q.text)}}if($.length>0){let D=o0.trace.getSpan(o0.context.active());if(typeof $[$.length-1]==="function"){if($[$.length-1]=w1.patchCallback(V,F,$[$.length-1],G,H),D)$[$.length-1]=o0.context.bind(o0.context.active(),$[$.length-1])}else if(typeof z?.callback==="function"){let _=w1.patchCallback(Z.getConfig(),F,z.callback,G,H);if(D)_=o0.context.bind(o0.context.active(),_);$[0].callback=_}}let{requestHook:B}=V;if(typeof B==="function"&&z)(0,v4.safeExecuteInTheMiddle)(()=>{let{database:D,host:_,port:O,user:w}=this.connectionParameters;B(F,{connection:{database:D,host:_,port:O,user:w},query:{text:z.text,values:z.values,name:z.name}})},(D)=>{if(D)Z._diag.error("Error running query hook",D)},!0);let U;try{U=J.apply(this,$)}catch(D){if(D instanceof Error)F.recordException(w1.sanitizedErrorMessage(D));throw F.setStatus({code:o0.SpanStatusCode.ERROR,message:w1.getErrorMessage(D)}),F.end(),D}if(U instanceof Promise)return U.then((D)=>{return new Promise((_)=>{w1.handleExecutionResult(Z.getConfig(),F,D),H(),F.end(),_(D)})}).catch((D)=>{return new Promise((_,O)=>{if(D instanceof Error)F.recordException(w1.sanitizedErrorMessage(D));F.setStatus({code:o0.SpanStatusCode.ERROR,message:D.message}),H(),F.end(),O(D)})});return U}}}_setPoolConnectEventListeners(Z){if(Z[oa.EVENT_LISTENERS_SET])return;let J=w1.getPoolName(Z.options);Z.on("connect",()=>{this._connectionsCounter=w1.updateCounter(J,Z,this._connectionsCount,this._connectionPendingRequests,this._connectionsCounter)}),Z.on("acquire",()=>{this._connectionsCounter=w1.updateCounter(J,Z,this._connectionsCount,this._connectionPendingRequests,this._connectionsCounter)}),Z.on("remove",()=>{this._connectionsCounter=w1.updateCounter(J,Z,this._connectionsCount,this._connectionPendingRequests,this._connectionsCounter)}),Z.on("release",()=>{this._connectionsCounter=w1.updateCounter(J,Z,this._connectionsCount,this._connectionPendingRequests,this._connectionsCounter)}),Z[oa.EVENT_LISTENERS_SET]=!0}_getPoolConnectPatch(){let Z=this;return(J)=>{return function($){if(w1.shouldSkipInstrumentation(Z.getConfig()))return J.call(this,$);let Y=Z.tracer.startSpan(sa.SpanNames.POOL_CONNECT,{kind:o0.SpanKind.CLIENT,attributes:w1.getSemanticAttributesFromPoolConnection(this.options,Z._semconvStability)});if(Z._setPoolConnectEventListeners(this),$){let W=o0.trace.getSpan(o0.context.active());if($=w1.patchCallbackPGPool(Y,$),W)$=o0.context.bind(o0.context.active(),$)}let Q=o0.context.with(o0.trace.setSpan(o0.context.active(),Y),()=>{return J.call(this,$)});return ta(Y,Q)}}}}Zr.PgInstrumentation=ea;function ta(Z,J){if(!(J instanceof Promise))return J;let X=J;return o0.context.bind(o0.context.active(),X.then(($)=>{return Z.end(),$}).catch(($)=>{if($ instanceof Error)Z.recordException(w1.sanitizedErrorMessage($));return Z.setStatus({code:o0.SpanStatusCode.ERROR,message:w1.getErrorMessage($)}),Z.end(),Promise.reject($)}))}});var $r=L((qz)=>{Object.defineProperty(qz,"__esModule",{value:!0});qz.AttributeNames=qz.PgInstrumentation=void 0;var Qg0=Xr();Object.defineProperty(qz,"PgInstrumentation",{enumerable:!0,get:function(){return Qg0.PgInstrumentation}});var Wg0=p2();Object.defineProperty(qz,"AttributeNames",{enumerable:!0,get:function(){return Wg0.AttributeNames}})});var Nr=L((qr)=>{Object.defineProperty(qr,"__esModule",{value:!0});qr.PACKAGE_NAME=qr.PACKAGE_VERSION=void 0;qr.PACKAGE_VERSION="0.55.0";qr.PACKAGE_NAME="@opentelemetry/instrumentation-hapi"});var e2=L((Rr)=>{Object.defineProperty(Rr,"__esModule",{value:!0});Rr.HapiLifecycleMethodNames=Rr.HapiLayerType=Rr.handlerPatched=Rr.HapiComponentName=void 0;Rr.HapiComponentName="@hapi/hapi";Rr.handlerPatched=Symbol("hapi-handler-patched");Rr.HapiLayerType={ROUTER:"router",PLUGIN:"plugin",EXT:"server.ext"};Rr.HapiLifecycleMethodNames=new Set(["onPreAuth","onCredentials","onPostAuth","onPreHandler","onPostHandler","onPreResponse","onRequest"])});var yr=L((Er)=>{Object.defineProperty(Er,"__esModule",{value:!0});Er.ATTR_HTTP_METHOD=void 0;Er.ATTR_HTTP_METHOD="http.method"});var JD=L((Sr)=>{Object.defineProperty(Sr,"__esModule",{value:!0});Sr.AttributeNames=void 0;var Ng0;(function(Z){Z.HAPI_TYPE="hapi.type",Z.PLUGIN_NAME="hapi.plugin.name",Z.EXT_TYPE="server.ext.type"})(Ng0=Sr.AttributeNames||(Sr.AttributeNames={}))});var fr=L((vr)=>{Object.defineProperty(vr,"__esModule",{value:!0});vr.getPluginFromInput=vr.getExtMetadata=vr.getRouteMetadata=vr.isPatchableExtMethod=vr.isDirectExtInput=vr.isLifecycleExtEventObj=vr.isLifecycleExtType=vr.getPluginName=void 0;var kr=p0(),Rg0=yr(),D3=e2(),O7=JD(),xr=H0();function Pg0(Z){if(Z.name)return Z.name;else return Z.pkg.name}vr.getPluginName=Pg0;var Eg0=(Z)=>{return typeof Z==="string"&&D3.HapiLifecycleMethodNames.has(Z)};vr.isLifecycleExtType=Eg0;var Ig0=(Z)=>{let J=Z?.type;return J!==void 0&&vr.isLifecycleExtType(J)};vr.isLifecycleExtEventObj=Ig0;var yg0=(Z)=>{return Array.isArray(Z)&&Z.length<=3&&vr.isLifecycleExtType(Z[0])&&typeof Z[1]==="function"};vr.isDirectExtInput=yg0;var Sg0=(Z)=>{return!Array.isArray(Z)};vr.isPatchableExtMethod=Sg0;var kg0=(Z,J,X)=>{let $={[kr.ATTR_HTTP_ROUTE]:Z.path};if(J&xr.SemconvStability.OLD)$[Rg0.ATTR_HTTP_METHOD]=Z.method;if(J&xr.SemconvStability.STABLE)$[kr.ATTR_HTTP_REQUEST_METHOD]=Z.method;let Y;if(X)$[O7.AttributeNames.HAPI_TYPE]=D3.HapiLayerType.PLUGIN,$[O7.AttributeNames.PLUGIN_NAME]=X,Y=`${X}: route - ${Z.path}`;else $[O7.AttributeNames.HAPI_TYPE]=D3.HapiLayerType.ROUTER,Y=`route - ${Z.path}`;return{attributes:$,name:Y}};vr.getRouteMetadata=kg0;var xg0=(Z,J)=>{if(J)return{attributes:{[O7.AttributeNames.EXT_TYPE]:Z,[O7.AttributeNames.HAPI_TYPE]:D3.HapiLayerType.EXT,[O7.AttributeNames.PLUGIN_NAME]:J},name:`${J}: ext - ${Z}`};return{attributes:{[O7.AttributeNames.EXT_TYPE]:Z,[O7.AttributeNames.HAPI_TYPE]:D3.HapiLayerType.EXT},name:`ext - ${Z}`}};vr.getExtMetadata=xg0;var vg0=(Z)=>{if("plugin"in Z){if("plugin"in Z.plugin)return Z.plugin.plugin;return Z.plugin}return Z};vr.getPluginFromInput=vg0});var cr=L((dr)=>{Object.defineProperty(dr,"__esModule",{value:!0});dr.HapiInstrumentation=void 0;var C6=f(),br=H1(),_3=H0(),gr=Nr(),O3=e2(),Q9=fr();class mr extends _3.InstrumentationBase{_semconvStability;constructor(Z={}){super(gr.PACKAGE_NAME,gr.PACKAGE_VERSION,Z);this._semconvStability=(0,_3.semconvStabilityFromStr)("http",process.env.OTEL_SEMCONV_STABILITY_OPT_IN)}init(){return new _3.InstrumentationNodeModuleDefinition(O3.HapiComponentName,[">=17.0.0 <22"],(Z)=>{let J=Z[Symbol.toStringTag]==="Module"?Z.default:Z;if(!(0,_3.isWrapped)(J.server))this._wrap(J,"server",this._getServerPatch.bind(this));if(!(0,_3.isWrapped)(J.Server))this._wrap(J,"Server",this._getServerPatch.bind(this));return J},(Z)=>{let J=Z[Symbol.toStringTag]==="Module"?Z.default:Z;this._massUnwrap([J],["server","Server"])})}_getServerPatch(Z){let J=this,X=this;return function(Y){let Q=Z.apply(this,[Y]);return X._wrap(Q,"route",(W)=>{return J._getServerRoutePatch.bind(J)(W)}),X._wrap(Q,"ext",(W)=>{return J._getServerExtPatch.bind(J)(W)}),X._wrap(Q,"register",J._getServerRegisterPatch.bind(J)),Q}}_getServerRegisterPatch(Z){let J=this;return function($,Y){if(Array.isArray($))for(let Q of $){let W=(0,Q9.getPluginFromInput)(Q);J._wrapRegisterHandler(W)}else{let Q=(0,Q9.getPluginFromInput)($);J._wrapRegisterHandler(Q)}return Z.apply(this,[$,Y])}}_getServerExtPatch(Z,J){let X=this;return function(...Y){if(Array.isArray(Y[0])){let Q=Y[0];for(let W=0;W<Q.length;W++){let K=Q[W];if((0,Q9.isLifecycleExtType)(K.type)){let z=K,G=X._wrapExtMethods(z.method,K.type,J);z.method=G,Q[W]=z}}return Z.apply(this,Y)}else if((0,Q9.isDirectExtInput)(Y)){let Q=Y,W=Q[1],K=X._wrapExtMethods(W,Q[0],J);return Z.apply(this,[Q[0],K,Q[2]])}else if((0,Q9.isLifecycleExtEventObj)(Y[0])){let Q=Y[0],W=X._wrapExtMethods(Q.method,Q.type,J);return Q.method=W,Z.call(this,Q)}return Z.apply(this,Y)}}_getServerRoutePatch(Z,J){let X=this;return function($){if(Array.isArray($))for(let Y=0;Y<$.length;Y++){let Q=X._wrapRouteHandler.call(X,$[Y],J);$[Y]=Q}else $=X._wrapRouteHandler.call(X,$,J);return Z.apply(this,[$])}}_wrapRegisterHandler(Z){let J=this,X=(0,Q9.getPluginName)(Z),$=Z.register,Y=this,Q=function(W,K){return Y._wrap(W,"route",(z)=>{return J._getServerRoutePatch.bind(J)(z,X)}),Y._wrap(W,"ext",(z)=>{return J._getServerExtPatch.bind(J)(z,X)}),$.call(this,W,K)};Z.register=Q}_wrapExtMethods(Z,J,X){let $=this;if(Z instanceof Array){for(let Y=0;Y<Z.length;Y++)Z[Y]=$._wrapExtMethods(Z[Y],J);return Z}else if((0,Q9.isPatchableExtMethod)(Z)){if(Z[O3.handlerPatched]===!0)return Z;return Z[O3.handlerPatched]=!0,async function(...Q){if(C6.trace.getSpan(C6.context.active())===void 0)return await Z.apply(this,Q);let W=(0,Q9.getExtMetadata)(J,X),K=$.tracer.startSpan(W.name,{attributes:W.attributes});try{return await C6.context.with(C6.trace.setSpan(C6.context.active(),K),Z,void 0,...Q)}catch(z){throw K.recordException(z),K.setStatus({code:C6.SpanStatusCode.ERROR,message:z.message}),z}finally{K.end()}}}return Z}_wrapRouteHandler(Z,J){let X=this;if(Z[O3.handlerPatched]===!0)return Z;Z[O3.handlerPatched]=!0;let $=(Y)=>{return async function(...Q){if(C6.trace.getSpan(C6.context.active())===void 0)return await Y.call(this,...Q);let W=(0,br.getRPCMetadata)(C6.context.active());if(W?.type===br.RPCType.HTTP)W.route=Z.path;let K=(0,Q9.getRouteMetadata)(Z,X._semconvStability,J),z=X.tracer.startSpan(K.name,{attributes:K.attributes});try{return await C6.context.with(C6.trace.setSpan(C6.context.active(),z),()=>Y.call(this,...Q))}catch(G){throw z.recordException(G),z.setStatus({code:C6.SpanStatusCode.ERROR,message:G.message}),G}finally{z.end()}}};if(typeof Z.handler==="function")Z.handler=$(Z.handler);else if(typeof Z.options==="function"){let Y=Z.options;Z.options=function(Q){let W=Y(Q);if(typeof W.handler==="function")W.handler=$(W.handler);return W}}else if(typeof Z.options?.handler==="function")Z.options.handler=$(Z.options.handler);return Z}}dr.HapiInstrumentation=mr});var lr=L((Pz)=>{Object.defineProperty(Pz,"__esModule",{value:!0});Pz.AttributeNames=Pz.HapiInstrumentation=void 0;var ug0=cr();Object.defineProperty(Pz,"HapiInstrumentation",{enumerable:!0,get:function(){return ug0.HapiInstrumentation}});var cg0=JD();Object.defineProperty(Pz,"AttributeNames",{enumerable:!0,get:function(){return cg0.AttributeNames}})});var yz=L((tr)=>{Object.defineProperty(tr,"__esModule",{value:!0});tr.KoaLayerType=void 0;var rg0;(function(Z){Z.ROUTER="router",Z.MIDDLEWARE="middleware"})(rg0=tr.KoaLayerType||(tr.KoaLayerType={}))});var Js=L((er)=>{Object.defineProperty(er,"__esModule",{value:!0});er.PACKAGE_NAME=er.PACKAGE_VERSION=void 0;er.PACKAGE_VERSION="0.57.0";er.PACKAGE_NAME="@opentelemetry/instrumentation-koa"});var WD=L((Xs)=>{Object.defineProperty(Xs,"__esModule",{value:!0});Xs.AttributeNames=void 0;var tg0;(function(Z){Z.KOA_TYPE="koa.type",Z.KOA_NAME="koa.name"})(tg0=Xs.AttributeNames||(Xs.AttributeNames={}))});var Ws=L((Ys)=>{Object.defineProperty(Ys,"__esModule",{value:!0});Ys.isLayerIgnored=Ys.getMiddlewareMetadata=void 0;var $s=yz(),Sz=WD(),eg0=p0(),Zm0=(Z,J,X,$)=>{if(X)return{attributes:{[Sz.AttributeNames.KOA_NAME]:$?.toString(),[Sz.AttributeNames.KOA_TYPE]:$s.KoaLayerType.ROUTER,[eg0.ATTR_HTTP_ROUTE]:$?.toString()},name:Z._matchedRouteName||`router - ${$}`};else return{attributes:{[Sz.AttributeNames.KOA_NAME]:J.name??"middleware",[Sz.AttributeNames.KOA_TYPE]:$s.KoaLayerType.MIDDLEWARE},name:`middleware - ${J.name}`}};Ys.getMiddlewareMetadata=Zm0;var Jm0=(Z,J)=>{return!!(Array.isArray(J?.ignoreLayersType)&&J?.ignoreLayersType?.includes(Z))};Ys.isLayerIgnored=Jm0});var Gs=L((Ks)=>{Object.defineProperty(Ks,"__esModule",{value:!0});Ks.kLayerPatched=void 0;Ks.kLayerPatched=Symbol("koa-layer-patched")});var Os=L((Ds)=>{Object.defineProperty(Ds,"__esModule",{value:!0});Ds.KoaInstrumentation=void 0;var z5=f(),j3=H0(),Hs=yz(),Vs=Js(),Fs=Ws(),Bs=H1(),Us=Gs();class Ls extends j3.InstrumentationBase{constructor(Z={}){super(Vs.PACKAGE_NAME,Vs.PACKAGE_VERSION,Z)}init(){return new j3.InstrumentationNodeModuleDefinition("koa",[">=2.0.0 <4"],(Z)=>{let J=Z[Symbol.toStringTag]==="Module"?Z.default:Z;if(J==null)return J;if((0,j3.isWrapped)(J.prototype.use))this._unwrap(J.prototype,"use");return this._wrap(J.prototype,"use",this._getKoaUsePatch.bind(this)),Z},(Z)=>{let J=Z[Symbol.toStringTag]==="Module"?Z.default:Z;if((0,j3.isWrapped)(J.prototype.use))this._unwrap(J.prototype,"use")})}_getKoaUsePatch(Z){let J=this;return function($){let Y;if($.router)Y=J._patchRouterDispatch($);else Y=J._patchLayer($,!1);return Z.apply(this,[Y])}}_patchRouterDispatch(Z){z5.diag.debug("Patching @koa/router dispatch");let X=Z.router?.stack??[];for(let $ of X){let{path:Y,stack:Q}=$;for(let W=0;W<Q.length;W++){let K=Q[W];Q[W]=this._patchLayer(K,!0,Y)}}return Z}_patchLayer(Z,J,X){let $=J?Hs.KoaLayerType.ROUTER:Hs.KoaLayerType.MIDDLEWARE;if(Z[Us.kLayerPatched]===!0||(0,Fs.isLayerIgnored)($,this.getConfig()))return Z;if(Z.constructor.name==="GeneratorFunction"||Z.constructor.name==="AsyncGeneratorFunction")return z5.diag.debug("ignoring generator-based Koa middleware layer"),Z;return Z[Us.kLayerPatched]=!0,z5.diag.debug("patching Koa middleware layer"),async(Y,Q)=>{if(z5.trace.getSpan(z5.context.active())===void 0)return Z(Y,Q);let K=(0,Fs.getMiddlewareMetadata)(Y,Z,J,X),z=this.tracer.startSpan(K.name,{attributes:K.attributes}),G=(0,Bs.getRPCMetadata)(z5.context.active());if(G?.type===Bs.RPCType.HTTP&&Y._matchedRoute)G.route=Y._matchedRoute.toString();let{requestHook:H}=this.getConfig();if(H)(0,j3.safeExecuteInTheMiddle)(()=>H(z,{context:Y,middlewareLayer:Z,layerType:$}),(F)=>{if(F)z5.diag.error("koa instrumentation: request hook failed",F)},!0);let V=z5.trace.setSpan(z5.context.active(),z);return z5.context.with(V,async()=>{try{return await Z(Y,Q)}catch(F){throw z.recordException(F),F}finally{z.end()}})}}}Ds.KoaInstrumentation=Ls});var ws=L((M3)=>{Object.defineProperty(M3,"__esModule",{value:!0});M3.KoaLayerType=M3.AttributeNames=M3.KoaInstrumentation=void 0;var $m0=Os();Object.defineProperty(M3,"KoaInstrumentation",{enumerable:!0,get:function(){return $m0.KoaInstrumentation}});var Ym0=WD();Object.defineProperty(M3,"AttributeNames",{enumerable:!0,get:function(){return Ym0.AttributeNames}});var Qm0=yz();Object.defineProperty(M3,"KoaLayerType",{enumerable:!0,get:function(){return Qm0.KoaLayerType}})});var zD=L((Rs)=>{Object.defineProperty(Rs,"__esModule",{value:!0});Rs.ConnectNames=Rs.ConnectTypes=Rs.AttributeNames=void 0;var zm0;(function(Z){Z.CONNECT_TYPE="connect.type",Z.CONNECT_NAME="connect.name"})(zm0=Rs.AttributeNames||(Rs.AttributeNames={}));var Gm0;(function(Z){Z.MIDDLEWARE="middleware",Z.REQUEST_HANDLER="request_handler"})(Gm0=Rs.ConnectTypes||(Rs.ConnectTypes={}));var Hm0;(function(Z){Z.MIDDLEWARE="middleware",Z.REQUEST_HANDLER="request handler"})(Hm0=Rs.ConnectNames||(Rs.ConnectNames={}))});var Is=L((Ps)=>{Object.defineProperty(Ps,"__esModule",{value:!0});Ps.PACKAGE_NAME=Ps.PACKAGE_VERSION=void 0;Ps.PACKAGE_VERSION="0.52.0";Ps.PACKAGE_NAME="@opentelemetry/instrumentation-connect"});var ks=L((ys)=>{Object.defineProperty(ys,"__esModule",{value:!0});ys._LAYERS_STORE_PROPERTY=void 0;ys._LAYERS_STORE_PROPERTY=Symbol("opentelemetry.instrumentation-connect.request-route-stack")});var hs=L((xs)=>{Object.defineProperty(xs,"__esModule",{value:!0});xs.generateRoute=xs.replaceCurrentStackRoute=xs.addNewStackLayer=void 0;var Fm0=f(),j7=ks(),Bm0=(Z)=>{if(Array.isArray(Z[j7._LAYERS_STORE_PROPERTY])===!1)Object.defineProperty(Z,j7._LAYERS_STORE_PROPERTY,{enumerable:!1,value:[]});Z[j7._LAYERS_STORE_PROPERTY].push("/");let J=Z[j7._LAYERS_STORE_PROPERTY].length;return()=>{if(J===Z[j7._LAYERS_STORE_PROPERTY].length)Z[j7._LAYERS_STORE_PROPERTY].pop();else Fm0.diag.warn("Connect: Trying to pop the stack multiple time")}};xs.addNewStackLayer=Bm0;var Um0=(Z,J)=>{if(J)Z[j7._LAYERS_STORE_PROPERTY].splice(-1,1,J)};xs.replaceCurrentStackRoute=Um0;var Lm0=(Z)=>{return Z[j7._LAYERS_STORE_PROPERTY].reduce((J,X)=>J.replace(/\/+$/,"")+X)};xs.generateRoute=Lm0});var us=L((ms)=>{Object.defineProperty(ms,"__esModule",{value:!0});ms.ConnectInstrumentation=ms.ANONYMOUS_NAME=void 0;var Om0=f(),fs=H1(),vX=zD(),bs=Is(),kz=H0(),wm0=p0(),GD=hs();ms.ANONYMOUS_NAME="anonymous";class gs extends kz.InstrumentationBase{constructor(Z={}){super(bs.PACKAGE_NAME,bs.PACKAGE_VERSION,Z)}init(){return[new kz.InstrumentationNodeModuleDefinition("connect",[">=3.0.0 <4"],(Z)=>{return this._patchConstructor(Z)})]}_patchApp(Z){if(!(0,kz.isWrapped)(Z.use))this._wrap(Z,"use",this._patchUse.bind(this));if(!(0,kz.isWrapped)(Z.handle))this._wrap(Z,"handle",this._patchHandle.bind(this))}_patchConstructor(Z){let J=this;return function(...X){let $=Z.apply(this,X);return J._patchApp($),$}}_patchNext(Z,J){return function($){let Y=Z.apply(this,[$]);return J(),Y}}_startSpan(Z,J){let X,$,Y;if(Z)X=vX.ConnectTypes.REQUEST_HANDLER,Y=vX.ConnectNames.REQUEST_HANDLER,$=Z;else X=vX.ConnectTypes.MIDDLEWARE,Y=vX.ConnectNames.MIDDLEWARE,$=J.name||ms.ANONYMOUS_NAME;let Q=`${Y} - ${$}`,W={attributes:{[wm0.ATTR_HTTP_ROUTE]:Z.length>0?Z:"/",[vX.AttributeNames.CONNECT_TYPE]:X,[vX.AttributeNames.CONNECT_NAME]:$}};return this.tracer.startSpan(Q,W)}_patchMiddleware(Z,J){let X=this,$=J.length===4;function Y(){if(!X.isEnabled())return J.apply(this,arguments);let[Q,W,K]=$?[1,2,3]:[0,1,2],z=arguments[Q],G=arguments[W],H=arguments[K];(0,GD.replaceCurrentStackRoute)(z,Z);let V=(0,fs.getRPCMetadata)(Om0.context.active());if(Z&&V?.type===fs.RPCType.HTTP)V.route=(0,GD.generateRoute)(z);let F="";if(Z)F=`request handler - ${Z}`;else F=`middleware - ${J.name||ms.ANONYMOUS_NAME}`;let B=X._startSpan(Z,J);X._diag.debug("start span",F);let U=!1;function D(){if(!U)U=!0,X._diag.debug(`finishing span ${B.name}`),B.end();else X._diag.debug(`span ${B.name} - already finished`);G.removeListener("close",D)}return G.addListener("close",D),arguments[K]=X._patchNext(H,D),J.apply(this,arguments)}return Object.defineProperty(Y,"length",{value:J.length,writable:!1,configurable:!0}),Y}_patchUse(Z){let J=this;return function(...X){let $=X[X.length-1],Y=X[X.length-2]||"";return X[X.length-1]=J._patchMiddleware(Y,$),Z.apply(this,X)}}_patchHandle(Z){let J=this;return function(){let[X,$]=[0,2],Y=arguments[X],Q=arguments[$],W=(0,GD.addNewStackLayer)(Y);if(typeof Q==="function")arguments[$]=J._patchOut(Q,W);return Z.apply(this,arguments)}}_patchOut(Z,J){return function(...$){return J(),Reflect.apply(Z,this,$)}}}ms.ConnectInstrumentation=gs});var ls=L((vZ)=>{Object.defineProperty(vZ,"__esModule",{value:!0});vZ.ConnectTypes=vZ.ConnectNames=vZ.AttributeNames=vZ.ANONYMOUS_NAME=vZ.ConnectInstrumentation=void 0;var cs=us();Object.defineProperty(vZ,"ConnectInstrumentation",{enumerable:!0,get:function(){return cs.ConnectInstrumentation}});Object.defineProperty(vZ,"ANONYMOUS_NAME",{enumerable:!0,get:function(){return cs.ANONYMOUS_NAME}});var VD=zD();Object.defineProperty(vZ,"AttributeNames",{enumerable:!0,get:function(){return VD.AttributeNames}});Object.defineProperty(vZ,"ConnectNames",{enumerable:!0,get:function(){return VD.ConnectNames}});Object.defineProperty(vZ,"ConnectTypes",{enumerable:!0,get:function(){return VD.ConnectTypes}})});var ss=L((as)=>{Object.defineProperty(as,"__esModule",{value:!0});as.DB_SYSTEM_VALUE_MSSQL=as.ATTR_NET_PEER_PORT=as.ATTR_NET_PEER_NAME=as.ATTR_DB_USER=as.ATTR_DB_SYSTEM=as.ATTR_DB_STATEMENT=as.ATTR_DB_SQL_TABLE=as.ATTR_DB_NAME=void 0;as.ATTR_DB_NAME="db.name";as.ATTR_DB_SQL_TABLE="db.sql.table";as.ATTR_DB_STATEMENT="db.statement";as.ATTR_DB_SYSTEM="db.system";as.ATTR_DB_USER="db.user";as.ATTR_NET_PEER_NAME="net.peer.name";as.ATTR_NET_PEER_PORT="net.peer.port";as.DB_SYSTEM_VALUE_MSSQL="mssql"});var Zt=L((ts)=>{Object.defineProperty(ts,"__esModule",{value:!0});ts.once=ts.getSpanName=void 0;function Em0(Z,J,X,$){if(Z==="execBulkLoad"&&$&&J)return`${Z} ${$} ${J}`;if(Z==="callProcedure"){if(J)return`${Z} ${X} ${J}`;return`${Z} ${X}`}if(J)return`${Z} ${J}`;return`${Z}`}ts.getSpanName=Em0;var Im0=(Z)=>{let J=!1;return(...X)=>{if(J)return;return J=!0,Z(...X)}};ts.once=Im0});var $t=L((Jt)=>{Object.defineProperty(Jt,"__esModule",{value:!0});Jt.PACKAGE_NAME=Jt.PACKAGE_VERSION=void 0;Jt.PACKAGE_VERSION="0.27.0";Jt.PACKAGE_NAME="@opentelemetry/instrumentation-tedious"});var Ht=L((zt)=>{Object.defineProperty(zt,"__esModule",{value:!0});zt.TediousInstrumentation=zt.INJECTED_CTX=void 0;var hX=f(),km0=N("events"),xz=H0(),M7=ss(),Yt=Zt(),Qt=$t(),Kt=Symbol("opentelemetry.instrumentation-tedious.current-database");zt.INJECTED_CTX=Symbol("opentelemetry.instrumentation-tedious.context-info-injected");var Wt=["callProcedure","execSql","execSqlBatch","execBulkLoad","prepare","execute"];function vz(Z){Object.defineProperty(this,Kt,{value:Z,writable:!0})}class BD extends xz.InstrumentationBase{static COMPONENT="tedious";constructor(Z={}){super(Qt.PACKAGE_NAME,Qt.PACKAGE_VERSION,Z)}init(){return[new xz.InstrumentationNodeModuleDefinition(BD.COMPONENT,[">=1.11.0 <20"],(Z)=>{let J=Z.Connection.prototype;for(let X of Wt){if((0,xz.isWrapped)(J[X]))this._unwrap(J,X);this._wrap(J,X,this._patchQuery(X,Z))}if((0,xz.isWrapped)(J.connect))this._unwrap(J,"connect");return this._wrap(J,"connect",this._patchConnect),Z},(Z)=>{if(Z===void 0)return;let J=Z.Connection.prototype;for(let X of Wt)this._unwrap(J,X);this._unwrap(J,"connect")})]}_patchConnect(Z){return function(){return vz.call(this,this.config?.options?.database),this.removeListener("databaseChange",vz),this.on("databaseChange",vz),this.once("end",()=>{this.removeListener("databaseChange",vz)}),Z.apply(this,arguments)}}_buildTraceparent(Z){let J=Z.spanContext();return`00-${J.traceId}-${J.spanId}-0${Number(J.traceFlags||hX.TraceFlags.NONE).toString(16)}`}_injectContextInfo(Z,J,X){return new Promise(($)=>{try{let Q=new J.Request("set context_info @opentelemetry_traceparent",(K)=>{$()});Object.defineProperty(Q,zt.INJECTED_CTX,{value:!0});let W=Buffer.from(X,"utf8");Q.addParameter("opentelemetry_traceparent",J.TYPES.VarBinary,W,{length:W.length}),Z.execSql(Q)}catch{$()}})}_shouldInjectFor(Z){return Z==="execSql"||Z==="execSqlBatch"||Z==="callProcedure"||Z==="execute"}_patchQuery(Z,J){return(X)=>{let $=this;function Y(Q){if(Q?.[zt.INJECTED_CTX])return X.apply(this,arguments);if(!(Q instanceof km0.EventEmitter))return $._diag.warn(`Unexpected invocation of patched ${Z} method. Span not recorded`),X.apply(this,arguments);let W=0,K=0,z=()=>K++,G=()=>W++,H=this[Kt],V=((w)=>{if(w.sqlTextOrProcedure==="sp_prepare"&&w.parametersByName?.stmt?.value)return w.parametersByName.stmt.value;return w.sqlTextOrProcedure})(Q),F=$.tracer.startSpan((0,Yt.getSpanName)(Z,H,V,Q.table),{kind:hX.SpanKind.CLIENT,attributes:{[M7.ATTR_DB_SYSTEM]:M7.DB_SYSTEM_VALUE_MSSQL,[M7.ATTR_DB_NAME]:H,[M7.ATTR_NET_PEER_PORT]:this.config?.options?.port,[M7.ATTR_NET_PEER_NAME]:this.config?.server,[M7.ATTR_DB_USER]:this.config?.userName??this.config?.authentication?.options?.userName,[M7.ATTR_DB_STATEMENT]:V,[M7.ATTR_DB_SQL_TABLE]:Q.table}}),B=(0,Yt.once)((w)=>{if(Q.removeListener("done",z),Q.removeListener("doneInProc",z),Q.removeListener("doneProc",G),Q.removeListener("error",B),this.removeListener("end",B),F.setAttribute("tedious.procedure_count",W),F.setAttribute("tedious.statement_count",K),w)F.setStatus({code:hX.SpanStatusCode.ERROR,message:w.message});F.end()});if(Q.on("done",z),Q.on("doneInProc",z),Q.on("doneProc",G),Q.once("error",B),this.on("end",B),typeof Q.callback==="function")$._wrap(Q,"callback",$._patchCallbackQuery(B));else $._diag.error("Expected request.callback to be a function");let U=()=>{return hX.context.with(hX.trace.setSpan(hX.context.active(),F),X,this,...arguments)};if(!($.getConfig().enableTraceContextPropagation&&$._shouldInjectFor(Z)))return U();let O=$._buildTraceparent(F);$._injectContextInfo(this,J,O).finally(U)}return Object.defineProperty(Y,"length",{value:X.length,writable:!1}),Y}}_patchCallbackQuery(Z){return(J)=>{return function(X,$,Y){return Z(X),J.apply(this,arguments)}}}}zt.TediousInstrumentation=BD});var Vt=L((UD)=>{Object.defineProperty(UD,"__esModule",{value:!0});UD.TediousInstrumentation=void 0;var xm0=Ht();Object.defineProperty(UD,"TediousInstrumentation",{enumerable:!0,get:function(){return xm0.TediousInstrumentation}})});var Ot=L((Dt)=>{Object.defineProperty(Dt,"__esModule",{value:!0});Dt.PACKAGE_NAME=Dt.PACKAGE_VERSION=void 0;Dt.PACKAGE_VERSION="0.52.0";Dt.PACKAGE_NAME="@opentelemetry/instrumentation-generic-pool"});var Tt=L((Mt)=>{Object.defineProperty(Mt,"__esModule",{value:!0});Mt.GenericPoolInstrumentation=void 0;var fX=f(),hZ=H0(),wt=Ot(),LD="generic-pool";class jt extends hZ.InstrumentationBase{_isDisabled=!1;constructor(Z={}){super(wt.PACKAGE_NAME,wt.PACKAGE_VERSION,Z)}init(){return[new hZ.InstrumentationNodeModuleDefinition(LD,[">=3.0.0 <4"],(Z)=>{let J=Z.Pool;if((0,hZ.isWrapped)(J.prototype.acquire))this._unwrap(J.prototype,"acquire");return this._wrap(J.prototype,"acquire",this._acquirePatcher.bind(this)),Z},(Z)=>{let J=Z.Pool;return this._unwrap(J.prototype,"acquire"),Z}),new hZ.InstrumentationNodeModuleDefinition(LD,[">=2.4.0 <3"],(Z)=>{let J=Z.Pool;if((0,hZ.isWrapped)(J.prototype.acquire))this._unwrap(J.prototype,"acquire");return this._wrap(J.prototype,"acquire",this._acquireWithCallbacksPatcher.bind(this)),Z},(Z)=>{let J=Z.Pool;return this._unwrap(J.prototype,"acquire"),Z}),new hZ.InstrumentationNodeModuleDefinition(LD,[">=2.0.0 <2.4"],(Z)=>{if(this._isDisabled=!1,(0,hZ.isWrapped)(Z.Pool))this._unwrap(Z,"Pool");return this._wrap(Z,"Pool",this._poolWrapper.bind(this)),Z},(Z)=>{return this._isDisabled=!0,Z})]}_acquirePatcher(Z){let J=this;return function(...$){let Y=fX.context.active(),Q=J.tracer.startSpan("generic-pool.acquire",{},Y);return fX.context.with(fX.trace.setSpan(Y,Q),()=>{return Z.call(this,...$).then((W)=>{return Q.end(),W},(W)=>{throw Q.recordException(W),Q.end(),W})})}}_poolWrapper(Z){let J=this;return function(){let $=Z.apply(this,arguments);return J._wrap($,"acquire",J._acquireWithCallbacksPatcher.bind(J)),$}}_acquireWithCallbacksPatcher(Z){let J=this;return function($,Y){if(J._isDisabled)return Z.call(this,$,Y);let Q=fX.context.active(),W=J.tracer.startSpan("generic-pool.acquire",{},Q);return fX.context.with(fX.trace.setSpan(Q,W),()=>{Z.call(this,(K,z)=>{if(W.end(),$)return $(K,z)},Y)})}}}Mt.GenericPoolInstrumentation=jt});var qt=L((DD)=>{Object.defineProperty(DD,"__esModule",{value:!0});DD.GenericPoolInstrumentation=void 0;var gm0=Tt();Object.defineProperty(DD,"GenericPoolInstrumentation",{enumerable:!0,get:function(){return gm0.GenericPoolInstrumentation}})});var _D=L((Et)=>{Object.defineProperty(Et,"__esModule",{value:!0});Et.ATTR_NET_PEER_PORT=Et.ATTR_NET_PEER_NAME=Et.ATTR_MESSAGING_SYSTEM=Et.ATTR_MESSAGING_OPERATION=void 0;Et.ATTR_MESSAGING_OPERATION="messaging.operation";Et.ATTR_MESSAGING_SYSTEM="messaging.system";Et.ATTR_NET_PEER_NAME="net.peer.name";Et.ATTR_NET_PEER_PORT="net.peer.port"});var OD=L((yt)=>{Object.defineProperty(yt,"__esModule",{value:!0});yt.ATTR_MESSAGING_CONVERSATION_ID=yt.OLD_ATTR_MESSAGING_MESSAGE_ID=yt.MESSAGING_DESTINATION_KIND_VALUE_TOPIC=yt.ATTR_MESSAGING_URL=yt.ATTR_MESSAGING_PROTOCOL_VERSION=yt.ATTR_MESSAGING_PROTOCOL=yt.MESSAGING_OPERATION_VALUE_PROCESS=yt.ATTR_MESSAGING_RABBITMQ_ROUTING_KEY=yt.ATTR_MESSAGING_DESTINATION_KIND=yt.ATTR_MESSAGING_DESTINATION=void 0;yt.ATTR_MESSAGING_DESTINATION="messaging.destination";yt.ATTR_MESSAGING_DESTINATION_KIND="messaging.destination_kind";yt.ATTR_MESSAGING_RABBITMQ_ROUTING_KEY="messaging.rabbitmq.routing_key";yt.MESSAGING_OPERATION_VALUE_PROCESS="process";yt.ATTR_MESSAGING_PROTOCOL="messaging.protocol";yt.ATTR_MESSAGING_PROTOCOL_VERSION="messaging.protocol_version";yt.ATTR_MESSAGING_URL="messaging.url";yt.MESSAGING_DESTINATION_KIND_VALUE_TOPIC="topic";yt.OLD_ATTR_MESSAGING_MESSAGE_ID="messaging.message_id";yt.ATTR_MESSAGING_CONVERSATION_ID="messaging.conversation_id"});var wD=L((xt)=>{Object.defineProperty(xt,"__esModule",{value:!0});xt.DEFAULT_CONFIG=xt.EndOperation=void 0;var Zd0;(function(Z){Z.AutoAck="auto ack",Z.Ack="ack",Z.AckAll="ackAll",Z.Reject="reject",Z.Nack="nack",Z.NackAll="nackAll",Z.ChannelClosed="channel closed",Z.ChannelError="channel error",Z.InstrumentationTimeout="instrumentation timeout"})(Zd0=xt.EndOperation||(xt.EndOperation={}));xt.DEFAULT_CONFIG={consumeTimeoutMs:60000,useLinksForConsume:!1}});var dt=L((gt)=>{Object.defineProperty(gt,"__esModule",{value:!0});gt.isConfirmChannelTracing=gt.unmarkConfirmChannelTracing=gt.markConfirmChannelTracing=gt.getConnectionAttributesFromUrl=gt.getConnectionAttributesFromServer=gt.normalizeExchange=gt.CONNECTION_ATTRIBUTES=gt.CHANNEL_CONSUME_TIMEOUT_TIMER=gt.CHANNEL_SPANS_NOT_ENDED=gt.MESSAGE_STORED_SPAN=void 0;var jD=f(),A3=_D(),hz=OD();gt.MESSAGE_STORED_SPAN=Symbol("opentelemetry.amqplib.message.stored-span");gt.CHANNEL_SPANS_NOT_ENDED=Symbol("opentelemetry.amqplib.channel.spans-not-ended");gt.CHANNEL_CONSUME_TIMEOUT_TIMER=Symbol("opentelemetry.amqplib.channel.consumer-timeout-timer");gt.CONNECTION_ATTRIBUTES=Symbol("opentelemetry.amqplib.connection.attributes");var MD=(0,jD.createContextKey)("opentelemetry.amqplib.channel.is-confirm-channel"),Jd0=(Z)=>Z!==""?Z:"<default>";gt.normalizeExchange=Jd0;var Xd0=(Z)=>{return Z.replace(/:[^:@/]*@/,":***@")},ht=(Z,J)=>{return Z||(J==="AMQP"?5672:5671)},ft=(Z)=>{let J=Z||"amqp";return(J.endsWith(":")?J.substring(0,J.length-1):J).toUpperCase()},bt=(Z)=>{return Z||"localhost"},bX=(Z,J,X,$)=>{if(X)return{[J]:X};else return jD.diag.error(`amqplib instrumentation: could not extract connection attribute ${$} from user supplied url`,{url:Z}),{}},$d0=(Z)=>{let J=Z.serverProperties.product?.toLowerCase?.();if(J)return{[A3.ATTR_MESSAGING_SYSTEM]:J};else return{}};gt.getConnectionAttributesFromServer=$d0;var Yd0=(Z)=>{let J={[hz.ATTR_MESSAGING_PROTOCOL_VERSION]:"0.9.1"};if(Z=Z||"amqp://localhost",typeof Z==="object"){let X=Z,$=ft(X?.protocol);Object.assign(J,{...bX(Z,hz.ATTR_MESSAGING_PROTOCOL,$,"protocol")});let Y=bt(X?.hostname);Object.assign(J,{...bX(Z,A3.ATTR_NET_PEER_NAME,Y,"hostname")});let Q=ht(X.port,$);Object.assign(J,{...bX(Z,A3.ATTR_NET_PEER_PORT,Q,"port")})}else{let X=Xd0(Z);J[hz.ATTR_MESSAGING_URL]=X;try{let $=new URL(X),Y=ft($.protocol);Object.assign(J,{...bX(X,hz.ATTR_MESSAGING_PROTOCOL,Y,"protocol")});let Q=bt($.hostname);Object.assign(J,{...bX(X,A3.ATTR_NET_PEER_NAME,Q,"hostname")});let W=ht($.port?parseInt($.port):void 0,Y);Object.assign(J,{...bX(X,A3.ATTR_NET_PEER_PORT,W,"port")})}catch($){jD.diag.error("amqplib instrumentation: error while extracting connection details from connection url",{censoredUrl:X,err:$})}}return J};gt.getConnectionAttributesFromUrl=Yd0;var Qd0=(Z)=>{return Z.setValue(MD,!0)};gt.markConfirmChannelTracing=Qd0;var Wd0=(Z)=>{return Z.deleteValue(MD)};gt.unmarkConfirmChannelTracing=Wd0;var Kd0=(Z)=>{return Z.getValue(MD)===!0};gt.isConfirmChannelTracing=Kd0});var lt=L((ut)=>{Object.defineProperty(ut,"__esModule",{value:!0});ut.PACKAGE_NAME=ut.PACKAGE_VERSION=void 0;ut.PACKAGE_VERSION="0.55.0";ut.PACKAGE_NAME="@opentelemetry/instrumentation-amqplib"});var at=L((nt)=>{Object.defineProperty(nt,"__esModule",{value:!0});nt.AmqplibInstrumentation=void 0;var j1=f(),fz=H1(),c0=H0(),Od0=_D(),N6=OD(),h4=wD(),P1=dt(),pt=lt(),bz=[">=0.5.5 <1"];class it extends c0.InstrumentationBase{constructor(Z={}){super(pt.PACKAGE_NAME,pt.PACKAGE_VERSION,{...h4.DEFAULT_CONFIG,...Z})}setConfig(Z={}){super.setConfig({...h4.DEFAULT_CONFIG,...Z})}init(){let Z=new c0.InstrumentationNodeModuleFile("amqplib/lib/channel_model.js",bz,this.patchChannelModel.bind(this),this.unpatchChannelModel.bind(this)),J=new c0.InstrumentationNodeModuleFile("amqplib/lib/callback_model.js",bz,this.patchChannelModel.bind(this),this.unpatchChannelModel.bind(this)),X=new c0.InstrumentationNodeModuleFile("amqplib/lib/connect.js",bz,this.patchConnect.bind(this),this.unpatchConnect.bind(this));return new c0.InstrumentationNodeModuleDefinition("amqplib",bz,void 0,void 0,[Z,X,J])}patchConnect(Z){if(Z=this.unpatchConnect(Z),!(0,c0.isWrapped)(Z.connect))this._wrap(Z,"connect",this.getConnectPatch.bind(this));return Z}unpatchConnect(Z){if((0,c0.isWrapped)(Z.connect))this._unwrap(Z,"connect");return Z}patchChannelModel(Z,J){if(!(0,c0.isWrapped)(Z.Channel.prototype.publish))this._wrap(Z.Channel.prototype,"publish",this.getPublishPatch.bind(this,J));if(!(0,c0.isWrapped)(Z.Channel.prototype.consume))this._wrap(Z.Channel.prototype,"consume",this.getConsumePatch.bind(this,J));if(!(0,c0.isWrapped)(Z.Channel.prototype.ack))this._wrap(Z.Channel.prototype,"ack",this.getAckPatch.bind(this,!1,h4.EndOperation.Ack));if(!(0,c0.isWrapped)(Z.Channel.prototype.nack))this._wrap(Z.Channel.prototype,"nack",this.getAckPatch.bind(this,!0,h4.EndOperation.Nack));if(!(0,c0.isWrapped)(Z.Channel.prototype.reject))this._wrap(Z.Channel.prototype,"reject",this.getAckPatch.bind(this,!0,h4.EndOperation.Reject));if(!(0,c0.isWrapped)(Z.Channel.prototype.ackAll))this._wrap(Z.Channel.prototype,"ackAll",this.getAckAllPatch.bind(this,!1,h4.EndOperation.AckAll));if(!(0,c0.isWrapped)(Z.Channel.prototype.nackAll))this._wrap(Z.Channel.prototype,"nackAll",this.getAckAllPatch.bind(this,!0,h4.EndOperation.NackAll));if(!(0,c0.isWrapped)(Z.Channel.prototype.emit))this._wrap(Z.Channel.prototype,"emit",this.getChannelEmitPatch.bind(this));if(!(0,c0.isWrapped)(Z.ConfirmChannel.prototype.publish))this._wrap(Z.ConfirmChannel.prototype,"publish",this.getConfirmedPublishPatch.bind(this,J));return Z}unpatchChannelModel(Z){if((0,c0.isWrapped)(Z.Channel.prototype.publish))this._unwrap(Z.Channel.prototype,"publish");if((0,c0.isWrapped)(Z.Channel.prototype.consume))this._unwrap(Z.Channel.prototype,"consume");if((0,c0.isWrapped)(Z.Channel.prototype.ack))this._unwrap(Z.Channel.prototype,"ack");if((0,c0.isWrapped)(Z.Channel.prototype.nack))this._unwrap(Z.Channel.prototype,"nack");if((0,c0.isWrapped)(Z.Channel.prototype.reject))this._unwrap(Z.Channel.prototype,"reject");if((0,c0.isWrapped)(Z.Channel.prototype.ackAll))this._unwrap(Z.Channel.prototype,"ackAll");if((0,c0.isWrapped)(Z.Channel.prototype.nackAll))this._unwrap(Z.Channel.prototype,"nackAll");if((0,c0.isWrapped)(Z.Channel.prototype.emit))this._unwrap(Z.Channel.prototype,"emit");if((0,c0.isWrapped)(Z.ConfirmChannel.prototype.publish))this._unwrap(Z.ConfirmChannel.prototype,"publish");return Z}getConnectPatch(Z){return function(X,$,Y){return Z.call(this,X,$,function(Q,W){if(Q==null){let K=(0,P1.getConnectionAttributesFromUrl)(X),z=(0,P1.getConnectionAttributesFromServer)(W);W[P1.CONNECTION_ATTRIBUTES]={...K,...z}}Y.apply(this,arguments)})}}getChannelEmitPatch(Z){let J=this;return function($){if($==="close"){J.endAllSpansOnChannel(this,!0,h4.EndOperation.ChannelClosed,void 0);let Y=this[P1.CHANNEL_CONSUME_TIMEOUT_TIMER];if(Y)clearInterval(Y);this[P1.CHANNEL_CONSUME_TIMEOUT_TIMER]=void 0}else if($==="error")J.endAllSpansOnChannel(this,!0,h4.EndOperation.ChannelError,void 0);return Z.apply(this,arguments)}}getAckAllPatch(Z,J,X){let $=this;return function(Q){return $.endAllSpansOnChannel(this,Z,J,Q),X.apply(this,arguments)}}getAckPatch(Z,J,X){let $=this;return function(Q,W,K){let z=this,G=J===h4.EndOperation.Reject?W:K,H=z[P1.CHANNEL_SPANS_NOT_ENDED]??[],V=H.findIndex((F)=>F.msg===Q);if(V<0)$.endConsumerSpan(Q,Z,J,G);else if(J!==h4.EndOperation.Reject&&W){for(let F=0;F<=V;F++)$.endConsumerSpan(H[F].msg,Z,J,G);H.splice(0,V+1)}else $.endConsumerSpan(Q,Z,J,G),H.splice(V,1);return X.apply(this,arguments)}}getConsumePatch(Z,J){let X=this;return function(Y,Q,W){let K=this;if(!Object.prototype.hasOwnProperty.call(K,P1.CHANNEL_SPANS_NOT_ENDED)){let{consumeTimeoutMs:G}=X.getConfig();if(G){let H=setInterval(()=>{X.checkConsumeTimeoutOnChannel(K)},G);H.unref(),K[P1.CHANNEL_CONSUME_TIMEOUT_TIMER]=H}K[P1.CHANNEL_SPANS_NOT_ENDED]=[]}let z=function(G){if(!G)return Q.call(this,G);let H=G.properties.headers??{},V=j1.propagation.extract(j1.ROOT_CONTEXT,H),F=G.fields?.exchange,B;if(X._config.useLinksForConsume){let O=V?j1.trace.getSpan(V)?.spanContext():void 0;if(V=void 0,O)B=[{context:O}]}let U=X.tracer.startSpan(`${Y} process`,{kind:j1.SpanKind.CONSUMER,attributes:{...K?.connection?.[P1.CONNECTION_ATTRIBUTES],[N6.ATTR_MESSAGING_DESTINATION]:F,[N6.ATTR_MESSAGING_DESTINATION_KIND]:N6.MESSAGING_DESTINATION_KIND_VALUE_TOPIC,[N6.ATTR_MESSAGING_RABBITMQ_ROUTING_KEY]:G.fields?.routingKey,[Od0.ATTR_MESSAGING_OPERATION]:N6.MESSAGING_OPERATION_VALUE_PROCESS,[N6.OLD_ATTR_MESSAGING_MESSAGE_ID]:G?.properties.messageId,[N6.ATTR_MESSAGING_CONVERSATION_ID]:G?.properties.correlationId},links:B},V),{consumeHook:D}=X.getConfig();if(D)(0,c0.safeExecuteInTheMiddle)(()=>D(U,{moduleVersion:Z,msg:G}),(O)=>{if(O)j1.diag.error("amqplib instrumentation: consumerHook error",O)},!0);if(!W?.noAck)K[P1.CHANNEL_SPANS_NOT_ENDED].push({msg:G,timeOfConsume:(0,fz.hrTime)()}),G[P1.MESSAGE_STORED_SPAN]=U;let _=V?V:j1.ROOT_CONTEXT;if(j1.context.with(j1.trace.setSpan(_,U),()=>{Q.call(this,G)}),W?.noAck)X.callConsumeEndHook(U,G,!1,h4.EndOperation.AutoAck),U.end()};return arguments[1]=z,J.apply(this,arguments)}}getConfirmedPublishPatch(Z,J){let X=this;return function(Y,Q,W,K,z){let G=this,{span:H,modifiedOptions:V}=X.createPublishSpan(X,Y,Q,G,K),{publishHook:F}=X.getConfig();if(F)(0,c0.safeExecuteInTheMiddle)(()=>F(H,{moduleVersion:Z,exchange:Y,routingKey:Q,content:W,options:V,isConfirmChannel:!0}),(_)=>{if(_)j1.diag.error("amqplib instrumentation: publishHook error",_)},!0);let B=function(_,O){try{z?.call(this,_,O)}finally{let{publishConfirmHook:w}=X.getConfig();if(w)(0,c0.safeExecuteInTheMiddle)(()=>w(H,{moduleVersion:Z,exchange:Y,routingKey:Q,content:W,options:K,isConfirmChannel:!0,confirmError:_}),(j)=>{if(j)j1.diag.error("amqplib instrumentation: publishConfirmHook error",j)},!0);if(_)H.setStatus({code:j1.SpanStatusCode.ERROR,message:"message confirmation has been nack'ed"});H.end()}},U=(0,P1.markConfirmChannelTracing)(j1.context.active()),D=[...arguments];return D[3]=V,D[4]=j1.context.bind((0,P1.unmarkConfirmChannelTracing)(j1.trace.setSpan(U,H)),B),j1.context.with(U,J.bind(this,...D))}}getPublishPatch(Z,J){let X=this;return function(Y,Q,W,K){if((0,P1.isConfirmChannelTracing)(j1.context.active()))return J.apply(this,arguments);else{let z=this,{span:G,modifiedOptions:H}=X.createPublishSpan(X,Y,Q,z,K),{publishHook:V}=X.getConfig();if(V)(0,c0.safeExecuteInTheMiddle)(()=>V(G,{moduleVersion:Z,exchange:Y,routingKey:Q,content:W,options:H,isConfirmChannel:!1}),(U)=>{if(U)j1.diag.error("amqplib instrumentation: publishHook error",U)},!0);let F=[...arguments];F[3]=H;let B=J.apply(this,F);return G.end(),B}}}createPublishSpan(Z,J,X,$,Y){let Q=(0,P1.normalizeExchange)(J),W=Z.tracer.startSpan(`publish ${Q}`,{kind:j1.SpanKind.PRODUCER,attributes:{...$.connection[P1.CONNECTION_ATTRIBUTES],[N6.ATTR_MESSAGING_DESTINATION]:J,[N6.ATTR_MESSAGING_DESTINATION_KIND]:N6.MESSAGING_DESTINATION_KIND_VALUE_TOPIC,[N6.ATTR_MESSAGING_RABBITMQ_ROUTING_KEY]:X,[N6.OLD_ATTR_MESSAGING_MESSAGE_ID]:Y?.messageId,[N6.ATTR_MESSAGING_CONVERSATION_ID]:Y?.correlationId}}),K=Y??{};return K.headers=K.headers??{},j1.propagation.inject(j1.trace.setSpan(j1.context.active(),W),K.headers),{span:W,modifiedOptions:K}}endConsumerSpan(Z,J,X,$){let Y=Z[P1.MESSAGE_STORED_SPAN];if(!Y)return;if(J!==!1)Y.setStatus({code:j1.SpanStatusCode.ERROR,message:X!==h4.EndOperation.ChannelClosed&&X!==h4.EndOperation.ChannelError?`${X} called on message${$===!0?" with requeue":$===!1?" without requeue":""}`:X});this.callConsumeEndHook(Y,Z,J,X),Y.end(),Z[P1.MESSAGE_STORED_SPAN]=void 0}endAllSpansOnChannel(Z,J,X,$){(Z[P1.CHANNEL_SPANS_NOT_ENDED]??[]).forEach((Q)=>{this.endConsumerSpan(Q.msg,J,X,$)}),Z[P1.CHANNEL_SPANS_NOT_ENDED]=[]}callConsumeEndHook(Z,J,X,$){let{consumeEndHook:Y}=this.getConfig();if(!Y)return;(0,c0.safeExecuteInTheMiddle)(()=>Y(Z,{msg:J,rejected:X,endOperation:$}),(Q)=>{if(Q)j1.diag.error("amqplib instrumentation: consumerEndHook error",Q)},!0)}checkConsumeTimeoutOnChannel(Z){let J=(0,fz.hrTime)(),X=Z[P1.CHANNEL_SPANS_NOT_ENDED]??[],$,{consumeTimeoutMs:Y}=this.getConfig();for($=0;$<X.length;$++){let Q=X[$],W=(0,fz.hrTimeDuration)(Q.timeOfConsume,J);if((0,fz.hrTimeToMilliseconds)(W)<Y)break;this.endConsumerSpan(Q.msg,null,h4.EndOperation.InstrumentationTimeout,!0)}X.splice(0,$)}}nt.AmqplibInstrumentation=it});var st=L((T3)=>{Object.defineProperty(T3,"__esModule",{value:!0});T3.EndOperation=T3.DEFAULT_CONFIG=T3.AmqplibInstrumentation=void 0;var wd0=at();Object.defineProperty(T3,"AmqplibInstrumentation",{enumerable:!0,get:function(){return wd0.AmqplibInstrumentation}});var rt=wD();Object.defineProperty(T3,"DEFAULT_CONFIG",{enumerable:!0,get:function(){return rt.DEFAULT_CONFIG}});Object.defineProperty(T3,"EndOperation",{enumerable:!0,get:function(){return rt.EndOperation}})});class xD{isDev;constructor(Z=!1){this.isDev=Z}debug(Z,J){if(this.isDev)console.log(`[DEBUG] ${Z}`,J||"")}info(Z,J){console.log(`[INFO] ${Z}`,J||"")}warn(Z,J){console.warn(`[WARN] ${Z}`,J||"")}error(Z,J){console.error(`[ERROR] ${Z}`,J||"")}}function de(Z=!1){return I3=new xD(Z),I3}function x(){if(!I3)I3=new xD(!1);return I3}var I3=null;var ne=L((gN1,ie)=>{ie.exports=Ou0;var _u0=Object.prototype.hasOwnProperty;function Ou0(){var Z={};for(var J=0;J<arguments.length;J++){var X=arguments[J];for(var $ in X)if(_u0.call(X,$))Z[$]=X[$]}return Z}});var nz=L((mN1,oe)=>{function wu0(Z){var J=new Z,X=J;function $(){var Q=J;if(Q.next)J=Q.next;else J=new Z,X=J;return Q.next=null,Q}function Y(Q){X.next=Q,X=Q}return{get:$,release:Y}}oe.exports=wu0});var hD=L((dN1,re)=>{var ju0=ne(),ae=nz(),Mu0={released:H9,results:!0};function Au0(Z){Z=ju0(Mu0,Z);var J=Z.released,X=ae(Z.results?Cu0:Tu0),$=ae(qu0),Y=Z.results?H:F,Q=Z.results?G:V;return W;function W(B,U,D,_){var O=X.get();if(_=_||H9,U.length===0)_.call(B),J(O);else{if(O._callback=_,O._callThat=B,O._release=K,typeof U==="function")Q(B,U,D,O);else Y(B,U,D,O);if(O._count===0)O.release()}}function K(B){X.release(B),J(B)}function z(B){$.release(B)}function G(B,U,D,_){var O=null;_._count=D.length,_._results=Array(_._count);for(var w=0;w<D.length;w++)if(O=$.get(),O._release=z,O.parent=_,O.pos=w,B)U.call(B,D[w],O.release);else U(D[w],O.release)}function H(B,U,D,_){var O=null,w=H9;_._count=U.length,_._results=Array(_._count);for(var j=0;j<U.length;j++)if(O=$.get(),O._release=z,O.parent=_,O.pos=j,w=U[j],B)if(w.length===1)w.call(B,O.release);else w.call(B,D,O.release);else if(w.length===1)w(O.release);else w(D,O.release)}function V(B,U,D,_){_._count=D.length;for(var O=0;O<D.length;O++)if(B)U.call(B,D[O],_.release);else U(D[O],_.release)}function F(B,U,D,_){var O=null;_._count=U.length;for(var w=0;w<U.length;w++)if(O=U[w],B)if(O.length===1)O.call(B,_.release);else O.call(B,D,_.release);else if(O.length===1)O(_.release);else O(D,_.release)}}function Tu0(){this._count=-1,this._callback=H9,this._callThat=null,this._release=null,this.next=null;var Z=this,J=0;this.release=function(){var X=Z._callback;if(++J===Z._count||Z._count===0){if(Z._callThat)X.call(Z._callThat);else X();Z._callback=H9,Z._callThat=null,J=0,Z._release(Z)}}}function qu0(){this.pos=-1,this._release=H9,this.parent=null,this.next=null;var Z=this;this.release=function(J,X){Z.parent.release(J,Z.pos,X),Z.pos=-1,Z.parent=null,Z._release(Z)}}function Cu0(){this._count=-1,this._callback=H9,this._results=null,this._err=null,this._callThat=null,this._release=H9,this.next=null;var Z=this,J=0;this.release=function(X,$,Y){if(Z._err=Z._err||X,$>=0)Z._results[$]=Y;var Q=Z._callback;if(++J===Z._count||Z._count===0){if(Z._callThat)Q.call(Z._callThat,Z._err,Z._results);else Q(Z._err,Z._results);Z._callback=H9,Z._results=null,Z._err=null,Z._callThat=null,J=0,Z._release(Z)}}}function H9(){}re.exports=Au0});var ee=L((uN1,te)=>{var Nu0={results:!0};function Ru0(Z){Z=Object.assign({},Nu0,Z);var J,X;if(Z.results)J=Iu0,X=yu0;else J=Pu0,X=Eu0;return $;function $(Y,Q,W,K){if(K=(K||Su0).bind(Y),Q.length===0)K.call(Y);else if(Q.bind){if(Y)Q=Q.bind(Y);J(Q,W,K)}else{var z;if(Y){var G=Q.length;z=Array(G);for(var H=0;H<G;H++)z[H]=Q[H].bind(Y)}else z=Q;X(z,W,K)}}}function Pu0(Z,J,X){var $=0,Y=J.length;Q();function Q(){if($<Y)oz(Z,J[$++],Q);else X()}}function Eu0(Z,J,X){var $=0,Y=Z.length,Q;if(Z[0].length===1)Q=se;else Q=oz;W();function W(){if($<Y)Q(Z[$++],J,W);else X()}}function Iu0(Z,J,X){var $=0,Y=J.length,Q=Array(Y);W(null,null);function W(K,z){if(K){X(K);return}if($>0)Q[$-1]=z;if($<Y)oz(Z,J[$++],W);else X(null,Q)}}function yu0(Z,J,X){var $=0,Y=Z.length,Q;if(Z[0].length===1)Q=se;else Q=oz;var W=Array(Y);K(null,null);function K(z,G){if(z){X(z);return}if($>0)W[$-1]=G;if($<Y)Q(Z[$++],J,K);else X(null,W)}}function se(Z,J,X){Z(X)}function oz(Z,J,X){Z(J,X)}function Su0(){}te.exports=Ru0});var X00=L((Z00)=>{Object.defineProperty(Z00,"__esModule",{value:!0});Z00.default=void 0;var cN1=Z00.default="ffffffff-ffff-ffff-ffff-ffffffffffff"});var Q00=L(($00)=>{Object.defineProperty($00,"__esModule",{value:!0});$00.default=void 0;var pN1=$00.default="00000000-0000-0000-0000-000000000000"});var z00=L((W00)=>{Object.defineProperty(W00,"__esModule",{value:!0});W00.default=void 0;var nN1=W00.default=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i});var y3=L((G00)=>{Object.defineProperty(G00,"__esModule",{value:!0});G00.default=void 0;var ku0=xu0(z00());function xu0(Z){return Z&&Z.__esModule?Z:{default:Z}}function vu0(Z){return typeof Z==="string"&&ku0.default.test(Z)}var aN1=G00.default=vu0});var S3=L((V00)=>{Object.defineProperty(V00,"__esModule",{value:!0});V00.default=void 0;var hu0=fu0(y3());function fu0(Z){return Z&&Z.__esModule?Z:{default:Z}}function bu0(Z){if(!(0,hu0.default)(Z))throw TypeError("Invalid UUID");let J,X=new Uint8Array(16);return X[0]=(J=parseInt(Z.slice(0,8),16))>>>24,X[1]=J>>>16&255,X[2]=J>>>8&255,X[3]=J&255,X[4]=(J=parseInt(Z.slice(9,13),16))>>>8,X[5]=J&255,X[6]=(J=parseInt(Z.slice(14,18),16))>>>8,X[7]=J&255,X[8]=(J=parseInt(Z.slice(19,23),16))>>>8,X[9]=J&255,X[10]=(J=parseInt(Z.slice(24,36),16))/1099511627776&255,X[11]=J/4294967296&255,X[12]=J>>>24&255,X[13]=J>>>16&255,X[14]=J>>>8&255,X[15]=J&255,X}var sN1=V00.default=bu0});var V9=L((U00)=>{Object.defineProperty(U00,"__esModule",{value:!0});U00.default=void 0;U00.unsafeStringify=B00;var gu0=mu0(y3());function mu0(Z){return Z&&Z.__esModule?Z:{default:Z}}var B4=[];for(let Z=0;Z<256;++Z)B4.push((Z+256).toString(16).slice(1));function B00(Z,J=0){return(B4[Z[J+0]]+B4[Z[J+1]]+B4[Z[J+2]]+B4[Z[J+3]]+"-"+B4[Z[J+4]]+B4[Z[J+5]]+"-"+B4[Z[J+6]]+B4[Z[J+7]]+"-"+B4[Z[J+8]]+B4[Z[J+9]]+"-"+B4[Z[J+10]]+B4[Z[J+11]]+B4[Z[J+12]]+B4[Z[J+13]]+B4[Z[J+14]]+B4[Z[J+15]]).toLowerCase()}function du0(Z,J=0){let X=B00(Z,J);if(!(0,gu0.default)(X))throw TypeError("Stringified UUID is invalid");return X}var eN1=U00.default=du0});var sz=L((D00)=>{Object.defineProperty(D00,"__esModule",{value:!0});D00.default=pu0;var cu0=lu0(N("crypto"));function lu0(Z){return Z&&Z.__esModule?Z:{default:Z}}var rz=new Uint8Array(256),az=rz.length;function pu0(){if(az>rz.length-16)cu0.default.randomFillSync(rz),az=0;return rz.slice(az,az+=16)}});var mD=L((_00)=>{Object.defineProperty(_00,"__esModule",{value:!0});_00.default=void 0;var nu0=au0(sz()),ou0=V9();function au0(Z){return Z&&Z.__esModule?Z:{default:Z}}var fD,tz,bD=0,gD=0;function ru0(Z,J,X){let $=J&&X||0,Y=J||Array(16);Z=Z||{};let{node:Q,clockseq:W}=Z;if(!Z._v6){if(!Q)Q=fD;if(W==null)W=tz}if(Q==null||W==null){let F=Z.random||(Z.rng||nu0.default)();if(Q==null){if(Q=[F[0],F[1],F[2],F[3],F[4],F[5]],!fD&&!Z._v6)Q[0]|=1,fD=Q}if(W==null){if(W=(F[6]<<8|F[7])&16383,tz===void 0&&!Z._v6)tz=W}}let K=Z.msecs!==void 0?Z.msecs:Date.now(),z=Z.nsecs!==void 0?Z.nsecs:gD+1,G=K-bD+(z-gD)/1e4;if(G<0&&Z.clockseq===void 0)W=W+1&16383;if((G<0||K>bD)&&Z.nsecs===void 0)z=0;if(z>=1e4)throw Error("uuid.v1(): Can't create more than 10M uuids/sec");bD=K,gD=z,tz=W,K+=12219292800000;let H=((K&268435455)*1e4+z)%4294967296;Y[$++]=H>>>24&255,Y[$++]=H>>>16&255,Y[$++]=H>>>8&255,Y[$++]=H&255;let V=K/4294967296*1e4&268435455;Y[$++]=V>>>8&255,Y[$++]=V&255,Y[$++]=V>>>24&15|16,Y[$++]=V>>>16&255,Y[$++]=W>>>8|128,Y[$++]=W&255;for(let F=0;F<6;++F)Y[$+F]=Q[F];return J||(0,ou0.unsafeStringify)(Y)}var XR1=_00.default=ru0});var dD=L((w00)=>{Object.defineProperty(w00,"__esModule",{value:!0});w00.default=Zc0;var su0=eu0(S3()),tu0=V9();function eu0(Z){return Z&&Z.__esModule?Z:{default:Z}}function Zc0(Z){let J=typeof Z==="string"?(0,su0.default)(Z):Z,X=Jc0(J);return typeof Z==="string"?(0,tu0.unsafeStringify)(X):X}function Jc0(Z,J=!1){return Uint8Array.of((Z[6]&15)<<4|Z[7]>>4&15,(Z[7]&15)<<4|(Z[4]&240)>>4,(Z[4]&15)<<4|(Z[5]&240)>>4,(Z[5]&15)<<4|(Z[0]&240)>>4,(Z[0]&15)<<4|(Z[1]&240)>>4,(Z[1]&15)<<4|(Z[2]&240)>>4,96|Z[2]&15,Z[3],Z[8],Z[9],Z[10],Z[11],Z[12],Z[13],Z[14],Z[15])}});var uD=L((j00)=>{Object.defineProperty(j00,"__esModule",{value:!0});j00.URL=j00.DNS=void 0;j00.default=Gc0;var $c0=V9(),Yc0=Qc0(S3());function Qc0(Z){return Z&&Z.__esModule?Z:{default:Z}}function Wc0(Z){Z=unescape(encodeURIComponent(Z));let J=[];for(let X=0;X<Z.length;++X)J.push(Z.charCodeAt(X));return J}var Kc0=j00.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",zc0=j00.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Gc0(Z,J,X){function $(Y,Q,W,K){var z;if(typeof Y==="string")Y=Wc0(Y);if(typeof Q==="string")Q=(0,Yc0.default)(Q);if(((z=Q)===null||z===void 0?void 0:z.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let G=new Uint8Array(16+Y.length);if(G.set(Q),G.set(Y,Q.length),G=X(G),G[6]=G[6]&15|J,G[8]=G[8]&63|128,W){K=K||0;for(let H=0;H<16;++H)W[K+H]=G[H];return W}return(0,$c0.unsafeStringify)(G)}try{$.name=Z}catch(Y){}return $.DNS=Kc0,$.URL=zc0,$}});var q00=L((A00)=>{Object.defineProperty(A00,"__esModule",{value:!0});A00.default=void 0;var Fc0=Bc0(N("crypto"));function Bc0(Z){return Z&&Z.__esModule?Z:{default:Z}}function Uc0(Z){if(Array.isArray(Z))Z=Buffer.from(Z);else if(typeof Z==="string")Z=Buffer.from(Z,"utf8");return Fc0.default.createHash("md5").update(Z).digest()}var WR1=A00.default=Uc0});var P00=L((N00)=>{Object.defineProperty(N00,"__esModule",{value:!0});N00.default=void 0;var Lc0=C00(uD()),Dc0=C00(q00());function C00(Z){return Z&&Z.__esModule?Z:{default:Z}}var _c0=(0,Lc0.default)("v3",48,Dc0.default),zR1=N00.default=_c0});var y00=L((E00)=>{Object.defineProperty(E00,"__esModule",{value:!0});E00.default=void 0;var Oc0=wc0(N("crypto"));function wc0(Z){return Z&&Z.__esModule?Z:{default:Z}}var HR1=E00.default={randomUUID:Oc0.default.randomUUID}});var h00=L((x00)=>{Object.defineProperty(x00,"__esModule",{value:!0});x00.default=void 0;var S00=k00(y00()),jc0=k00(sz()),Mc0=V9();function k00(Z){return Z&&Z.__esModule?Z:{default:Z}}function Ac0(Z,J,X){if(S00.default.randomUUID&&!J&&!Z)return S00.default.randomUUID();Z=Z||{};let $=Z.random||(Z.rng||jc0.default)();if($[6]=$[6]&15|64,$[8]=$[8]&63|128,J){X=X||0;for(let Y=0;Y<16;++Y)J[X+Y]=$[Y];return J}return(0,Mc0.unsafeStringify)($)}var FR1=x00.default=Ac0});var g00=L((f00)=>{Object.defineProperty(f00,"__esModule",{value:!0});f00.default=void 0;var Tc0=qc0(N("crypto"));function qc0(Z){return Z&&Z.__esModule?Z:{default:Z}}function Cc0(Z){if(Array.isArray(Z))Z=Buffer.from(Z);else if(typeof Z==="string")Z=Buffer.from(Z,"utf8");return Tc0.default.createHash("sha1").update(Z).digest()}var UR1=f00.default=Cc0});var c00=L((d00)=>{Object.defineProperty(d00,"__esModule",{value:!0});d00.default=void 0;var Nc0=m00(uD()),Rc0=m00(g00());function m00(Z){return Z&&Z.__esModule?Z:{default:Z}}var Pc0=(0,Nc0.default)("v5",80,Rc0.default),DR1=d00.default=Pc0});var i00=L((p00)=>{Object.defineProperty(p00,"__esModule",{value:!0});p00.default=Sc0;var Ec0=V9(),Ic0=l00(mD()),yc0=l00(dD());function l00(Z){return Z&&Z.__esModule?Z:{default:Z}}function Sc0(Z={},J,X=0){let $=(0,Ic0.default)({...Z,_v6:!0},new Uint8Array(16));if($=(0,yc0.default)($),J){for(let Y=0;Y<16;Y++)J[X+Y]=$[Y];return J}return(0,Ec0.unsafeStringify)($)}});var o00=L((n00)=>{Object.defineProperty(n00,"__esModule",{value:!0});n00.default=fc0;var xc0=hc0(S3()),vc0=V9();function hc0(Z){return Z&&Z.__esModule?Z:{default:Z}}function fc0(Z){let J=typeof Z==="string"?(0,xc0.default)(Z):Z,X=bc0(J);return typeof Z==="string"?(0,vc0.unsafeStringify)(X):X}function bc0(Z){return Uint8Array.of((Z[3]&15)<<4|Z[4]>>4&15,(Z[4]&15)<<4|(Z[5]&240)>>4,(Z[5]&15)<<4|Z[6]&15,Z[7],(Z[1]&15)<<4|(Z[2]&240)>>4,(Z[2]&15)<<4|(Z[3]&240)>>4,16|(Z[0]&240)>>4,(Z[0]&15)<<4|(Z[1]&240)>>4,Z[8],Z[9],Z[10],Z[11],Z[12],Z[13],Z[14],Z[15])}});var e00=L((s00)=>{Object.defineProperty(s00,"__esModule",{value:!0});s00.default=void 0;var mc0=uc0(sz()),dc0=V9();function uc0(Z){return Z&&Z.__esModule?Z:{default:Z}}var a00=null,r00=null,k8=0;function cc0(Z,J,X){Z=Z||{};let $=J&&X||0,Y=J||new Uint8Array(16),Q=Z.random||(Z.rng||mc0.default)(),W=Z.msecs!==void 0?Z.msecs:Date.now(),K=Z.seq!==void 0?Z.seq:null,z=r00,G=a00;if(W>k8&&Z.msecs===void 0){if(k8=W,K!==null)z=null,G=null}if(K!==null){if(K>2147483647)K=2147483647;z=K>>>19&4095,G=K&524287}if(z===null||G===null)z=Q[6]&127,z=z<<8|Q[7],G=Q[8]&63,G=G<<8|Q[9],G=G<<5|Q[10]>>>3;if(W+1e4>k8&&K===null){if(++G>524287){if(G=0,++z>4095)z=0,k8++}}else k8=W;return r00=z,a00=G,Y[$++]=k8/1099511627776&255,Y[$++]=k8/4294967296&255,Y[$++]=k8/16777216&255,Y[$++]=k8/65536&255,Y[$++]=k8/256&255,Y[$++]=k8&255,Y[$++]=z>>>4&15|112,Y[$++]=z&255,Y[$++]=G>>>13&63|128,Y[$++]=G>>>5&255,Y[$++]=G<<3&255|Q[10]&7,Y[$++]=Q[11],Y[$++]=Q[12],Y[$++]=Q[13],Y[$++]=Q[14],Y[$++]=Q[15],J||(0,dc0.unsafeStringify)(Y)}var jR1=s00.default=cc0});var X10=L((Z10)=>{Object.defineProperty(Z10,"__esModule",{value:!0});Z10.default=void 0;var lc0=pc0(y3());function pc0(Z){return Z&&Z.__esModule?Z:{default:Z}}function ic0(Z){if(!(0,lc0.default)(Z))throw TypeError("Invalid UUID");return parseInt(Z.slice(14,15),16)}var AR1=Z10.default=ic0});var $10=L((A4)=>{Object.defineProperty(A4,"__esModule",{value:!0});Object.defineProperty(A4,"MAX",{enumerable:!0,get:function(){return nc0.default}});Object.defineProperty(A4,"NIL",{enumerable:!0,get:function(){return oc0.default}});Object.defineProperty(A4,"parse",{enumerable:!0,get:function(){return ac0.default}});Object.defineProperty(A4,"stringify",{enumerable:!0,get:function(){return rc0.default}});Object.defineProperty(A4,"v1",{enumerable:!0,get:function(){return sc0.default}});Object.defineProperty(A4,"v1ToV6",{enumerable:!0,get:function(){return tc0.default}});Object.defineProperty(A4,"v3",{enumerable:!0,get:function(){return ec0.default}});Object.defineProperty(A4,"v4",{enumerable:!0,get:function(){return Zl0.default}});Object.defineProperty(A4,"v5",{enumerable:!0,get:function(){return Jl0.default}});Object.defineProperty(A4,"v6",{enumerable:!0,get:function(){return Xl0.default}});Object.defineProperty(A4,"v6ToV1",{enumerable:!0,get:function(){return $l0.default}});Object.defineProperty(A4,"v7",{enumerable:!0,get:function(){return Yl0.default}});Object.defineProperty(A4,"validate",{enumerable:!0,get:function(){return Ql0.default}});Object.defineProperty(A4,"version",{enumerable:!0,get:function(){return Wl0.default}});var nc0=W6(X00()),oc0=W6(Q00()),ac0=W6(S3()),rc0=W6(V9()),sc0=W6(mD()),tc0=W6(dD()),ec0=W6(P00()),Zl0=W6(h00()),Jl0=W6(c00()),Xl0=W6(i00()),$l0=W6(o00()),Yl0=W6(e00()),Ql0=W6(y3()),Wl0=W6(X10());function W6(Z){return Z&&Z.__esModule?Z:{default:Z}}});var lX=L((CR1,Y10)=>{function Kl0(Z,J){if(Object.prototype.hasOwnProperty.call(Z,"clientId"))this.clientId=Z.clientId;if(Object.prototype.hasOwnProperty.call(Z,"nl"))this.nl=Z.nl;if(this.cmd=Z.cmd||"publish",this.brokerId=Z.brokerId||J&&J.id,this.brokerCounter=Z.brokerCounter||(J?++J.counter:0),this.topic=Z.topic,this.payload=Z.payload||Buffer.alloc(0),this.qos=Z.qos||0,this.retain=Z.retain||!1,this.dup=Z.dup||!1,this.qos>0||this.cmd!=="publish")this.messageId=void 0}Y10.exports=Kl0});var cD=L((NR1,Q10)=>{var x8=N("util");Q10.exports=function(Z,J){class X extends Z{constructor($){super($);this.addP=x8.promisify(this.add_async),this.removeP=x8.promisify(this.remove_async),this.matchP=x8.promisify(this.match_async),this.testP=x8.promisify(this.test_async),this.clearP=x8.promisify(this.clear_async),this._get_visitorP=x8.promisify(this.get_visitor_async),this._visit_nextP=x8.promisify(this.visit_next_async),this._get_restorerP=x8.promisify(this.get_restorer_async),this._restore_nextP=x8.promisify(this.restore_next_async),this._match_iterP=x8.promisify(this.match_iter_async),this._match_nextP=x8.promisify(this.match_next_async)}*visit(){let $=this.get_visitor();while(!0){let Y=this.visit_next($);if(Y===void 0)break;yield Y}}async*visitP(){let $=await this._get_visitorP();while(!0){let Y=await this._visit_nextP($);if(Y===void 0)break;yield Y}}*match_iter($,Y){let Q=super.match_iter($,Y);while(!0){let W=this.match_next(Q);if(W===void 0)break;yield W.value}}async*match_iterP($,Y){let Q=await this._match_iterP($,Y);while(!0){let W=await this._match_nextP(Q);if(W===void 0)break;yield W.value}}get_trie(){let $=new J(this.options),Y=$.get_restorer();for(let Q of this.visit())Y(Q);return $.get_trie()}get_restorer($){let Y=super.get_restorer($);return(Q)=>{super.restore_next(Y,Q)}}async get_restorerP($){let Y=await this._get_restorerP($);return async(Q)=>{await this._restore_nextP(Y,Q)}}}return X.is_native=!0,X.nonNative=J,X}});var iD=L((K10)=>{var ez=N("util");function x0(Z){if(Z=Z||{},this._separator=Z.separator||".",this._wildcard_one=Z.wildcard_one||"*",this._wildcard_some=Z.wildcard_some||"#",this._max_words=Z.max_words||100,this._max_wildcard_somes=Z.max_wildcard_somes||3,this._match_empty_levels=Z.match_empty_levels,this._trie=new Map,Z.cache_adds instanceof Map)this._shortcuts=Z.cache_adds;else if(Z.cache_adds)this._shortcuts=new Map;if(Z.cache_splits>0)this._cache_splits=Z.cache_splits,this._split_cache=new Map}x0.prototype._initial_value=function(Z){return[Z]};x0.prototype._add_value=function(Z,J){Z[Z.length]=J};x0.prototype._add_values=function(Z,J){var X,$=Z.length,Y=J.length;for(X=0;X<Y;X+=1)Z[$+X]=J[X]};x0.prototype._iter_values=function(Z,J){return Z[Symbol.iterator](J)};x0.prototype._remove_value=function(Z,J){if(J===void 0)return!0;var X=Z.lastIndexOf(J);if(X>=0)Z.splice(X,1);return Z.length===0};x0.prototype._add=function(Z,J,X,$){var Y,Q;if(J===X.length){if(Y=$.get(this._separator),Y)this._add_value(Y,Z);else Y=this._initial_value(Z),$.set(this._separator,Y);return Y}if(Q=X[J],Y=$.get(Q),!Y)Y=new Map,$.set(Q,Y);return this._add(Z,J+1,X,Y)};x0.prototype._remove=function(Z,J,X,$){var Y,Q,W;if(J===X.length){if(Y=$.get(this._separator),Y&&this._remove_value(Y,Z))return $.delete(this._separator),!0;return!1}if(Q=X[J],Y=$.get(Q),!Y)return!1;if(W=this._remove(Z,J+1,X,Y),Y.size===0)$.delete(Q);return W};x0.prototype._match_some=function(Z,J,X,$,Y){var Q,W;for(W of $.keys())if(W!==this._separator){for(Q=J;Q<X.length;Q+=1)Z=this._match(Z,Q,X,$,Y);break}return Z};x0.prototype._match=function(Z,J,X,$,Y){var Q,W;if(W=$.get(this._wildcard_some),W)Z=this._match_some(Z,J,X,W,Y),Z=this._match(Z,X.length,X,W,Y);if(J===X.length){if(W=$.get(this._separator),W)if(Z.dest)this._add_values(Z.dest,Z.source,Y),this._add_values(Z.dest,W,Y),Z=Z.dest;else if(Z.source)Z.dest=Z.source,Z.source=W;else this._add_values(Z,W,Y)}else{if(Q=X[J],Q!==this._wildcard_one&&Q!==this._wildcard_some){if(W=$.get(Q),W)Z=this._match(Z,J+1,X,W,Y)}if(Q||this._match_empty_levels){if(W=$.get(this._wildcard_one),W)Z=this._match(Z,J+1,X,W,Y)}}return Z};x0.prototype._match2=function(Z,J,X){var $=this._match({source:Z},0,this._split(J,!1),this._trie,X);return $.source||$};x0.prototype._test_some=function(Z,J,X,$){var Y,Q;for(Q of $.keys())if(Q!==this._separator){for(Y=J;Y<X.length;Y+=1)if(this._test(Z,Y,X,$))return!0;break}return!1};x0.prototype._test=function(Z,J,X,$){var Y,Q;if(Q=$.get(this._wildcard_some),Q){if(this._test_some(Z,J,X,Q)||this._test(Z,X.length,X,Q))return!0}if(J===X.length){if(Q=$.get(this._separator),Q&&this.test_values(Q,Z))return!0}else{if(Y=X[J],Y!==this._wildcard_one&&Y!==this._wildcard_some){if(Q=$.get(Y),Q&&this._test(Z,J+1,X,Q))return!0}if(Y||this._match_empty_levels){if(Q=$.get(this._wildcard_one),Q&&this._test(Z,J+1,X,Q))return!0}}return!1};x0.prototype._match_some_iter=function*(Z,J,X,$){var Y,Q;for(Q of X.keys())if(Q!==this._separator){for(Y=Z;Y<J.length;Y+=1)yield*this._match_iter(Y,J,X,$);break}};x0.prototype._match_iter=function*(Z,J,X,$){var Y,Q;if(Q=X.get(this._wildcard_some),Q)yield*this._match_some_iter(Z,J,Q,$),yield*this._match_iter(J.length,J,Q,$);if(Z===J.length){if(Q=X.get(this._separator),Q)yield*this._iter_values(Q,$)}else{if(Y=J[Z],Y!==this._wildcard_one&&Y!==this._wildcard_some){if(Q=X.get(Y),Q)yield*this._match_iter(Z+1,J,Q,$)}if(Y||this._match_empty_levels){if(Q=X.get(this._wildcard_one),Q)yield*this._match_iter(Z+1,J,Q,$)}}};x0.prototype._split_words=function(Z){let J=Z.split(this._separator);if(J.length>this._max_words)throw Error("too many words");return J};x0.prototype._split=function(Z,J){let X;if(this._split_cache){if(X=this._split_cache.get(Z),X===void 0){if(X=this._split_words(Z),this._split_cache.set(Z,X),this._split_cache.size>this._cache_splits)for(let $ of this._split_cache.keys()){this._split_cache.delete($);break}}}else X=this._split_words(Z);if(J&&X.reduce(($,Y)=>$+(Y===this._wildcard_some),0)>this._max_wildcard_somes)throw Error("too many wildcard somes");return X};x0.prototype.add=function(Z,J){var X=this._shortcuts&&this._shortcuts.get(Z);if(X)this._add_value(X,J);else if(X=this._add(J,0,this._split(Z,!0),this._trie),this._shortcuts)this._shortcuts.set(Z,X);return this};x0.prototype.remove=function(Z,J){if(this._remove(J,0,this._split(Z,!1),this._trie)&&this._shortcuts)this._shortcuts.delete(Z);return this};x0.prototype.match=function(Z,J){return this._match2([],Z,J)};x0.prototype.match_iter=function(Z,J){return this._match_iter(0,this._split(Z,!1),this._trie,J)};x0.prototype.test=function(Z,J){return this._test(J,0,this._split(Z,!1),this._trie)};x0.prototype.test_values=function(Z,J){return Z.indexOf(J)>=0};x0.prototype.clear=function(){if(this._trie.clear(),this._shortcuts)this._shortcuts.clear();if(this._split_cache)this._split_cache.clear();return this};x0.prototype.get_trie=function(){return this._trie};x0.prototype.visit=function*(){let Z=[],J=this._trie.entries(),X=0;while(!0){if(X===0)yield{type:"start_entries"};let $=J.next();if($.done){yield{type:"end_entries"};let W=Z.pop();if(W===void 0)return;[J,X]=W;continue}let[Y,Q]=$.value;if(yield{type:"entry",key:Y},++X,Y===this._separator){if(yield{type:"start_values"},Q[Symbol.iterator])for(let W of Q)yield{type:"value",value:W};else yield{type:"value",value:Q};yield{type:"end_values"};continue}Z.push([J,X]),J=Q.entries(),X=0}};x0.prototype.get_restorer=function(Z){Z=Z||{};let J=[],X=this._trie,$="";return(Y)=>{switch(Y.type){case"entry":if(X=X||new Map,J.push([X,Y.key,$]),X=X.get(Y.key),Z.cache_adds){if($)$+=this._separator;$+=Y.key}break;case"value":if(X)this._add_value(X,Y.value);else X=this._initial_value(Y.value);break;case"end_entries":if(X&&X.size===0)X=void 0;case"end_values":let Q=J.pop();if(Q===void 0)X=void 0,$="";else{let[W,K,z]=Q;if(X){if(Z.cache_adds&&this._shortcuts&&Y.type==="end_values")this._shortcuts.set(z,X);W.set(K,X)}X=W,$=z}break}}};function t6(Z){x0.call(this,Z)}ez.inherits(t6,x0);t6.prototype._initial_value=function(Z){return new Set().add(Z)};t6.prototype._add_value=function(Z,J){Z.add(J)};t6.prototype._add_values=function(Z,J){J.forEach(function(X){Z.add(X)})};t6.prototype._remove_value=function(Z,J){if(J===void 0)return!0;return Z.delete(J),Z.size===0};t6.prototype.test_values=function(Z,J){return Z.has(J)};t6.prototype.match=function(Z,J){return this._match2(new Set,Z,J)};function H5(Z){x0.call(this,Z)}ez.inherits(H5,x0);H5.prototype._initial_value=function(){return!0};H5.prototype._add_value=function(){};H5.prototype._remove_value=function(){return!0};H5.prototype._iter_values=function*(){yield!0};H5.prototype.test_values=function(){return!0};H5.prototype.match=function(Z,J){return this.test(Z,J)};var ZG=N("stream");function lD(Z){ZG.Readable.call(this,{objectMode:!0}),this._iterator=Z.visit()}ez.inherits(lD,ZG.Readable);lD.prototype._read=function(){while(!0){let{done:Z,value:J}=this._iterator.next();if(Z){this.push(null);break}if(!this.push(J))break}};function pD(Z){ZG.Writable.call(this,{objectMode:!0}),this._restorer=Z.get_restorer()}ez.inherits(pD,ZG.Writable);pD.prototype._write=function(Z,J,X){this._restorer(Z),X()};var W10=null;function zl0(Z){if(Z!==W10){let J=cD();x0.nativeString=J(Z.QlobberString,x0),x0.nativeNumber=J(Z.QlobberNumber,x0),t6.nativeString=J(Z.QlobberDedupString,t6),t6.nativeNumber=J(Z.QlobberDedupNumber,t6),H5.native=J(Z.QlobberTrue,H5),W10=Z}return K10}K10.Qlobber=x0;K10.QlobberDedup=t6;K10.QlobberTrue=H5;K10.VisitorStream=lD;K10.RestorerStream=pD;K10.set_native=zl0});var z10=L((PR1,oD)=>{var Ll0=N("util"),Dl0=iD(),nD=Dl0.Qlobber;function e6(Z){nD.call(this,Z),this.subscriptionsCount=0}Ll0.inherits(e6,nD);e6.prototype._initial_value=function(Z){this.subscriptionsCount+=1;let J={topic:Z.topic,clientMap:new Map().set(Z.clientId,{qos:Z.qos,rh:Z.rh,rap:Z.rap,nl:Z.nl})};return J[Symbol.iterator]=function*(X){if(X===void 0)for(let[$,Y]of J.clientMap)yield{topic:J.topic,clientId:$,...Y};else if(J.topic===X)for(let[$,Y]of J.clientMap)yield{clientId:$,...Y}},J};e6.prototype._add_value=function(Z,J){var X=Z.clientMap,$=X.size;if(X.set(J.clientId,{qos:J.qos,rh:J.rh,rap:J.rap,nl:J.nl}),X.size>$)this.subscriptionsCount+=1};e6.prototype._add_values=function(Z,J,X){if(X===void 0)for(let[$,Y]of J.clientMap)Z.push({clientId:$,topic:J.topic,...Y});else if(J.topic===X)for(let[$,Y]of J.clientMap)Z.push({clientId:$,...Y})};e6.prototype._remove_value=function(Z,J){var X=Z.clientMap,$=X.size;X.delete(J.clientId);var Y=X.size;if(Y<$)this.subscriptionsCount-=1;return Y===0};e6.prototype.test_values=function(Z,J){var X=Z.clientMap;return Z.topic===J.topic&&X.size===1&&X.has(J.clientId)};e6.prototype.match=function(Z,J){return this._match([],0,Z.split(this._separator),this._trie,J)};e6.prototype.clear=function(){return this.subscriptionsCount=0,nD.prototype.clear.call(this)};e6.set_native=function(Z){let J=cD();return e6.native=J(Z.QlobberSub,e6),oD.exports};oD.exports=e6});var F10=L((ER1,rD)=>{var{Readable:k3}=N("stream"),_l0=z10(),{QlobberTrue:Ol0}=iD(),aD=lX(),H10={wildcard_one:"+",wildcard_some:"#",separator:"/"};function*wl0(Z){for(let J of Z)yield*J}function*G10(Z,J){let X=new Ol0(H10);X.add(J);for(let[$,Y]of Z)if(X.test($))yield Y}function*jl0(Z,J){for(let X of Z.values())if(!J[X.brokerId])yield X}function*Ml0(Z,J){for(let[X,$]of Z)if($.has(J))yield X}class V10{#J;#X;#G;#$;#Y;#B;#Q;constructor(){this.#J=new Map,this.#X=new Map,this.#G=new Map,this.#$=new Map,this.#Y=new Map,this.#B=0,this.#Q=new _l0(H10)}storeRetained(Z,J){let X=Object.assign({},Z);if(X.payload.length===0)this.#J.delete(X.topic);else this.#J.set(X.topic,X);J(null)}createRetainedStreamCombi(Z){let J=Z.map((X)=>{return G10(this.#J,X)});return k3.from(wl0(J))}createRetainedStream(Z){return k3.from(G10(this.#J,Z))}addSubscriptions(Z,J,X){let $=this.#X.get(Z.id),Y=this.#Q;if(!$)$=new Map,this.#X.set(Z.id,$),this.#B++;for(let Q of J){let W=$.get(Q.topic);if(Q.qos>0)Y.add(Q.topic,{clientId:Z.id,topic:Q.topic,qos:Q.qos,rh:Q.rh,rap:Q.rap,nl:Q.nl});else if(W?.qos>0)Y.remove(Q.topic,{clientId:Z.id,topic:Q.topic});$.set(Q.topic,{qos:Q.qos,rh:Q.rh,rap:Q.rap,nl:Q.nl})}X(null,Z)}removeSubscriptions(Z,J,X){let $=this.#X.get(Z.id),Y=this.#Q;if($){for(let Q of J){let W=$.get(Q);if(W!==void 0){if(W.qos>0)Y.remove(Q,{clientId:Z.id,topic:Q});$.delete(Q)}}if($.size===0)this.#B--,this.#X.delete(Z.id)}X(null,Z)}subscriptionsByClient(Z,J){let X=null,$=this.#X.get(Z.id);if($){X=[];for(let[Y,Q]of $)X.push({topic:Y,...Q})}J(null,X,Z)}countOffline(Z){return Z(null,this.#Q.subscriptionsCount,this.#B)}subscriptionsByTopic(Z,J){J(null,this.#Q.match(Z))}cleanSubscriptions(Z,J){let X=this.#Q,$=this.#X.get(Z.id);if($){for(let[Y,Q]of $)if(Q.qos>0)X.remove(Y,{clientId:Z.id,topic:Y});this.#B--,this.#X.delete(Z.id)}J(null,Z)}#H(Z,J){let X=Z.clientId,$=bZ(this.#G,X,[],!0);$[$.length]=new aD(J)}outgoingEnqueue(Z,J,X){this.#H(Z,J),process.nextTick(X)}outgoingEnqueueCombi(Z,J,X){for(let $=0;$<Z.length;$++)this.#H(Z[$],J);process.nextTick(X)}outgoingUpdate(Z,J,X){let $=bZ(this.#G,Z.id,[],!0),Y;for(let Q=0;Q<$.length;Q++)if(Y=$[Q],Y.brokerId===J.brokerId){if(Y.brokerCounter===J.brokerCounter)return Y.messageId=J.messageId,X(null,Z,J)}else if(Y.messageId===J.messageId)return $[Q]=J,X(null,Z,J);X(Error("no such packet"),Z,J)}outgoingClearMessageId(Z,J,X){let $=bZ(this.#G,Z.id,[],!0),Y;for(let Q=0;Q<$.length;Q++)if(Y=$[Q],Y.messageId===J.messageId)return $.splice(Q,1),X(null,Y);X()}outgoingStream(Z){let J=[].concat(bZ(this.#G,Z.id,[]));return k3.from(J)}incomingStorePacket(Z,J,X){let $=Z.id,Y=bZ(this.#$,$,{},!0);Y[J.messageId]=new aD(J),Y[J.messageId].messageId=J.messageId,X(null)}incomingGetPacket(Z,J,X){let $=Z.id,Y=bZ(this.#$,$,{}),Q=null;if(this.#$.set($,Y),!Y[J.messageId])Q=Error("no such packet");X(Q,Y[J.messageId])}incomingDelPacket(Z,J,X){let $=Z.id,Y=bZ(this.#$,$,{}),Q=Y[J.messageId],W=null;if(!Q)W=Error("no such packet");else delete Y[J.messageId];X(W)}putWill(Z,J,X){J.brokerId=this.broker.id,J.clientId=Z.id,this.#Y.set(Z.id,J),X(null,Z)}getWill(Z,J){J(null,this.#Y.get(Z.id),Z)}delWill(Z,J){let X=this.#Y.get(Z.id);this.#Y.delete(Z.id),J(null,X,Z)}streamWill(Z={}){return k3.from(jl0(this.#Y,Z))}getClientList(Z){return k3.from(Ml0(this.#X,Z))}destroy(Z){if(this.#J=null,Z)Z(null)}}function bZ(Z,J,X,$=!1){let Y=Z.get(J);if(Y===void 0&&$)Z.set(J,X);return Y||X}rD.exports=()=>{return new V10};rD.exports.Packet=aD});var U10=L((IR1,B10)=>{var v8=N("util");B10.exports=function(Z,J){class X extends Z{constructor($){super($);this.addP=v8.promisify(this.add_async),this.removeP=v8.promisify(this.remove_async),this.matchP=v8.promisify(this.match_async),this.testP=v8.promisify(this.test_async),this.clearP=v8.promisify(this.clear_async),this._get_visitorP=v8.promisify(this.get_visitor_async),this._visit_nextP=v8.promisify(this.visit_next_async),this._get_restorerP=v8.promisify(this.get_restorer_async),this._restore_nextP=v8.promisify(this.restore_next_async),this._match_iterP=v8.promisify(this.match_iter_async),this._match_nextP=v8.promisify(this.match_next_async)}*visit(){let $=this.get_visitor();while(!0){let Y=this.visit_next($);if(Y===void 0)break;yield Y}}async*visitP(){let $=await this._get_visitorP();while(!0){let Y=await this._visit_nextP($);if(Y===void 0)break;yield Y}}*match_iter($,Y){let Q=super.match_iter($,Y);while(!0){let W=this.match_next(Q);if(W===void 0)break;yield W.value}}async*match_iterP($,Y){let Q=await this._match_iterP($,Y);while(!0){let W=await this._match_nextP(Q);if(W===void 0)break;yield W.value}}get_trie(){let $=new J(this.options),Y=$.get_restorer();for(let Q of this.visit())Y(Q);return $.get_trie()}get_restorer($){let Y=super.get_restorer($);return(Q)=>{super.restore_next(Y,Q)}}async get_restorerP($){let Y=await this._get_restorerP($);return async(Q)=>{await this._restore_nextP(Y,Q)}}}return X.is_native=!0,X.nonNative=J,X}});var _10=L((D10)=>{var JG=N("util");function v0(Z){if(Z=Z||{},this._separator=Z.separator||".",this._wildcard_one=Z.wildcard_one||"*",this._wildcard_some=Z.wildcard_some||"#",this._max_words=Z.max_words||100,this._max_wildcard_somes=Z.max_wildcard_somes||3,this._match_empty_levels=Z.match_empty_levels,this._trie=new Map,Z.cache_adds instanceof Map)this._shortcuts=Z.cache_adds;else if(Z.cache_adds)this._shortcuts=new Map;if(Z.cache_splits>0)this._cache_splits=Z.cache_splits,this._split_cache=new Map}v0.prototype._initial_value=function(Z){return[Z]};v0.prototype._add_value=function(Z,J){Z[Z.length]=J};v0.prototype._add_values=function(Z,J){var X,$=Z.length,Y=J.length;for(X=0;X<Y;X+=1)Z[$+X]=J[X]};v0.prototype._iter_values=function(Z,J){return Z[Symbol.iterator](J)};v0.prototype._remove_value=function(Z,J){if(J===void 0)return!0;var X=Z.lastIndexOf(J);if(X>=0)Z.splice(X,1);return Z.length===0};v0.prototype._add=function(Z,J,X,$){var Y,Q;if(J===X.length){if(Y=$.get(this._separator),Y)this._add_value(Y,Z);else Y=this._initial_value(Z),$.set(this._separator,Y);return Y}if(Q=X[J],Y=$.get(Q),!Y)Y=new Map,$.set(Q,Y);return this._add(Z,J+1,X,Y)};v0.prototype._remove=function(Z,J,X,$){var Y,Q,W;if(J===X.length){if(Y=$.get(this._separator),Y&&this._remove_value(Y,Z))return $.delete(this._separator),!0;return!1}if(Q=X[J],Y=$.get(Q),!Y)return!1;if(W=this._remove(Z,J+1,X,Y),Y.size===0)$.delete(Q);return W};v0.prototype._match_some=function(Z,J,X,$,Y){var Q,W;for(W of $.keys())if(W!==this._separator){for(Q=J;Q<X.length;Q+=1)Z=this._match(Z,Q,X,$,Y);break}return Z};v0.prototype._match=function(Z,J,X,$,Y){var Q,W;if(W=$.get(this._wildcard_some),W)Z=this._match_some(Z,J,X,W,Y),Z=this._match(Z,X.length,X,W,Y);if(J===X.length){if(W=$.get(this._separator),W)if(Z.dest)this._add_values(Z.dest,Z.source,Y),this._add_values(Z.dest,W,Y),Z=Z.dest;else if(Z.source)Z.dest=Z.source,Z.source=W;else this._add_values(Z,W,Y)}else{if(Q=X[J],Q!==this._wildcard_one&&Q!==this._wildcard_some){if(W=$.get(Q),W)Z=this._match(Z,J+1,X,W,Y)}if(Q||this._match_empty_levels){if(W=$.get(this._wildcard_one),W)Z=this._match(Z,J+1,X,W,Y)}}return Z};v0.prototype._match2=function(Z,J,X){var $=this._match({source:Z},0,this._split(J,!1),this._trie,X);return $.source||$};v0.prototype._test_some=function(Z,J,X,$){var Y,Q;for(Q of $.keys())if(Q!==this._separator){for(Y=J;Y<X.length;Y+=1)if(this._test(Z,Y,X,$))return!0;break}return!1};v0.prototype._test=function(Z,J,X,$){var Y,Q;if(Q=$.get(this._wildcard_some),Q){if(this._test_some(Z,J,X,Q)||this._test(Z,X.length,X,Q))return!0}if(J===X.length){if(Q=$.get(this._separator),Q&&this.test_values(Q,Z))return!0}else{if(Y=X[J],Y!==this._wildcard_one&&Y!==this._wildcard_some){if(Q=$.get(Y),Q&&this._test(Z,J+1,X,Q))return!0}if(Y||this._match_empty_levels){if(Q=$.get(this._wildcard_one),Q&&this._test(Z,J+1,X,Q))return!0}}return!1};v0.prototype._match_some_iter=function*(Z,J,X,$){var Y,Q;for(Q of X.keys())if(Q!==this._separator){for(Y=Z;Y<J.length;Y+=1)yield*this._match_iter(Y,J,X,$);break}};v0.prototype._match_iter=function*(Z,J,X,$){var Y,Q;if(Q=X.get(this._wildcard_some),Q)yield*this._match_some_iter(Z,J,Q,$),yield*this._match_iter(J.length,J,Q,$);if(Z===J.length){if(Q=X.get(this._separator),Q)yield*this._iter_values(Q,$)}else{if(Y=J[Z],Y!==this._wildcard_one&&Y!==this._wildcard_some){if(Q=X.get(Y),Q)yield*this._match_iter(Z+1,J,Q,$)}if(Y||this._match_empty_levels){if(Q=X.get(this._wildcard_one),Q)yield*this._match_iter(Z+1,J,Q,$)}}};v0.prototype._split_words=function(Z){let J=Z.split(this._separator);if(J.length>this._max_words)throw Error("too many words");return J};v0.prototype._split=function(Z,J){let X;if(this._split_cache){if(X=this._split_cache.get(Z),X===void 0){if(X=this._split_words(Z),this._split_cache.set(Z,X),this._split_cache.size>this._cache_splits)for(let $ of this._split_cache.keys()){this._split_cache.delete($);break}}}else X=this._split_words(Z);if(J&&X.reduce(($,Y)=>$+(Y===this._wildcard_some),0)>this._max_wildcard_somes)throw Error("too many wildcard somes");return X};v0.prototype.add=function(Z,J){var X=this._shortcuts&&this._shortcuts.get(Z);if(X)this._add_value(X,J);else if(X=this._add(J,0,this._split(Z,!0),this._trie),this._shortcuts)this._shortcuts.set(Z,X);return this};v0.prototype.remove=function(Z,J){if(this._remove(J,0,this._split(Z,!1),this._trie)&&this._shortcuts)this._shortcuts.delete(Z);return this};v0.prototype.match=function(Z,J){return this._match2([],Z,J)};v0.prototype.match_iter=function(Z,J){return this._match_iter(0,this._split(Z,!1),this._trie,J)};v0.prototype.test=function(Z,J){return this._test(J,0,this._split(Z,!1),this._trie)};v0.prototype.test_values=function(Z,J){return Z.indexOf(J)>=0};v0.prototype.clear=function(){if(this._trie.clear(),this._shortcuts)this._shortcuts.clear();if(this._split_cache)this._split_cache.clear();return this};v0.prototype.get_trie=function(){return this._trie};v0.prototype.visit=function*(){let Z=[],J=this._trie.entries(),X=0;while(!0){if(X===0)yield{type:"start_entries"};let $=J.next();if($.done){yield{type:"end_entries"};let W=Z.pop();if(W===void 0)return;[J,X]=W;continue}let[Y,Q]=$.value;if(yield{type:"entry",key:Y},++X,Y===this._separator){if(yield{type:"start_values"},Q[Symbol.iterator])for(let W of Q)yield{type:"value",value:W};else yield{type:"value",value:Q};yield{type:"end_values"};continue}Z.push([J,X]),J=Q.entries(),X=0}};v0.prototype.get_restorer=function(Z){Z=Z||{};let J=[],X=this._trie,$="";return(Y)=>{switch(Y.type){case"entry":if(X=X||new Map,J.push([X,Y.key,$]),X=X.get(Y.key),Z.cache_adds){if($)$+=this._separator;$+=Y.key}break;case"value":if(X)this._add_value(X,Y.value);else X=this._initial_value(Y.value);break;case"end_entries":if(X&&X.size===0)X=void 0;case"end_values":let Q=J.pop();if(Q===void 0)X=void 0,$="";else{let[W,K,z]=Q;if(X){if(Z.cache_adds&&this._shortcuts&&Y.type==="end_values")this._shortcuts.set(z,X);W.set(K,X)}X=W,$=z}break}}};function Z8(Z){v0.call(this,Z)}JG.inherits(Z8,v0);Z8.prototype._initial_value=function(Z){return new Set().add(Z)};Z8.prototype._add_value=function(Z,J){Z.add(J)};Z8.prototype._add_values=function(Z,J){J.forEach(function(X){Z.add(X)})};Z8.prototype._remove_value=function(Z,J){if(J===void 0)return!0;return Z.delete(J),Z.size===0};Z8.prototype.test_values=function(Z,J){return Z.has(J)};Z8.prototype.match=function(Z,J){return this._match2(new Set,Z,J)};function V5(Z){v0.call(this,Z)}JG.inherits(V5,v0);V5.prototype._initial_value=function(){return!0};V5.prototype._add_value=function(){};V5.prototype._remove_value=function(){return!0};V5.prototype._iter_values=function*(){yield!0};V5.prototype.test_values=function(){return!0};V5.prototype.match=function(Z,J){return this.test(Z,J)};var XG=N("stream");function sD(Z){XG.Readable.call(this,{objectMode:!0}),this._iterator=Z.visit()}JG.inherits(sD,XG.Readable);sD.prototype._read=function(){while(!0){let{done:Z,value:J}=this._iterator.next();if(Z){this.push(null);break}if(!this.push(J))break}};function tD(Z){XG.Writable.call(this,{objectMode:!0}),this._restorer=Z.get_restorer()}JG.inherits(tD,XG.Writable);tD.prototype._write=function(Z,J,X){this._restorer(Z),X()};var L10=null;function Al0(Z){if(Z!==L10){let J=U10();v0.nativeString=J(Z.QlobberString,v0),v0.nativeNumber=J(Z.QlobberNumber,v0),Z8.nativeString=J(Z.QlobberDedupString,Z8),Z8.nativeNumber=J(Z.QlobberDedupNumber,Z8),V5.native=J(Z.QlobberTrue,V5),L10=Z}return D10}D10.Qlobber=v0;D10.QlobberDedup=Z8;D10.QlobberTrue=V5;D10.VisitorStream=sD;D10.RestorerStream=tD;D10.set_native=Al0});var w10=L((SR1,O10)=>{var{Qlobber:El0}=_10(),pX=N("assert"),Il0=hD();function F5(Z){if(!(this instanceof F5))return new F5(Z);let J=this;Z=Z||{},Z.matchEmptyLevels=Z.matchEmptyLevels===void 0?!0:!!Z.matchEmptyLevels,Z.separator=Z.separator||"/",Z.wildcardOne=Z.wildcardOne||"+",Z.wildcardSome=Z.wildcardSome||"#",this._messageQueue=[],this._messageCallbacks=[],this._parallel=Il0({results:!1,released:X}),this.concurrency=Z.concurrency||0,this.current=0,this._doing=!1,this._matcher=new El0({match_empty_levels:Z.matchEmptyLevels,separator:Z.separator,wildcard_one:Z.wildcardOne,wildcard_some:Z.wildcardSome}),this.closed=!1,this._released=X;function X(){J.current--;let $=J._messageQueue.shift(),Y=J._messageCallbacks.shift();if($)J._do($,Y);else J._doing=!1}}Object.defineProperty(F5.prototype,"length",{get:function(){return this._messageQueue.length},enumerable:!0});F5.prototype.on=function(J,X,$){if(pX(J),pX(X),this._matcher.add(J,X),$)setImmediate($);return this};F5.prototype.removeListener=function(J,X,$){pX(J),pX(X);let Y=this;return setImmediate(function(){if(Y._matcher.remove(J,X),$)$()}),this};F5.prototype.removeAllListeners=function(J,X){if(pX(J),this._matcher.remove(J),X)setImmediate(X);return this};F5.prototype.emit=function(J,X){if(pX(J),X=X||yl0,this.closed)return X(Error("mqemitter is closed"));if(this.concurrency>0&&this.current>=this.concurrency){if(this._messageQueue.push(J),this._messageCallbacks.push(X),!this._doing)process.emitWarning("MqEmitter leak detected",{detail:"For more info check: https://github.com/mcollina/mqemitter/pull/94"}),this._released()}else this._do(J,X);return this};F5.prototype.close=function(J){return this.closed=!0,setImmediate(J),this};F5.prototype._do=function(Z,J){this._doing=!0;let X=this._matcher.match(Z.topic);return this.current++,this._parallel(this,X,Z,J),this};function yl0(){}O10.exports=F5});var F1=L((kR1,M10)=>{class j10 extends Error{constructor(Z){if(!Array.isArray(Z))throw TypeError(`Expected input to be an Array, got ${typeof Z}`);let J="";for(let X=0;X<Z.length;X++)J+=` ${Z[X].stack}
11
- `;super(J);this.name="AggregateError",this.errors=Z}}M10.exports={AggregateError:j10,ArrayIsArray(Z){return Array.isArray(Z)},ArrayPrototypeIncludes(Z,J){return Z.includes(J)},ArrayPrototypeIndexOf(Z,J){return Z.indexOf(J)},ArrayPrototypeJoin(Z,J){return Z.join(J)},ArrayPrototypeMap(Z,J){return Z.map(J)},ArrayPrototypePop(Z,J){return Z.pop(J)},ArrayPrototypePush(Z,J){return Z.push(J)},ArrayPrototypeSlice(Z,J,X){return Z.slice(J,X)},Error,FunctionPrototypeCall(Z,J,...X){return Z.call(J,...X)},FunctionPrototypeSymbolHasInstance(Z,J){return Function.prototype[Symbol.hasInstance].call(Z,J)},MathFloor:Math.floor,Number,NumberIsInteger:Number.isInteger,NumberIsNaN:Number.isNaN,NumberMAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,NumberParseInt:Number.parseInt,ObjectDefineProperties(Z,J){return Object.defineProperties(Z,J)},ObjectDefineProperty(Z,J,X){return Object.defineProperty(Z,J,X)},ObjectGetOwnPropertyDescriptor(Z,J){return Object.getOwnPropertyDescriptor(Z,J)},ObjectKeys(Z){return Object.keys(Z)},ObjectSetPrototypeOf(Z,J){return Object.setPrototypeOf(Z,J)},Promise,PromisePrototypeCatch(Z,J){return Z.catch(J)},PromisePrototypeThen(Z,J,X){return Z.then(J,X)},PromiseReject(Z){return Promise.reject(Z)},PromiseResolve(Z){return Promise.resolve(Z)},ReflectApply:Reflect.apply,RegExpPrototypeTest(Z,J){return Z.test(J)},SafeSet:Set,String,StringPrototypeSlice(Z,J,X){return Z.slice(J,X)},StringPrototypeToLowerCase(Z){return Z.toLowerCase()},StringPrototypeToUpperCase(Z){return Z.toUpperCase()},StringPrototypeTrim(Z){return Z.trim()},Symbol,SymbolFor:Symbol.for,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,SymbolDispose:Symbol.dispose||Symbol("Symbol.dispose"),SymbolAsyncDispose:Symbol.asyncDispose||Symbol("Symbol.asyncDispose"),TypedArrayPrototypeSet(Z,J,X){return Z.set(J,X)},Boolean,Uint8Array}});var eD=L((xR1,A10)=>{A10.exports={format(Z,...J){return Z.replace(/%([sdifj])/g,function(...[X,$]){let Y=J.shift();if($==="f")return Y.toFixed(6);else if($==="j")return JSON.stringify(Y);else if($==="s"&&typeof Y==="object")return`${Y.constructor!==Object?Y.constructor.name:""} {}`.trim();else return Y.toString()})},inspect(Z){switch(typeof Z){case"string":if(Z.includes("'")){if(!Z.includes('"'))return`"${Z}"`;else if(!Z.includes("`")&&!Z.includes("${"))return`\`${Z}\``}return`'${Z}'`;case"number":if(isNaN(Z))return"NaN";else if(Object.is(Z,-0))return String(Z);return Z;case"bigint":return`${String(Z)}n`;case"boolean":case"undefined":return String(Z);case"object":return"{}"}}}});var T4=L((vR1,N10)=>{var{format:Sl0,inspect:$G}=eD(),{AggregateError:kl0}=F1(),xl0=globalThis.AggregateError||kl0,vl0=Symbol("kIsNodeError"),hl0=["string","function","number","object","Function","Object","boolean","bigint","symbol"],fl0=/^([A-Z][a-z0-9]*)+$/,YG={};function gZ(Z,J){if(!Z)throw new YG.ERR_INTERNAL_ASSERTION(J)}function T10(Z){let J="",X=Z.length,$=Z[0]==="-"?1:0;for(;X>=$+4;X-=3)J=`_${Z.slice(X-3,X)}${J}`;return`${Z.slice(0,X)}${J}`}function bl0(Z,J,X){if(typeof J==="function")return gZ(J.length<=X.length,`Code: ${Z}; The provided arguments length (${X.length}) does not match the required ones (${J.length}).`),J(...X);let $=(J.match(/%[dfijoOs]/g)||[]).length;if(gZ($===X.length,`Code: ${Z}; The provided arguments length (${X.length}) does not match the required ones (${$}).`),X.length===0)return J;return Sl0(J,...X)}function U4(Z,J,X){if(!X)X=Error;class $ extends X{constructor(...Y){super(bl0(Z,J,Y))}toString(){return`${this.name} [${Z}]: ${this.message}`}}Object.defineProperties($.prototype,{name:{value:X.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${Z}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),$.prototype.code=Z,$.prototype[vl0]=!0,YG[Z]=$}function q10(Z){let J="__node_internal_"+Z.name;return Object.defineProperty(Z,"name",{value:J}),Z}function gl0(Z,J){if(Z&&J&&Z!==J){if(Array.isArray(J.errors))return J.errors.push(Z),J;let X=new xl0([J,Z],J.message);return X.code=J.code,X}return Z||J}class C10 extends Error{constructor(Z="The operation was aborted",J=void 0){if(J!==void 0&&typeof J!=="object")throw new YG.ERR_INVALID_ARG_TYPE("options","Object",J);super(Z,J);this.code="ABORT_ERR",this.name="AbortError"}}U4("ERR_ASSERTION","%s",Error);U4("ERR_INVALID_ARG_TYPE",(Z,J,X)=>{if(gZ(typeof Z==="string","'name' must be a string"),!Array.isArray(J))J=[J];let $="The ";if(Z.endsWith(" argument"))$+=`${Z} `;else $+=`"${Z}" ${Z.includes(".")?"property":"argument"} `;$+="must be ";let Y=[],Q=[],W=[];for(let z of J)if(gZ(typeof z==="string","All expected entries have to be of type string"),hl0.includes(z))Y.push(z.toLowerCase());else if(fl0.test(z))Q.push(z);else gZ(z!=="object",'The value "object" should be written as "Object"'),W.push(z);if(Q.length>0){let z=Y.indexOf("object");if(z!==-1)Y.splice(Y,z,1),Q.push("Object")}if(Y.length>0){switch(Y.length){case 1:$+=`of type ${Y[0]}`;break;case 2:$+=`one of type ${Y[0]} or ${Y[1]}`;break;default:{let z=Y.pop();$+=`one of type ${Y.join(", ")}, or ${z}`}}if(Q.length>0||W.length>0)$+=" or "}if(Q.length>0){switch(Q.length){case 1:$+=`an instance of ${Q[0]}`;break;case 2:$+=`an instance of ${Q[0]} or ${Q[1]}`;break;default:{let z=Q.pop();$+=`an instance of ${Q.join(", ")}, or ${z}`}}if(W.length>0)$+=" or "}switch(W.length){case 0:break;case 1:if(W[0].toLowerCase()!==W[0])$+="an ";$+=`${W[0]}`;break;case 2:$+=`one of ${W[0]} or ${W[1]}`;break;default:{let z=W.pop();$+=`one of ${W.join(", ")}, or ${z}`}}if(X==null)$+=`. Received ${X}`;else if(typeof X==="function"&&X.name)$+=`. Received function ${X.name}`;else if(typeof X==="object"){var K;if((K=X.constructor)!==null&&K!==void 0&&K.name)$+=`. Received an instance of ${X.constructor.name}`;else{let z=$G(X,{depth:-1});$+=`. Received ${z}`}}else{let z=$G(X,{colors:!1});if(z.length>25)z=`${z.slice(0,25)}...`;$+=`. Received type ${typeof X} (${z})`}return $},TypeError);U4("ERR_INVALID_ARG_VALUE",(Z,J,X="is invalid")=>{let $=$G(J);if($.length>128)$=$.slice(0,128)+"...";return`The ${Z.includes(".")?"property":"argument"} '${Z}' ${X}. Received ${$}`},TypeError);U4("ERR_INVALID_RETURN_VALUE",(Z,J,X)=>{var $;let Y=X!==null&&X!==void 0&&($=X.constructor)!==null&&$!==void 0&&$.name?`instance of ${X.constructor.name}`:`type ${typeof X}`;return`Expected ${Z} to be returned from the "${J}" function but got ${Y}.`},TypeError);U4("ERR_MISSING_ARGS",(...Z)=>{gZ(Z.length>0,"At least one arg needs to be specified");let J,X=Z.length;switch(Z=(Array.isArray(Z)?Z:[Z]).map(($)=>`"${$}"`).join(" or "),X){case 1:J+=`The ${Z[0]} argument`;break;case 2:J+=`The ${Z[0]} and ${Z[1]} arguments`;break;default:{let $=Z.pop();J+=`The ${Z.join(", ")}, and ${$} arguments`}break}return`${J} must be specified`},TypeError);U4("ERR_OUT_OF_RANGE",(Z,J,X)=>{gZ(J,'Missing "range" argument');let $;if(Number.isInteger(X)&&Math.abs(X)>4294967296)$=T10(String(X));else if(typeof X==="bigint"){$=String(X);let Y=BigInt(2)**BigInt(32);if(X>Y||X<-Y)$=T10($);$+="n"}else $=$G(X);return`The value of "${Z}" is out of range. It must be ${J}. Received ${$}`},RangeError);U4("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error);U4("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error);U4("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error);U4("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error);U4("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error);U4("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError);U4("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error);U4("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error);U4("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error);U4("ERR_STREAM_WRITE_AFTER_END","write after end",Error);U4("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError);N10.exports={AbortError:C10,aggregateTwoErrors:q10(gl0),hideStackFrames:q10,codes:YG}});var b4=L((hR1,J_)=>{var ml0=N("buffer"),{format:dl0,inspect:ul0}=eD(),{codes:{ERR_INVALID_ARG_TYPE:Z_}}=T4(),{kResistStopPropagation:cl0,AggregateError:ll0,SymbolDispose:pl0}=F1(),il0=globalThis.AbortSignal||N("abort-controller").AbortSignal,nl0=globalThis.AbortController||N("abort-controller").AbortController,ol0=Object.getPrototypeOf(async function(){}).constructor,R10=globalThis.Blob||ml0.Blob,al0=typeof R10<"u"?function(J){return J instanceof R10}:function(J){return!1},P10=(Z,J)=>{if(Z!==void 0&&(Z===null||typeof Z!=="object"||!("aborted"in Z)))throw new Z_(J,"AbortSignal",Z)},rl0=(Z,J)=>{if(typeof Z!=="function")throw new Z_(J,"Function",Z)};J_.exports={AggregateError:ll0,kEmptyObject:Object.freeze({}),once(Z){let J=!1;return function(...X){if(J)return;J=!0,Z.apply(this,X)}},createDeferredPromise:function(){let Z,J;return{promise:new Promise(($,Y)=>{Z=$,J=Y}),resolve:Z,reject:J}},promisify(Z){return new Promise((J,X)=>{Z(($,...Y)=>{if($)return X($);return J(...Y)})})},debuglog(){return function(){}},format:dl0,inspect:ul0,types:{isAsyncFunction(Z){return Z instanceof ol0},isArrayBufferView(Z){return ArrayBuffer.isView(Z)}},isBlob:al0,deprecate(Z,J){return Z},addAbortListener:N("events").addAbortListener||function(J,X){if(J===void 0)throw new Z_("signal","AbortSignal",J);P10(J,"signal"),rl0(X,"listener");let $;if(J.aborted)queueMicrotask(()=>X());else J.addEventListener("abort",X,{__proto__:null,once:!0,[cl0]:!0}),$=()=>{J.removeEventListener("abort",X)};return{__proto__:null,[pl0](){var Y;(Y=$)===null||Y===void 0||Y()}}},AbortSignalAny:il0.any||function(J){if(J.length===1)return J[0];let X=new nl0,$=()=>X.abort();return J.forEach((Y)=>{P10(Y,"signals"),Y.addEventListener("abort",$,{once:!0})}),X.signal.addEventListener("abort",()=>{J.forEach((Y)=>Y.removeEventListener("abort",$))},{once:!0}),X.signal}};J_.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")});var nX=L((fR1,b10)=>{var{ArrayIsArray:$_,ArrayPrototypeIncludes:S10,ArrayPrototypeJoin:k10,ArrayPrototypeMap:sl0,NumberIsInteger:Y_,NumberIsNaN:tl0,NumberMAX_SAFE_INTEGER:el0,NumberMIN_SAFE_INTEGER:Zp0,NumberParseInt:Jp0,ObjectPrototypeHasOwnProperty:Xp0,RegExpPrototypeExec:x10,String:$p0,StringPrototypeToUpperCase:Yp0,StringPrototypeTrim:Qp0}=F1(),{hideStackFrames:J8,codes:{ERR_SOCKET_BAD_PORT:Wp0,ERR_INVALID_ARG_TYPE:q4,ERR_INVALID_ARG_VALUE:iX,ERR_OUT_OF_RANGE:mZ,ERR_UNKNOWN_SIGNAL:E10}}=T4(),{normalizeEncoding:Kp0}=b4(),{isAsyncFunction:zp0,isArrayBufferView:Gp0}=b4().types,I10={};function Hp0(Z){return Z===(Z|0)}function Vp0(Z){return Z===Z>>>0}var Fp0=/^[0-7]+$/,Bp0="must be a 32-bit unsigned integer or an octal string";function Up0(Z,J,X){if(typeof Z>"u")Z=X;if(typeof Z==="string"){if(x10(Fp0,Z)===null)throw new iX(J,Z,Bp0);Z=Jp0(Z,8)}return v10(Z,J),Z}var Lp0=J8((Z,J,X=Zp0,$=el0)=>{if(typeof Z!=="number")throw new q4(J,"number",Z);if(!Y_(Z))throw new mZ(J,"an integer",Z);if(Z<X||Z>$)throw new mZ(J,`>= ${X} && <= ${$}`,Z)}),Dp0=J8((Z,J,X=-2147483648,$=2147483647)=>{if(typeof Z!=="number")throw new q4(J,"number",Z);if(!Y_(Z))throw new mZ(J,"an integer",Z);if(Z<X||Z>$)throw new mZ(J,`>= ${X} && <= ${$}`,Z)}),v10=J8((Z,J,X=!1)=>{if(typeof Z!=="number")throw new q4(J,"number",Z);if(!Y_(Z))throw new mZ(J,"an integer",Z);let $=X?1:0,Y=4294967295;if(Z<$||Z>Y)throw new mZ(J,`>= ${$} && <= ${Y}`,Z)});function Q_(Z,J){if(typeof Z!=="string")throw new q4(J,"string",Z)}function _p0(Z,J,X=void 0,$){if(typeof Z!=="number")throw new q4(J,"number",Z);if(X!=null&&Z<X||$!=null&&Z>$||(X!=null||$!=null)&&tl0(Z))throw new mZ(J,`${X!=null?`>= ${X}`:""}${X!=null&&$!=null?" && ":""}${$!=null?`<= ${$}`:""}`,Z)}var Op0=J8((Z,J,X)=>{if(!S10(X,Z)){let Y="must be one of: "+k10(sl0(X,(Q)=>typeof Q==="string"?`'${Q}'`:$p0(Q)),", ");throw new iX(J,Z,Y)}});function h10(Z,J){if(typeof Z!=="boolean")throw new q4(J,"boolean",Z)}function X_(Z,J,X){return Z==null||!Xp0(Z,J)?X:Z[J]}var wp0=J8((Z,J,X=null)=>{let $=X_(X,"allowArray",!1),Y=X_(X,"allowFunction",!1);if(!X_(X,"nullable",!1)&&Z===null||!$&&$_(Z)||typeof Z!=="object"&&(!Y||typeof Z!=="function"))throw new q4(J,"Object",Z)}),jp0=J8((Z,J)=>{if(Z!=null&&typeof Z!=="object"&&typeof Z!=="function")throw new q4(J,"a dictionary",Z)}),QG=J8((Z,J,X=0)=>{if(!$_(Z))throw new q4(J,"Array",Z);if(Z.length<X){let $=`must be longer than ${X}`;throw new iX(J,Z,$)}});function Mp0(Z,J){QG(Z,J);for(let X=0;X<Z.length;X++)Q_(Z[X],`${J}[${X}]`)}function Ap0(Z,J){QG(Z,J);for(let X=0;X<Z.length;X++)h10(Z[X],`${J}[${X}]`)}function Tp0(Z,J){QG(Z,J);for(let X=0;X<Z.length;X++){let $=Z[X],Y=`${J}[${X}]`;if($==null)throw new q4(Y,"AbortSignal",$);f10($,Y)}}function qp0(Z,J="signal"){if(Q_(Z,J),I10[Z]===void 0){if(I10[Yp0(Z)]!==void 0)throw new E10(Z+" (signals must use all capital letters)");throw new E10(Z)}}var Cp0=J8((Z,J="buffer")=>{if(!Gp0(Z))throw new q4(J,["Buffer","TypedArray","DataView"],Z)});function Np0(Z,J){let X=Kp0(J),$=Z.length;if(X==="hex"&&$%2!==0)throw new iX("encoding",J,`is invalid for data of length ${$}`)}function Rp0(Z,J="Port",X=!0){if(typeof Z!=="number"&&typeof Z!=="string"||typeof Z==="string"&&Qp0(Z).length===0||+Z!==+Z>>>0||Z>65535||Z===0&&!X)throw new Wp0(J,Z,X);return Z|0}var f10=J8((Z,J)=>{if(Z!==void 0&&(Z===null||typeof Z!=="object"||!("aborted"in Z)))throw new q4(J,"AbortSignal",Z)}),Pp0=J8((Z,J)=>{if(typeof Z!=="function")throw new q4(J,"Function",Z)}),Ep0=J8((Z,J)=>{if(typeof Z!=="function"||zp0(Z))throw new q4(J,"Function",Z)}),Ip0=J8((Z,J)=>{if(Z!==void 0)throw new q4(J,"undefined",Z)});function yp0(Z,J,X){if(!S10(X,Z))throw new q4(J,`('${k10(X,"|")}')`,Z)}var Sp0=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function y10(Z,J){if(typeof Z>"u"||!x10(Sp0,Z))throw new iX(J,Z,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}function kp0(Z){if(typeof Z==="string")return y10(Z,"hints"),Z;else if($_(Z)){let J=Z.length,X="";if(J===0)return X;for(let $=0;$<J;$++){let Y=Z[$];if(y10(Y,"hints"),X+=Y,$!==J-1)X+=", "}return X}throw new iX("hints",Z,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}b10.exports={isInt32:Hp0,isUint32:Vp0,parseFileMode:Up0,validateArray:QG,validateStringArray:Mp0,validateBooleanArray:Ap0,validateAbortSignalArray:Tp0,validateBoolean:h10,validateBuffer:Cp0,validateDictionary:jp0,validateEncoding:Np0,validateFunction:Pp0,validateInt32:Dp0,validateInteger:Lp0,validateNumber:_p0,validateObject:wp0,validateOneOf:Op0,validatePlainFunction:Ep0,validatePort:Rp0,validateSignalName:qp0,validateString:Q_,validateUint32:v10,validateUndefined:Ip0,validateUnion:yp0,validateAbortSignal:f10,validateLinkHeaderValue:kp0}});var q7=L((bR1,g10)=>{g10.exports=global.process});var U5=L((gR1,Z40)=>{var{SymbolAsyncIterator:m10,SymbolIterator:d10,SymbolFor:dZ}=F1(),u10=dZ("nodejs.stream.destroyed"),c10=dZ("nodejs.stream.errored"),W_=dZ("nodejs.stream.readable"),K_=dZ("nodejs.stream.writable"),l10=dZ("nodejs.stream.disturbed"),xp0=dZ("nodejs.webstream.isClosedPromise"),vp0=dZ("nodejs.webstream.controllerErrorFunction");function WG(Z,J=!1){var X;return!!(Z&&typeof Z.pipe==="function"&&typeof Z.on==="function"&&(!J||typeof Z.pause==="function"&&typeof Z.resume==="function")&&(!Z._writableState||((X=Z._readableState)===null||X===void 0?void 0:X.readable)!==!1)&&(!Z._writableState||Z._readableState))}function KG(Z){var J;return!!(Z&&typeof Z.write==="function"&&typeof Z.on==="function"&&(!Z._readableState||((J=Z._writableState)===null||J===void 0?void 0:J.writable)!==!1))}function hp0(Z){return!!(Z&&typeof Z.pipe==="function"&&Z._readableState&&typeof Z.on==="function"&&typeof Z.write==="function")}function B5(Z){return Z&&(Z._readableState||Z._writableState||typeof Z.write==="function"&&typeof Z.on==="function"||typeof Z.pipe==="function"&&typeof Z.on==="function")}function p10(Z){return!!(Z&&!B5(Z)&&typeof Z.pipeThrough==="function"&&typeof Z.getReader==="function"&&typeof Z.cancel==="function")}function i10(Z){return!!(Z&&!B5(Z)&&typeof Z.getWriter==="function"&&typeof Z.abort==="function")}function n10(Z){return!!(Z&&!B5(Z)&&typeof Z.readable==="object"&&typeof Z.writable==="object")}function fp0(Z){return p10(Z)||i10(Z)||n10(Z)}function bp0(Z,J){if(Z==null)return!1;if(J===!0)return typeof Z[m10]==="function";if(J===!1)return typeof Z[d10]==="function";return typeof Z[m10]==="function"||typeof Z[d10]==="function"}function zG(Z){if(!B5(Z))return null;let{_writableState:J,_readableState:X}=Z,$=J||X;return!!(Z.destroyed||Z[u10]||$!==null&&$!==void 0&&$.destroyed)}function o10(Z){if(!KG(Z))return null;if(Z.writableEnded===!0)return!0;let J=Z._writableState;if(J!==null&&J!==void 0&&J.errored)return!1;if(typeof(J===null||J===void 0?void 0:J.ended)!=="boolean")return null;return J.ended}function gp0(Z,J){if(!KG(Z))return null;if(Z.writableFinished===!0)return!0;let X=Z._writableState;if(X!==null&&X!==void 0&&X.errored)return!1;if(typeof(X===null||X===void 0?void 0:X.finished)!=="boolean")return null;return!!(X.finished||J===!1&&X.ended===!0&&X.length===0)}function mp0(Z){if(!WG(Z))return null;if(Z.readableEnded===!0)return!0;let J=Z._readableState;if(!J||J.errored)return!1;if(typeof(J===null||J===void 0?void 0:J.ended)!=="boolean")return null;return J.ended}function a10(Z,J){if(!WG(Z))return null;let X=Z._readableState;if(X!==null&&X!==void 0&&X.errored)return!1;if(typeof(X===null||X===void 0?void 0:X.endEmitted)!=="boolean")return null;return!!(X.endEmitted||J===!1&&X.ended===!0&&X.length===0)}function r10(Z){if(Z&&Z[W_]!=null)return Z[W_];if(typeof(Z===null||Z===void 0?void 0:Z.readable)!=="boolean")return null;if(zG(Z))return!1;return WG(Z)&&Z.readable&&!a10(Z)}function s10(Z){if(Z&&Z[K_]!=null)return Z[K_];if(typeof(Z===null||Z===void 0?void 0:Z.writable)!=="boolean")return null;if(zG(Z))return!1;return KG(Z)&&Z.writable&&!o10(Z)}function dp0(Z,J){if(!B5(Z))return null;if(zG(Z))return!0;if((J===null||J===void 0?void 0:J.readable)!==!1&&r10(Z))return!1;if((J===null||J===void 0?void 0:J.writable)!==!1&&s10(Z))return!1;return!0}function up0(Z){var J,X;if(!B5(Z))return null;if(Z.writableErrored)return Z.writableErrored;return(J=(X=Z._writableState)===null||X===void 0?void 0:X.errored)!==null&&J!==void 0?J:null}function cp0(Z){var J,X;if(!B5(Z))return null;if(Z.readableErrored)return Z.readableErrored;return(J=(X=Z._readableState)===null||X===void 0?void 0:X.errored)!==null&&J!==void 0?J:null}function lp0(Z){if(!B5(Z))return null;if(typeof Z.closed==="boolean")return Z.closed;let{_writableState:J,_readableState:X}=Z;if(typeof(J===null||J===void 0?void 0:J.closed)==="boolean"||typeof(X===null||X===void 0?void 0:X.closed)==="boolean")return(J===null||J===void 0?void 0:J.closed)||(X===null||X===void 0?void 0:X.closed);if(typeof Z._closed==="boolean"&&t10(Z))return Z._closed;return null}function t10(Z){return typeof Z._closed==="boolean"&&typeof Z._defaultKeepAlive==="boolean"&&typeof Z._removedConnection==="boolean"&&typeof Z._removedContLen==="boolean"}function e10(Z){return typeof Z._sent100==="boolean"&&t10(Z)}function pp0(Z){var J;return typeof Z._consuming==="boolean"&&typeof Z._dumped==="boolean"&&((J=Z.req)===null||J===void 0?void 0:J.upgradeOrConnect)===void 0}function ip0(Z){if(!B5(Z))return null;let{_writableState:J,_readableState:X}=Z,$=J||X;return!$&&e10(Z)||!!($&&$.autoDestroy&&$.emitClose&&$.closed===!1)}function np0(Z){var J;return!!(Z&&((J=Z[l10])!==null&&J!==void 0?J:Z.readableDidRead||Z.readableAborted))}function op0(Z){var J,X,$,Y,Q,W,K,z,G,H;return!!(Z&&((J=(X=($=(Y=(Q=(W=Z[c10])!==null&&W!==void 0?W:Z.readableErrored)!==null&&Q!==void 0?Q:Z.writableErrored)!==null&&Y!==void 0?Y:(K=Z._readableState)===null||K===void 0?void 0:K.errorEmitted)!==null&&$!==void 0?$:(z=Z._writableState)===null||z===void 0?void 0:z.errorEmitted)!==null&&X!==void 0?X:(G=Z._readableState)===null||G===void 0?void 0:G.errored)!==null&&J!==void 0?J:(H=Z._writableState)===null||H===void 0?void 0:H.errored))}Z40.exports={isDestroyed:zG,kIsDestroyed:u10,isDisturbed:np0,kIsDisturbed:l10,isErrored:op0,kIsErrored:c10,isReadable:r10,kIsReadable:W_,kIsClosedPromise:xp0,kControllerErrorFunction:vp0,kIsWritable:K_,isClosed:lp0,isDuplexNodeStream:hp0,isFinished:dp0,isIterable:bp0,isReadableNodeStream:WG,isReadableStream:p10,isReadableEnded:mp0,isReadableFinished:a10,isReadableErrored:cp0,isNodeStream:B5,isWebStream:fp0,isWritable:s10,isWritableNodeStream:KG,isWritableStream:i10,isWritableEnded:o10,isWritableFinished:gp0,isWritableErrored:up0,isServerRequest:pp0,isServerResponse:e10,willEmitClose:ip0,isTransformStream:n10}});var F9=L((mR1,F_)=>{var C7=q7(),{AbortError:G40,codes:ap0}=T4(),{ERR_INVALID_ARG_TYPE:rp0,ERR_STREAM_PREMATURE_CLOSE:J40}=ap0,{kEmptyObject:G_,once:H_}=b4(),{validateAbortSignal:sp0,validateFunction:tp0,validateObject:ep0,validateBoolean:Zi0}=nX(),{Promise:Ji0,PromisePrototypeThen:Xi0,SymbolDispose:H40}=F1(),{isClosed:$i0,isReadable:X40,isReadableNodeStream:z_,isReadableStream:Yi0,isReadableFinished:$40,isReadableErrored:Y40,isWritable:Q40,isWritableNodeStream:W40,isWritableStream:Qi0,isWritableFinished:K40,isWritableErrored:z40,isNodeStream:Wi0,willEmitClose:Ki0,kIsClosedPromise:zi0}=U5(),oX;function Gi0(Z){return Z.setHeader&&typeof Z.abort==="function"}var V_=()=>{};function V40(Z,J,X){var $,Y;if(arguments.length===2)X=J,J=G_;else if(J==null)J=G_;else ep0(J,"options");if(tp0(X,"callback"),sp0(J.signal,"options.signal"),X=H_(X),Yi0(Z)||Qi0(Z))return Hi0(Z,J,X);if(!Wi0(Z))throw new rp0("stream",["ReadableStream","WritableStream","Stream"],Z);let Q=($=J.readable)!==null&&$!==void 0?$:z_(Z),W=(Y=J.writable)!==null&&Y!==void 0?Y:W40(Z),K=Z._writableState,z=Z._readableState,G=()=>{if(!Z.writable)F()},H=Ki0(Z)&&z_(Z)===Q&&W40(Z)===W,V=K40(Z,!1),F=()=>{if(V=!0,Z.destroyed)H=!1;if(H&&(!Z.readable||Q))return;if(!Q||B)X.call(Z)},B=$40(Z,!1),U=()=>{if(B=!0,Z.destroyed)H=!1;if(H&&(!Z.writable||W))return;if(!W||V)X.call(Z)},D=(R)=>{X.call(Z,R)},_=$i0(Z),O=()=>{_=!0;let R=z40(Z)||Y40(Z);if(R&&typeof R!=="boolean")return X.call(Z,R);if(Q&&!B&&z_(Z,!0)){if(!$40(Z,!1))return X.call(Z,new J40)}if(W&&!V){if(!K40(Z,!1))return X.call(Z,new J40)}X.call(Z)},w=()=>{_=!0;let R=z40(Z)||Y40(Z);if(R&&typeof R!=="boolean")return X.call(Z,R);X.call(Z)},j=()=>{Z.req.on("finish",F)};if(Gi0(Z)){if(Z.on("complete",F),!H)Z.on("abort",O);if(Z.req)j();else Z.on("request",j)}else if(W&&!K)Z.on("end",G),Z.on("close",G);if(!H&&typeof Z.aborted==="boolean")Z.on("aborted",O);if(Z.on("end",U),Z.on("finish",F),J.error!==!1)Z.on("error",D);if(Z.on("close",O),_)C7.nextTick(O);else if(K!==null&&K!==void 0&&K.errorEmitted||z!==null&&z!==void 0&&z.errorEmitted){if(!H)C7.nextTick(w)}else if(!Q&&(!H||X40(Z))&&(V||Q40(Z)===!1))C7.nextTick(w);else if(!W&&(!H||Q40(Z))&&(B||X40(Z)===!1))C7.nextTick(w);else if(z&&Z.req&&Z.aborted)C7.nextTick(w);let q=()=>{if(X=V_,Z.removeListener("aborted",O),Z.removeListener("complete",F),Z.removeListener("abort",O),Z.removeListener("request",j),Z.req)Z.req.removeListener("finish",F);Z.removeListener("end",G),Z.removeListener("close",G),Z.removeListener("finish",F),Z.removeListener("end",U),Z.removeListener("error",D),Z.removeListener("close",O)};if(J.signal&&!_){let R=()=>{let T=X;q(),T.call(Z,new G40(void 0,{cause:J.signal.reason}))};if(J.signal.aborted)C7.nextTick(R);else{oX=oX||b4().addAbortListener;let T=oX(J.signal,R),y=X;X=H_((...i)=>{T[H40](),y.apply(Z,i)})}}return q}function Hi0(Z,J,X){let $=!1,Y=V_;if(J.signal)if(Y=()=>{$=!0,X.call(Z,new G40(void 0,{cause:J.signal.reason}))},J.signal.aborted)C7.nextTick(Y);else{oX=oX||b4().addAbortListener;let W=oX(J.signal,Y),K=X;X=H_((...z)=>{W[H40](),K.apply(Z,z)})}let Q=(...W)=>{if(!$)C7.nextTick(()=>X.apply(Z,W))};return Xi0(Z[zi0].promise,Q,Q),V_}function Vi0(Z,J){var X;let $=!1;if(J===null)J=G_;if((X=J)!==null&&X!==void 0&&X.cleanup)Zi0(J.cleanup,"cleanup"),$=J.cleanup;return new Ji0((Y,Q)=>{let W=V40(Z,J,(K)=>{if($)W();if(K)Q(K);else Y()})})}F_.exports=V40;F_.exports.finished=Vi0});var uZ=L((dR1,w40)=>{var L5=q7(),{aggregateTwoErrors:Fi0,codes:{ERR_MULTIPLE_CALLBACK:Bi0},AbortError:Ui0}=T4(),{Symbol:U40}=F1(),{kIsDestroyed:Li0,isDestroyed:Di0,isFinished:_i0,isServerRequest:Oi0}=U5(),L40=U40("kDestroy"),B_=U40("kConstruct");function D40(Z,J,X){if(Z){if(Z.stack,J&&!J.errored)J.errored=Z;if(X&&!X.errored)X.errored=Z}}function wi0(Z,J){let X=this._readableState,$=this._writableState,Y=$||X;if($!==null&&$!==void 0&&$.destroyed||X!==null&&X!==void 0&&X.destroyed){if(typeof J==="function")J();return this}if(D40(Z,$,X),$)$.destroyed=!0;if(X)X.destroyed=!0;if(!Y.constructed)this.once(L40,function(Q){F40(this,Fi0(Q,Z),J)});else F40(this,Z,J);return this}function F40(Z,J,X){let $=!1;function Y(Q){if($)return;$=!0;let{_readableState:W,_writableState:K}=Z;if(D40(Q,K,W),K)K.closed=!0;if(W)W.closed=!0;if(typeof X==="function")X(Q);if(Q)L5.nextTick(ji0,Z,Q);else L5.nextTick(_40,Z)}try{Z._destroy(J||null,Y)}catch(Q){Y(Q)}}function ji0(Z,J){U_(Z,J),_40(Z)}function _40(Z){let{_readableState:J,_writableState:X}=Z;if(X)X.closeEmitted=!0;if(J)J.closeEmitted=!0;if(X!==null&&X!==void 0&&X.emitClose||J!==null&&J!==void 0&&J.emitClose)Z.emit("close")}function U_(Z,J){let{_readableState:X,_writableState:$}=Z;if($!==null&&$!==void 0&&$.errorEmitted||X!==null&&X!==void 0&&X.errorEmitted)return;if($)$.errorEmitted=!0;if(X)X.errorEmitted=!0;Z.emit("error",J)}function Mi0(){let Z=this._readableState,J=this._writableState;if(Z)Z.constructed=!0,Z.closed=!1,Z.closeEmitted=!1,Z.destroyed=!1,Z.errored=null,Z.errorEmitted=!1,Z.reading=!1,Z.ended=Z.readable===!1,Z.endEmitted=Z.readable===!1;if(J)J.constructed=!0,J.destroyed=!1,J.closed=!1,J.closeEmitted=!1,J.errored=null,J.errorEmitted=!1,J.finalCalled=!1,J.prefinished=!1,J.ended=J.writable===!1,J.ending=J.writable===!1,J.finished=J.writable===!1}function L_(Z,J,X){let{_readableState:$,_writableState:Y}=Z;if(Y!==null&&Y!==void 0&&Y.destroyed||$!==null&&$!==void 0&&$.destroyed)return this;if($!==null&&$!==void 0&&$.autoDestroy||Y!==null&&Y!==void 0&&Y.autoDestroy)Z.destroy(J);else if(J){if(J.stack,Y&&!Y.errored)Y.errored=J;if($&&!$.errored)$.errored=J;if(X)L5.nextTick(U_,Z,J);else U_(Z,J)}}function Ai0(Z,J){if(typeof Z._construct!=="function")return;let{_readableState:X,_writableState:$}=Z;if(X)X.constructed=!1;if($)$.constructed=!1;if(Z.once(B_,J),Z.listenerCount(B_)>1)return;L5.nextTick(Ti0,Z)}function Ti0(Z){let J=!1;function X($){if(J){L_(Z,$!==null&&$!==void 0?$:new Bi0);return}J=!0;let{_readableState:Y,_writableState:Q}=Z,W=Q||Y;if(Y)Y.constructed=!0;if(Q)Q.constructed=!0;if(W.destroyed)Z.emit(L40,$);else if($)L_(Z,$,!0);else L5.nextTick(qi0,Z)}try{Z._construct(($)=>{L5.nextTick(X,$)})}catch($){L5.nextTick(X,$)}}function qi0(Z){Z.emit(B_)}function B40(Z){return(Z===null||Z===void 0?void 0:Z.setHeader)&&typeof Z.abort==="function"}function O40(Z){Z.emit("close")}function Ci0(Z,J){Z.emit("error",J),L5.nextTick(O40,Z)}function Ni0(Z,J){if(!Z||Di0(Z))return;if(!J&&!_i0(Z))J=new Ui0;if(Oi0(Z))Z.socket=null,Z.destroy(J);else if(B40(Z))Z.abort();else if(B40(Z.req))Z.req.abort();else if(typeof Z.destroy==="function")Z.destroy(J);else if(typeof Z.close==="function")Z.close();else if(J)L5.nextTick(Ci0,Z,J);else L5.nextTick(O40,Z);if(!Z.destroyed)Z[Li0]=!0}w40.exports={construct:Ai0,destroyer:Ni0,destroy:wi0,undestroy:Mi0,errorOrDestroy:L_}});var VG=L((uR1,M40)=>{var{ArrayIsArray:Ri0,ObjectSetPrototypeOf:j40}=F1(),{EventEmitter:GG}=N("events");function HG(Z){GG.call(this,Z)}j40(HG.prototype,GG.prototype);j40(HG,GG);HG.prototype.pipe=function(Z,J){let X=this;function $(H){if(Z.writable&&Z.write(H)===!1&&X.pause)X.pause()}X.on("data",$);function Y(){if(X.readable&&X.resume)X.resume()}if(Z.on("drain",Y),!Z._isStdio&&(!J||J.end!==!1))X.on("end",W),X.on("close",K);let Q=!1;function W(){if(Q)return;Q=!0,Z.end()}function K(){if(Q)return;if(Q=!0,typeof Z.destroy==="function")Z.destroy()}function z(H){if(G(),GG.listenerCount(this,"error")===0)this.emit("error",H)}D_(X,"error",z),D_(Z,"error",z);function G(){X.removeListener("data",$),Z.removeListener("drain",Y),X.removeListener("end",W),X.removeListener("close",K),X.removeListener("error",z),Z.removeListener("error",z),X.removeListener("end",G),X.removeListener("close",G),Z.removeListener("close",G)}return X.on("end",G),X.on("close",G),Z.on("close",G),Z.emit("pipe",X),Z};function D_(Z,J,X){if(typeof Z.prependListener==="function")return Z.prependListener(J,X);if(!Z._events||!Z._events[J])Z.on(J,X);else if(Ri0(Z._events[J]))Z._events[J].unshift(X);else Z._events[J]=[X,Z._events[J]]}M40.exports={Stream:HG,prependListener:D_}});var x3=L((xi0,FG)=>{var{SymbolDispose:Pi0}=F1(),{AbortError:A40,codes:Ei0}=T4(),{isNodeStream:T40,isWebStream:Ii0,kControllerErrorFunction:yi0}=U5(),Si0=F9(),{ERR_INVALID_ARG_TYPE:q40}=Ei0,__,ki0=(Z,J)=>{if(typeof Z!=="object"||!("aborted"in Z))throw new q40(J,"AbortSignal",Z)};xi0.addAbortSignal=function(J,X){if(ki0(J,"signal"),!T40(X)&&!Ii0(X))throw new q40("stream",["ReadableStream","WritableStream","Stream"],X);return xi0.addAbortSignalNoValidate(J,X)};xi0.addAbortSignalNoValidate=function(Z,J){if(typeof Z!=="object"||!("aborted"in Z))return J;let X=T40(J)?()=>{J.destroy(new A40(void 0,{cause:Z.reason}))}:()=>{J[yi0](new A40(void 0,{cause:Z.reason}))};if(Z.aborted)X();else{__=__||b4().addAbortListener;let $=__(Z,X);Si0(J,$[Pi0])}return J}});var R40=L((cR1,N40)=>{var{StringPrototypeSlice:C40,SymbolIterator:fi0,TypedArrayPrototypeSet:BG,Uint8Array:bi0}=F1(),{Buffer:O_}=N("buffer"),{inspect:gi0}=b4();N40.exports=class{constructor(){this.head=null,this.tail=null,this.length=0}push(J){let X={data:J,next:null};if(this.length>0)this.tail.next=X;else this.head=X;this.tail=X,++this.length}unshift(J){let X={data:J,next:this.head};if(this.length===0)this.tail=X;this.head=X,++this.length}shift(){if(this.length===0)return;let J=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;return--this.length,J}clear(){this.head=this.tail=null,this.length=0}join(J){if(this.length===0)return"";let X=this.head,$=""+X.data;while((X=X.next)!==null)$+=J+X.data;return $}concat(J){if(this.length===0)return O_.alloc(0);let X=O_.allocUnsafe(J>>>0),$=this.head,Y=0;while($)BG(X,$.data,Y),Y+=$.data.length,$=$.next;return X}consume(J,X){let $=this.head.data;if(J<$.length){let Y=$.slice(0,J);return this.head.data=$.slice(J),Y}if(J===$.length)return this.shift();return X?this._getString(J):this._getBuffer(J)}first(){return this.head.data}*[fi0](){for(let J=this.head;J;J=J.next)yield J.data}_getString(J){let X="",$=this.head,Y=0;do{let Q=$.data;if(J>Q.length)X+=Q,J-=Q.length;else{if(J===Q.length)if(X+=Q,++Y,$.next)this.head=$.next;else this.head=this.tail=null;else X+=C40(Q,0,J),this.head=$,$.data=C40(Q,J);break}++Y}while(($=$.next)!==null);return this.length-=Y,X}_getBuffer(J){let X=O_.allocUnsafe(J),$=J,Y=this.head,Q=0;do{let W=Y.data;if(J>W.length)BG(X,W,$-J),J-=W.length;else{if(J===W.length)if(BG(X,W,$-J),++Q,Y.next)this.head=Y.next;else this.head=this.tail=null;else BG(X,new bi0(W.buffer,W.byteOffset,J),$-J),this.head=Y,Y.data=W.slice(J);break}++Q}while((Y=Y.next)!==null);return this.length-=Q,X}[Symbol.for("nodejs.util.inspect.custom")](J,X){return gi0(this,{...X,depth:0,customInspect:!1})}}});var v3=L((lR1,y40)=>{var{MathFloor:mi0,NumberIsInteger:di0}=F1(),{validateInteger:ui0}=nX(),{ERR_INVALID_ARG_VALUE:ci0}=T4().codes,P40=16384,E40=16;function li0(Z,J,X){return Z.highWaterMark!=null?Z.highWaterMark:J?Z[X]:null}function I40(Z){return Z?E40:P40}function pi0(Z,J){if(ui0(J,"value",0),Z)E40=J;else P40=J}function ii0(Z,J,X,$){let Y=li0(J,$,X);if(Y!=null){if(!di0(Y)||Y<0){let Q=$?`options.${X}`:"options.highWaterMark";throw new ci0(Q,Y)}return mi0(Y)}return I40(Z.objectMode)}y40.exports={getHighWaterMark:ii0,getDefaultHighWaterMark:I40,setDefaultHighWaterMark:pi0}});var x40=L((w_,k40)=>{/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var UG=N("buffer"),D5=UG.Buffer;function S40(Z,J){for(var X in Z)J[X]=Z[X]}if(D5.from&&D5.alloc&&D5.allocUnsafe&&D5.allocUnsafeSlow)k40.exports=UG;else S40(UG,w_),w_.Buffer=cZ;function cZ(Z,J,X){return D5(Z,J,X)}cZ.prototype=Object.create(D5.prototype);S40(D5,cZ);cZ.from=function(Z,J,X){if(typeof Z==="number")throw TypeError("Argument must not be a number");return D5(Z,J,X)};cZ.alloc=function(Z,J,X){if(typeof Z!=="number")throw TypeError("Argument must be a number");var $=D5(Z);if(J!==void 0)if(typeof X==="string")$.fill(J,X);else $.fill(J);else $.fill(0);return $};cZ.allocUnsafe=function(Z){if(typeof Z!=="number")throw TypeError("Argument must be a number");return D5(Z)};cZ.allocUnsafeSlow=function(Z){if(typeof Z!=="number")throw TypeError("Argument must be a number");return UG.SlowBuffer(Z)}});var h40=L((Wn0)=>{var M_=x40().Buffer,v40=M_.isEncoding||function(Z){switch(Z=""+Z,Z&&Z.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function ni0(Z){if(!Z)return"utf8";var J;while(!0)switch(Z){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return Z;default:if(J)return;Z=(""+Z).toLowerCase(),J=!0}}function oi0(Z){var J=ni0(Z);if(typeof J!=="string"&&(M_.isEncoding===v40||!v40(Z)))throw Error("Unknown encoding: "+Z);return J||Z}Wn0.StringDecoder=h3;function h3(Z){this.encoding=oi0(Z);var J;switch(this.encoding){case"utf16le":this.text=Zn0,this.end=Jn0,J=4;break;case"utf8":this.fillLast=si0,J=4;break;case"base64":this.text=Xn0,this.end=$n0,J=3;break;default:this.write=Yn0,this.end=Qn0;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=M_.allocUnsafe(J)}h3.prototype.write=function(Z){if(Z.length===0)return"";var J,X;if(this.lastNeed){if(J=this.fillLast(Z),J===void 0)return"";X=this.lastNeed,this.lastNeed=0}else X=0;if(X<Z.length)return J?J+this.text(Z,X):this.text(Z,X);return J||""};h3.prototype.end=ei0;h3.prototype.text=ti0;h3.prototype.fillLast=function(Z){if(this.lastNeed<=Z.length)return Z.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);Z.copy(this.lastChar,this.lastTotal-this.lastNeed,0,Z.length),this.lastNeed-=Z.length};function j_(Z){if(Z<=127)return 0;else if(Z>>5===6)return 2;else if(Z>>4===14)return 3;else if(Z>>3===30)return 4;return Z>>6===2?-1:-2}function ai0(Z,J,X){var $=J.length-1;if($<X)return 0;var Y=j_(J[$]);if(Y>=0){if(Y>0)Z.lastNeed=Y-1;return Y}if(--$<X||Y===-2)return 0;if(Y=j_(J[$]),Y>=0){if(Y>0)Z.lastNeed=Y-2;return Y}if(--$<X||Y===-2)return 0;if(Y=j_(J[$]),Y>=0){if(Y>0)if(Y===2)Y=0;else Z.lastNeed=Y-3;return Y}return 0}function ri0(Z,J,X){if((J[0]&192)!==128)return Z.lastNeed=0,"\uFFFD";if(Z.lastNeed>1&&J.length>1){if((J[1]&192)!==128)return Z.lastNeed=1,"\uFFFD";if(Z.lastNeed>2&&J.length>2){if((J[2]&192)!==128)return Z.lastNeed=2,"\uFFFD"}}}function si0(Z){var J=this.lastTotal-this.lastNeed,X=ri0(this,Z,J);if(X!==void 0)return X;if(this.lastNeed<=Z.length)return Z.copy(this.lastChar,J,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);Z.copy(this.lastChar,J,0,Z.length),this.lastNeed-=Z.length}function ti0(Z,J){var X=ai0(this,Z,J);if(!this.lastNeed)return Z.toString("utf8",J);this.lastTotal=X;var $=Z.length-(X-this.lastNeed);return Z.copy(this.lastChar,0,$),Z.toString("utf8",J,$)}function ei0(Z){var J=Z&&Z.length?this.write(Z):"";if(this.lastNeed)return J+"\uFFFD";return J}function Zn0(Z,J){if((Z.length-J)%2===0){var X=Z.toString("utf16le",J);if(X){var $=X.charCodeAt(X.length-1);if($>=55296&&$<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=Z[Z.length-2],this.lastChar[1]=Z[Z.length-1],X.slice(0,-1)}return X}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=Z[Z.length-1],Z.toString("utf16le",J,Z.length-1)}function Jn0(Z){var J=Z&&Z.length?this.write(Z):"";if(this.lastNeed){var X=this.lastTotal-this.lastNeed;return J+this.lastChar.toString("utf16le",0,X)}return J}function Xn0(Z,J){var X=(Z.length-J)%3;if(X===0)return Z.toString("base64",J);if(this.lastNeed=3-X,this.lastTotal=3,X===1)this.lastChar[0]=Z[Z.length-1];else this.lastChar[0]=Z[Z.length-2],this.lastChar[1]=Z[Z.length-1];return Z.toString("base64",J,Z.length-X)}function $n0(Z){var J=Z&&Z.length?this.write(Z):"";if(this.lastNeed)return J+this.lastChar.toString("base64",0,3-this.lastNeed);return J}function Yn0(Z){return Z.toString(this.encoding)}function Qn0(Z){return Z&&Z.length?this.write(Z):""}});var A_=L((iR1,m40)=>{var f40=q7(),{PromisePrototypeThen:zn0,SymbolAsyncIterator:b40,SymbolIterator:g40}=F1(),{Buffer:Gn0}=N("buffer"),{ERR_INVALID_ARG_TYPE:Hn0,ERR_STREAM_NULL_VALUES:Vn0}=T4().codes;function Fn0(Z,J,X){let $;if(typeof J==="string"||J instanceof Gn0)return new Z({objectMode:!0,...X,read(){this.push(J),this.push(null)}});let Y;if(J&&J[b40])Y=!0,$=J[b40]();else if(J&&J[g40])Y=!1,$=J[g40]();else throw new Hn0("iterable",["Iterable"],J);let Q=new Z({objectMode:!0,highWaterMark:1,...X}),W=!1;Q._read=function(){if(!W)W=!0,z()},Q._destroy=function(G,H){zn0(K(G),()=>f40.nextTick(H,G),(V)=>f40.nextTick(H,V||G))};async function K(G){let H=G!==void 0&&G!==null,V=typeof $.throw==="function";if(H&&V){let{value:F,done:B}=await $.throw(G);if(await F,B)return}if(typeof $.return==="function"){let{value:F}=await $.return();await F}}async function z(){for(;;){try{let{value:G,done:H}=Y?await $.next():$.next();if(H)Q.push(null);else{let V=G&&typeof G.then==="function"?await G:G;if(V===null)throw W=!1,new Vn0;else if(Q.push(V))continue;else W=!1}}catch(G){Q.destroy(G)}break}}return Q}m40.exports=Fn0});var b3=L((nR1,Y60)=>{var h8=q7(),{ArrayPrototypeIndexOf:Bn0,NumberIsInteger:Un0,NumberIsNaN:Ln0,NumberParseInt:Dn0,ObjectDefineProperties:I_,ObjectKeys:_n0,ObjectSetPrototypeOf:c40,Promise:l40,SafeSet:On0,SymbolAsyncDispose:wn0,SymbolAsyncIterator:jn0,Symbol:Mn0}=F1();Y60.exports=q0;q0.ReadableState=OG;var{EventEmitter:An0}=N("events"),{Stream:N7,prependListener:Tn0}=VG(),{Buffer:T_}=N("buffer"),{addAbortSignal:qn0}=x3(),p40=F9(),y0=b4().debuglog("stream",(Z)=>{y0=Z}),Cn0=R40(),sX=uZ(),{getHighWaterMark:Nn0,getDefaultHighWaterMark:Rn0}=v3(),{aggregateTwoErrors:d40,codes:{ERR_INVALID_ARG_TYPE:Pn0,ERR_METHOD_NOT_IMPLEMENTED:En0,ERR_OUT_OF_RANGE:In0,ERR_STREAM_PUSH_AFTER_EOF:yn0,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:Sn0},AbortError:kn0}=T4(),{validateObject:xn0}=nX(),lZ=Mn0("kPaused"),{StringDecoder:i40}=h40(),vn0=A_();c40(q0.prototype,N7.prototype);c40(q0,N7);var q_=()=>{},{errorOrDestroy:aX}=sX,rX=1,hn0=2,n40=4,f3=8,o40=16,LG=32,DG=64,a40=128,fn0=256,bn0=512,gn0=1024,P_=2048,E_=4096,mn0=8192,dn0=16384,un0=32768,r40=65536,cn0=131072,ln0=262144;function i1(Z){return{enumerable:!1,get(){return(this.state&Z)!==0},set(J){if(J)this.state|=Z;else this.state&=~Z}}}I_(OG.prototype,{objectMode:i1(rX),ended:i1(hn0),endEmitted:i1(n40),reading:i1(f3),constructed:i1(o40),sync:i1(LG),needReadable:i1(DG),emittedReadable:i1(a40),readableListening:i1(fn0),resumeScheduled:i1(bn0),errorEmitted:i1(gn0),emitClose:i1(P_),autoDestroy:i1(E_),destroyed:i1(mn0),closed:i1(dn0),closeEmitted:i1(un0),multiAwaitDrain:i1(r40),readingMore:i1(cn0),dataEmitted:i1(ln0)});function OG(Z,J,X){if(typeof X!=="boolean")X=J instanceof _5();if(this.state=P_|E_|o40|LG,Z&&Z.objectMode)this.state|=rX;if(X&&Z&&Z.readableObjectMode)this.state|=rX;if(this.highWaterMark=Z?Nn0(this,Z,"readableHighWaterMark",X):Rn0(!1),this.buffer=new Cn0,this.length=0,this.pipes=[],this.flowing=null,this[lZ]=null,Z&&Z.emitClose===!1)this.state&=~P_;if(Z&&Z.autoDestroy===!1)this.state&=~E_;if(this.errored=null,this.defaultEncoding=Z&&Z.defaultEncoding||"utf8",this.awaitDrainWriters=null,this.decoder=null,this.encoding=null,Z&&Z.encoding)this.decoder=new i40(Z.encoding),this.encoding=Z.encoding}function q0(Z){if(!(this instanceof q0))return new q0(Z);let J=this instanceof _5();if(this._readableState=new OG(Z,this,J),Z){if(typeof Z.read==="function")this._read=Z.read;if(typeof Z.destroy==="function")this._destroy=Z.destroy;if(typeof Z.construct==="function")this._construct=Z.construct;if(Z.signal&&!J)qn0(Z.signal,this)}N7.call(this,Z),sX.construct(this,()=>{if(this._readableState.needReadable)_G(this,this._readableState)})}q0.prototype.destroy=sX.destroy;q0.prototype._undestroy=sX.undestroy;q0.prototype._destroy=function(Z,J){J(Z)};q0.prototype[An0.captureRejectionSymbol]=function(Z){this.destroy(Z)};q0.prototype[wn0]=function(){let Z;if(!this.destroyed)Z=this.readableEnded?null:new kn0,this.destroy(Z);return new l40((J,X)=>p40(this,($)=>$&&$!==Z?X($):J(null)))};q0.prototype.push=function(Z,J){return s40(this,Z,J,!1)};q0.prototype.unshift=function(Z,J){return s40(this,Z,J,!0)};function s40(Z,J,X,$){y0("readableAddChunk",J);let Y=Z._readableState,Q;if((Y.state&rX)===0){if(typeof J==="string"){if(X=X||Y.defaultEncoding,Y.encoding!==X)if($&&Y.encoding)J=T_.from(J,X).toString(Y.encoding);else J=T_.from(J,X),X=""}else if(J instanceof T_)X="";else if(N7._isUint8Array(J))J=N7._uint8ArrayToBuffer(J),X="";else if(J!=null)Q=new Pn0("chunk",["string","Buffer","Uint8Array"],J)}if(Q)aX(Z,Q);else if(J===null)Y.state&=~f3,nn0(Z,Y);else if((Y.state&rX)!==0||J&&J.length>0)if($)if((Y.state&n40)!==0)aX(Z,new Sn0);else if(Y.destroyed||Y.errored)return!1;else C_(Z,Y,J,!0);else if(Y.ended)aX(Z,new yn0);else if(Y.destroyed||Y.errored)return!1;else if(Y.state&=~f3,Y.decoder&&!X)if(J=Y.decoder.write(J),Y.objectMode||J.length!==0)C_(Z,Y,J,!1);else _G(Z,Y);else C_(Z,Y,J,!1);else if(!$)Y.state&=~f3,_G(Z,Y);return!Y.ended&&(Y.length<Y.highWaterMark||Y.length===0)}function C_(Z,J,X,$){if(J.flowing&&J.length===0&&!J.sync&&Z.listenerCount("data")>0){if((J.state&r40)!==0)J.awaitDrainWriters.clear();else J.awaitDrainWriters=null;J.dataEmitted=!0,Z.emit("data",X)}else{if(J.length+=J.objectMode?1:X.length,$)J.buffer.unshift(X);else J.buffer.push(X);if((J.state&DG)!==0)wG(Z)}_G(Z,J)}q0.prototype.isPaused=function(){let Z=this._readableState;return Z[lZ]===!0||Z.flowing===!1};q0.prototype.setEncoding=function(Z){let J=new i40(Z);this._readableState.decoder=J,this._readableState.encoding=this._readableState.decoder.encoding;let X=this._readableState.buffer,$="";for(let Y of X)$+=J.write(Y);if(X.clear(),$!=="")X.push($);return this._readableState.length=$.length,this};var pn0=1073741824;function in0(Z){if(Z>pn0)throw new In0("size","<= 1GiB",Z);else Z--,Z|=Z>>>1,Z|=Z>>>2,Z|=Z>>>4,Z|=Z>>>8,Z|=Z>>>16,Z++;return Z}function u40(Z,J){if(Z<=0||J.length===0&&J.ended)return 0;if((J.state&rX)!==0)return 1;if(Ln0(Z)){if(J.flowing&&J.length)return J.buffer.first().length;return J.length}if(Z<=J.length)return Z;return J.ended?J.length:0}q0.prototype.read=function(Z){if(y0("read",Z),Z===void 0)Z=NaN;else if(!Un0(Z))Z=Dn0(Z,10);let J=this._readableState,X=Z;if(Z>J.highWaterMark)J.highWaterMark=in0(Z);if(Z!==0)J.state&=~a40;if(Z===0&&J.needReadable&&((J.highWaterMark!==0?J.length>=J.highWaterMark:J.length>0)||J.ended)){if(y0("read: emitReadable",J.length,J.ended),J.length===0&&J.ended)N_(this);else wG(this);return null}if(Z=u40(Z,J),Z===0&&J.ended){if(J.length===0)N_(this);return null}let $=(J.state&DG)!==0;if(y0("need readable",$),J.length===0||J.length-Z<J.highWaterMark)$=!0,y0("length less than watermark",$);if(J.ended||J.reading||J.destroyed||J.errored||!J.constructed)$=!1,y0("reading, ended or constructing",$);else if($){if(y0("do read"),J.state|=f3|LG,J.length===0)J.state|=DG;try{this._read(J.highWaterMark)}catch(Q){aX(this,Q)}if(J.state&=~LG,!J.reading)Z=u40(X,J)}let Y;if(Z>0)Y=X60(Z,J);else Y=null;if(Y===null)J.needReadable=J.length<=J.highWaterMark,Z=0;else if(J.length-=Z,J.multiAwaitDrain)J.awaitDrainWriters.clear();else J.awaitDrainWriters=null;if(J.length===0){if(!J.ended)J.needReadable=!0;if(X!==Z&&J.ended)N_(this)}if(Y!==null&&!J.errorEmitted&&!J.closeEmitted)J.dataEmitted=!0,this.emit("data",Y);return Y};function nn0(Z,J){if(y0("onEofChunk"),J.ended)return;if(J.decoder){let X=J.decoder.end();if(X&&X.length)J.buffer.push(X),J.length+=J.objectMode?1:X.length}if(J.ended=!0,J.sync)wG(Z);else J.needReadable=!1,J.emittedReadable=!0,t40(Z)}function wG(Z){let J=Z._readableState;if(y0("emitReadable",J.needReadable,J.emittedReadable),J.needReadable=!1,!J.emittedReadable)y0("emitReadable",J.flowing),J.emittedReadable=!0,h8.nextTick(t40,Z)}function t40(Z){let J=Z._readableState;if(y0("emitReadable_",J.destroyed,J.length,J.ended),!J.destroyed&&!J.errored&&(J.length||J.ended))Z.emit("readable"),J.emittedReadable=!1;J.needReadable=!J.flowing&&!J.ended&&J.length<=J.highWaterMark,Z60(Z)}function _G(Z,J){if(!J.readingMore&&J.constructed)J.readingMore=!0,h8.nextTick(on0,Z,J)}function on0(Z,J){while(!J.reading&&!J.ended&&(J.length<J.highWaterMark||J.flowing&&J.length===0)){let X=J.length;if(y0("maybeReadMore read 0"),Z.read(0),X===J.length)break}J.readingMore=!1}q0.prototype._read=function(Z){throw new En0("_read()")};q0.prototype.pipe=function(Z,J){let X=this,$=this._readableState;if($.pipes.length===1){if(!$.multiAwaitDrain)$.multiAwaitDrain=!0,$.awaitDrainWriters=new On0($.awaitDrainWriters?[$.awaitDrainWriters]:[])}$.pipes.push(Z),y0("pipe count=%d opts=%j",$.pipes.length,J);let Q=(!J||J.end!==!1)&&Z!==h8.stdout&&Z!==h8.stderr?K:_;if($.endEmitted)h8.nextTick(Q);else X.once("end",Q);Z.on("unpipe",W);function W(O,w){if(y0("onunpipe"),O===X){if(w&&w.hasUnpiped===!1)w.hasUnpiped=!0,H()}}function K(){y0("onend"),Z.end()}let z,G=!1;function H(){if(y0("cleanup"),Z.removeListener("close",U),Z.removeListener("finish",D),z)Z.removeListener("drain",z);if(Z.removeListener("error",B),Z.removeListener("unpipe",W),X.removeListener("end",K),X.removeListener("end",_),X.removeListener("data",F),G=!0,z&&$.awaitDrainWriters&&(!Z._writableState||Z._writableState.needDrain))z()}function V(){if(!G){if($.pipes.length===1&&$.pipes[0]===Z)y0("false write response, pause",0),$.awaitDrainWriters=Z,$.multiAwaitDrain=!1;else if($.pipes.length>1&&$.pipes.includes(Z))y0("false write response, pause",$.awaitDrainWriters.size),$.awaitDrainWriters.add(Z);X.pause()}if(!z)z=an0(X,Z),Z.on("drain",z)}X.on("data",F);function F(O){y0("ondata");let w=Z.write(O);if(y0("dest.write",w),w===!1)V()}function B(O){if(y0("onerror",O),_(),Z.removeListener("error",B),Z.listenerCount("error")===0){let w=Z._writableState||Z._readableState;if(w&&!w.errorEmitted)aX(Z,O);else Z.emit("error",O)}}Tn0(Z,"error",B);function U(){Z.removeListener("finish",D),_()}Z.once("close",U);function D(){y0("onfinish"),Z.removeListener("close",U),_()}Z.once("finish",D);function _(){y0("unpipe"),X.unpipe(Z)}if(Z.emit("pipe",X),Z.writableNeedDrain===!0)V();else if(!$.flowing)y0("pipe resume"),X.resume();return Z};function an0(Z,J){return function(){let $=Z._readableState;if($.awaitDrainWriters===J)y0("pipeOnDrain",1),$.awaitDrainWriters=null;else if($.multiAwaitDrain)y0("pipeOnDrain",$.awaitDrainWriters.size),$.awaitDrainWriters.delete(J);if((!$.awaitDrainWriters||$.awaitDrainWriters.size===0)&&Z.listenerCount("data"))Z.resume()}}q0.prototype.unpipe=function(Z){let J=this._readableState,X={hasUnpiped:!1};if(J.pipes.length===0)return this;if(!Z){let Y=J.pipes;J.pipes=[],this.pause();for(let Q=0;Q<Y.length;Q++)Y[Q].emit("unpipe",this,{hasUnpiped:!1});return this}let $=Bn0(J.pipes,Z);if($===-1)return this;if(J.pipes.splice($,1),J.pipes.length===0)this.pause();return Z.emit("unpipe",this,X),this};q0.prototype.on=function(Z,J){let X=N7.prototype.on.call(this,Z,J),$=this._readableState;if(Z==="data"){if($.readableListening=this.listenerCount("readable")>0,$.flowing!==!1)this.resume()}else if(Z==="readable"){if(!$.endEmitted&&!$.readableListening){if($.readableListening=$.needReadable=!0,$.flowing=!1,$.emittedReadable=!1,y0("on readable",$.length,$.reading),$.length)wG(this);else if(!$.reading)h8.nextTick(rn0,this)}}return X};q0.prototype.addListener=q0.prototype.on;q0.prototype.removeListener=function(Z,J){let X=N7.prototype.removeListener.call(this,Z,J);if(Z==="readable")h8.nextTick(e40,this);return X};q0.prototype.off=q0.prototype.removeListener;q0.prototype.removeAllListeners=function(Z){let J=N7.prototype.removeAllListeners.apply(this,arguments);if(Z==="readable"||Z===void 0)h8.nextTick(e40,this);return J};function e40(Z){let J=Z._readableState;if(J.readableListening=Z.listenerCount("readable")>0,J.resumeScheduled&&J[lZ]===!1)J.flowing=!0;else if(Z.listenerCount("data")>0)Z.resume();else if(!J.readableListening)J.flowing=null}function rn0(Z){y0("readable nexttick read 0"),Z.read(0)}q0.prototype.resume=function(){let Z=this._readableState;if(!Z.flowing)y0("resume"),Z.flowing=!Z.readableListening,sn0(this,Z);return Z[lZ]=!1,this};function sn0(Z,J){if(!J.resumeScheduled)J.resumeScheduled=!0,h8.nextTick(tn0,Z,J)}function tn0(Z,J){if(y0("resume",J.reading),!J.reading)Z.read(0);if(J.resumeScheduled=!1,Z.emit("resume"),Z60(Z),J.flowing&&!J.reading)Z.read(0)}q0.prototype.pause=function(){if(y0("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1)y0("pause"),this._readableState.flowing=!1,this.emit("pause");return this._readableState[lZ]=!0,this};function Z60(Z){let J=Z._readableState;y0("flow",J.flowing);while(J.flowing&&Z.read()!==null);}q0.prototype.wrap=function(Z){let J=!1;Z.on("data",($)=>{if(!this.push($)&&Z.pause)J=!0,Z.pause()}),Z.on("end",()=>{this.push(null)}),Z.on("error",($)=>{aX(this,$)}),Z.on("close",()=>{this.destroy()}),Z.on("destroy",()=>{this.destroy()}),this._read=()=>{if(J&&Z.resume)J=!1,Z.resume()};let X=_n0(Z);for(let $=1;$<X.length;$++){let Y=X[$];if(this[Y]===void 0&&typeof Z[Y]==="function")this[Y]=Z[Y].bind(Z)}return this};q0.prototype[jn0]=function(){return J60(this)};q0.prototype.iterator=function(Z){if(Z!==void 0)xn0(Z,"options");return J60(this,Z)};function J60(Z,J){if(typeof Z.read!=="function")Z=q0.wrap(Z,{objectMode:!0});let X=en0(Z,J);return X.stream=Z,X}async function*en0(Z,J){let X=q_;function $(W){if(this===Z)X(),X=q_;else X=W}Z.on("readable",$);let Y,Q=p40(Z,{writable:!1},(W)=>{Y=W?d40(Y,W):null,X(),X=q_});try{while(!0){let W=Z.destroyed?null:Z.read();if(W!==null)yield W;else if(Y)throw Y;else if(Y===null)return;else await new l40($)}}catch(W){throw Y=d40(Y,W),Y}finally{if((Y||(J===null||J===void 0?void 0:J.destroyOnReturn)!==!1)&&(Y===void 0||Z._readableState.autoDestroy))sX.destroyer(Z,null);else Z.off("readable",$),Q()}}I_(q0.prototype,{readable:{__proto__:null,get(){let Z=this._readableState;return!!Z&&Z.readable!==!1&&!Z.destroyed&&!Z.errorEmitted&&!Z.endEmitted},set(Z){if(this._readableState)this._readableState.readable=!!Z}},readableDidRead:{__proto__:null,enumerable:!1,get:function(){return this._readableState.dataEmitted}},readableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._readableState.readable!==!1&&(this._readableState.destroyed||this._readableState.errored)&&!this._readableState.endEmitted)}},readableHighWaterMark:{__proto__:null,enumerable:!1,get:function(){return this._readableState.highWaterMark}},readableBuffer:{__proto__:null,enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}},readableFlowing:{__proto__:null,enumerable:!1,get:function(){return this._readableState.flowing},set:function(Z){if(this._readableState)this._readableState.flowing=Z}},readableLength:{__proto__:null,enumerable:!1,get(){return this._readableState.length}},readableObjectMode:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.objectMode:!1}},readableEncoding:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.encoding:null}},errored:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.errored:null}},closed:{__proto__:null,get(){return this._readableState?this._readableState.closed:!1}},destroyed:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.destroyed:!1},set(Z){if(!this._readableState)return;this._readableState.destroyed=Z}},readableEnded:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.endEmitted:!1}}});I_(OG.prototype,{pipesCount:{__proto__:null,get(){return this.pipes.length}},paused:{__proto__:null,get(){return this[lZ]!==!1},set(Z){this[lZ]=!!Z}}});q0._fromList=X60;function X60(Z,J){if(J.length===0)return null;let X;if(J.objectMode)X=J.buffer.shift();else if(!Z||Z>=J.length){if(J.decoder)X=J.buffer.join("");else if(J.buffer.length===1)X=J.buffer.first();else X=J.buffer.concat(J.length);J.buffer.clear()}else X=J.buffer.consume(Z,J.decoder);return X}function N_(Z){let J=Z._readableState;if(y0("endReadable",J.endEmitted),!J.endEmitted)J.ended=!0,h8.nextTick(Zo0,J,Z)}function Zo0(Z,J){if(y0("endReadableNT",Z.endEmitted,Z.length),!Z.errored&&!Z.closeEmitted&&!Z.endEmitted&&Z.length===0){if(Z.endEmitted=!0,J.emit("end"),J.writable&&J.allowHalfOpen===!1)h8.nextTick(Jo0,J);else if(Z.autoDestroy){let X=J._writableState;if(!X||X.autoDestroy&&(X.finished||X.writable===!1))J.destroy()}}}function Jo0(Z){if(Z.writable&&!Z.writableEnded&&!Z.destroyed)Z.end()}q0.from=function(Z,J){return vn0(q0,Z,J)};var R_;function $60(){if(R_===void 0)R_={};return R_}q0.fromWeb=function(Z,J){return $60().newStreamReadableFromReadableStream(Z,J)};q0.toWeb=function(Z,J){return $60().newReadableStreamFromStreamReadable(Z,J)};q0.wrap=function(Z,J){var X,$;return new q0({objectMode:(X=($=Z.readableObjectMode)!==null&&$!==void 0?$:Z.objectMode)!==null&&X!==void 0?X:!0,...J,destroy(Y,Q){sX.destroyer(Z,Y),Q(Y)}}).wrap(Z)}});var qG=L((oR1,D60)=>{var pZ=q7(),{ArrayPrototypeSlice:K60,Error:Xo0,FunctionPrototypeSymbolHasInstance:z60,ObjectDefineProperty:G60,ObjectDefineProperties:$o0,ObjectSetPrototypeOf:H60,StringPrototypeToLowerCase:Yo0,Symbol:Qo0,SymbolHasInstance:Wo0}=F1();D60.exports=M1;M1.WritableState=d3;var{EventEmitter:Ko0}=N("events"),g3=VG().Stream,{Buffer:jG}=N("buffer"),TG=uZ(),{addAbortSignal:zo0}=x3(),{getHighWaterMark:Go0,getDefaultHighWaterMark:Ho0}=v3(),{ERR_INVALID_ARG_TYPE:Vo0,ERR_METHOD_NOT_IMPLEMENTED:Fo0,ERR_MULTIPLE_CALLBACK:V60,ERR_STREAM_CANNOT_PIPE:Bo0,ERR_STREAM_DESTROYED:m3,ERR_STREAM_ALREADY_FINISHED:Uo0,ERR_STREAM_NULL_VALUES:Lo0,ERR_STREAM_WRITE_AFTER_END:Do0,ERR_UNKNOWN_ENCODING:F60}=T4().codes,{errorOrDestroy:tX}=TG;H60(M1.prototype,g3.prototype);H60(M1,g3);function k_(){}var eX=Qo0("kOnFinished");function d3(Z,J,X){if(typeof X!=="boolean")X=J instanceof _5();if(this.objectMode=!!(Z&&Z.objectMode),X)this.objectMode=this.objectMode||!!(Z&&Z.writableObjectMode);this.highWaterMark=Z?Go0(this,Z,"writableHighWaterMark",X):Ho0(!1),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;let $=!!(Z&&Z.decodeStrings===!1);this.decodeStrings=!$,this.defaultEncoding=Z&&Z.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=Oo0.bind(void 0,J),this.writecb=null,this.writelen=0,this.afterWriteTickInfo=null,AG(this),this.pendingcb=0,this.constructed=!0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!Z||Z.emitClose!==!1,this.autoDestroy=!Z||Z.autoDestroy!==!1,this.errored=null,this.closed=!1,this.closeEmitted=!1,this[eX]=[]}function AG(Z){Z.buffered=[],Z.bufferedIndex=0,Z.allBuffers=!0,Z.allNoop=!0}d3.prototype.getBuffer=function(){return K60(this.buffered,this.bufferedIndex)};G60(d3.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}});function M1(Z){let J=this instanceof _5();if(!J&&!z60(M1,this))return new M1(Z);if(this._writableState=new d3(Z,this,J),Z){if(typeof Z.write==="function")this._write=Z.write;if(typeof Z.writev==="function")this._writev=Z.writev;if(typeof Z.destroy==="function")this._destroy=Z.destroy;if(typeof Z.final==="function")this._final=Z.final;if(typeof Z.construct==="function")this._construct=Z.construct;if(Z.signal)zo0(Z.signal,this)}g3.call(this,Z),TG.construct(this,()=>{let X=this._writableState;if(!X.writing)v_(this,X);h_(this,X)})}G60(M1,Wo0,{__proto__:null,value:function(Z){if(z60(this,Z))return!0;if(this!==M1)return!1;return Z&&Z._writableState instanceof d3}});M1.prototype.pipe=function(){tX(this,new Bo0)};function B60(Z,J,X,$){let Y=Z._writableState;if(typeof X==="function")$=X,X=Y.defaultEncoding;else{if(!X)X=Y.defaultEncoding;else if(X!=="buffer"&&!jG.isEncoding(X))throw new F60(X);if(typeof $!=="function")$=k_}if(J===null)throw new Lo0;else if(!Y.objectMode)if(typeof J==="string"){if(Y.decodeStrings!==!1)J=jG.from(J,X),X="buffer"}else if(J instanceof jG)X="buffer";else if(g3._isUint8Array(J))J=g3._uint8ArrayToBuffer(J),X="buffer";else throw new Vo0("chunk",["string","Buffer","Uint8Array"],J);let Q;if(Y.ending)Q=new Do0;else if(Y.destroyed)Q=new m3("write");if(Q)return pZ.nextTick($,Q),tX(Z,Q,!0),Q;return Y.pendingcb++,_o0(Z,Y,J,X,$)}M1.prototype.write=function(Z,J,X){return B60(this,Z,J,X)===!0};M1.prototype.cork=function(){this._writableState.corked++};M1.prototype.uncork=function(){let Z=this._writableState;if(Z.corked){if(Z.corked--,!Z.writing)v_(this,Z)}};M1.prototype.setDefaultEncoding=function(J){if(typeof J==="string")J=Yo0(J);if(!jG.isEncoding(J))throw new F60(J);return this._writableState.defaultEncoding=J,this};function _o0(Z,J,X,$,Y){let Q=J.objectMode?1:X.length;J.length+=Q;let W=J.length<J.highWaterMark;if(!W)J.needDrain=!0;if(J.writing||J.corked||J.errored||!J.constructed){if(J.buffered.push({chunk:X,encoding:$,callback:Y}),J.allBuffers&&$!=="buffer")J.allBuffers=!1;if(J.allNoop&&Y!==k_)J.allNoop=!1}else J.writelen=Q,J.writecb=Y,J.writing=!0,J.sync=!0,Z._write(X,$,J.onwrite),J.sync=!1;return W&&!J.errored&&!J.destroyed}function Q60(Z,J,X,$,Y,Q,W){if(J.writelen=$,J.writecb=W,J.writing=!0,J.sync=!0,J.destroyed)J.onwrite(new m3("write"));else if(X)Z._writev(Y,J.onwrite);else Z._write(Y,Q,J.onwrite);J.sync=!1}function W60(Z,J,X,$){--J.pendingcb,$(X),x_(J),tX(Z,X)}function Oo0(Z,J){let X=Z._writableState,$=X.sync,Y=X.writecb;if(typeof Y!=="function"){tX(Z,new V60);return}if(X.writing=!1,X.writecb=null,X.length-=X.writelen,X.writelen=0,J){if(J.stack,!X.errored)X.errored=J;if(Z._readableState&&!Z._readableState.errored)Z._readableState.errored=J;if($)pZ.nextTick(W60,Z,X,J,Y);else W60(Z,X,J,Y)}else{if(X.buffered.length>X.bufferedIndex)v_(Z,X);if($)if(X.afterWriteTickInfo!==null&&X.afterWriteTickInfo.cb===Y)X.afterWriteTickInfo.count++;else X.afterWriteTickInfo={count:1,cb:Y,stream:Z,state:X},pZ.nextTick(wo0,X.afterWriteTickInfo);else U60(Z,X,1,Y)}}function wo0({stream:Z,state:J,count:X,cb:$}){return J.afterWriteTickInfo=null,U60(Z,J,X,$)}function U60(Z,J,X,$){if(!J.ending&&!Z.destroyed&&J.length===0&&J.needDrain)J.needDrain=!1,Z.emit("drain");while(X-- >0)J.pendingcb--,$();if(J.destroyed)x_(J);h_(Z,J)}function x_(Z){if(Z.writing)return;for(let Y=Z.bufferedIndex;Y<Z.buffered.length;++Y){var J;let{chunk:Q,callback:W}=Z.buffered[Y],K=Z.objectMode?1:Q.length;Z.length-=K,W((J=Z.errored)!==null&&J!==void 0?J:new m3("write"))}let X=Z[eX].splice(0);for(let Y=0;Y<X.length;Y++){var $;X[Y](($=Z.errored)!==null&&$!==void 0?$:new m3("end"))}AG(Z)}function v_(Z,J){if(J.corked||J.bufferProcessing||J.destroyed||!J.constructed)return;let{buffered:X,bufferedIndex:$,objectMode:Y}=J,Q=X.length-$;if(!Q)return;let W=$;if(J.bufferProcessing=!0,Q>1&&Z._writev){J.pendingcb-=Q-1;let K=J.allNoop?k_:(G)=>{for(let H=W;H<X.length;++H)X[H].callback(G)},z=J.allNoop&&W===0?X:K60(X,W);z.allBuffers=J.allBuffers,Q60(Z,J,!0,J.length,z,"",K),AG(J)}else{do{let{chunk:K,encoding:z,callback:G}=X[W];X[W++]=null;let H=Y?1:K.length;Q60(Z,J,!1,H,K,z,G)}while(W<X.length&&!J.writing);if(W===X.length)AG(J);else if(W>256)X.splice(0,W),J.bufferedIndex=0;else J.bufferedIndex=W}J.bufferProcessing=!1}M1.prototype._write=function(Z,J,X){if(this._writev)this._writev([{chunk:Z,encoding:J}],X);else throw new Fo0("_write()")};M1.prototype._writev=null;M1.prototype.end=function(Z,J,X){let $=this._writableState;if(typeof Z==="function")X=Z,Z=null,J=null;else if(typeof J==="function")X=J,J=null;let Y;if(Z!==null&&Z!==void 0){let Q=B60(this,Z,J);if(Q instanceof Xo0)Y=Q}if($.corked)$.corked=1,this.uncork();if(Y);else if(!$.errored&&!$.ending)$.ending=!0,h_(this,$,!0),$.ended=!0;else if($.finished)Y=new Uo0("end");else if($.destroyed)Y=new m3("end");if(typeof X==="function")if(Y||$.finished)pZ.nextTick(X,Y);else $[eX].push(X);return this};function MG(Z){return Z.ending&&!Z.destroyed&&Z.constructed&&Z.length===0&&!Z.errored&&Z.buffered.length===0&&!Z.finished&&!Z.writing&&!Z.errorEmitted&&!Z.closeEmitted}function jo0(Z,J){let X=!1;function $(Y){if(X){tX(Z,Y!==null&&Y!==void 0?Y:V60());return}if(X=!0,J.pendingcb--,Y){let Q=J[eX].splice(0);for(let W=0;W<Q.length;W++)Q[W](Y);tX(Z,Y,J.sync)}else if(MG(J))J.prefinished=!0,Z.emit("prefinish"),J.pendingcb++,pZ.nextTick(S_,Z,J)}J.sync=!0,J.pendingcb++;try{Z._final($)}catch(Y){$(Y)}J.sync=!1}function Mo0(Z,J){if(!J.prefinished&&!J.finalCalled)if(typeof Z._final==="function"&&!J.destroyed)J.finalCalled=!0,jo0(Z,J);else J.prefinished=!0,Z.emit("prefinish")}function h_(Z,J,X){if(MG(J)){if(Mo0(Z,J),J.pendingcb===0){if(X)J.pendingcb++,pZ.nextTick(($,Y)=>{if(MG(Y))S_($,Y);else Y.pendingcb--},Z,J);else if(MG(J))J.pendingcb++,S_(Z,J)}}}function S_(Z,J){J.pendingcb--,J.finished=!0;let X=J[eX].splice(0);for(let $=0;$<X.length;$++)X[$]();if(Z.emit("finish"),J.autoDestroy){let $=Z._readableState;if(!$||$.autoDestroy&&($.endEmitted||$.readable===!1))Z.destroy()}}$o0(M1.prototype,{closed:{__proto__:null,get(){return this._writableState?this._writableState.closed:!1}},destroyed:{__proto__:null,get(){return this._writableState?this._writableState.destroyed:!1},set(Z){if(this._writableState)this._writableState.destroyed=Z}},writable:{__proto__:null,get(){let Z=this._writableState;return!!Z&&Z.writable!==!1&&!Z.destroyed&&!Z.errored&&!Z.ending&&!Z.ended},set(Z){if(this._writableState)this._writableState.writable=!!Z}},writableFinished:{__proto__:null,get(){return this._writableState?this._writableState.finished:!1}},writableObjectMode:{__proto__:null,get(){return this._writableState?this._writableState.objectMode:!1}},writableBuffer:{__proto__:null,get(){return this._writableState&&this._writableState.getBuffer()}},writableEnded:{__proto__:null,get(){return this._writableState?this._writableState.ending:!1}},writableNeedDrain:{__proto__:null,get(){let Z=this._writableState;if(!Z)return!1;return!Z.destroyed&&!Z.ending&&Z.needDrain}},writableHighWaterMark:{__proto__:null,get(){return this._writableState&&this._writableState.highWaterMark}},writableCorked:{__proto__:null,get(){return this._writableState?this._writableState.corked:0}},writableLength:{__proto__:null,get(){return this._writableState&&this._writableState.length}},errored:{__proto__:null,enumerable:!1,get(){return this._writableState?this._writableState.errored:null}},writableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._writableState.writable!==!1&&(this._writableState.destroyed||this._writableState.errored)&&!this._writableState.finished)}}});var Ao0=TG.destroy;M1.prototype.destroy=function(Z,J){let X=this._writableState;if(!X.destroyed&&(X.bufferedIndex<X.buffered.length||X[eX].length))pZ.nextTick(x_,X);return Ao0.call(this,Z,J),this};M1.prototype._undestroy=TG.undestroy;M1.prototype._destroy=function(Z,J){J(Z)};M1.prototype[Ko0.captureRejectionSymbol]=function(Z){this.destroy(Z)};var y_;function L60(){if(y_===void 0)y_={};return y_}M1.fromWeb=function(Z,J){return L60().newStreamWritableFromWritableStream(Z,J)};M1.toWeb=function(Z){return L60().newWritableStreamFromStreamWritable(Z)}});var y60=L((aR1,I60)=>{var f_=q7(),To0=N("buffer"),{isReadable:qo0,isWritable:Co0,isIterable:_60,isNodeStream:No0,isReadableNodeStream:O60,isWritableNodeStream:w60,isDuplexNodeStream:Ro0,isReadableStream:j60,isWritableStream:M60}=U5(),A60=F9(),{AbortError:P60,codes:{ERR_INVALID_ARG_TYPE:Po0,ERR_INVALID_RETURN_VALUE:T60}}=T4(),{destroyer:J$}=uZ(),Eo0=_5(),E60=b3(),Io0=qG(),{createDeferredPromise:q60}=b4(),C60=A_(),N60=globalThis.Blob||To0.Blob,yo0=typeof N60<"u"?function(J){return J instanceof N60}:function(J){return!1},So0=globalThis.AbortController||N("abort-controller").AbortController,{FunctionPrototypeCall:R60}=F1();class iZ extends Eo0{constructor(Z){super(Z);if((Z===null||Z===void 0?void 0:Z.readable)===!1)this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0;if((Z===null||Z===void 0?void 0:Z.writable)===!1)this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0}}I60.exports=function Z(J,X){if(Ro0(J))return J;if(O60(J))return Z$({readable:J});if(w60(J))return Z$({writable:J});if(No0(J))return Z$({writable:!1,readable:!1});if(j60(J))return Z$({readable:E60.fromWeb(J)});if(M60(J))return Z$({writable:Io0.fromWeb(J)});if(typeof J==="function"){let{value:Y,write:Q,final:W,destroy:K}=ko0(J);if(_60(Y))return C60(iZ,Y,{objectMode:!0,write:Q,final:W,destroy:K});let z=Y===null||Y===void 0?void 0:Y.then;if(typeof z==="function"){let G,H=R60(z,Y,(V)=>{if(V!=null)throw new T60("nully","body",V)},(V)=>{J$(G,V)});return G=new iZ({objectMode:!0,readable:!1,write:Q,final(V){W(async()=>{try{await H,f_.nextTick(V,null)}catch(F){f_.nextTick(V,F)}})},destroy:K})}throw new T60("Iterable, AsyncIterable or AsyncFunction",X,Y)}if(yo0(J))return Z(J.arrayBuffer());if(_60(J))return C60(iZ,J,{objectMode:!0,writable:!1});if(j60(J===null||J===void 0?void 0:J.readable)&&M60(J===null||J===void 0?void 0:J.writable))return iZ.fromWeb(J);if(typeof(J===null||J===void 0?void 0:J.writable)==="object"||typeof(J===null||J===void 0?void 0:J.readable)==="object"){let Y=J!==null&&J!==void 0&&J.readable?O60(J===null||J===void 0?void 0:J.readable)?J===null||J===void 0?void 0:J.readable:Z(J.readable):void 0,Q=J!==null&&J!==void 0&&J.writable?w60(J===null||J===void 0?void 0:J.writable)?J===null||J===void 0?void 0:J.writable:Z(J.writable):void 0;return Z$({readable:Y,writable:Q})}let $=J===null||J===void 0?void 0:J.then;if(typeof $==="function"){let Y;return R60($,J,(Q)=>{if(Q!=null)Y.push(Q);Y.push(null)},(Q)=>{J$(Y,Q)}),Y=new iZ({objectMode:!0,writable:!1,read(){}})}throw new Po0(X,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],J)};function ko0(Z){let{promise:J,resolve:X}=q60(),$=new So0,Y=$.signal;return{value:Z(async function*(){while(!0){let W=J;J=null;let{chunk:K,done:z,cb:G}=await W;if(f_.nextTick(G),z)return;if(Y.aborted)throw new P60(void 0,{cause:Y.reason});({promise:J,resolve:X}=q60()),yield K}}(),{signal:Y}),write(W,K,z){let G=X;X=null,G({chunk:W,done:!1,cb:z})},final(W){let K=X;X=null,K({done:!0,cb:W})},destroy(W,K){$.abort(),K(W)}}}function Z$(Z){let J=Z.readable&&typeof Z.readable.read!=="function"?E60.wrap(Z.readable):Z.readable,X=Z.writable,$=!!qo0(J),Y=!!Co0(X),Q,W,K,z,G;function H(V){let F=z;if(z=null,F)F(V);else if(V)G.destroy(V)}if(G=new iZ({readableObjectMode:!!(J!==null&&J!==void 0&&J.readableObjectMode),writableObjectMode:!!(X!==null&&X!==void 0&&X.writableObjectMode),readable:$,writable:Y}),Y)A60(X,(V)=>{if(Y=!1,V)J$(J,V);H(V)}),G._write=function(V,F,B){if(X.write(V,F))B();else Q=B},G._final=function(V){X.end(),W=V},X.on("drain",function(){if(Q){let V=Q;Q=null,V()}}),X.on("finish",function(){if(W){let V=W;W=null,V()}});if($)A60(J,(V)=>{if($=!1,V)J$(J,V);H(V)}),J.on("readable",function(){if(K){let V=K;K=null,V()}}),J.on("end",function(){G.push(null)}),G._read=function(){while(!0){let V=J.read();if(V===null){K=G._read;return}if(!G.push(V))return}};return G._destroy=function(V,F){if(!V&&z!==null)V=new P60;if(K=null,Q=null,W=null,z===null)F(V);else z=F,J$(X,V),J$(J,V)},G}});var _5=L((rR1,x60)=>{var{ObjectDefineProperties:xo0,ObjectGetOwnPropertyDescriptor:B9,ObjectKeys:vo0,ObjectSetPrototypeOf:S60}=F1();x60.exports=f8;var m_=b3(),X8=qG();S60(f8.prototype,m_.prototype);S60(f8,m_);{let Z=vo0(X8.prototype);for(let J=0;J<Z.length;J++){let X=Z[J];if(!f8.prototype[X])f8.prototype[X]=X8.prototype[X]}}function f8(Z){if(!(this instanceof f8))return new f8(Z);if(m_.call(this,Z),X8.call(this,Z),Z){if(this.allowHalfOpen=Z.allowHalfOpen!==!1,Z.readable===!1)this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0;if(Z.writable===!1)this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0}else this.allowHalfOpen=!0}xo0(f8.prototype,{writable:{__proto__:null,...B9(X8.prototype,"writable")},writableHighWaterMark:{__proto__:null,...B9(X8.prototype,"writableHighWaterMark")},writableObjectMode:{__proto__:null,...B9(X8.prototype,"writableObjectMode")},writableBuffer:{__proto__:null,...B9(X8.prototype,"writableBuffer")},writableLength:{__proto__:null,...B9(X8.prototype,"writableLength")},writableFinished:{__proto__:null,...B9(X8.prototype,"writableFinished")},writableCorked:{__proto__:null,...B9(X8.prototype,"writableCorked")},writableEnded:{__proto__:null,...B9(X8.prototype,"writableEnded")},writableNeedDrain:{__proto__:null,...B9(X8.prototype,"writableNeedDrain")},destroyed:{__proto__:null,get(){if(this._readableState===void 0||this._writableState===void 0)return!1;return this._readableState.destroyed&&this._writableState.destroyed},set(Z){if(this._readableState&&this._writableState)this._readableState.destroyed=Z,this._writableState.destroyed=Z}}});var b_;function k60(){if(b_===void 0)b_={};return b_}f8.fromWeb=function(Z,J){return k60().newStreamDuplexFromReadableWritablePair(Z,J)};f8.toWeb=function(Z){return k60().newReadableWritablePairFromDuplex(Z)};var g_;f8.from=function(Z){if(!g_)g_=y60();return g_(Z,"body")}});var c_=L((sR1,h60)=>{var{ObjectSetPrototypeOf:v60,Symbol:ho0}=F1();h60.exports=U9;var{ERR_METHOD_NOT_IMPLEMENTED:fo0}=T4().codes,u_=_5(),{getHighWaterMark:bo0}=v3();v60(U9.prototype,u_.prototype);v60(U9,u_);var u3=ho0("kCallback");function U9(Z){if(!(this instanceof U9))return new U9(Z);let J=Z?bo0(this,Z,"readableHighWaterMark",!0):null;if(J===0)Z={...Z,highWaterMark:null,readableHighWaterMark:J,writableHighWaterMark:Z.writableHighWaterMark||0};if(u_.call(this,Z),this._readableState.sync=!1,this[u3]=null,Z){if(typeof Z.transform==="function")this._transform=Z.transform;if(typeof Z.flush==="function")this._flush=Z.flush}this.on("prefinish",go0)}function d_(Z){if(typeof this._flush==="function"&&!this.destroyed)this._flush((J,X)=>{if(J){if(Z)Z(J);else this.destroy(J);return}if(X!=null)this.push(X);if(this.push(null),Z)Z()});else if(this.push(null),Z)Z()}function go0(){if(this._final!==d_)d_.call(this)}U9.prototype._final=d_;U9.prototype._transform=function(Z,J,X){throw new fo0("_transform()")};U9.prototype._write=function(Z,J,X){let $=this._readableState,Y=this._writableState,Q=$.length;this._transform(Z,J,(W,K)=>{if(W){X(W);return}if(K!=null)this.push(K);if(Y.ended||Q===$.length||$.length<$.highWaterMark)X();else this[u3]=X})};U9.prototype._read=function(){if(this[u3]){let Z=this[u3];this[u3]=null,Z()}}});var p_=L((tR1,b60)=>{var{ObjectSetPrototypeOf:f60}=F1();b60.exports=X$;var l_=c_();f60(X$.prototype,l_.prototype);f60(X$,l_);function X$(Z){if(!(this instanceof X$))return new X$(Z);l_.call(this,Z)}X$.prototype._transform=function(Z,J,X){X(null,Z)}});var PG=L((eR1,c60)=>{var c3=q7(),{ArrayIsArray:mo0,Promise:do0,SymbolAsyncIterator:uo0,SymbolDispose:co0}=F1(),RG=F9(),{once:lo0}=b4(),po0=uZ(),g60=_5(),{aggregateTwoErrors:io0,codes:{ERR_INVALID_ARG_TYPE:ZO,ERR_INVALID_RETURN_VALUE:i_,ERR_MISSING_ARGS:no0,ERR_STREAM_DESTROYED:oo0,ERR_STREAM_PREMATURE_CLOSE:ao0},AbortError:ro0}=T4(),{validateFunction:so0,validateAbortSignal:to0}=nX(),{isIterable:nZ,isReadable:n_,isReadableNodeStream:NG,isNodeStream:m60,isTransformStream:$$,isWebStream:eo0,isReadableStream:o_,isReadableFinished:Za0}=U5(),Ja0=globalThis.AbortController||N("abort-controller").AbortController,a_,r_,s_;function d60(Z,J,X){let $=!1;Z.on("close",()=>{$=!0});let Y=RG(Z,{readable:J,writable:X},(Q)=>{$=!Q});return{destroy:(Q)=>{if($)return;$=!0,po0.destroyer(Z,Q||new oo0("pipe"))},cleanup:Y}}function Xa0(Z){return so0(Z[Z.length-1],"streams[stream.length - 1]"),Z.pop()}function t_(Z){if(nZ(Z))return Z;else if(NG(Z))return $a0(Z);throw new ZO("val",["Readable","Iterable","AsyncIterable"],Z)}async function*$a0(Z){if(!r_)r_=b3();yield*r_.prototype[uo0].call(Z)}async function CG(Z,J,X,{end:$}){let Y,Q=null,W=(G)=>{if(G)Y=G;if(Q){let H=Q;Q=null,H()}},K=()=>new do0((G,H)=>{if(Y)H(Y);else Q=()=>{if(Y)H(Y);else G()}});J.on("drain",W);let z=RG(J,{readable:!1},W);try{if(J.writableNeedDrain)await K();for await(let G of Z)if(!J.write(G))await K();if($)J.end(),await K();X()}catch(G){X(Y!==G?io0(Y,G):G)}finally{z(),J.off("drain",W)}}async function e_(Z,J,X,{end:$}){if($$(J))J=J.writable;let Y=J.getWriter();try{for await(let Q of Z)await Y.ready,Y.write(Q).catch(()=>{});if(await Y.ready,$)await Y.close();X()}catch(Q){try{await Y.abort(Q),X(Q)}catch(W){X(W)}}}function Ya0(...Z){return u60(Z,lo0(Xa0(Z)))}function u60(Z,J,X){if(Z.length===1&&mo0(Z[0]))Z=Z[0];if(Z.length<2)throw new no0("streams");let $=new Ja0,Y=$.signal,Q=X===null||X===void 0?void 0:X.signal,W=[];to0(Q,"options.signal");function K(){U(new ro0)}s_=s_||b4().addAbortListener;let z;if(Q)z=s_(Q,K);let G,H,V=[],F=0;function B(j){U(j,--F===0)}function U(j,q){var R;if(j&&(!G||G.code==="ERR_STREAM_PREMATURE_CLOSE"))G=j;if(!G&&!q)return;while(V.length)V.shift()(G);if((R=z)===null||R===void 0||R[co0](),$.abort(),q){if(!G)W.forEach((T)=>T());c3.nextTick(J,G,H)}}let D;for(let j=0;j<Z.length;j++){let q=Z[j],R=j<Z.length-1,T=j>0,y=R||(X===null||X===void 0?void 0:X.end)!==!1,i=j===Z.length-1;if(m60(q)){let s=function(O0){if(O0&&O0.name!=="AbortError"&&O0.code!=="ERR_STREAM_PREMATURE_CLOSE")B(O0)};var w=s;if(y){let{destroy:O0,cleanup:d0}=d60(q,R,T);if(V.push(O0),n_(q)&&i)W.push(d0)}if(q.on("error",s),n_(q)&&i)W.push(()=>{q.removeListener("error",s)})}if(j===0)if(typeof q==="function"){if(D=q({signal:Y}),!nZ(D))throw new i_("Iterable, AsyncIterable or Stream","source",D)}else if(nZ(q)||NG(q)||$$(q))D=q;else D=g60.from(q);else if(typeof q==="function"){if($$(D)){var _;D=t_((_=D)===null||_===void 0?void 0:_.readable)}else D=t_(D);if(D=q(D,{signal:Y}),R){if(!nZ(D,!0))throw new i_("AsyncIterable",`transform[${j-1}]`,D)}else{var O;if(!a_)a_=p_();let s=new a_({objectMode:!0}),O0=(O=D)===null||O===void 0?void 0:O.then;if(typeof O0==="function")F++,O0.call(D,(G0)=>{if(H=G0,G0!=null)s.write(G0);if(y)s.end();c3.nextTick(B)},(G0)=>{s.destroy(G0),c3.nextTick(B,G0)});else if(nZ(D,!0))F++,CG(D,s,B,{end:y});else if(o_(D)||$$(D)){let G0=D.readable||D;F++,CG(G0,s,B,{end:y})}else throw new i_("AsyncIterable or Promise","destination",D);D=s;let{destroy:d0,cleanup:b0}=d60(D,!1,!0);if(V.push(d0),i)W.push(b0)}}else if(m60(q)){if(NG(D)){F+=2;let s=Qa0(D,q,B,{end:y});if(n_(q)&&i)W.push(s)}else if($$(D)||o_(D)){let s=D.readable||D;F++,CG(s,q,B,{end:y})}else if(nZ(D))F++,CG(D,q,B,{end:y});else throw new ZO("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],D);D=q}else if(eo0(q)){if(NG(D))F++,e_(t_(D),q,B,{end:y});else if(o_(D)||nZ(D))F++,e_(D,q,B,{end:y});else if($$(D))F++,e_(D.readable,q,B,{end:y});else throw new ZO("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],D);D=q}else D=g60.from(q)}if(Y!==null&&Y!==void 0&&Y.aborted||Q!==null&&Q!==void 0&&Q.aborted)c3.nextTick(K);return D}function Qa0(Z,J,X,{end:$}){let Y=!1;if(J.on("close",()=>{if(!Y)X(new ao0)}),Z.pipe(J,{end:!1}),$){let W=function(){Y=!0,J.end()};var Q=W;if(Za0(Z))c3.nextTick(W);else Z.once("end",W)}else X();return RG(Z,{readable:!0,writable:!1},(W)=>{let K=Z._readableState;if(W&&W.code==="ERR_STREAM_PREMATURE_CLOSE"&&K&&K.ended&&!K.errored&&!K.errorEmitted)Z.once("end",X).once("error",X);else X(W)}),RG(J,{readable:!1,writable:!0},X)}c60.exports={pipelineImpl:u60,pipeline:Ya0}});var XO=L((ZP1,a60)=>{var{pipeline:Wa0}=PG(),EG=_5(),{destroyer:Ka0}=uZ(),{isNodeStream:IG,isReadable:l60,isWritable:p60,isWebStream:JO,isTransformStream:oZ,isWritableStream:i60,isReadableStream:n60}=U5(),{AbortError:za0,codes:{ERR_INVALID_ARG_VALUE:o60,ERR_MISSING_ARGS:Ga0}}=T4(),Ha0=F9();a60.exports=function(...J){if(J.length===0)throw new Ga0("streams");if(J.length===1)return EG.from(J[0]);let X=[...J];if(typeof J[0]==="function")J[0]=EG.from(J[0]);if(typeof J[J.length-1]==="function"){let B=J.length-1;J[B]=EG.from(J[B])}for(let B=0;B<J.length;++B){if(!IG(J[B])&&!JO(J[B]))continue;if(B<J.length-1&&!(l60(J[B])||n60(J[B])||oZ(J[B])))throw new o60(`streams[${B}]`,X[B],"must be readable");if(B>0&&!(p60(J[B])||i60(J[B])||oZ(J[B])))throw new o60(`streams[${B}]`,X[B],"must be writable")}let $,Y,Q,W,K;function z(B){let U=W;if(W=null,U)U(B);else if(B)K.destroy(B);else if(!F&&!V)K.destroy()}let G=J[0],H=Wa0(J,z),V=!!(p60(G)||i60(G)||oZ(G)),F=!!(l60(H)||n60(H)||oZ(H));if(K=new EG({writableObjectMode:!!(G!==null&&G!==void 0&&G.writableObjectMode),readableObjectMode:!!(H!==null&&H!==void 0&&H.readableObjectMode),writable:V,readable:F}),V){if(IG(G))K._write=function(U,D,_){if(G.write(U,D))_();else $=_},K._final=function(U){G.end(),Y=U},G.on("drain",function(){if($){let U=$;$=null,U()}});else if(JO(G)){let D=(oZ(G)?G.writable:G).getWriter();K._write=async function(_,O,w){try{await D.ready,D.write(_).catch(()=>{}),w()}catch(j){w(j)}},K._final=async function(_){try{await D.ready,D.close().catch(()=>{}),Y=_}catch(O){_(O)}}}let B=oZ(H)?H.readable:H;Ha0(B,()=>{if(Y){let U=Y;Y=null,U()}})}if(F){if(IG(H))H.on("readable",function(){if(Q){let B=Q;Q=null,B()}}),H.on("end",function(){K.push(null)}),K._read=function(){while(!0){let B=H.read();if(B===null){Q=K._read;return}if(!K.push(B))return}};else if(JO(H)){let U=(oZ(H)?H.readable:H).getReader();K._read=async function(){while(!0)try{let{value:D,done:_}=await U.read();if(!K.push(D))return;if(_){K.push(null);return}}catch{return}}}}return K._destroy=function(B,U){if(!B&&W!==null)B=new za0;if(Q=null,$=null,Y=null,W===null)U(B);else if(W=U,IG(H))Ka0(H,B)},K}});var W80=L((ba0,YO)=>{var Va0=globalThis.AbortController||N("abort-controller").AbortController,{codes:{ERR_INVALID_ARG_VALUE:Fa0,ERR_INVALID_ARG_TYPE:l3,ERR_MISSING_ARGS:Ba0,ERR_OUT_OF_RANGE:Ua0},AbortError:O5}=T4(),{validateAbortSignal:aZ,validateInteger:r60,validateObject:rZ}=nX(),La0=F1().Symbol("kWeak"),Da0=F1().Symbol("kResistStopPropagation"),{finished:_a0}=F9(),Oa0=XO(),{addAbortSignalNoValidate:wa0}=x3(),{isWritable:ja0,isNodeStream:Ma0}=U5(),{deprecate:Aa0}=b4(),{ArrayPrototypePush:Ta0,Boolean:qa0,MathFloor:s60,Number:Ca0,NumberIsNaN:Na0,Promise:t60,PromiseReject:e60,PromiseResolve:Ra0,PromisePrototypeThen:Z80,Symbol:X80}=F1(),yG=X80("kEmpty"),J80=X80("kEof");function Pa0(Z,J){if(J!=null)rZ(J,"options");if((J===null||J===void 0?void 0:J.signal)!=null)aZ(J.signal,"options.signal");if(Ma0(Z)&&!ja0(Z))throw new Fa0("stream",Z,"must be writable");let X=Oa0(this,Z);if(J!==null&&J!==void 0&&J.signal)wa0(J.signal,X);return X}function SG(Z,J){if(typeof Z!=="function")throw new l3("fn",["Function","AsyncFunction"],Z);if(J!=null)rZ(J,"options");if((J===null||J===void 0?void 0:J.signal)!=null)aZ(J.signal,"options.signal");let X=1;if((J===null||J===void 0?void 0:J.concurrency)!=null)X=s60(J.concurrency);let $=X-1;if((J===null||J===void 0?void 0:J.highWaterMark)!=null)$=s60(J.highWaterMark);return r60(X,"options.concurrency",1),r60($,"options.highWaterMark",0),$+=X,async function*(){let Q=b4().AbortSignalAny([J===null||J===void 0?void 0:J.signal].filter(qa0)),W=this,K=[],z={signal:Q},G,H,V=!1,F=0;function B(){V=!0,U()}function U(){F-=1,D()}function D(){if(H&&!V&&F<X&&K.length<$)H(),H=null}async function _(){try{for await(let O of W){if(V)return;if(Q.aborted)throw new O5;try{if(O=Z(O,z),O===yG)continue;O=Ra0(O)}catch(w){O=e60(w)}if(F+=1,Z80(O,U,B),K.push(O),G)G(),G=null;if(!V&&(K.length>=$||F>=X))await new t60((w)=>{H=w})}K.push(J80)}catch(O){let w=e60(O);Z80(w,U,B),K.push(w)}finally{if(V=!0,G)G(),G=null}}_();try{while(!0){while(K.length>0){let O=await K[0];if(O===J80)return;if(Q.aborted)throw new O5;if(O!==yG)yield O;K.shift(),D()}await new t60((O)=>{G=O})}}finally{if(V=!0,H)H(),H=null}}.call(this)}function Ea0(Z=void 0){if(Z!=null)rZ(Z,"options");if((Z===null||Z===void 0?void 0:Z.signal)!=null)aZ(Z.signal,"options.signal");return async function*(){let X=0;for await(let Y of this){var $;if(Z!==null&&Z!==void 0&&($=Z.signal)!==null&&$!==void 0&&$.aborted)throw new O5({cause:Z.signal.reason});yield[X++,Y]}}.call(this)}async function $80(Z,J=void 0){for await(let X of $O.call(this,Z,J))return!0;return!1}async function Ia0(Z,J=void 0){if(typeof Z!=="function")throw new l3("fn",["Function","AsyncFunction"],Z);return!await $80.call(this,async(...X)=>{return!await Z(...X)},J)}async function ya0(Z,J){for await(let X of $O.call(this,Z,J))return X;return}async function Sa0(Z,J){if(typeof Z!=="function")throw new l3("fn",["Function","AsyncFunction"],Z);async function X($,Y){return await Z($,Y),yG}for await(let $ of SG.call(this,X,J));}function $O(Z,J){if(typeof Z!=="function")throw new l3("fn",["Function","AsyncFunction"],Z);async function X($,Y){if(await Z($,Y))return $;return yG}return SG.call(this,X,J)}class Y80 extends Ba0{constructor(){super("reduce");this.message="Reduce of an empty stream requires an initial value"}}async function ka0(Z,J,X){var $;if(typeof Z!=="function")throw new l3("reducer",["Function","AsyncFunction"],Z);if(X!=null)rZ(X,"options");if((X===null||X===void 0?void 0:X.signal)!=null)aZ(X.signal,"options.signal");let Y=arguments.length>1;if(X!==null&&X!==void 0&&($=X.signal)!==null&&$!==void 0&&$.aborted){let G=new O5(void 0,{cause:X.signal.reason});throw this.once("error",()=>{}),await _a0(this.destroy(G)),G}let Q=new Va0,W=Q.signal;if(X!==null&&X!==void 0&&X.signal){let G={once:!0,[La0]:this,[Da0]:!0};X.signal.addEventListener("abort",()=>Q.abort(),G)}let K=!1;try{for await(let G of this){var z;if(K=!0,X!==null&&X!==void 0&&(z=X.signal)!==null&&z!==void 0&&z.aborted)throw new O5;if(!Y)J=G,Y=!0;else J=await Z(J,G,{signal:W})}if(!K&&!Y)throw new Y80}finally{Q.abort()}return J}async function xa0(Z){if(Z!=null)rZ(Z,"options");if((Z===null||Z===void 0?void 0:Z.signal)!=null)aZ(Z.signal,"options.signal");let J=[];for await(let $ of this){var X;if(Z!==null&&Z!==void 0&&(X=Z.signal)!==null&&X!==void 0&&X.aborted)throw new O5(void 0,{cause:Z.signal.reason});Ta0(J,$)}return J}function va0(Z,J){let X=SG.call(this,Z,J);return async function*(){for await(let Y of X)yield*Y}.call(this)}function Q80(Z){if(Z=Ca0(Z),Na0(Z))return 0;if(Z<0)throw new Ua0("number",">= 0",Z);return Z}function ha0(Z,J=void 0){if(J!=null)rZ(J,"options");if((J===null||J===void 0?void 0:J.signal)!=null)aZ(J.signal,"options.signal");return Z=Q80(Z),async function*(){var $;if(J!==null&&J!==void 0&&($=J.signal)!==null&&$!==void 0&&$.aborted)throw new O5;for await(let Q of this){var Y;if(J!==null&&J!==void 0&&(Y=J.signal)!==null&&Y!==void 0&&Y.aborted)throw new O5;if(Z--<=0)yield Q}}.call(this)}function fa0(Z,J=void 0){if(J!=null)rZ(J,"options");if((J===null||J===void 0?void 0:J.signal)!=null)aZ(J.signal,"options.signal");return Z=Q80(Z),async function*(){var $;if(J!==null&&J!==void 0&&($=J.signal)!==null&&$!==void 0&&$.aborted)throw new O5;for await(let Q of this){var Y;if(J!==null&&J!==void 0&&(Y=J.signal)!==null&&Y!==void 0&&Y.aborted)throw new O5;if(Z-- >0)yield Q;if(Z<=0)return}}.call(this)}ba0.streamReturningOperators={asIndexedPairs:Aa0(Ea0,"readable.asIndexedPairs will be removed in a future version."),drop:ha0,filter:$O,flatMap:va0,map:SG,take:fa0,compose:Pa0};ba0.promiseReturningOperators={every:Ia0,forEach:Sa0,reduce:ka0,toArray:xa0,some:$80,find:ya0}});var QO=L((JP1,K80)=>{var{ArrayPrototypePop:da0,Promise:ua0}=F1(),{isIterable:ca0,isNodeStream:la0,isWebStream:pa0}=U5(),{pipelineImpl:ia0}=PG(),{finished:na0}=F9();WO();function oa0(...Z){return new ua0((J,X)=>{let $,Y,Q=Z[Z.length-1];if(Q&&typeof Q==="object"&&!la0(Q)&&!ca0(Q)&&!pa0(Q)){let W=da0(Z);$=W.signal,Y=W.end}ia0(Z,(W,K)=>{if(W)X(W);else J(K)},{signal:$,end:Y})})}K80.exports={finished:na0,pipeline:oa0}});var WO=L((XP1,D80)=>{var{Buffer:aa0}=N("buffer"),{ObjectDefineProperty:L9,ObjectKeys:H80,ReflectApply:V80}=F1(),{promisify:{custom:F80}}=b4(),{streamReturningOperators:z80,promiseReturningOperators:G80}=W80(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:B80}}=T4(),ra0=XO(),{setDefaultHighWaterMark:sa0,getDefaultHighWaterMark:ta0}=v3(),{pipeline:U80}=PG(),{destroyer:ea0}=uZ(),L80=F9(),KO=QO(),p3=U5(),Q1=D80.exports=VG().Stream;Q1.isDestroyed=p3.isDestroyed;Q1.isDisturbed=p3.isDisturbed;Q1.isErrored=p3.isErrored;Q1.isReadable=p3.isReadable;Q1.isWritable=p3.isWritable;Q1.Readable=b3();for(let Z of H80(z80)){let X=function(...$){if(new.target)throw B80();return Q1.Readable.from(V80(J,this,$))},J=z80[Z];L9(X,"name",{__proto__:null,value:J.name}),L9(X,"length",{__proto__:null,value:J.length}),L9(Q1.Readable.prototype,Z,{__proto__:null,value:X,enumerable:!1,configurable:!0,writable:!0})}for(let Z of H80(G80)){let X=function(...$){if(new.target)throw B80();return V80(J,this,$)},J=G80[Z];L9(X,"name",{__proto__:null,value:J.name}),L9(X,"length",{__proto__:null,value:J.length}),L9(Q1.Readable.prototype,Z,{__proto__:null,value:X,enumerable:!1,configurable:!0,writable:!0})}Q1.Writable=qG();Q1.Duplex=_5();Q1.Transform=c_();Q1.PassThrough=p_();Q1.pipeline=U80;var{addAbortSignal:Zr0}=x3();Q1.addAbortSignal=Zr0;Q1.finished=L80;Q1.destroy=ea0;Q1.compose=ra0;Q1.setDefaultHighWaterMark=sa0;Q1.getDefaultHighWaterMark=ta0;L9(Q1,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return KO}});L9(U80,F80,{__proto__:null,enumerable:!0,get(){return KO.pipeline}});L9(L80,F80,{__proto__:null,enumerable:!0,get(){return KO.finished}});Q1.Stream=Q1;Q1._isUint8Array=function(J){return J instanceof Uint8Array};Q1._uint8ArrayToBuffer=function(J){return aa0.from(J.buffer,J.byteOffset,J.byteLength)}});var R7=L(($P1,P0)=>{var n1=N("stream");if(n1&&process.env.READABLE_STREAM==="disable"){let Z=n1.promises;P0.exports._uint8ArrayToBuffer=n1._uint8ArrayToBuffer,P0.exports._isUint8Array=n1._isUint8Array,P0.exports.isDisturbed=n1.isDisturbed,P0.exports.isErrored=n1.isErrored,P0.exports.isReadable=n1.isReadable,P0.exports.Readable=n1.Readable,P0.exports.Writable=n1.Writable,P0.exports.Duplex=n1.Duplex,P0.exports.Transform=n1.Transform,P0.exports.PassThrough=n1.PassThrough,P0.exports.addAbortSignal=n1.addAbortSignal,P0.exports.finished=n1.finished,P0.exports.destroy=n1.destroy,P0.exports.pipeline=n1.pipeline,P0.exports.compose=n1.compose,Object.defineProperty(n1,"promises",{configurable:!0,enumerable:!0,get(){return Z}}),P0.exports.Stream=n1.Stream}else{let Z=WO(),J=QO(),X=Z.Readable.destroy;P0.exports=Z.Readable,P0.exports._uint8ArrayToBuffer=Z._uint8ArrayToBuffer,P0.exports._isUint8Array=Z._isUint8Array,P0.exports.isDisturbed=Z.isDisturbed,P0.exports.isErrored=Z.isErrored,P0.exports.isReadable=Z.isReadable,P0.exports.Readable=Z.Readable,P0.exports.Writable=Z.Writable,P0.exports.Duplex=Z.Duplex,P0.exports.Transform=Z.Transform,P0.exports.PassThrough=Z.PassThrough,P0.exports.addAbortSignal=Z.addAbortSignal,P0.exports.finished=Z.finished,P0.exports.destroy=Z.destroy,P0.exports.destroy=X,P0.exports.pipeline=Z.pipeline,P0.exports.compose=Z.compose,Object.defineProperty(Z,"promises",{configurable:!0,enumerable:!0,get(){return J}}),P0.exports.Stream=Z.Stream}P0.exports.default=P0.exports});var _80=L((jP1,zO)=>{if(typeof Object.create==="function")zO.exports=function(J,X){if(X)J.super_=X,J.prototype=Object.create(X.prototype,{constructor:{value:J,enumerable:!1,writable:!0,configurable:!0}})};else zO.exports=function(J,X){if(X){J.super_=X;var $=function(){};$.prototype=X.prototype,J.prototype=new $,J.prototype.constructor=J}}});var O80=L((MP1,GO)=>{try{if(kG=N("util"),typeof kG.inherits!=="function")throw"";GO.exports=kG.inherits}catch(Z){GO.exports=_80()}var kG});var M80=L((AP1,j80)=>{var{Buffer:b8}=N("buffer"),w80=Symbol.for("BufferList");function g0(Z){if(!(this instanceof g0))return new g0(Z);g0._init.call(this,Z)}g0._init=function(J){if(Object.defineProperty(this,w80,{value:!0}),this._bufs=[],this.length=0,J)this.append(J)};g0.prototype._new=function(J){return new g0(J)};g0.prototype._offset=function(J){if(J===0)return[0,0];let X=0;for(let $=0;$<this._bufs.length;$++){let Y=X+this._bufs[$].length;if(J<Y||$===this._bufs.length-1)return[$,J-X];X=Y}};g0.prototype._reverseOffset=function(Z){let J=Z[0],X=Z[1];for(let $=0;$<J;$++)X+=this._bufs[$].length;return X};g0.prototype.getBuffers=function(){return this._bufs};g0.prototype.get=function(J){if(J>this.length||J<0)return;let X=this._offset(J);return this._bufs[X[0]][X[1]]};g0.prototype.slice=function(J,X){if(typeof J==="number"&&J<0)J+=this.length;if(typeof X==="number"&&X<0)X+=this.length;return this.copy(null,0,J,X)};g0.prototype.copy=function(J,X,$,Y){if(typeof $!=="number"||$<0)$=0;if(typeof Y!=="number"||Y>this.length)Y=this.length;if($>=this.length)return J||b8.alloc(0);if(Y<=0)return J||b8.alloc(0);let Q=!!J,W=this._offset($),K=Y-$,z=K,G=Q&&X||0,H=W[1];if($===0&&Y===this.length){if(!Q)return this._bufs.length===1?this._bufs[0]:b8.concat(this._bufs,this.length);for(let V=0;V<this._bufs.length;V++)this._bufs[V].copy(J,G),G+=this._bufs[V].length;return J}if(z<=this._bufs[W[0]].length-H)return Q?this._bufs[W[0]].copy(J,X,H,H+z):this._bufs[W[0]].slice(H,H+z);if(!Q)J=b8.allocUnsafe(K);for(let V=W[0];V<this._bufs.length;V++){let F=this._bufs[V].length-H;if(z>F)this._bufs[V].copy(J,G,H),G+=F;else{this._bufs[V].copy(J,G,H,H+z),G+=F;break}if(z-=F,H)H=0}if(J.length>G)return J.slice(0,G);return J};g0.prototype.shallowSlice=function(J,X){if(J=J||0,X=typeof X!=="number"?this.length:X,J<0)J+=this.length;if(X<0)X+=this.length;if(J===X)return this._new();let $=this._offset(J),Y=this._offset(X),Q=this._bufs.slice($[0],Y[0]+1);if(Y[1]===0)Q.pop();else Q[Q.length-1]=Q[Q.length-1].slice(0,Y[1]);if($[1]!==0)Q[0]=Q[0].slice($[1]);return this._new(Q)};g0.prototype.toString=function(J,X,$){return this.slice(X,$).toString(J)};g0.prototype.consume=function(J){if(J=Math.trunc(J),Number.isNaN(J)||J<=0)return this;while(this._bufs.length)if(J>=this._bufs[0].length)J-=this._bufs[0].length,this.length-=this._bufs[0].length,this._bufs.shift();else{this._bufs[0]=this._bufs[0].slice(J),this.length-=J;break}return this};g0.prototype.duplicate=function(){let J=this._new();for(let X=0;X<this._bufs.length;X++)J.append(this._bufs[X]);return J};g0.prototype.append=function(J){return this._attach(J,g0.prototype._appendBuffer)};g0.prototype.prepend=function(J){return this._attach(J,g0.prototype._prependBuffer,!0)};g0.prototype._attach=function(J,X,$){if(J==null)return this;if(J.buffer)X.call(this,b8.from(J.buffer,J.byteOffset,J.byteLength));else if(Array.isArray(J)){let[Y,Q]=$?[J.length-1,-1]:[0,1];for(let W=Y;W>=0&&W<J.length;W+=Q)this._attach(J[W],X,$)}else if(this._isBufferList(J)){let[Y,Q]=$?[J._bufs.length-1,-1]:[0,1];for(let W=Y;W>=0&&W<J._bufs.length;W+=Q)this._attach(J._bufs[W],X,$)}else{if(typeof J==="number")J=J.toString();X.call(this,b8.from(J))}return this};g0.prototype._appendBuffer=function(J){this._bufs.push(J),this.length+=J.length};g0.prototype._prependBuffer=function(J){this._bufs.unshift(J),this.length+=J.length};g0.prototype.indexOf=function(Z,J,X){if(X===void 0&&typeof J==="string")X=J,J=void 0;if(typeof Z==="function"||Array.isArray(Z))throw TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.');else if(typeof Z==="number")Z=b8.from([Z]);else if(typeof Z==="string")Z=b8.from(Z,X);else if(this._isBufferList(Z))Z=Z.slice();else if(Array.isArray(Z.buffer))Z=b8.from(Z.buffer,Z.byteOffset,Z.byteLength);else if(!b8.isBuffer(Z))Z=b8.from(Z);if(J=Number(J||0),isNaN(J))J=0;if(J<0)J=this.length+J;if(J<0)J=0;if(Z.length===0)return J>this.length?this.length:J;let $=this._offset(J),Y=$[0],Q=$[1];for(;Y<this._bufs.length;Y++){let W=this._bufs[Y];while(Q<W.length)if(W.length-Q>=Z.length){let z=W.indexOf(Z,Q);if(z!==-1)return this._reverseOffset([Y,z]);Q=W.length-Z.length+1}else{let z=this._reverseOffset([Y,Q]);if(this._match(z,Z))return z;Q++}Q=0}return-1};g0.prototype._match=function(Z,J){if(this.length-Z<J.length)return!1;for(let X=0;X<J.length;X++)if(this.get(Z+X)!==J[X])return!1;return!0};(function(){let Z={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readBigInt64BE:8,readBigInt64LE:8,readBigUInt64BE:8,readBigUInt64LE:8,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1,readIntBE:null,readIntLE:null,readUIntBE:null,readUIntLE:null};for(let J in Z)(function(X){if(Z[X]===null)g0.prototype[X]=function($,Y){return this.slice($,$+Y)[X](0,Y)};else g0.prototype[X]=function($=0){return this.slice($,$+Z[X])[X](0)}})(J)})();g0.prototype._isBufferList=function(J){return J instanceof g0||g0.isBufferList(J)};g0.isBufferList=function(J){return J!=null&&J[w80]};j80.exports=g0});var A80=L((TP1,xG)=>{var HO=R7().Duplex,Jr0=O80(),i3=M80();function C4(Z){if(!(this instanceof C4))return new C4(Z);if(typeof Z==="function"){this._callback=Z;let J=function($){if(this._callback)this._callback($),this._callback=null}.bind(this);this.on("pipe",function($){$.on("error",J)}),this.on("unpipe",function($){$.removeListener("error",J)}),Z=null}i3._init.call(this,Z),HO.call(this)}Jr0(C4,HO);Object.assign(C4.prototype,i3.prototype);C4.prototype._new=function(J){return new C4(J)};C4.prototype._write=function(J,X,$){if(this._appendBuffer(J),typeof $==="function")$()};C4.prototype._read=function(J){if(!this.length)return this.push(null);J=Math.min(J,this.length),this.push(this.slice(0,J)),this.consume(J)};C4.prototype.end=function(J){if(HO.prototype.end.call(this,J),this._callback)this._callback(null,this.slice()),this._callback=null};C4.prototype._destroy=function(J,X){this._bufs.length=0,this.length=0,X(J)};C4.prototype._isBufferList=function(J){return J instanceof C4||J instanceof i3||C4.isBufferList(J)};C4.isBufferList=i3.isBufferList;xG.exports=C4;xG.exports.BufferListStream=C4;xG.exports.BufferList=i3});var C80=L((qP1,q80)=>{class T80{constructor(){this.cmd=null,this.retain=!1,this.qos=0,this.dup=!1,this.length=-1,this.topic=null,this.payload=null}}q80.exports=T80});var VO=L((CP1,N80)=>{var b=CP1,{Buffer:K6}=N("buffer");b.types={0:"reserved",1:"connect",2:"connack",3:"publish",4:"puback",5:"pubrec",6:"pubrel",7:"pubcomp",8:"subscribe",9:"suback",10:"unsubscribe",11:"unsuback",12:"pingreq",13:"pingresp",14:"disconnect",15:"auth"};b.requiredHeaderFlags={1:0,2:0,4:0,5:0,6:2,7:0,8:2,9:0,10:2,11:0,12:0,13:0,14:0,15:0};b.requiredHeaderFlagsErrors={};for(let Z in b.requiredHeaderFlags){let J=b.requiredHeaderFlags[Z];b.requiredHeaderFlagsErrors[Z]="Invalid header flag bits, must be 0x"+J.toString(16)+" for "+b.types[Z]+" packet"}b.codes={};for(let Z in b.types){let J=b.types[Z];b.codes[J]=Z}b.CMD_SHIFT=4;b.CMD_MASK=240;b.DUP_MASK=8;b.QOS_MASK=3;b.QOS_SHIFT=1;b.RETAIN_MASK=1;b.VARBYTEINT_MASK=127;b.VARBYTEINT_FIN_MASK=128;b.VARBYTEINT_MAX=268435455;b.SESSIONPRESENT_MASK=1;b.SESSIONPRESENT_HEADER=K6.from([b.SESSIONPRESENT_MASK]);b.CONNACK_HEADER=K6.from([b.codes.connack<<b.CMD_SHIFT]);b.USERNAME_MASK=128;b.PASSWORD_MASK=64;b.WILL_RETAIN_MASK=32;b.WILL_QOS_MASK=24;b.WILL_QOS_SHIFT=3;b.WILL_FLAG_MASK=4;b.CLEAN_SESSION_MASK=2;b.CONNECT_HEADER=K6.from([b.codes.connect<<b.CMD_SHIFT]);b.properties={sessionExpiryInterval:17,willDelayInterval:24,receiveMaximum:33,maximumPacketSize:39,topicAliasMaximum:34,requestResponseInformation:25,requestProblemInformation:23,userProperties:38,authenticationMethod:21,authenticationData:22,payloadFormatIndicator:1,messageExpiryInterval:2,contentType:3,responseTopic:8,correlationData:9,maximumQoS:36,retainAvailable:37,assignedClientIdentifier:18,reasonString:31,wildcardSubscriptionAvailable:40,subscriptionIdentifiersAvailable:41,sharedSubscriptionAvailable:42,serverKeepAlive:19,responseInformation:26,serverReference:28,topicAlias:35,subscriptionIdentifier:11};b.propertiesCodes={};for(let Z in b.properties){let J=b.properties[Z];b.propertiesCodes[J]=Z}b.propertiesTypes={sessionExpiryInterval:"int32",willDelayInterval:"int32",receiveMaximum:"int16",maximumPacketSize:"int32",topicAliasMaximum:"int16",requestResponseInformation:"byte",requestProblemInformation:"byte",userProperties:"pair",authenticationMethod:"string",authenticationData:"binary",payloadFormatIndicator:"byte",messageExpiryInterval:"int32",contentType:"string",responseTopic:"string",correlationData:"binary",maximumQoS:"int8",retainAvailable:"byte",assignedClientIdentifier:"string",reasonString:"string",wildcardSubscriptionAvailable:"byte",subscriptionIdentifiersAvailable:"byte",sharedSubscriptionAvailable:"byte",serverKeepAlive:"int16",responseInformation:"string",serverReference:"string",topicAlias:"int16",subscriptionIdentifier:"var"};function P7(Z){return[0,1,2].map((J)=>{return[0,1].map((X)=>{return[0,1].map(($)=>{let Y=K6.alloc(1);return Y.writeUInt8(b.codes[Z]<<b.CMD_SHIFT|(X?b.DUP_MASK:0)|J<<b.QOS_SHIFT|$,0,!0),Y})})})}b.PUBLISH_HEADER=P7("publish");b.SUBSCRIBE_HEADER=P7("subscribe");b.SUBSCRIBE_OPTIONS_QOS_MASK=3;b.SUBSCRIBE_OPTIONS_NL_MASK=1;b.SUBSCRIBE_OPTIONS_NL_SHIFT=2;b.SUBSCRIBE_OPTIONS_RAP_MASK=1;b.SUBSCRIBE_OPTIONS_RAP_SHIFT=3;b.SUBSCRIBE_OPTIONS_RH_MASK=3;b.SUBSCRIBE_OPTIONS_RH_SHIFT=4;b.SUBSCRIBE_OPTIONS_RH=[0,16,32];b.SUBSCRIBE_OPTIONS_NL=4;b.SUBSCRIBE_OPTIONS_RAP=8;b.SUBSCRIBE_OPTIONS_QOS=[0,1,2];b.UNSUBSCRIBE_HEADER=P7("unsubscribe");b.ACKS={unsuback:P7("unsuback"),puback:P7("puback"),pubcomp:P7("pubcomp"),pubrel:P7("pubrel"),pubrec:P7("pubrec")};b.SUBACK_HEADER=K6.from([b.codes.suback<<b.CMD_SHIFT]);b.VERSION3=K6.from([3]);b.VERSION4=K6.from([4]);b.VERSION5=K6.from([5]);b.VERSION131=K6.from([131]);b.VERSION132=K6.from([132]);b.QOS=[0,1,2].map((Z)=>{return K6.from([Z])});b.EMPTY={pingreq:K6.from([b.codes.pingreq<<4,0]),pingresp:K6.from([b.codes.pingresp<<4,0]),disconnect:K6.from([b.codes.disconnect<<4,0])};b.MQTT5_PUBACK_PUBREC_CODES={0:"Success",16:"No matching subscribers",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",144:"Topic Name invalid",145:"Packet identifier in use",151:"Quota exceeded",153:"Payload format invalid"};b.MQTT5_PUBREL_PUBCOMP_CODES={0:"Success",146:"Packet Identifier not found"};b.MQTT5_SUBACK_CODES={0:"Granted QoS 0",1:"Granted QoS 1",2:"Granted QoS 2",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",143:"Topic Filter invalid",145:"Packet Identifier in use",151:"Quota exceeded",158:"Shared Subscriptions not supported",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"};b.MQTT5_UNSUBACK_CODES={0:"Success",17:"No subscription existed",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",143:"Topic Filter invalid",145:"Packet Identifier in use"};b.MQTT5_DISCONNECT_CODES={0:"Normal disconnection",4:"Disconnect with Will Message",128:"Unspecified error",129:"Malformed Packet",130:"Protocol Error",131:"Implementation specific error",135:"Not authorized",137:"Server busy",139:"Server shutting down",141:"Keep Alive timeout",142:"Session taken over",143:"Topic Filter invalid",144:"Topic Name invalid",147:"Receive Maximum exceeded",148:"Topic Alias invalid",149:"Packet too large",150:"Message rate too high",151:"Quota exceeded",152:"Administrative action",153:"Payload format invalid",154:"Retain not supported",155:"QoS not supported",156:"Use another server",157:"Server moved",158:"Shared Subscriptions not supported",159:"Connection rate exceeded",160:"Maximum connect time",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"};b.MQTT5_AUTH_CODES={0:"Success",24:"Continue authentication",25:"Re-authenticate"}});var E80=L((NP1,P80)=>{var Xr0=A80(),{EventEmitter:$r0}=N("events"),R80=C80(),S0=VO(),F0=h6()("mqtt-packet:parser");class vG extends $r0{constructor(){super();this.parser=this.constructor.parser}static parser(Z){if(!(this instanceof vG))return new vG().parser(Z);return this.settings=Z||{},this._states=["_parseHeader","_parseLength","_parsePayload","_newPacket"],this._resetState(),this}_resetState(){F0("_resetState: resetting packet, error, _list, and _stateCounter"),this.packet=new R80,this.error=null,this._list=Xr0(),this._stateCounter=0}parse(Z){if(this.error)this._resetState();this._list.append(Z),F0("parse: current state: %s",this._states[this._stateCounter]);while((this.packet.length!==-1||this._list.length>0)&&this[this._states[this._stateCounter]]()&&!this.error)if(this._stateCounter++,F0("parse: state complete. _stateCounter is now: %d",this._stateCounter),F0("parse: packet.length: %d, buffer list length: %d",this.packet.length,this._list.length),this._stateCounter>=this._states.length)this._stateCounter=0;return F0("parse: exited while loop. packet: %d, buffer list length: %d",this.packet.length,this._list.length),this._list.length}_parseHeader(){let Z=this._list.readUInt8(0),J=Z>>S0.CMD_SHIFT;this.packet.cmd=S0.types[J];let X=Z&15,$=S0.requiredHeaderFlags[J];if($!=null&&X!==$)return this._emitError(Error(S0.requiredHeaderFlagsErrors[J]));if(this.packet.retain=(Z&S0.RETAIN_MASK)!==0,this.packet.qos=Z>>S0.QOS_SHIFT&S0.QOS_MASK,this.packet.qos>2)return this._emitError(Error("Packet must not have both QoS bits set to 1"));return this.packet.dup=(Z&S0.DUP_MASK)!==0,F0("_parseHeader: packet: %o",this.packet),this._list.consume(1),!0}_parseLength(){let Z=this._parseVarByteNum(!0);if(Z)this.packet.length=Z.value,this._list.consume(Z.bytes);return F0("_parseLength %d",Z.value),!!Z}_parsePayload(){F0("_parsePayload: payload %O",this._list);let Z=!1;if(this.packet.length===0||this._list.length>=this.packet.length){switch(this._pos=0,this.packet.cmd){case"connect":this._parseConnect();break;case"connack":this._parseConnack();break;case"publish":this._parsePublish();break;case"puback":case"pubrec":case"pubrel":case"pubcomp":this._parseConfirmation();break;case"subscribe":this._parseSubscribe();break;case"suback":this._parseSuback();break;case"unsubscribe":this._parseUnsubscribe();break;case"unsuback":this._parseUnsuback();break;case"pingreq":case"pingresp":break;case"disconnect":this._parseDisconnect();break;case"auth":this._parseAuth();break;default:this._emitError(Error("Not supported"))}Z=!0}return F0("_parsePayload complete result: %s",Z),Z}_parseConnect(){F0("_parseConnect");let Z,J,X,$,Y={},Q=this.packet,W=this._parseString();if(W===null)return this._emitError(Error("Cannot parse protocolId"));if(W!=="MQTT"&&W!=="MQIsdp")return this._emitError(Error("Invalid protocolId"));if(Q.protocolId=W,this._pos>=this._list.length)return this._emitError(Error("Packet too short"));if(Q.protocolVersion=this._list.readUInt8(this._pos),Q.protocolVersion>=128)Q.bridgeMode=!0,Q.protocolVersion=Q.protocolVersion-128;if(Q.protocolVersion!==3&&Q.protocolVersion!==4&&Q.protocolVersion!==5)return this._emitError(Error("Invalid protocol version"));if(this._pos++,this._pos>=this._list.length)return this._emitError(Error("Packet too short"));if(this._list.readUInt8(this._pos)&1)return this._emitError(Error("Connect flag bit 0 must be 0, but got 1"));Y.username=this._list.readUInt8(this._pos)&S0.USERNAME_MASK,Y.password=this._list.readUInt8(this._pos)&S0.PASSWORD_MASK,Y.will=this._list.readUInt8(this._pos)&S0.WILL_FLAG_MASK;let K=!!(this._list.readUInt8(this._pos)&S0.WILL_RETAIN_MASK),z=(this._list.readUInt8(this._pos)&S0.WILL_QOS_MASK)>>S0.WILL_QOS_SHIFT;if(Y.will)Q.will={},Q.will.retain=K,Q.will.qos=z;else{if(K)return this._emitError(Error("Will Retain Flag must be set to zero when Will Flag is set to 0"));if(z)return this._emitError(Error("Will QoS must be set to zero when Will Flag is set to 0"))}if(Q.clean=(this._list.readUInt8(this._pos)&S0.CLEAN_SESSION_MASK)!==0,this._pos++,Q.keepalive=this._parseNum(),Q.keepalive===-1)return this._emitError(Error("Packet too short"));if(Q.protocolVersion===5){let H=this._parseProperties();if(Object.getOwnPropertyNames(H).length)Q.properties=H}let G=this._parseString();if(G===null)return this._emitError(Error("Packet too short"));if(Q.clientId=G,F0("_parseConnect: packet.clientId: %s",Q.clientId),Y.will){if(Q.protocolVersion===5){let H=this._parseProperties();if(Object.getOwnPropertyNames(H).length)Q.will.properties=H}if(Z=this._parseString(),Z===null)return this._emitError(Error("Cannot parse will topic"));if(Q.will.topic=Z,F0("_parseConnect: packet.will.topic: %s",Q.will.topic),J=this._parseBuffer(),J===null)return this._emitError(Error("Cannot parse will payload"));Q.will.payload=J,F0("_parseConnect: packet.will.paylaod: %s",Q.will.payload)}if(Y.username){if($=this._parseString(),$===null)return this._emitError(Error("Cannot parse username"));Q.username=$,F0("_parseConnect: packet.username: %s",Q.username)}if(Y.password){if(X=this._parseBuffer(),X===null)return this._emitError(Error("Cannot parse password"));Q.password=X}return this.settings=Q,F0("_parseConnect: complete"),Q}_parseConnack(){F0("_parseConnack");let Z=this.packet;if(this._list.length<1)return null;let J=this._list.readUInt8(this._pos++);if(J>1)return this._emitError(Error("Invalid connack flags, bits 7-1 must be set to 0"));if(Z.sessionPresent=!!(J&S0.SESSIONPRESENT_MASK),this.settings.protocolVersion===5)if(this._list.length>=2)Z.reasonCode=this._list.readUInt8(this._pos++);else Z.reasonCode=0;else{if(this._list.length<2)return null;Z.returnCode=this._list.readUInt8(this._pos++)}if(Z.returnCode===-1||Z.reasonCode===-1)return this._emitError(Error("Cannot parse return code"));if(this.settings.protocolVersion===5){let X=this._parseProperties();if(Object.getOwnPropertyNames(X).length)Z.properties=X}F0("_parseConnack: complete")}_parsePublish(){F0("_parsePublish");let Z=this.packet;if(Z.topic=this._parseString(),Z.topic===null)return this._emitError(Error("Cannot parse topic"));if(Z.qos>0){if(!this._parseMessageId())return}if(this.settings.protocolVersion===5){let J=this._parseProperties();if(Object.getOwnPropertyNames(J).length)Z.properties=J}Z.payload=this._list.slice(this._pos,Z.length),F0("_parsePublish: payload from buffer list: %o",Z.payload)}_parseSubscribe(){F0("_parseSubscribe");let Z=this.packet,J,X,$,Y,Q,W,K;if(Z.subscriptions=[],!this._parseMessageId())return;if(this.settings.protocolVersion===5){let z=this._parseProperties();if(Object.getOwnPropertyNames(z).length)Z.properties=z}if(Z.length<=0)return this._emitError(Error("Malformed subscribe, no payload specified"));while(this._pos<Z.length){if(J=this._parseString(),J===null)return this._emitError(Error("Cannot parse topic"));if(this._pos>=Z.length)return this._emitError(Error("Malformed Subscribe Payload"));if(X=this._parseByte(),this.settings.protocolVersion===5){if(X&192)return this._emitError(Error("Invalid subscribe topic flag bits, bits 7-6 must be 0"))}else if(X&252)return this._emitError(Error("Invalid subscribe topic flag bits, bits 7-2 must be 0"));if($=X&S0.SUBSCRIBE_OPTIONS_QOS_MASK,$>2)return this._emitError(Error("Invalid subscribe QoS, must be <= 2"));if(W=(X>>S0.SUBSCRIBE_OPTIONS_NL_SHIFT&S0.SUBSCRIBE_OPTIONS_NL_MASK)!==0,Q=(X>>S0.SUBSCRIBE_OPTIONS_RAP_SHIFT&S0.SUBSCRIBE_OPTIONS_RAP_MASK)!==0,Y=X>>S0.SUBSCRIBE_OPTIONS_RH_SHIFT&S0.SUBSCRIBE_OPTIONS_RH_MASK,Y>2)return this._emitError(Error("Invalid retain handling, must be <= 2"));if(K={topic:J,qos:$},this.settings.protocolVersion===5)K.nl=W,K.rap=Q,K.rh=Y;else if(this.settings.bridgeMode)K.rh=0,K.rap=!0,K.nl=!0;F0("_parseSubscribe: push subscription `%s` to subscription",K),Z.subscriptions.push(K)}}_parseSuback(){F0("_parseSuback");let Z=this.packet;if(this.packet.granted=[],!this._parseMessageId())return;if(this.settings.protocolVersion===5){let J=this._parseProperties();if(Object.getOwnPropertyNames(J).length)Z.properties=J}if(Z.length<=0)return this._emitError(Error("Malformed suback, no payload specified"));while(this._pos<this.packet.length){let J=this._list.readUInt8(this._pos++);if(this.settings.protocolVersion===5){if(!S0.MQTT5_SUBACK_CODES[J])return this._emitError(Error("Invalid suback code"))}else if(J>2&&J!==128)return this._emitError(Error("Invalid suback QoS, must be 0, 1, 2 or 128"));this.packet.granted.push(J)}}_parseUnsubscribe(){F0("_parseUnsubscribe");let Z=this.packet;if(Z.unsubscriptions=[],!this._parseMessageId())return;if(this.settings.protocolVersion===5){let J=this._parseProperties();if(Object.getOwnPropertyNames(J).length)Z.properties=J}if(Z.length<=0)return this._emitError(Error("Malformed unsubscribe, no payload specified"));while(this._pos<Z.length){let J=this._parseString();if(J===null)return this._emitError(Error("Cannot parse topic"));F0("_parseUnsubscribe: push topic `%s` to unsubscriptions",J),Z.unsubscriptions.push(J)}}_parseUnsuback(){F0("_parseUnsuback");let Z=this.packet;if(!this._parseMessageId())return this._emitError(Error("Cannot parse messageId"));if((this.settings.protocolVersion===3||this.settings.protocolVersion===4)&&Z.length!==2)return this._emitError(Error("Malformed unsuback, payload length must be 2"));if(Z.length<=0)return this._emitError(Error("Malformed unsuback, no payload specified"));if(this.settings.protocolVersion===5){let J=this._parseProperties();if(Object.getOwnPropertyNames(J).length)Z.properties=J;Z.granted=[];while(this._pos<this.packet.length){let X=this._list.readUInt8(this._pos++);if(!S0.MQTT5_UNSUBACK_CODES[X])return this._emitError(Error("Invalid unsuback code"));this.packet.granted.push(X)}}}_parseConfirmation(){F0("_parseConfirmation: packet.cmd: `%s`",this.packet.cmd);let Z=this.packet;if(this._parseMessageId(),this.settings.protocolVersion===5){if(Z.length>2){switch(Z.reasonCode=this._parseByte(),this.packet.cmd){case"puback":case"pubrec":if(!S0.MQTT5_PUBACK_PUBREC_CODES[Z.reasonCode])return this._emitError(Error("Invalid "+this.packet.cmd+" reason code"));break;case"pubrel":case"pubcomp":if(!S0.MQTT5_PUBREL_PUBCOMP_CODES[Z.reasonCode])return this._emitError(Error("Invalid "+this.packet.cmd+" reason code"));break}F0("_parseConfirmation: packet.reasonCode `%d`",Z.reasonCode)}else Z.reasonCode=0;if(Z.length>3){let J=this._parseProperties();if(Object.getOwnPropertyNames(J).length)Z.properties=J}}return!0}_parseDisconnect(){let Z=this.packet;if(F0("_parseDisconnect"),this.settings.protocolVersion===5){if(this._list.length>0){if(Z.reasonCode=this._parseByte(),!S0.MQTT5_DISCONNECT_CODES[Z.reasonCode])this._emitError(Error("Invalid disconnect reason code"))}else Z.reasonCode=0;let J=this._parseProperties();if(Object.getOwnPropertyNames(J).length)Z.properties=J}return F0("_parseDisconnect result: true"),!0}_parseAuth(){F0("_parseAuth");let Z=this.packet;if(this.settings.protocolVersion!==5)return this._emitError(Error("Not supported auth packet for this version MQTT"));if(Z.reasonCode=this._parseByte(),!S0.MQTT5_AUTH_CODES[Z.reasonCode])return this._emitError(Error("Invalid auth reason code"));let J=this._parseProperties();if(Object.getOwnPropertyNames(J).length)Z.properties=J;return F0("_parseAuth: result: true"),!0}_parseMessageId(){let Z=this.packet;if(Z.messageId=this._parseNum(),Z.messageId===null)return this._emitError(Error("Cannot parse messageId")),!1;return F0("_parseMessageId: packet.messageId %d",Z.messageId),!0}_parseString(Z){let J=this._parseNum(),X=J+this._pos;if(J===-1||X>this._list.length||X>this.packet.length)return null;let $=this._list.toString("utf8",this._pos,X);return this._pos+=J,F0("_parseString: result: %s",$),$}_parseStringPair(){return F0("_parseStringPair"),{name:this._parseString(),value:this._parseString()}}_parseBuffer(){let Z=this._parseNum(),J=Z+this._pos;if(Z===-1||J>this._list.length||J>this.packet.length)return null;let X=this._list.slice(this._pos,J);return this._pos+=Z,F0("_parseBuffer: result: %o",X),X}_parseNum(){if(this._list.length-this._pos<2)return-1;let Z=this._list.readUInt16BE(this._pos);return this._pos+=2,F0("_parseNum: result: %s",Z),Z}_parse4ByteNum(){if(this._list.length-this._pos<4)return-1;let Z=this._list.readUInt32BE(this._pos);return this._pos+=4,F0("_parse4ByteNum: result: %s",Z),Z}_parseVarByteNum(Z){F0("_parseVarByteNum");let J=4,X=0,$=1,Y=0,Q=!1,W,K=this._pos?this._pos:0;while(X<J&&K+X<this._list.length){if(W=this._list.readUInt8(K+X++),Y+=$*(W&S0.VARBYTEINT_MASK),$*=128,(W&S0.VARBYTEINT_FIN_MASK)===0){Q=!0;break}if(this._list.length<=X)break}if(!Q&&X===J&&this._list.length>=X)this._emitError(Error("Invalid variable byte integer"));if(K)this._pos+=X;if(Q)if(Z)Q={bytes:X,value:Y};else Q=Y;else Q=!1;return F0("_parseVarByteNum: result: %o",Q),Q}_parseByte(){let Z;if(this._pos<this._list.length)Z=this._list.readUInt8(this._pos),this._pos++;return F0("_parseByte: result: %o",Z),Z}_parseByType(Z){switch(F0("_parseByType: type: %s",Z),Z){case"byte":return this._parseByte()!==0;case"int8":return this._parseByte();case"int16":return this._parseNum();case"int32":return this._parse4ByteNum();case"var":return this._parseVarByteNum();case"string":return this._parseString();case"pair":return this._parseStringPair();case"binary":return this._parseBuffer()}}_parseProperties(){F0("_parseProperties");let Z=this._parseVarByteNum(),X=this._pos+Z,$={};while(this._pos<X){let Y=this._parseByte();if(!Y)return this._emitError(Error("Cannot parse property code type")),!1;let Q=S0.propertiesCodes[Y];if(!Q)return this._emitError(Error("Unknown property")),!1;if(Q==="userProperties"){if(!$[Q])$[Q]=Object.create(null);let W=this._parseByType(S0.propertiesTypes[Q]);if($[Q][W.name])if(Array.isArray($[Q][W.name]))$[Q][W.name].push(W.value);else{let K=$[Q][W.name];$[Q][W.name]=[K],$[Q][W.name].push(W.value)}else $[Q][W.name]=W.value;continue}if($[Q])if(Array.isArray($[Q]))$[Q].push(this._parseByType(S0.propertiesTypes[Q]));else $[Q]=[$[Q]],$[Q].push(this._parseByType(S0.propertiesTypes[Q]));else $[Q]=this._parseByType(S0.propertiesTypes[Q])}return $}_newPacket(){if(F0("_newPacket"),this.packet)this._list.consume(this.packet.length),F0("_newPacket: parser emit packet: packet.cmd: %s, packet.payload: %s, packet.length: %d",this.packet.cmd,this.packet.payload,this.packet.length),this.emit("packet",this.packet);return F0("_newPacket: new packet"),this.packet=new R80,this._pos=0,!0}_emitError(Z){F0("_emitError",Z),this.error=Z,this.emit("error",Z)}}P80.exports=vG});var k80=L((RP1,S80)=>{var{Buffer:n3}=N("buffer"),I80={},Yr0=n3.isBuffer(n3.from([1,2]).subarray(0,1));function y80(Z){let J=n3.allocUnsafe(2);return J.writeUInt8(Z>>8,0),J.writeUInt8(Z&255,1),J}function Qr0(){for(let Z=0;Z<65536;Z++)I80[Z]=y80(Z)}function Wr0(Z){let X=0,$=0,Y=n3.allocUnsafe(4);do{if(X=Z%128|0,Z=Z/128|0,Z>0)X=X|128;Y.writeUInt8(X,$++)}while(Z>0&&$<4);if(Z>0)$=0;return Yr0?Y.subarray(0,$):Y.slice(0,$)}function Kr0(Z){let J=n3.allocUnsafe(4);return J.writeUInt32BE(Z,0),J}S80.exports={cache:I80,generateCache:Qr0,generateNumber:y80,genBufVariableByteInt:Wr0,generate4ByteBuffer:Kr0}});var x80=L((PP1,FO)=>{if(typeof process>"u"||!process.version||process.version.indexOf("v0.")===0||process.version.indexOf("v1.")===0&&process.version.indexOf("v1.8.")!==0)FO.exports={nextTick:zr0};else FO.exports=process;function zr0(Z,J,X,$){if(typeof Z!=="function")throw TypeError('"callback" argument must be a function');var Y=arguments.length,Q,W;switch(Y){case 0:case 1:return process.nextTick(Z);case 2:return process.nextTick(function(){Z.call(null,J)});case 3:return process.nextTick(function(){Z.call(null,J,X)});case 4:return process.nextTick(function(){Z.call(null,J,X,$)});default:Q=Array(Y-1),W=0;while(W<Q.length)Q[W++]=arguments[W];return process.nextTick(function(){Z.apply(null,Q)})}}});var LO=L((EP1,u80)=>{var B0=VO(),{Buffer:z0}=N("buffer"),Gr0=z0.allocUnsafe(0),Hr0=z0.from([0]),o3=k80(),Vr0=x80().nextTick,$8=h6()("mqtt-packet:writeToStream"),hG=o3.cache,Fr0=o3.generateNumber,Br0=o3.generateCache,BO=o3.genBufVariableByteInt,Ur0=o3.generate4ByteBuffer,g4=UO,fG=!0;function m80(Z,J,X){if($8("generate called"),J.cork)J.cork(),Vr0(Lr0,J);if(fG)fG=!1,Br0();switch($8("generate: packet.cmd: %s",Z.cmd),Z.cmd){case"connect":return Dr0(Z,J,X);case"connack":return _r0(Z,J,X);case"publish":return Or0(Z,J,X);case"puback":case"pubrec":case"pubrel":case"pubcomp":return wr0(Z,J,X);case"subscribe":return jr0(Z,J,X);case"suback":return Mr0(Z,J,X);case"unsubscribe":return Ar0(Z,J,X);case"unsuback":return Tr0(Z,J,X);case"pingreq":case"pingresp":return qr0(Z,J,X);case"disconnect":return Cr0(Z,J,X);case"auth":return Nr0(Z,J,X);default:return J.destroy(Error("Unknown command")),!1}}Object.defineProperty(m80,"cacheNumbers",{get(){return g4===UO},set(Z){if(Z){if(!hG||Object.keys(hG).length===0)fG=!0;g4=UO}else fG=!1,g4=Rr0}});function Lr0(Z){Z.uncork()}function Dr0(Z,J,X){let $=Z||{},Y=$.protocolId||"MQTT",Q=$.protocolVersion||4,W=$.will,K=$.clean,z=$.keepalive||0,G=$.clientId||"",H=$.username,V=$.password,F=$.properties;if(K===void 0)K=!0;let B=0;if(!Y||typeof Y!=="string"&&!z0.isBuffer(Y))return J.destroy(Error("Invalid protocolId")),!1;else B+=Y.length+2;if(Q!==3&&Q!==4&&Q!==5)return J.destroy(Error("Invalid protocol version")),!1;else B+=1;if((typeof G==="string"||z0.isBuffer(G))&&(G||Q>=4)&&(G||K))B+=z0.byteLength(G)+2;else{if(Q<4)return J.destroy(Error("clientId must be supplied before 3.1.1")),!1;if(K*1===0)return J.destroy(Error("clientId must be given if cleanSession set to 0")),!1}if(typeof z!=="number"||z<0||z>65535||z%1!==0)return J.destroy(Error("Invalid keepalive")),!1;else B+=2;B+=1;let U,D;if(Q===5){if(U=E7(J,F),!U)return!1;B+=U.length}if(W){if(typeof W!=="object")return J.destroy(Error("Invalid will")),!1;if(!W.topic||typeof W.topic!=="string")return J.destroy(Error("Invalid will topic")),!1;else B+=z0.byteLength(W.topic)+2;if(B+=2,W.payload)if(W.payload.length>=0)if(typeof W.payload==="string")B+=z0.byteLength(W.payload);else B+=W.payload.length;else return J.destroy(Error("Invalid will payload")),!1;if(D={},Q===5){if(D=E7(J,W.properties),!D)return!1;B+=D.length}}let _=!1;if(H!=null)if(g80(H))_=!0,B+=z0.byteLength(H)+2;else return J.destroy(Error("Invalid username")),!1;if(V!=null){if(!_)return J.destroy(Error("Username is required to use password")),!1;if(g80(V))B+=d80(V)+2;else return J.destroy(Error("Invalid password")),!1}if(J.write(B0.CONNECT_HEADER),Y8(J,B),Y$(J,Y),$.bridgeMode)Q+=128;J.write(Q===131?B0.VERSION131:Q===132?B0.VERSION132:Q===4?B0.VERSION4:Q===5?B0.VERSION5:B0.VERSION3);let O=0;if(O|=H!=null?B0.USERNAME_MASK:0,O|=V!=null?B0.PASSWORD_MASK:0,O|=W&&W.retain?B0.WILL_RETAIN_MASK:0,O|=W&&W.qos?W.qos<<B0.WILL_QOS_SHIFT:0,O|=W?B0.WILL_FLAG_MASK:0,O|=K?B0.CLEAN_SESSION_MASK:0,J.write(z0.from([O])),g4(J,z),Q===5)U.write();if(Y$(J,G),W){if(Q===5)D.write();sZ(J,W.topic),Y$(J,W.payload)}if(H!=null)Y$(J,H);if(V!=null)Y$(J,V);return!0}function _r0(Z,J,X){let $=X?X.protocolVersion:4,Y=Z||{},Q=$===5?Y.reasonCode:Y.returnCode,W=Y.properties,K=2;if(typeof Q!=="number")return J.destroy(Error("Invalid return code")),!1;let z=null;if($===5){if(z=E7(J,W),!z)return!1;K+=z.length}if(J.write(B0.CONNACK_HEADER),Y8(J,K),J.write(Y.sessionPresent?B0.SESSIONPRESENT_HEADER:Hr0),J.write(z0.from([Q])),z!=null)z.write();return!0}function Or0(Z,J,X){$8("publish: packet: %o",Z);let $=X?X.protocolVersion:4,Y=Z||{},Q=Y.qos||0,W=Y.retain?B0.RETAIN_MASK:0,K=Y.topic,z=Y.payload||Gr0,G=Y.messageId,H=Y.properties,V=0;if(typeof K==="string")V+=z0.byteLength(K)+2;else if(z0.isBuffer(K))V+=K.length+2;else return J.destroy(Error("Invalid topic")),!1;if(!z0.isBuffer(z))V+=z0.byteLength(z);else V+=z.length;if(Q&&typeof G!=="number")return J.destroy(Error("Invalid messageId")),!1;else if(Q)V+=2;let F=null;if($===5){if(F=E7(J,H),!F)return!1;V+=F.length}if(J.write(B0.PUBLISH_HEADER[Q][Y.dup?1:0][W?1:0]),Y8(J,V),g4(J,d80(K)),J.write(K),Q>0)g4(J,G);if(F!=null)F.write();return $8("publish: payload: %o",z),J.write(z)}function wr0(Z,J,X){let $=X?X.protocolVersion:4,Y=Z||{},Q=Y.cmd||"puback",W=Y.messageId,K=Y.dup&&Q==="pubrel"?B0.DUP_MASK:0,z=0,G=Y.reasonCode,H=Y.properties,V=$===5?3:2;if(Q==="pubrel")z=1;if(typeof W!=="number")return J.destroy(Error("Invalid messageId")),!1;let F=null;if($===5){if(typeof H==="object"){if(F=a3(J,H,X,V),!F)return!1;V+=F.length}}if(J.write(B0.ACKS[Q][z][K][0]),V===3)V+=G!==0?1:-1;if(Y8(J,V),g4(J,W),$===5&&V!==2)J.write(z0.from([G]));if(F!==null)F.write();else if(V===4)J.write(z0.from([0]));return!0}function jr0(Z,J,X){$8("subscribe: packet: ");let $=X?X.protocolVersion:4,Y=Z||{},Q=Y.dup?B0.DUP_MASK:0,W=Y.messageId,K=Y.subscriptions,z=Y.properties,G=0;if(typeof W!=="number")return J.destroy(Error("Invalid messageId")),!1;else G+=2;let H=null;if($===5){if(H=E7(J,z),!H)return!1;G+=H.length}if(typeof K==="object"&&K.length)for(let F=0;F<K.length;F+=1){let B=K[F].topic,U=K[F].qos;if(typeof B!=="string")return J.destroy(Error("Invalid subscriptions - invalid topic")),!1;if(typeof U!=="number")return J.destroy(Error("Invalid subscriptions - invalid qos")),!1;if($===5){if(typeof(K[F].nl||!1)!=="boolean")return J.destroy(Error("Invalid subscriptions - invalid No Local")),!1;if(typeof(K[F].rap||!1)!=="boolean")return J.destroy(Error("Invalid subscriptions - invalid Retain as Published")),!1;let O=K[F].rh||0;if(typeof O!=="number"||O>2)return J.destroy(Error("Invalid subscriptions - invalid Retain Handling")),!1}G+=z0.byteLength(B)+2+1}else return J.destroy(Error("Invalid subscriptions")),!1;if($8("subscribe: writing to stream: %o",B0.SUBSCRIBE_HEADER),J.write(B0.SUBSCRIBE_HEADER[1][Q?1:0][0]),Y8(J,G),g4(J,W),H!==null)H.write();let V=!0;for(let F of K){let{topic:B,qos:U}=F,D=+F.nl,_=+F.rap,O=F.rh,w;if(sZ(J,B),w=B0.SUBSCRIBE_OPTIONS_QOS[U],$===5)w|=D?B0.SUBSCRIBE_OPTIONS_NL:0,w|=_?B0.SUBSCRIBE_OPTIONS_RAP:0,w|=O?B0.SUBSCRIBE_OPTIONS_RH[O]:0;V=J.write(z0.from([w]))}return V}function Mr0(Z,J,X){let $=X?X.protocolVersion:4,Y=Z||{},Q=Y.messageId,W=Y.granted,K=Y.properties,z=0;if(typeof Q!=="number")return J.destroy(Error("Invalid messageId")),!1;else z+=2;if(typeof W==="object"&&W.length)for(let H=0;H<W.length;H+=1){if(typeof W[H]!=="number")return J.destroy(Error("Invalid qos vector")),!1;z+=1}else return J.destroy(Error("Invalid qos vector")),!1;let G=null;if($===5){if(G=a3(J,K,X,z),!G)return!1;z+=G.length}if(J.write(B0.SUBACK_HEADER),Y8(J,z),g4(J,Q),G!==null)G.write();return J.write(z0.from(W))}function Ar0(Z,J,X){let $=X?X.protocolVersion:4,Y=Z||{},Q=Y.messageId,W=Y.dup?B0.DUP_MASK:0,K=Y.unsubscriptions,z=Y.properties,G=0;if(typeof Q!=="number")return J.destroy(Error("Invalid messageId")),!1;else G+=2;if(typeof K==="object"&&K.length)for(let F=0;F<K.length;F+=1){if(typeof K[F]!=="string")return J.destroy(Error("Invalid unsubscriptions")),!1;G+=z0.byteLength(K[F])+2}else return J.destroy(Error("Invalid unsubscriptions")),!1;let H=null;if($===5){if(H=E7(J,z),!H)return!1;G+=H.length}if(J.write(B0.UNSUBSCRIBE_HEADER[1][W?1:0][0]),Y8(J,G),g4(J,Q),H!==null)H.write();let V=!0;for(let F=0;F<K.length;F++)V=sZ(J,K[F]);return V}function Tr0(Z,J,X){let $=X?X.protocolVersion:4,Y=Z||{},Q=Y.messageId,W=Y.dup?B0.DUP_MASK:0,K=Y.granted,z=Y.properties,G=Y.cmd,H=0,V=2;if(typeof Q!=="number")return J.destroy(Error("Invalid messageId")),!1;if($===5)if(typeof K==="object"&&K.length)for(let B=0;B<K.length;B+=1){if(typeof K[B]!=="number")return J.destroy(Error("Invalid qos vector")),!1;V+=1}else return J.destroy(Error("Invalid qos vector")),!1;let F=null;if($===5){if(F=a3(J,z,X,V),!F)return!1;V+=F.length}if(J.write(B0.ACKS[G][0][W][0]),Y8(J,V),g4(J,Q),F!==null)F.write();if($===5)J.write(z0.from(K));return!0}function qr0(Z,J,X){return J.write(B0.EMPTY[Z.cmd])}function Cr0(Z,J,X){let $=X?X.protocolVersion:4,Y=Z||{},Q=Y.reasonCode,W=Y.properties,K=$===5?1:0,z=null;if($===5){if(z=a3(J,W,X,K),!z)return!1;K+=z.length}if(J.write(z0.from([B0.codes.disconnect<<4])),Y8(J,K),$===5)J.write(z0.from([Q]));if(z!==null)z.write();return!0}function Nr0(Z,J,X){let $=X?X.protocolVersion:4,Y=Z||{},Q=Y.reasonCode,W=Y.properties,K=$===5?1:0;if($!==5)J.destroy(Error("Invalid mqtt version for auth packet"));let z=a3(J,W,X,K);if(!z)return!1;if(K+=z.length,J.write(z0.from([B0.codes.auth<<4])),Y8(J,K),J.write(z0.from([Q])),z!==null)z.write();return!0}var v80={};function Y8(Z,J){if(J>B0.VARBYTEINT_MAX)return Z.destroy(Error(`Invalid variable byte integer: ${J}`)),!1;let X=v80[J];if(!X){if(X=BO(J),J<16384)v80[J]=X}return $8("writeVarByteInt: writing to stream: %o",X),Z.write(X)}function sZ(Z,J){let X=z0.byteLength(J);return g4(Z,X),$8("writeString: %s",J),Z.write(J,"utf8")}function h80(Z,J,X){sZ(Z,J),sZ(Z,X)}function UO(Z,J){return $8("writeNumberCached: number: %d",J),$8("writeNumberCached: %o",hG[J]),Z.write(hG[J])}function Rr0(Z,J){let X=Fr0(J);return $8("writeNumberGenerated: %o",X),Z.write(X)}function Pr0(Z,J){let X=Ur0(J);return $8("write4ByteNumber: %o",X),Z.write(X)}function Y$(Z,J){if(typeof J==="string")sZ(Z,J);else if(J)g4(Z,J.length),Z.write(J);else g4(Z,0)}function E7(Z,J){if(typeof J!=="object"||J.length!=null)return{length:1,write(){b80(Z,{},0)}};let X=0;function $(Q,W){let K=B0.propertiesTypes[Q],z=0;switch(K){case"byte":{if(typeof W!=="boolean")return Z.destroy(Error(`Invalid ${Q}: ${W}`)),!1;z+=2;break}case"int8":{if(typeof W!=="number"||W<0||W>255)return Z.destroy(Error(`Invalid ${Q}: ${W}`)),!1;z+=2;break}case"binary":{if(W&&W===null)return Z.destroy(Error(`Invalid ${Q}: ${W}`)),!1;z+=1+z0.byteLength(W)+2;break}case"int16":{if(typeof W!=="number"||W<0||W>65535)return Z.destroy(Error(`Invalid ${Q}: ${W}`)),!1;z+=3;break}case"int32":{if(typeof W!=="number"||W<0||W>4294967295)return Z.destroy(Error(`Invalid ${Q}: ${W}`)),!1;z+=5;break}case"var":{if(typeof W!=="number"||W<0||W>268435455)return Z.destroy(Error(`Invalid ${Q}: ${W}`)),!1;z+=1+z0.byteLength(BO(W));break}case"string":{if(typeof W!=="string")return Z.destroy(Error(`Invalid ${Q}: ${W}`)),!1;z+=3+z0.byteLength(W.toString());break}case"pair":{if(typeof W!=="object")return Z.destroy(Error(`Invalid ${Q}: ${W}`)),!1;z+=Object.getOwnPropertyNames(W).reduce((G,H)=>{let V=W[H];if(Array.isArray(V))G+=V.reduce((F,B)=>{return F+=3+z0.byteLength(H.toString())+2+z0.byteLength(B.toString()),F},0);else G+=3+z0.byteLength(H.toString())+2+z0.byteLength(W[H].toString());return G},0);break}default:return Z.destroy(Error(`Invalid property ${Q}: ${W}`)),!1}return z}if(J)for(let Q in J){let W=0,K=0,z=J[Q];if(z===void 0)continue;else if(Array.isArray(z))for(let G=0;G<z.length;G++){if(K=$(Q,z[G]),!K)return!1;W+=K}else{if(K=$(Q,z),!K)return!1;W=K}if(!W)return!1;X+=W}return{length:z0.byteLength(BO(X))+X,write(){b80(Z,J,X)}}}function a3(Z,J,X,$){let Y=["reasonString","userProperties"],Q=X&&X.properties&&X.properties.maximumPacketSize?X.properties.maximumPacketSize:0,W=E7(Z,J);if(Q)while($+W.length>Q){let K=Y.shift();if(K&&J[K])delete J[K],W=E7(Z,J);else return!1}return W}function f80(Z,J,X){switch(B0.propertiesTypes[J]){case"byte":{Z.write(z0.from([B0.properties[J]])),Z.write(z0.from([+X]));break}case"int8":{Z.write(z0.from([B0.properties[J]])),Z.write(z0.from([X]));break}case"binary":{Z.write(z0.from([B0.properties[J]])),Y$(Z,X);break}case"int16":{Z.write(z0.from([B0.properties[J]])),g4(Z,X);break}case"int32":{Z.write(z0.from([B0.properties[J]])),Pr0(Z,X);break}case"var":{Z.write(z0.from([B0.properties[J]])),Y8(Z,X);break}case"string":{Z.write(z0.from([B0.properties[J]])),sZ(Z,X);break}case"pair":{Object.getOwnPropertyNames(X).forEach((Y)=>{let Q=X[Y];if(Array.isArray(Q))Q.forEach((W)=>{Z.write(z0.from([B0.properties[J]])),h80(Z,Y.toString(),W.toString())});else Z.write(z0.from([B0.properties[J]])),h80(Z,Y.toString(),Q.toString())});break}default:return Z.destroy(Error(`Invalid property ${J} value: ${X}`)),!1}}function b80(Z,J,X){Y8(Z,X);for(let $ in J)if(Object.prototype.hasOwnProperty.call(J,$)&&J[$]!=null){let Y=J[$];if(Array.isArray(Y))for(let Q=0;Q<Y.length;Q++)f80(Z,$,Y[Q]);else f80(Z,$,Y)}}function d80(Z){if(!Z)return 0;else if(Z instanceof z0)return Z.length;else return z0.byteLength(Z)}function g80(Z){return typeof Z==="string"||Z instanceof z0}u80.exports=m80});var i80=L((IP1,p80)=>{var Er0=LO(),{EventEmitter:Ir0}=N("events"),{Buffer:c80}=N("buffer");function yr0(Z,J){let X=new l80;return Er0(Z,X,J),X.concat()}class l80 extends Ir0{constructor(){super();this._array=Array(20),this._i=0}write(Z){return this._array[this._i++]=Z,!0}concat(){let Z=0,J=Array(this._array.length),X=this._array,$=0,Y;for(Y=0;Y<X.length&&X[Y]!==void 0;Y++){if(typeof X[Y]!=="string")J[Y]=X[Y].length;else J[Y]=c80.byteLength(X[Y]);Z+=J[Y]}let Q=c80.allocUnsafe(Z);for(Y=0;Y<X.length&&X[Y]!==void 0;Y++)if(typeof X[Y]!=="string")X[Y].copy(Q,$),$+=J[Y];else Q.write(X[Y],$),$+=J[Y];return Q}destroy(Z){if(Z)this.emit("error",Z)}}p80.exports=yr0});var bG=L((Sr0)=>{Sr0.parser=E80().parser;Sr0.generate=i80();Sr0.writeToStream=LO()});var a80=L((SP1,o80)=>{o80.exports=n80;function n80(Z,J){if(Z&&J)return n80(Z)(J);if(typeof Z!=="function")throw TypeError("need wrapper function");return Object.keys(Z).forEach(function($){X[$]=Z[$]}),X;function X(){var $=Array(arguments.length);for(var Y=0;Y<$.length;Y++)$[Y]=arguments[Y];var Q=Z.apply(this,$),W=$[$.length-1];if(typeof Q==="function"&&Q!==W)Object.keys(W).forEach(function(K){Q[K]=W[K]});return Q}}});var t80=L((kP1,DO)=>{var r80=a80();DO.exports=r80(gG);DO.exports.strict=r80(s80);gG.proto=gG(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return gG(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return s80(this)},configurable:!0})});function gG(Z){var J=function(){if(J.called)return J.value;return J.called=!0,J.value=Z.apply(this,arguments)};return J.called=!1,J}function s80(Z){var J=function(){if(J.called)throw Error(J.onceError);return J.called=!0,J.value=Z.apply(this,arguments)},X=Z.name||"Function wrapped with `once`";return J.onceError=X+" shouldn't be called more than once",J.called=!1,J}});var J50=L((xP1,Z50)=>{var hr0=t80(),fr0=function(){},br0=global.Bare?queueMicrotask:process.nextTick.bind(process),gr0=function(Z){return Z.setHeader&&typeof Z.abort==="function"},mr0=function(Z){return Z.stdio&&Array.isArray(Z.stdio)&&Z.stdio.length===3},e80=function(Z,J,X){if(typeof J==="function")return e80(Z,null,J);if(!J)J={};X=hr0(X||fr0);var{_writableState:$,_readableState:Y}=Z,Q=J.readable||J.readable!==!1&&Z.readable,W=J.writable||J.writable!==!1&&Z.writable,K=!1,z=function(){if(!Z.writable)G()},G=function(){if(W=!1,!Q)X.call(Z)},H=function(){if(Q=!1,!W)X.call(Z)},V=function(_){X.call(Z,_?Error("exited with error code: "+_):null)},F=function(_){X.call(Z,_)},B=function(){br0(U)},U=function(){if(K)return;if(Q&&!(Y&&(Y.ended&&!Y.destroyed)))return X.call(Z,Error("premature close"));if(W&&!($&&($.ended&&!$.destroyed)))return X.call(Z,Error("premature close"))},D=function(){Z.req.on("finish",G)};if(gr0(Z))if(Z.on("complete",G),Z.on("abort",B),Z.req)D();else Z.on("request",D);else if(W&&!$)Z.on("end",z),Z.on("close",z);if(mr0(Z))Z.on("exit",V);if(Z.on("end",H),Z.on("finish",G),J.error!==!1)Z.on("error",F);return Z.on("close",B),function(){if(K=!0,Z.removeListener("complete",G),Z.removeListener("abort",B),Z.removeListener("request",D),Z.req)Z.req.removeListener("finish",G);Z.removeListener("end",z),Z.removeListener("close",z),Z.removeListener("finish",G),Z.removeListener("exit",V),Z.removeListener("end",H),Z.removeListener("error",F),Z.removeListener("close",B)}};Z50.exports=e80});var D9=L((vP1,X50)=>{var dr0=bG();function ur0(Z,J,X){let $=null;if(Z.connecting||Z.connected)try{if(!dr0.writeToStream(J,Z.conn)&&!Z.errored){Z.conn.once("drain",X);return}}catch(Y){$=Error("packet received not valid")}else $=Error("connection closed");setImmediate(X,$,Z)}X50.exports=ur0});var _O=L((hP1,Q50)=>{var $50=lX(),cr0=N("util");function Y50(Z,J){if($50.call(this,Z,J.broker),this.writeCallback=J._onError.bind(J),!Z.messageId)if(this.messageId=J._nextId,J._nextId>=65535)J._nextId=1;else J._nextId++;else this.messageId=Z.messageId}cr0.inherits(Y50,$50);Q50.exports=Y50});var z50=L((fP1,K50)=>{var lr0=nz(),W50=[];function pr0(Z,J){if(Array.isArray(Z))J=Z,Z=null;var X=lr0(ir0);return J?Q:$;function $(){var W=X.get();if(W.release=Y,arguments.length===3)W.context=arguments[0],W.list=arguments[1],W.callback=arguments[2]||r3;else W.context=Z,W.list=arguments[0],W.callback=arguments[1]||r3;W.work()}function Y(W){X.release(W)}function Q(){var W=X.get();W.release=Y,W.list=J;var K,z,G=arguments.length-1;switch(W.context=this||Z,W.callback=arguments[G]||r3,G){case 0:W.work();break;case 1:W.work(null,arguments[0]);break;case 2:W.work(null,arguments[0],arguments[1]);break;case 3:W.work(null,arguments[0],arguments[1],arguments[2]);break;case 4:W.work(null,arguments[0],arguments[1],arguments[2],arguments[3]);break;default:K=Array(G+1),K[0]=null;for(z=0;z<G;z++)K[z+1]=arguments[z];W.work.apply(null,K)}}}function r3(){}function ir0(){this.list=W50,this.callback=r3,this.count=0,this.context=void 0,this.release=r3;var Z=this;this.work=function J(){if(arguments.length>0&&arguments[0])return Z.callback.call(Z.context,arguments[0]);var X=arguments.length,$,Y,Q;if(Z.count<Z.list.length)switch(Q=Z.list[Z.count++],X){case 0:case 1:return Q.call(Z.context,J);case 2:return Q.call(Z.context,arguments[1],J);case 3:return Q.call(Z.context,arguments[1],arguments[2],J);case 4:return Q.call(Z.context,arguments[1],arguments[2],arguments[3],J);default:Y=Array(X);for($=1;$<X;$++)Y[$-1]=arguments[$];Y[X-1]=J,Q.apply(Z.context,Y)}else{switch(X){case 0:Z.callback.call(Z.context);break;case 1:Z.callback.call(Z.context,arguments[0]);break;case 2:Z.callback.call(Z.context,arguments[0],arguments[1]);break;case 3:Z.callback.call(Z.context,arguments[0],arguments[1],arguments[2]);break;case 4:Z.callback.call(Z.context,arguments[0],arguments[1],arguments[2],arguments[3]);break;default:Y=Array(X);for($=0;$<X;$++)Y[$]=arguments[$];Z.callback.apply(Z.context,Y)}Z.context=void 0,Z.list=W50,Z.count=0,Z.release(Z)}}}K50.exports=pr0});var tZ=L((bP1,G50)=>{var{Transform:nr0,Writable:or0}=N("stream");function ar0(Z,J){if(!Z||Z.length===0)return Error("impossible to "+J+" to an empty topic");let X=Z.length-1,$=X-1,Y=$>0&&Z.charCodeAt($)!==47;for(let Q=0;Q<Z.length;Q++)switch(Z.charCodeAt(Q)){case 35:{if(Q!==X||Y)return Error("# is only allowed in "+J+" in the last position");break}case 43:{let W=Q<X-1&&Z.charCodeAt(Q+1)!==47,K=Q>1&&Z.charCodeAt(Q-1)!==47;if(W||K)return Error("+ is only allowed in "+J+" between /");break}}}function rr0(Z){return new nr0({objectMode:!0,transform:Z})}function sr0(Z){return new or0({objectMode:!0,writev:function(J,X){Z(J.map(($)=>$.chunk),X)}})}G50.exports={validateTopic:ar0,through:rr0,bulk:sr0,$SYS_PREFIX:"$SYS/"}});var mG=L((gP1,L50)=>{var V50=z50(),F50=lX(),{through:tr0}=tZ(),{validateTopic:er0,$SYS_PREFIX:Zs0}=tZ(),Js0=D9(),Xs0=V50([B50,Vs0,U50]),$s0=V50([B50,U50]);function Ys0(Z,J){this.cmd="suback",this.messageId=Z.messageId,this.granted=J}function H50(Z,J,X,$,Y){this.qos=Z,this.func=J,this.rh=X,this.rap=$,this.nl=Y}function Qs0(Z,J,X,$){this.client=Z,this.packet=J,this.actions=X?$s0:Xs0,this.finish=$,this.subState=[]}function Ws0(Z,J,X,$,Y,Q){this.client=Z,this.packet=J,this.granted=X,this.rh=$,this.rap=Y,this.nl=Q}function Ks0(Z){let J={};for(let $=0;$<Z.length;$++){let Y=Z[$];J[Y.topic]=Y}let X=[];for(let $ in J)X.push(J[$]);return X}function zs0(Z,J,X,$){J.subscriptions=J.subscriptions.length===1?J.subscriptions:Ks0(J.subscriptions),Z.broker._parallel(new Qs0(Z,J,X,$),Gs0,J.subscriptions,X?$:Bs0)}function Gs0(Z,J){let X=new Ws0(this.client,this.packet,Z.qos,Z.rh,Z.rap,Z.nl);this.subState.push(X),this.actions.call(X,Z,J)}function B50(Z,J){let X=er0(Z.topic,"SUBSCRIBE");if(X)return J(X);let $=this.client;$.broker.authorizeSubscribe($,Z,J)}function Hs0(Z){return function(X,$){if(X.topic.charCodeAt(0)===36)$();else Z(X,$)}}function Vs0(Z,J){if(!Z||typeof Z!=="object")return this.granted=128,J(null,null);let X=this.packet,$=this.client;if($.clean)return J(null,Z);$.broker.persistence.addSubscriptions($,X.subscriptions,function(Q){J(Q,Z)})}function U50(Z,J){if(!Z||typeof Z!=="object")return J();let X=this.client,$=X.broker,Y=Z.topic,Q=Z.qos,W=this.rh,K=this.rap,z=this.nl,G=Q>0?X.deliverQoS:X.deliver0,H=G;if(G=function(F,B){if(F=new F50(F,$),F.nl=z,!K)F.retain=!1;H(F,B)},Fs0(Y))G=Hs0(G);if(X.closed||X.broker.closed)return;if(!X.subscriptions[Y])X.subscriptions[Y]=new H50(Q,G,W,K,z),$.subscribe(Y,G,J);else if(X.subscriptions[Y].qos!==Q||X.subscriptions[Y].rh!==W||X.subscriptions[Y].rap!==K||X.subscriptions[Y].nl!==z)$.unsubscribe(Y,X.subscriptions[Y].func),X.subscriptions[Y]=new H50(Q,G,W,K,z),$.subscribe(Y,G,J);else J()}function Fs0(Z){let J=Z.charCodeAt(0);return J===43||J===35}function Bs0(Z){let J=this.finish;if(Z)return J(Z);let X=this.packet,$=this.client;if(X.messageId!==void 0)Js0($,new Ys0(X,this.subState.map((K)=>K.granted)),J);else J();let Y=$.broker,Q=X.subscriptions,W=[];for(let K=0;K<Q.length;K++){if(this.subState[K].granted!==128)W.push(Q[K].topic);Q[K].qos=this.subState[K].granted}if(this.subState=[],Y.emit("subscribe",Q,$),Y.publish({topic:Zs0+Y.id+"/new/subscribes",payload:Buffer.from(JSON.stringify({clientId:$.id,subs:Q}),"utf8")},Us0),W.length>0)Y.persistence.createRetainedStreamCombi(W).pipe(tr0(function(H,V,F){H=new F50({cmd:H.cmd,qos:H.qos,topic:H.topic,payload:H.payload,retain:!0},Y),H.brokerId=null,$.deliverQoS(H,F)}))}function Us0(){}L50.exports=zs0});var wO=L((mP1,D50)=>{var Ls0=D9(),{validateTopic:Ds0,$SYS_PREFIX:_s0}=tZ();function Os0(Z){this.cmd="unsuback",this.messageId=Z.messageId}function ws0(Z,J,X){this.client=Z,this.packet=J,this.finish=X}function js0(Z,J,X){let $=Z.broker,Y=J.unsubscriptions,Q;for(let W=0;W<Y.length;W++)if(Q=Ds0(Y[W],"UNSUBSCRIBE"),Q)return X(Q);if(J.messageId!==void 0){if(Z.clean)return OO(Z,J,X);$.persistence.removeSubscriptions(Z,Y,function(W){if(W)return X(W);OO(Z,J,X)})}else OO(Z,J,X)}function OO(Z,J,X){Z.broker._parallel(new ws0(Z,J,X),Ms0,J.unsubscriptions,As0)}function Ms0(Z,J){let X=this.client,$=X.broker,Y=X.subscriptions[Z];if(Y){let Q=Y.func;delete X.subscriptions[Z],$.unsubscribe(Z,Q,J)}else J()}function As0(Z){let J=this.client;if(Z){J.emit("error",Z);return}let X=this.packet,$=this.finish;if(X.messageId!==void 0)Ls0(J,new Os0(X),$);else $();if((!J.closed||J.clean===!0)&&X.unsubscriptions.length>0)J.broker.emit("unsubscribe",X.unsubscriptions,J),J.broker.publish({topic:_s0+J.broker.id+"/new/unsubscribes",payload:Buffer.from(JSON.stringify({clientId:J.id,subs:X.unsubscriptions}),"utf8")},Ts0)}function Ts0(){}D50.exports=js0});var O50=L((dP1,_50)=>{_50.exports=function(){let J=process.hrtime();return Math.floor(J[0]*1000+J[1]/1e6)}});var j50=L((uP1,w50)=>{w50.exports={clearInterval,clearTimeout,setInterval,setTimeout}});var T50=L((cP1,MO)=>{var dG=O50(),{clearTimeout:M50,setTimeout:A50}=j50();class jO{constructor(Z,J,X){let $=this;this._started=dG(),this._rescheduled=0,this._scheduled=J,this._args=X,this._triggered=!1,this._timerWrapper=()=>{if($._rescheduled>0)$._scheduled=$._rescheduled-(dG()-$._started),$._schedule($._scheduled);else $._triggered=!0,Z.apply(null,$._args)},this._timer=A50(this._timerWrapper,J)}reschedule(Z){if(!Z)Z=this._scheduled;let J=dG();if(J+Z-(this._started+this._scheduled)<0)M50(this._timer),this._schedule(Z);else if(!this._triggered)this._started=J,this._rescheduled=Z;else this._schedule(Z)}_schedule(Z){this._triggered=!1,this._started=dG(),this._rescheduled=0,this._scheduled=Z,this._timer=A50(this._timerWrapper,Z)}clear(){M50(this._timer)}}function qs0(){if(typeof arguments[0]!=="function")throw Error("callback needed");if(typeof arguments[1]!=="number")throw Error("timeout needed");let Z;if(arguments.length>0){Z=Array(arguments.length-2);for(var J=0;J<Z.length;J++)Z[J]=arguments[J+2]}return new jO(arguments[0],arguments[1],Z)}MO.exports=qs0;MO.exports.Retimer=jO});var AO=L((q50)=>{Object.defineProperty(q50,"__esModule",{value:!0});q50.default=Rs0;var Cs0=Ns0(N("crypto"));function Ns0(Z){return Z&&Z.__esModule?Z:{default:Z}}var cG=new Uint8Array(256),uG=cG.length;function Rs0(){if(uG>cG.length-16)Cs0.default.randomFillSync(cG),uG=0;return cG.slice(uG,uG+=16)}});var R50=L((C50)=>{Object.defineProperty(C50,"__esModule",{value:!0});C50.default=void 0;var Es0=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;C50.default=Es0});var s3=L((P50)=>{Object.defineProperty(P50,"__esModule",{value:!0});P50.default=void 0;var Is0=ys0(R50());function ys0(Z){return Z&&Z.__esModule?Z:{default:Z}}function Ss0(Z){return typeof Z==="string"&&Is0.default.test(Z)}var ks0=Ss0;P50.default=ks0});var t3=L((I50)=>{Object.defineProperty(I50,"__esModule",{value:!0});I50.default=void 0;var xs0=vs0(s3());function vs0(Z){return Z&&Z.__esModule?Z:{default:Z}}var L4=[];for(let Z=0;Z<256;++Z)L4.push((Z+256).toString(16).substr(1));function hs0(Z,J=0){let X=(L4[Z[J+0]]+L4[Z[J+1]]+L4[Z[J+2]]+L4[Z[J+3]]+"-"+L4[Z[J+4]]+L4[Z[J+5]]+"-"+L4[Z[J+6]]+L4[Z[J+7]]+"-"+L4[Z[J+8]]+L4[Z[J+9]]+"-"+L4[Z[J+10]]+L4[Z[J+11]]+L4[Z[J+12]]+L4[Z[J+13]]+L4[Z[J+14]]+L4[Z[J+15]]).toLowerCase();if(!(0,xs0.default)(X))throw TypeError("Stringified UUID is invalid");return X}var fs0=hs0;I50.default=fs0});var h50=L((x50)=>{Object.defineProperty(x50,"__esModule",{value:!0});x50.default=void 0;var bs0=k50(AO()),gs0=k50(t3());function k50(Z){return Z&&Z.__esModule?Z:{default:Z}}var S50,TO,qO=0,CO=0;function ms0(Z,J,X){let $=J&&X||0,Y=J||Array(16);Z=Z||{};let Q=Z.node||S50,W=Z.clockseq!==void 0?Z.clockseq:TO;if(Q==null||W==null){let F=Z.random||(Z.rng||bs0.default)();if(Q==null)Q=S50=[F[0]|1,F[1],F[2],F[3],F[4],F[5]];if(W==null)W=TO=(F[6]<<8|F[7])&16383}let K=Z.msecs!==void 0?Z.msecs:Date.now(),z=Z.nsecs!==void 0?Z.nsecs:CO+1,G=K-qO+(z-CO)/1e4;if(G<0&&Z.clockseq===void 0)W=W+1&16383;if((G<0||K>qO)&&Z.nsecs===void 0)z=0;if(z>=1e4)throw Error("uuid.v1(): Can't create more than 10M uuids/sec");qO=K,CO=z,TO=W,K+=12219292800000;let H=((K&268435455)*1e4+z)%4294967296;Y[$++]=H>>>24&255,Y[$++]=H>>>16&255,Y[$++]=H>>>8&255,Y[$++]=H&255;let V=K/4294967296*1e4&268435455;Y[$++]=V>>>8&255,Y[$++]=V&255,Y[$++]=V>>>24&15|16,Y[$++]=V>>>16&255,Y[$++]=W>>>8|128,Y[$++]=W&255;for(let F=0;F<6;++F)Y[$+F]=Q[F];return J||(0,gs0.default)(Y)}var ds0=ms0;x50.default=ds0});var NO=L((f50)=>{Object.defineProperty(f50,"__esModule",{value:!0});f50.default=void 0;var us0=cs0(s3());function cs0(Z){return Z&&Z.__esModule?Z:{default:Z}}function ls0(Z){if(!(0,us0.default)(Z))throw TypeError("Invalid UUID");let J,X=new Uint8Array(16);return X[0]=(J=parseInt(Z.slice(0,8),16))>>>24,X[1]=J>>>16&255,X[2]=J>>>8&255,X[3]=J&255,X[4]=(J=parseInt(Z.slice(9,13),16))>>>8,X[5]=J&255,X[6]=(J=parseInt(Z.slice(14,18),16))>>>8,X[7]=J&255,X[8]=(J=parseInt(Z.slice(19,23),16))>>>8,X[9]=J&255,X[10]=(J=parseInt(Z.slice(24,36),16))/1099511627776&255,X[11]=J/4294967296&255,X[12]=J>>>24&255,X[13]=J>>>16&255,X[14]=J>>>8&255,X[15]=J&255,X}var ps0=ls0;f50.default=ps0});var RO=L((u50)=>{Object.defineProperty(u50,"__esModule",{value:!0});u50.default=as0;u50.URL=u50.DNS=void 0;var is0=g50(t3()),ns0=g50(NO());function g50(Z){return Z&&Z.__esModule?Z:{default:Z}}function os0(Z){Z=unescape(encodeURIComponent(Z));let J=[];for(let X=0;X<Z.length;++X)J.push(Z.charCodeAt(X));return J}var m50="6ba7b810-9dad-11d1-80b4-00c04fd430c8";u50.DNS=m50;var d50="6ba7b811-9dad-11d1-80b4-00c04fd430c8";u50.URL=d50;function as0(Z,J,X){function $(Y,Q,W,K){if(typeof Y==="string")Y=os0(Y);if(typeof Q==="string")Q=(0,ns0.default)(Q);if(Q.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let z=new Uint8Array(16+Y.length);if(z.set(Q),z.set(Y,Q.length),z=X(z),z[6]=z[6]&15|J,z[8]=z[8]&63|128,W){K=K||0;for(let G=0;G<16;++G)W[K+G]=z[G];return W}return(0,is0.default)(z)}try{$.name=Z}catch(Y){}return $.DNS=m50,$.URL=d50,$}});var i50=L((l50)=>{Object.defineProperty(l50,"__esModule",{value:!0});l50.default=void 0;var ts0=es0(N("crypto"));function es0(Z){return Z&&Z.__esModule?Z:{default:Z}}function Zt0(Z){if(Array.isArray(Z))Z=Buffer.from(Z);else if(typeof Z==="string")Z=Buffer.from(Z,"utf8");return ts0.default.createHash("md5").update(Z).digest()}var Jt0=Zt0;l50.default=Jt0});var r50=L((o50)=>{Object.defineProperty(o50,"__esModule",{value:!0});o50.default=void 0;var Xt0=n50(RO()),$t0=n50(i50());function n50(Z){return Z&&Z.__esModule?Z:{default:Z}}var Yt0=(0,Xt0.default)("v3",48,$t0.default),Qt0=Yt0;o50.default=Qt0});var Z90=L((t50)=>{Object.defineProperty(t50,"__esModule",{value:!0});t50.default=void 0;var Wt0=s50(AO()),Kt0=s50(t3());function s50(Z){return Z&&Z.__esModule?Z:{default:Z}}function zt0(Z,J,X){Z=Z||{};let $=Z.random||(Z.rng||Wt0.default)();if($[6]=$[6]&15|64,$[8]=$[8]&63|128,J){X=X||0;for(let Y=0;Y<16;++Y)J[X+Y]=$[Y];return J}return(0,Kt0.default)($)}var Gt0=zt0;t50.default=Gt0});var $90=L((J90)=>{Object.defineProperty(J90,"__esModule",{value:!0});J90.default=void 0;var Ht0=Vt0(N("crypto"));function Vt0(Z){return Z&&Z.__esModule?Z:{default:Z}}function Ft0(Z){if(Array.isArray(Z))Z=Buffer.from(Z);else if(typeof Z==="string")Z=Buffer.from(Z,"utf8");return Ht0.default.createHash("sha1").update(Z).digest()}var Bt0=Ft0;J90.default=Bt0});var K90=L((Q90)=>{Object.defineProperty(Q90,"__esModule",{value:!0});Q90.default=void 0;var Ut0=Y90(RO()),Lt0=Y90($90());function Y90(Z){return Z&&Z.__esModule?Z:{default:Z}}var Dt0=(0,Ut0.default)("v5",80,Lt0.default),_t0=Dt0;Q90.default=_t0});var H90=L((z90)=>{Object.defineProperty(z90,"__esModule",{value:!0});z90.default=void 0;var Ot0="00000000-0000-0000-0000-000000000000";z90.default=Ot0});var B90=L((V90)=>{Object.defineProperty(V90,"__esModule",{value:!0});V90.default=void 0;var wt0=jt0(s3());function jt0(Z){return Z&&Z.__esModule?Z:{default:Z}}function Mt0(Z){if(!(0,wt0.default)(Z))throw TypeError("Invalid UUID");return parseInt(Z.substr(14,1),16)}var At0=Mt0;V90.default=At0});var U90=L((g8)=>{Object.defineProperty(g8,"__esModule",{value:!0});Object.defineProperty(g8,"v1",{enumerable:!0,get:function(){return Tt0.default}});Object.defineProperty(g8,"v3",{enumerable:!0,get:function(){return qt0.default}});Object.defineProperty(g8,"v4",{enumerable:!0,get:function(){return Ct0.default}});Object.defineProperty(g8,"v5",{enumerable:!0,get:function(){return Nt0.default}});Object.defineProperty(g8,"NIL",{enumerable:!0,get:function(){return Rt0.default}});Object.defineProperty(g8,"version",{enumerable:!0,get:function(){return Pt0.default}});Object.defineProperty(g8,"validate",{enumerable:!0,get:function(){return Et0.default}});Object.defineProperty(g8,"stringify",{enumerable:!0,get:function(){return It0.default}});Object.defineProperty(g8,"parse",{enumerable:!0,get:function(){return yt0.default}});var Tt0=_9(h50()),qt0=_9(r50()),Ct0=_9(Z90()),Nt0=_9(K90()),Rt0=_9(H90()),Pt0=_9(B90()),Et0=_9(s3()),It0=_9(t3()),yt0=_9(NO());function _9(Z){return Z&&Z.__esModule?Z:{default:Z}}});var _90=L((QE1,D90)=>{var St0=U90(),L90=N("crypto");D90.exports=typeof L90.randomUUID==="function"?L90.randomUUID:St0.v4});var j90=L((WE1,w90)=>{var PO=[],O90={};for(I7=0;I7<256;I7++)PO[I7]=(I7+256).toString(16).substr(1),O90[PO[I7]]=I7;var I7;function kt0(Z,J,X){var $=J&&X||0,Y=0;J=J||[],Z.toLowerCase().replace(/[0-9a-f]{2}/g,function(Q){if(Y<16)J[$+Y++]=O90[Q]});while(Y<16)J[$+Y++]=0;return J}function xt0(Z,J){var X=J||0,$=PO;return $[Z[X++]]+$[Z[X++]]+$[Z[X++]]+$[Z[X++]]+"-"+$[Z[X++]]+$[Z[X++]]+"-"+$[Z[X++]]+$[Z[X++]]+"-"+$[Z[X++]]+$[Z[X++]]+"-"+$[Z[X++]]+$[Z[X++]]+$[Z[X++]]+$[Z[X++]]+$[Z[X++]]+$[Z[X++]]}w90.exports={parse:kt0,unparse:xt0}});var A90=L((ut0)=>{ut0.byteLength=ht0;ut0.toByteArray=bt0;ut0.fromByteArray=dt0;var w5=[],Q8=[],vt0=typeof Uint8Array<"u"?Uint8Array:Array,EO="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(y7=0,IO=EO.length;y7<IO;++y7)w5[y7]=EO[y7],Q8[EO.charCodeAt(y7)]=y7;var y7,IO;Q8[45]=62;Q8[95]=63;function M90(Z){var J=Z.length;if(J%4>0)throw Error("Invalid string. Length must be a multiple of 4");var X=Z.indexOf("=");if(X===-1)X=J;var $=X===J?0:4-X%4;return[X,$]}function ht0(Z){var J=M90(Z),X=J[0],$=J[1];return(X+$)*3/4-$}function ft0(Z,J,X){return(J+X)*3/4-X}function bt0(Z){var J,X=M90(Z),$=X[0],Y=X[1],Q=new vt0(ft0(Z,$,Y)),W=0,K=Y>0?$-4:$,z;for(z=0;z<K;z+=4)J=Q8[Z.charCodeAt(z)]<<18|Q8[Z.charCodeAt(z+1)]<<12|Q8[Z.charCodeAt(z+2)]<<6|Q8[Z.charCodeAt(z+3)],Q[W++]=J>>16&255,Q[W++]=J>>8&255,Q[W++]=J&255;if(Y===2)J=Q8[Z.charCodeAt(z)]<<2|Q8[Z.charCodeAt(z+1)]>>4,Q[W++]=J&255;if(Y===1)J=Q8[Z.charCodeAt(z)]<<10|Q8[Z.charCodeAt(z+1)]<<4|Q8[Z.charCodeAt(z+2)]>>2,Q[W++]=J>>8&255,Q[W++]=J&255;return Q}function gt0(Z){return w5[Z>>18&63]+w5[Z>>12&63]+w5[Z>>6&63]+w5[Z&63]}function mt0(Z,J,X){var $,Y=[];for(var Q=J;Q<X;Q+=3)$=(Z[Q]<<16&16711680)+(Z[Q+1]<<8&65280)+(Z[Q+2]&255),Y.push(gt0($));return Y.join("")}function dt0(Z){var J,X=Z.length,$=X%3,Y=[],Q=16383;for(var W=0,K=X-$;W<K;W+=Q)Y.push(mt0(Z,W,W+Q>K?K:W+Q));if($===1)J=Z[X-1],Y.push(w5[J>>2]+w5[J<<4&63]+"==");else if($===2)J=(Z[X-2]<<8)+Z[X-1],Y.push(w5[J>>10]+w5[J>>4&63]+w5[J<<2&63]+"=");return Y.join("")}});var T90=L((it0)=>{/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */it0.read=function(Z,J,X,$,Y){var Q,W,K=Y*8-$-1,z=(1<<K)-1,G=z>>1,H=-7,V=X?Y-1:0,F=X?-1:1,B=Z[J+V];V+=F,Q=B&(1<<-H)-1,B>>=-H,H+=K;for(;H>0;Q=Q*256+Z[J+V],V+=F,H-=8);W=Q&(1<<-H)-1,Q>>=-H,H+=$;for(;H>0;W=W*256+Z[J+V],V+=F,H-=8);if(Q===0)Q=1-G;else if(Q===z)return W?NaN:(B?-1:1)*(1/0);else W=W+Math.pow(2,$),Q=Q-G;return(B?-1:1)*W*Math.pow(2,Q-$)};it0.write=function(Z,J,X,$,Y,Q){var W,K,z,G=Q*8-Y-1,H=(1<<G)-1,V=H>>1,F=Y===23?Math.pow(2,-24)-Math.pow(2,-77):0,B=$?0:Q-1,U=$?1:-1,D=J<0||J===0&&1/J<0?1:0;if(J=Math.abs(J),isNaN(J)||J===1/0)K=isNaN(J)?1:0,W=H;else{if(W=Math.floor(Math.log(J)/Math.LN2),J*(z=Math.pow(2,-W))<1)W--,z*=2;if(W+V>=1)J+=F/z;else J+=F*Math.pow(2,1-V);if(J*z>=2)W++,z/=2;if(W+V>=H)K=0,W=H;else if(W+V>=1)K=(J*z-1)*Math.pow(2,Y),W=W+V;else K=J*Math.pow(2,V-1)*Math.pow(2,Y),W=0}for(;Y>=8;Z[X+B]=K&255,B+=U,K/=256,Y-=8);W=W<<Y|K,G+=Y;for(;G>0;Z[X+B]=W&255,B+=U,W/=256,G-=8);Z[X+B-U]|=D*128}});var f90=L((Oe0)=>{/*!
11
+ `;super(J);this.name="AggregateError",this.errors=Z}}M10.exports={AggregateError:j10,ArrayIsArray(Z){return Array.isArray(Z)},ArrayPrototypeIncludes(Z,J){return Z.includes(J)},ArrayPrototypeIndexOf(Z,J){return Z.indexOf(J)},ArrayPrototypeJoin(Z,J){return Z.join(J)},ArrayPrototypeMap(Z,J){return Z.map(J)},ArrayPrototypePop(Z,J){return Z.pop(J)},ArrayPrototypePush(Z,J){return Z.push(J)},ArrayPrototypeSlice(Z,J,X){return Z.slice(J,X)},Error,FunctionPrototypeCall(Z,J,...X){return Z.call(J,...X)},FunctionPrototypeSymbolHasInstance(Z,J){return Function.prototype[Symbol.hasInstance].call(Z,J)},MathFloor:Math.floor,Number,NumberIsInteger:Number.isInteger,NumberIsNaN:Number.isNaN,NumberMAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,NumberParseInt:Number.parseInt,ObjectDefineProperties(Z,J){return Object.defineProperties(Z,J)},ObjectDefineProperty(Z,J,X){return Object.defineProperty(Z,J,X)},ObjectGetOwnPropertyDescriptor(Z,J){return Object.getOwnPropertyDescriptor(Z,J)},ObjectKeys(Z){return Object.keys(Z)},ObjectSetPrototypeOf(Z,J){return Object.setPrototypeOf(Z,J)},Promise,PromisePrototypeCatch(Z,J){return Z.catch(J)},PromisePrototypeThen(Z,J,X){return Z.then(J,X)},PromiseReject(Z){return Promise.reject(Z)},PromiseResolve(Z){return Promise.resolve(Z)},ReflectApply:Reflect.apply,RegExpPrototypeTest(Z,J){return Z.test(J)},SafeSet:Set,String,StringPrototypeSlice(Z,J,X){return Z.slice(J,X)},StringPrototypeToLowerCase(Z){return Z.toLowerCase()},StringPrototypeToUpperCase(Z){return Z.toUpperCase()},StringPrototypeTrim(Z){return Z.trim()},Symbol,SymbolFor:Symbol.for,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,SymbolDispose:Symbol.dispose||Symbol("Symbol.dispose"),SymbolAsyncDispose:Symbol.asyncDispose||Symbol("Symbol.asyncDispose"),TypedArrayPrototypeSet(Z,J,X){return Z.set(J,X)},Boolean,Uint8Array}});var eD=L((xR1,A10)=>{A10.exports={format(Z,...J){return Z.replace(/%([sdifj])/g,function(...[X,$]){let Y=J.shift();if($==="f")return Y.toFixed(6);else if($==="j")return JSON.stringify(Y);else if($==="s"&&typeof Y==="object")return`${Y.constructor!==Object?Y.constructor.name:""} {}`.trim();else return Y.toString()})},inspect(Z){switch(typeof Z){case"string":if(Z.includes("'")){if(!Z.includes('"'))return`"${Z}"`;else if(!Z.includes("`")&&!Z.includes("${"))return`\`${Z}\``}return`'${Z}'`;case"number":if(isNaN(Z))return"NaN";else if(Object.is(Z,-0))return String(Z);return Z;case"bigint":return`${String(Z)}n`;case"boolean":case"undefined":return String(Z);case"object":return"{}"}}}});var T4=L((vR1,N10)=>{var{format:Sl0,inspect:$G}=eD(),{AggregateError:kl0}=F1(),xl0=globalThis.AggregateError||kl0,vl0=Symbol("kIsNodeError"),hl0=["string","function","number","object","Function","Object","boolean","bigint","symbol"],fl0=/^([A-Z][a-z0-9]*)+$/,YG={};function gZ(Z,J){if(!Z)throw new YG.ERR_INTERNAL_ASSERTION(J)}function T10(Z){let J="",X=Z.length,$=Z[0]==="-"?1:0;for(;X>=$+4;X-=3)J=`_${Z.slice(X-3,X)}${J}`;return`${Z.slice(0,X)}${J}`}function bl0(Z,J,X){if(typeof J==="function")return gZ(J.length<=X.length,`Code: ${Z}; The provided arguments length (${X.length}) does not match the required ones (${J.length}).`),J(...X);let $=(J.match(/%[dfijoOs]/g)||[]).length;if(gZ($===X.length,`Code: ${Z}; The provided arguments length (${X.length}) does not match the required ones (${$}).`),X.length===0)return J;return Sl0(J,...X)}function U4(Z,J,X){if(!X)X=Error;class $ extends X{constructor(...Y){super(bl0(Z,J,Y))}toString(){return`${this.name} [${Z}]: ${this.message}`}}Object.defineProperties($.prototype,{name:{value:X.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${Z}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),$.prototype.code=Z,$.prototype[vl0]=!0,YG[Z]=$}function q10(Z){let J="__node_internal_"+Z.name;return Object.defineProperty(Z,"name",{value:J}),Z}function gl0(Z,J){if(Z&&J&&Z!==J){if(Array.isArray(J.errors))return J.errors.push(Z),J;let X=new xl0([J,Z],J.message);return X.code=J.code,X}return Z||J}class C10 extends Error{constructor(Z="The operation was aborted",J=void 0){if(J!==void 0&&typeof J!=="object")throw new YG.ERR_INVALID_ARG_TYPE("options","Object",J);super(Z,J);this.code="ABORT_ERR",this.name="AbortError"}}U4("ERR_ASSERTION","%s",Error);U4("ERR_INVALID_ARG_TYPE",(Z,J,X)=>{if(gZ(typeof Z==="string","'name' must be a string"),!Array.isArray(J))J=[J];let $="The ";if(Z.endsWith(" argument"))$+=`${Z} `;else $+=`"${Z}" ${Z.includes(".")?"property":"argument"} `;$+="must be ";let Y=[],Q=[],W=[];for(let z of J)if(gZ(typeof z==="string","All expected entries have to be of type string"),hl0.includes(z))Y.push(z.toLowerCase());else if(fl0.test(z))Q.push(z);else gZ(z!=="object",'The value "object" should be written as "Object"'),W.push(z);if(Q.length>0){let z=Y.indexOf("object");if(z!==-1)Y.splice(Y,z,1),Q.push("Object")}if(Y.length>0){switch(Y.length){case 1:$+=`of type ${Y[0]}`;break;case 2:$+=`one of type ${Y[0]} or ${Y[1]}`;break;default:{let z=Y.pop();$+=`one of type ${Y.join(", ")}, or ${z}`}}if(Q.length>0||W.length>0)$+=" or "}if(Q.length>0){switch(Q.length){case 1:$+=`an instance of ${Q[0]}`;break;case 2:$+=`an instance of ${Q[0]} or ${Q[1]}`;break;default:{let z=Q.pop();$+=`an instance of ${Q.join(", ")}, or ${z}`}}if(W.length>0)$+=" or "}switch(W.length){case 0:break;case 1:if(W[0].toLowerCase()!==W[0])$+="an ";$+=`${W[0]}`;break;case 2:$+=`one of ${W[0]} or ${W[1]}`;break;default:{let z=W.pop();$+=`one of ${W.join(", ")}, or ${z}`}}if(X==null)$+=`. Received ${X}`;else if(typeof X==="function"&&X.name)$+=`. Received function ${X.name}`;else if(typeof X==="object"){var K;if((K=X.constructor)!==null&&K!==void 0&&K.name)$+=`. Received an instance of ${X.constructor.name}`;else{let z=$G(X,{depth:-1});$+=`. Received ${z}`}}else{let z=$G(X,{colors:!1});if(z.length>25)z=`${z.slice(0,25)}...`;$+=`. Received type ${typeof X} (${z})`}return $},TypeError);U4("ERR_INVALID_ARG_VALUE",(Z,J,X="is invalid")=>{let $=$G(J);if($.length>128)$=$.slice(0,128)+"...";return`The ${Z.includes(".")?"property":"argument"} '${Z}' ${X}. Received ${$}`},TypeError);U4("ERR_INVALID_RETURN_VALUE",(Z,J,X)=>{var $;let Y=X!==null&&X!==void 0&&($=X.constructor)!==null&&$!==void 0&&$.name?`instance of ${X.constructor.name}`:`type ${typeof X}`;return`Expected ${Z} to be returned from the "${J}" function but got ${Y}.`},TypeError);U4("ERR_MISSING_ARGS",(...Z)=>{gZ(Z.length>0,"At least one arg needs to be specified");let J,X=Z.length;switch(Z=(Array.isArray(Z)?Z:[Z]).map(($)=>`"${$}"`).join(" or "),X){case 1:J+=`The ${Z[0]} argument`;break;case 2:J+=`The ${Z[0]} and ${Z[1]} arguments`;break;default:{let $=Z.pop();J+=`The ${Z.join(", ")}, and ${$} arguments`}break}return`${J} must be specified`},TypeError);U4("ERR_OUT_OF_RANGE",(Z,J,X)=>{gZ(J,'Missing "range" argument');let $;if(Number.isInteger(X)&&Math.abs(X)>4294967296)$=T10(String(X));else if(typeof X==="bigint"){$=String(X);let Y=BigInt(2)**BigInt(32);if(X>Y||X<-Y)$=T10($);$+="n"}else $=$G(X);return`The value of "${Z}" is out of range. It must be ${J}. Received ${$}`},RangeError);U4("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error);U4("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error);U4("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error);U4("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error);U4("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error);U4("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError);U4("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error);U4("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error);U4("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error);U4("ERR_STREAM_WRITE_AFTER_END","write after end",Error);U4("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError);N10.exports={AbortError:C10,aggregateTwoErrors:q10(gl0),hideStackFrames:q10,codes:YG}});var b4=L((hR1,J_)=>{var ml0=N("buffer"),{format:dl0,inspect:ul0}=eD(),{codes:{ERR_INVALID_ARG_TYPE:Z_}}=T4(),{kResistStopPropagation:cl0,AggregateError:ll0,SymbolDispose:pl0}=F1(),il0=globalThis.AbortSignal||N("abort-controller").AbortSignal,nl0=globalThis.AbortController||N("abort-controller").AbortController,ol0=Object.getPrototypeOf(async function(){}).constructor,R10=globalThis.Blob||ml0.Blob,al0=typeof R10<"u"?function(J){return J instanceof R10}:function(J){return!1},P10=(Z,J)=>{if(Z!==void 0&&(Z===null||typeof Z!=="object"||!("aborted"in Z)))throw new Z_(J,"AbortSignal",Z)},rl0=(Z,J)=>{if(typeof Z!=="function")throw new Z_(J,"Function",Z)};J_.exports={AggregateError:ll0,kEmptyObject:Object.freeze({}),once(Z){let J=!1;return function(...X){if(J)return;J=!0,Z.apply(this,X)}},createDeferredPromise:function(){let Z,J;return{promise:new Promise(($,Y)=>{Z=$,J=Y}),resolve:Z,reject:J}},promisify(Z){return new Promise((J,X)=>{Z(($,...Y)=>{if($)return X($);return J(...Y)})})},debuglog(){return function(){}},format:dl0,inspect:ul0,types:{isAsyncFunction(Z){return Z instanceof ol0},isArrayBufferView(Z){return ArrayBuffer.isView(Z)}},isBlob:al0,deprecate(Z,J){return Z},addAbortListener:N("events").addAbortListener||function(J,X){if(J===void 0)throw new Z_("signal","AbortSignal",J);P10(J,"signal"),rl0(X,"listener");let $;if(J.aborted)queueMicrotask(()=>X());else J.addEventListener("abort",X,{__proto__:null,once:!0,[cl0]:!0}),$=()=>{J.removeEventListener("abort",X)};return{__proto__:null,[pl0](){var Y;(Y=$)===null||Y===void 0||Y()}}},AbortSignalAny:il0.any||function(J){if(J.length===1)return J[0];let X=new nl0,$=()=>X.abort();return J.forEach((Y)=>{P10(Y,"signals"),Y.addEventListener("abort",$,{once:!0})}),X.signal.addEventListener("abort",()=>{J.forEach((Y)=>Y.removeEventListener("abort",$))},{once:!0}),X.signal}};J_.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")});var nX=L((fR1,b10)=>{var{ArrayIsArray:$_,ArrayPrototypeIncludes:S10,ArrayPrototypeJoin:k10,ArrayPrototypeMap:sl0,NumberIsInteger:Y_,NumberIsNaN:tl0,NumberMAX_SAFE_INTEGER:el0,NumberMIN_SAFE_INTEGER:Zp0,NumberParseInt:Jp0,ObjectPrototypeHasOwnProperty:Xp0,RegExpPrototypeExec:x10,String:$p0,StringPrototypeToUpperCase:Yp0,StringPrototypeTrim:Qp0}=F1(),{hideStackFrames:J8,codes:{ERR_SOCKET_BAD_PORT:Wp0,ERR_INVALID_ARG_TYPE:q4,ERR_INVALID_ARG_VALUE:iX,ERR_OUT_OF_RANGE:mZ,ERR_UNKNOWN_SIGNAL:E10}}=T4(),{normalizeEncoding:Kp0}=b4(),{isAsyncFunction:zp0,isArrayBufferView:Gp0}=b4().types,I10={};function Hp0(Z){return Z===(Z|0)}function Vp0(Z){return Z===Z>>>0}var Fp0=/^[0-7]+$/,Bp0="must be a 32-bit unsigned integer or an octal string";function Up0(Z,J,X){if(typeof Z>"u")Z=X;if(typeof Z==="string"){if(x10(Fp0,Z)===null)throw new iX(J,Z,Bp0);Z=Jp0(Z,8)}return v10(Z,J),Z}var Lp0=J8((Z,J,X=Zp0,$=el0)=>{if(typeof Z!=="number")throw new q4(J,"number",Z);if(!Y_(Z))throw new mZ(J,"an integer",Z);if(Z<X||Z>$)throw new mZ(J,`>= ${X} && <= ${$}`,Z)}),Dp0=J8((Z,J,X=-2147483648,$=2147483647)=>{if(typeof Z!=="number")throw new q4(J,"number",Z);if(!Y_(Z))throw new mZ(J,"an integer",Z);if(Z<X||Z>$)throw new mZ(J,`>= ${X} && <= ${$}`,Z)}),v10=J8((Z,J,X=!1)=>{if(typeof Z!=="number")throw new q4(J,"number",Z);if(!Y_(Z))throw new mZ(J,"an integer",Z);let $=X?1:0,Y=4294967295;if(Z<$||Z>Y)throw new mZ(J,`>= ${$} && <= ${Y}`,Z)});function Q_(Z,J){if(typeof Z!=="string")throw new q4(J,"string",Z)}function _p0(Z,J,X=void 0,$){if(typeof Z!=="number")throw new q4(J,"number",Z);if(X!=null&&Z<X||$!=null&&Z>$||(X!=null||$!=null)&&tl0(Z))throw new mZ(J,`${X!=null?`>= ${X}`:""}${X!=null&&$!=null?" && ":""}${$!=null?`<= ${$}`:""}`,Z)}var Op0=J8((Z,J,X)=>{if(!S10(X,Z)){let Y="must be one of: "+k10(sl0(X,(Q)=>typeof Q==="string"?`'${Q}'`:$p0(Q)),", ");throw new iX(J,Z,Y)}});function h10(Z,J){if(typeof Z!=="boolean")throw new q4(J,"boolean",Z)}function X_(Z,J,X){return Z==null||!Xp0(Z,J)?X:Z[J]}var wp0=J8((Z,J,X=null)=>{let $=X_(X,"allowArray",!1),Y=X_(X,"allowFunction",!1);if(!X_(X,"nullable",!1)&&Z===null||!$&&$_(Z)||typeof Z!=="object"&&(!Y||typeof Z!=="function"))throw new q4(J,"Object",Z)}),jp0=J8((Z,J)=>{if(Z!=null&&typeof Z!=="object"&&typeof Z!=="function")throw new q4(J,"a dictionary",Z)}),QG=J8((Z,J,X=0)=>{if(!$_(Z))throw new q4(J,"Array",Z);if(Z.length<X){let $=`must be longer than ${X}`;throw new iX(J,Z,$)}});function Mp0(Z,J){QG(Z,J);for(let X=0;X<Z.length;X++)Q_(Z[X],`${J}[${X}]`)}function Ap0(Z,J){QG(Z,J);for(let X=0;X<Z.length;X++)h10(Z[X],`${J}[${X}]`)}function Tp0(Z,J){QG(Z,J);for(let X=0;X<Z.length;X++){let $=Z[X],Y=`${J}[${X}]`;if($==null)throw new q4(Y,"AbortSignal",$);f10($,Y)}}function qp0(Z,J="signal"){if(Q_(Z,J),I10[Z]===void 0){if(I10[Yp0(Z)]!==void 0)throw new E10(Z+" (signals must use all capital letters)");throw new E10(Z)}}var Cp0=J8((Z,J="buffer")=>{if(!Gp0(Z))throw new q4(J,["Buffer","TypedArray","DataView"],Z)});function Np0(Z,J){let X=Kp0(J),$=Z.length;if(X==="hex"&&$%2!==0)throw new iX("encoding",J,`is invalid for data of length ${$}`)}function Rp0(Z,J="Port",X=!0){if(typeof Z!=="number"&&typeof Z!=="string"||typeof Z==="string"&&Qp0(Z).length===0||+Z!==+Z>>>0||Z>65535||Z===0&&!X)throw new Wp0(J,Z,X);return Z|0}var f10=J8((Z,J)=>{if(Z!==void 0&&(Z===null||typeof Z!=="object"||!("aborted"in Z)))throw new q4(J,"AbortSignal",Z)}),Pp0=J8((Z,J)=>{if(typeof Z!=="function")throw new q4(J,"Function",Z)}),Ep0=J8((Z,J)=>{if(typeof Z!=="function"||zp0(Z))throw new q4(J,"Function",Z)}),Ip0=J8((Z,J)=>{if(Z!==void 0)throw new q4(J,"undefined",Z)});function yp0(Z,J,X){if(!S10(X,Z))throw new q4(J,`('${k10(X,"|")}')`,Z)}var Sp0=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function y10(Z,J){if(typeof Z>"u"||!x10(Sp0,Z))throw new iX(J,Z,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}function kp0(Z){if(typeof Z==="string")return y10(Z,"hints"),Z;else if($_(Z)){let J=Z.length,X="";if(J===0)return X;for(let $=0;$<J;$++){let Y=Z[$];if(y10(Y,"hints"),X+=Y,$!==J-1)X+=", "}return X}throw new iX("hints",Z,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}b10.exports={isInt32:Hp0,isUint32:Vp0,parseFileMode:Up0,validateArray:QG,validateStringArray:Mp0,validateBooleanArray:Ap0,validateAbortSignalArray:Tp0,validateBoolean:h10,validateBuffer:Cp0,validateDictionary:jp0,validateEncoding:Np0,validateFunction:Pp0,validateInt32:Dp0,validateInteger:Lp0,validateNumber:_p0,validateObject:wp0,validateOneOf:Op0,validatePlainFunction:Ep0,validatePort:Rp0,validateSignalName:qp0,validateString:Q_,validateUint32:v10,validateUndefined:Ip0,validateUnion:yp0,validateAbortSignal:f10,validateLinkHeaderValue:kp0}});var q7=L((bR1,g10)=>{g10.exports=global.process});var U5=L((gR1,Z40)=>{var{SymbolAsyncIterator:m10,SymbolIterator:d10,SymbolFor:dZ}=F1(),u10=dZ("nodejs.stream.destroyed"),c10=dZ("nodejs.stream.errored"),W_=dZ("nodejs.stream.readable"),K_=dZ("nodejs.stream.writable"),l10=dZ("nodejs.stream.disturbed"),xp0=dZ("nodejs.webstream.isClosedPromise"),vp0=dZ("nodejs.webstream.controllerErrorFunction");function WG(Z,J=!1){var X;return!!(Z&&typeof Z.pipe==="function"&&typeof Z.on==="function"&&(!J||typeof Z.pause==="function"&&typeof Z.resume==="function")&&(!Z._writableState||((X=Z._readableState)===null||X===void 0?void 0:X.readable)!==!1)&&(!Z._writableState||Z._readableState))}function KG(Z){var J;return!!(Z&&typeof Z.write==="function"&&typeof Z.on==="function"&&(!Z._readableState||((J=Z._writableState)===null||J===void 0?void 0:J.writable)!==!1))}function hp0(Z){return!!(Z&&typeof Z.pipe==="function"&&Z._readableState&&typeof Z.on==="function"&&typeof Z.write==="function")}function B5(Z){return Z&&(Z._readableState||Z._writableState||typeof Z.write==="function"&&typeof Z.on==="function"||typeof Z.pipe==="function"&&typeof Z.on==="function")}function p10(Z){return!!(Z&&!B5(Z)&&typeof Z.pipeThrough==="function"&&typeof Z.getReader==="function"&&typeof Z.cancel==="function")}function i10(Z){return!!(Z&&!B5(Z)&&typeof Z.getWriter==="function"&&typeof Z.abort==="function")}function n10(Z){return!!(Z&&!B5(Z)&&typeof Z.readable==="object"&&typeof Z.writable==="object")}function fp0(Z){return p10(Z)||i10(Z)||n10(Z)}function bp0(Z,J){if(Z==null)return!1;if(J===!0)return typeof Z[m10]==="function";if(J===!1)return typeof Z[d10]==="function";return typeof Z[m10]==="function"||typeof Z[d10]==="function"}function zG(Z){if(!B5(Z))return null;let{_writableState:J,_readableState:X}=Z,$=J||X;return!!(Z.destroyed||Z[u10]||$!==null&&$!==void 0&&$.destroyed)}function o10(Z){if(!KG(Z))return null;if(Z.writableEnded===!0)return!0;let J=Z._writableState;if(J!==null&&J!==void 0&&J.errored)return!1;if(typeof(J===null||J===void 0?void 0:J.ended)!=="boolean")return null;return J.ended}function gp0(Z,J){if(!KG(Z))return null;if(Z.writableFinished===!0)return!0;let X=Z._writableState;if(X!==null&&X!==void 0&&X.errored)return!1;if(typeof(X===null||X===void 0?void 0:X.finished)!=="boolean")return null;return!!(X.finished||J===!1&&X.ended===!0&&X.length===0)}function mp0(Z){if(!WG(Z))return null;if(Z.readableEnded===!0)return!0;let J=Z._readableState;if(!J||J.errored)return!1;if(typeof(J===null||J===void 0?void 0:J.ended)!=="boolean")return null;return J.ended}function a10(Z,J){if(!WG(Z))return null;let X=Z._readableState;if(X!==null&&X!==void 0&&X.errored)return!1;if(typeof(X===null||X===void 0?void 0:X.endEmitted)!=="boolean")return null;return!!(X.endEmitted||J===!1&&X.ended===!0&&X.length===0)}function r10(Z){if(Z&&Z[W_]!=null)return Z[W_];if(typeof(Z===null||Z===void 0?void 0:Z.readable)!=="boolean")return null;if(zG(Z))return!1;return WG(Z)&&Z.readable&&!a10(Z)}function s10(Z){if(Z&&Z[K_]!=null)return Z[K_];if(typeof(Z===null||Z===void 0?void 0:Z.writable)!=="boolean")return null;if(zG(Z))return!1;return KG(Z)&&Z.writable&&!o10(Z)}function dp0(Z,J){if(!B5(Z))return null;if(zG(Z))return!0;if((J===null||J===void 0?void 0:J.readable)!==!1&&r10(Z))return!1;if((J===null||J===void 0?void 0:J.writable)!==!1&&s10(Z))return!1;return!0}function up0(Z){var J,X;if(!B5(Z))return null;if(Z.writableErrored)return Z.writableErrored;return(J=(X=Z._writableState)===null||X===void 0?void 0:X.errored)!==null&&J!==void 0?J:null}function cp0(Z){var J,X;if(!B5(Z))return null;if(Z.readableErrored)return Z.readableErrored;return(J=(X=Z._readableState)===null||X===void 0?void 0:X.errored)!==null&&J!==void 0?J:null}function lp0(Z){if(!B5(Z))return null;if(typeof Z.closed==="boolean")return Z.closed;let{_writableState:J,_readableState:X}=Z;if(typeof(J===null||J===void 0?void 0:J.closed)==="boolean"||typeof(X===null||X===void 0?void 0:X.closed)==="boolean")return(J===null||J===void 0?void 0:J.closed)||(X===null||X===void 0?void 0:X.closed);if(typeof Z._closed==="boolean"&&t10(Z))return Z._closed;return null}function t10(Z){return typeof Z._closed==="boolean"&&typeof Z._defaultKeepAlive==="boolean"&&typeof Z._removedConnection==="boolean"&&typeof Z._removedContLen==="boolean"}function e10(Z){return typeof Z._sent100==="boolean"&&t10(Z)}function pp0(Z){var J;return typeof Z._consuming==="boolean"&&typeof Z._dumped==="boolean"&&((J=Z.req)===null||J===void 0?void 0:J.upgradeOrConnect)===void 0}function ip0(Z){if(!B5(Z))return null;let{_writableState:J,_readableState:X}=Z,$=J||X;return!$&&e10(Z)||!!($&&$.autoDestroy&&$.emitClose&&$.closed===!1)}function np0(Z){var J;return!!(Z&&((J=Z[l10])!==null&&J!==void 0?J:Z.readableDidRead||Z.readableAborted))}function op0(Z){var J,X,$,Y,Q,W,K,z,G,H;return!!(Z&&((J=(X=($=(Y=(Q=(W=Z[c10])!==null&&W!==void 0?W:Z.readableErrored)!==null&&Q!==void 0?Q:Z.writableErrored)!==null&&Y!==void 0?Y:(K=Z._readableState)===null||K===void 0?void 0:K.errorEmitted)!==null&&$!==void 0?$:(z=Z._writableState)===null||z===void 0?void 0:z.errorEmitted)!==null&&X!==void 0?X:(G=Z._readableState)===null||G===void 0?void 0:G.errored)!==null&&J!==void 0?J:(H=Z._writableState)===null||H===void 0?void 0:H.errored))}Z40.exports={isDestroyed:zG,kIsDestroyed:u10,isDisturbed:np0,kIsDisturbed:l10,isErrored:op0,kIsErrored:c10,isReadable:r10,kIsReadable:W_,kIsClosedPromise:xp0,kControllerErrorFunction:vp0,kIsWritable:K_,isClosed:lp0,isDuplexNodeStream:hp0,isFinished:dp0,isIterable:bp0,isReadableNodeStream:WG,isReadableStream:p10,isReadableEnded:mp0,isReadableFinished:a10,isReadableErrored:cp0,isNodeStream:B5,isWebStream:fp0,isWritable:s10,isWritableNodeStream:KG,isWritableStream:i10,isWritableEnded:o10,isWritableFinished:gp0,isWritableErrored:up0,isServerRequest:pp0,isServerResponse:e10,willEmitClose:ip0,isTransformStream:n10}});var F9=L((mR1,F_)=>{var C7=q7(),{AbortError:G40,codes:ap0}=T4(),{ERR_INVALID_ARG_TYPE:rp0,ERR_STREAM_PREMATURE_CLOSE:J40}=ap0,{kEmptyObject:G_,once:H_}=b4(),{validateAbortSignal:sp0,validateFunction:tp0,validateObject:ep0,validateBoolean:Zi0}=nX(),{Promise:Ji0,PromisePrototypeThen:Xi0,SymbolDispose:H40}=F1(),{isClosed:$i0,isReadable:X40,isReadableNodeStream:z_,isReadableStream:Yi0,isReadableFinished:$40,isReadableErrored:Y40,isWritable:Q40,isWritableNodeStream:W40,isWritableStream:Qi0,isWritableFinished:K40,isWritableErrored:z40,isNodeStream:Wi0,willEmitClose:Ki0,kIsClosedPromise:zi0}=U5(),oX;function Gi0(Z){return Z.setHeader&&typeof Z.abort==="function"}var V_=()=>{};function V40(Z,J,X){var $,Y;if(arguments.length===2)X=J,J=G_;else if(J==null)J=G_;else ep0(J,"options");if(tp0(X,"callback"),sp0(J.signal,"options.signal"),X=H_(X),Yi0(Z)||Qi0(Z))return Hi0(Z,J,X);if(!Wi0(Z))throw new rp0("stream",["ReadableStream","WritableStream","Stream"],Z);let Q=($=J.readable)!==null&&$!==void 0?$:z_(Z),W=(Y=J.writable)!==null&&Y!==void 0?Y:W40(Z),K=Z._writableState,z=Z._readableState,G=()=>{if(!Z.writable)F()},H=Ki0(Z)&&z_(Z)===Q&&W40(Z)===W,V=K40(Z,!1),F=()=>{if(V=!0,Z.destroyed)H=!1;if(H&&(!Z.readable||Q))return;if(!Q||B)X.call(Z)},B=$40(Z,!1),U=()=>{if(B=!0,Z.destroyed)H=!1;if(H&&(!Z.writable||W))return;if(!W||V)X.call(Z)},D=(R)=>{X.call(Z,R)},_=$i0(Z),O=()=>{_=!0;let R=z40(Z)||Y40(Z);if(R&&typeof R!=="boolean")return X.call(Z,R);if(Q&&!B&&z_(Z,!0)){if(!$40(Z,!1))return X.call(Z,new J40)}if(W&&!V){if(!K40(Z,!1))return X.call(Z,new J40)}X.call(Z)},w=()=>{_=!0;let R=z40(Z)||Y40(Z);if(R&&typeof R!=="boolean")return X.call(Z,R);X.call(Z)},j=()=>{Z.req.on("finish",F)};if(Gi0(Z)){if(Z.on("complete",F),!H)Z.on("abort",O);if(Z.req)j();else Z.on("request",j)}else if(W&&!K)Z.on("end",G),Z.on("close",G);if(!H&&typeof Z.aborted==="boolean")Z.on("aborted",O);if(Z.on("end",U),Z.on("finish",F),J.error!==!1)Z.on("error",D);if(Z.on("close",O),_)C7.nextTick(O);else if(K!==null&&K!==void 0&&K.errorEmitted||z!==null&&z!==void 0&&z.errorEmitted){if(!H)C7.nextTick(w)}else if(!Q&&(!H||X40(Z))&&(V||Q40(Z)===!1))C7.nextTick(w);else if(!W&&(!H||Q40(Z))&&(B||X40(Z)===!1))C7.nextTick(w);else if(z&&Z.req&&Z.aborted)C7.nextTick(w);let q=()=>{if(X=V_,Z.removeListener("aborted",O),Z.removeListener("complete",F),Z.removeListener("abort",O),Z.removeListener("request",j),Z.req)Z.req.removeListener("finish",F);Z.removeListener("end",G),Z.removeListener("close",G),Z.removeListener("finish",F),Z.removeListener("end",U),Z.removeListener("error",D),Z.removeListener("close",O)};if(J.signal&&!_){let R=()=>{let T=X;q(),T.call(Z,new G40(void 0,{cause:J.signal.reason}))};if(J.signal.aborted)C7.nextTick(R);else{oX=oX||b4().addAbortListener;let T=oX(J.signal,R),y=X;X=H_((...i)=>{T[H40](),y.apply(Z,i)})}}return q}function Hi0(Z,J,X){let $=!1,Y=V_;if(J.signal)if(Y=()=>{$=!0,X.call(Z,new G40(void 0,{cause:J.signal.reason}))},J.signal.aborted)C7.nextTick(Y);else{oX=oX||b4().addAbortListener;let W=oX(J.signal,Y),K=X;X=H_((...z)=>{W[H40](),K.apply(Z,z)})}let Q=(...W)=>{if(!$)C7.nextTick(()=>X.apply(Z,W))};return Xi0(Z[zi0].promise,Q,Q),V_}function Vi0(Z,J){var X;let $=!1;if(J===null)J=G_;if((X=J)!==null&&X!==void 0&&X.cleanup)Zi0(J.cleanup,"cleanup"),$=J.cleanup;return new Ji0((Y,Q)=>{let W=V40(Z,J,(K)=>{if($)W();if(K)Q(K);else Y()})})}F_.exports=V40;F_.exports.finished=Vi0});var uZ=L((dR1,w40)=>{var L5=q7(),{aggregateTwoErrors:Fi0,codes:{ERR_MULTIPLE_CALLBACK:Bi0},AbortError:Ui0}=T4(),{Symbol:U40}=F1(),{kIsDestroyed:Li0,isDestroyed:Di0,isFinished:_i0,isServerRequest:Oi0}=U5(),L40=U40("kDestroy"),B_=U40("kConstruct");function D40(Z,J,X){if(Z){if(Z.stack,J&&!J.errored)J.errored=Z;if(X&&!X.errored)X.errored=Z}}function wi0(Z,J){let X=this._readableState,$=this._writableState,Y=$||X;if($!==null&&$!==void 0&&$.destroyed||X!==null&&X!==void 0&&X.destroyed){if(typeof J==="function")J();return this}if(D40(Z,$,X),$)$.destroyed=!0;if(X)X.destroyed=!0;if(!Y.constructed)this.once(L40,function(Q){F40(this,Fi0(Q,Z),J)});else F40(this,Z,J);return this}function F40(Z,J,X){let $=!1;function Y(Q){if($)return;$=!0;let{_readableState:W,_writableState:K}=Z;if(D40(Q,K,W),K)K.closed=!0;if(W)W.closed=!0;if(typeof X==="function")X(Q);if(Q)L5.nextTick(ji0,Z,Q);else L5.nextTick(_40,Z)}try{Z._destroy(J||null,Y)}catch(Q){Y(Q)}}function ji0(Z,J){U_(Z,J),_40(Z)}function _40(Z){let{_readableState:J,_writableState:X}=Z;if(X)X.closeEmitted=!0;if(J)J.closeEmitted=!0;if(X!==null&&X!==void 0&&X.emitClose||J!==null&&J!==void 0&&J.emitClose)Z.emit("close")}function U_(Z,J){let{_readableState:X,_writableState:$}=Z;if($!==null&&$!==void 0&&$.errorEmitted||X!==null&&X!==void 0&&X.errorEmitted)return;if($)$.errorEmitted=!0;if(X)X.errorEmitted=!0;Z.emit("error",J)}function Mi0(){let Z=this._readableState,J=this._writableState;if(Z)Z.constructed=!0,Z.closed=!1,Z.closeEmitted=!1,Z.destroyed=!1,Z.errored=null,Z.errorEmitted=!1,Z.reading=!1,Z.ended=Z.readable===!1,Z.endEmitted=Z.readable===!1;if(J)J.constructed=!0,J.destroyed=!1,J.closed=!1,J.closeEmitted=!1,J.errored=null,J.errorEmitted=!1,J.finalCalled=!1,J.prefinished=!1,J.ended=J.writable===!1,J.ending=J.writable===!1,J.finished=J.writable===!1}function L_(Z,J,X){let{_readableState:$,_writableState:Y}=Z;if(Y!==null&&Y!==void 0&&Y.destroyed||$!==null&&$!==void 0&&$.destroyed)return this;if($!==null&&$!==void 0&&$.autoDestroy||Y!==null&&Y!==void 0&&Y.autoDestroy)Z.destroy(J);else if(J){if(J.stack,Y&&!Y.errored)Y.errored=J;if($&&!$.errored)$.errored=J;if(X)L5.nextTick(U_,Z,J);else U_(Z,J)}}function Ai0(Z,J){if(typeof Z._construct!=="function")return;let{_readableState:X,_writableState:$}=Z;if(X)X.constructed=!1;if($)$.constructed=!1;if(Z.once(B_,J),Z.listenerCount(B_)>1)return;L5.nextTick(Ti0,Z)}function Ti0(Z){let J=!1;function X($){if(J){L_(Z,$!==null&&$!==void 0?$:new Bi0);return}J=!0;let{_readableState:Y,_writableState:Q}=Z,W=Q||Y;if(Y)Y.constructed=!0;if(Q)Q.constructed=!0;if(W.destroyed)Z.emit(L40,$);else if($)L_(Z,$,!0);else L5.nextTick(qi0,Z)}try{Z._construct(($)=>{L5.nextTick(X,$)})}catch($){L5.nextTick(X,$)}}function qi0(Z){Z.emit(B_)}function B40(Z){return(Z===null||Z===void 0?void 0:Z.setHeader)&&typeof Z.abort==="function"}function O40(Z){Z.emit("close")}function Ci0(Z,J){Z.emit("error",J),L5.nextTick(O40,Z)}function Ni0(Z,J){if(!Z||Di0(Z))return;if(!J&&!_i0(Z))J=new Ui0;if(Oi0(Z))Z.socket=null,Z.destroy(J);else if(B40(Z))Z.abort();else if(B40(Z.req))Z.req.abort();else if(typeof Z.destroy==="function")Z.destroy(J);else if(typeof Z.close==="function")Z.close();else if(J)L5.nextTick(Ci0,Z,J);else L5.nextTick(O40,Z);if(!Z.destroyed)Z[Li0]=!0}w40.exports={construct:Ai0,destroyer:Ni0,destroy:wi0,undestroy:Mi0,errorOrDestroy:L_}});var VG=L((uR1,M40)=>{var{ArrayIsArray:Ri0,ObjectSetPrototypeOf:j40}=F1(),{EventEmitter:GG}=N("events");function HG(Z){GG.call(this,Z)}j40(HG.prototype,GG.prototype);j40(HG,GG);HG.prototype.pipe=function(Z,J){let X=this;function $(H){if(Z.writable&&Z.write(H)===!1&&X.pause)X.pause()}X.on("data",$);function Y(){if(X.readable&&X.resume)X.resume()}if(Z.on("drain",Y),!Z._isStdio&&(!J||J.end!==!1))X.on("end",W),X.on("close",K);let Q=!1;function W(){if(Q)return;Q=!0,Z.end()}function K(){if(Q)return;if(Q=!0,typeof Z.destroy==="function")Z.destroy()}function z(H){if(G(),GG.listenerCount(this,"error")===0)this.emit("error",H)}D_(X,"error",z),D_(Z,"error",z);function G(){X.removeListener("data",$),Z.removeListener("drain",Y),X.removeListener("end",W),X.removeListener("close",K),X.removeListener("error",z),Z.removeListener("error",z),X.removeListener("end",G),X.removeListener("close",G),Z.removeListener("close",G)}return X.on("end",G),X.on("close",G),Z.on("close",G),Z.emit("pipe",X),Z};function D_(Z,J,X){if(typeof Z.prependListener==="function")return Z.prependListener(J,X);if(!Z._events||!Z._events[J])Z.on(J,X);else if(Ri0(Z._events[J]))Z._events[J].unshift(X);else Z._events[J]=[X,Z._events[J]]}M40.exports={Stream:HG,prependListener:D_}});var x3=L((xi0,FG)=>{var{SymbolDispose:Pi0}=F1(),{AbortError:A40,codes:Ei0}=T4(),{isNodeStream:T40,isWebStream:Ii0,kControllerErrorFunction:yi0}=U5(),Si0=F9(),{ERR_INVALID_ARG_TYPE:q40}=Ei0,__,ki0=(Z,J)=>{if(typeof Z!=="object"||!("aborted"in Z))throw new q40(J,"AbortSignal",Z)};xi0.addAbortSignal=function(J,X){if(ki0(J,"signal"),!T40(X)&&!Ii0(X))throw new q40("stream",["ReadableStream","WritableStream","Stream"],X);return xi0.addAbortSignalNoValidate(J,X)};xi0.addAbortSignalNoValidate=function(Z,J){if(typeof Z!=="object"||!("aborted"in Z))return J;let X=T40(J)?()=>{J.destroy(new A40(void 0,{cause:Z.reason}))}:()=>{J[yi0](new A40(void 0,{cause:Z.reason}))};if(Z.aborted)X();else{__=__||b4().addAbortListener;let $=__(Z,X);Si0(J,$[Pi0])}return J}});var R40=L((cR1,N40)=>{var{StringPrototypeSlice:C40,SymbolIterator:fi0,TypedArrayPrototypeSet:BG,Uint8Array:bi0}=F1(),{Buffer:O_}=N("buffer"),{inspect:gi0}=b4();N40.exports=class{constructor(){this.head=null,this.tail=null,this.length=0}push(J){let X={data:J,next:null};if(this.length>0)this.tail.next=X;else this.head=X;this.tail=X,++this.length}unshift(J){let X={data:J,next:this.head};if(this.length===0)this.tail=X;this.head=X,++this.length}shift(){if(this.length===0)return;let J=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;return--this.length,J}clear(){this.head=this.tail=null,this.length=0}join(J){if(this.length===0)return"";let X=this.head,$=""+X.data;while((X=X.next)!==null)$+=J+X.data;return $}concat(J){if(this.length===0)return O_.alloc(0);let X=O_.allocUnsafe(J>>>0),$=this.head,Y=0;while($)BG(X,$.data,Y),Y+=$.data.length,$=$.next;return X}consume(J,X){let $=this.head.data;if(J<$.length){let Y=$.slice(0,J);return this.head.data=$.slice(J),Y}if(J===$.length)return this.shift();return X?this._getString(J):this._getBuffer(J)}first(){return this.head.data}*[fi0](){for(let J=this.head;J;J=J.next)yield J.data}_getString(J){let X="",$=this.head,Y=0;do{let Q=$.data;if(J>Q.length)X+=Q,J-=Q.length;else{if(J===Q.length)if(X+=Q,++Y,$.next)this.head=$.next;else this.head=this.tail=null;else X+=C40(Q,0,J),this.head=$,$.data=C40(Q,J);break}++Y}while(($=$.next)!==null);return this.length-=Y,X}_getBuffer(J){let X=O_.allocUnsafe(J),$=J,Y=this.head,Q=0;do{let W=Y.data;if(J>W.length)BG(X,W,$-J),J-=W.length;else{if(J===W.length)if(BG(X,W,$-J),++Q,Y.next)this.head=Y.next;else this.head=this.tail=null;else BG(X,new bi0(W.buffer,W.byteOffset,J),$-J),this.head=Y,Y.data=W.slice(J);break}++Q}while((Y=Y.next)!==null);return this.length-=Q,X}[Symbol.for("nodejs.util.inspect.custom")](J,X){return gi0(this,{...X,depth:0,customInspect:!1})}}});var v3=L((lR1,y40)=>{var{MathFloor:mi0,NumberIsInteger:di0}=F1(),{validateInteger:ui0}=nX(),{ERR_INVALID_ARG_VALUE:ci0}=T4().codes,P40=16384,E40=16;function li0(Z,J,X){return Z.highWaterMark!=null?Z.highWaterMark:J?Z[X]:null}function I40(Z){return Z?E40:P40}function pi0(Z,J){if(ui0(J,"value",0),Z)E40=J;else P40=J}function ii0(Z,J,X,$){let Y=li0(J,$,X);if(Y!=null){if(!di0(Y)||Y<0){let Q=$?`options.${X}`:"options.highWaterMark";throw new ci0(Q,Y)}return mi0(Y)}return I40(Z.objectMode)}y40.exports={getHighWaterMark:ii0,getDefaultHighWaterMark:I40,setDefaultHighWaterMark:pi0}});var x40=L((w_,k40)=>{/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var UG=N("buffer"),D5=UG.Buffer;function S40(Z,J){for(var X in Z)J[X]=Z[X]}if(D5.from&&D5.alloc&&D5.allocUnsafe&&D5.allocUnsafeSlow)k40.exports=UG;else S40(UG,w_),w_.Buffer=cZ;function cZ(Z,J,X){return D5(Z,J,X)}cZ.prototype=Object.create(D5.prototype);S40(D5,cZ);cZ.from=function(Z,J,X){if(typeof Z==="number")throw TypeError("Argument must not be a number");return D5(Z,J,X)};cZ.alloc=function(Z,J,X){if(typeof Z!=="number")throw TypeError("Argument must be a number");var $=D5(Z);if(J!==void 0)if(typeof X==="string")$.fill(J,X);else $.fill(J);else $.fill(0);return $};cZ.allocUnsafe=function(Z){if(typeof Z!=="number")throw TypeError("Argument must be a number");return D5(Z)};cZ.allocUnsafeSlow=function(Z){if(typeof Z!=="number")throw TypeError("Argument must be a number");return UG.SlowBuffer(Z)}});var h40=L((Wn0)=>{var M_=x40().Buffer,v40=M_.isEncoding||function(Z){switch(Z=""+Z,Z&&Z.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function ni0(Z){if(!Z)return"utf8";var J;while(!0)switch(Z){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return Z;default:if(J)return;Z=(""+Z).toLowerCase(),J=!0}}function oi0(Z){var J=ni0(Z);if(typeof J!=="string"&&(M_.isEncoding===v40||!v40(Z)))throw Error("Unknown encoding: "+Z);return J||Z}Wn0.StringDecoder=h3;function h3(Z){this.encoding=oi0(Z);var J;switch(this.encoding){case"utf16le":this.text=Zn0,this.end=Jn0,J=4;break;case"utf8":this.fillLast=si0,J=4;break;case"base64":this.text=Xn0,this.end=$n0,J=3;break;default:this.write=Yn0,this.end=Qn0;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=M_.allocUnsafe(J)}h3.prototype.write=function(Z){if(Z.length===0)return"";var J,X;if(this.lastNeed){if(J=this.fillLast(Z),J===void 0)return"";X=this.lastNeed,this.lastNeed=0}else X=0;if(X<Z.length)return J?J+this.text(Z,X):this.text(Z,X);return J||""};h3.prototype.end=ei0;h3.prototype.text=ti0;h3.prototype.fillLast=function(Z){if(this.lastNeed<=Z.length)return Z.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);Z.copy(this.lastChar,this.lastTotal-this.lastNeed,0,Z.length),this.lastNeed-=Z.length};function j_(Z){if(Z<=127)return 0;else if(Z>>5===6)return 2;else if(Z>>4===14)return 3;else if(Z>>3===30)return 4;return Z>>6===2?-1:-2}function ai0(Z,J,X){var $=J.length-1;if($<X)return 0;var Y=j_(J[$]);if(Y>=0){if(Y>0)Z.lastNeed=Y-1;return Y}if(--$<X||Y===-2)return 0;if(Y=j_(J[$]),Y>=0){if(Y>0)Z.lastNeed=Y-2;return Y}if(--$<X||Y===-2)return 0;if(Y=j_(J[$]),Y>=0){if(Y>0)if(Y===2)Y=0;else Z.lastNeed=Y-3;return Y}return 0}function ri0(Z,J,X){if((J[0]&192)!==128)return Z.lastNeed=0,"\uFFFD";if(Z.lastNeed>1&&J.length>1){if((J[1]&192)!==128)return Z.lastNeed=1,"\uFFFD";if(Z.lastNeed>2&&J.length>2){if((J[2]&192)!==128)return Z.lastNeed=2,"\uFFFD"}}}function si0(Z){var J=this.lastTotal-this.lastNeed,X=ri0(this,Z,J);if(X!==void 0)return X;if(this.lastNeed<=Z.length)return Z.copy(this.lastChar,J,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);Z.copy(this.lastChar,J,0,Z.length),this.lastNeed-=Z.length}function ti0(Z,J){var X=ai0(this,Z,J);if(!this.lastNeed)return Z.toString("utf8",J);this.lastTotal=X;var $=Z.length-(X-this.lastNeed);return Z.copy(this.lastChar,0,$),Z.toString("utf8",J,$)}function ei0(Z){var J=Z&&Z.length?this.write(Z):"";if(this.lastNeed)return J+"\uFFFD";return J}function Zn0(Z,J){if((Z.length-J)%2===0){var X=Z.toString("utf16le",J);if(X){var $=X.charCodeAt(X.length-1);if($>=55296&&$<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=Z[Z.length-2],this.lastChar[1]=Z[Z.length-1],X.slice(0,-1)}return X}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=Z[Z.length-1],Z.toString("utf16le",J,Z.length-1)}function Jn0(Z){var J=Z&&Z.length?this.write(Z):"";if(this.lastNeed){var X=this.lastTotal-this.lastNeed;return J+this.lastChar.toString("utf16le",0,X)}return J}function Xn0(Z,J){var X=(Z.length-J)%3;if(X===0)return Z.toString("base64",J);if(this.lastNeed=3-X,this.lastTotal=3,X===1)this.lastChar[0]=Z[Z.length-1];else this.lastChar[0]=Z[Z.length-2],this.lastChar[1]=Z[Z.length-1];return Z.toString("base64",J,Z.length-X)}function $n0(Z){var J=Z&&Z.length?this.write(Z):"";if(this.lastNeed)return J+this.lastChar.toString("base64",0,3-this.lastNeed);return J}function Yn0(Z){return Z.toString(this.encoding)}function Qn0(Z){return Z&&Z.length?this.write(Z):""}});var A_=L((iR1,m40)=>{var f40=q7(),{PromisePrototypeThen:zn0,SymbolAsyncIterator:b40,SymbolIterator:g40}=F1(),{Buffer:Gn0}=N("buffer"),{ERR_INVALID_ARG_TYPE:Hn0,ERR_STREAM_NULL_VALUES:Vn0}=T4().codes;function Fn0(Z,J,X){let $;if(typeof J==="string"||J instanceof Gn0)return new Z({objectMode:!0,...X,read(){this.push(J),this.push(null)}});let Y;if(J&&J[b40])Y=!0,$=J[b40]();else if(J&&J[g40])Y=!1,$=J[g40]();else throw new Hn0("iterable",["Iterable"],J);let Q=new Z({objectMode:!0,highWaterMark:1,...X}),W=!1;Q._read=function(){if(!W)W=!0,z()},Q._destroy=function(G,H){zn0(K(G),()=>f40.nextTick(H,G),(V)=>f40.nextTick(H,V||G))};async function K(G){let H=G!==void 0&&G!==null,V=typeof $.throw==="function";if(H&&V){let{value:F,done:B}=await $.throw(G);if(await F,B)return}if(typeof $.return==="function"){let{value:F}=await $.return();await F}}async function z(){for(;;){try{let{value:G,done:H}=Y?await $.next():$.next();if(H)Q.push(null);else{let V=G&&typeof G.then==="function"?await G:G;if(V===null)throw W=!1,new Vn0;else if(Q.push(V))continue;else W=!1}}catch(G){Q.destroy(G)}break}}return Q}m40.exports=Fn0});var b3=L((nR1,Y60)=>{var h8=q7(),{ArrayPrototypeIndexOf:Bn0,NumberIsInteger:Un0,NumberIsNaN:Ln0,NumberParseInt:Dn0,ObjectDefineProperties:I_,ObjectKeys:_n0,ObjectSetPrototypeOf:c40,Promise:l40,SafeSet:On0,SymbolAsyncDispose:wn0,SymbolAsyncIterator:jn0,Symbol:Mn0}=F1();Y60.exports=q0;q0.ReadableState=OG;var{EventEmitter:An0}=N("events"),{Stream:N7,prependListener:Tn0}=VG(),{Buffer:T_}=N("buffer"),{addAbortSignal:qn0}=x3(),p40=F9(),y0=b4().debuglog("stream",(Z)=>{y0=Z}),Cn0=R40(),sX=uZ(),{getHighWaterMark:Nn0,getDefaultHighWaterMark:Rn0}=v3(),{aggregateTwoErrors:d40,codes:{ERR_INVALID_ARG_TYPE:Pn0,ERR_METHOD_NOT_IMPLEMENTED:En0,ERR_OUT_OF_RANGE:In0,ERR_STREAM_PUSH_AFTER_EOF:yn0,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:Sn0},AbortError:kn0}=T4(),{validateObject:xn0}=nX(),lZ=Mn0("kPaused"),{StringDecoder:i40}=h40(),vn0=A_();c40(q0.prototype,N7.prototype);c40(q0,N7);var q_=()=>{},{errorOrDestroy:aX}=sX,rX=1,hn0=2,n40=4,f3=8,o40=16,LG=32,DG=64,a40=128,fn0=256,bn0=512,gn0=1024,P_=2048,E_=4096,mn0=8192,dn0=16384,un0=32768,r40=65536,cn0=131072,ln0=262144;function n1(Z){return{enumerable:!1,get(){return(this.state&Z)!==0},set(J){if(J)this.state|=Z;else this.state&=~Z}}}I_(OG.prototype,{objectMode:n1(rX),ended:n1(hn0),endEmitted:n1(n40),reading:n1(f3),constructed:n1(o40),sync:n1(LG),needReadable:n1(DG),emittedReadable:n1(a40),readableListening:n1(fn0),resumeScheduled:n1(bn0),errorEmitted:n1(gn0),emitClose:n1(P_),autoDestroy:n1(E_),destroyed:n1(mn0),closed:n1(dn0),closeEmitted:n1(un0),multiAwaitDrain:n1(r40),readingMore:n1(cn0),dataEmitted:n1(ln0)});function OG(Z,J,X){if(typeof X!=="boolean")X=J instanceof _5();if(this.state=P_|E_|o40|LG,Z&&Z.objectMode)this.state|=rX;if(X&&Z&&Z.readableObjectMode)this.state|=rX;if(this.highWaterMark=Z?Nn0(this,Z,"readableHighWaterMark",X):Rn0(!1),this.buffer=new Cn0,this.length=0,this.pipes=[],this.flowing=null,this[lZ]=null,Z&&Z.emitClose===!1)this.state&=~P_;if(Z&&Z.autoDestroy===!1)this.state&=~E_;if(this.errored=null,this.defaultEncoding=Z&&Z.defaultEncoding||"utf8",this.awaitDrainWriters=null,this.decoder=null,this.encoding=null,Z&&Z.encoding)this.decoder=new i40(Z.encoding),this.encoding=Z.encoding}function q0(Z){if(!(this instanceof q0))return new q0(Z);let J=this instanceof _5();if(this._readableState=new OG(Z,this,J),Z){if(typeof Z.read==="function")this._read=Z.read;if(typeof Z.destroy==="function")this._destroy=Z.destroy;if(typeof Z.construct==="function")this._construct=Z.construct;if(Z.signal&&!J)qn0(Z.signal,this)}N7.call(this,Z),sX.construct(this,()=>{if(this._readableState.needReadable)_G(this,this._readableState)})}q0.prototype.destroy=sX.destroy;q0.prototype._undestroy=sX.undestroy;q0.prototype._destroy=function(Z,J){J(Z)};q0.prototype[An0.captureRejectionSymbol]=function(Z){this.destroy(Z)};q0.prototype[wn0]=function(){let Z;if(!this.destroyed)Z=this.readableEnded?null:new kn0,this.destroy(Z);return new l40((J,X)=>p40(this,($)=>$&&$!==Z?X($):J(null)))};q0.prototype.push=function(Z,J){return s40(this,Z,J,!1)};q0.prototype.unshift=function(Z,J){return s40(this,Z,J,!0)};function s40(Z,J,X,$){y0("readableAddChunk",J);let Y=Z._readableState,Q;if((Y.state&rX)===0){if(typeof J==="string"){if(X=X||Y.defaultEncoding,Y.encoding!==X)if($&&Y.encoding)J=T_.from(J,X).toString(Y.encoding);else J=T_.from(J,X),X=""}else if(J instanceof T_)X="";else if(N7._isUint8Array(J))J=N7._uint8ArrayToBuffer(J),X="";else if(J!=null)Q=new Pn0("chunk",["string","Buffer","Uint8Array"],J)}if(Q)aX(Z,Q);else if(J===null)Y.state&=~f3,nn0(Z,Y);else if((Y.state&rX)!==0||J&&J.length>0)if($)if((Y.state&n40)!==0)aX(Z,new Sn0);else if(Y.destroyed||Y.errored)return!1;else C_(Z,Y,J,!0);else if(Y.ended)aX(Z,new yn0);else if(Y.destroyed||Y.errored)return!1;else if(Y.state&=~f3,Y.decoder&&!X)if(J=Y.decoder.write(J),Y.objectMode||J.length!==0)C_(Z,Y,J,!1);else _G(Z,Y);else C_(Z,Y,J,!1);else if(!$)Y.state&=~f3,_G(Z,Y);return!Y.ended&&(Y.length<Y.highWaterMark||Y.length===0)}function C_(Z,J,X,$){if(J.flowing&&J.length===0&&!J.sync&&Z.listenerCount("data")>0){if((J.state&r40)!==0)J.awaitDrainWriters.clear();else J.awaitDrainWriters=null;J.dataEmitted=!0,Z.emit("data",X)}else{if(J.length+=J.objectMode?1:X.length,$)J.buffer.unshift(X);else J.buffer.push(X);if((J.state&DG)!==0)wG(Z)}_G(Z,J)}q0.prototype.isPaused=function(){let Z=this._readableState;return Z[lZ]===!0||Z.flowing===!1};q0.prototype.setEncoding=function(Z){let J=new i40(Z);this._readableState.decoder=J,this._readableState.encoding=this._readableState.decoder.encoding;let X=this._readableState.buffer,$="";for(let Y of X)$+=J.write(Y);if(X.clear(),$!=="")X.push($);return this._readableState.length=$.length,this};var pn0=1073741824;function in0(Z){if(Z>pn0)throw new In0("size","<= 1GiB",Z);else Z--,Z|=Z>>>1,Z|=Z>>>2,Z|=Z>>>4,Z|=Z>>>8,Z|=Z>>>16,Z++;return Z}function u40(Z,J){if(Z<=0||J.length===0&&J.ended)return 0;if((J.state&rX)!==0)return 1;if(Ln0(Z)){if(J.flowing&&J.length)return J.buffer.first().length;return J.length}if(Z<=J.length)return Z;return J.ended?J.length:0}q0.prototype.read=function(Z){if(y0("read",Z),Z===void 0)Z=NaN;else if(!Un0(Z))Z=Dn0(Z,10);let J=this._readableState,X=Z;if(Z>J.highWaterMark)J.highWaterMark=in0(Z);if(Z!==0)J.state&=~a40;if(Z===0&&J.needReadable&&((J.highWaterMark!==0?J.length>=J.highWaterMark:J.length>0)||J.ended)){if(y0("read: emitReadable",J.length,J.ended),J.length===0&&J.ended)N_(this);else wG(this);return null}if(Z=u40(Z,J),Z===0&&J.ended){if(J.length===0)N_(this);return null}let $=(J.state&DG)!==0;if(y0("need readable",$),J.length===0||J.length-Z<J.highWaterMark)$=!0,y0("length less than watermark",$);if(J.ended||J.reading||J.destroyed||J.errored||!J.constructed)$=!1,y0("reading, ended or constructing",$);else if($){if(y0("do read"),J.state|=f3|LG,J.length===0)J.state|=DG;try{this._read(J.highWaterMark)}catch(Q){aX(this,Q)}if(J.state&=~LG,!J.reading)Z=u40(X,J)}let Y;if(Z>0)Y=X60(Z,J);else Y=null;if(Y===null)J.needReadable=J.length<=J.highWaterMark,Z=0;else if(J.length-=Z,J.multiAwaitDrain)J.awaitDrainWriters.clear();else J.awaitDrainWriters=null;if(J.length===0){if(!J.ended)J.needReadable=!0;if(X!==Z&&J.ended)N_(this)}if(Y!==null&&!J.errorEmitted&&!J.closeEmitted)J.dataEmitted=!0,this.emit("data",Y);return Y};function nn0(Z,J){if(y0("onEofChunk"),J.ended)return;if(J.decoder){let X=J.decoder.end();if(X&&X.length)J.buffer.push(X),J.length+=J.objectMode?1:X.length}if(J.ended=!0,J.sync)wG(Z);else J.needReadable=!1,J.emittedReadable=!0,t40(Z)}function wG(Z){let J=Z._readableState;if(y0("emitReadable",J.needReadable,J.emittedReadable),J.needReadable=!1,!J.emittedReadable)y0("emitReadable",J.flowing),J.emittedReadable=!0,h8.nextTick(t40,Z)}function t40(Z){let J=Z._readableState;if(y0("emitReadable_",J.destroyed,J.length,J.ended),!J.destroyed&&!J.errored&&(J.length||J.ended))Z.emit("readable"),J.emittedReadable=!1;J.needReadable=!J.flowing&&!J.ended&&J.length<=J.highWaterMark,Z60(Z)}function _G(Z,J){if(!J.readingMore&&J.constructed)J.readingMore=!0,h8.nextTick(on0,Z,J)}function on0(Z,J){while(!J.reading&&!J.ended&&(J.length<J.highWaterMark||J.flowing&&J.length===0)){let X=J.length;if(y0("maybeReadMore read 0"),Z.read(0),X===J.length)break}J.readingMore=!1}q0.prototype._read=function(Z){throw new En0("_read()")};q0.prototype.pipe=function(Z,J){let X=this,$=this._readableState;if($.pipes.length===1){if(!$.multiAwaitDrain)$.multiAwaitDrain=!0,$.awaitDrainWriters=new On0($.awaitDrainWriters?[$.awaitDrainWriters]:[])}$.pipes.push(Z),y0("pipe count=%d opts=%j",$.pipes.length,J);let Q=(!J||J.end!==!1)&&Z!==h8.stdout&&Z!==h8.stderr?K:_;if($.endEmitted)h8.nextTick(Q);else X.once("end",Q);Z.on("unpipe",W);function W(O,w){if(y0("onunpipe"),O===X){if(w&&w.hasUnpiped===!1)w.hasUnpiped=!0,H()}}function K(){y0("onend"),Z.end()}let z,G=!1;function H(){if(y0("cleanup"),Z.removeListener("close",U),Z.removeListener("finish",D),z)Z.removeListener("drain",z);if(Z.removeListener("error",B),Z.removeListener("unpipe",W),X.removeListener("end",K),X.removeListener("end",_),X.removeListener("data",F),G=!0,z&&$.awaitDrainWriters&&(!Z._writableState||Z._writableState.needDrain))z()}function V(){if(!G){if($.pipes.length===1&&$.pipes[0]===Z)y0("false write response, pause",0),$.awaitDrainWriters=Z,$.multiAwaitDrain=!1;else if($.pipes.length>1&&$.pipes.includes(Z))y0("false write response, pause",$.awaitDrainWriters.size),$.awaitDrainWriters.add(Z);X.pause()}if(!z)z=an0(X,Z),Z.on("drain",z)}X.on("data",F);function F(O){y0("ondata");let w=Z.write(O);if(y0("dest.write",w),w===!1)V()}function B(O){if(y0("onerror",O),_(),Z.removeListener("error",B),Z.listenerCount("error")===0){let w=Z._writableState||Z._readableState;if(w&&!w.errorEmitted)aX(Z,O);else Z.emit("error",O)}}Tn0(Z,"error",B);function U(){Z.removeListener("finish",D),_()}Z.once("close",U);function D(){y0("onfinish"),Z.removeListener("close",U),_()}Z.once("finish",D);function _(){y0("unpipe"),X.unpipe(Z)}if(Z.emit("pipe",X),Z.writableNeedDrain===!0)V();else if(!$.flowing)y0("pipe resume"),X.resume();return Z};function an0(Z,J){return function(){let $=Z._readableState;if($.awaitDrainWriters===J)y0("pipeOnDrain",1),$.awaitDrainWriters=null;else if($.multiAwaitDrain)y0("pipeOnDrain",$.awaitDrainWriters.size),$.awaitDrainWriters.delete(J);if((!$.awaitDrainWriters||$.awaitDrainWriters.size===0)&&Z.listenerCount("data"))Z.resume()}}q0.prototype.unpipe=function(Z){let J=this._readableState,X={hasUnpiped:!1};if(J.pipes.length===0)return this;if(!Z){let Y=J.pipes;J.pipes=[],this.pause();for(let Q=0;Q<Y.length;Q++)Y[Q].emit("unpipe",this,{hasUnpiped:!1});return this}let $=Bn0(J.pipes,Z);if($===-1)return this;if(J.pipes.splice($,1),J.pipes.length===0)this.pause();return Z.emit("unpipe",this,X),this};q0.prototype.on=function(Z,J){let X=N7.prototype.on.call(this,Z,J),$=this._readableState;if(Z==="data"){if($.readableListening=this.listenerCount("readable")>0,$.flowing!==!1)this.resume()}else if(Z==="readable"){if(!$.endEmitted&&!$.readableListening){if($.readableListening=$.needReadable=!0,$.flowing=!1,$.emittedReadable=!1,y0("on readable",$.length,$.reading),$.length)wG(this);else if(!$.reading)h8.nextTick(rn0,this)}}return X};q0.prototype.addListener=q0.prototype.on;q0.prototype.removeListener=function(Z,J){let X=N7.prototype.removeListener.call(this,Z,J);if(Z==="readable")h8.nextTick(e40,this);return X};q0.prototype.off=q0.prototype.removeListener;q0.prototype.removeAllListeners=function(Z){let J=N7.prototype.removeAllListeners.apply(this,arguments);if(Z==="readable"||Z===void 0)h8.nextTick(e40,this);return J};function e40(Z){let J=Z._readableState;if(J.readableListening=Z.listenerCount("readable")>0,J.resumeScheduled&&J[lZ]===!1)J.flowing=!0;else if(Z.listenerCount("data")>0)Z.resume();else if(!J.readableListening)J.flowing=null}function rn0(Z){y0("readable nexttick read 0"),Z.read(0)}q0.prototype.resume=function(){let Z=this._readableState;if(!Z.flowing)y0("resume"),Z.flowing=!Z.readableListening,sn0(this,Z);return Z[lZ]=!1,this};function sn0(Z,J){if(!J.resumeScheduled)J.resumeScheduled=!0,h8.nextTick(tn0,Z,J)}function tn0(Z,J){if(y0("resume",J.reading),!J.reading)Z.read(0);if(J.resumeScheduled=!1,Z.emit("resume"),Z60(Z),J.flowing&&!J.reading)Z.read(0)}q0.prototype.pause=function(){if(y0("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1)y0("pause"),this._readableState.flowing=!1,this.emit("pause");return this._readableState[lZ]=!0,this};function Z60(Z){let J=Z._readableState;y0("flow",J.flowing);while(J.flowing&&Z.read()!==null);}q0.prototype.wrap=function(Z){let J=!1;Z.on("data",($)=>{if(!this.push($)&&Z.pause)J=!0,Z.pause()}),Z.on("end",()=>{this.push(null)}),Z.on("error",($)=>{aX(this,$)}),Z.on("close",()=>{this.destroy()}),Z.on("destroy",()=>{this.destroy()}),this._read=()=>{if(J&&Z.resume)J=!1,Z.resume()};let X=_n0(Z);for(let $=1;$<X.length;$++){let Y=X[$];if(this[Y]===void 0&&typeof Z[Y]==="function")this[Y]=Z[Y].bind(Z)}return this};q0.prototype[jn0]=function(){return J60(this)};q0.prototype.iterator=function(Z){if(Z!==void 0)xn0(Z,"options");return J60(this,Z)};function J60(Z,J){if(typeof Z.read!=="function")Z=q0.wrap(Z,{objectMode:!0});let X=en0(Z,J);return X.stream=Z,X}async function*en0(Z,J){let X=q_;function $(W){if(this===Z)X(),X=q_;else X=W}Z.on("readable",$);let Y,Q=p40(Z,{writable:!1},(W)=>{Y=W?d40(Y,W):null,X(),X=q_});try{while(!0){let W=Z.destroyed?null:Z.read();if(W!==null)yield W;else if(Y)throw Y;else if(Y===null)return;else await new l40($)}}catch(W){throw Y=d40(Y,W),Y}finally{if((Y||(J===null||J===void 0?void 0:J.destroyOnReturn)!==!1)&&(Y===void 0||Z._readableState.autoDestroy))sX.destroyer(Z,null);else Z.off("readable",$),Q()}}I_(q0.prototype,{readable:{__proto__:null,get(){let Z=this._readableState;return!!Z&&Z.readable!==!1&&!Z.destroyed&&!Z.errorEmitted&&!Z.endEmitted},set(Z){if(this._readableState)this._readableState.readable=!!Z}},readableDidRead:{__proto__:null,enumerable:!1,get:function(){return this._readableState.dataEmitted}},readableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._readableState.readable!==!1&&(this._readableState.destroyed||this._readableState.errored)&&!this._readableState.endEmitted)}},readableHighWaterMark:{__proto__:null,enumerable:!1,get:function(){return this._readableState.highWaterMark}},readableBuffer:{__proto__:null,enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}},readableFlowing:{__proto__:null,enumerable:!1,get:function(){return this._readableState.flowing},set:function(Z){if(this._readableState)this._readableState.flowing=Z}},readableLength:{__proto__:null,enumerable:!1,get(){return this._readableState.length}},readableObjectMode:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.objectMode:!1}},readableEncoding:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.encoding:null}},errored:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.errored:null}},closed:{__proto__:null,get(){return this._readableState?this._readableState.closed:!1}},destroyed:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.destroyed:!1},set(Z){if(!this._readableState)return;this._readableState.destroyed=Z}},readableEnded:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.endEmitted:!1}}});I_(OG.prototype,{pipesCount:{__proto__:null,get(){return this.pipes.length}},paused:{__proto__:null,get(){return this[lZ]!==!1},set(Z){this[lZ]=!!Z}}});q0._fromList=X60;function X60(Z,J){if(J.length===0)return null;let X;if(J.objectMode)X=J.buffer.shift();else if(!Z||Z>=J.length){if(J.decoder)X=J.buffer.join("");else if(J.buffer.length===1)X=J.buffer.first();else X=J.buffer.concat(J.length);J.buffer.clear()}else X=J.buffer.consume(Z,J.decoder);return X}function N_(Z){let J=Z._readableState;if(y0("endReadable",J.endEmitted),!J.endEmitted)J.ended=!0,h8.nextTick(Zo0,J,Z)}function Zo0(Z,J){if(y0("endReadableNT",Z.endEmitted,Z.length),!Z.errored&&!Z.closeEmitted&&!Z.endEmitted&&Z.length===0){if(Z.endEmitted=!0,J.emit("end"),J.writable&&J.allowHalfOpen===!1)h8.nextTick(Jo0,J);else if(Z.autoDestroy){let X=J._writableState;if(!X||X.autoDestroy&&(X.finished||X.writable===!1))J.destroy()}}}function Jo0(Z){if(Z.writable&&!Z.writableEnded&&!Z.destroyed)Z.end()}q0.from=function(Z,J){return vn0(q0,Z,J)};var R_;function $60(){if(R_===void 0)R_={};return R_}q0.fromWeb=function(Z,J){return $60().newStreamReadableFromReadableStream(Z,J)};q0.toWeb=function(Z,J){return $60().newReadableStreamFromStreamReadable(Z,J)};q0.wrap=function(Z,J){var X,$;return new q0({objectMode:(X=($=Z.readableObjectMode)!==null&&$!==void 0?$:Z.objectMode)!==null&&X!==void 0?X:!0,...J,destroy(Y,Q){sX.destroyer(Z,Y),Q(Y)}}).wrap(Z)}});var qG=L((oR1,D60)=>{var pZ=q7(),{ArrayPrototypeSlice:K60,Error:Xo0,FunctionPrototypeSymbolHasInstance:z60,ObjectDefineProperty:G60,ObjectDefineProperties:$o0,ObjectSetPrototypeOf:H60,StringPrototypeToLowerCase:Yo0,Symbol:Qo0,SymbolHasInstance:Wo0}=F1();D60.exports=M1;M1.WritableState=d3;var{EventEmitter:Ko0}=N("events"),g3=VG().Stream,{Buffer:jG}=N("buffer"),TG=uZ(),{addAbortSignal:zo0}=x3(),{getHighWaterMark:Go0,getDefaultHighWaterMark:Ho0}=v3(),{ERR_INVALID_ARG_TYPE:Vo0,ERR_METHOD_NOT_IMPLEMENTED:Fo0,ERR_MULTIPLE_CALLBACK:V60,ERR_STREAM_CANNOT_PIPE:Bo0,ERR_STREAM_DESTROYED:m3,ERR_STREAM_ALREADY_FINISHED:Uo0,ERR_STREAM_NULL_VALUES:Lo0,ERR_STREAM_WRITE_AFTER_END:Do0,ERR_UNKNOWN_ENCODING:F60}=T4().codes,{errorOrDestroy:tX}=TG;H60(M1.prototype,g3.prototype);H60(M1,g3);function k_(){}var eX=Qo0("kOnFinished");function d3(Z,J,X){if(typeof X!=="boolean")X=J instanceof _5();if(this.objectMode=!!(Z&&Z.objectMode),X)this.objectMode=this.objectMode||!!(Z&&Z.writableObjectMode);this.highWaterMark=Z?Go0(this,Z,"writableHighWaterMark",X):Ho0(!1),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;let $=!!(Z&&Z.decodeStrings===!1);this.decodeStrings=!$,this.defaultEncoding=Z&&Z.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=Oo0.bind(void 0,J),this.writecb=null,this.writelen=0,this.afterWriteTickInfo=null,AG(this),this.pendingcb=0,this.constructed=!0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!Z||Z.emitClose!==!1,this.autoDestroy=!Z||Z.autoDestroy!==!1,this.errored=null,this.closed=!1,this.closeEmitted=!1,this[eX]=[]}function AG(Z){Z.buffered=[],Z.bufferedIndex=0,Z.allBuffers=!0,Z.allNoop=!0}d3.prototype.getBuffer=function(){return K60(this.buffered,this.bufferedIndex)};G60(d3.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}});function M1(Z){let J=this instanceof _5();if(!J&&!z60(M1,this))return new M1(Z);if(this._writableState=new d3(Z,this,J),Z){if(typeof Z.write==="function")this._write=Z.write;if(typeof Z.writev==="function")this._writev=Z.writev;if(typeof Z.destroy==="function")this._destroy=Z.destroy;if(typeof Z.final==="function")this._final=Z.final;if(typeof Z.construct==="function")this._construct=Z.construct;if(Z.signal)zo0(Z.signal,this)}g3.call(this,Z),TG.construct(this,()=>{let X=this._writableState;if(!X.writing)v_(this,X);h_(this,X)})}G60(M1,Wo0,{__proto__:null,value:function(Z){if(z60(this,Z))return!0;if(this!==M1)return!1;return Z&&Z._writableState instanceof d3}});M1.prototype.pipe=function(){tX(this,new Bo0)};function B60(Z,J,X,$){let Y=Z._writableState;if(typeof X==="function")$=X,X=Y.defaultEncoding;else{if(!X)X=Y.defaultEncoding;else if(X!=="buffer"&&!jG.isEncoding(X))throw new F60(X);if(typeof $!=="function")$=k_}if(J===null)throw new Lo0;else if(!Y.objectMode)if(typeof J==="string"){if(Y.decodeStrings!==!1)J=jG.from(J,X),X="buffer"}else if(J instanceof jG)X="buffer";else if(g3._isUint8Array(J))J=g3._uint8ArrayToBuffer(J),X="buffer";else throw new Vo0("chunk",["string","Buffer","Uint8Array"],J);let Q;if(Y.ending)Q=new Do0;else if(Y.destroyed)Q=new m3("write");if(Q)return pZ.nextTick($,Q),tX(Z,Q,!0),Q;return Y.pendingcb++,_o0(Z,Y,J,X,$)}M1.prototype.write=function(Z,J,X){return B60(this,Z,J,X)===!0};M1.prototype.cork=function(){this._writableState.corked++};M1.prototype.uncork=function(){let Z=this._writableState;if(Z.corked){if(Z.corked--,!Z.writing)v_(this,Z)}};M1.prototype.setDefaultEncoding=function(J){if(typeof J==="string")J=Yo0(J);if(!jG.isEncoding(J))throw new F60(J);return this._writableState.defaultEncoding=J,this};function _o0(Z,J,X,$,Y){let Q=J.objectMode?1:X.length;J.length+=Q;let W=J.length<J.highWaterMark;if(!W)J.needDrain=!0;if(J.writing||J.corked||J.errored||!J.constructed){if(J.buffered.push({chunk:X,encoding:$,callback:Y}),J.allBuffers&&$!=="buffer")J.allBuffers=!1;if(J.allNoop&&Y!==k_)J.allNoop=!1}else J.writelen=Q,J.writecb=Y,J.writing=!0,J.sync=!0,Z._write(X,$,J.onwrite),J.sync=!1;return W&&!J.errored&&!J.destroyed}function Q60(Z,J,X,$,Y,Q,W){if(J.writelen=$,J.writecb=W,J.writing=!0,J.sync=!0,J.destroyed)J.onwrite(new m3("write"));else if(X)Z._writev(Y,J.onwrite);else Z._write(Y,Q,J.onwrite);J.sync=!1}function W60(Z,J,X,$){--J.pendingcb,$(X),x_(J),tX(Z,X)}function Oo0(Z,J){let X=Z._writableState,$=X.sync,Y=X.writecb;if(typeof Y!=="function"){tX(Z,new V60);return}if(X.writing=!1,X.writecb=null,X.length-=X.writelen,X.writelen=0,J){if(J.stack,!X.errored)X.errored=J;if(Z._readableState&&!Z._readableState.errored)Z._readableState.errored=J;if($)pZ.nextTick(W60,Z,X,J,Y);else W60(Z,X,J,Y)}else{if(X.buffered.length>X.bufferedIndex)v_(Z,X);if($)if(X.afterWriteTickInfo!==null&&X.afterWriteTickInfo.cb===Y)X.afterWriteTickInfo.count++;else X.afterWriteTickInfo={count:1,cb:Y,stream:Z,state:X},pZ.nextTick(wo0,X.afterWriteTickInfo);else U60(Z,X,1,Y)}}function wo0({stream:Z,state:J,count:X,cb:$}){return J.afterWriteTickInfo=null,U60(Z,J,X,$)}function U60(Z,J,X,$){if(!J.ending&&!Z.destroyed&&J.length===0&&J.needDrain)J.needDrain=!1,Z.emit("drain");while(X-- >0)J.pendingcb--,$();if(J.destroyed)x_(J);h_(Z,J)}function x_(Z){if(Z.writing)return;for(let Y=Z.bufferedIndex;Y<Z.buffered.length;++Y){var J;let{chunk:Q,callback:W}=Z.buffered[Y],K=Z.objectMode?1:Q.length;Z.length-=K,W((J=Z.errored)!==null&&J!==void 0?J:new m3("write"))}let X=Z[eX].splice(0);for(let Y=0;Y<X.length;Y++){var $;X[Y](($=Z.errored)!==null&&$!==void 0?$:new m3("end"))}AG(Z)}function v_(Z,J){if(J.corked||J.bufferProcessing||J.destroyed||!J.constructed)return;let{buffered:X,bufferedIndex:$,objectMode:Y}=J,Q=X.length-$;if(!Q)return;let W=$;if(J.bufferProcessing=!0,Q>1&&Z._writev){J.pendingcb-=Q-1;let K=J.allNoop?k_:(G)=>{for(let H=W;H<X.length;++H)X[H].callback(G)},z=J.allNoop&&W===0?X:K60(X,W);z.allBuffers=J.allBuffers,Q60(Z,J,!0,J.length,z,"",K),AG(J)}else{do{let{chunk:K,encoding:z,callback:G}=X[W];X[W++]=null;let H=Y?1:K.length;Q60(Z,J,!1,H,K,z,G)}while(W<X.length&&!J.writing);if(W===X.length)AG(J);else if(W>256)X.splice(0,W),J.bufferedIndex=0;else J.bufferedIndex=W}J.bufferProcessing=!1}M1.prototype._write=function(Z,J,X){if(this._writev)this._writev([{chunk:Z,encoding:J}],X);else throw new Fo0("_write()")};M1.prototype._writev=null;M1.prototype.end=function(Z,J,X){let $=this._writableState;if(typeof Z==="function")X=Z,Z=null,J=null;else if(typeof J==="function")X=J,J=null;let Y;if(Z!==null&&Z!==void 0){let Q=B60(this,Z,J);if(Q instanceof Xo0)Y=Q}if($.corked)$.corked=1,this.uncork();if(Y);else if(!$.errored&&!$.ending)$.ending=!0,h_(this,$,!0),$.ended=!0;else if($.finished)Y=new Uo0("end");else if($.destroyed)Y=new m3("end");if(typeof X==="function")if(Y||$.finished)pZ.nextTick(X,Y);else $[eX].push(X);return this};function MG(Z){return Z.ending&&!Z.destroyed&&Z.constructed&&Z.length===0&&!Z.errored&&Z.buffered.length===0&&!Z.finished&&!Z.writing&&!Z.errorEmitted&&!Z.closeEmitted}function jo0(Z,J){let X=!1;function $(Y){if(X){tX(Z,Y!==null&&Y!==void 0?Y:V60());return}if(X=!0,J.pendingcb--,Y){let Q=J[eX].splice(0);for(let W=0;W<Q.length;W++)Q[W](Y);tX(Z,Y,J.sync)}else if(MG(J))J.prefinished=!0,Z.emit("prefinish"),J.pendingcb++,pZ.nextTick(S_,Z,J)}J.sync=!0,J.pendingcb++;try{Z._final($)}catch(Y){$(Y)}J.sync=!1}function Mo0(Z,J){if(!J.prefinished&&!J.finalCalled)if(typeof Z._final==="function"&&!J.destroyed)J.finalCalled=!0,jo0(Z,J);else J.prefinished=!0,Z.emit("prefinish")}function h_(Z,J,X){if(MG(J)){if(Mo0(Z,J),J.pendingcb===0){if(X)J.pendingcb++,pZ.nextTick(($,Y)=>{if(MG(Y))S_($,Y);else Y.pendingcb--},Z,J);else if(MG(J))J.pendingcb++,S_(Z,J)}}}function S_(Z,J){J.pendingcb--,J.finished=!0;let X=J[eX].splice(0);for(let $=0;$<X.length;$++)X[$]();if(Z.emit("finish"),J.autoDestroy){let $=Z._readableState;if(!$||$.autoDestroy&&($.endEmitted||$.readable===!1))Z.destroy()}}$o0(M1.prototype,{closed:{__proto__:null,get(){return this._writableState?this._writableState.closed:!1}},destroyed:{__proto__:null,get(){return this._writableState?this._writableState.destroyed:!1},set(Z){if(this._writableState)this._writableState.destroyed=Z}},writable:{__proto__:null,get(){let Z=this._writableState;return!!Z&&Z.writable!==!1&&!Z.destroyed&&!Z.errored&&!Z.ending&&!Z.ended},set(Z){if(this._writableState)this._writableState.writable=!!Z}},writableFinished:{__proto__:null,get(){return this._writableState?this._writableState.finished:!1}},writableObjectMode:{__proto__:null,get(){return this._writableState?this._writableState.objectMode:!1}},writableBuffer:{__proto__:null,get(){return this._writableState&&this._writableState.getBuffer()}},writableEnded:{__proto__:null,get(){return this._writableState?this._writableState.ending:!1}},writableNeedDrain:{__proto__:null,get(){let Z=this._writableState;if(!Z)return!1;return!Z.destroyed&&!Z.ending&&Z.needDrain}},writableHighWaterMark:{__proto__:null,get(){return this._writableState&&this._writableState.highWaterMark}},writableCorked:{__proto__:null,get(){return this._writableState?this._writableState.corked:0}},writableLength:{__proto__:null,get(){return this._writableState&&this._writableState.length}},errored:{__proto__:null,enumerable:!1,get(){return this._writableState?this._writableState.errored:null}},writableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._writableState.writable!==!1&&(this._writableState.destroyed||this._writableState.errored)&&!this._writableState.finished)}}});var Ao0=TG.destroy;M1.prototype.destroy=function(Z,J){let X=this._writableState;if(!X.destroyed&&(X.bufferedIndex<X.buffered.length||X[eX].length))pZ.nextTick(x_,X);return Ao0.call(this,Z,J),this};M1.prototype._undestroy=TG.undestroy;M1.prototype._destroy=function(Z,J){J(Z)};M1.prototype[Ko0.captureRejectionSymbol]=function(Z){this.destroy(Z)};var y_;function L60(){if(y_===void 0)y_={};return y_}M1.fromWeb=function(Z,J){return L60().newStreamWritableFromWritableStream(Z,J)};M1.toWeb=function(Z){return L60().newWritableStreamFromStreamWritable(Z)}});var y60=L((aR1,I60)=>{var f_=q7(),To0=N("buffer"),{isReadable:qo0,isWritable:Co0,isIterable:_60,isNodeStream:No0,isReadableNodeStream:O60,isWritableNodeStream:w60,isDuplexNodeStream:Ro0,isReadableStream:j60,isWritableStream:M60}=U5(),A60=F9(),{AbortError:P60,codes:{ERR_INVALID_ARG_TYPE:Po0,ERR_INVALID_RETURN_VALUE:T60}}=T4(),{destroyer:J$}=uZ(),Eo0=_5(),E60=b3(),Io0=qG(),{createDeferredPromise:q60}=b4(),C60=A_(),N60=globalThis.Blob||To0.Blob,yo0=typeof N60<"u"?function(J){return J instanceof N60}:function(J){return!1},So0=globalThis.AbortController||N("abort-controller").AbortController,{FunctionPrototypeCall:R60}=F1();class iZ extends Eo0{constructor(Z){super(Z);if((Z===null||Z===void 0?void 0:Z.readable)===!1)this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0;if((Z===null||Z===void 0?void 0:Z.writable)===!1)this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0}}I60.exports=function Z(J,X){if(Ro0(J))return J;if(O60(J))return Z$({readable:J});if(w60(J))return Z$({writable:J});if(No0(J))return Z$({writable:!1,readable:!1});if(j60(J))return Z$({readable:E60.fromWeb(J)});if(M60(J))return Z$({writable:Io0.fromWeb(J)});if(typeof J==="function"){let{value:Y,write:Q,final:W,destroy:K}=ko0(J);if(_60(Y))return C60(iZ,Y,{objectMode:!0,write:Q,final:W,destroy:K});let z=Y===null||Y===void 0?void 0:Y.then;if(typeof z==="function"){let G,H=R60(z,Y,(V)=>{if(V!=null)throw new T60("nully","body",V)},(V)=>{J$(G,V)});return G=new iZ({objectMode:!0,readable:!1,write:Q,final(V){W(async()=>{try{await H,f_.nextTick(V,null)}catch(F){f_.nextTick(V,F)}})},destroy:K})}throw new T60("Iterable, AsyncIterable or AsyncFunction",X,Y)}if(yo0(J))return Z(J.arrayBuffer());if(_60(J))return C60(iZ,J,{objectMode:!0,writable:!1});if(j60(J===null||J===void 0?void 0:J.readable)&&M60(J===null||J===void 0?void 0:J.writable))return iZ.fromWeb(J);if(typeof(J===null||J===void 0?void 0:J.writable)==="object"||typeof(J===null||J===void 0?void 0:J.readable)==="object"){let Y=J!==null&&J!==void 0&&J.readable?O60(J===null||J===void 0?void 0:J.readable)?J===null||J===void 0?void 0:J.readable:Z(J.readable):void 0,Q=J!==null&&J!==void 0&&J.writable?w60(J===null||J===void 0?void 0:J.writable)?J===null||J===void 0?void 0:J.writable:Z(J.writable):void 0;return Z$({readable:Y,writable:Q})}let $=J===null||J===void 0?void 0:J.then;if(typeof $==="function"){let Y;return R60($,J,(Q)=>{if(Q!=null)Y.push(Q);Y.push(null)},(Q)=>{J$(Y,Q)}),Y=new iZ({objectMode:!0,writable:!1,read(){}})}throw new Po0(X,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],J)};function ko0(Z){let{promise:J,resolve:X}=q60(),$=new So0,Y=$.signal;return{value:Z(async function*(){while(!0){let W=J;J=null;let{chunk:K,done:z,cb:G}=await W;if(f_.nextTick(G),z)return;if(Y.aborted)throw new P60(void 0,{cause:Y.reason});({promise:J,resolve:X}=q60()),yield K}}(),{signal:Y}),write(W,K,z){let G=X;X=null,G({chunk:W,done:!1,cb:z})},final(W){let K=X;X=null,K({done:!0,cb:W})},destroy(W,K){$.abort(),K(W)}}}function Z$(Z){let J=Z.readable&&typeof Z.readable.read!=="function"?E60.wrap(Z.readable):Z.readable,X=Z.writable,$=!!qo0(J),Y=!!Co0(X),Q,W,K,z,G;function H(V){let F=z;if(z=null,F)F(V);else if(V)G.destroy(V)}if(G=new iZ({readableObjectMode:!!(J!==null&&J!==void 0&&J.readableObjectMode),writableObjectMode:!!(X!==null&&X!==void 0&&X.writableObjectMode),readable:$,writable:Y}),Y)A60(X,(V)=>{if(Y=!1,V)J$(J,V);H(V)}),G._write=function(V,F,B){if(X.write(V,F))B();else Q=B},G._final=function(V){X.end(),W=V},X.on("drain",function(){if(Q){let V=Q;Q=null,V()}}),X.on("finish",function(){if(W){let V=W;W=null,V()}});if($)A60(J,(V)=>{if($=!1,V)J$(J,V);H(V)}),J.on("readable",function(){if(K){let V=K;K=null,V()}}),J.on("end",function(){G.push(null)}),G._read=function(){while(!0){let V=J.read();if(V===null){K=G._read;return}if(!G.push(V))return}};return G._destroy=function(V,F){if(!V&&z!==null)V=new P60;if(K=null,Q=null,W=null,z===null)F(V);else z=F,J$(X,V),J$(J,V)},G}});var _5=L((rR1,x60)=>{var{ObjectDefineProperties:xo0,ObjectGetOwnPropertyDescriptor:B9,ObjectKeys:vo0,ObjectSetPrototypeOf:S60}=F1();x60.exports=f8;var m_=b3(),X8=qG();S60(f8.prototype,m_.prototype);S60(f8,m_);{let Z=vo0(X8.prototype);for(let J=0;J<Z.length;J++){let X=Z[J];if(!f8.prototype[X])f8.prototype[X]=X8.prototype[X]}}function f8(Z){if(!(this instanceof f8))return new f8(Z);if(m_.call(this,Z),X8.call(this,Z),Z){if(this.allowHalfOpen=Z.allowHalfOpen!==!1,Z.readable===!1)this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0;if(Z.writable===!1)this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0}else this.allowHalfOpen=!0}xo0(f8.prototype,{writable:{__proto__:null,...B9(X8.prototype,"writable")},writableHighWaterMark:{__proto__:null,...B9(X8.prototype,"writableHighWaterMark")},writableObjectMode:{__proto__:null,...B9(X8.prototype,"writableObjectMode")},writableBuffer:{__proto__:null,...B9(X8.prototype,"writableBuffer")},writableLength:{__proto__:null,...B9(X8.prototype,"writableLength")},writableFinished:{__proto__:null,...B9(X8.prototype,"writableFinished")},writableCorked:{__proto__:null,...B9(X8.prototype,"writableCorked")},writableEnded:{__proto__:null,...B9(X8.prototype,"writableEnded")},writableNeedDrain:{__proto__:null,...B9(X8.prototype,"writableNeedDrain")},destroyed:{__proto__:null,get(){if(this._readableState===void 0||this._writableState===void 0)return!1;return this._readableState.destroyed&&this._writableState.destroyed},set(Z){if(this._readableState&&this._writableState)this._readableState.destroyed=Z,this._writableState.destroyed=Z}}});var b_;function k60(){if(b_===void 0)b_={};return b_}f8.fromWeb=function(Z,J){return k60().newStreamDuplexFromReadableWritablePair(Z,J)};f8.toWeb=function(Z){return k60().newReadableWritablePairFromDuplex(Z)};var g_;f8.from=function(Z){if(!g_)g_=y60();return g_(Z,"body")}});var c_=L((sR1,h60)=>{var{ObjectSetPrototypeOf:v60,Symbol:ho0}=F1();h60.exports=U9;var{ERR_METHOD_NOT_IMPLEMENTED:fo0}=T4().codes,u_=_5(),{getHighWaterMark:bo0}=v3();v60(U9.prototype,u_.prototype);v60(U9,u_);var u3=ho0("kCallback");function U9(Z){if(!(this instanceof U9))return new U9(Z);let J=Z?bo0(this,Z,"readableHighWaterMark",!0):null;if(J===0)Z={...Z,highWaterMark:null,readableHighWaterMark:J,writableHighWaterMark:Z.writableHighWaterMark||0};if(u_.call(this,Z),this._readableState.sync=!1,this[u3]=null,Z){if(typeof Z.transform==="function")this._transform=Z.transform;if(typeof Z.flush==="function")this._flush=Z.flush}this.on("prefinish",go0)}function d_(Z){if(typeof this._flush==="function"&&!this.destroyed)this._flush((J,X)=>{if(J){if(Z)Z(J);else this.destroy(J);return}if(X!=null)this.push(X);if(this.push(null),Z)Z()});else if(this.push(null),Z)Z()}function go0(){if(this._final!==d_)d_.call(this)}U9.prototype._final=d_;U9.prototype._transform=function(Z,J,X){throw new fo0("_transform()")};U9.prototype._write=function(Z,J,X){let $=this._readableState,Y=this._writableState,Q=$.length;this._transform(Z,J,(W,K)=>{if(W){X(W);return}if(K!=null)this.push(K);if(Y.ended||Q===$.length||$.length<$.highWaterMark)X();else this[u3]=X})};U9.prototype._read=function(){if(this[u3]){let Z=this[u3];this[u3]=null,Z()}}});var p_=L((tR1,b60)=>{var{ObjectSetPrototypeOf:f60}=F1();b60.exports=X$;var l_=c_();f60(X$.prototype,l_.prototype);f60(X$,l_);function X$(Z){if(!(this instanceof X$))return new X$(Z);l_.call(this,Z)}X$.prototype._transform=function(Z,J,X){X(null,Z)}});var PG=L((eR1,c60)=>{var c3=q7(),{ArrayIsArray:mo0,Promise:do0,SymbolAsyncIterator:uo0,SymbolDispose:co0}=F1(),RG=F9(),{once:lo0}=b4(),po0=uZ(),g60=_5(),{aggregateTwoErrors:io0,codes:{ERR_INVALID_ARG_TYPE:ZO,ERR_INVALID_RETURN_VALUE:i_,ERR_MISSING_ARGS:no0,ERR_STREAM_DESTROYED:oo0,ERR_STREAM_PREMATURE_CLOSE:ao0},AbortError:ro0}=T4(),{validateFunction:so0,validateAbortSignal:to0}=nX(),{isIterable:nZ,isReadable:n_,isReadableNodeStream:NG,isNodeStream:m60,isTransformStream:$$,isWebStream:eo0,isReadableStream:o_,isReadableFinished:Za0}=U5(),Ja0=globalThis.AbortController||N("abort-controller").AbortController,a_,r_,s_;function d60(Z,J,X){let $=!1;Z.on("close",()=>{$=!0});let Y=RG(Z,{readable:J,writable:X},(Q)=>{$=!Q});return{destroy:(Q)=>{if($)return;$=!0,po0.destroyer(Z,Q||new oo0("pipe"))},cleanup:Y}}function Xa0(Z){return so0(Z[Z.length-1],"streams[stream.length - 1]"),Z.pop()}function t_(Z){if(nZ(Z))return Z;else if(NG(Z))return $a0(Z);throw new ZO("val",["Readable","Iterable","AsyncIterable"],Z)}async function*$a0(Z){if(!r_)r_=b3();yield*r_.prototype[uo0].call(Z)}async function CG(Z,J,X,{end:$}){let Y,Q=null,W=(G)=>{if(G)Y=G;if(Q){let H=Q;Q=null,H()}},K=()=>new do0((G,H)=>{if(Y)H(Y);else Q=()=>{if(Y)H(Y);else G()}});J.on("drain",W);let z=RG(J,{readable:!1},W);try{if(J.writableNeedDrain)await K();for await(let G of Z)if(!J.write(G))await K();if($)J.end(),await K();X()}catch(G){X(Y!==G?io0(Y,G):G)}finally{z(),J.off("drain",W)}}async function e_(Z,J,X,{end:$}){if($$(J))J=J.writable;let Y=J.getWriter();try{for await(let Q of Z)await Y.ready,Y.write(Q).catch(()=>{});if(await Y.ready,$)await Y.close();X()}catch(Q){try{await Y.abort(Q),X(Q)}catch(W){X(W)}}}function Ya0(...Z){return u60(Z,lo0(Xa0(Z)))}function u60(Z,J,X){if(Z.length===1&&mo0(Z[0]))Z=Z[0];if(Z.length<2)throw new no0("streams");let $=new Ja0,Y=$.signal,Q=X===null||X===void 0?void 0:X.signal,W=[];to0(Q,"options.signal");function K(){U(new ro0)}s_=s_||b4().addAbortListener;let z;if(Q)z=s_(Q,K);let G,H,V=[],F=0;function B(j){U(j,--F===0)}function U(j,q){var R;if(j&&(!G||G.code==="ERR_STREAM_PREMATURE_CLOSE"))G=j;if(!G&&!q)return;while(V.length)V.shift()(G);if((R=z)===null||R===void 0||R[co0](),$.abort(),q){if(!G)W.forEach((T)=>T());c3.nextTick(J,G,H)}}let D;for(let j=0;j<Z.length;j++){let q=Z[j],R=j<Z.length-1,T=j>0,y=R||(X===null||X===void 0?void 0:X.end)!==!1,i=j===Z.length-1;if(m60(q)){let s=function(O0){if(O0&&O0.name!=="AbortError"&&O0.code!=="ERR_STREAM_PREMATURE_CLOSE")B(O0)};var w=s;if(y){let{destroy:O0,cleanup:d0}=d60(q,R,T);if(V.push(O0),n_(q)&&i)W.push(d0)}if(q.on("error",s),n_(q)&&i)W.push(()=>{q.removeListener("error",s)})}if(j===0)if(typeof q==="function"){if(D=q({signal:Y}),!nZ(D))throw new i_("Iterable, AsyncIterable or Stream","source",D)}else if(nZ(q)||NG(q)||$$(q))D=q;else D=g60.from(q);else if(typeof q==="function"){if($$(D)){var _;D=t_((_=D)===null||_===void 0?void 0:_.readable)}else D=t_(D);if(D=q(D,{signal:Y}),R){if(!nZ(D,!0))throw new i_("AsyncIterable",`transform[${j-1}]`,D)}else{var O;if(!a_)a_=p_();let s=new a_({objectMode:!0}),O0=(O=D)===null||O===void 0?void 0:O.then;if(typeof O0==="function")F++,O0.call(D,(G0)=>{if(H=G0,G0!=null)s.write(G0);if(y)s.end();c3.nextTick(B)},(G0)=>{s.destroy(G0),c3.nextTick(B,G0)});else if(nZ(D,!0))F++,CG(D,s,B,{end:y});else if(o_(D)||$$(D)){let G0=D.readable||D;F++,CG(G0,s,B,{end:y})}else throw new i_("AsyncIterable or Promise","destination",D);D=s;let{destroy:d0,cleanup:b0}=d60(D,!1,!0);if(V.push(d0),i)W.push(b0)}}else if(m60(q)){if(NG(D)){F+=2;let s=Qa0(D,q,B,{end:y});if(n_(q)&&i)W.push(s)}else if($$(D)||o_(D)){let s=D.readable||D;F++,CG(s,q,B,{end:y})}else if(nZ(D))F++,CG(D,q,B,{end:y});else throw new ZO("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],D);D=q}else if(eo0(q)){if(NG(D))F++,e_(t_(D),q,B,{end:y});else if(o_(D)||nZ(D))F++,e_(D,q,B,{end:y});else if($$(D))F++,e_(D.readable,q,B,{end:y});else throw new ZO("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],D);D=q}else D=g60.from(q)}if(Y!==null&&Y!==void 0&&Y.aborted||Q!==null&&Q!==void 0&&Q.aborted)c3.nextTick(K);return D}function Qa0(Z,J,X,{end:$}){let Y=!1;if(J.on("close",()=>{if(!Y)X(new ao0)}),Z.pipe(J,{end:!1}),$){let W=function(){Y=!0,J.end()};var Q=W;if(Za0(Z))c3.nextTick(W);else Z.once("end",W)}else X();return RG(Z,{readable:!0,writable:!1},(W)=>{let K=Z._readableState;if(W&&W.code==="ERR_STREAM_PREMATURE_CLOSE"&&K&&K.ended&&!K.errored&&!K.errorEmitted)Z.once("end",X).once("error",X);else X(W)}),RG(J,{readable:!1,writable:!0},X)}c60.exports={pipelineImpl:u60,pipeline:Ya0}});var XO=L((ZP1,a60)=>{var{pipeline:Wa0}=PG(),EG=_5(),{destroyer:Ka0}=uZ(),{isNodeStream:IG,isReadable:l60,isWritable:p60,isWebStream:JO,isTransformStream:oZ,isWritableStream:i60,isReadableStream:n60}=U5(),{AbortError:za0,codes:{ERR_INVALID_ARG_VALUE:o60,ERR_MISSING_ARGS:Ga0}}=T4(),Ha0=F9();a60.exports=function(...J){if(J.length===0)throw new Ga0("streams");if(J.length===1)return EG.from(J[0]);let X=[...J];if(typeof J[0]==="function")J[0]=EG.from(J[0]);if(typeof J[J.length-1]==="function"){let B=J.length-1;J[B]=EG.from(J[B])}for(let B=0;B<J.length;++B){if(!IG(J[B])&&!JO(J[B]))continue;if(B<J.length-1&&!(l60(J[B])||n60(J[B])||oZ(J[B])))throw new o60(`streams[${B}]`,X[B],"must be readable");if(B>0&&!(p60(J[B])||i60(J[B])||oZ(J[B])))throw new o60(`streams[${B}]`,X[B],"must be writable")}let $,Y,Q,W,K;function z(B){let U=W;if(W=null,U)U(B);else if(B)K.destroy(B);else if(!F&&!V)K.destroy()}let G=J[0],H=Wa0(J,z),V=!!(p60(G)||i60(G)||oZ(G)),F=!!(l60(H)||n60(H)||oZ(H));if(K=new EG({writableObjectMode:!!(G!==null&&G!==void 0&&G.writableObjectMode),readableObjectMode:!!(H!==null&&H!==void 0&&H.readableObjectMode),writable:V,readable:F}),V){if(IG(G))K._write=function(U,D,_){if(G.write(U,D))_();else $=_},K._final=function(U){G.end(),Y=U},G.on("drain",function(){if($){let U=$;$=null,U()}});else if(JO(G)){let D=(oZ(G)?G.writable:G).getWriter();K._write=async function(_,O,w){try{await D.ready,D.write(_).catch(()=>{}),w()}catch(j){w(j)}},K._final=async function(_){try{await D.ready,D.close().catch(()=>{}),Y=_}catch(O){_(O)}}}let B=oZ(H)?H.readable:H;Ha0(B,()=>{if(Y){let U=Y;Y=null,U()}})}if(F){if(IG(H))H.on("readable",function(){if(Q){let B=Q;Q=null,B()}}),H.on("end",function(){K.push(null)}),K._read=function(){while(!0){let B=H.read();if(B===null){Q=K._read;return}if(!K.push(B))return}};else if(JO(H)){let U=(oZ(H)?H.readable:H).getReader();K._read=async function(){while(!0)try{let{value:D,done:_}=await U.read();if(!K.push(D))return;if(_){K.push(null);return}}catch{return}}}}return K._destroy=function(B,U){if(!B&&W!==null)B=new za0;if(Q=null,$=null,Y=null,W===null)U(B);else if(W=U,IG(H))Ka0(H,B)},K}});var W80=L((ba0,YO)=>{var Va0=globalThis.AbortController||N("abort-controller").AbortController,{codes:{ERR_INVALID_ARG_VALUE:Fa0,ERR_INVALID_ARG_TYPE:l3,ERR_MISSING_ARGS:Ba0,ERR_OUT_OF_RANGE:Ua0},AbortError:O5}=T4(),{validateAbortSignal:aZ,validateInteger:r60,validateObject:rZ}=nX(),La0=F1().Symbol("kWeak"),Da0=F1().Symbol("kResistStopPropagation"),{finished:_a0}=F9(),Oa0=XO(),{addAbortSignalNoValidate:wa0}=x3(),{isWritable:ja0,isNodeStream:Ma0}=U5(),{deprecate:Aa0}=b4(),{ArrayPrototypePush:Ta0,Boolean:qa0,MathFloor:s60,Number:Ca0,NumberIsNaN:Na0,Promise:t60,PromiseReject:e60,PromiseResolve:Ra0,PromisePrototypeThen:Z80,Symbol:X80}=F1(),yG=X80("kEmpty"),J80=X80("kEof");function Pa0(Z,J){if(J!=null)rZ(J,"options");if((J===null||J===void 0?void 0:J.signal)!=null)aZ(J.signal,"options.signal");if(Ma0(Z)&&!ja0(Z))throw new Fa0("stream",Z,"must be writable");let X=Oa0(this,Z);if(J!==null&&J!==void 0&&J.signal)wa0(J.signal,X);return X}function SG(Z,J){if(typeof Z!=="function")throw new l3("fn",["Function","AsyncFunction"],Z);if(J!=null)rZ(J,"options");if((J===null||J===void 0?void 0:J.signal)!=null)aZ(J.signal,"options.signal");let X=1;if((J===null||J===void 0?void 0:J.concurrency)!=null)X=s60(J.concurrency);let $=X-1;if((J===null||J===void 0?void 0:J.highWaterMark)!=null)$=s60(J.highWaterMark);return r60(X,"options.concurrency",1),r60($,"options.highWaterMark",0),$+=X,async function*(){let Q=b4().AbortSignalAny([J===null||J===void 0?void 0:J.signal].filter(qa0)),W=this,K=[],z={signal:Q},G,H,V=!1,F=0;function B(){V=!0,U()}function U(){F-=1,D()}function D(){if(H&&!V&&F<X&&K.length<$)H(),H=null}async function _(){try{for await(let O of W){if(V)return;if(Q.aborted)throw new O5;try{if(O=Z(O,z),O===yG)continue;O=Ra0(O)}catch(w){O=e60(w)}if(F+=1,Z80(O,U,B),K.push(O),G)G(),G=null;if(!V&&(K.length>=$||F>=X))await new t60((w)=>{H=w})}K.push(J80)}catch(O){let w=e60(O);Z80(w,U,B),K.push(w)}finally{if(V=!0,G)G(),G=null}}_();try{while(!0){while(K.length>0){let O=await K[0];if(O===J80)return;if(Q.aborted)throw new O5;if(O!==yG)yield O;K.shift(),D()}await new t60((O)=>{G=O})}}finally{if(V=!0,H)H(),H=null}}.call(this)}function Ea0(Z=void 0){if(Z!=null)rZ(Z,"options");if((Z===null||Z===void 0?void 0:Z.signal)!=null)aZ(Z.signal,"options.signal");return async function*(){let X=0;for await(let Y of this){var $;if(Z!==null&&Z!==void 0&&($=Z.signal)!==null&&$!==void 0&&$.aborted)throw new O5({cause:Z.signal.reason});yield[X++,Y]}}.call(this)}async function $80(Z,J=void 0){for await(let X of $O.call(this,Z,J))return!0;return!1}async function Ia0(Z,J=void 0){if(typeof Z!=="function")throw new l3("fn",["Function","AsyncFunction"],Z);return!await $80.call(this,async(...X)=>{return!await Z(...X)},J)}async function ya0(Z,J){for await(let X of $O.call(this,Z,J))return X;return}async function Sa0(Z,J){if(typeof Z!=="function")throw new l3("fn",["Function","AsyncFunction"],Z);async function X($,Y){return await Z($,Y),yG}for await(let $ of SG.call(this,X,J));}function $O(Z,J){if(typeof Z!=="function")throw new l3("fn",["Function","AsyncFunction"],Z);async function X($,Y){if(await Z($,Y))return $;return yG}return SG.call(this,X,J)}class Y80 extends Ba0{constructor(){super("reduce");this.message="Reduce of an empty stream requires an initial value"}}async function ka0(Z,J,X){var $;if(typeof Z!=="function")throw new l3("reducer",["Function","AsyncFunction"],Z);if(X!=null)rZ(X,"options");if((X===null||X===void 0?void 0:X.signal)!=null)aZ(X.signal,"options.signal");let Y=arguments.length>1;if(X!==null&&X!==void 0&&($=X.signal)!==null&&$!==void 0&&$.aborted){let G=new O5(void 0,{cause:X.signal.reason});throw this.once("error",()=>{}),await _a0(this.destroy(G)),G}let Q=new Va0,W=Q.signal;if(X!==null&&X!==void 0&&X.signal){let G={once:!0,[La0]:this,[Da0]:!0};X.signal.addEventListener("abort",()=>Q.abort(),G)}let K=!1;try{for await(let G of this){var z;if(K=!0,X!==null&&X!==void 0&&(z=X.signal)!==null&&z!==void 0&&z.aborted)throw new O5;if(!Y)J=G,Y=!0;else J=await Z(J,G,{signal:W})}if(!K&&!Y)throw new Y80}finally{Q.abort()}return J}async function xa0(Z){if(Z!=null)rZ(Z,"options");if((Z===null||Z===void 0?void 0:Z.signal)!=null)aZ(Z.signal,"options.signal");let J=[];for await(let $ of this){var X;if(Z!==null&&Z!==void 0&&(X=Z.signal)!==null&&X!==void 0&&X.aborted)throw new O5(void 0,{cause:Z.signal.reason});Ta0(J,$)}return J}function va0(Z,J){let X=SG.call(this,Z,J);return async function*(){for await(let Y of X)yield*Y}.call(this)}function Q80(Z){if(Z=Ca0(Z),Na0(Z))return 0;if(Z<0)throw new Ua0("number",">= 0",Z);return Z}function ha0(Z,J=void 0){if(J!=null)rZ(J,"options");if((J===null||J===void 0?void 0:J.signal)!=null)aZ(J.signal,"options.signal");return Z=Q80(Z),async function*(){var $;if(J!==null&&J!==void 0&&($=J.signal)!==null&&$!==void 0&&$.aborted)throw new O5;for await(let Q of this){var Y;if(J!==null&&J!==void 0&&(Y=J.signal)!==null&&Y!==void 0&&Y.aborted)throw new O5;if(Z--<=0)yield Q}}.call(this)}function fa0(Z,J=void 0){if(J!=null)rZ(J,"options");if((J===null||J===void 0?void 0:J.signal)!=null)aZ(J.signal,"options.signal");return Z=Q80(Z),async function*(){var $;if(J!==null&&J!==void 0&&($=J.signal)!==null&&$!==void 0&&$.aborted)throw new O5;for await(let Q of this){var Y;if(J!==null&&J!==void 0&&(Y=J.signal)!==null&&Y!==void 0&&Y.aborted)throw new O5;if(Z-- >0)yield Q;if(Z<=0)return}}.call(this)}ba0.streamReturningOperators={asIndexedPairs:Aa0(Ea0,"readable.asIndexedPairs will be removed in a future version."),drop:ha0,filter:$O,flatMap:va0,map:SG,take:fa0,compose:Pa0};ba0.promiseReturningOperators={every:Ia0,forEach:Sa0,reduce:ka0,toArray:xa0,some:$80,find:ya0}});var QO=L((JP1,K80)=>{var{ArrayPrototypePop:da0,Promise:ua0}=F1(),{isIterable:ca0,isNodeStream:la0,isWebStream:pa0}=U5(),{pipelineImpl:ia0}=PG(),{finished:na0}=F9();WO();function oa0(...Z){return new ua0((J,X)=>{let $,Y,Q=Z[Z.length-1];if(Q&&typeof Q==="object"&&!la0(Q)&&!ca0(Q)&&!pa0(Q)){let W=da0(Z);$=W.signal,Y=W.end}ia0(Z,(W,K)=>{if(W)X(W);else J(K)},{signal:$,end:Y})})}K80.exports={finished:na0,pipeline:oa0}});var WO=L((XP1,D80)=>{var{Buffer:aa0}=N("buffer"),{ObjectDefineProperty:L9,ObjectKeys:H80,ReflectApply:V80}=F1(),{promisify:{custom:F80}}=b4(),{streamReturningOperators:z80,promiseReturningOperators:G80}=W80(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:B80}}=T4(),ra0=XO(),{setDefaultHighWaterMark:sa0,getDefaultHighWaterMark:ta0}=v3(),{pipeline:U80}=PG(),{destroyer:ea0}=uZ(),L80=F9(),KO=QO(),p3=U5(),Q1=D80.exports=VG().Stream;Q1.isDestroyed=p3.isDestroyed;Q1.isDisturbed=p3.isDisturbed;Q1.isErrored=p3.isErrored;Q1.isReadable=p3.isReadable;Q1.isWritable=p3.isWritable;Q1.Readable=b3();for(let Z of H80(z80)){let X=function(...$){if(new.target)throw B80();return Q1.Readable.from(V80(J,this,$))},J=z80[Z];L9(X,"name",{__proto__:null,value:J.name}),L9(X,"length",{__proto__:null,value:J.length}),L9(Q1.Readable.prototype,Z,{__proto__:null,value:X,enumerable:!1,configurable:!0,writable:!0})}for(let Z of H80(G80)){let X=function(...$){if(new.target)throw B80();return V80(J,this,$)},J=G80[Z];L9(X,"name",{__proto__:null,value:J.name}),L9(X,"length",{__proto__:null,value:J.length}),L9(Q1.Readable.prototype,Z,{__proto__:null,value:X,enumerable:!1,configurable:!0,writable:!0})}Q1.Writable=qG();Q1.Duplex=_5();Q1.Transform=c_();Q1.PassThrough=p_();Q1.pipeline=U80;var{addAbortSignal:Zr0}=x3();Q1.addAbortSignal=Zr0;Q1.finished=L80;Q1.destroy=ea0;Q1.compose=ra0;Q1.setDefaultHighWaterMark=sa0;Q1.getDefaultHighWaterMark=ta0;L9(Q1,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return KO}});L9(U80,F80,{__proto__:null,enumerable:!0,get(){return KO.pipeline}});L9(L80,F80,{__proto__:null,enumerable:!0,get(){return KO.finished}});Q1.Stream=Q1;Q1._isUint8Array=function(J){return J instanceof Uint8Array};Q1._uint8ArrayToBuffer=function(J){return aa0.from(J.buffer,J.byteOffset,J.byteLength)}});var R7=L(($P1,P0)=>{var o1=N("stream");if(o1&&process.env.READABLE_STREAM==="disable"){let Z=o1.promises;P0.exports._uint8ArrayToBuffer=o1._uint8ArrayToBuffer,P0.exports._isUint8Array=o1._isUint8Array,P0.exports.isDisturbed=o1.isDisturbed,P0.exports.isErrored=o1.isErrored,P0.exports.isReadable=o1.isReadable,P0.exports.Readable=o1.Readable,P0.exports.Writable=o1.Writable,P0.exports.Duplex=o1.Duplex,P0.exports.Transform=o1.Transform,P0.exports.PassThrough=o1.PassThrough,P0.exports.addAbortSignal=o1.addAbortSignal,P0.exports.finished=o1.finished,P0.exports.destroy=o1.destroy,P0.exports.pipeline=o1.pipeline,P0.exports.compose=o1.compose,Object.defineProperty(o1,"promises",{configurable:!0,enumerable:!0,get(){return Z}}),P0.exports.Stream=o1.Stream}else{let Z=WO(),J=QO(),X=Z.Readable.destroy;P0.exports=Z.Readable,P0.exports._uint8ArrayToBuffer=Z._uint8ArrayToBuffer,P0.exports._isUint8Array=Z._isUint8Array,P0.exports.isDisturbed=Z.isDisturbed,P0.exports.isErrored=Z.isErrored,P0.exports.isReadable=Z.isReadable,P0.exports.Readable=Z.Readable,P0.exports.Writable=Z.Writable,P0.exports.Duplex=Z.Duplex,P0.exports.Transform=Z.Transform,P0.exports.PassThrough=Z.PassThrough,P0.exports.addAbortSignal=Z.addAbortSignal,P0.exports.finished=Z.finished,P0.exports.destroy=Z.destroy,P0.exports.destroy=X,P0.exports.pipeline=Z.pipeline,P0.exports.compose=Z.compose,Object.defineProperty(Z,"promises",{configurable:!0,enumerable:!0,get(){return J}}),P0.exports.Stream=Z.Stream}P0.exports.default=P0.exports});var _80=L((jP1,zO)=>{if(typeof Object.create==="function")zO.exports=function(J,X){if(X)J.super_=X,J.prototype=Object.create(X.prototype,{constructor:{value:J,enumerable:!1,writable:!0,configurable:!0}})};else zO.exports=function(J,X){if(X){J.super_=X;var $=function(){};$.prototype=X.prototype,J.prototype=new $,J.prototype.constructor=J}}});var O80=L((MP1,GO)=>{try{if(kG=N("util"),typeof kG.inherits!=="function")throw"";GO.exports=kG.inherits}catch(Z){GO.exports=_80()}var kG});var M80=L((AP1,j80)=>{var{Buffer:b8}=N("buffer"),w80=Symbol.for("BufferList");function g0(Z){if(!(this instanceof g0))return new g0(Z);g0._init.call(this,Z)}g0._init=function(J){if(Object.defineProperty(this,w80,{value:!0}),this._bufs=[],this.length=0,J)this.append(J)};g0.prototype._new=function(J){return new g0(J)};g0.prototype._offset=function(J){if(J===0)return[0,0];let X=0;for(let $=0;$<this._bufs.length;$++){let Y=X+this._bufs[$].length;if(J<Y||$===this._bufs.length-1)return[$,J-X];X=Y}};g0.prototype._reverseOffset=function(Z){let J=Z[0],X=Z[1];for(let $=0;$<J;$++)X+=this._bufs[$].length;return X};g0.prototype.getBuffers=function(){return this._bufs};g0.prototype.get=function(J){if(J>this.length||J<0)return;let X=this._offset(J);return this._bufs[X[0]][X[1]]};g0.prototype.slice=function(J,X){if(typeof J==="number"&&J<0)J+=this.length;if(typeof X==="number"&&X<0)X+=this.length;return this.copy(null,0,J,X)};g0.prototype.copy=function(J,X,$,Y){if(typeof $!=="number"||$<0)$=0;if(typeof Y!=="number"||Y>this.length)Y=this.length;if($>=this.length)return J||b8.alloc(0);if(Y<=0)return J||b8.alloc(0);let Q=!!J,W=this._offset($),K=Y-$,z=K,G=Q&&X||0,H=W[1];if($===0&&Y===this.length){if(!Q)return this._bufs.length===1?this._bufs[0]:b8.concat(this._bufs,this.length);for(let V=0;V<this._bufs.length;V++)this._bufs[V].copy(J,G),G+=this._bufs[V].length;return J}if(z<=this._bufs[W[0]].length-H)return Q?this._bufs[W[0]].copy(J,X,H,H+z):this._bufs[W[0]].slice(H,H+z);if(!Q)J=b8.allocUnsafe(K);for(let V=W[0];V<this._bufs.length;V++){let F=this._bufs[V].length-H;if(z>F)this._bufs[V].copy(J,G,H),G+=F;else{this._bufs[V].copy(J,G,H,H+z),G+=F;break}if(z-=F,H)H=0}if(J.length>G)return J.slice(0,G);return J};g0.prototype.shallowSlice=function(J,X){if(J=J||0,X=typeof X!=="number"?this.length:X,J<0)J+=this.length;if(X<0)X+=this.length;if(J===X)return this._new();let $=this._offset(J),Y=this._offset(X),Q=this._bufs.slice($[0],Y[0]+1);if(Y[1]===0)Q.pop();else Q[Q.length-1]=Q[Q.length-1].slice(0,Y[1]);if($[1]!==0)Q[0]=Q[0].slice($[1]);return this._new(Q)};g0.prototype.toString=function(J,X,$){return this.slice(X,$).toString(J)};g0.prototype.consume=function(J){if(J=Math.trunc(J),Number.isNaN(J)||J<=0)return this;while(this._bufs.length)if(J>=this._bufs[0].length)J-=this._bufs[0].length,this.length-=this._bufs[0].length,this._bufs.shift();else{this._bufs[0]=this._bufs[0].slice(J),this.length-=J;break}return this};g0.prototype.duplicate=function(){let J=this._new();for(let X=0;X<this._bufs.length;X++)J.append(this._bufs[X]);return J};g0.prototype.append=function(J){return this._attach(J,g0.prototype._appendBuffer)};g0.prototype.prepend=function(J){return this._attach(J,g0.prototype._prependBuffer,!0)};g0.prototype._attach=function(J,X,$){if(J==null)return this;if(J.buffer)X.call(this,b8.from(J.buffer,J.byteOffset,J.byteLength));else if(Array.isArray(J)){let[Y,Q]=$?[J.length-1,-1]:[0,1];for(let W=Y;W>=0&&W<J.length;W+=Q)this._attach(J[W],X,$)}else if(this._isBufferList(J)){let[Y,Q]=$?[J._bufs.length-1,-1]:[0,1];for(let W=Y;W>=0&&W<J._bufs.length;W+=Q)this._attach(J._bufs[W],X,$)}else{if(typeof J==="number")J=J.toString();X.call(this,b8.from(J))}return this};g0.prototype._appendBuffer=function(J){this._bufs.push(J),this.length+=J.length};g0.prototype._prependBuffer=function(J){this._bufs.unshift(J),this.length+=J.length};g0.prototype.indexOf=function(Z,J,X){if(X===void 0&&typeof J==="string")X=J,J=void 0;if(typeof Z==="function"||Array.isArray(Z))throw TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.');else if(typeof Z==="number")Z=b8.from([Z]);else if(typeof Z==="string")Z=b8.from(Z,X);else if(this._isBufferList(Z))Z=Z.slice();else if(Array.isArray(Z.buffer))Z=b8.from(Z.buffer,Z.byteOffset,Z.byteLength);else if(!b8.isBuffer(Z))Z=b8.from(Z);if(J=Number(J||0),isNaN(J))J=0;if(J<0)J=this.length+J;if(J<0)J=0;if(Z.length===0)return J>this.length?this.length:J;let $=this._offset(J),Y=$[0],Q=$[1];for(;Y<this._bufs.length;Y++){let W=this._bufs[Y];while(Q<W.length)if(W.length-Q>=Z.length){let z=W.indexOf(Z,Q);if(z!==-1)return this._reverseOffset([Y,z]);Q=W.length-Z.length+1}else{let z=this._reverseOffset([Y,Q]);if(this._match(z,Z))return z;Q++}Q=0}return-1};g0.prototype._match=function(Z,J){if(this.length-Z<J.length)return!1;for(let X=0;X<J.length;X++)if(this.get(Z+X)!==J[X])return!1;return!0};(function(){let Z={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readBigInt64BE:8,readBigInt64LE:8,readBigUInt64BE:8,readBigUInt64LE:8,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1,readIntBE:null,readIntLE:null,readUIntBE:null,readUIntLE:null};for(let J in Z)(function(X){if(Z[X]===null)g0.prototype[X]=function($,Y){return this.slice($,$+Y)[X](0,Y)};else g0.prototype[X]=function($=0){return this.slice($,$+Z[X])[X](0)}})(J)})();g0.prototype._isBufferList=function(J){return J instanceof g0||g0.isBufferList(J)};g0.isBufferList=function(J){return J!=null&&J[w80]};j80.exports=g0});var A80=L((TP1,xG)=>{var HO=R7().Duplex,Jr0=O80(),i3=M80();function C4(Z){if(!(this instanceof C4))return new C4(Z);if(typeof Z==="function"){this._callback=Z;let J=function($){if(this._callback)this._callback($),this._callback=null}.bind(this);this.on("pipe",function($){$.on("error",J)}),this.on("unpipe",function($){$.removeListener("error",J)}),Z=null}i3._init.call(this,Z),HO.call(this)}Jr0(C4,HO);Object.assign(C4.prototype,i3.prototype);C4.prototype._new=function(J){return new C4(J)};C4.prototype._write=function(J,X,$){if(this._appendBuffer(J),typeof $==="function")$()};C4.prototype._read=function(J){if(!this.length)return this.push(null);J=Math.min(J,this.length),this.push(this.slice(0,J)),this.consume(J)};C4.prototype.end=function(J){if(HO.prototype.end.call(this,J),this._callback)this._callback(null,this.slice()),this._callback=null};C4.prototype._destroy=function(J,X){this._bufs.length=0,this.length=0,X(J)};C4.prototype._isBufferList=function(J){return J instanceof C4||J instanceof i3||C4.isBufferList(J)};C4.isBufferList=i3.isBufferList;xG.exports=C4;xG.exports.BufferListStream=C4;xG.exports.BufferList=i3});var C80=L((qP1,q80)=>{class T80{constructor(){this.cmd=null,this.retain=!1,this.qos=0,this.dup=!1,this.length=-1,this.topic=null,this.payload=null}}q80.exports=T80});var VO=L((CP1,N80)=>{var b=CP1,{Buffer:K6}=N("buffer");b.types={0:"reserved",1:"connect",2:"connack",3:"publish",4:"puback",5:"pubrec",6:"pubrel",7:"pubcomp",8:"subscribe",9:"suback",10:"unsubscribe",11:"unsuback",12:"pingreq",13:"pingresp",14:"disconnect",15:"auth"};b.requiredHeaderFlags={1:0,2:0,4:0,5:0,6:2,7:0,8:2,9:0,10:2,11:0,12:0,13:0,14:0,15:0};b.requiredHeaderFlagsErrors={};for(let Z in b.requiredHeaderFlags){let J=b.requiredHeaderFlags[Z];b.requiredHeaderFlagsErrors[Z]="Invalid header flag bits, must be 0x"+J.toString(16)+" for "+b.types[Z]+" packet"}b.codes={};for(let Z in b.types){let J=b.types[Z];b.codes[J]=Z}b.CMD_SHIFT=4;b.CMD_MASK=240;b.DUP_MASK=8;b.QOS_MASK=3;b.QOS_SHIFT=1;b.RETAIN_MASK=1;b.VARBYTEINT_MASK=127;b.VARBYTEINT_FIN_MASK=128;b.VARBYTEINT_MAX=268435455;b.SESSIONPRESENT_MASK=1;b.SESSIONPRESENT_HEADER=K6.from([b.SESSIONPRESENT_MASK]);b.CONNACK_HEADER=K6.from([b.codes.connack<<b.CMD_SHIFT]);b.USERNAME_MASK=128;b.PASSWORD_MASK=64;b.WILL_RETAIN_MASK=32;b.WILL_QOS_MASK=24;b.WILL_QOS_SHIFT=3;b.WILL_FLAG_MASK=4;b.CLEAN_SESSION_MASK=2;b.CONNECT_HEADER=K6.from([b.codes.connect<<b.CMD_SHIFT]);b.properties={sessionExpiryInterval:17,willDelayInterval:24,receiveMaximum:33,maximumPacketSize:39,topicAliasMaximum:34,requestResponseInformation:25,requestProblemInformation:23,userProperties:38,authenticationMethod:21,authenticationData:22,payloadFormatIndicator:1,messageExpiryInterval:2,contentType:3,responseTopic:8,correlationData:9,maximumQoS:36,retainAvailable:37,assignedClientIdentifier:18,reasonString:31,wildcardSubscriptionAvailable:40,subscriptionIdentifiersAvailable:41,sharedSubscriptionAvailable:42,serverKeepAlive:19,responseInformation:26,serverReference:28,topicAlias:35,subscriptionIdentifier:11};b.propertiesCodes={};for(let Z in b.properties){let J=b.properties[Z];b.propertiesCodes[J]=Z}b.propertiesTypes={sessionExpiryInterval:"int32",willDelayInterval:"int32",receiveMaximum:"int16",maximumPacketSize:"int32",topicAliasMaximum:"int16",requestResponseInformation:"byte",requestProblemInformation:"byte",userProperties:"pair",authenticationMethod:"string",authenticationData:"binary",payloadFormatIndicator:"byte",messageExpiryInterval:"int32",contentType:"string",responseTopic:"string",correlationData:"binary",maximumQoS:"int8",retainAvailable:"byte",assignedClientIdentifier:"string",reasonString:"string",wildcardSubscriptionAvailable:"byte",subscriptionIdentifiersAvailable:"byte",sharedSubscriptionAvailable:"byte",serverKeepAlive:"int16",responseInformation:"string",serverReference:"string",topicAlias:"int16",subscriptionIdentifier:"var"};function P7(Z){return[0,1,2].map((J)=>{return[0,1].map((X)=>{return[0,1].map(($)=>{let Y=K6.alloc(1);return Y.writeUInt8(b.codes[Z]<<b.CMD_SHIFT|(X?b.DUP_MASK:0)|J<<b.QOS_SHIFT|$,0,!0),Y})})})}b.PUBLISH_HEADER=P7("publish");b.SUBSCRIBE_HEADER=P7("subscribe");b.SUBSCRIBE_OPTIONS_QOS_MASK=3;b.SUBSCRIBE_OPTIONS_NL_MASK=1;b.SUBSCRIBE_OPTIONS_NL_SHIFT=2;b.SUBSCRIBE_OPTIONS_RAP_MASK=1;b.SUBSCRIBE_OPTIONS_RAP_SHIFT=3;b.SUBSCRIBE_OPTIONS_RH_MASK=3;b.SUBSCRIBE_OPTIONS_RH_SHIFT=4;b.SUBSCRIBE_OPTIONS_RH=[0,16,32];b.SUBSCRIBE_OPTIONS_NL=4;b.SUBSCRIBE_OPTIONS_RAP=8;b.SUBSCRIBE_OPTIONS_QOS=[0,1,2];b.UNSUBSCRIBE_HEADER=P7("unsubscribe");b.ACKS={unsuback:P7("unsuback"),puback:P7("puback"),pubcomp:P7("pubcomp"),pubrel:P7("pubrel"),pubrec:P7("pubrec")};b.SUBACK_HEADER=K6.from([b.codes.suback<<b.CMD_SHIFT]);b.VERSION3=K6.from([3]);b.VERSION4=K6.from([4]);b.VERSION5=K6.from([5]);b.VERSION131=K6.from([131]);b.VERSION132=K6.from([132]);b.QOS=[0,1,2].map((Z)=>{return K6.from([Z])});b.EMPTY={pingreq:K6.from([b.codes.pingreq<<4,0]),pingresp:K6.from([b.codes.pingresp<<4,0]),disconnect:K6.from([b.codes.disconnect<<4,0])};b.MQTT5_PUBACK_PUBREC_CODES={0:"Success",16:"No matching subscribers",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",144:"Topic Name invalid",145:"Packet identifier in use",151:"Quota exceeded",153:"Payload format invalid"};b.MQTT5_PUBREL_PUBCOMP_CODES={0:"Success",146:"Packet Identifier not found"};b.MQTT5_SUBACK_CODES={0:"Granted QoS 0",1:"Granted QoS 1",2:"Granted QoS 2",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",143:"Topic Filter invalid",145:"Packet Identifier in use",151:"Quota exceeded",158:"Shared Subscriptions not supported",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"};b.MQTT5_UNSUBACK_CODES={0:"Success",17:"No subscription existed",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",143:"Topic Filter invalid",145:"Packet Identifier in use"};b.MQTT5_DISCONNECT_CODES={0:"Normal disconnection",4:"Disconnect with Will Message",128:"Unspecified error",129:"Malformed Packet",130:"Protocol Error",131:"Implementation specific error",135:"Not authorized",137:"Server busy",139:"Server shutting down",141:"Keep Alive timeout",142:"Session taken over",143:"Topic Filter invalid",144:"Topic Name invalid",147:"Receive Maximum exceeded",148:"Topic Alias invalid",149:"Packet too large",150:"Message rate too high",151:"Quota exceeded",152:"Administrative action",153:"Payload format invalid",154:"Retain not supported",155:"QoS not supported",156:"Use another server",157:"Server moved",158:"Shared Subscriptions not supported",159:"Connection rate exceeded",160:"Maximum connect time",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"};b.MQTT5_AUTH_CODES={0:"Success",24:"Continue authentication",25:"Re-authenticate"}});var E80=L((NP1,P80)=>{var Xr0=A80(),{EventEmitter:$r0}=N("events"),R80=C80(),S0=VO(),F0=h6()("mqtt-packet:parser");class vG extends $r0{constructor(){super();this.parser=this.constructor.parser}static parser(Z){if(!(this instanceof vG))return new vG().parser(Z);return this.settings=Z||{},this._states=["_parseHeader","_parseLength","_parsePayload","_newPacket"],this._resetState(),this}_resetState(){F0("_resetState: resetting packet, error, _list, and _stateCounter"),this.packet=new R80,this.error=null,this._list=Xr0(),this._stateCounter=0}parse(Z){if(this.error)this._resetState();this._list.append(Z),F0("parse: current state: %s",this._states[this._stateCounter]);while((this.packet.length!==-1||this._list.length>0)&&this[this._states[this._stateCounter]]()&&!this.error)if(this._stateCounter++,F0("parse: state complete. _stateCounter is now: %d",this._stateCounter),F0("parse: packet.length: %d, buffer list length: %d",this.packet.length,this._list.length),this._stateCounter>=this._states.length)this._stateCounter=0;return F0("parse: exited while loop. packet: %d, buffer list length: %d",this.packet.length,this._list.length),this._list.length}_parseHeader(){let Z=this._list.readUInt8(0),J=Z>>S0.CMD_SHIFT;this.packet.cmd=S0.types[J];let X=Z&15,$=S0.requiredHeaderFlags[J];if($!=null&&X!==$)return this._emitError(Error(S0.requiredHeaderFlagsErrors[J]));if(this.packet.retain=(Z&S0.RETAIN_MASK)!==0,this.packet.qos=Z>>S0.QOS_SHIFT&S0.QOS_MASK,this.packet.qos>2)return this._emitError(Error("Packet must not have both QoS bits set to 1"));return this.packet.dup=(Z&S0.DUP_MASK)!==0,F0("_parseHeader: packet: %o",this.packet),this._list.consume(1),!0}_parseLength(){let Z=this._parseVarByteNum(!0);if(Z)this.packet.length=Z.value,this._list.consume(Z.bytes);return F0("_parseLength %d",Z.value),!!Z}_parsePayload(){F0("_parsePayload: payload %O",this._list);let Z=!1;if(this.packet.length===0||this._list.length>=this.packet.length){switch(this._pos=0,this.packet.cmd){case"connect":this._parseConnect();break;case"connack":this._parseConnack();break;case"publish":this._parsePublish();break;case"puback":case"pubrec":case"pubrel":case"pubcomp":this._parseConfirmation();break;case"subscribe":this._parseSubscribe();break;case"suback":this._parseSuback();break;case"unsubscribe":this._parseUnsubscribe();break;case"unsuback":this._parseUnsuback();break;case"pingreq":case"pingresp":break;case"disconnect":this._parseDisconnect();break;case"auth":this._parseAuth();break;default:this._emitError(Error("Not supported"))}Z=!0}return F0("_parsePayload complete result: %s",Z),Z}_parseConnect(){F0("_parseConnect");let Z,J,X,$,Y={},Q=this.packet,W=this._parseString();if(W===null)return this._emitError(Error("Cannot parse protocolId"));if(W!=="MQTT"&&W!=="MQIsdp")return this._emitError(Error("Invalid protocolId"));if(Q.protocolId=W,this._pos>=this._list.length)return this._emitError(Error("Packet too short"));if(Q.protocolVersion=this._list.readUInt8(this._pos),Q.protocolVersion>=128)Q.bridgeMode=!0,Q.protocolVersion=Q.protocolVersion-128;if(Q.protocolVersion!==3&&Q.protocolVersion!==4&&Q.protocolVersion!==5)return this._emitError(Error("Invalid protocol version"));if(this._pos++,this._pos>=this._list.length)return this._emitError(Error("Packet too short"));if(this._list.readUInt8(this._pos)&1)return this._emitError(Error("Connect flag bit 0 must be 0, but got 1"));Y.username=this._list.readUInt8(this._pos)&S0.USERNAME_MASK,Y.password=this._list.readUInt8(this._pos)&S0.PASSWORD_MASK,Y.will=this._list.readUInt8(this._pos)&S0.WILL_FLAG_MASK;let K=!!(this._list.readUInt8(this._pos)&S0.WILL_RETAIN_MASK),z=(this._list.readUInt8(this._pos)&S0.WILL_QOS_MASK)>>S0.WILL_QOS_SHIFT;if(Y.will)Q.will={},Q.will.retain=K,Q.will.qos=z;else{if(K)return this._emitError(Error("Will Retain Flag must be set to zero when Will Flag is set to 0"));if(z)return this._emitError(Error("Will QoS must be set to zero when Will Flag is set to 0"))}if(Q.clean=(this._list.readUInt8(this._pos)&S0.CLEAN_SESSION_MASK)!==0,this._pos++,Q.keepalive=this._parseNum(),Q.keepalive===-1)return this._emitError(Error("Packet too short"));if(Q.protocolVersion===5){let H=this._parseProperties();if(Object.getOwnPropertyNames(H).length)Q.properties=H}let G=this._parseString();if(G===null)return this._emitError(Error("Packet too short"));if(Q.clientId=G,F0("_parseConnect: packet.clientId: %s",Q.clientId),Y.will){if(Q.protocolVersion===5){let H=this._parseProperties();if(Object.getOwnPropertyNames(H).length)Q.will.properties=H}if(Z=this._parseString(),Z===null)return this._emitError(Error("Cannot parse will topic"));if(Q.will.topic=Z,F0("_parseConnect: packet.will.topic: %s",Q.will.topic),J=this._parseBuffer(),J===null)return this._emitError(Error("Cannot parse will payload"));Q.will.payload=J,F0("_parseConnect: packet.will.paylaod: %s",Q.will.payload)}if(Y.username){if($=this._parseString(),$===null)return this._emitError(Error("Cannot parse username"));Q.username=$,F0("_parseConnect: packet.username: %s",Q.username)}if(Y.password){if(X=this._parseBuffer(),X===null)return this._emitError(Error("Cannot parse password"));Q.password=X}return this.settings=Q,F0("_parseConnect: complete"),Q}_parseConnack(){F0("_parseConnack");let Z=this.packet;if(this._list.length<1)return null;let J=this._list.readUInt8(this._pos++);if(J>1)return this._emitError(Error("Invalid connack flags, bits 7-1 must be set to 0"));if(Z.sessionPresent=!!(J&S0.SESSIONPRESENT_MASK),this.settings.protocolVersion===5)if(this._list.length>=2)Z.reasonCode=this._list.readUInt8(this._pos++);else Z.reasonCode=0;else{if(this._list.length<2)return null;Z.returnCode=this._list.readUInt8(this._pos++)}if(Z.returnCode===-1||Z.reasonCode===-1)return this._emitError(Error("Cannot parse return code"));if(this.settings.protocolVersion===5){let X=this._parseProperties();if(Object.getOwnPropertyNames(X).length)Z.properties=X}F0("_parseConnack: complete")}_parsePublish(){F0("_parsePublish");let Z=this.packet;if(Z.topic=this._parseString(),Z.topic===null)return this._emitError(Error("Cannot parse topic"));if(Z.qos>0){if(!this._parseMessageId())return}if(this.settings.protocolVersion===5){let J=this._parseProperties();if(Object.getOwnPropertyNames(J).length)Z.properties=J}Z.payload=this._list.slice(this._pos,Z.length),F0("_parsePublish: payload from buffer list: %o",Z.payload)}_parseSubscribe(){F0("_parseSubscribe");let Z=this.packet,J,X,$,Y,Q,W,K;if(Z.subscriptions=[],!this._parseMessageId())return;if(this.settings.protocolVersion===5){let z=this._parseProperties();if(Object.getOwnPropertyNames(z).length)Z.properties=z}if(Z.length<=0)return this._emitError(Error("Malformed subscribe, no payload specified"));while(this._pos<Z.length){if(J=this._parseString(),J===null)return this._emitError(Error("Cannot parse topic"));if(this._pos>=Z.length)return this._emitError(Error("Malformed Subscribe Payload"));if(X=this._parseByte(),this.settings.protocolVersion===5){if(X&192)return this._emitError(Error("Invalid subscribe topic flag bits, bits 7-6 must be 0"))}else if(X&252)return this._emitError(Error("Invalid subscribe topic flag bits, bits 7-2 must be 0"));if($=X&S0.SUBSCRIBE_OPTIONS_QOS_MASK,$>2)return this._emitError(Error("Invalid subscribe QoS, must be <= 2"));if(W=(X>>S0.SUBSCRIBE_OPTIONS_NL_SHIFT&S0.SUBSCRIBE_OPTIONS_NL_MASK)!==0,Q=(X>>S0.SUBSCRIBE_OPTIONS_RAP_SHIFT&S0.SUBSCRIBE_OPTIONS_RAP_MASK)!==0,Y=X>>S0.SUBSCRIBE_OPTIONS_RH_SHIFT&S0.SUBSCRIBE_OPTIONS_RH_MASK,Y>2)return this._emitError(Error("Invalid retain handling, must be <= 2"));if(K={topic:J,qos:$},this.settings.protocolVersion===5)K.nl=W,K.rap=Q,K.rh=Y;else if(this.settings.bridgeMode)K.rh=0,K.rap=!0,K.nl=!0;F0("_parseSubscribe: push subscription `%s` to subscription",K),Z.subscriptions.push(K)}}_parseSuback(){F0("_parseSuback");let Z=this.packet;if(this.packet.granted=[],!this._parseMessageId())return;if(this.settings.protocolVersion===5){let J=this._parseProperties();if(Object.getOwnPropertyNames(J).length)Z.properties=J}if(Z.length<=0)return this._emitError(Error("Malformed suback, no payload specified"));while(this._pos<this.packet.length){let J=this._list.readUInt8(this._pos++);if(this.settings.protocolVersion===5){if(!S0.MQTT5_SUBACK_CODES[J])return this._emitError(Error("Invalid suback code"))}else if(J>2&&J!==128)return this._emitError(Error("Invalid suback QoS, must be 0, 1, 2 or 128"));this.packet.granted.push(J)}}_parseUnsubscribe(){F0("_parseUnsubscribe");let Z=this.packet;if(Z.unsubscriptions=[],!this._parseMessageId())return;if(this.settings.protocolVersion===5){let J=this._parseProperties();if(Object.getOwnPropertyNames(J).length)Z.properties=J}if(Z.length<=0)return this._emitError(Error("Malformed unsubscribe, no payload specified"));while(this._pos<Z.length){let J=this._parseString();if(J===null)return this._emitError(Error("Cannot parse topic"));F0("_parseUnsubscribe: push topic `%s` to unsubscriptions",J),Z.unsubscriptions.push(J)}}_parseUnsuback(){F0("_parseUnsuback");let Z=this.packet;if(!this._parseMessageId())return this._emitError(Error("Cannot parse messageId"));if((this.settings.protocolVersion===3||this.settings.protocolVersion===4)&&Z.length!==2)return this._emitError(Error("Malformed unsuback, payload length must be 2"));if(Z.length<=0)return this._emitError(Error("Malformed unsuback, no payload specified"));if(this.settings.protocolVersion===5){let J=this._parseProperties();if(Object.getOwnPropertyNames(J).length)Z.properties=J;Z.granted=[];while(this._pos<this.packet.length){let X=this._list.readUInt8(this._pos++);if(!S0.MQTT5_UNSUBACK_CODES[X])return this._emitError(Error("Invalid unsuback code"));this.packet.granted.push(X)}}}_parseConfirmation(){F0("_parseConfirmation: packet.cmd: `%s`",this.packet.cmd);let Z=this.packet;if(this._parseMessageId(),this.settings.protocolVersion===5){if(Z.length>2){switch(Z.reasonCode=this._parseByte(),this.packet.cmd){case"puback":case"pubrec":if(!S0.MQTT5_PUBACK_PUBREC_CODES[Z.reasonCode])return this._emitError(Error("Invalid "+this.packet.cmd+" reason code"));break;case"pubrel":case"pubcomp":if(!S0.MQTT5_PUBREL_PUBCOMP_CODES[Z.reasonCode])return this._emitError(Error("Invalid "+this.packet.cmd+" reason code"));break}F0("_parseConfirmation: packet.reasonCode `%d`",Z.reasonCode)}else Z.reasonCode=0;if(Z.length>3){let J=this._parseProperties();if(Object.getOwnPropertyNames(J).length)Z.properties=J}}return!0}_parseDisconnect(){let Z=this.packet;if(F0("_parseDisconnect"),this.settings.protocolVersion===5){if(this._list.length>0){if(Z.reasonCode=this._parseByte(),!S0.MQTT5_DISCONNECT_CODES[Z.reasonCode])this._emitError(Error("Invalid disconnect reason code"))}else Z.reasonCode=0;let J=this._parseProperties();if(Object.getOwnPropertyNames(J).length)Z.properties=J}return F0("_parseDisconnect result: true"),!0}_parseAuth(){F0("_parseAuth");let Z=this.packet;if(this.settings.protocolVersion!==5)return this._emitError(Error("Not supported auth packet for this version MQTT"));if(Z.reasonCode=this._parseByte(),!S0.MQTT5_AUTH_CODES[Z.reasonCode])return this._emitError(Error("Invalid auth reason code"));let J=this._parseProperties();if(Object.getOwnPropertyNames(J).length)Z.properties=J;return F0("_parseAuth: result: true"),!0}_parseMessageId(){let Z=this.packet;if(Z.messageId=this._parseNum(),Z.messageId===null)return this._emitError(Error("Cannot parse messageId")),!1;return F0("_parseMessageId: packet.messageId %d",Z.messageId),!0}_parseString(Z){let J=this._parseNum(),X=J+this._pos;if(J===-1||X>this._list.length||X>this.packet.length)return null;let $=this._list.toString("utf8",this._pos,X);return this._pos+=J,F0("_parseString: result: %s",$),$}_parseStringPair(){return F0("_parseStringPair"),{name:this._parseString(),value:this._parseString()}}_parseBuffer(){let Z=this._parseNum(),J=Z+this._pos;if(Z===-1||J>this._list.length||J>this.packet.length)return null;let X=this._list.slice(this._pos,J);return this._pos+=Z,F0("_parseBuffer: result: %o",X),X}_parseNum(){if(this._list.length-this._pos<2)return-1;let Z=this._list.readUInt16BE(this._pos);return this._pos+=2,F0("_parseNum: result: %s",Z),Z}_parse4ByteNum(){if(this._list.length-this._pos<4)return-1;let Z=this._list.readUInt32BE(this._pos);return this._pos+=4,F0("_parse4ByteNum: result: %s",Z),Z}_parseVarByteNum(Z){F0("_parseVarByteNum");let J=4,X=0,$=1,Y=0,Q=!1,W,K=this._pos?this._pos:0;while(X<J&&K+X<this._list.length){if(W=this._list.readUInt8(K+X++),Y+=$*(W&S0.VARBYTEINT_MASK),$*=128,(W&S0.VARBYTEINT_FIN_MASK)===0){Q=!0;break}if(this._list.length<=X)break}if(!Q&&X===J&&this._list.length>=X)this._emitError(Error("Invalid variable byte integer"));if(K)this._pos+=X;if(Q)if(Z)Q={bytes:X,value:Y};else Q=Y;else Q=!1;return F0("_parseVarByteNum: result: %o",Q),Q}_parseByte(){let Z;if(this._pos<this._list.length)Z=this._list.readUInt8(this._pos),this._pos++;return F0("_parseByte: result: %o",Z),Z}_parseByType(Z){switch(F0("_parseByType: type: %s",Z),Z){case"byte":return this._parseByte()!==0;case"int8":return this._parseByte();case"int16":return this._parseNum();case"int32":return this._parse4ByteNum();case"var":return this._parseVarByteNum();case"string":return this._parseString();case"pair":return this._parseStringPair();case"binary":return this._parseBuffer()}}_parseProperties(){F0("_parseProperties");let Z=this._parseVarByteNum(),X=this._pos+Z,$={};while(this._pos<X){let Y=this._parseByte();if(!Y)return this._emitError(Error("Cannot parse property code type")),!1;let Q=S0.propertiesCodes[Y];if(!Q)return this._emitError(Error("Unknown property")),!1;if(Q==="userProperties"){if(!$[Q])$[Q]=Object.create(null);let W=this._parseByType(S0.propertiesTypes[Q]);if($[Q][W.name])if(Array.isArray($[Q][W.name]))$[Q][W.name].push(W.value);else{let K=$[Q][W.name];$[Q][W.name]=[K],$[Q][W.name].push(W.value)}else $[Q][W.name]=W.value;continue}if($[Q])if(Array.isArray($[Q]))$[Q].push(this._parseByType(S0.propertiesTypes[Q]));else $[Q]=[$[Q]],$[Q].push(this._parseByType(S0.propertiesTypes[Q]));else $[Q]=this._parseByType(S0.propertiesTypes[Q])}return $}_newPacket(){if(F0("_newPacket"),this.packet)this._list.consume(this.packet.length),F0("_newPacket: parser emit packet: packet.cmd: %s, packet.payload: %s, packet.length: %d",this.packet.cmd,this.packet.payload,this.packet.length),this.emit("packet",this.packet);return F0("_newPacket: new packet"),this.packet=new R80,this._pos=0,!0}_emitError(Z){F0("_emitError",Z),this.error=Z,this.emit("error",Z)}}P80.exports=vG});var k80=L((RP1,S80)=>{var{Buffer:n3}=N("buffer"),I80={},Yr0=n3.isBuffer(n3.from([1,2]).subarray(0,1));function y80(Z){let J=n3.allocUnsafe(2);return J.writeUInt8(Z>>8,0),J.writeUInt8(Z&255,1),J}function Qr0(){for(let Z=0;Z<65536;Z++)I80[Z]=y80(Z)}function Wr0(Z){let X=0,$=0,Y=n3.allocUnsafe(4);do{if(X=Z%128|0,Z=Z/128|0,Z>0)X=X|128;Y.writeUInt8(X,$++)}while(Z>0&&$<4);if(Z>0)$=0;return Yr0?Y.subarray(0,$):Y.slice(0,$)}function Kr0(Z){let J=n3.allocUnsafe(4);return J.writeUInt32BE(Z,0),J}S80.exports={cache:I80,generateCache:Qr0,generateNumber:y80,genBufVariableByteInt:Wr0,generate4ByteBuffer:Kr0}});var x80=L((PP1,FO)=>{if(typeof process>"u"||!process.version||process.version.indexOf("v0.")===0||process.version.indexOf("v1.")===0&&process.version.indexOf("v1.8.")!==0)FO.exports={nextTick:zr0};else FO.exports=process;function zr0(Z,J,X,$){if(typeof Z!=="function")throw TypeError('"callback" argument must be a function');var Y=arguments.length,Q,W;switch(Y){case 0:case 1:return process.nextTick(Z);case 2:return process.nextTick(function(){Z.call(null,J)});case 3:return process.nextTick(function(){Z.call(null,J,X)});case 4:return process.nextTick(function(){Z.call(null,J,X,$)});default:Q=Array(Y-1),W=0;while(W<Q.length)Q[W++]=arguments[W];return process.nextTick(function(){Z.apply(null,Q)})}}});var LO=L((EP1,u80)=>{var B0=VO(),{Buffer:z0}=N("buffer"),Gr0=z0.allocUnsafe(0),Hr0=z0.from([0]),o3=k80(),Vr0=x80().nextTick,$8=h6()("mqtt-packet:writeToStream"),hG=o3.cache,Fr0=o3.generateNumber,Br0=o3.generateCache,BO=o3.genBufVariableByteInt,Ur0=o3.generate4ByteBuffer,g4=UO,fG=!0;function m80(Z,J,X){if($8("generate called"),J.cork)J.cork(),Vr0(Lr0,J);if(fG)fG=!1,Br0();switch($8("generate: packet.cmd: %s",Z.cmd),Z.cmd){case"connect":return Dr0(Z,J,X);case"connack":return _r0(Z,J,X);case"publish":return Or0(Z,J,X);case"puback":case"pubrec":case"pubrel":case"pubcomp":return wr0(Z,J,X);case"subscribe":return jr0(Z,J,X);case"suback":return Mr0(Z,J,X);case"unsubscribe":return Ar0(Z,J,X);case"unsuback":return Tr0(Z,J,X);case"pingreq":case"pingresp":return qr0(Z,J,X);case"disconnect":return Cr0(Z,J,X);case"auth":return Nr0(Z,J,X);default:return J.destroy(Error("Unknown command")),!1}}Object.defineProperty(m80,"cacheNumbers",{get(){return g4===UO},set(Z){if(Z){if(!hG||Object.keys(hG).length===0)fG=!0;g4=UO}else fG=!1,g4=Rr0}});function Lr0(Z){Z.uncork()}function Dr0(Z,J,X){let $=Z||{},Y=$.protocolId||"MQTT",Q=$.protocolVersion||4,W=$.will,K=$.clean,z=$.keepalive||0,G=$.clientId||"",H=$.username,V=$.password,F=$.properties;if(K===void 0)K=!0;let B=0;if(!Y||typeof Y!=="string"&&!z0.isBuffer(Y))return J.destroy(Error("Invalid protocolId")),!1;else B+=Y.length+2;if(Q!==3&&Q!==4&&Q!==5)return J.destroy(Error("Invalid protocol version")),!1;else B+=1;if((typeof G==="string"||z0.isBuffer(G))&&(G||Q>=4)&&(G||K))B+=z0.byteLength(G)+2;else{if(Q<4)return J.destroy(Error("clientId must be supplied before 3.1.1")),!1;if(K*1===0)return J.destroy(Error("clientId must be given if cleanSession set to 0")),!1}if(typeof z!=="number"||z<0||z>65535||z%1!==0)return J.destroy(Error("Invalid keepalive")),!1;else B+=2;B+=1;let U,D;if(Q===5){if(U=E7(J,F),!U)return!1;B+=U.length}if(W){if(typeof W!=="object")return J.destroy(Error("Invalid will")),!1;if(!W.topic||typeof W.topic!=="string")return J.destroy(Error("Invalid will topic")),!1;else B+=z0.byteLength(W.topic)+2;if(B+=2,W.payload)if(W.payload.length>=0)if(typeof W.payload==="string")B+=z0.byteLength(W.payload);else B+=W.payload.length;else return J.destroy(Error("Invalid will payload")),!1;if(D={},Q===5){if(D=E7(J,W.properties),!D)return!1;B+=D.length}}let _=!1;if(H!=null)if(g80(H))_=!0,B+=z0.byteLength(H)+2;else return J.destroy(Error("Invalid username")),!1;if(V!=null){if(!_)return J.destroy(Error("Username is required to use password")),!1;if(g80(V))B+=d80(V)+2;else return J.destroy(Error("Invalid password")),!1}if(J.write(B0.CONNECT_HEADER),Y8(J,B),Y$(J,Y),$.bridgeMode)Q+=128;J.write(Q===131?B0.VERSION131:Q===132?B0.VERSION132:Q===4?B0.VERSION4:Q===5?B0.VERSION5:B0.VERSION3);let O=0;if(O|=H!=null?B0.USERNAME_MASK:0,O|=V!=null?B0.PASSWORD_MASK:0,O|=W&&W.retain?B0.WILL_RETAIN_MASK:0,O|=W&&W.qos?W.qos<<B0.WILL_QOS_SHIFT:0,O|=W?B0.WILL_FLAG_MASK:0,O|=K?B0.CLEAN_SESSION_MASK:0,J.write(z0.from([O])),g4(J,z),Q===5)U.write();if(Y$(J,G),W){if(Q===5)D.write();sZ(J,W.topic),Y$(J,W.payload)}if(H!=null)Y$(J,H);if(V!=null)Y$(J,V);return!0}function _r0(Z,J,X){let $=X?X.protocolVersion:4,Y=Z||{},Q=$===5?Y.reasonCode:Y.returnCode,W=Y.properties,K=2;if(typeof Q!=="number")return J.destroy(Error("Invalid return code")),!1;let z=null;if($===5){if(z=E7(J,W),!z)return!1;K+=z.length}if(J.write(B0.CONNACK_HEADER),Y8(J,K),J.write(Y.sessionPresent?B0.SESSIONPRESENT_HEADER:Hr0),J.write(z0.from([Q])),z!=null)z.write();return!0}function Or0(Z,J,X){$8("publish: packet: %o",Z);let $=X?X.protocolVersion:4,Y=Z||{},Q=Y.qos||0,W=Y.retain?B0.RETAIN_MASK:0,K=Y.topic,z=Y.payload||Gr0,G=Y.messageId,H=Y.properties,V=0;if(typeof K==="string")V+=z0.byteLength(K)+2;else if(z0.isBuffer(K))V+=K.length+2;else return J.destroy(Error("Invalid topic")),!1;if(!z0.isBuffer(z))V+=z0.byteLength(z);else V+=z.length;if(Q&&typeof G!=="number")return J.destroy(Error("Invalid messageId")),!1;else if(Q)V+=2;let F=null;if($===5){if(F=E7(J,H),!F)return!1;V+=F.length}if(J.write(B0.PUBLISH_HEADER[Q][Y.dup?1:0][W?1:0]),Y8(J,V),g4(J,d80(K)),J.write(K),Q>0)g4(J,G);if(F!=null)F.write();return $8("publish: payload: %o",z),J.write(z)}function wr0(Z,J,X){let $=X?X.protocolVersion:4,Y=Z||{},Q=Y.cmd||"puback",W=Y.messageId,K=Y.dup&&Q==="pubrel"?B0.DUP_MASK:0,z=0,G=Y.reasonCode,H=Y.properties,V=$===5?3:2;if(Q==="pubrel")z=1;if(typeof W!=="number")return J.destroy(Error("Invalid messageId")),!1;let F=null;if($===5){if(typeof H==="object"){if(F=a3(J,H,X,V),!F)return!1;V+=F.length}}if(J.write(B0.ACKS[Q][z][K][0]),V===3)V+=G!==0?1:-1;if(Y8(J,V),g4(J,W),$===5&&V!==2)J.write(z0.from([G]));if(F!==null)F.write();else if(V===4)J.write(z0.from([0]));return!0}function jr0(Z,J,X){$8("subscribe: packet: ");let $=X?X.protocolVersion:4,Y=Z||{},Q=Y.dup?B0.DUP_MASK:0,W=Y.messageId,K=Y.subscriptions,z=Y.properties,G=0;if(typeof W!=="number")return J.destroy(Error("Invalid messageId")),!1;else G+=2;let H=null;if($===5){if(H=E7(J,z),!H)return!1;G+=H.length}if(typeof K==="object"&&K.length)for(let F=0;F<K.length;F+=1){let B=K[F].topic,U=K[F].qos;if(typeof B!=="string")return J.destroy(Error("Invalid subscriptions - invalid topic")),!1;if(typeof U!=="number")return J.destroy(Error("Invalid subscriptions - invalid qos")),!1;if($===5){if(typeof(K[F].nl||!1)!=="boolean")return J.destroy(Error("Invalid subscriptions - invalid No Local")),!1;if(typeof(K[F].rap||!1)!=="boolean")return J.destroy(Error("Invalid subscriptions - invalid Retain as Published")),!1;let O=K[F].rh||0;if(typeof O!=="number"||O>2)return J.destroy(Error("Invalid subscriptions - invalid Retain Handling")),!1}G+=z0.byteLength(B)+2+1}else return J.destroy(Error("Invalid subscriptions")),!1;if($8("subscribe: writing to stream: %o",B0.SUBSCRIBE_HEADER),J.write(B0.SUBSCRIBE_HEADER[1][Q?1:0][0]),Y8(J,G),g4(J,W),H!==null)H.write();let V=!0;for(let F of K){let{topic:B,qos:U}=F,D=+F.nl,_=+F.rap,O=F.rh,w;if(sZ(J,B),w=B0.SUBSCRIBE_OPTIONS_QOS[U],$===5)w|=D?B0.SUBSCRIBE_OPTIONS_NL:0,w|=_?B0.SUBSCRIBE_OPTIONS_RAP:0,w|=O?B0.SUBSCRIBE_OPTIONS_RH[O]:0;V=J.write(z0.from([w]))}return V}function Mr0(Z,J,X){let $=X?X.protocolVersion:4,Y=Z||{},Q=Y.messageId,W=Y.granted,K=Y.properties,z=0;if(typeof Q!=="number")return J.destroy(Error("Invalid messageId")),!1;else z+=2;if(typeof W==="object"&&W.length)for(let H=0;H<W.length;H+=1){if(typeof W[H]!=="number")return J.destroy(Error("Invalid qos vector")),!1;z+=1}else return J.destroy(Error("Invalid qos vector")),!1;let G=null;if($===5){if(G=a3(J,K,X,z),!G)return!1;z+=G.length}if(J.write(B0.SUBACK_HEADER),Y8(J,z),g4(J,Q),G!==null)G.write();return J.write(z0.from(W))}function Ar0(Z,J,X){let $=X?X.protocolVersion:4,Y=Z||{},Q=Y.messageId,W=Y.dup?B0.DUP_MASK:0,K=Y.unsubscriptions,z=Y.properties,G=0;if(typeof Q!=="number")return J.destroy(Error("Invalid messageId")),!1;else G+=2;if(typeof K==="object"&&K.length)for(let F=0;F<K.length;F+=1){if(typeof K[F]!=="string")return J.destroy(Error("Invalid unsubscriptions")),!1;G+=z0.byteLength(K[F])+2}else return J.destroy(Error("Invalid unsubscriptions")),!1;let H=null;if($===5){if(H=E7(J,z),!H)return!1;G+=H.length}if(J.write(B0.UNSUBSCRIBE_HEADER[1][W?1:0][0]),Y8(J,G),g4(J,Q),H!==null)H.write();let V=!0;for(let F=0;F<K.length;F++)V=sZ(J,K[F]);return V}function Tr0(Z,J,X){let $=X?X.protocolVersion:4,Y=Z||{},Q=Y.messageId,W=Y.dup?B0.DUP_MASK:0,K=Y.granted,z=Y.properties,G=Y.cmd,H=0,V=2;if(typeof Q!=="number")return J.destroy(Error("Invalid messageId")),!1;if($===5)if(typeof K==="object"&&K.length)for(let B=0;B<K.length;B+=1){if(typeof K[B]!=="number")return J.destroy(Error("Invalid qos vector")),!1;V+=1}else return J.destroy(Error("Invalid qos vector")),!1;let F=null;if($===5){if(F=a3(J,z,X,V),!F)return!1;V+=F.length}if(J.write(B0.ACKS[G][0][W][0]),Y8(J,V),g4(J,Q),F!==null)F.write();if($===5)J.write(z0.from(K));return!0}function qr0(Z,J,X){return J.write(B0.EMPTY[Z.cmd])}function Cr0(Z,J,X){let $=X?X.protocolVersion:4,Y=Z||{},Q=Y.reasonCode,W=Y.properties,K=$===5?1:0,z=null;if($===5){if(z=a3(J,W,X,K),!z)return!1;K+=z.length}if(J.write(z0.from([B0.codes.disconnect<<4])),Y8(J,K),$===5)J.write(z0.from([Q]));if(z!==null)z.write();return!0}function Nr0(Z,J,X){let $=X?X.protocolVersion:4,Y=Z||{},Q=Y.reasonCode,W=Y.properties,K=$===5?1:0;if($!==5)J.destroy(Error("Invalid mqtt version for auth packet"));let z=a3(J,W,X,K);if(!z)return!1;if(K+=z.length,J.write(z0.from([B0.codes.auth<<4])),Y8(J,K),J.write(z0.from([Q])),z!==null)z.write();return!0}var v80={};function Y8(Z,J){if(J>B0.VARBYTEINT_MAX)return Z.destroy(Error(`Invalid variable byte integer: ${J}`)),!1;let X=v80[J];if(!X){if(X=BO(J),J<16384)v80[J]=X}return $8("writeVarByteInt: writing to stream: %o",X),Z.write(X)}function sZ(Z,J){let X=z0.byteLength(J);return g4(Z,X),$8("writeString: %s",J),Z.write(J,"utf8")}function h80(Z,J,X){sZ(Z,J),sZ(Z,X)}function UO(Z,J){return $8("writeNumberCached: number: %d",J),$8("writeNumberCached: %o",hG[J]),Z.write(hG[J])}function Rr0(Z,J){let X=Fr0(J);return $8("writeNumberGenerated: %o",X),Z.write(X)}function Pr0(Z,J){let X=Ur0(J);return $8("write4ByteNumber: %o",X),Z.write(X)}function Y$(Z,J){if(typeof J==="string")sZ(Z,J);else if(J)g4(Z,J.length),Z.write(J);else g4(Z,0)}function E7(Z,J){if(typeof J!=="object"||J.length!=null)return{length:1,write(){b80(Z,{},0)}};let X=0;function $(Q,W){let K=B0.propertiesTypes[Q],z=0;switch(K){case"byte":{if(typeof W!=="boolean")return Z.destroy(Error(`Invalid ${Q}: ${W}`)),!1;z+=2;break}case"int8":{if(typeof W!=="number"||W<0||W>255)return Z.destroy(Error(`Invalid ${Q}: ${W}`)),!1;z+=2;break}case"binary":{if(W&&W===null)return Z.destroy(Error(`Invalid ${Q}: ${W}`)),!1;z+=1+z0.byteLength(W)+2;break}case"int16":{if(typeof W!=="number"||W<0||W>65535)return Z.destroy(Error(`Invalid ${Q}: ${W}`)),!1;z+=3;break}case"int32":{if(typeof W!=="number"||W<0||W>4294967295)return Z.destroy(Error(`Invalid ${Q}: ${W}`)),!1;z+=5;break}case"var":{if(typeof W!=="number"||W<0||W>268435455)return Z.destroy(Error(`Invalid ${Q}: ${W}`)),!1;z+=1+z0.byteLength(BO(W));break}case"string":{if(typeof W!=="string")return Z.destroy(Error(`Invalid ${Q}: ${W}`)),!1;z+=3+z0.byteLength(W.toString());break}case"pair":{if(typeof W!=="object")return Z.destroy(Error(`Invalid ${Q}: ${W}`)),!1;z+=Object.getOwnPropertyNames(W).reduce((G,H)=>{let V=W[H];if(Array.isArray(V))G+=V.reduce((F,B)=>{return F+=3+z0.byteLength(H.toString())+2+z0.byteLength(B.toString()),F},0);else G+=3+z0.byteLength(H.toString())+2+z0.byteLength(W[H].toString());return G},0);break}default:return Z.destroy(Error(`Invalid property ${Q}: ${W}`)),!1}return z}if(J)for(let Q in J){let W=0,K=0,z=J[Q];if(z===void 0)continue;else if(Array.isArray(z))for(let G=0;G<z.length;G++){if(K=$(Q,z[G]),!K)return!1;W+=K}else{if(K=$(Q,z),!K)return!1;W=K}if(!W)return!1;X+=W}return{length:z0.byteLength(BO(X))+X,write(){b80(Z,J,X)}}}function a3(Z,J,X,$){let Y=["reasonString","userProperties"],Q=X&&X.properties&&X.properties.maximumPacketSize?X.properties.maximumPacketSize:0,W=E7(Z,J);if(Q)while($+W.length>Q){let K=Y.shift();if(K&&J[K])delete J[K],W=E7(Z,J);else return!1}return W}function f80(Z,J,X){switch(B0.propertiesTypes[J]){case"byte":{Z.write(z0.from([B0.properties[J]])),Z.write(z0.from([+X]));break}case"int8":{Z.write(z0.from([B0.properties[J]])),Z.write(z0.from([X]));break}case"binary":{Z.write(z0.from([B0.properties[J]])),Y$(Z,X);break}case"int16":{Z.write(z0.from([B0.properties[J]])),g4(Z,X);break}case"int32":{Z.write(z0.from([B0.properties[J]])),Pr0(Z,X);break}case"var":{Z.write(z0.from([B0.properties[J]])),Y8(Z,X);break}case"string":{Z.write(z0.from([B0.properties[J]])),sZ(Z,X);break}case"pair":{Object.getOwnPropertyNames(X).forEach((Y)=>{let Q=X[Y];if(Array.isArray(Q))Q.forEach((W)=>{Z.write(z0.from([B0.properties[J]])),h80(Z,Y.toString(),W.toString())});else Z.write(z0.from([B0.properties[J]])),h80(Z,Y.toString(),Q.toString())});break}default:return Z.destroy(Error(`Invalid property ${J} value: ${X}`)),!1}}function b80(Z,J,X){Y8(Z,X);for(let $ in J)if(Object.prototype.hasOwnProperty.call(J,$)&&J[$]!=null){let Y=J[$];if(Array.isArray(Y))for(let Q=0;Q<Y.length;Q++)f80(Z,$,Y[Q]);else f80(Z,$,Y)}}function d80(Z){if(!Z)return 0;else if(Z instanceof z0)return Z.length;else return z0.byteLength(Z)}function g80(Z){return typeof Z==="string"||Z instanceof z0}u80.exports=m80});var i80=L((IP1,p80)=>{var Er0=LO(),{EventEmitter:Ir0}=N("events"),{Buffer:c80}=N("buffer");function yr0(Z,J){let X=new l80;return Er0(Z,X,J),X.concat()}class l80 extends Ir0{constructor(){super();this._array=Array(20),this._i=0}write(Z){return this._array[this._i++]=Z,!0}concat(){let Z=0,J=Array(this._array.length),X=this._array,$=0,Y;for(Y=0;Y<X.length&&X[Y]!==void 0;Y++){if(typeof X[Y]!=="string")J[Y]=X[Y].length;else J[Y]=c80.byteLength(X[Y]);Z+=J[Y]}let Q=c80.allocUnsafe(Z);for(Y=0;Y<X.length&&X[Y]!==void 0;Y++)if(typeof X[Y]!=="string")X[Y].copy(Q,$),$+=J[Y];else Q.write(X[Y],$),$+=J[Y];return Q}destroy(Z){if(Z)this.emit("error",Z)}}p80.exports=yr0});var bG=L((Sr0)=>{Sr0.parser=E80().parser;Sr0.generate=i80();Sr0.writeToStream=LO()});var a80=L((SP1,o80)=>{o80.exports=n80;function n80(Z,J){if(Z&&J)return n80(Z)(J);if(typeof Z!=="function")throw TypeError("need wrapper function");return Object.keys(Z).forEach(function($){X[$]=Z[$]}),X;function X(){var $=Array(arguments.length);for(var Y=0;Y<$.length;Y++)$[Y]=arguments[Y];var Q=Z.apply(this,$),W=$[$.length-1];if(typeof Q==="function"&&Q!==W)Object.keys(W).forEach(function(K){Q[K]=W[K]});return Q}}});var t80=L((kP1,DO)=>{var r80=a80();DO.exports=r80(gG);DO.exports.strict=r80(s80);gG.proto=gG(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return gG(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return s80(this)},configurable:!0})});function gG(Z){var J=function(){if(J.called)return J.value;return J.called=!0,J.value=Z.apply(this,arguments)};return J.called=!1,J}function s80(Z){var J=function(){if(J.called)throw Error(J.onceError);return J.called=!0,J.value=Z.apply(this,arguments)},X=Z.name||"Function wrapped with `once`";return J.onceError=X+" shouldn't be called more than once",J.called=!1,J}});var J50=L((xP1,Z50)=>{var hr0=t80(),fr0=function(){},br0=global.Bare?queueMicrotask:process.nextTick.bind(process),gr0=function(Z){return Z.setHeader&&typeof Z.abort==="function"},mr0=function(Z){return Z.stdio&&Array.isArray(Z.stdio)&&Z.stdio.length===3},e80=function(Z,J,X){if(typeof J==="function")return e80(Z,null,J);if(!J)J={};X=hr0(X||fr0);var{_writableState:$,_readableState:Y}=Z,Q=J.readable||J.readable!==!1&&Z.readable,W=J.writable||J.writable!==!1&&Z.writable,K=!1,z=function(){if(!Z.writable)G()},G=function(){if(W=!1,!Q)X.call(Z)},H=function(){if(Q=!1,!W)X.call(Z)},V=function(_){X.call(Z,_?Error("exited with error code: "+_):null)},F=function(_){X.call(Z,_)},B=function(){br0(U)},U=function(){if(K)return;if(Q&&!(Y&&(Y.ended&&!Y.destroyed)))return X.call(Z,Error("premature close"));if(W&&!($&&($.ended&&!$.destroyed)))return X.call(Z,Error("premature close"))},D=function(){Z.req.on("finish",G)};if(gr0(Z))if(Z.on("complete",G),Z.on("abort",B),Z.req)D();else Z.on("request",D);else if(W&&!$)Z.on("end",z),Z.on("close",z);if(mr0(Z))Z.on("exit",V);if(Z.on("end",H),Z.on("finish",G),J.error!==!1)Z.on("error",F);return Z.on("close",B),function(){if(K=!0,Z.removeListener("complete",G),Z.removeListener("abort",B),Z.removeListener("request",D),Z.req)Z.req.removeListener("finish",G);Z.removeListener("end",z),Z.removeListener("close",z),Z.removeListener("finish",G),Z.removeListener("exit",V),Z.removeListener("end",H),Z.removeListener("error",F),Z.removeListener("close",B)}};Z50.exports=e80});var D9=L((vP1,X50)=>{var dr0=bG();function ur0(Z,J,X){let $=null;if(Z.connecting||Z.connected)try{if(!dr0.writeToStream(J,Z.conn)&&!Z.errored){Z.conn.once("drain",X);return}}catch(Y){$=Error("packet received not valid")}else $=Error("connection closed");setImmediate(X,$,Z)}X50.exports=ur0});var _O=L((hP1,Q50)=>{var $50=lX(),cr0=N("util");function Y50(Z,J){if($50.call(this,Z,J.broker),this.writeCallback=J._onError.bind(J),!Z.messageId)if(this.messageId=J._nextId,J._nextId>=65535)J._nextId=1;else J._nextId++;else this.messageId=Z.messageId}cr0.inherits(Y50,$50);Q50.exports=Y50});var z50=L((fP1,K50)=>{var lr0=nz(),W50=[];function pr0(Z,J){if(Array.isArray(Z))J=Z,Z=null;var X=lr0(ir0);return J?Q:$;function $(){var W=X.get();if(W.release=Y,arguments.length===3)W.context=arguments[0],W.list=arguments[1],W.callback=arguments[2]||r3;else W.context=Z,W.list=arguments[0],W.callback=arguments[1]||r3;W.work()}function Y(W){X.release(W)}function Q(){var W=X.get();W.release=Y,W.list=J;var K,z,G=arguments.length-1;switch(W.context=this||Z,W.callback=arguments[G]||r3,G){case 0:W.work();break;case 1:W.work(null,arguments[0]);break;case 2:W.work(null,arguments[0],arguments[1]);break;case 3:W.work(null,arguments[0],arguments[1],arguments[2]);break;case 4:W.work(null,arguments[0],arguments[1],arguments[2],arguments[3]);break;default:K=Array(G+1),K[0]=null;for(z=0;z<G;z++)K[z+1]=arguments[z];W.work.apply(null,K)}}}function r3(){}function ir0(){this.list=W50,this.callback=r3,this.count=0,this.context=void 0,this.release=r3;var Z=this;this.work=function J(){if(arguments.length>0&&arguments[0])return Z.callback.call(Z.context,arguments[0]);var X=arguments.length,$,Y,Q;if(Z.count<Z.list.length)switch(Q=Z.list[Z.count++],X){case 0:case 1:return Q.call(Z.context,J);case 2:return Q.call(Z.context,arguments[1],J);case 3:return Q.call(Z.context,arguments[1],arguments[2],J);case 4:return Q.call(Z.context,arguments[1],arguments[2],arguments[3],J);default:Y=Array(X);for($=1;$<X;$++)Y[$-1]=arguments[$];Y[X-1]=J,Q.apply(Z.context,Y)}else{switch(X){case 0:Z.callback.call(Z.context);break;case 1:Z.callback.call(Z.context,arguments[0]);break;case 2:Z.callback.call(Z.context,arguments[0],arguments[1]);break;case 3:Z.callback.call(Z.context,arguments[0],arguments[1],arguments[2]);break;case 4:Z.callback.call(Z.context,arguments[0],arguments[1],arguments[2],arguments[3]);break;default:Y=Array(X);for($=0;$<X;$++)Y[$]=arguments[$];Z.callback.apply(Z.context,Y)}Z.context=void 0,Z.list=W50,Z.count=0,Z.release(Z)}}}K50.exports=pr0});var tZ=L((bP1,G50)=>{var{Transform:nr0,Writable:or0}=N("stream");function ar0(Z,J){if(!Z||Z.length===0)return Error("impossible to "+J+" to an empty topic");let X=Z.length-1,$=X-1,Y=$>0&&Z.charCodeAt($)!==47;for(let Q=0;Q<Z.length;Q++)switch(Z.charCodeAt(Q)){case 35:{if(Q!==X||Y)return Error("# is only allowed in "+J+" in the last position");break}case 43:{let W=Q<X-1&&Z.charCodeAt(Q+1)!==47,K=Q>1&&Z.charCodeAt(Q-1)!==47;if(W||K)return Error("+ is only allowed in "+J+" between /");break}}}function rr0(Z){return new nr0({objectMode:!0,transform:Z})}function sr0(Z){return new or0({objectMode:!0,writev:function(J,X){Z(J.map(($)=>$.chunk),X)}})}G50.exports={validateTopic:ar0,through:rr0,bulk:sr0,$SYS_PREFIX:"$SYS/"}});var mG=L((gP1,L50)=>{var V50=z50(),F50=lX(),{through:tr0}=tZ(),{validateTopic:er0,$SYS_PREFIX:Zs0}=tZ(),Js0=D9(),Xs0=V50([B50,Vs0,U50]),$s0=V50([B50,U50]);function Ys0(Z,J){this.cmd="suback",this.messageId=Z.messageId,this.granted=J}function H50(Z,J,X,$,Y){this.qos=Z,this.func=J,this.rh=X,this.rap=$,this.nl=Y}function Qs0(Z,J,X,$){this.client=Z,this.packet=J,this.actions=X?$s0:Xs0,this.finish=$,this.subState=[]}function Ws0(Z,J,X,$,Y,Q){this.client=Z,this.packet=J,this.granted=X,this.rh=$,this.rap=Y,this.nl=Q}function Ks0(Z){let J={};for(let $=0;$<Z.length;$++){let Y=Z[$];J[Y.topic]=Y}let X=[];for(let $ in J)X.push(J[$]);return X}function zs0(Z,J,X,$){J.subscriptions=J.subscriptions.length===1?J.subscriptions:Ks0(J.subscriptions),Z.broker._parallel(new Qs0(Z,J,X,$),Gs0,J.subscriptions,X?$:Bs0)}function Gs0(Z,J){let X=new Ws0(this.client,this.packet,Z.qos,Z.rh,Z.rap,Z.nl);this.subState.push(X),this.actions.call(X,Z,J)}function B50(Z,J){let X=er0(Z.topic,"SUBSCRIBE");if(X)return J(X);let $=this.client;$.broker.authorizeSubscribe($,Z,J)}function Hs0(Z){return function(X,$){if(X.topic.charCodeAt(0)===36)$();else Z(X,$)}}function Vs0(Z,J){if(!Z||typeof Z!=="object")return this.granted=128,J(null,null);let X=this.packet,$=this.client;if($.clean)return J(null,Z);$.broker.persistence.addSubscriptions($,X.subscriptions,function(Q){J(Q,Z)})}function U50(Z,J){if(!Z||typeof Z!=="object")return J();let X=this.client,$=X.broker,Y=Z.topic,Q=Z.qos,W=this.rh,K=this.rap,z=this.nl,G=Q>0?X.deliverQoS:X.deliver0,H=G;if(G=function(F,B){if(F=new F50(F,$),F.nl=z,!K)F.retain=!1;H(F,B)},Fs0(Y))G=Hs0(G);if(X.closed||X.broker.closed)return;if(!X.subscriptions[Y])X.subscriptions[Y]=new H50(Q,G,W,K,z),$.subscribe(Y,G,J);else if(X.subscriptions[Y].qos!==Q||X.subscriptions[Y].rh!==W||X.subscriptions[Y].rap!==K||X.subscriptions[Y].nl!==z)$.unsubscribe(Y,X.subscriptions[Y].func),X.subscriptions[Y]=new H50(Q,G,W,K,z),$.subscribe(Y,G,J);else J()}function Fs0(Z){let J=Z.charCodeAt(0);return J===43||J===35}function Bs0(Z){let J=this.finish;if(Z)return J(Z);let X=this.packet,$=this.client;if(X.messageId!==void 0)Js0($,new Ys0(X,this.subState.map((K)=>K.granted)),J);else J();let Y=$.broker,Q=X.subscriptions,W=[];for(let K=0;K<Q.length;K++){if(this.subState[K].granted!==128)W.push(Q[K].topic);Q[K].qos=this.subState[K].granted}if(this.subState=[],Y.emit("subscribe",Q,$),Y.publish({topic:Zs0+Y.id+"/new/subscribes",payload:Buffer.from(JSON.stringify({clientId:$.id,subs:Q}),"utf8")},Us0),W.length>0)Y.persistence.createRetainedStreamCombi(W).pipe(tr0(function(H,V,F){H=new F50({cmd:H.cmd,qos:H.qos,topic:H.topic,payload:H.payload,retain:!0},Y),H.brokerId=null,$.deliverQoS(H,F)}))}function Us0(){}L50.exports=zs0});var wO=L((mP1,D50)=>{var Ls0=D9(),{validateTopic:Ds0,$SYS_PREFIX:_s0}=tZ();function Os0(Z){this.cmd="unsuback",this.messageId=Z.messageId}function ws0(Z,J,X){this.client=Z,this.packet=J,this.finish=X}function js0(Z,J,X){let $=Z.broker,Y=J.unsubscriptions,Q;for(let W=0;W<Y.length;W++)if(Q=Ds0(Y[W],"UNSUBSCRIBE"),Q)return X(Q);if(J.messageId!==void 0){if(Z.clean)return OO(Z,J,X);$.persistence.removeSubscriptions(Z,Y,function(W){if(W)return X(W);OO(Z,J,X)})}else OO(Z,J,X)}function OO(Z,J,X){Z.broker._parallel(new ws0(Z,J,X),Ms0,J.unsubscriptions,As0)}function Ms0(Z,J){let X=this.client,$=X.broker,Y=X.subscriptions[Z];if(Y){let Q=Y.func;delete X.subscriptions[Z],$.unsubscribe(Z,Q,J)}else J()}function As0(Z){let J=this.client;if(Z){J.emit("error",Z);return}let X=this.packet,$=this.finish;if(X.messageId!==void 0)Ls0(J,new Os0(X),$);else $();if((!J.closed||J.clean===!0)&&X.unsubscriptions.length>0)J.broker.emit("unsubscribe",X.unsubscriptions,J),J.broker.publish({topic:_s0+J.broker.id+"/new/unsubscribes",payload:Buffer.from(JSON.stringify({clientId:J.id,subs:X.unsubscriptions}),"utf8")},Ts0)}function Ts0(){}D50.exports=js0});var O50=L((dP1,_50)=>{_50.exports=function(){let J=process.hrtime();return Math.floor(J[0]*1000+J[1]/1e6)}});var j50=L((uP1,w50)=>{w50.exports={clearInterval,clearTimeout,setInterval,setTimeout}});var T50=L((cP1,MO)=>{var dG=O50(),{clearTimeout:M50,setTimeout:A50}=j50();class jO{constructor(Z,J,X){let $=this;this._started=dG(),this._rescheduled=0,this._scheduled=J,this._args=X,this._triggered=!1,this._timerWrapper=()=>{if($._rescheduled>0)$._scheduled=$._rescheduled-(dG()-$._started),$._schedule($._scheduled);else $._triggered=!0,Z.apply(null,$._args)},this._timer=A50(this._timerWrapper,J)}reschedule(Z){if(!Z)Z=this._scheduled;let J=dG();if(J+Z-(this._started+this._scheduled)<0)M50(this._timer),this._schedule(Z);else if(!this._triggered)this._started=J,this._rescheduled=Z;else this._schedule(Z)}_schedule(Z){this._triggered=!1,this._started=dG(),this._rescheduled=0,this._scheduled=Z,this._timer=A50(this._timerWrapper,Z)}clear(){M50(this._timer)}}function qs0(){if(typeof arguments[0]!=="function")throw Error("callback needed");if(typeof arguments[1]!=="number")throw Error("timeout needed");let Z;if(arguments.length>0){Z=Array(arguments.length-2);for(var J=0;J<Z.length;J++)Z[J]=arguments[J+2]}return new jO(arguments[0],arguments[1],Z)}MO.exports=qs0;MO.exports.Retimer=jO});var AO=L((q50)=>{Object.defineProperty(q50,"__esModule",{value:!0});q50.default=Rs0;var Cs0=Ns0(N("crypto"));function Ns0(Z){return Z&&Z.__esModule?Z:{default:Z}}var cG=new Uint8Array(256),uG=cG.length;function Rs0(){if(uG>cG.length-16)Cs0.default.randomFillSync(cG),uG=0;return cG.slice(uG,uG+=16)}});var R50=L((C50)=>{Object.defineProperty(C50,"__esModule",{value:!0});C50.default=void 0;var Es0=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;C50.default=Es0});var s3=L((P50)=>{Object.defineProperty(P50,"__esModule",{value:!0});P50.default=void 0;var Is0=ys0(R50());function ys0(Z){return Z&&Z.__esModule?Z:{default:Z}}function Ss0(Z){return typeof Z==="string"&&Is0.default.test(Z)}var ks0=Ss0;P50.default=ks0});var t3=L((I50)=>{Object.defineProperty(I50,"__esModule",{value:!0});I50.default=void 0;var xs0=vs0(s3());function vs0(Z){return Z&&Z.__esModule?Z:{default:Z}}var L4=[];for(let Z=0;Z<256;++Z)L4.push((Z+256).toString(16).substr(1));function hs0(Z,J=0){let X=(L4[Z[J+0]]+L4[Z[J+1]]+L4[Z[J+2]]+L4[Z[J+3]]+"-"+L4[Z[J+4]]+L4[Z[J+5]]+"-"+L4[Z[J+6]]+L4[Z[J+7]]+"-"+L4[Z[J+8]]+L4[Z[J+9]]+"-"+L4[Z[J+10]]+L4[Z[J+11]]+L4[Z[J+12]]+L4[Z[J+13]]+L4[Z[J+14]]+L4[Z[J+15]]).toLowerCase();if(!(0,xs0.default)(X))throw TypeError("Stringified UUID is invalid");return X}var fs0=hs0;I50.default=fs0});var h50=L((x50)=>{Object.defineProperty(x50,"__esModule",{value:!0});x50.default=void 0;var bs0=k50(AO()),gs0=k50(t3());function k50(Z){return Z&&Z.__esModule?Z:{default:Z}}var S50,TO,qO=0,CO=0;function ms0(Z,J,X){let $=J&&X||0,Y=J||Array(16);Z=Z||{};let Q=Z.node||S50,W=Z.clockseq!==void 0?Z.clockseq:TO;if(Q==null||W==null){let F=Z.random||(Z.rng||bs0.default)();if(Q==null)Q=S50=[F[0]|1,F[1],F[2],F[3],F[4],F[5]];if(W==null)W=TO=(F[6]<<8|F[7])&16383}let K=Z.msecs!==void 0?Z.msecs:Date.now(),z=Z.nsecs!==void 0?Z.nsecs:CO+1,G=K-qO+(z-CO)/1e4;if(G<0&&Z.clockseq===void 0)W=W+1&16383;if((G<0||K>qO)&&Z.nsecs===void 0)z=0;if(z>=1e4)throw Error("uuid.v1(): Can't create more than 10M uuids/sec");qO=K,CO=z,TO=W,K+=12219292800000;let H=((K&268435455)*1e4+z)%4294967296;Y[$++]=H>>>24&255,Y[$++]=H>>>16&255,Y[$++]=H>>>8&255,Y[$++]=H&255;let V=K/4294967296*1e4&268435455;Y[$++]=V>>>8&255,Y[$++]=V&255,Y[$++]=V>>>24&15|16,Y[$++]=V>>>16&255,Y[$++]=W>>>8|128,Y[$++]=W&255;for(let F=0;F<6;++F)Y[$+F]=Q[F];return J||(0,gs0.default)(Y)}var ds0=ms0;x50.default=ds0});var NO=L((f50)=>{Object.defineProperty(f50,"__esModule",{value:!0});f50.default=void 0;var us0=cs0(s3());function cs0(Z){return Z&&Z.__esModule?Z:{default:Z}}function ls0(Z){if(!(0,us0.default)(Z))throw TypeError("Invalid UUID");let J,X=new Uint8Array(16);return X[0]=(J=parseInt(Z.slice(0,8),16))>>>24,X[1]=J>>>16&255,X[2]=J>>>8&255,X[3]=J&255,X[4]=(J=parseInt(Z.slice(9,13),16))>>>8,X[5]=J&255,X[6]=(J=parseInt(Z.slice(14,18),16))>>>8,X[7]=J&255,X[8]=(J=parseInt(Z.slice(19,23),16))>>>8,X[9]=J&255,X[10]=(J=parseInt(Z.slice(24,36),16))/1099511627776&255,X[11]=J/4294967296&255,X[12]=J>>>24&255,X[13]=J>>>16&255,X[14]=J>>>8&255,X[15]=J&255,X}var ps0=ls0;f50.default=ps0});var RO=L((u50)=>{Object.defineProperty(u50,"__esModule",{value:!0});u50.default=as0;u50.URL=u50.DNS=void 0;var is0=g50(t3()),ns0=g50(NO());function g50(Z){return Z&&Z.__esModule?Z:{default:Z}}function os0(Z){Z=unescape(encodeURIComponent(Z));let J=[];for(let X=0;X<Z.length;++X)J.push(Z.charCodeAt(X));return J}var m50="6ba7b810-9dad-11d1-80b4-00c04fd430c8";u50.DNS=m50;var d50="6ba7b811-9dad-11d1-80b4-00c04fd430c8";u50.URL=d50;function as0(Z,J,X){function $(Y,Q,W,K){if(typeof Y==="string")Y=os0(Y);if(typeof Q==="string")Q=(0,ns0.default)(Q);if(Q.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let z=new Uint8Array(16+Y.length);if(z.set(Q),z.set(Y,Q.length),z=X(z),z[6]=z[6]&15|J,z[8]=z[8]&63|128,W){K=K||0;for(let G=0;G<16;++G)W[K+G]=z[G];return W}return(0,is0.default)(z)}try{$.name=Z}catch(Y){}return $.DNS=m50,$.URL=d50,$}});var i50=L((l50)=>{Object.defineProperty(l50,"__esModule",{value:!0});l50.default=void 0;var ts0=es0(N("crypto"));function es0(Z){return Z&&Z.__esModule?Z:{default:Z}}function Zt0(Z){if(Array.isArray(Z))Z=Buffer.from(Z);else if(typeof Z==="string")Z=Buffer.from(Z,"utf8");return ts0.default.createHash("md5").update(Z).digest()}var Jt0=Zt0;l50.default=Jt0});var r50=L((o50)=>{Object.defineProperty(o50,"__esModule",{value:!0});o50.default=void 0;var Xt0=n50(RO()),$t0=n50(i50());function n50(Z){return Z&&Z.__esModule?Z:{default:Z}}var Yt0=(0,Xt0.default)("v3",48,$t0.default),Qt0=Yt0;o50.default=Qt0});var Z90=L((t50)=>{Object.defineProperty(t50,"__esModule",{value:!0});t50.default=void 0;var Wt0=s50(AO()),Kt0=s50(t3());function s50(Z){return Z&&Z.__esModule?Z:{default:Z}}function zt0(Z,J,X){Z=Z||{};let $=Z.random||(Z.rng||Wt0.default)();if($[6]=$[6]&15|64,$[8]=$[8]&63|128,J){X=X||0;for(let Y=0;Y<16;++Y)J[X+Y]=$[Y];return J}return(0,Kt0.default)($)}var Gt0=zt0;t50.default=Gt0});var $90=L((J90)=>{Object.defineProperty(J90,"__esModule",{value:!0});J90.default=void 0;var Ht0=Vt0(N("crypto"));function Vt0(Z){return Z&&Z.__esModule?Z:{default:Z}}function Ft0(Z){if(Array.isArray(Z))Z=Buffer.from(Z);else if(typeof Z==="string")Z=Buffer.from(Z,"utf8");return Ht0.default.createHash("sha1").update(Z).digest()}var Bt0=Ft0;J90.default=Bt0});var K90=L((Q90)=>{Object.defineProperty(Q90,"__esModule",{value:!0});Q90.default=void 0;var Ut0=Y90(RO()),Lt0=Y90($90());function Y90(Z){return Z&&Z.__esModule?Z:{default:Z}}var Dt0=(0,Ut0.default)("v5",80,Lt0.default),_t0=Dt0;Q90.default=_t0});var H90=L((z90)=>{Object.defineProperty(z90,"__esModule",{value:!0});z90.default=void 0;var Ot0="00000000-0000-0000-0000-000000000000";z90.default=Ot0});var B90=L((V90)=>{Object.defineProperty(V90,"__esModule",{value:!0});V90.default=void 0;var wt0=jt0(s3());function jt0(Z){return Z&&Z.__esModule?Z:{default:Z}}function Mt0(Z){if(!(0,wt0.default)(Z))throw TypeError("Invalid UUID");return parseInt(Z.substr(14,1),16)}var At0=Mt0;V90.default=At0});var U90=L((g8)=>{Object.defineProperty(g8,"__esModule",{value:!0});Object.defineProperty(g8,"v1",{enumerable:!0,get:function(){return Tt0.default}});Object.defineProperty(g8,"v3",{enumerable:!0,get:function(){return qt0.default}});Object.defineProperty(g8,"v4",{enumerable:!0,get:function(){return Ct0.default}});Object.defineProperty(g8,"v5",{enumerable:!0,get:function(){return Nt0.default}});Object.defineProperty(g8,"NIL",{enumerable:!0,get:function(){return Rt0.default}});Object.defineProperty(g8,"version",{enumerable:!0,get:function(){return Pt0.default}});Object.defineProperty(g8,"validate",{enumerable:!0,get:function(){return Et0.default}});Object.defineProperty(g8,"stringify",{enumerable:!0,get:function(){return It0.default}});Object.defineProperty(g8,"parse",{enumerable:!0,get:function(){return yt0.default}});var Tt0=_9(h50()),qt0=_9(r50()),Ct0=_9(Z90()),Nt0=_9(K90()),Rt0=_9(H90()),Pt0=_9(B90()),Et0=_9(s3()),It0=_9(t3()),yt0=_9(NO());function _9(Z){return Z&&Z.__esModule?Z:{default:Z}}});var _90=L((QE1,D90)=>{var St0=U90(),L90=N("crypto");D90.exports=typeof L90.randomUUID==="function"?L90.randomUUID:St0.v4});var j90=L((WE1,w90)=>{var PO=[],O90={};for(I7=0;I7<256;I7++)PO[I7]=(I7+256).toString(16).substr(1),O90[PO[I7]]=I7;var I7;function kt0(Z,J,X){var $=J&&X||0,Y=0;J=J||[],Z.toLowerCase().replace(/[0-9a-f]{2}/g,function(Q){if(Y<16)J[$+Y++]=O90[Q]});while(Y<16)J[$+Y++]=0;return J}function xt0(Z,J){var X=J||0,$=PO;return $[Z[X++]]+$[Z[X++]]+$[Z[X++]]+$[Z[X++]]+"-"+$[Z[X++]]+$[Z[X++]]+"-"+$[Z[X++]]+$[Z[X++]]+"-"+$[Z[X++]]+$[Z[X++]]+"-"+$[Z[X++]]+$[Z[X++]]+$[Z[X++]]+$[Z[X++]]+$[Z[X++]]+$[Z[X++]]}w90.exports={parse:kt0,unparse:xt0}});var A90=L((ut0)=>{ut0.byteLength=ht0;ut0.toByteArray=bt0;ut0.fromByteArray=dt0;var w5=[],Q8=[],vt0=typeof Uint8Array<"u"?Uint8Array:Array,EO="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(y7=0,IO=EO.length;y7<IO;++y7)w5[y7]=EO[y7],Q8[EO.charCodeAt(y7)]=y7;var y7,IO;Q8[45]=62;Q8[95]=63;function M90(Z){var J=Z.length;if(J%4>0)throw Error("Invalid string. Length must be a multiple of 4");var X=Z.indexOf("=");if(X===-1)X=J;var $=X===J?0:4-X%4;return[X,$]}function ht0(Z){var J=M90(Z),X=J[0],$=J[1];return(X+$)*3/4-$}function ft0(Z,J,X){return(J+X)*3/4-X}function bt0(Z){var J,X=M90(Z),$=X[0],Y=X[1],Q=new vt0(ft0(Z,$,Y)),W=0,K=Y>0?$-4:$,z;for(z=0;z<K;z+=4)J=Q8[Z.charCodeAt(z)]<<18|Q8[Z.charCodeAt(z+1)]<<12|Q8[Z.charCodeAt(z+2)]<<6|Q8[Z.charCodeAt(z+3)],Q[W++]=J>>16&255,Q[W++]=J>>8&255,Q[W++]=J&255;if(Y===2)J=Q8[Z.charCodeAt(z)]<<2|Q8[Z.charCodeAt(z+1)]>>4,Q[W++]=J&255;if(Y===1)J=Q8[Z.charCodeAt(z)]<<10|Q8[Z.charCodeAt(z+1)]<<4|Q8[Z.charCodeAt(z+2)]>>2,Q[W++]=J>>8&255,Q[W++]=J&255;return Q}function gt0(Z){return w5[Z>>18&63]+w5[Z>>12&63]+w5[Z>>6&63]+w5[Z&63]}function mt0(Z,J,X){var $,Y=[];for(var Q=J;Q<X;Q+=3)$=(Z[Q]<<16&16711680)+(Z[Q+1]<<8&65280)+(Z[Q+2]&255),Y.push(gt0($));return Y.join("")}function dt0(Z){var J,X=Z.length,$=X%3,Y=[],Q=16383;for(var W=0,K=X-$;W<K;W+=Q)Y.push(mt0(Z,W,W+Q>K?K:W+Q));if($===1)J=Z[X-1],Y.push(w5[J>>2]+w5[J<<4&63]+"==");else if($===2)J=(Z[X-2]<<8)+Z[X-1],Y.push(w5[J>>10]+w5[J>>4&63]+w5[J<<2&63]+"=");return Y.join("")}});var T90=L((it0)=>{/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */it0.read=function(Z,J,X,$,Y){var Q,W,K=Y*8-$-1,z=(1<<K)-1,G=z>>1,H=-7,V=X?Y-1:0,F=X?-1:1,B=Z[J+V];V+=F,Q=B&(1<<-H)-1,B>>=-H,H+=K;for(;H>0;Q=Q*256+Z[J+V],V+=F,H-=8);W=Q&(1<<-H)-1,Q>>=-H,H+=$;for(;H>0;W=W*256+Z[J+V],V+=F,H-=8);if(Q===0)Q=1-G;else if(Q===z)return W?NaN:(B?-1:1)*(1/0);else W=W+Math.pow(2,$),Q=Q-G;return(B?-1:1)*W*Math.pow(2,Q-$)};it0.write=function(Z,J,X,$,Y,Q){var W,K,z,G=Q*8-Y-1,H=(1<<G)-1,V=H>>1,F=Y===23?Math.pow(2,-24)-Math.pow(2,-77):0,B=$?0:Q-1,U=$?1:-1,D=J<0||J===0&&1/J<0?1:0;if(J=Math.abs(J),isNaN(J)||J===1/0)K=isNaN(J)?1:0,W=H;else{if(W=Math.floor(Math.log(J)/Math.LN2),J*(z=Math.pow(2,-W))<1)W--,z*=2;if(W+V>=1)J+=F/z;else J+=F*Math.pow(2,1-V);if(J*z>=2)W++,z/=2;if(W+V>=H)K=0,W=H;else if(W+V>=1)K=(J*z-1)*Math.pow(2,Y),W=W+V;else K=J*Math.pow(2,V-1)*Math.pow(2,Y),W=0}for(;Y>=8;Z[X+B]=K&255,B+=U,K/=256,Y-=8);W=W<<Y|K,G+=Y;for(;G>0;Z[X+B]=W&255,B+=U,W/=256,G-=8);Z[X+B-U]|=D*128}});var f90=L((Oe0)=>{/*!
12
12
  * The buffer module from node.js, for the browser.
13
13
  *
14
14
  * @author Feross Aboukhadijeh <https://feross.org>
15
15
  * @license MIT
16
16
  */var yO=A90(),Q$=T90(),q90=typeof Symbol==="function"&&typeof Symbol.for==="function"?Symbol.for("nodejs.util.inspect.custom"):null;Oe0.Buffer=I;Oe0.SlowBuffer=Ze0;Oe0.INSPECT_MAX_BYTES=50;var lG=2147483647;Oe0.kMaxLength=lG;I.TYPED_ARRAY_SUPPORT=at0();if(!I.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error==="function")console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function at0(){try{var Z=new Uint8Array(1),J={foo:function(){return 42}};return Object.setPrototypeOf(J,Uint8Array.prototype),Object.setPrototypeOf(Z,J),Z.foo()===42}catch(X){return!1}}Object.defineProperty(I.prototype,"parent",{enumerable:!0,get:function(){if(!I.isBuffer(this))return;return this.buffer}});Object.defineProperty(I.prototype,"offset",{enumerable:!0,get:function(){if(!I.isBuffer(this))return;return this.byteOffset}});function O9(Z){if(Z>lG)throw RangeError('The value "'+Z+'" is invalid for option "size"');var J=new Uint8Array(Z);return Object.setPrototypeOf(J,I.prototype),J}function I(Z,J,X){if(typeof Z==="number"){if(typeof J==="string")throw TypeError('The "string" argument must be of type string. Received type number');return vO(Z)}return R90(Z,J,X)}I.poolSize=8192;function R90(Z,J,X){if(typeof Z==="string")return st0(Z,J);if(ArrayBuffer.isView(Z))return tt0(Z);if(Z==null)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof Z);if(j5(Z,ArrayBuffer)||Z&&j5(Z.buffer,ArrayBuffer))return kO(Z,J,X);if(typeof SharedArrayBuffer<"u"&&(j5(Z,SharedArrayBuffer)||Z&&j5(Z.buffer,SharedArrayBuffer)))return kO(Z,J,X);if(typeof Z==="number")throw TypeError('The "value" argument must not be of type number. Received type number');var $=Z.valueOf&&Z.valueOf();if($!=null&&$!==Z)return I.from($,J,X);var Y=et0(Z);if(Y)return Y;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof Z[Symbol.toPrimitive]==="function")return I.from(Z[Symbol.toPrimitive]("string"),J,X);throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof Z)}I.from=function(Z,J,X){return R90(Z,J,X)};Object.setPrototypeOf(I.prototype,Uint8Array.prototype);Object.setPrototypeOf(I,Uint8Array);function P90(Z){if(typeof Z!=="number")throw TypeError('"size" argument must be of type number');else if(Z<0)throw RangeError('The value "'+Z+'" is invalid for option "size"')}function rt0(Z,J,X){if(P90(Z),Z<=0)return O9(Z);if(J!==void 0)return typeof X==="string"?O9(Z).fill(J,X):O9(Z).fill(J);return O9(Z)}I.alloc=function(Z,J,X){return rt0(Z,J,X)};function vO(Z){return P90(Z),O9(Z<0?0:hO(Z)|0)}I.allocUnsafe=function(Z){return vO(Z)};I.allocUnsafeSlow=function(Z){return vO(Z)};function st0(Z,J){if(typeof J!=="string"||J==="")J="utf8";if(!I.isEncoding(J))throw TypeError("Unknown encoding: "+J);var X=E90(Z,J)|0,$=O9(X),Y=$.write(Z,J);if(Y!==X)$=$.slice(0,Y);return $}function SO(Z){var J=Z.length<0?0:hO(Z.length)|0,X=O9(J);for(var $=0;$<J;$+=1)X[$]=Z[$]&255;return X}function tt0(Z){if(j5(Z,Uint8Array)){var J=new Uint8Array(Z);return kO(J.buffer,J.byteOffset,J.byteLength)}return SO(Z)}function kO(Z,J,X){if(J<0||Z.byteLength<J)throw RangeError('"offset" is outside of buffer bounds');if(Z.byteLength<J+(X||0))throw RangeError('"length" is outside of buffer bounds');var $;if(J===void 0&&X===void 0)$=new Uint8Array(Z);else if(X===void 0)$=new Uint8Array(Z,J);else $=new Uint8Array(Z,J,X);return Object.setPrototypeOf($,I.prototype),$}function et0(Z){if(I.isBuffer(Z)){var J=hO(Z.length)|0,X=O9(J);if(X.length===0)return X;return Z.copy(X,0,0,J),X}if(Z.length!==void 0){if(typeof Z.length!=="number"||fO(Z.length))return O9(0);return SO(Z)}if(Z.type==="Buffer"&&Array.isArray(Z.data))return SO(Z.data)}function hO(Z){if(Z>=lG)throw RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+lG.toString(16)+" bytes");return Z|0}function Ze0(Z){if(+Z!=Z)Z=0;return I.alloc(+Z)}I.isBuffer=function(J){return J!=null&&J._isBuffer===!0&&J!==I.prototype};I.compare=function(J,X){if(j5(J,Uint8Array))J=I.from(J,J.offset,J.byteLength);if(j5(X,Uint8Array))X=I.from(X,X.offset,X.byteLength);if(!I.isBuffer(J)||!I.isBuffer(X))throw TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(J===X)return 0;var $=J.length,Y=X.length;for(var Q=0,W=Math.min($,Y);Q<W;++Q)if(J[Q]!==X[Q]){$=J[Q],Y=X[Q];break}if($<Y)return-1;if(Y<$)return 1;return 0};I.isEncoding=function(J){switch(String(J).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}};I.concat=function(J,X){if(!Array.isArray(J))throw TypeError('"list" argument must be an Array of Buffers');if(J.length===0)return I.alloc(0);var $;if(X===void 0){X=0;for($=0;$<J.length;++$)X+=J[$].length}var Y=I.allocUnsafe(X),Q=0;for($=0;$<J.length;++$){var W=J[$];if(j5(W,Uint8Array))if(Q+W.length>Y.length)I.from(W).copy(Y,Q);else Uint8Array.prototype.set.call(Y,W,Q);else if(!I.isBuffer(W))throw TypeError('"list" argument must be an Array of Buffers');else W.copy(Y,Q);Q+=W.length}return Y};function E90(Z,J){if(I.isBuffer(Z))return Z.length;if(ArrayBuffer.isView(Z)||j5(Z,ArrayBuffer))return Z.byteLength;if(typeof Z!=="string")throw TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof Z);var X=Z.length,$=arguments.length>2&&arguments[2]===!0;if(!$&&X===0)return 0;var Y=!1;for(;;)switch(J){case"ascii":case"latin1":case"binary":return X;case"utf8":case"utf-8":return xO(Z).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return X*2;case"hex":return X>>>1;case"base64":return v90(Z).length;default:if(Y)return $?-1:xO(Z).length;J=(""+J).toLowerCase(),Y=!0}}I.byteLength=E90;function Je0(Z,J,X){var $=!1;if(J===void 0||J<0)J=0;if(J>this.length)return"";if(X===void 0||X>this.length)X=this.length;if(X<=0)return"";if(X>>>=0,J>>>=0,X<=J)return"";if(!Z)Z="utf8";while(!0)switch(Z){case"hex":return Ve0(this,J,X);case"utf8":case"utf-8":return y90(this,J,X);case"ascii":return Ge0(this,J,X);case"latin1":case"binary":return He0(this,J,X);case"base64":return Ke0(this,J,X);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Fe0(this,J,X);default:if($)throw TypeError("Unknown encoding: "+Z);Z=(Z+"").toLowerCase(),$=!0}}I.prototype._isBuffer=!0;function eZ(Z,J,X){var $=Z[J];Z[J]=Z[X],Z[X]=$}I.prototype.swap16=function(){var J=this.length;if(J%2!==0)throw RangeError("Buffer size must be a multiple of 16-bits");for(var X=0;X<J;X+=2)eZ(this,X,X+1);return this};I.prototype.swap32=function(){var J=this.length;if(J%4!==0)throw RangeError("Buffer size must be a multiple of 32-bits");for(var X=0;X<J;X+=4)eZ(this,X,X+3),eZ(this,X+1,X+2);return this};I.prototype.swap64=function(){var J=this.length;if(J%8!==0)throw RangeError("Buffer size must be a multiple of 64-bits");for(var X=0;X<J;X+=8)eZ(this,X,X+7),eZ(this,X+1,X+6),eZ(this,X+2,X+5),eZ(this,X+3,X+4);return this};I.prototype.toString=function(){var J=this.length;if(J===0)return"";if(arguments.length===0)return y90(this,0,J);return Je0.apply(this,arguments)};I.prototype.toLocaleString=I.prototype.toString;I.prototype.equals=function(J){if(!I.isBuffer(J))throw TypeError("Argument must be a Buffer");if(this===J)return!0;return I.compare(this,J)===0};I.prototype.inspect=function(){var J="",X=Oe0.INSPECT_MAX_BYTES;if(J=this.toString("hex",0,X).replace(/(.{2})/g,"$1 ").trim(),this.length>X)J+=" ... ";return"<Buffer "+J+">"};if(q90)I.prototype[q90]=I.prototype.inspect;I.prototype.compare=function(J,X,$,Y,Q){if(j5(J,Uint8Array))J=I.from(J,J.offset,J.byteLength);if(!I.isBuffer(J))throw TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof J);if(X===void 0)X=0;if($===void 0)$=J?J.length:0;if(Y===void 0)Y=0;if(Q===void 0)Q=this.length;if(X<0||$>J.length||Y<0||Q>this.length)throw RangeError("out of range index");if(Y>=Q&&X>=$)return 0;if(Y>=Q)return-1;if(X>=$)return 1;if(X>>>=0,$>>>=0,Y>>>=0,Q>>>=0,this===J)return 0;var W=Q-Y,K=$-X,z=Math.min(W,K),G=this.slice(Y,Q),H=J.slice(X,$);for(var V=0;V<z;++V)if(G[V]!==H[V]){W=G[V],K=H[V];break}if(W<K)return-1;if(K<W)return 1;return 0};function I90(Z,J,X,$,Y){if(Z.length===0)return-1;if(typeof X==="string")$=X,X=0;else if(X>2147483647)X=2147483647;else if(X<-2147483648)X=-2147483648;if(X=+X,fO(X))X=Y?0:Z.length-1;if(X<0)X=Z.length+X;if(X>=Z.length)if(Y)return-1;else X=Z.length-1;else if(X<0)if(Y)X=0;else return-1;if(typeof J==="string")J=I.from(J,$);if(I.isBuffer(J)){if(J.length===0)return-1;return C90(Z,J,X,$,Y)}else if(typeof J==="number"){if(J=J&255,typeof Uint8Array.prototype.indexOf==="function")if(Y)return Uint8Array.prototype.indexOf.call(Z,J,X);else return Uint8Array.prototype.lastIndexOf.call(Z,J,X);return C90(Z,[J],X,$,Y)}throw TypeError("val must be string, number or Buffer")}function C90(Z,J,X,$,Y){var Q=1,W=Z.length,K=J.length;if($!==void 0){if($=String($).toLowerCase(),$==="ucs2"||$==="ucs-2"||$==="utf16le"||$==="utf-16le"){if(Z.length<2||J.length<2)return-1;Q=2,W/=2,K/=2,X/=2}}function z(B,U){if(Q===1)return B[U];else return B.readUInt16BE(U*Q)}var G;if(Y){var H=-1;for(G=X;G<W;G++)if(z(Z,G)===z(J,H===-1?0:G-H)){if(H===-1)H=G;if(G-H+1===K)return H*Q}else{if(H!==-1)G-=G-H;H=-1}}else{if(X+K>W)X=W-K;for(G=X;G>=0;G--){var V=!0;for(var F=0;F<K;F++)if(z(Z,G+F)!==z(J,F)){V=!1;break}if(V)return G}}return-1}I.prototype.includes=function(J,X,$){return this.indexOf(J,X,$)!==-1};I.prototype.indexOf=function(J,X,$){return I90(this,J,X,$,!0)};I.prototype.lastIndexOf=function(J,X,$){return I90(this,J,X,$,!1)};function Xe0(Z,J,X,$){X=Number(X)||0;var Y=Z.length-X;if(!$)$=Y;else if($=Number($),$>Y)$=Y;var Q=J.length;if($>Q/2)$=Q/2;for(var W=0;W<$;++W){var K=parseInt(J.substr(W*2,2),16);if(fO(K))return W;Z[X+W]=K}return W}function $e0(Z,J,X,$){return pG(xO(J,Z.length-X),Z,X,$)}function Ye0(Z,J,X,$){return pG(Le0(J),Z,X,$)}function Qe0(Z,J,X,$){return pG(v90(J),Z,X,$)}function We0(Z,J,X,$){return pG(De0(J,Z.length-X),Z,X,$)}I.prototype.write=function(J,X,$,Y){if(X===void 0)Y="utf8",$=this.length,X=0;else if($===void 0&&typeof X==="string")Y=X,$=this.length,X=0;else if(isFinite(X))if(X=X>>>0,isFinite($)){if($=$>>>0,Y===void 0)Y="utf8"}else Y=$,$=void 0;else throw Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var Q=this.length-X;if($===void 0||$>Q)$=Q;if(J.length>0&&($<0||X<0)||X>this.length)throw RangeError("Attempt to write outside buffer bounds");if(!Y)Y="utf8";var W=!1;for(;;)switch(Y){case"hex":return Xe0(this,J,X,$);case"utf8":case"utf-8":return $e0(this,J,X,$);case"ascii":case"latin1":case"binary":return Ye0(this,J,X,$);case"base64":return Qe0(this,J,X,$);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return We0(this,J,X,$);default:if(W)throw TypeError("Unknown encoding: "+Y);Y=(""+Y).toLowerCase(),W=!0}};I.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function Ke0(Z,J,X){if(J===0&&X===Z.length)return yO.fromByteArray(Z);else return yO.fromByteArray(Z.slice(J,X))}function y90(Z,J,X){X=Math.min(Z.length,X);var $=[],Y=J;while(Y<X){var Q=Z[Y],W=null,K=Q>239?4:Q>223?3:Q>191?2:1;if(Y+K<=X){var z,G,H,V;switch(K){case 1:if(Q<128)W=Q;break;case 2:if(z=Z[Y+1],(z&192)===128){if(V=(Q&31)<<6|z&63,V>127)W=V}break;case 3:if(z=Z[Y+1],G=Z[Y+2],(z&192)===128&&(G&192)===128){if(V=(Q&15)<<12|(z&63)<<6|G&63,V>2047&&(V<55296||V>57343))W=V}break;case 4:if(z=Z[Y+1],G=Z[Y+2],H=Z[Y+3],(z&192)===128&&(G&192)===128&&(H&192)===128){if(V=(Q&15)<<18|(z&63)<<12|(G&63)<<6|H&63,V>65535&&V<1114112)W=V}}}if(W===null)W=65533,K=1;else if(W>65535)W-=65536,$.push(W>>>10&1023|55296),W=56320|W&1023;$.push(W),Y+=K}return ze0($)}var N90=4096;function ze0(Z){var J=Z.length;if(J<=N90)return String.fromCharCode.apply(String,Z);var X="",$=0;while($<J)X+=String.fromCharCode.apply(String,Z.slice($,$+=N90));return X}function Ge0(Z,J,X){var $="";X=Math.min(Z.length,X);for(var Y=J;Y<X;++Y)$+=String.fromCharCode(Z[Y]&127);return $}function He0(Z,J,X){var $="";X=Math.min(Z.length,X);for(var Y=J;Y<X;++Y)$+=String.fromCharCode(Z[Y]);return $}function Ve0(Z,J,X){var $=Z.length;if(!J||J<0)J=0;if(!X||X<0||X>$)X=$;var Y="";for(var Q=J;Q<X;++Q)Y+=_e0[Z[Q]];return Y}function Fe0(Z,J,X){var $=Z.slice(J,X),Y="";for(var Q=0;Q<$.length-1;Q+=2)Y+=String.fromCharCode($[Q]+$[Q+1]*256);return Y}I.prototype.slice=function(J,X){var $=this.length;if(J=~~J,X=X===void 0?$:~~X,J<0){if(J+=$,J<0)J=0}else if(J>$)J=$;if(X<0){if(X+=$,X<0)X=0}else if(X>$)X=$;if(X<J)X=J;var Y=this.subarray(J,X);return Object.setPrototypeOf(Y,I.prototype),Y};function J4(Z,J,X){if(Z%1!==0||Z<0)throw RangeError("offset is not uint");if(Z+J>X)throw RangeError("Trying to access beyond buffer length")}I.prototype.readUintLE=I.prototype.readUIntLE=function(J,X,$){if(J=J>>>0,X=X>>>0,!$)J4(J,X,this.length);var Y=this[J],Q=1,W=0;while(++W<X&&(Q*=256))Y+=this[J+W]*Q;return Y};I.prototype.readUintBE=I.prototype.readUIntBE=function(J,X,$){if(J=J>>>0,X=X>>>0,!$)J4(J,X,this.length);var Y=this[J+--X],Q=1;while(X>0&&(Q*=256))Y+=this[J+--X]*Q;return Y};I.prototype.readUint8=I.prototype.readUInt8=function(J,X){if(J=J>>>0,!X)J4(J,1,this.length);return this[J]};I.prototype.readUint16LE=I.prototype.readUInt16LE=function(J,X){if(J=J>>>0,!X)J4(J,2,this.length);return this[J]|this[J+1]<<8};I.prototype.readUint16BE=I.prototype.readUInt16BE=function(J,X){if(J=J>>>0,!X)J4(J,2,this.length);return this[J]<<8|this[J+1]};I.prototype.readUint32LE=I.prototype.readUInt32LE=function(J,X){if(J=J>>>0,!X)J4(J,4,this.length);return(this[J]|this[J+1]<<8|this[J+2]<<16)+this[J+3]*16777216};I.prototype.readUint32BE=I.prototype.readUInt32BE=function(J,X){if(J=J>>>0,!X)J4(J,4,this.length);return this[J]*16777216+(this[J+1]<<16|this[J+2]<<8|this[J+3])};I.prototype.readIntLE=function(J,X,$){if(J=J>>>0,X=X>>>0,!$)J4(J,X,this.length);var Y=this[J],Q=1,W=0;while(++W<X&&(Q*=256))Y+=this[J+W]*Q;if(Q*=128,Y>=Q)Y-=Math.pow(2,8*X);return Y};I.prototype.readIntBE=function(J,X,$){if(J=J>>>0,X=X>>>0,!$)J4(J,X,this.length);var Y=X,Q=1,W=this[J+--Y];while(Y>0&&(Q*=256))W+=this[J+--Y]*Q;if(Q*=128,W>=Q)W-=Math.pow(2,8*X);return W};I.prototype.readInt8=function(J,X){if(J=J>>>0,!X)J4(J,1,this.length);if(!(this[J]&128))return this[J];return(255-this[J]+1)*-1};I.prototype.readInt16LE=function(J,X){if(J=J>>>0,!X)J4(J,2,this.length);var $=this[J]|this[J+1]<<8;return $&32768?$|4294901760:$};I.prototype.readInt16BE=function(J,X){if(J=J>>>0,!X)J4(J,2,this.length);var $=this[J+1]|this[J]<<8;return $&32768?$|4294901760:$};I.prototype.readInt32LE=function(J,X){if(J=J>>>0,!X)J4(J,4,this.length);return this[J]|this[J+1]<<8|this[J+2]<<16|this[J+3]<<24};I.prototype.readInt32BE=function(J,X){if(J=J>>>0,!X)J4(J,4,this.length);return this[J]<<24|this[J+1]<<16|this[J+2]<<8|this[J+3]};I.prototype.readFloatLE=function(J,X){if(J=J>>>0,!X)J4(J,4,this.length);return Q$.read(this,J,!0,23,4)};I.prototype.readFloatBE=function(J,X){if(J=J>>>0,!X)J4(J,4,this.length);return Q$.read(this,J,!1,23,4)};I.prototype.readDoubleLE=function(J,X){if(J=J>>>0,!X)J4(J,8,this.length);return Q$.read(this,J,!0,52,8)};I.prototype.readDoubleBE=function(J,X){if(J=J>>>0,!X)J4(J,8,this.length);return Q$.read(this,J,!1,52,8)};function z6(Z,J,X,$,Y,Q){if(!I.isBuffer(Z))throw TypeError('"buffer" argument must be a Buffer instance');if(J>Y||J<Q)throw RangeError('"value" argument is out of bounds');if(X+$>Z.length)throw RangeError("Index out of range")}I.prototype.writeUintLE=I.prototype.writeUIntLE=function(J,X,$,Y){if(J=+J,X=X>>>0,$=$>>>0,!Y){var Q=Math.pow(2,8*$)-1;z6(this,J,X,$,Q,0)}var W=1,K=0;this[X]=J&255;while(++K<$&&(W*=256))this[X+K]=J/W&255;return X+$};I.prototype.writeUintBE=I.prototype.writeUIntBE=function(J,X,$,Y){if(J=+J,X=X>>>0,$=$>>>0,!Y){var Q=Math.pow(2,8*$)-1;z6(this,J,X,$,Q,0)}var W=$-1,K=1;this[X+W]=J&255;while(--W>=0&&(K*=256))this[X+W]=J/K&255;return X+$};I.prototype.writeUint8=I.prototype.writeUInt8=function(J,X,$){if(J=+J,X=X>>>0,!$)z6(this,J,X,1,255,0);return this[X]=J&255,X+1};I.prototype.writeUint16LE=I.prototype.writeUInt16LE=function(J,X,$){if(J=+J,X=X>>>0,!$)z6(this,J,X,2,65535,0);return this[X]=J&255,this[X+1]=J>>>8,X+2};I.prototype.writeUint16BE=I.prototype.writeUInt16BE=function(J,X,$){if(J=+J,X=X>>>0,!$)z6(this,J,X,2,65535,0);return this[X]=J>>>8,this[X+1]=J&255,X+2};I.prototype.writeUint32LE=I.prototype.writeUInt32LE=function(J,X,$){if(J=+J,X=X>>>0,!$)z6(this,J,X,4,4294967295,0);return this[X+3]=J>>>24,this[X+2]=J>>>16,this[X+1]=J>>>8,this[X]=J&255,X+4};I.prototype.writeUint32BE=I.prototype.writeUInt32BE=function(J,X,$){if(J=+J,X=X>>>0,!$)z6(this,J,X,4,4294967295,0);return this[X]=J>>>24,this[X+1]=J>>>16,this[X+2]=J>>>8,this[X+3]=J&255,X+4};I.prototype.writeIntLE=function(J,X,$,Y){if(J=+J,X=X>>>0,!Y){var Q=Math.pow(2,8*$-1);z6(this,J,X,$,Q-1,-Q)}var W=0,K=1,z=0;this[X]=J&255;while(++W<$&&(K*=256)){if(J<0&&z===0&&this[X+W-1]!==0)z=1;this[X+W]=(J/K>>0)-z&255}return X+$};I.prototype.writeIntBE=function(J,X,$,Y){if(J=+J,X=X>>>0,!Y){var Q=Math.pow(2,8*$-1);z6(this,J,X,$,Q-1,-Q)}var W=$-1,K=1,z=0;this[X+W]=J&255;while(--W>=0&&(K*=256)){if(J<0&&z===0&&this[X+W+1]!==0)z=1;this[X+W]=(J/K>>0)-z&255}return X+$};I.prototype.writeInt8=function(J,X,$){if(J=+J,X=X>>>0,!$)z6(this,J,X,1,127,-128);if(J<0)J=255+J+1;return this[X]=J&255,X+1};I.prototype.writeInt16LE=function(J,X,$){if(J=+J,X=X>>>0,!$)z6(this,J,X,2,32767,-32768);return this[X]=J&255,this[X+1]=J>>>8,X+2};I.prototype.writeInt16BE=function(J,X,$){if(J=+J,X=X>>>0,!$)z6(this,J,X,2,32767,-32768);return this[X]=J>>>8,this[X+1]=J&255,X+2};I.prototype.writeInt32LE=function(J,X,$){if(J=+J,X=X>>>0,!$)z6(this,J,X,4,2147483647,-2147483648);return this[X]=J&255,this[X+1]=J>>>8,this[X+2]=J>>>16,this[X+3]=J>>>24,X+4};I.prototype.writeInt32BE=function(J,X,$){if(J=+J,X=X>>>0,!$)z6(this,J,X,4,2147483647,-2147483648);if(J<0)J=4294967295+J+1;return this[X]=J>>>24,this[X+1]=J>>>16,this[X+2]=J>>>8,this[X+3]=J&255,X+4};function S90(Z,J,X,$,Y,Q){if(X+$>Z.length)throw RangeError("Index out of range");if(X<0)throw RangeError("Index out of range")}function k90(Z,J,X,$,Y){if(J=+J,X=X>>>0,!Y)S90(Z,J,X,4,340282346638528860000000000000000000000,-340282346638528860000000000000000000000);return Q$.write(Z,J,X,$,23,4),X+4}I.prototype.writeFloatLE=function(J,X,$){return k90(this,J,X,!0,$)};I.prototype.writeFloatBE=function(J,X,$){return k90(this,J,X,!1,$)};function x90(Z,J,X,$,Y){if(J=+J,X=X>>>0,!Y)S90(Z,J,X,8,179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,-179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000);return Q$.write(Z,J,X,$,52,8),X+8}I.prototype.writeDoubleLE=function(J,X,$){return x90(this,J,X,!0,$)};I.prototype.writeDoubleBE=function(J,X,$){return x90(this,J,X,!1,$)};I.prototype.copy=function(J,X,$,Y){if(!I.isBuffer(J))throw TypeError("argument should be a Buffer");if(!$)$=0;if(!Y&&Y!==0)Y=this.length;if(X>=J.length)X=J.length;if(!X)X=0;if(Y>0&&Y<$)Y=$;if(Y===$)return 0;if(J.length===0||this.length===0)return 0;if(X<0)throw RangeError("targetStart out of bounds");if($<0||$>=this.length)throw RangeError("Index out of range");if(Y<0)throw RangeError("sourceEnd out of bounds");if(Y>this.length)Y=this.length;if(J.length-X<Y-$)Y=J.length-X+$;var Q=Y-$;if(this===J&&typeof Uint8Array.prototype.copyWithin==="function")this.copyWithin(X,$,Y);else Uint8Array.prototype.set.call(J,this.subarray($,Y),X);return Q};I.prototype.fill=function(J,X,$,Y){if(typeof J==="string"){if(typeof X==="string")Y=X,X=0,$=this.length;else if(typeof $==="string")Y=$,$=this.length;if(Y!==void 0&&typeof Y!=="string")throw TypeError("encoding must be a string");if(typeof Y==="string"&&!I.isEncoding(Y))throw TypeError("Unknown encoding: "+Y);if(J.length===1){var Q=J.charCodeAt(0);if(Y==="utf8"&&Q<128||Y==="latin1")J=Q}}else if(typeof J==="number")J=J&255;else if(typeof J==="boolean")J=Number(J);if(X<0||this.length<X||this.length<$)throw RangeError("Out of range index");if($<=X)return this;if(X=X>>>0,$=$===void 0?this.length:$>>>0,!J)J=0;var W;if(typeof J==="number")for(W=X;W<$;++W)this[W]=J;else{var K=I.isBuffer(J)?J:I.from(J,Y),z=K.length;if(z===0)throw TypeError('The value "'+J+'" is invalid for argument "value"');for(W=0;W<$-X;++W)this[W+X]=K[W%z]}return this};var Be0=/[^+/0-9A-Za-z-_]/g;function Ue0(Z){if(Z=Z.split("=")[0],Z=Z.trim().replace(Be0,""),Z.length<2)return"";while(Z.length%4!==0)Z=Z+"=";return Z}function xO(Z,J){J=J||1/0;var X,$=Z.length,Y=null,Q=[];for(var W=0;W<$;++W){if(X=Z.charCodeAt(W),X>55295&&X<57344){if(!Y){if(X>56319){if((J-=3)>-1)Q.push(239,191,189);continue}else if(W+1===$){if((J-=3)>-1)Q.push(239,191,189);continue}Y=X;continue}if(X<56320){if((J-=3)>-1)Q.push(239,191,189);Y=X;continue}X=(Y-55296<<10|X-56320)+65536}else if(Y){if((J-=3)>-1)Q.push(239,191,189)}if(Y=null,X<128){if((J-=1)<0)break;Q.push(X)}else if(X<2048){if((J-=2)<0)break;Q.push(X>>6|192,X&63|128)}else if(X<65536){if((J-=3)<0)break;Q.push(X>>12|224,X>>6&63|128,X&63|128)}else if(X<1114112){if((J-=4)<0)break;Q.push(X>>18|240,X>>12&63|128,X>>6&63|128,X&63|128)}else throw Error("Invalid code point")}return Q}function Le0(Z){var J=[];for(var X=0;X<Z.length;++X)J.push(Z.charCodeAt(X)&255);return J}function De0(Z,J){var X,$,Y,Q=[];for(var W=0;W<Z.length;++W){if((J-=2)<0)break;X=Z.charCodeAt(W),$=X>>8,Y=X%256,Q.push(Y),Q.push($)}return Q}function v90(Z){return yO.toByteArray(Ue0(Z))}function pG(Z,J,X,$){for(var Y=0;Y<$;++Y){if(Y+X>=J.length||Y>=Z.length)break;J[Y+X]=Z[Y]}return Y}function j5(Z,J){return Z instanceof J||Z!=null&&Z.constructor!=null&&Z.constructor.name!=null&&Z.constructor.name===J.name}function fO(Z){return Z!==Z}var _e0=function(){var Z="0123456789abcdef",J=Array(256);for(var X=0;X<16;++X){var $=X*16;for(var Y=0;Y<16;++Y)J[$+Y]=Z[X]+Z[Y]}return J}()});var u90=L((HE1,bO)=>{var b90=_90(),m90=j90(),iG=Ae0();function Ae0(){let Z=N("buffer");return Z&&Z.Buffer?Z.Buffer:f90().Buffer}var Te0=iG.from("==","base64");function qe0(Z){let J=!1,X=!1,$=Math.pow(2,31)-1;if(typeof Z==="boolean")J=Z;else Z=Z||{},$=Z.maxInt||Math.pow(2,31)-1,X=!!Z.urlSafe,J=!!Z.fixedLength;W.uuid=b90(),W.decode=d90;let Y=g90(W.uuid,X),Q=Math.floor(Z.startFrom||0);if(isNaN($))throw Error(`maxInt must be a number. recieved ${Z.maxInt}`);if(isNaN(Q)||!($>Q&&Q>=0))throw Error([`when passed, opts.startFrom must be a number between 0 and ${$}.`,"Only the integer part matters.",`- got: ${Z.startFrom}`].join(`
17
17
  `));return W;function W(){let K;if(Q===$)W.uuid=b90(),Y=g90(W.uuid,X),Q=0;if(J)K=Y+`0000000000${Q}`.slice(-10);else K=Y+Q;return Q=Q+1|0,K}}function g90(Z,J){let X=iG.concat([iG.from(m90.parse(Z)),Te0]).toString("base64");if(J)return X.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"-");return X.replace(/=+$/,"/")}function d90(Z,J){if(J=J||{},!!J.urlSafe)Z=Z.replace(/-([^-]*)$/,"/$1").replace(/-/g,"+").replace(/_/g,"/");if(Z.length<22)return null;let $=Z.lastIndexOf("/");if($===-1)return null;let Y=Z.substring(0,$),Q=Number(Z.substring($+1));if(!Y||isNaN(Q))return null;return{uuid:m90.unparse(iG.from(Y+"==","base64")),count:Q}}bO.exports=qe0;bO.exports.decode=d90});var p90=L((VE1,l90)=>{var Ce0=T50(),{pipeline:Ne0}=N("stream"),c90=D9(),Re0=_O(),{through:Pe0}=tZ(),Ee0=mG(),Ie0=u90()();function ye0(Z){this.cmd="connack",this.returnCode=Z.returnCode,this.sessionPresent=Z.sessionPresent}function Se0(Z,J){this.client=Z,this.packet=J}var ke0=[he0,fe0,be0,me0,de0,ue0,mO,ce0],gO=["","unacceptable protocol version","identifier rejected","Server unavailable","bad user name or password","not authorized","keep alive limit exceeded"];function xe0(Z,J,X){clearTimeout(Z._connectTimer),Z._connectTimer=null,Z.connecting=!0,Z.broker.preConnect(Z,J,$);function $(Y,Q){if(!Y&&Q===!0)setImmediate(ve0,Z,J,X);else Z.connecting=!1,X(Y)}}function ve0(Z,J,X){let $=J.clientId,Y=0;if(J.protocolVersion<3||J.protocolVersion>4)Y=1;if(J.protocolVersion===3&&$.length>Z.broker.maxClientsIdLength)Y=2;if(Z.broker.keepaliveLimit&&(!J.keepalive||J.keepalive>Z.broker.keepaliveLimit))Y=6;if(Y>0){let Q=Error(gO[Y]);Q.errorCode=Y,mO({client:Z,returnCode:Y,sessionPresent:!1},X.bind(this,Q));return}Z.id=$||"aedes_"+Ie0(),Z.clean=J.clean,Z.version=J.protocolVersion,Z._will=J.will,Z.broker._series(new Se0(Z,J),ke0,{returnCode:0,sessionPresent:!1},function(Q){if(this.client.connecting=!1,!Q)this.client.connected=!0,this.client.broker.emit("clientReady",Z),this.client.emit("connected");X(Q)})}function he0(Z,J){let X=this.client;X.pause(),X.broker.authenticate(X,this.packet.username,this.packet.password,$);function $(Y,Q){if(X.closed||X.broker.closed)return;if(!Y&&Q)return X._authorized=!0,J();if(Y){let W=Y.returnCode;if(W&&(W>=2&&W<=5))Z.returnCode=W;else Z.returnCode=5;if(!Y.message)Y.message=gO[Z.returnCode]}else Z.returnCode=5,Y=Error(gO[Z.returnCode]);Y.errorCode=Z.returnCode,Z.client=X,mO(Z,X.close.bind(X,J.bind(this,Y)))}}function fe0(Z,J){if(this.packet.keepalive>0){let X=this.client;X._keepaliveInterval=this.packet.keepalive*1500+1,X._keepaliveTimer=Ce0(function(){X.broker.emit("keepaliveTimeout",X),X.emit("error",Error("keep alive timeout"))},X._keepaliveInterval)}J()}function be0(Z,J){let X=this.client;if(!this.packet.clean){X.broker.persistence.subscriptionsByClient({id:X.id,done:J,arg:Z},ge0);return}Z.sessionPresent=!1,X.broker.persistence.cleanSubscriptions(X,J)}function ge0(Z,J,X){if(Z)return X.done(Z);X.arg.subs=J,X.done()}function me0(Z,J){if(Z.subs){Ee0(this.client,{subscriptions:Z.subs},!0,J),Z.sessionPresent=!!Z.subs;return}Z.sessionPresent=!1,J()}function de0(Z,J){let X=this.client;X.will=X._will,X.broker.persistence.delWill(X,function(){if(X.will)X.broker.persistence.putWill(X,X.will,J);else J()})}function ue0(Z,J){let X=this.client;X.broker.registerClient(X),J()}function mO(Z,J){let X=Z.client||this.client,$=new ye0(Z);c90(X,$,function(Y){if(!Y)X.broker.emit("connackSent",$,X),X.connackSent=!0;J(Y)})}function ce0(Z,J){let X=this.client,$=X.broker.persistence,Y=$.outgoingStream(X);X.resume(),Ne0(Y,Pe0(function(W,K,z){let G=new Re0(W,X);G.writeCallback=(H,V)=>z(H),$.outgoingUpdate(X,G,le0)}),J)}function le0(Z,J,X){let $=X.writeCallback;if(Z)return J.emit("error",Z),$();let Y=X.cmd==="publish"?J.broker.authorizeForward(J,X):!0,Q=J.broker.persistence;if(J.clean||!Y)Q.outgoingClearMessageId(J,X,$);else c90(J,X,$)}l90.exports=xe0});var o90=L((FE1,n90)=>{var i90=D9();function pe0(Z){this.cmd="puback",this.messageId=Z.messageId}function ie0(Z){this.cmd="pubrec",this.messageId=Z.messageId}var ne0=[re0,ae0];function oe0(Z,J,X){let $=J.topic,Y;if($.length===0)return Y=Error("empty topic not allowed in PUBLISH"),X(Y);if($.indexOf("#")>-1)return Y=Error("# is not allowed in PUBLISH"),X(Y);if($.indexOf("+")>-1)return Y=Error("+ is not allowed in PUBLISH"),X(Y);Z.broker._series(Z,ne0,J,X)}function ae0(Z,J){let X=this;switch(Z.qos){case 2:X.broker.persistence.incomingStorePacket(X,Z,function($){if($)return J($);i90(X,new ie0(Z),J)});break;case 1:i90(X,new pe0(Z),function($){if($)return J($);X.broker.publish(Z,X,J)});break;case 0:X.broker.publish(Z,X,J);break;default:}}function re0(Z,J){this.broker.authorizePublish(this,Z,J)}n90.exports=oe0});var r90=L((BE1,a90)=>{function se0(Z,J,X){Z.broker.persistence.outgoingClearMessageId(Z,J,function(Y,Q){Z.broker.emit("ack",Q,Z),X(Y)})}a90.exports=se0});var t90=L((UE1,s90)=>{var te0=D9();function ee0(Z,J){this.client=Z,this.packet=J}function Z01(Z){this.cmd="pubcomp",this.messageId=Z.messageId}var J01=[$01,Y01,Q01,W01];function X01(Z,J,X){Z.broker._series(new ee0(Z,J),J01,{},X)}function $01(Z,J){this.client.broker.persistence.incomingGetPacket(this.client,this.packet,$);function $(Y,Q){Z.packet=Q,J(Y)}}function Y01(Z,J){this.client.broker.publish(Z.packet,this.client,J)}function Q01(Z,J){te0(this.client,new Z01(Z.packet),J)}function W01(Z,J){this.client.broker.persistence.incomingDelPacket(this.client,Z.packet,J)}s90.exports=X01});var J70=L((LE1,Z70)=>{var e90=D9();function K01(Z){this.cmd="pubrel",this.messageId=Z.messageId}function z01(Z,J,X){let $=new K01(J);if(Z.clean){e90(Z,$,X);return}Z.broker.persistence.outgoingUpdate(Z,$,Y);function Y(Q){if(Q)X(Q);else e90(Z,$,X)}}Z70.exports=z01});var $70=L((DE1,X70)=>{var G01=D9(),H01={cmd:"pingresp"};function V01(Z,J,X){Z.broker.emit("ping",J,Z),G01(Z,H01,X)}X70.exports=V01});var W70=L((_E1,Q70)=>{var F01=p90(),B01=mG(),U01=wO(),L01=o90(),D01=r90(),_01=t90(),O01=J70(),w01=$70();function j01(Z,J,X){if(J.cmd==="connect"){if(Z.connecting||Z.connected){Y70(Z.conn,J,X);return}F01(Z,J,X);return}if(!Z.connecting&&!Z.connected){Y70(Z.conn,J,X);return}switch(J.cmd){case"publish":L01(Z,J,X);break;case"subscribe":B01(Z,J,!1,X);break;case"unsubscribe":U01(Z,J,X);break;case"pubcomp":case"puback":D01(Z,J,X);break;case"pubrel":_01(Z,J,X);break;case"pubrec":O01(Z,J,X);break;case"pingreq":w01(Z,J,X);break;case"disconnect":Z._disconnected=!0,Z.conn.destroy(),X();return;default:Z.conn.destroy(),X();return}if(Z._keepaliveInterval>0)Z._keepaliveTimer.reschedule(Z._keepaliveInterval)}function Y70(Z,J,X){Z.destroy();let $=Error("Invalid protocol");$.info=J,X($)}Q70.exports=j01});var U70=L((OE1,B70)=>{var M01=bG(),A01=N("events"),T01=N("util"),q01=J50(),z70=lX(),G70=D9(),C01=_O(),N01=mG(),H70=wO(),V70=W70(),{pipeline:R01}=N("stream"),{through:P01}=tZ();B70.exports=M5;function M5(Z,J,X){let $=this;this.closed=!1,this.connecting=!1,this.connected=!1,this.connackSent=!1,this.errored=!1,this.id=null,this.clean=!0,this.version=null,this.subscriptions={},this.duplicates={},this.broker=Z,this.conn=J,J.client=this,this._disconnected=!1,this._authorized=!1,this._parsingBatch=1,this._nextId=Math.ceil(Math.random()*65535),this.req=X,this.connDetails=X?X.connDetails:null,this.will=null,this._will=null,this._parser=M01.parser(),this._parser.client=this,this._parser._queue=[],this._parser.on("packet",y01),this.once("connected",S01);function Y(W){if(W){$.emit("error",W);return}let K=$;if(K._paused)return;if($._parsingBatch--,$._parsingBatch<=0){$._parsingBatch=0;let z=K.conn.read(null);if(z)K._parser.parse(z)}}this._nextBatch=Y,J.on("readable",Y),this.on("error",F70),J.on("error",this.emit.bind(this,"error")),this._parser.on("error",this.emit.bind(this,"error")),J.on("end",this.close.bind(this)),this._eos=q01(this.conn,this.close.bind(this));let Q=(W)=>{if(W.clientId===$.id&&W.nl)return;return E01($,W)&&$.broker.authorizeForward($,W)};this.deliver0=function(K,z){let G=Q(K);if(G)setImmediate(()=>{let H=new z70(G,Z);H.qos=0,G70($,H,function(V){$._onError(V),z()})});else setImmediate(z)},this.deliverQoS=function(K,z){if(K.qos===0){$.deliver0(K,z);return}let G=Q(K);if(G)setImmediate(()=>{let H=new C01(G,$),V=$.subscriptions[H.topic];if(V&&(V.qos||0)<H.qos)H.qos=V.qos;if(H.writeCallback=z,$.clean||H.retain)K70(null,$,H);else Z.persistence.outgoingUpdate($,H,K70)});else if($.clean===!1)$.broker.persistence.outgoingClearMessageId($,K,W$),setImmediate(z);else setImmediate(z)},this._keepaliveTimer=null,this._keepaliveInterval=-1,this._connectTimer=setTimeout(function(){$.emit("error",Error("connect did not arrive in time"))},Z.connectTimeout)}function E01(Z,J){let X=J.brokerId;if(!X)return!0;let $=Z.duplicates,Y=J.brokerCounter,Q=($[X]||0)<Y;if(Q)$[X]=Y;return Q}function K70(Z,J,X){if(Z)J.emit("error",Z),X.writeCallback();else G70(J,X,function($){if($)J.emit("error",$);X.writeCallback()})}function I01(Z){Z.callback()}function F70(Z){if(!Z)return;this.errored=!0,this.conn.removeAllListeners("error"),this.conn.on("error",W$);let J=this.conn._writableState;(typeof J.getBuffer==="function"?J.getBuffer():J.buffer).forEach(I01),this.broker.emit(this.id?"clientError":"connectionError",this,Z),this.close()}T01.inherits(M5,A01);M5.prototype._onError=F70;M5.prototype.publish=function(Z,J){let X=new z70(Z,this.broker),$=this;if(X.qos===0){this.deliver0(X,J);return}if(!this.clean&&this.id)this.broker.persistence.outgoingEnqueue({clientId:this.id},X,function(Q){if(Q)return J(Q);$.deliverQoS(X,J)});else $.deliverQoS(X,J)};M5.prototype.subscribe=function(Z,J){if(!Z.subscriptions){if(!Array.isArray(Z))Z=[Z];Z={subscriptions:Z}}N01(this,Z,!1,J)};M5.prototype.unsubscribe=function(Z,J){if(!Z.unsubscriptions){if(!Array.isArray(Z))Z=[Z];Z={unsubscriptions:Z}}H70(this,Z,J)};M5.prototype.close=function(Z){if(this.closed){if(typeof Z==="function")Z();return}let J=this,X=this.conn;if(this.closed=!0,this._parser.removeAllListeners("packet"),X.removeAllListeners("readable"),this._parser._queue=null,this._keepaliveTimer)this._keepaliveTimer.clear(),this._keepaliveInterval=-1,this._keepaliveTimer=null;if(this._connectTimer)clearTimeout(this._connectTimer),this._connectTimer=null;this._eos(),this._eos=W$,H70(this,{unsubscriptions:Object.keys(this.subscriptions)},$);function $(){let Y=J.will;if(!J._disconnected&&Y)J.broker.authorizePublish(J,Y,function(Q){if(Q)return W();J.broker.publish(Y,J,W);function W(){J.broker.persistence.delWill({id:J.id,brokerId:J.broker.id},W$)}});else if(Y)J.broker.persistence.delWill({id:J.id,brokerId:J.broker.id},W$);if(J.will=null,J._will=null,J.connected=!1,J.connecting=!1,X.removeAllListeners("error"),X.on("error",W$),J.broker.clients[J.id]&&J._authorized)J.broker.unregisterClient(J);if(J.conn.emit("drain"),J.conn.removeAllListeners("drain"),X.destroy(),typeof Z==="function")Z()}};M5.prototype.pause=function(){this._paused=!0};M5.prototype.resume=function(){this._paused=!1,this._nextBatch()};function y01(Z){let J=this.client;if(J._parsingBatch++,J.connackSent||J._parsingBatch===1)V70(J,Z,J._nextBatch);else if(this._queue.length<J.broker.queueLimit)this._queue.push(Z);else this.emit("error",Error("Client queue limit reached"))}function S01(){let Z=this._parser._queue;if(Z){for(let J=0,X=Z.length;J<X;J++)V70(this,Z[J],this._nextBatch);this._parser._queue=null}}M5.prototype.emptyOutgoingQueue=function(Z){let J=this,X=J.broker.persistence;function $(Y,Q,W){X.outgoingClearMessageId(J,Y,W)}R01(X.outgoingStream(J),P01($),Z)};function W$(){}});var L70=L((wE1,k01)=>{k01.exports={name:"aedes",version:"0.51.3",description:"Stream-based MQTT broker",main:"aedes.js",types:"aedes.d.ts",scripts:{lint:"npm run lint:standard && npm run lint:typescript && npm run lint:markdown","lint:fix":"standard --fix && eslint -c types/.eslintrc.json --fix aedes.d.ts types/**/*.ts test/types/**/*.test-d.ts","lint:standard":"standard --verbose | snazzy","lint:typescript":"eslint -c types/.eslintrc.json aedes.d.ts types/**/*.ts test/types/**/*.test-d.ts","lint:markdown":"markdownlint docs/*.md README.md",test:"npm run lint && npm run unit && npm run test:typescript","test:ci":"npm run lint && npm run unit -- --cov --no-check-coverage --coverage-report=lcovonly && npm run test:typescript","test:report":"npm run lint && npm run unit:report && npm run test:typescript","test:typescript":"tsd",unit:"tap -J test/*.js","unit:report":"tap -J test/*.js --cov --coverage-report=html --coverage-report=cobertura | tee out.tap","license-checker":'license-checker --production --onlyAllow="MIT;ISC;BSD-3-Clause;BSD-2-Clause;0BSD"',release:"read -p 'GITHUB_TOKEN: ' GITHUB_TOKEN && export GITHUB_TOKEN=$GITHUB_TOKEN && release-it --disable-metrics"},"release-it":{github:{release:!0},git:{tagName:"v${version}"},hooks:{"before:init":["npm run test:ci"]},npm:{publish:!0}},"pre-commit":["test"],tsd:{directory:"test/types"},standard:{ignore:["types/*","test/types/*"]},repository:{type:"git",url:"git+https://github.com/moscajs/aedes.git"},keywords:["mqtt","broker","server","mqtt-server","stream","streams","publish","subscribe","pubsub","messaging","mosca","mosquitto","iot","internet","of","things"],author:"Matteo Collina <hello@matteocollina.com>",contributors:[{name:"Gavin D'mello",url:"https://github.com/GavinDmello"},{name:"Behrad Zari",url:"https://github.com/behrad"},{name:"Gnought",url:"https://github.com/gnought"},{name:"Daniel Lando",url:"https://github.com/robertsLando"}],license:"MIT",funding:{type:"opencollective",url:"https://opencollective.com/aedes"},bugs:{url:"https://github.com/moscajs/aedes/issues"},homepage:"https://github.com/moscajs/aedes#readme",engines:{node:">=16"},devDependencies:{"@sinonjs/fake-timers":"^11.2.2","@types/node":"^20.11.17","@typescript-eslint/eslint-plugin":"^7.0.1","@typescript-eslint/parser":"^7.0.1","concat-stream":"^2.0.0",duplexify:"^4.1.2","license-checker":"^25.0.1","markdownlint-cli":"^0.41.0",mqtt:"^5.3.5","mqtt-connection":"^4.1.0","pre-commit":"^1.2.2",proxyquire:"^2.1.3","release-it":"^17.0.5",snazzy:"^9.0.0",standard:"^17.1.0",tap:"^16.3.10",tsd:"^0.31.0",typescript:"^5.3.3","websocket-stream":"^5.5.2"},dependencies:{"aedes-packet":"^3.0.0","aedes-persistence":"^9.1.2","end-of-stream":"^1.4.4",fastfall:"^1.5.1",fastparallel:"^2.4.1",fastseries:"^2.0.0",hyperid:"^3.2.0",mqemitter:"^6.0.0","mqtt-packet":"^9.0.0",retimer:"^4.0.0",reusify:"^1.0.4",uuid:"^10.0.0"}}});var j70=L((jE1,w70)=>{var x01=N("events"),v01=N("util"),h01=hD(),f01=ee(),{v4:b01}=$10(),g01=nz(),{pipeline:m01}=N("stream"),d01=lX(),u01=F10(),c01=w10(),l01=U70(),{$SYS_PREFIX:A5,bulk:p01}=tZ();w70.exports=G6.createBroker=G6;var i01={concurrency:100,heartbeatInterval:60000,connectTimeout:30000,decodeProtocol:null,preConnect:e01,authenticate:Z11,authorizePublish:J11,authorizeSubscribe:X11,authorizeForward:$11,published:Y11,trustProxy:!1,trustedProxies:[],queueLimit:42,maxClientsIdLength:23,keepaliveLimit:0};function G6(Z){let J=this;if(!(this instanceof G6))return new G6(Z);Z=Object.assign({},i01,Z),this.id=Z.id||b01(),this.counter=0,this.queueLimit=Z.queueLimit,this.connectTimeout=Z.connectTimeout,this.keepaliveLimit=Z.keepaliveLimit,this.maxClientsIdLength=Z.maxClientsIdLength,this.mq=Z.mq||c01({concurrency:Z.concurrency,matchEmptyLevels:!0}),this.handle=function(H,V){return H.setMaxListeners(Z.concurrency*2),new l01(J,H,V)},this.persistence=Z.persistence||u01(),this.persistence.broker=this,this._parallel=h01(),this._series=f01(),this._enqueuers=g01(o01),this.preConnect=Z.preConnect,this.authenticate=Z.authenticate,this.authorizePublish=Z.authorizePublish,this.authorizeSubscribe=Z.authorizeSubscribe,this.authorizeForward=Z.authorizeForward,this.published=Z.published,this.decodeProtocol=Z.decodeProtocol,this.trustProxy=Z.trustProxy,this.trustedProxies=Z.trustedProxies,this.clients={},this.brokers={};let X=A5+J.id+"/heartbeat",$=A5+J.id+"/birth";this._heartbeatInterval=setInterval(Q,Z.heartbeatInterval);let Y=Buffer.from(J.id,"utf8");J.publish({topic:$,payload:Y},e3);function Q(){J.publish({topic:X,payload:Y},e3)}function W(G){if(J.brokers[G]+3*Z.heartbeatInterval<Date.now())delete J.brokers[G]}this._clearWillInterval=setInterval(function(){Object.keys(J.brokers).forEach(W),m01(J.persistence.streamWill(J.brokers),p01(K),function(H){if(H)J.emit("error",H)})},Z.heartbeatInterval*4);function K(G,H){J._parallel(J,z,G,H)}function z(G,H){if(J.brokers[G.brokerId]!==void 0&&J.brokers[G.brokerId]+3*Z.heartbeatInterval>=Date.now())return H();this.authorizePublish(J.clients[G.clientId]||null,G,function(F){if(F)return B();J.publish(G,B);function B(U){if(U)return H(U);J.persistence.delWill({id:G.clientId,brokerId:G.brokerId},H)}})}this.mq.on(A5+"+/heartbeat",function(H,V){J.brokers[H.payload.toString()]=Date.now(),V()}),this.mq.on(A5+"+/birth",function(H,V){let F=H.payload.toString();if(F!==J.id)for(let B in J.clients)delete J.clients[B].duplicates[F];V()}),this.mq.on(A5+"+/new/clients",function(H,V){let F=H.topic.split("/")[1],B=H.payload.toString();if(J.clients[B]&&F!==J.id)if(J.clients[B].closed)J.deleteClient(B),V();else J.clients[B].close(V);else V()}),this.connectedClients=0,this.closed=!1}v01.inherits(G6,x01);function D70(Z,J){if(Z.retain)this.broker.persistence.storeRetained(Z,J);else J()}function _70(Z,J){if(this.client)Z.clientId=this.client.id;this.broker.mq.emit(Z,J)}function n01(Z,J){let X=this.broker._enqueuers.get();X.complete=J,X.packet=Z,X.topic=Z.topic,X.broker=this.broker,this.broker.persistence.subscriptionsByTopic(Z.topic,X.done)}function o01(){this.next=null,this.complete=null,this.packet=null,this.topic=null,this.broker=null;let Z=this;this.done=function(X,$){let Y=Z.broker;if(X){Y.emit("error",X);return}if(Z.topic.indexOf(A5)===0)$=$.filter(a01);let{packet:Q,complete:W}=Z;Z.packet=null,Z.complete=null,Z.topic=null,Y.persistence.outgoingEnqueueCombi($,Q,W),Y._enqueuers.release(Z)}}function a01(Z){let J=Z.topic.charCodeAt(0);return J!==43&&J!==35}function O70(Z,J){this.broker.published(this.packet,this.client,J),this.broker.emit("publish",this.packet,this.client)}var r01=[D70,_70,O70],s01=[D70,n01,_70,O70];G6.prototype.publish=function(Z,J,X){if(typeof J==="function")X=J,J=null;let $=new d01(Z,this),Y=$.qos>0?s01:r01;this._series(new Q11(this,J,Z),Y,$,X)};G6.prototype.subscribe=function(Z,J,X){this.mq.on(Z,J,X)};G6.prototype.unsubscribe=function(Z,J,X){this.mq.removeListener(Z,J,X)};G6.prototype.registerClient=function(Z){let J=this;if(this.clients[Z.id])this.clients[Z.id].close(function(){J._finishRegisterClient(Z)});else this._finishRegisterClient(Z)};G6.prototype._finishRegisterClient=function(Z){this.connectedClients++,this.clients[Z.id]=Z,this.emit("client",Z),this.publish({topic:A5+this.id+"/new/clients",payload:Buffer.from(Z.id,"utf8")},e3)};G6.prototype.unregisterClient=function(Z){this.deleteClient(Z.id),this.emit("clientDisconnect",Z),this.publish({topic:A5+this.id+"/disconnect/clients",payload:Buffer.from(Z.id,"utf8")},e3)};G6.prototype.deleteClient=function(Z){this.connectedClients--,delete this.clients[Z]};function t01(Z,J){this.clients[Z].close(J)}G6.prototype.close=function(Z=e3){let J=this;if(this.closed)return Z();this.closed=!0,clearInterval(this._heartbeatInterval),clearInterval(this._clearWillInterval),this._parallel(this,t01,Object.keys(this.clients),X);function X(){J.emit("closed"),J.mq.close(Z)}};G6.prototype.version=L70().version;function e01(Z,J,X){X(null,!0)}function Z11(Z,J,X,$){$(null,!0)}function J11(Z,J,X){if(J.topic.startsWith(A5))return X(Error(A5+" topic is reserved"));X(null)}function X11(Z,J,X){X(null,J)}function $11(Z,J){return J}function Y11(Z,J,X){X(null)}function Q11(Z,J,X){this.broker=Z,this.client=J,this.packet=X}function e3(){}});var q70=L((EE1,T70)=>{T70.exports=K11;function K$(Z){if(Z instanceof Buffer)return Buffer.from(Z);return new Z.constructor(Z.buffer.slice(),Z.byteOffset,Z.length)}function K11(Z){if(Z=Z||{},Z.circles)return z11(Z);let J=new Map;if(J.set(Date,(W)=>new Date(W)),J.set(Map,(W,K)=>new Map($(Array.from(W),K))),J.set(Set,(W,K)=>new Set($(Array.from(W),K))),Z.constructorHandlers)for(let W of Z.constructorHandlers)J.set(W[0],W[1]);let X=null;return Z.proto?Q:Y;function $(W,K){let z=Object.keys(W),G=Array(z.length);for(let H=0;H<z.length;H++){let V=z[H],F=W[V];if(typeof F!=="object"||F===null)G[V]=F;else if(F.constructor!==Object&&(X=J.get(F.constructor)))G[V]=X(F,K);else if(ArrayBuffer.isView(F))G[V]=K$(F);else G[V]=K(F)}return G}function Y(W){if(typeof W!=="object"||W===null)return W;if(Array.isArray(W))return $(W,Y);if(W.constructor!==Object&&(X=J.get(W.constructor)))return X(W,Y);let K={};for(let z in W){if(Object.hasOwnProperty.call(W,z)===!1)continue;let G=W[z];if(typeof G!=="object"||G===null)K[z]=G;else if(G.constructor!==Object&&(X=J.get(G.constructor)))K[z]=X(G,Y);else if(ArrayBuffer.isView(G))K[z]=K$(G);else K[z]=Y(G)}return K}function Q(W){if(typeof W!=="object"||W===null)return W;if(Array.isArray(W))return $(W,Q);if(W.constructor!==Object&&(X=J.get(W.constructor)))return X(W,Q);let K={};for(let z in W){let G=W[z];if(typeof G!=="object"||G===null)K[z]=G;else if(G.constructor!==Object&&(X=J.get(G.constructor)))K[z]=X(G,Q);else if(ArrayBuffer.isView(G))K[z]=K$(G);else K[z]=Q(G)}return K}}function z11(Z){let J=[],X=[],$=new Map;if($.set(Date,(z)=>new Date(z)),$.set(Map,(z,G)=>new Map(Q(Array.from(z),G))),$.set(Set,(z,G)=>new Set(Q(Array.from(z),G))),Z.constructorHandlers)for(let z of Z.constructorHandlers)$.set(z[0],z[1]);let Y=null;return Z.proto?K:W;function Q(z,G){let H=Object.keys(z),V=Array(H.length);for(let F=0;F<H.length;F++){let B=H[F],U=z[B];if(typeof U!=="object"||U===null)V[B]=U;else if(U.constructor!==Object&&(Y=$.get(U.constructor)))V[B]=Y(U,G);else if(ArrayBuffer.isView(U))V[B]=K$(U);else{let D=J.indexOf(U);if(D!==-1)V[B]=X[D];else V[B]=G(U)}}return V}function W(z){if(typeof z!=="object"||z===null)return z;if(Array.isArray(z))return Q(z,W);if(z.constructor!==Object&&(Y=$.get(z.constructor)))return Y(z,W);let G={};J.push(z),X.push(G);for(let H in z){if(Object.hasOwnProperty.call(z,H)===!1)continue;let V=z[H];if(typeof V!=="object"||V===null)G[H]=V;else if(V.constructor!==Object&&(Y=$.get(V.constructor)))G[H]=Y(V,W);else if(ArrayBuffer.isView(V))G[H]=K$(V);else{let F=J.indexOf(V);if(F!==-1)G[H]=X[F];else G[H]=W(V)}}return J.pop(),X.pop(),G}function K(z){if(typeof z!=="object"||z===null)return z;if(Array.isArray(z))return Q(z,K);if(z.constructor!==Object&&(Y=$.get(z.constructor)))return Y(z,K);let G={};J.push(z),X.push(G);for(let H in z){let V=z[H];if(typeof V!=="object"||V===null)G[H]=V;else if(V.constructor!==Object&&(Y=$.get(V.constructor)))G[H]=Y(V,K);else if(ArrayBuffer.isView(V))G[H]=K$(V);else{let F=J.indexOf(V);if(F!==-1)G[H]=X[F];else G[H]=K(V)}}return J.pop(),X.pop(),G}}});var N70=L((IE1,C70)=>{C70.exports=q70()()});var E70=L((P70)=>{Object.defineProperty(P70,"__esModule",{value:!0});P70.validateTopic=R70;P70.validateTopics=G11;function R70(Z){let J=Z.split("/");for(let X=0;X<J.length;X++){if(J[X]==="+")continue;if(J[X]==="#")return X===J.length-1;if(J[X].indexOf("+")!==-1||J[X].indexOf("#")!==-1)return!1}return!0}function G11(Z){if(Z.length===0)return"empty_topic_list";for(let J=0;J<Z.length;J++)if(!R70(Z[J]))return Z[J];return null}});var dO=L((y70)=>{Object.defineProperty(y70,"__esModule",{value:!0});var F11=R7(),B11={objectMode:!0},U11={clean:!0};class I70{options;_inflights;constructor(Z){this.options=Z||{},this.options={...U11,...Z},this._inflights=new Map}put(Z,J){if(this._inflights.set(Z.messageId,Z),J)J();return this}createStream(){let Z=new F11.Readable(B11),J=[],X=!1,$=0;return this._inflights.forEach((Y,Q)=>{J.push(Y)}),Z._read=()=>{if(!X&&$<J.length)Z.push(J[$++]);else Z.push(null)},Z.destroy=(Y)=>{if(X)return;return X=!0,setTimeout(()=>{Z.emit("close")},0),Z},Z}del(Z,J){let X=this._inflights.get(Z.messageId);if(X)this._inflights.delete(Z.messageId),J(null,X);else if(J)J(Error("missing packet"));return this}get(Z,J){let X=this._inflights.get(Z.messageId);if(X)J(null,X);else if(J)J(Error("missing packet"));return this}close(Z){if(this.options.clean)this._inflights=null;if(Z)Z()}}y70.default=I70});var x70=L((k70)=>{Object.defineProperty(k70,"__esModule",{value:!0});var S70=[0,16,128,131,135,144,145,151,153],D11=(Z,J,X)=>{Z.log("handlePublish: packet %o",J),X=typeof X<"u"?X:Z.noop;let $=J.topic.toString(),Y=J.payload,{qos:Q}=J,{messageId:W}=J,{options:K}=Z;if(Z.options.protocolVersion===5){let z;if(J.properties)z=J.properties.topicAlias;if(typeof z<"u")if($.length===0)if(z>0&&z<=65535){let G=Z.topicAliasRecv.getTopicByAlias(z);if(G)$=G,Z.log("handlePublish :: topic complemented by alias. topic: %s - alias: %d",$,z);else{Z.log("handlePublish :: unregistered topic alias. alias: %d",z),Z.emit("error",Error("Received unregistered Topic Alias"));return}}else{Z.log("handlePublish :: topic alias out of range. alias: %d",z),Z.emit("error",Error("Received Topic Alias is out of range"));return}else if(Z.topicAliasRecv.put($,z))Z.log("handlePublish :: registered topic: %s - alias: %d",$,z);else{Z.log("handlePublish :: topic alias out of range. alias: %d",z),Z.emit("error",Error("Received Topic Alias is out of range"));return}}switch(Z.log("handlePublish: qos %d",Q),Q){case 2:{K.customHandleAcks($,Y,J,(z,G)=>{if(typeof z==="number")G=z,z=null;if(z)return Z.emit("error",z);if(S70.indexOf(G)===-1)return Z.emit("error",Error("Wrong reason code for pubrec"));if(G)Z._sendPacket({cmd:"pubrec",messageId:W,reasonCode:G},X);else Z.incomingStore.put(J,()=>{Z._sendPacket({cmd:"pubrec",messageId:W},X)})});break}case 1:{K.customHandleAcks($,Y,J,(z,G)=>{if(typeof z==="number")G=z,z=null;if(z)return Z.emit("error",z);if(S70.indexOf(G)===-1)return Z.emit("error",Error("Wrong reason code for puback"));if(!G)Z.emit("message",$,Y,J);Z.handleMessage(J,(H)=>{if(H)return X&&X(H);Z._sendPacket({cmd:"puback",messageId:W,reasonCode:G},X)})});break}case 0:Z.emit("message",$,Y,J),Z.handleMessage(J,X);break;default:Z.log("handlePublish: unknown QoS. Doing nothing.");break}};k70.default=D11});var v70=L((xE1,O11)=>{O11.exports={name:"mqtt",description:"A library for the MQTT protocol",version:"5.14.1",contributors:["Adam Rudd <adamvrr@gmail.com>","Matteo Collina <matteo.collina@gmail.com> (https://github.com/mcollina)","Siarhei Buntsevich <scarry0506@gmail.com> (https://github.com/scarry1992)","Yoseph Maguire <yomaguir@microsoft.com> (https://github.com/YoDaMa)","Daniel Lando <daniel.sorridi@gmail.com> (https://github.com/robertsLando)"],keywords:["mqtt","publish/subscribe","publish","subscribe"],license:"MIT",repository:{type:"git",url:"git://github.com/mqttjs/MQTT.js.git"},main:"./build/index.js",module:"./dist/mqtt.esm.js",bin:{mqtt_pub:"./build/bin/pub.js",mqtt_sub:"./build/bin/sub.js",mqtt:"./build/bin/mqtt.js"},files:["dist/","CONTRIBUTING.md","LICENSE.md","help/","build/"],exports:{".":{"react-native":"./dist/mqtt.esm.js",browser:{import:"./dist/mqtt.esm.js",default:"./dist/mqtt.min.js"},default:"./build/index.js"},"./package.json":"./package.json","./*.map":"./build/*.js.map","./dist/*":"./dist/*.js","./*":"./build/*.js"},types:"build/index.d.ts",typesVersions:{"*":{"*":["./build/index.d.ts"]}},scripts:{lint:"eslint --ext .ts .","lint-fix":"eslint --fix --ext .ts .","build:ts":"rimraf build/ && tsc -p tsconfig.build.json","build:browser":"node esbuild.js",build:"npm run build:ts && npm run build:browser",prepare:"npm run build","unit-test:node":"node -r esbuild-register --test-concurrency 4 --test-reporter=junit --test-reporter-destination=junit.xml --test-reporter=spec --test-reporter-destination=stdout --test test/node/*.ts ","unit-test:browser":"wtr","test:node":"node_modules/.bin/nyc npm run unit-test:node","test:browser":"npm run build && npm run unit-test:browser",test:"npm run test:node",changelog:"conventional-changelog -p angular -i CHANGELOG.md -s && git add CHANGELOG.md","changelog-init":"conventional-changelog -p angular -i CHANGELOG.md -s -r 0",release:"read -p 'GITHUB_TOKEN: ' GITHUB_TOKEN && export GITHUB_TOKEN=$GITHUB_TOKEN && release-it"},"release-it":{github:{release:!0},git:{tagName:"v${version}",commitMessage:"chore(release): ${version}"},hooks:{"before:init":["npm run test"]},npm:{publish:!0},plugins:{"@release-it/conventional-changelog":{preset:"angular",infile:"CHANGELOG.md"}}},publishConfig:{provenance:!0},"pre-commit":["lint"],engines:{node:">=16.0.0"},browser:{"./mqtt.js":"./dist/mqtt.js",fs:!1,tls:!1,net:!1},dependencies:{"@types/readable-stream":"^4.0.21","@types/ws":"^8.18.1",commist:"^3.2.0","concat-stream":"^2.0.0",debug:"^4.4.1","help-me":"^5.0.0","lru-cache":"^10.4.3",minimist:"^1.2.8","mqtt-packet":"^9.0.2","number-allocator":"^1.0.14","readable-stream":"^4.7.0",rfdc:"^1.4.1",socks:"^2.8.6",split2:"^4.2.0","worker-timers":"^8.0.23",ws:"^8.18.3"},devDependencies:{"@eslint/eslintrc":"^3.3.1","@eslint/js":"^9.32.0","@esm-bundle/chai":"^4.3.4","@release-it/conventional-changelog":"^10.0.1","@tsconfig/node20":"^20.1.6","@types/chai":"^5.2.2","@types/node":"^20.17.16","@types/sinon":"^17.0.4","@types/tape":"^5.8.1","@typescript-eslint/eslint-plugin":"^8.38.0","@typescript-eslint/parser":"^8.38.0","@web/test-runner":"^0.20.2","@web/test-runner-playwright":"^0.11.1","aedes-cli":"^0.8.0",chai:"^5.2.1",chokidar:"^4.0.3","conventional-changelog-cli":"^5.0.0","end-of-stream":"^1.4.5",esbuild:"^0.25.8","esbuild-plugin-polyfill-node":"^0.3.0","esbuild-register":"^3.6.0",eslint:"^9.32.0","eslint-config-prettier":"^10.1.8","eslint-plugin-import":"^2.32.0","eslint-plugin-prettier":"^5.5.3",global:"^4.4.0",globals:"^16.3.0","leaked-handles":"^5.2.0",mkdirp:"^3.0.1","mqtt-connection":"^4.1.0","mqtt-level-store":"^3.1.0",nyc:"^17.1.0","pre-commit":"^1.2.2",prettier:"^3.6.2","release-it":"^19.0.4",rimraf:"^6.0.1",should:"^13.2.3",sinon:"^17.0.2",snazzy:"^9.0.0",tape:"^5.9.0","ts-node":"^10.9.2",typescript:"^5.8.3"}}});var ZJ=L((h70)=>{Object.defineProperty(h70,"__esModule",{value:!0});h70.MQTTJS_VERSION=h70.nextTick=h70.ErrorWithSubackPacket=h70.ErrorWithReasonCode=void 0;h70.applyMixin=w11;class uO extends Error{code;constructor(Z,J){super(Z);this.code=J,Object.setPrototypeOf(this,uO.prototype),Object.getPrototypeOf(this).name="ErrorWithReasonCode"}}h70.ErrorWithReasonCode=uO;class cO extends Error{packet;constructor(Z,J){super(Z);this.packet=J,Object.setPrototypeOf(this,cO.prototype),Object.getPrototypeOf(this).name="ErrorWithSubackPacket"}}h70.ErrorWithSubackPacket=cO;function w11(Z,J,X=!1){let $=[J];while(!0){let Y=$[0],Q=Object.getPrototypeOf(Y);if(Q?.prototype)$.unshift(Q);else break}for(let Y of $)for(let Q of Object.getOwnPropertyNames(Y.prototype))if(X||Q!=="constructor")Object.defineProperty(Z.prototype,Q,Object.getOwnPropertyDescriptor(Y.prototype,Q)??Object.create(null))}h70.nextTick=typeof process?.nextTick==="function"?process.nextTick:(Z)=>{setTimeout(Z,0)};h70.MQTTJS_VERSION=v70().version});var JQ=L((g70)=>{Object.defineProperty(g70,"__esModule",{value:!0});g70.ReasonCodes=void 0;var b70=ZJ();g70.ReasonCodes={0:"",1:"Unacceptable protocol version",2:"Identifier rejected",3:"Server unavailable",4:"Bad username or password",5:"Not authorized",16:"No matching subscribers",17:"No subscription existed",128:"Unspecified error",129:"Malformed Packet",130:"Protocol Error",131:"Implementation specific error",132:"Unsupported Protocol Version",133:"Client Identifier not valid",134:"Bad User Name or Password",135:"Not authorized",136:"Server unavailable",137:"Server busy",138:"Banned",139:"Server shutting down",140:"Bad authentication method",141:"Keep Alive timeout",142:"Session taken over",143:"Topic Filter invalid",144:"Topic Name invalid",145:"Packet identifier in use",146:"Packet Identifier not found",147:"Receive Maximum exceeded",148:"Topic Alias invalid",149:"Packet too large",150:"Message rate too high",151:"Quota exceeded",152:"Administrative action",153:"Payload format invalid",154:"Retain not supported",155:"QoS not supported",156:"Use another server",157:"Server moved",158:"Shared Subscriptions not supported",159:"Connection rate exceeded",160:"Maximum connect time",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"};var q11=(Z,J)=>{let{messageId:X}=J,$=J.cmd,Y=null,Q=Z.outgoing[X]?Z.outgoing[X].cb:null,W=null;if(!Q){Z.log("_handleAck :: Server sent an ack in error. Ignoring.");return}switch(Z.log("_handleAck :: packet type",$),$){case"pubcomp":case"puback":{let K=J.reasonCode;if(K&&K>0&&K!==16)W=new b70.ErrorWithReasonCode(`Publish error: ${g70.ReasonCodes[K]}`,K),Z._removeOutgoingAndStoreMessage(X,()=>{Q(W,J)});else Z._removeOutgoingAndStoreMessage(X,Q);break}case"pubrec":{Y={cmd:"pubrel",qos:2,messageId:X};let K=J.reasonCode;if(K&&K>0&&K!==16)W=new b70.ErrorWithReasonCode(`Publish error: ${g70.ReasonCodes[K]}`,K),Z._removeOutgoingAndStoreMessage(X,()=>{Q(W,J)});else Z._sendPacket(Y);break}case"suback":{delete Z.outgoing[X],Z.messageIdProvider.deallocate(X);let K=J.granted;for(let z=0;z<K.length;z++){let G=K[z];if((G&128)!==0){W=Error(`Subscribe error: ${g70.ReasonCodes[G]}`),W.code=G;let H=Z.messageIdToTopic[X];if(H)H.forEach((V)=>{delete Z._resubscribeTopics[V]})}}delete Z.messageIdToTopic[X],Z._invokeStoreProcessingQueue(),Q(W,J);break}case"unsuback":{delete Z.outgoing[X],Z.messageIdProvider.deallocate(X),Z._invokeStoreProcessingQueue(),Q(null,J);break}default:Z.emit("error",Error("unrecognized packet type"))}if(Z.disconnecting&&Object.keys(Z.outgoing).length===0)Z.emit("outgoingEmpty")};g70.default=q11});var u70=L((d70)=>{Object.defineProperty(d70,"__esModule",{value:!0});var m70=ZJ(),N11=JQ(),R11=(Z,J)=>{let{options:X}=Z,$=X.protocolVersion,Y=$===5?J.reasonCode:J.returnCode;if($!==5){let Q=new m70.ErrorWithReasonCode(`Protocol error: Auth packets are only supported in MQTT 5. Your version:${$}`,Y);Z.emit("error",Q);return}Z.handleAuth(J,(Q,W)=>{if(Q){Z.emit("error",Q);return}if(Y===24)Z.reconnecting=!1,Z._sendPacket(W);else{let K=new m70.ErrorWithReasonCode(`Connection refused: ${N11.ReasonCodes[Y]}`,Y);Z.emit("error",K)}})};d70.default=R11});var a70=L((n70)=>{Object.defineProperty(n70,"__esModule",{value:!0});n70.LRUCache=void 0;var z$=typeof performance==="object"&&performance&&typeof performance.now==="function"?performance:Date,l70=new Set,lO=typeof process==="object"&&!!process?process:{},p70=(Z,J,X,$)=>{typeof lO.emitWarning==="function"?lO.emitWarning(Z,J,X,$):console.error(`[${X}] ${J}: ${Z}`)},oG=globalThis.AbortController,c70=globalThis.AbortSignal;if(typeof oG>"u"){c70=class{onabort;_onabort=[];reason;aborted=!1;addEventListener($,Y){this._onabort.push(Y)}},oG=class{constructor(){J()}signal=new c70;abort($){if(this.signal.aborted)return;this.signal.reason=$,this.signal.aborted=!0;for(let Y of this.signal._onabort)Y($);this.signal.onabort?.($)}};let Z=lO.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",J=()=>{if(!Z)return;Z=!1,p70("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",J)}}var E11=(Z)=>!l70.has(Z),bE1=Symbol("type"),S7=(Z)=>Z&&Z===Math.floor(Z)&&Z>0&&isFinite(Z),i70=(Z)=>!S7(Z)?null:Z<=Math.pow(2,8)?Uint8Array:Z<=Math.pow(2,16)?Uint16Array:Z<=Math.pow(2,32)?Uint32Array:Z<=Number.MAX_SAFE_INTEGER?XQ:null;class XQ extends Array{constructor(Z){super(Z);this.fill(0)}}class G${heap;length;static#J=!1;static create(Z){let J=i70(Z);if(!J)return[];G$.#J=!0;let X=new G$(Z,J);return G$.#J=!1,X}constructor(Z,J){if(!G$.#J)throw TypeError("instantiate Stack using Stack.create(n)");this.heap=new J(Z),this.length=0}push(Z){this.heap[this.length++]=Z}pop(){return this.heap[--this.length]}}class pO{#J;#X;#G;#$;#Y;#B;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#Q;#H;#K;#W;#Z;#L;#D;#F;#V;#j;#U;#M;#A;#O;#T;#P;#_;static unsafeExposeInternals(Z){return{starts:Z.#A,ttls:Z.#O,sizes:Z.#M,keyMap:Z.#K,keyList:Z.#W,valList:Z.#Z,next:Z.#L,prev:Z.#D,get head(){return Z.#F},get tail(){return Z.#V},free:Z.#j,isBackgroundFetch:(J)=>Z.#z(J),backgroundFetch:(J,X,$,Y)=>Z.#x(J,X,$,Y),moveToTail:(J)=>Z.#y(J),indexes:(J)=>Z.#q(J),rindexes:(J)=>Z.#C(J),isStale:(J)=>Z.#w(J)}}get max(){return this.#J}get maxSize(){return this.#X}get calculatedSize(){return this.#H}get size(){return this.#Q}get fetchMethod(){return this.#Y}get memoMethod(){return this.#B}get dispose(){return this.#G}get disposeAfter(){return this.#$}constructor(Z){let{max:J=0,ttl:X,ttlResolution:$=1,ttlAutopurge:Y,updateAgeOnGet:Q,updateAgeOnHas:W,allowStale:K,dispose:z,disposeAfter:G,noDisposeOnSet:H,noUpdateTTL:V,maxSize:F=0,maxEntrySize:B=0,sizeCalculation:U,fetchMethod:D,memoMethod:_,noDeleteOnFetchRejection:O,noDeleteOnStaleGet:w,allowStaleOnFetchRejection:j,allowStaleOnFetchAbort:q,ignoreFetchAbort:R}=Z;if(J!==0&&!S7(J))throw TypeError("max option must be a nonnegative integer");let T=J?i70(J):Array;if(!T)throw Error("invalid max value: "+J);if(this.#J=J,this.#X=F,this.maxEntrySize=B||this.#X,this.sizeCalculation=U,this.sizeCalculation){if(!this.#X&&!this.maxEntrySize)throw TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!=="function")throw TypeError("sizeCalculation set to non-function")}if(_!==void 0&&typeof _!=="function")throw TypeError("memoMethod must be a function if defined");if(this.#B=_,D!==void 0&&typeof D!=="function")throw TypeError("fetchMethod must be a function if specified");if(this.#Y=D,this.#P=!!D,this.#K=new Map,this.#W=Array(J).fill(void 0),this.#Z=Array(J).fill(void 0),this.#L=new T(J),this.#D=new T(J),this.#F=0,this.#V=0,this.#j=G$.create(J),this.#Q=0,this.#H=0,typeof z==="function")this.#G=z;if(typeof G==="function")this.#$=G,this.#U=[];else this.#$=void 0,this.#U=void 0;if(this.#T=!!this.#G,this.#_=!!this.#$,this.noDisposeOnSet=!!H,this.noUpdateTTL=!!V,this.noDeleteOnFetchRejection=!!O,this.allowStaleOnFetchRejection=!!j,this.allowStaleOnFetchAbort=!!q,this.ignoreFetchAbort=!!R,this.maxEntrySize!==0){if(this.#X!==0){if(!S7(this.#X))throw TypeError("maxSize must be a positive integer if specified")}if(!S7(this.maxEntrySize))throw TypeError("maxEntrySize must be a positive integer if specified");this.#d()}if(this.allowStale=!!K,this.noDeleteOnStaleGet=!!w,this.updateAgeOnGet=!!Q,this.updateAgeOnHas=!!W,this.ttlResolution=S7($)||$===0?$:1,this.ttlAutopurge=!!Y,this.ttl=X||0,this.ttl){if(!S7(this.ttl))throw TypeError("ttl must be a positive integer if specified");this.#v()}if(this.#J===0&&this.ttl===0&&this.#X===0)throw TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#J&&!this.#X){if(E11("LRU_CACHE_UNBOUNDED"))l70.add("LRU_CACHE_UNBOUNDED"),p70("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning","LRU_CACHE_UNBOUNDED",pO)}}getRemainingTTL(Z){return this.#K.has(Z)?1/0:0}#v(){let Z=new XQ(this.#J),J=new XQ(this.#J);this.#O=Z,this.#A=J,this.#h=(Y,Q,W=z$.now())=>{if(J[Y]=Q!==0?W:0,Z[Y]=Q,Q!==0&&this.ttlAutopurge){let K=setTimeout(()=>{if(this.#w(Y))this.#N(this.#W[Y],"expire")},Q+1);if(K.unref)K.unref()}},this.#E=(Y)=>{J[Y]=Z[Y]!==0?z$.now():0},this.#R=(Y,Q)=>{if(Z[Q]){let W=Z[Q],K=J[Q];if(!W||!K)return;Y.ttl=W,Y.start=K,Y.now=X||$();let z=Y.now-K;Y.remainingTTL=W-z}};let X=0,$=()=>{let Y=z$.now();if(this.ttlResolution>0){X=Y;let Q=setTimeout(()=>X=0,this.ttlResolution);if(Q.unref)Q.unref()}return Y};this.getRemainingTTL=(Y)=>{let Q=this.#K.get(Y);if(Q===void 0)return 0;let W=Z[Q],K=J[Q];if(!W||!K)return 1/0;let z=(X||$())-K;return W-z},this.#w=(Y)=>{let Q=J[Y],W=Z[Y];return!!W&&!!Q&&(X||$())-Q>W}}#E=()=>{};#R=()=>{};#h=()=>{};#w=()=>!1;#d(){let Z=new XQ(this.#J);this.#H=0,this.#M=Z,this.#I=(J)=>{this.#H-=Z[J],Z[J]=0},this.#f=(J,X,$,Y)=>{if(this.#z(X))return 0;if(!S7($))if(Y){if(typeof Y!=="function")throw TypeError("sizeCalculation must be a function");if($=Y(X,J),!S7($))throw TypeError("sizeCalculation return invalid (expect positive integer)")}else throw TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return $},this.#S=(J,X,$)=>{if(Z[J]=X,this.#X){let Y=this.#X-Z[J];while(this.#H>Y)this.#k(!0)}if(this.#H+=Z[J],$)$.entrySize=X,$.totalCalculatedSize=this.#H}}#I=(Z)=>{};#S=(Z,J,X)=>{};#f=(Z,J,X,$)=>{if(X||$)throw TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#q({allowStale:Z=this.allowStale}={}){if(this.#Q)for(let J=this.#V;;){if(!this.#b(J))break;if(Z||!this.#w(J))yield J;if(J===this.#F)break;else J=this.#D[J]}}*#C({allowStale:Z=this.allowStale}={}){if(this.#Q)for(let J=this.#F;;){if(!this.#b(J))break;if(Z||!this.#w(J))yield J;if(J===this.#V)break;else J=this.#L[J]}}#b(Z){return Z!==void 0&&this.#K.get(this.#W[Z])===Z}*entries(){for(let Z of this.#q())if(this.#Z[Z]!==void 0&&this.#W[Z]!==void 0&&!this.#z(this.#Z[Z]))yield[this.#W[Z],this.#Z[Z]]}*rentries(){for(let Z of this.#C())if(this.#Z[Z]!==void 0&&this.#W[Z]!==void 0&&!this.#z(this.#Z[Z]))yield[this.#W[Z],this.#Z[Z]]}*keys(){for(let Z of this.#q()){let J=this.#W[Z];if(J!==void 0&&!this.#z(this.#Z[Z]))yield J}}*rkeys(){for(let Z of this.#C()){let J=this.#W[Z];if(J!==void 0&&!this.#z(this.#Z[Z]))yield J}}*values(){for(let Z of this.#q())if(this.#Z[Z]!==void 0&&!this.#z(this.#Z[Z]))yield this.#Z[Z]}*rvalues(){for(let Z of this.#C())if(this.#Z[Z]!==void 0&&!this.#z(this.#Z[Z]))yield this.#Z[Z]}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(Z,J={}){for(let X of this.#q()){let $=this.#Z[X],Y=this.#z($)?$.__staleWhileFetching:$;if(Y===void 0)continue;if(Z(Y,this.#W[X],this))return this.get(this.#W[X],J)}}forEach(Z,J=this){for(let X of this.#q()){let $=this.#Z[X],Y=this.#z($)?$.__staleWhileFetching:$;if(Y===void 0)continue;Z.call(J,Y,this.#W[X],this)}}rforEach(Z,J=this){for(let X of this.#C()){let $=this.#Z[X],Y=this.#z($)?$.__staleWhileFetching:$;if(Y===void 0)continue;Z.call(J,Y,this.#W[X],this)}}purgeStale(){let Z=!1;for(let J of this.#C({allowStale:!0}))if(this.#w(J))this.#N(this.#W[J],"expire"),Z=!0;return Z}info(Z){let J=this.#K.get(Z);if(J===void 0)return;let X=this.#Z[J],$=this.#z(X)?X.__staleWhileFetching:X;if($===void 0)return;let Y={value:$};if(this.#O&&this.#A){let Q=this.#O[J],W=this.#A[J];if(Q&&W){let K=Q-(z$.now()-W);Y.ttl=K,Y.start=Date.now()}}if(this.#M)Y.size=this.#M[J];return Y}dump(){let Z=[];for(let J of this.#q({allowStale:!0})){let X=this.#W[J],$=this.#Z[J],Y=this.#z($)?$.__staleWhileFetching:$;if(Y===void 0||X===void 0)continue;let Q={value:Y};if(this.#O&&this.#A){Q.ttl=this.#O[J];let W=z$.now()-this.#A[J];Q.start=Math.floor(Date.now()-W)}if(this.#M)Q.size=this.#M[J];Z.unshift([X,Q])}return Z}load(Z){this.clear();for(let[J,X]of Z){if(X.start){let $=Date.now()-X.start;X.start=z$.now()-$}this.set(J,X.value,X)}}set(Z,J,X={}){if(J===void 0)return this.delete(Z),this;let{ttl:$=this.ttl,start:Y,noDisposeOnSet:Q=this.noDisposeOnSet,sizeCalculation:W=this.sizeCalculation,status:K}=X,{noUpdateTTL:z=this.noUpdateTTL}=X,G=this.#f(Z,J,X.size||0,W);if(this.maxEntrySize&&G>this.maxEntrySize){if(K)K.set="miss",K.maxEntrySizeExceeded=!0;return this.#N(Z,"set"),this}let H=this.#Q===0?void 0:this.#K.get(Z);if(H===void 0){if(H=this.#Q===0?this.#V:this.#j.length!==0?this.#j.pop():this.#Q===this.#J?this.#k(!1):this.#Q,this.#W[H]=Z,this.#Z[H]=J,this.#K.set(Z,H),this.#L[this.#V]=H,this.#D[H]=this.#V,this.#V=H,this.#Q++,this.#S(H,G,K),K)K.set="add";z=!1}else{this.#y(H);let V=this.#Z[H];if(J!==V){if(this.#P&&this.#z(V)){V.__abortController.abort(Error("replaced"));let{__staleWhileFetching:F}=V;if(F!==void 0&&!Q){if(this.#T)this.#G?.(F,Z,"set");if(this.#_)this.#U?.push([F,Z,"set"])}}else if(!Q){if(this.#T)this.#G?.(V,Z,"set");if(this.#_)this.#U?.push([V,Z,"set"])}if(this.#I(H),this.#S(H,G,K),this.#Z[H]=J,K){K.set="replace";let F=V&&this.#z(V)?V.__staleWhileFetching:V;if(F!==void 0)K.oldValue=F}}else if(K)K.set="update"}if($!==0&&!this.#O)this.#v();if(this.#O){if(!z)this.#h(H,$,Y);if(K)this.#R(K,H)}if(!Q&&this.#_&&this.#U){let V=this.#U,F;while(F=V?.shift())this.#$?.(...F)}return this}pop(){try{while(this.#Q){let Z=this.#Z[this.#F];if(this.#k(!0),this.#z(Z)){if(Z.__staleWhileFetching)return Z.__staleWhileFetching}else if(Z!==void 0)return Z}}finally{if(this.#_&&this.#U){let Z=this.#U,J;while(J=Z?.shift())this.#$?.(...J)}}}#k(Z){let J=this.#F,X=this.#W[J],$=this.#Z[J];if(this.#P&&this.#z($))$.__abortController.abort(Error("evicted"));else if(this.#T||this.#_){if(this.#T)this.#G?.($,X,"evict");if(this.#_)this.#U?.push([$,X,"evict"])}if(this.#I(J),Z)this.#W[J]=void 0,this.#Z[J]=void 0,this.#j.push(J);if(this.#Q===1)this.#F=this.#V=0,this.#j.length=0;else this.#F=this.#L[J];return this.#K.delete(X),this.#Q--,J}has(Z,J={}){let{updateAgeOnHas:X=this.updateAgeOnHas,status:$}=J,Y=this.#K.get(Z);if(Y!==void 0){let Q=this.#Z[Y];if(this.#z(Q)&&Q.__staleWhileFetching===void 0)return!1;if(!this.#w(Y)){if(X)this.#E(Y);if($)$.has="hit",this.#R($,Y);return!0}else if($)$.has="stale",this.#R($,Y)}else if($)$.has="miss";return!1}peek(Z,J={}){let{allowStale:X=this.allowStale}=J,$=this.#K.get(Z);if($===void 0||!X&&this.#w($))return;let Y=this.#Z[$];return this.#z(Y)?Y.__staleWhileFetching:Y}#x(Z,J,X,$){let Y=J===void 0?void 0:this.#Z[J];if(this.#z(Y))return Y;let Q=new oG,{signal:W}=X;W?.addEventListener("abort",()=>Q.abort(W.reason),{signal:Q.signal});let K={signal:Q.signal,options:X,context:$},z=(U,D=!1)=>{let{aborted:_}=Q.signal,O=X.ignoreFetchAbort&&U!==void 0;if(X.status)if(_&&!D){if(X.status.fetchAborted=!0,X.status.fetchError=Q.signal.reason,O)X.status.fetchAbortIgnored=!0}else X.status.fetchResolved=!0;if(_&&!O&&!D)return H(Q.signal.reason);let w=F;if(this.#Z[J]===F)if(U===void 0)if(w.__staleWhileFetching)this.#Z[J]=w.__staleWhileFetching;else this.#N(Z,"fetch");else{if(X.status)X.status.fetchUpdated=!0;this.set(Z,U,K.options)}return U},G=(U)=>{if(X.status)X.status.fetchRejected=!0,X.status.fetchError=U;return H(U)},H=(U)=>{let{aborted:D}=Q.signal,_=D&&X.allowStaleOnFetchAbort,O=_||X.allowStaleOnFetchRejection,w=O||X.noDeleteOnFetchRejection,j=F;if(this.#Z[J]===F){if(!w||j.__staleWhileFetching===void 0)this.#N(Z,"fetch");else if(!_)this.#Z[J]=j.__staleWhileFetching}if(O){if(X.status&&j.__staleWhileFetching!==void 0)X.status.returnedStale=!0;return j.__staleWhileFetching}else if(j.__returned===j)throw U},V=(U,D)=>{let _=this.#Y?.(Z,Y,K);if(_&&_ instanceof Promise)_.then((O)=>U(O===void 0?void 0:O),D);Q.signal.addEventListener("abort",()=>{if(!X.ignoreFetchAbort||X.allowStaleOnFetchAbort){if(U(void 0),X.allowStaleOnFetchAbort)U=(O)=>z(O,!0)}})};if(X.status)X.status.fetchDispatched=!0;let F=new Promise(V).then(z,G),B=Object.assign(F,{__abortController:Q,__staleWhileFetching:Y,__returned:void 0});if(J===void 0)this.set(Z,B,{...K.options,status:void 0}),J=this.#K.get(Z);else this.#Z[J]=B;return B}#z(Z){if(!this.#P)return!1;let J=Z;return!!J&&J instanceof Promise&&J.hasOwnProperty("__staleWhileFetching")&&J.__abortController instanceof oG}async fetch(Z,J={}){let{allowStale:X=this.allowStale,updateAgeOnGet:$=this.updateAgeOnGet,noDeleteOnStaleGet:Y=this.noDeleteOnStaleGet,ttl:Q=this.ttl,noDisposeOnSet:W=this.noDisposeOnSet,size:K=0,sizeCalculation:z=this.sizeCalculation,noUpdateTTL:G=this.noUpdateTTL,noDeleteOnFetchRejection:H=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:V=this.allowStaleOnFetchRejection,ignoreFetchAbort:F=this.ignoreFetchAbort,allowStaleOnFetchAbort:B=this.allowStaleOnFetchAbort,context:U,forceRefresh:D=!1,status:_,signal:O}=J;if(!this.#P){if(_)_.fetch="get";return this.get(Z,{allowStale:X,updateAgeOnGet:$,noDeleteOnStaleGet:Y,status:_})}let w={allowStale:X,updateAgeOnGet:$,noDeleteOnStaleGet:Y,ttl:Q,noDisposeOnSet:W,size:K,sizeCalculation:z,noUpdateTTL:G,noDeleteOnFetchRejection:H,allowStaleOnFetchRejection:V,allowStaleOnFetchAbort:B,ignoreFetchAbort:F,status:_,signal:O},j=this.#K.get(Z);if(j===void 0){if(_)_.fetch="miss";let q=this.#x(Z,j,w,U);return q.__returned=q}else{let q=this.#Z[j];if(this.#z(q)){let s=X&&q.__staleWhileFetching!==void 0;if(_){if(_.fetch="inflight",s)_.returnedStale=!0}return s?q.__staleWhileFetching:q.__returned=q}let R=this.#w(j);if(!D&&!R){if(_)_.fetch="hit";if(this.#y(j),$)this.#E(j);if(_)this.#R(_,j);return q}let T=this.#x(Z,j,w,U),i=T.__staleWhileFetching!==void 0&&X;if(_){if(_.fetch=R?"stale":"refresh",i&&R)_.returnedStale=!0}return i?T.__staleWhileFetching:T.__returned=T}}async forceFetch(Z,J={}){let X=await this.fetch(Z,J);if(X===void 0)throw Error("fetch() returned undefined");return X}memo(Z,J={}){let X=this.#B;if(!X)throw Error("no memoMethod provided to constructor");let{context:$,forceRefresh:Y,...Q}=J,W=this.get(Z,Q);if(!Y&&W!==void 0)return W;let K=X(Z,W,{options:Q,context:$});return this.set(Z,K,Q),K}get(Z,J={}){let{allowStale:X=this.allowStale,updateAgeOnGet:$=this.updateAgeOnGet,noDeleteOnStaleGet:Y=this.noDeleteOnStaleGet,status:Q}=J,W=this.#K.get(Z);if(W!==void 0){let K=this.#Z[W],z=this.#z(K);if(Q)this.#R(Q,W);if(this.#w(W)){if(Q)Q.get="stale";if(!z){if(!Y)this.#N(Z,"expire");if(Q&&X)Q.returnedStale=!0;return X?K:void 0}else{if(Q&&X&&K.__staleWhileFetching!==void 0)Q.returnedStale=!0;return X?K.__staleWhileFetching:void 0}}else{if(Q)Q.get="hit";if(z)return K.__staleWhileFetching;if(this.#y(W),$)this.#E(W);return K}}else if(Q)Q.get="miss"}#g(Z,J){this.#D[J]=Z,this.#L[Z]=J}#y(Z){if(Z!==this.#V){if(Z===this.#F)this.#F=this.#L[Z];else this.#g(this.#D[Z],this.#L[Z]);this.#g(this.#V,Z),this.#V=Z}}delete(Z){return this.#N(Z,"delete")}#N(Z,J){let X=!1;if(this.#Q!==0){let $=this.#K.get(Z);if($!==void 0)if(X=!0,this.#Q===1)this.#m(J);else{this.#I($);let Y=this.#Z[$];if(this.#z(Y))Y.__abortController.abort(Error("deleted"));else if(this.#T||this.#_){if(this.#T)this.#G?.(Y,Z,J);if(this.#_)this.#U?.push([Y,Z,J])}if(this.#K.delete(Z),this.#W[$]=void 0,this.#Z[$]=void 0,$===this.#V)this.#V=this.#D[$];else if($===this.#F)this.#F=this.#L[$];else{let Q=this.#D[$];this.#L[Q]=this.#L[$];let W=this.#L[$];this.#D[W]=this.#D[$]}this.#Q--,this.#j.push($)}}if(this.#_&&this.#U?.length){let $=this.#U,Y;while(Y=$?.shift())this.#$?.(...Y)}return X}clear(){return this.#m("delete")}#m(Z){for(let J of this.#C({allowStale:!0})){let X=this.#Z[J];if(this.#z(X))X.__abortController.abort(Error("deleted"));else{let $=this.#W[J];if(this.#T)this.#G?.(X,$,Z);if(this.#_)this.#U?.push([X,$,Z])}}if(this.#K.clear(),this.#Z.fill(void 0),this.#W.fill(void 0),this.#O&&this.#A)this.#O.fill(0),this.#A.fill(0);if(this.#M)this.#M.fill(0);if(this.#F=0,this.#V=0,this.#j.length=0,this.#H=0,this.#Q=0,this.#_&&this.#U){let J=this.#U,X;while(X=J?.shift())this.#$?.(...X)}}}n70.LRUCache=pO});var T5=L((t70)=>{Object.defineProperty(t70,"t",{value:!0});t70.ContainerIterator=t70.Container=t70.Base=void 0;class r70{constructor(Z=0){this.iteratorType=Z}equals(Z){return this.o===Z.o}}t70.ContainerIterator=r70;class iO{constructor(){this.i=0}get length(){return this.i}size(){return this.i}empty(){return this.i===0}}t70.Base=iO;class s70 extends iO{}t70.Container=s70});var $Z0=L((JZ0)=>{Object.defineProperty(JZ0,"t",{value:!0});JZ0.default=void 0;var S11=T5();class ZZ0 extends S11.Base{constructor(Z=[]){super();this.S=[];let J=this;Z.forEach(function(X){J.push(X)})}clear(){this.i=0,this.S=[]}push(Z){return this.S.push(Z),this.i+=1,this.i}pop(){if(this.i===0)return;return this.i-=1,this.S.pop()}top(){return this.S[this.i-1]}}var k11=ZZ0;JZ0.default=k11});var KZ0=L((QZ0)=>{Object.defineProperty(QZ0,"t",{value:!0});QZ0.default=void 0;var x11=T5();class YZ0 extends x11.Base{constructor(Z=[]){super();this.j=0,this.q=[];let J=this;Z.forEach(function(X){J.push(X)})}clear(){this.q=[],this.i=this.j=0}push(Z){let J=this.q.length;if(this.j/J>0.5&&this.j+this.i>=J&&J>4096){let X=this.i;for(let $=0;$<X;++$)this.q[$]=this.q[this.j+$];this.j=0,this.q[this.i]=Z}else this.q[this.j+this.i]=Z;return++this.i}pop(){if(this.i===0)return;let Z=this.q[this.j++];return this.i-=1,Z}front(){if(this.i===0)return;return this.q[this.j]}}var v11=YZ0;QZ0.default=v11});var VZ0=L((GZ0)=>{Object.defineProperty(GZ0,"t",{value:!0});GZ0.default=void 0;var h11=T5();class zZ0 extends h11.Base{constructor(Z=[],J=function($,Y){if($>Y)return-1;if($<Y)return 1;return 0},X=!0){super();if(this.v=J,Array.isArray(Z))this.C=X?[...Z]:Z;else{this.C=[];let Y=this;Z.forEach(function(Q){Y.C.push(Q)})}this.i=this.C.length;let $=this.i>>1;for(let Y=this.i-1>>1;Y>=0;--Y)this.k(Y,$)}m(Z){let J=this.C[Z];while(Z>0){let X=Z-1>>1,$=this.C[X];if(this.v($,J)<=0)break;this.C[Z]=$,Z=X}this.C[Z]=J}k(Z,J){let X=this.C[Z];while(Z<J){let $=Z<<1|1,Y=$+1,Q=this.C[$];if(Y<this.i&&this.v(Q,this.C[Y])>0)$=Y,Q=this.C[Y];if(this.v(Q,X)>=0)break;this.C[Z]=Q,Z=$}this.C[Z]=X}clear(){this.i=0,this.C.length=0}push(Z){this.C.push(Z),this.m(this.i),this.i+=1}pop(){if(this.i===0)return;let Z=this.C[0],J=this.C.pop();if(this.i-=1,this.i)this.C[0]=J,this.k(0,this.i>>1);return Z}top(){return this.C[0]}find(Z){return this.C.indexOf(Z)>=0}remove(Z){let J=this.C.indexOf(Z);if(J<0)return!1;if(J===0)this.pop();else if(J===this.i-1)this.C.pop(),this.i-=1;else this.C.splice(J,1,this.C.pop()),this.i-=1,this.m(J),this.k(J,this.i>>1);return!0}updateItem(Z){let J=this.C.indexOf(Z);if(J<0)return!1;return this.m(J),this.k(J,this.i>>1),!0}toArray(){return[...this.C]}}var f11=zZ0;GZ0.default=f11});var aG=L((BZ0)=>{Object.defineProperty(BZ0,"t",{value:!0});BZ0.default=void 0;var b11=T5();class FZ0 extends b11.Container{}var g11=FZ0;BZ0.default=g11});var q5=L((LZ0)=>{Object.defineProperty(LZ0,"t",{value:!0});LZ0.throwIteratorAccessError=m11;function m11(){throw RangeError("Iterator access denied!")}});var nO=L((_Z0)=>{Object.defineProperty(_Z0,"t",{value:!0});_Z0.RandomIterator=void 0;var u11=T5(),rG=q5();class DZ0 extends u11.ContainerIterator{constructor(Z,J){super(J);if(this.o=Z,this.iteratorType===0)this.pre=function(){if(this.o===0)(0,rG.throwIteratorAccessError)();return this.o-=1,this},this.next=function(){if(this.o===this.container.size())(0,rG.throwIteratorAccessError)();return this.o+=1,this};else this.pre=function(){if(this.o===this.container.size()-1)(0,rG.throwIteratorAccessError)();return this.o+=1,this},this.next=function(){if(this.o===-1)(0,rG.throwIteratorAccessError)();return this.o-=1,this}}get pointer(){return this.container.getElementByPos(this.o)}set pointer(Z){this.container.setElementByPos(this.o,Z)}}_Z0.RandomIterator=DZ0});var AZ0=L((jZ0)=>{Object.defineProperty(jZ0,"t",{value:!0});jZ0.default=void 0;var c11=p11(aG()),l11=nO();function p11(Z){return Z&&Z.t?Z:{default:Z}}class JJ extends l11.RandomIterator{constructor(Z,J,X){super(Z,X);this.container=J}copy(){return new JJ(this.o,this.container,this.iteratorType)}}class wZ0 extends c11.default{constructor(Z=[],J=!0){super();if(Array.isArray(Z))this.J=J?[...Z]:Z,this.i=Z.length;else{this.J=[];let X=this;Z.forEach(function($){X.pushBack($)})}}clear(){this.i=0,this.J.length=0}begin(){return new JJ(0,this)}end(){return new JJ(this.i,this)}rBegin(){return new JJ(this.i-1,this,1)}rEnd(){return new JJ(-1,this,1)}front(){return this.J[0]}back(){return this.J[this.i-1]}getElementByPos(Z){if(Z<0||Z>this.i-1)throw RangeError();return this.J[Z]}eraseElementByPos(Z){if(Z<0||Z>this.i-1)throw RangeError();return this.J.splice(Z,1),this.i-=1,this.i}eraseElementByValue(Z){let J=0;for(let X=0;X<this.i;++X)if(this.J[X]!==Z)this.J[J++]=this.J[X];return this.i=this.J.length=J,this.i}eraseElementByIterator(Z){let J=Z.o;return Z=Z.next(),this.eraseElementByPos(J),Z}pushBack(Z){return this.J.push(Z),this.i+=1,this.i}popBack(){if(this.i===0)return;return this.i-=1,this.J.pop()}setElementByPos(Z,J){if(Z<0||Z>this.i-1)throw RangeError();this.J[Z]=J}insert(Z,J,X=1){if(Z<0||Z>this.i)throw RangeError();return this.J.splice(Z,0,...Array(X).fill(J)),this.i+=X,this.i}find(Z){for(let J=0;J<this.i;++J)if(this.J[J]===Z)return new JJ(J,this);return this.end()}reverse(){this.J.reverse()}unique(){let Z=1;for(let J=1;J<this.i;++J)if(this.J[J]!==this.J[J-1])this.J[Z++]=this.J[J];return this.i=this.J.length=Z,this.i}sort(Z){this.J.sort(Z)}forEach(Z){for(let J=0;J<this.i;++J)Z(this.J[J],J,this)}[Symbol.iterator](){return function*(){yield*this.J}.bind(this)()}}var i11=wZ0;jZ0.default=i11});var NZ0=L((qZ0)=>{Object.defineProperty(qZ0,"t",{value:!0});qZ0.default=void 0;var n11=a11(aG()),o11=T5(),XJ=q5();function a11(Z){return Z&&Z.t?Z:{default:Z}}class $J extends o11.ContainerIterator{constructor(Z,J,X,$){super($);if(this.o=Z,this.h=J,this.container=X,this.iteratorType===0)this.pre=function(){if(this.o.L===this.h)(0,XJ.throwIteratorAccessError)();return this.o=this.o.L,this},this.next=function(){if(this.o===this.h)(0,XJ.throwIteratorAccessError)();return this.o=this.o.B,this};else this.pre=function(){if(this.o.B===this.h)(0,XJ.throwIteratorAccessError)();return this.o=this.o.B,this},this.next=function(){if(this.o===this.h)(0,XJ.throwIteratorAccessError)();return this.o=this.o.L,this}}get pointer(){if(this.o===this.h)(0,XJ.throwIteratorAccessError)();return this.o.l}set pointer(Z){if(this.o===this.h)(0,XJ.throwIteratorAccessError)();this.o.l=Z}copy(){return new $J(this.o,this.h,this.container,this.iteratorType)}}class TZ0 extends n11.default{constructor(Z=[]){super();this.h={},this.p=this._=this.h.L=this.h.B=this.h;let J=this;Z.forEach(function(X){J.pushBack(X)})}V(Z){let{L:J,B:X}=Z;if(J.B=X,X.L=J,Z===this.p)this.p=X;if(Z===this._)this._=J;this.i-=1}G(Z,J){let X=J.B,$={l:Z,L:J,B:X};if(J.B=$,X.L=$,J===this.h)this.p=$;if(X===this.h)this._=$;this.i+=1}clear(){this.i=0,this.p=this._=this.h.L=this.h.B=this.h}begin(){return new $J(this.p,this.h,this)}end(){return new $J(this.h,this.h,this)}rBegin(){return new $J(this._,this.h,this,1)}rEnd(){return new $J(this.h,this.h,this,1)}front(){return this.p.l}back(){return this._.l}getElementByPos(Z){if(Z<0||Z>this.i-1)throw RangeError();let J=this.p;while(Z--)J=J.B;return J.l}eraseElementByPos(Z){if(Z<0||Z>this.i-1)throw RangeError();let J=this.p;while(Z--)J=J.B;return this.V(J),this.i}eraseElementByValue(Z){let J=this.p;while(J!==this.h){if(J.l===Z)this.V(J);J=J.B}return this.i}eraseElementByIterator(Z){let J=Z.o;if(J===this.h)(0,XJ.throwIteratorAccessError)();return Z=Z.next(),this.V(J),Z}pushBack(Z){return this.G(Z,this._),this.i}popBack(){if(this.i===0)return;let Z=this._.l;return this.V(this._),Z}pushFront(Z){return this.G(Z,this.h),this.i}popFront(){if(this.i===0)return;let Z=this.p.l;return this.V(this.p),Z}setElementByPos(Z,J){if(Z<0||Z>this.i-1)throw RangeError();let X=this.p;while(Z--)X=X.B;X.l=J}insert(Z,J,X=1){if(Z<0||Z>this.i)throw RangeError();if(X<=0)return this.i;if(Z===0)while(X--)this.pushFront(J);else if(Z===this.i)while(X--)this.pushBack(J);else{let $=this.p;for(let Q=1;Q<Z;++Q)$=$.B;let Y=$.B;this.i+=X;while(X--)$.B={l:J,L:$},$.B.L=$,$=$.B;$.B=Y,Y.L=$}return this.i}find(Z){let J=this.p;while(J!==this.h){if(J.l===Z)return new $J(J,this.h,this);J=J.B}return this.end()}reverse(){if(this.i<=1)return;let Z=this.p,J=this._,X=0;while(X<<1<this.i){let $=Z.l;Z.l=J.l,J.l=$,Z=Z.B,J=J.L,X+=1}}unique(){if(this.i<=1)return this.i;let Z=this.p;while(Z!==this.h){let J=Z;while(J.B!==this.h&&J.l===J.B.l)J=J.B,this.i-=1;Z.B=J.B,Z.B.L=Z,Z=Z.B}return this.i}sort(Z){if(this.i<=1)return;let J=[];this.forEach(function($){J.push($)}),J.sort(Z);let X=this.p;J.forEach(function($){X.l=$,X=X.B})}merge(Z){let J=this;if(this.i===0)Z.forEach(function(X){J.pushBack(X)});else{let X=this.p;Z.forEach(function($){while(X!==J.h&&X.l<=$)X=X.B;J.G($,X.L)})}return this.i}forEach(Z){let J=this.p,X=0;while(J!==this.h)Z(J.l,X++,this),J=J.B}[Symbol.iterator](){return function*(){if(this.i===0)return;let Z=this.p;while(Z!==this.h)yield Z.l,Z=Z.B}.bind(this)()}}var r11=TZ0;qZ0.default=r11});var IZ0=L((PZ0)=>{Object.defineProperty(PZ0,"t",{value:!0});PZ0.default=void 0;var s11=e11(aG()),t11=nO();function e11(Z){return Z&&Z.t?Z:{default:Z}}class YJ extends t11.RandomIterator{constructor(Z,J,X){super(Z,X);this.container=J}copy(){return new YJ(this.o,this.container,this.iteratorType)}}class RZ0 extends s11.default{constructor(Z=[],J=4096){super();this.j=0,this.D=0,this.R=0,this.N=0,this.P=0,this.A=[];let X=(()=>{if(typeof Z.length==="number")return Z.length;if(typeof Z.size==="number")return Z.size;if(typeof Z.size==="function")return Z.size();throw TypeError("Cannot get the length or size of the container")})();this.F=J,this.P=Math.max(Math.ceil(X/this.F),1);for(let Q=0;Q<this.P;++Q)this.A.push(Array(this.F));let $=Math.ceil(X/this.F);this.j=this.R=(this.P>>1)-($>>1),this.D=this.N=this.F-X%this.F>>1;let Y=this;Z.forEach(function(Q){Y.pushBack(Q)})}T(){let Z=[],J=Math.max(this.P>>1,1);for(let X=0;X<J;++X)Z[X]=Array(this.F);for(let X=this.j;X<this.P;++X)Z[Z.length]=this.A[X];for(let X=0;X<this.R;++X)Z[Z.length]=this.A[X];Z[Z.length]=[...this.A[this.R]],this.j=J,this.R=Z.length-1;for(let X=0;X<J;++X)Z[Z.length]=Array(this.F);this.A=Z,this.P=Z.length}O(Z){let J=this.D+Z+1,X=J%this.F,$=X-1,Y=this.j+(J-X)/this.F;if(X===0)Y-=1;if(Y%=this.P,$<0)$+=this.F;return{curNodeBucketIndex:Y,curNodePointerIndex:$}}clear(){this.A=[Array(this.F)],this.P=1,this.j=this.R=this.i=0,this.D=this.N=this.F>>1}begin(){return new YJ(0,this)}end(){return new YJ(this.i,this)}rBegin(){return new YJ(this.i-1,this,1)}rEnd(){return new YJ(-1,this,1)}front(){if(this.i===0)return;return this.A[this.j][this.D]}back(){if(this.i===0)return;return this.A[this.R][this.N]}pushBack(Z){if(this.i){if(this.N<this.F-1)this.N+=1;else if(this.R<this.P-1)this.R+=1,this.N=0;else this.R=0,this.N=0;if(this.R===this.j&&this.N===this.D)this.T()}return this.i+=1,this.A[this.R][this.N]=Z,this.i}popBack(){if(this.i===0)return;let Z=this.A[this.R][this.N];if(this.i!==1)if(this.N>0)this.N-=1;else if(this.R>0)this.R-=1,this.N=this.F-1;else this.R=this.P-1,this.N=this.F-1;return this.i-=1,Z}pushFront(Z){if(this.i){if(this.D>0)this.D-=1;else if(this.j>0)this.j-=1,this.D=this.F-1;else this.j=this.P-1,this.D=this.F-1;if(this.j===this.R&&this.D===this.N)this.T()}return this.i+=1,this.A[this.j][this.D]=Z,this.i}popFront(){if(this.i===0)return;let Z=this.A[this.j][this.D];if(this.i!==1)if(this.D<this.F-1)this.D+=1;else if(this.j<this.P-1)this.j+=1,this.D=0;else this.j=0,this.D=0;return this.i-=1,Z}getElementByPos(Z){if(Z<0||Z>this.i-1)throw RangeError();let{curNodeBucketIndex:J,curNodePointerIndex:X}=this.O(Z);return this.A[J][X]}setElementByPos(Z,J){if(Z<0||Z>this.i-1)throw RangeError();let{curNodeBucketIndex:X,curNodePointerIndex:$}=this.O(Z);this.A[X][$]=J}insert(Z,J,X=1){if(Z<0||Z>this.i)throw RangeError();if(Z===0)while(X--)this.pushFront(J);else if(Z===this.i)while(X--)this.pushBack(J);else{let $=[];for(let Y=Z;Y<this.i;++Y)$.push(this.getElementByPos(Y));this.cut(Z-1);for(let Y=0;Y<X;++Y)this.pushBack(J);for(let Y=0;Y<$.length;++Y)this.pushBack($[Y])}return this.i}cut(Z){if(Z<0)return this.clear(),0;let{curNodeBucketIndex:J,curNodePointerIndex:X}=this.O(Z);return this.R=J,this.N=X,this.i=Z+1,this.i}eraseElementByPos(Z){if(Z<0||Z>this.i-1)throw RangeError();if(Z===0)this.popFront();else if(Z===this.i-1)this.popBack();else{let J=[];for(let $=Z+1;$<this.i;++$)J.push(this.getElementByPos($));this.cut(Z),this.popBack();let X=this;J.forEach(function($){X.pushBack($)})}return this.i}eraseElementByValue(Z){if(this.i===0)return 0;let J=[];for(let $=0;$<this.i;++$){let Y=this.getElementByPos($);if(Y!==Z)J.push(Y)}let X=J.length;for(let $=0;$<X;++$)this.setElementByPos($,J[$]);return this.cut(X-1)}eraseElementByIterator(Z){let J=Z.o;return this.eraseElementByPos(J),Z=Z.next(),Z}find(Z){for(let J=0;J<this.i;++J)if(this.getElementByPos(J)===Z)return new YJ(J,this);return this.end()}reverse(){let Z=0,J=this.i-1;while(Z<J){let X=this.getElementByPos(Z);this.setElementByPos(Z,this.getElementByPos(J)),this.setElementByPos(J,X),Z+=1,J-=1}}unique(){if(this.i<=1)return this.i;let Z=1,J=this.getElementByPos(0);for(let X=1;X<this.i;++X){let $=this.getElementByPos(X);if($!==J)J=$,this.setElementByPos(Z++,$)}while(this.i>Z)this.popBack();return this.i}sort(Z){let J=[];for(let X=0;X<this.i;++X)J.push(this.getElementByPos(X));J.sort(Z);for(let X=0;X<this.i;++X)this.setElementByPos(X,J[X])}shrinkToFit(){if(this.i===0)return;let Z=[];this.forEach(function(J){Z.push(J)}),this.P=Math.max(Math.ceil(this.i/this.F),1),this.i=this.j=this.R=this.D=this.N=0,this.A=[];for(let J=0;J<this.P;++J)this.A.push(Array(this.F));for(let J=0;J<Z.length;++J)this.pushBack(Z[J])}forEach(Z){for(let J=0;J<this.i;++J)Z(this.getElementByPos(J),J,this)}[Symbol.iterator](){return function*(){for(let Z=0;Z<this.i;++Z)yield this.getElementByPos(Z)}.bind(this)()}}var Z41=RZ0;PZ0.default=Z41});var xZ0=L((SZ0)=>{Object.defineProperty(SZ0,"t",{value:!0});SZ0.TreeNodeEnableIndex=SZ0.TreeNode=void 0;class oO{constructor(Z,J){this.ee=1,this.u=void 0,this.l=void 0,this.U=void 0,this.W=void 0,this.tt=void 0,this.u=Z,this.l=J}L(){let Z=this;if(Z.ee===1&&Z.tt.tt===Z)Z=Z.W;else if(Z.U){Z=Z.U;while(Z.W)Z=Z.W}else{let J=Z.tt;while(J.U===Z)Z=J,J=Z.tt;Z=J}return Z}B(){let Z=this;if(Z.W){Z=Z.W;while(Z.U)Z=Z.U;return Z}else{let J=Z.tt;while(J.W===Z)Z=J,J=Z.tt;if(Z.W!==J)return J;else return Z}}te(){let Z=this.tt,J=this.W,X=J.U;if(Z.tt===this)Z.tt=J;else if(Z.U===this)Z.U=J;else Z.W=J;if(J.tt=Z,J.U=this,this.tt=J,this.W=X,X)X.tt=this;return J}se(){let Z=this.tt,J=this.U,X=J.W;if(Z.tt===this)Z.tt=J;else if(Z.U===this)Z.U=J;else Z.W=J;if(J.tt=Z,J.W=this,this.tt=J,this.U=X,X)X.tt=this;return J}}SZ0.TreeNode=oO;class yZ0 extends oO{constructor(){super(...arguments);this.rt=1}te(){let Z=super.te();return this.ie(),Z.ie(),Z}se(){let Z=super.se();return this.ie(),Z.ie(),Z}ie(){if(this.rt=1,this.U)this.rt+=this.U.rt;if(this.W)this.rt+=this.W.rt}}SZ0.TreeNodeEnableIndex=yZ0});var aO=L((bZ0)=>{Object.defineProperty(bZ0,"t",{value:!0});bZ0.default=void 0;var vZ0=xZ0(),X41=T5(),hZ0=q5();class fZ0 extends X41.Container{constructor(Z=function(X,$){if(X<$)return-1;if(X>$)return 1;return 0},J=!1){super();if(this.Y=void 0,this.v=Z,J)this.re=vZ0.TreeNodeEnableIndex,this.M=function(X,$,Y){let Q=this.ne(X,$,Y);if(Q){let W=Q.tt;while(W!==this.h)W.rt+=1,W=W.tt;let K=this.he(Q);if(K){let{parentNode:z,grandParent:G,curNode:H}=K;z.ie(),G.ie(),H.ie()}}return this.i},this.V=function(X){let $=this.fe(X);while($!==this.h)$.rt-=1,$=$.tt};else this.re=vZ0.TreeNode,this.M=function(X,$,Y){let Q=this.ne(X,$,Y);if(Q)this.he(Q);return this.i},this.V=this.fe;this.h=new this.re}X(Z,J){let X=this.h;while(Z){let $=this.v(Z.u,J);if($<0)Z=Z.W;else if($>0)X=Z,Z=Z.U;else return Z}return X}Z(Z,J){let X=this.h;while(Z)if(this.v(Z.u,J)<=0)Z=Z.W;else X=Z,Z=Z.U;return X}$(Z,J){let X=this.h;while(Z){let $=this.v(Z.u,J);if($<0)X=Z,Z=Z.W;else if($>0)Z=Z.U;else return Z}return X}rr(Z,J){let X=this.h;while(Z)if(this.v(Z.u,J)<0)X=Z,Z=Z.W;else Z=Z.U;return X}ue(Z){while(!0){let J=Z.tt;if(J===this.h)return;if(Z.ee===1){Z.ee=0;return}if(Z===J.U){let X=J.W;if(X.ee===1)if(X.ee=0,J.ee=1,J===this.Y)this.Y=J.te();else J.te();else if(X.W&&X.W.ee===1){if(X.ee=J.ee,J.ee=0,X.W.ee=0,J===this.Y)this.Y=J.te();else J.te();return}else if(X.U&&X.U.ee===1)X.ee=1,X.U.ee=0,X.se();else X.ee=1,Z=J}else{let X=J.U;if(X.ee===1)if(X.ee=0,J.ee=1,J===this.Y)this.Y=J.se();else J.se();else if(X.U&&X.U.ee===1){if(X.ee=J.ee,J.ee=0,X.U.ee=0,J===this.Y)this.Y=J.se();else J.se();return}else if(X.W&&X.W.ee===1)X.ee=1,X.W.ee=0,X.te();else X.ee=1,Z=J}}}fe(Z){if(this.i===1)return this.clear(),this.h;let J=Z;while(J.U||J.W){if(J.W){J=J.W;while(J.U)J=J.U}else J=J.U;[Z.u,J.u]=[J.u,Z.u],[Z.l,J.l]=[J.l,Z.l],Z=J}if(this.h.U===J)this.h.U=J.tt;else if(this.h.W===J)this.h.W=J.tt;this.ue(J);let X=J.tt;if(J===X.U)X.U=void 0;else X.W=void 0;return this.i-=1,this.Y.ee=0,X}oe(Z,J){if(Z===void 0)return!1;if(this.oe(Z.U,J))return!0;if(J(Z))return!0;return this.oe(Z.W,J)}he(Z){while(!0){let J=Z.tt;if(J.ee===0)return;let X=J.tt;if(J===X.U){let $=X.W;if($&&$.ee===1){if($.ee=J.ee=0,X===this.Y)return;X.ee=1,Z=X;continue}else if(Z===J.W){if(Z.ee=0,Z.U)Z.U.tt=J;if(Z.W)Z.W.tt=X;if(J.W=Z.U,X.U=Z.W,Z.U=J,Z.W=X,X===this.Y)this.Y=Z,this.h.tt=Z;else{let Y=X.tt;if(Y.U===X)Y.U=Z;else Y.W=Z}return Z.tt=X.tt,J.tt=Z,X.tt=Z,X.ee=1,{parentNode:J,grandParent:X,curNode:Z}}else{if(J.ee=0,X===this.Y)this.Y=X.se();else X.se();X.ee=1}}else{let $=X.U;if($&&$.ee===1){if($.ee=J.ee=0,X===this.Y)return;X.ee=1,Z=X;continue}else if(Z===J.U){if(Z.ee=0,Z.U)Z.U.tt=X;if(Z.W)Z.W.tt=J;if(X.W=Z.U,J.U=Z.W,Z.U=X,Z.W=J,X===this.Y)this.Y=Z,this.h.tt=Z;else{let Y=X.tt;if(Y.U===X)Y.U=Z;else Y.W=Z}return Z.tt=X.tt,J.tt=Z,X.tt=Z,X.ee=1,{parentNode:J,grandParent:X,curNode:Z}}else{if(J.ee=0,X===this.Y)this.Y=X.te();else X.te();X.ee=1}}return}}ne(Z,J,X){if(this.Y===void 0){this.i+=1,this.Y=new this.re(Z,J),this.Y.ee=0,this.Y.tt=this.h,this.h.tt=this.Y,this.h.U=this.Y,this.h.W=this.Y;return}let $,Y=this.h.U,Q=this.v(Y.u,Z);if(Q===0){Y.l=J;return}else if(Q>0)Y.U=new this.re(Z,J),Y.U.tt=Y,$=Y.U,this.h.U=$;else{let W=this.h.W,K=this.v(W.u,Z);if(K===0){W.l=J;return}else if(K<0)W.W=new this.re(Z,J),W.W.tt=W,$=W.W,this.h.W=$;else{if(X!==void 0){let z=X.o;if(z!==this.h){let G=this.v(z.u,Z);if(G===0){z.l=J;return}else if(G>0){let H=z.L(),V=this.v(H.u,Z);if(V===0){H.l=J;return}else if(V<0)if($=new this.re(Z,J),H.W===void 0)H.W=$,$.tt=H;else z.U=$,$.tt=z}}}if($===void 0){$=this.Y;while(!0){let z=this.v($.u,Z);if(z>0){if($.U===void 0){$.U=new this.re(Z,J),$.U.tt=$,$=$.U;break}$=$.U}else if(z<0){if($.W===void 0){$.W=new this.re(Z,J),$.W.tt=$,$=$.W;break}$=$.W}else{$.l=J;return}}}}}return this.i+=1,$}I(Z,J){while(Z){let X=this.v(Z.u,J);if(X<0)Z=Z.W;else if(X>0)Z=Z.U;else return Z}return Z||this.h}clear(){this.i=0,this.Y=void 0,this.h.tt=void 0,this.h.U=this.h.W=void 0}updateKeyByIterator(Z,J){let X=Z.o;if(X===this.h)(0,hZ0.throwIteratorAccessError)();if(this.i===1)return X.u=J,!0;if(X===this.h.U){if(this.v(X.B().u,J)>0)return X.u=J,!0;return!1}if(X===this.h.W){if(this.v(X.L().u,J)<0)return X.u=J,!0;return!1}let $=X.L().u;if(this.v($,J)>=0)return!1;let Y=X.B().u;if(this.v(Y,J)<=0)return!1;return X.u=J,!0}eraseElementByPos(Z){if(Z<0||Z>this.i-1)throw RangeError();let J=0,X=this;return this.oe(this.Y,function($){if(Z===J)return X.V($),!0;return J+=1,!1}),this.i}eraseElementByKey(Z){if(this.i===0)return!1;let J=this.I(this.Y,Z);if(J===this.h)return!1;return this.V(J),!0}eraseElementByIterator(Z){let J=Z.o;if(J===this.h)(0,hZ0.throwIteratorAccessError)();let X=J.W===void 0;if(Z.iteratorType===0){if(X)Z.next()}else if(!X||J.U===void 0)Z.next();return this.V(J),Z}forEach(Z){let J=0;for(let X of this)Z(X,J++,this)}getElementByPos(Z){if(Z<0||Z>this.i-1)throw RangeError();let J,X=0;for(let $ of this){if(X===Z){J=$;break}X+=1}return J}getHeight(){if(this.i===0)return 0;let Z=function(J){if(!J)return 0;return Math.max(Z(J.U),Z(J.W))+1};return Z(this.Y)}}var $41=fZ0;bZ0.default=$41});var rO=L((dZ0)=>{Object.defineProperty(dZ0,"t",{value:!0});dZ0.default=void 0;var Y41=T5(),sG=q5();class mZ0 extends Y41.ContainerIterator{constructor(Z,J,X){super(X);if(this.o=Z,this.h=J,this.iteratorType===0)this.pre=function(){if(this.o===this.h.U)(0,sG.throwIteratorAccessError)();return this.o=this.o.L(),this},this.next=function(){if(this.o===this.h)(0,sG.throwIteratorAccessError)();return this.o=this.o.B(),this};else this.pre=function(){if(this.o===this.h.W)(0,sG.throwIteratorAccessError)();return this.o=this.o.B(),this},this.next=function(){if(this.o===this.h)(0,sG.throwIteratorAccessError)();return this.o=this.o.L(),this}}get index(){let Z=this.o,J=this.h.tt;if(Z===this.h){if(J)return J.rt-1;return 0}let X=0;if(Z.U)X+=Z.U.rt;while(Z!==J){let $=Z.tt;if(Z===$.W){if(X+=1,$.U)X+=$.U.rt}Z=$}return X}}var Q41=mZ0;dZ0.default=Q41});var nZ0=L((pZ0)=>{Object.defineProperty(pZ0,"t",{value:!0});pZ0.default=void 0;var W41=cZ0(aO()),K41=cZ0(rO()),z41=q5();function cZ0(Z){return Z&&Z.t?Z:{default:Z}}class m8 extends K41.default{constructor(Z,J,X,$){super(Z,J,$);this.container=X}get pointer(){if(this.o===this.h)(0,z41.throwIteratorAccessError)();return this.o.u}copy(){return new m8(this.o,this.h,this.container,this.iteratorType)}}class lZ0 extends W41.default{constructor(Z=[],J,X){super(J,X);let $=this;Z.forEach(function(Y){$.insert(Y)})}*K(Z){if(Z===void 0)return;yield*this.K(Z.U),yield Z.u,yield*this.K(Z.W)}begin(){return new m8(this.h.U||this.h,this.h,this)}end(){return new m8(this.h,this.h,this)}rBegin(){return new m8(this.h.W||this.h,this.h,this,1)}rEnd(){return new m8(this.h,this.h,this,1)}front(){return this.h.U?this.h.U.u:void 0}back(){return this.h.W?this.h.W.u:void 0}insert(Z,J){return this.M(Z,void 0,J)}find(Z){let J=this.I(this.Y,Z);return new m8(J,this.h,this)}lowerBound(Z){let J=this.X(this.Y,Z);return new m8(J,this.h,this)}upperBound(Z){let J=this.Z(this.Y,Z);return new m8(J,this.h,this)}reverseLowerBound(Z){let J=this.$(this.Y,Z);return new m8(J,this.h,this)}reverseUpperBound(Z){let J=this.rr(this.Y,Z);return new m8(J,this.h,this)}union(Z){let J=this;return Z.forEach(function(X){J.insert(X)}),this.i}[Symbol.iterator](){return this.K(this.Y)}}var G41=lZ0;pZ0.default=G41});var tZ0=L((rZ0)=>{Object.defineProperty(rZ0,"t",{value:!0});rZ0.default=void 0;var H41=oZ0(aO()),V41=oZ0(rO()),F41=q5();function oZ0(Z){return Z&&Z.t?Z:{default:Z}}class d8 extends V41.default{constructor(Z,J,X,$){super(Z,J,$);this.container=X}get pointer(){if(this.o===this.h)(0,F41.throwIteratorAccessError)();let Z=this;return new Proxy([],{get(J,X){if(X==="0")return Z.o.u;else if(X==="1")return Z.o.l},set(J,X,$){if(X!=="1")throw TypeError("props must be 1");return Z.o.l=$,!0}})}copy(){return new d8(this.o,this.h,this.container,this.iteratorType)}}class aZ0 extends H41.default{constructor(Z=[],J,X){super(J,X);let $=this;Z.forEach(function(Y){$.setElement(Y[0],Y[1])})}*K(Z){if(Z===void 0)return;yield*this.K(Z.U),yield[Z.u,Z.l],yield*this.K(Z.W)}begin(){return new d8(this.h.U||this.h,this.h,this)}end(){return new d8(this.h,this.h,this)}rBegin(){return new d8(this.h.W||this.h,this.h,this,1)}rEnd(){return new d8(this.h,this.h,this,1)}front(){if(this.i===0)return;let Z=this.h.U;return[Z.u,Z.l]}back(){if(this.i===0)return;let Z=this.h.W;return[Z.u,Z.l]}lowerBound(Z){let J=this.X(this.Y,Z);return new d8(J,this.h,this)}upperBound(Z){let J=this.Z(this.Y,Z);return new d8(J,this.h,this)}reverseLowerBound(Z){let J=this.$(this.Y,Z);return new d8(J,this.h,this)}reverseUpperBound(Z){let J=this.rr(this.Y,Z);return new d8(J,this.h,this)}setElement(Z,J,X){return this.M(Z,J,X)}find(Z){let J=this.I(this.Y,Z);return new d8(J,this.h,this)}getElementByKey(Z){return this.I(this.Y,Z).l}union(Z){let J=this;return Z.forEach(function(X){J.setElement(X[0],X[1])}),this.i}[Symbol.iterator](){return this.K(this.Y)}}var B41=aZ0;rZ0.default=B41});var sO=L((eZ0)=>{Object.defineProperty(eZ0,"t",{value:!0});eZ0.default=U41;function U41(Z){let J=typeof Z;return J==="object"&&Z!==null||J==="function"}});var eO=L(($J0)=>{Object.defineProperty($J0,"t",{value:!0});$J0.HashContainerIterator=$J0.HashContainer=void 0;var ZJ0=T5(),tO=D41(sO()),$Q=q5();function D41(Z){return Z&&Z.t?Z:{default:Z}}class JJ0 extends ZJ0.ContainerIterator{constructor(Z,J,X){super(X);if(this.o=Z,this.h=J,this.iteratorType===0)this.pre=function(){if(this.o.L===this.h)(0,$Q.throwIteratorAccessError)();return this.o=this.o.L,this},this.next=function(){if(this.o===this.h)(0,$Q.throwIteratorAccessError)();return this.o=this.o.B,this};else this.pre=function(){if(this.o.B===this.h)(0,$Q.throwIteratorAccessError)();return this.o=this.o.B,this},this.next=function(){if(this.o===this.h)(0,$Q.throwIteratorAccessError)();return this.o=this.o.L,this}}}$J0.HashContainerIterator=JJ0;class XJ0 extends ZJ0.Container{constructor(){super();this.H=[],this.g={},this.HASH_TAG=Symbol("@@HASH_TAG"),Object.setPrototypeOf(this.g,null),this.h={},this.h.L=this.h.B=this.p=this._=this.h}V(Z){let{L:J,B:X}=Z;if(J.B=X,X.L=J,Z===this.p)this.p=X;if(Z===this._)this._=J;this.i-=1}M(Z,J,X){if(X===void 0)X=(0,tO.default)(Z);let $;if(X){let Y=Z[this.HASH_TAG];if(Y!==void 0)return this.H[Y].l=J,this.i;Object.defineProperty(Z,this.HASH_TAG,{value:this.H.length,configurable:!0}),$={u:Z,l:J,L:this._,B:this.h},this.H.push($)}else{let Y=this.g[Z];if(Y)return Y.l=J,this.i;$={u:Z,l:J,L:this._,B:this.h},this.g[Z]=$}if(this.i===0)this.p=$,this.h.B=$;else this._.B=$;return this._=$,this.h.L=$,++this.i}I(Z,J){if(J===void 0)J=(0,tO.default)(Z);if(J){let X=Z[this.HASH_TAG];if(X===void 0)return this.h;return this.H[X]}else return this.g[Z]||this.h}clear(){let Z=this.HASH_TAG;this.H.forEach(function(J){delete J.u[Z]}),this.H=[],this.g={},Object.setPrototypeOf(this.g,null),this.i=0,this.p=this._=this.h.L=this.h.B=this.h}eraseElementByKey(Z,J){let X;if(J===void 0)J=(0,tO.default)(Z);if(J){let $=Z[this.HASH_TAG];if($===void 0)return!1;delete Z[this.HASH_TAG],X=this.H[$],delete this.H[$]}else{if(X=this.g[Z],X===void 0)return!1;delete this.g[Z]}return this.V(X),!0}eraseElementByIterator(Z){let J=Z.o;if(J===this.h)(0,$Q.throwIteratorAccessError)();return this.V(J),Z.next()}eraseElementByPos(Z){if(Z<0||Z>this.i-1)throw RangeError();let J=this.p;while(Z--)J=J.B;return this.V(J),this.i}}$J0.HashContainer=XJ0});var GJ0=L((KJ0)=>{Object.defineProperty(KJ0,"t",{value:!0});KJ0.default=void 0;var QJ0=eO(),O41=q5();class QJ extends QJ0.HashContainerIterator{constructor(Z,J,X,$){super(Z,J,$);this.container=X}get pointer(){if(this.o===this.h)(0,O41.throwIteratorAccessError)();return this.o.u}copy(){return new QJ(this.o,this.h,this.container,this.iteratorType)}}class WJ0 extends QJ0.HashContainer{constructor(Z=[]){super();let J=this;Z.forEach(function(X){J.insert(X)})}begin(){return new QJ(this.p,this.h,this)}end(){return new QJ(this.h,this.h,this)}rBegin(){return new QJ(this._,this.h,this,1)}rEnd(){return new QJ(this.h,this.h,this,1)}front(){return this.p.u}back(){return this._.u}insert(Z,J){return this.M(Z,void 0,J)}getElementByPos(Z){if(Z<0||Z>this.i-1)throw RangeError();let J=this.p;while(Z--)J=J.B;return J.u}find(Z,J){let X=this.I(Z,J);return new QJ(X,this.h,this)}forEach(Z){let J=0,X=this.p;while(X!==this.h)Z(X.u,J++,this),X=X.B}[Symbol.iterator](){return function*(){let Z=this.p;while(Z!==this.h)yield Z.u,Z=Z.B}.bind(this)()}}var w41=WJ0;KJ0.default=w41});var UJ0=L((FJ0)=>{Object.defineProperty(FJ0,"t",{value:!0});FJ0.default=void 0;var HJ0=eO(),j41=A41(sO()),M41=q5();function A41(Z){return Z&&Z.t?Z:{default:Z}}class WJ extends HJ0.HashContainerIterator{constructor(Z,J,X,$){super(Z,J,$);this.container=X}get pointer(){if(this.o===this.h)(0,M41.throwIteratorAccessError)();let Z=this;return new Proxy([],{get(J,X){if(X==="0")return Z.o.u;else if(X==="1")return Z.o.l},set(J,X,$){if(X!=="1")throw TypeError("props must be 1");return Z.o.l=$,!0}})}copy(){return new WJ(this.o,this.h,this.container,this.iteratorType)}}class VJ0 extends HJ0.HashContainer{constructor(Z=[]){super();let J=this;Z.forEach(function(X){J.setElement(X[0],X[1])})}begin(){return new WJ(this.p,this.h,this)}end(){return new WJ(this.h,this.h,this)}rBegin(){return new WJ(this._,this.h,this,1)}rEnd(){return new WJ(this.h,this.h,this,1)}front(){if(this.i===0)return;return[this.p.u,this.p.l]}back(){if(this.i===0)return;return[this._.u,this._.l]}setElement(Z,J,X){return this.M(Z,J,X)}getElementByKey(Z,J){if(J===void 0)J=(0,j41.default)(Z);if(J){let $=Z[this.HASH_TAG];return $!==void 0?this.H[$].l:void 0}let X=this.g[Z];return X?X.l:void 0}getElementByPos(Z){if(Z<0||Z>this.i-1)throw RangeError();let J=this.p;while(Z--)J=J.B;return[J.u,J.l]}find(Z,J){let X=this.I(Z,J);return new WJ(X,this.h,this)}forEach(Z){let J=0,X=this.p;while(X!==this.h)Z([X.u,X.l],J++,this),X=X.B}[Symbol.iterator](){return function*(){let Z=this.p;while(Z!==this.h)yield[Z.u,Z.l],Z=Z.B}.bind(this)()}}var T41=VJ0;FJ0.default=T41});var LJ0=L((W8)=>{Object.defineProperty(W8,"t",{value:!0});Object.defineProperty(W8,"Deque",{enumerable:!0,get:function(){return E41.default}});Object.defineProperty(W8,"HashMap",{enumerable:!0,get:function(){return k41.default}});Object.defineProperty(W8,"HashSet",{enumerable:!0,get:function(){return S41.default}});Object.defineProperty(W8,"LinkList",{enumerable:!0,get:function(){return P41.default}});Object.defineProperty(W8,"OrderedMap",{enumerable:!0,get:function(){return y41.default}});Object.defineProperty(W8,"OrderedSet",{enumerable:!0,get:function(){return I41.default}});Object.defineProperty(W8,"PriorityQueue",{enumerable:!0,get:function(){return N41.default}});Object.defineProperty(W8,"Queue",{enumerable:!0,get:function(){return C41.default}});Object.defineProperty(W8,"Stack",{enumerable:!0,get:function(){return q41.default}});Object.defineProperty(W8,"Vector",{enumerable:!0,get:function(){return R41.default}});var q41=C5($Z0()),C41=C5(KZ0()),N41=C5(VZ0()),R41=C5(AZ0()),P41=C5(NZ0()),E41=C5(IZ0()),I41=C5(nZ0()),y41=C5(tZ0()),S41=C5(GJ0()),k41=C5(UJ0());function C5(Z){return Z&&Z.t?Z:{default:Z}}});var _J0=L((WI1,DJ0)=>{var x41=LJ0().OrderedSet,N5=h6()("number-allocator:trace"),v41=h6()("number-allocator:error");function m4(Z,J){this.low=Z,this.high=J}m4.prototype.equals=function(Z){return this.low===Z.low&&this.high===Z.high};m4.prototype.compare=function(Z){if(this.low<Z.low&&this.high<Z.low)return-1;if(Z.low<this.low&&Z.high<this.low)return 1;return 0};function R5(Z,J){if(!(this instanceof R5))return new R5(Z,J);this.min=Z,this.max=J,this.ss=new x41([],(X,$)=>{return X.compare($)}),N5("Create"),this.clear()}R5.prototype.firstVacant=function(){if(this.ss.size()===0)return null;return this.ss.front().low};R5.prototype.alloc=function(){if(this.ss.size()===0)return N5("alloc():empty"),null;let Z=this.ss.begin(),J=Z.pointer.low,X=Z.pointer.high,$=J;if($+1<=X)this.ss.updateKeyByIterator(Z,new m4(J+1,X));else this.ss.eraseElementByPos(0);return N5("alloc():"+$),$};R5.prototype.use=function(Z){let J=new m4(Z,Z),X=this.ss.lowerBound(J);if(!X.equals(this.ss.end())){let $=X.pointer.low,Y=X.pointer.high;if(X.pointer.equals(J))return this.ss.eraseElementByIterator(X),N5("use():"+Z),!0;if($>Z)return!1;if($===Z)return this.ss.updateKeyByIterator(X,new m4($+1,Y)),N5("use():"+Z),!0;if(Y===Z)return this.ss.updateKeyByIterator(X,new m4($,Y-1)),N5("use():"+Z),!0;return this.ss.updateKeyByIterator(X,new m4(Z+1,Y)),this.ss.insert(new m4($,Z-1)),N5("use():"+Z),!0}return N5("use():failed"),!1};R5.prototype.free=function(Z){if(Z<this.min||Z>this.max){v41("free():"+Z+" is out of range");return}let J=new m4(Z,Z),X=this.ss.upperBound(J);if(X.equals(this.ss.end())){if(X.equals(this.ss.begin())){this.ss.insert(J);return}X.pre();let $=X.pointer.high;if(X.pointer.high+1===Z)this.ss.updateKeyByIterator(X,new m4($,Z));else this.ss.insert(J)}else if(X.equals(this.ss.begin()))if(Z+1===X.pointer.low){let $=X.pointer.high;this.ss.updateKeyByIterator(X,new m4(Z,$))}else this.ss.insert(J);else{let $=X.pointer.low,Y=X.pointer.high;X.pre();let Q=X.pointer.low;if(X.pointer.high+1===Z)if(Z+1===$)this.ss.eraseElementByIterator(X),this.ss.updateKeyByIterator(X,new m4(Q,Y));else this.ss.updateKeyByIterator(X,new m4(Q,Z));else if(Z+1===$)this.ss.eraseElementByIterator(X.next()),this.ss.insert(new m4(Z,Y));else this.ss.insert(J)}N5("free():"+Z)};R5.prototype.clear=function(){N5("clear()"),this.ss.clear(),this.ss.insert(new m4(this.min,this.max))};R5.prototype.intervalCount=function(){return this.ss.size()};R5.prototype.dump=function(){console.log("length:"+this.ss.size());for(let Z of this.ss)console.log(Z)};DJ0.exports=R5});var Zw=L((f41,OJ0)=>{var h41=_J0();f41.NumberAllocator=h41});var MJ0=L((jJ0)=>{Object.defineProperty(jJ0,"__esModule",{value:!0});var g41=a70(),m41=Zw();class wJ0{aliasToTopic;topicToAlias;max;numberAllocator;length;constructor(Z){if(Z>0)this.aliasToTopic=new g41.LRUCache({max:Z}),this.topicToAlias={},this.numberAllocator=new m41.NumberAllocator(1,Z),this.max=Z,this.length=0}put(Z,J){if(J===0||J>this.max)return!1;let X=this.aliasToTopic.get(J);if(X)delete this.topicToAlias[X];return this.aliasToTopic.set(J,Z),this.topicToAlias[Z]=J,this.numberAllocator.use(J),this.length=this.aliasToTopic.size,!0}getTopicByAlias(Z){return this.aliasToTopic.get(Z)}getAliasByTopic(Z){let J=this.topicToAlias[Z];if(typeof J<"u")this.aliasToTopic.get(J);return J}clear(){this.aliasToTopic.clear(),this.topicToAlias={},this.numberAllocator.clear(),this.length=0}getLruAlias(){let Z=this.numberAllocator.firstVacant();if(Z)return Z;return[...this.aliasToTopic.keys()][this.aliasToTopic.size-1]}}jJ0.default=wJ0});var AJ0=L((YQ)=>{var u41=YQ&&YQ.__importDefault||function(Z){return Z&&Z.__esModule?Z:{default:Z}};Object.defineProperty(YQ,"__esModule",{value:!0});var c41=JQ(),l41=u41(MJ0()),p41=ZJ(),i41=(Z,J)=>{Z.log("_handleConnack");let{options:X}=Z,Y=X.protocolVersion===5?J.reasonCode:J.returnCode;if(clearTimeout(Z.connackTimer),delete Z.topicAliasSend,J.properties){if(J.properties.topicAliasMaximum){if(J.properties.topicAliasMaximum>65535){Z.emit("error",Error("topicAliasMaximum from broker is out of range"));return}if(J.properties.topicAliasMaximum>0)Z.topicAliasSend=new l41.default(J.properties.topicAliasMaximum)}if(J.properties.serverKeepAlive&&X.keepalive)X.keepalive=J.properties.serverKeepAlive;if(J.properties.maximumPacketSize){if(!X.properties)X.properties={};X.properties.maximumPacketSize=J.properties.maximumPacketSize}}if(Y===0)Z.reconnecting=!1,Z._onConnect(J);else if(Y>0){let Q=new p41.ErrorWithReasonCode(`Connection refused: ${c41.ReasonCodes[Y]}`,Y);if(Z.emit("error",Q),Z.options.reconnectOnConnackError)Z._cleanUp(!0)}};YQ.default=i41});var qJ0=L((TJ0)=>{Object.defineProperty(TJ0,"__esModule",{value:!0});var n41=(Z,J,X)=>{Z.log("handling pubrel packet");let $=typeof X<"u"?X:Z.noop,{messageId:Y}=J,Q={cmd:"pubcomp",messageId:Y};Z.incomingStore.get(J,(W,K)=>{if(!W)Z.emit("message",K.topic,K.payload,K),Z.handleMessage(K,(z)=>{if(z)return $(z);Z.incomingStore.del(K,Z.noop),Z._sendPacket(Q,$)});else Z._sendPacket(Q,$)})};TJ0.default=n41});var CJ0=L((QQ)=>{var WQ=QQ&&QQ.__importDefault||function(Z){return Z&&Z.__esModule?Z:{default:Z}};Object.defineProperty(QQ,"__esModule",{value:!0});var a41=WQ(x70()),r41=WQ(u70()),s41=WQ(AJ0()),t41=WQ(JQ()),e41=WQ(qJ0()),Z61=(Z,J,X)=>{let{options:$}=Z;if($.protocolVersion===5&&$.properties&&$.properties.maximumPacketSize&&$.properties.maximumPacketSize<J.length)return Z.emit("error",Error(`exceeding packets size ${J.cmd}`)),Z.end({reasonCode:149,properties:{reasonString:"Maximum packet size was exceeded"}}),Z;switch(Z.log("_handlePacket :: emitting packetreceive"),Z.emit("packetreceive",J),J.cmd){case"publish":(0,a41.default)(Z,J,X);break;case"puback":case"pubrec":case"pubcomp":case"suback":case"unsuback":Z.reschedulePing(),(0,t41.default)(Z,J),X();break;case"pubrel":Z.reschedulePing(),(0,e41.default)(Z,J,X);break;case"connack":(0,s41.default)(Z,J),X();break;case"auth":Z.reschedulePing(),(0,r41.default)(Z,J),X();break;case"pingresp":Z.log("_handlePacket :: received pingresp"),Z.reschedulePing(!0),X();break;case"disconnect":Z.emit("disconnect",J),X();break;default:Z.log("_handlePacket :: unknown command"),X();break}};QQ.default=Z61});var Jw=L((RJ0)=>{Object.defineProperty(RJ0,"__esModule",{value:!0});class NJ0{nextId;constructor(){this.nextId=Math.max(1,Math.floor(Math.random()*65535))}allocate(){let Z=this.nextId++;if(this.nextId===65536)this.nextId=1;return Z}getLastAllocated(){return this.nextId===1?65535:this.nextId-1}register(Z){return!0}deallocate(Z){}clear(){}}RJ0.default=NJ0});var IJ0=L((EJ0)=>{Object.defineProperty(EJ0,"__esModule",{value:!0});class PJ0{aliasToTopic;max;length;constructor(Z){this.aliasToTopic={},this.max=Z}put(Z,J){if(J===0||J>this.max)return!1;return this.aliasToTopic[J]=Z,this.length=Object.keys(this.aliasToTopic).length,!0}getTopicByAlias(Z){return this.aliasToTopic[Z]}clear(){this.aliasToTopic={}}}EJ0.default=PJ0});var yJ0=L((H$)=>{var $61=H$&&H$.__importDefault||function(Z){return Z&&Z.__esModule?Z:{default:Z}};Object.defineProperty(H$,"__esModule",{value:!0});H$.TypedEventEmitter=void 0;var Y61=$61(N("events")),Q61=ZJ();class Xw{}H$.TypedEventEmitter=Xw;(0,Q61.applyMixin)(Xw,Y61.default)});var KQ=L((UI1,w9)=>{function $w(Z){return w9.exports=$w=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(J){return typeof J}:function(J){return J&&typeof Symbol=="function"&&J.constructor===Symbol&&J!==Symbol.prototype?"symbol":typeof J},w9.exports.__esModule=!0,w9.exports.default=w9.exports,$w(Z)}w9.exports=$w,w9.exports.__esModule=!0,w9.exports.default=w9.exports});var kJ0=L((LI1,zQ)=>{var SJ0=KQ().default;function W61(Z,J){if(SJ0(Z)!="object"||!Z)return Z;var X=Z[Symbol.toPrimitive];if(X!==void 0){var $=X.call(Z,J||"default");if(SJ0($)!="object")return $;throw TypeError("@@toPrimitive must return a primitive value.")}return(J==="string"?String:Number)(Z)}zQ.exports=W61,zQ.exports.__esModule=!0,zQ.exports.default=zQ.exports});var xJ0=L((DI1,GQ)=>{var K61=KQ().default,z61=kJ0();function G61(Z){var J=z61(Z,"string");return K61(J)=="symbol"?J:J+""}GQ.exports=G61,GQ.exports.__esModule=!0,GQ.exports.default=GQ.exports});var vJ0=L((_I1,HQ)=>{var H61=xJ0();function V61(Z,J,X){return(J=H61(J))in Z?Object.defineProperty(Z,J,{value:X,enumerable:!0,configurable:!0,writable:!0}):Z[J]=X,Z}HQ.exports=V61,HQ.exports.__esModule=!0,HQ.exports.default=HQ.exports});var hJ0=L((OI1,VQ)=>{function F61(Z){if(Array.isArray(Z))return Z}VQ.exports=F61,VQ.exports.__esModule=!0,VQ.exports.default=VQ.exports});var fJ0=L((wI1,FQ)=>{function B61(Z,J){var X=Z==null?null:typeof Symbol<"u"&&Z[Symbol.iterator]||Z["@@iterator"];if(X!=null){var $,Y,Q,W,K=[],z=!0,G=!1;try{if(Q=(X=X.call(Z)).next,J===0){if(Object(X)!==X)return;z=!1}else for(;!(z=($=Q.call(X)).done)&&(K.push($.value),K.length!==J);z=!0);}catch(H){G=!0,Y=H}finally{try{if(!z&&X.return!=null&&(W=X.return(),Object(W)!==W))return}finally{if(G)throw Y}}return K}}FQ.exports=B61,FQ.exports.__esModule=!0,FQ.exports.default=FQ.exports});var bJ0=L((jI1,BQ)=>{function U61(Z,J){(J==null||J>Z.length)&&(J=Z.length);for(var X=0,$=Array(J);X<J;X++)$[X]=Z[X];return $}BQ.exports=U61,BQ.exports.__esModule=!0,BQ.exports.default=BQ.exports});var mJ0=L((MI1,UQ)=>{var gJ0=bJ0();function L61(Z,J){if(Z){if(typeof Z=="string")return gJ0(Z,J);var X={}.toString.call(Z).slice(8,-1);return X==="Object"&&Z.constructor&&(X=Z.constructor.name),X==="Map"||X==="Set"?Array.from(Z):X==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(X)?gJ0(Z,J):void 0}}UQ.exports=L61,UQ.exports.__esModule=!0,UQ.exports.default=UQ.exports});var dJ0=L((AI1,LQ)=>{function D61(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
18
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}LQ.exports=D61,LQ.exports.__esModule=!0,LQ.exports.default=LQ.exports});var uJ0=L((TI1,DQ)=>{var _61=hJ0(),O61=fJ0(),w61=mJ0(),j61=dJ0();function M61(Z,J){return _61(Z)||O61(Z,J)||w61(Z,J)||j61()}DQ.exports=M61,DQ.exports.__esModule=!0,DQ.exports.default=DQ.exports});var pJ0=L((cJ0)=>{Object.defineProperty(cJ0,"__esModule",{value:!0});cJ0.createAddUniqueNumber=void 0;var A61=(Z)=>{return(J)=>{let X=Z(J);return J.add(X),X}};cJ0.createAddUniqueNumber=A61});var oJ0=L((iJ0)=>{Object.defineProperty(iJ0,"__esModule",{value:!0});iJ0.createCache=void 0;var T61=(Z)=>{return(J,X)=>{return Z.set(J,X),X}};iJ0.createCache=T61});var ZX0=L((tJ0)=>{Object.defineProperty(tJ0,"__esModule",{value:!0});tJ0.createGenerateUniqueNumber=void 0;var aJ0=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,sJ0=536870912,rJ0=sJ0*2,q61=(Z,J)=>{return(X)=>{let $=J.get(X),Y=$===void 0?X.size:$<rJ0?$+1:0;if(!X.has(Y))return Z(X,Y);if(X.size<sJ0){while(X.has(Y))Y=Math.floor(Math.random()*rJ0);return Z(X,Y)}if(X.size>aJ0)throw Error("Congratulations, you created a collection of unique numbers which uses all available integers!");while(X.has(Y))Y=Math.floor(Math.random()*aJ0);return Z(X,Y)}};tJ0.createGenerateUniqueNumber=q61});var Yw=L((XX0)=>{Object.defineProperty(XX0,"__esModule",{value:!0});XX0.generateUniqueNumber=XX0.addUniqueNumber=void 0;var C61=pJ0(),N61=oJ0(),R61=ZX0(),JX0=new WeakMap,P61=(0,N61.createCache)(JX0),E61=XX0.generateUniqueNumber=(0,R61.createGenerateUniqueNumber)(P61,JX0),RI1=XX0.addUniqueNumber=(0,C61.createAddUniqueNumber)(E61)});var QX0=L((EI1,_Q)=>{function YX0(Z,J,X,$,Y,Q,W){try{var K=Z[Q](W),z=K.value}catch(G){return void X(G)}K.done?J(z):Promise.resolve(z).then($,Y)}function y61(Z){return function(){var J=this,X=arguments;return new Promise(function($,Y){var Q=Z.apply(J,X);function W(z){YX0(Q,$,Y,W,K,"next",z)}function K(z){YX0(Q,$,Y,W,K,"throw",z)}W(void 0)})}}_Q.exports=y61,_Q.exports.__esModule=!0,_Q.exports.default=_Q.exports});var Qw=L((II1,OQ)=>{function S61(Z,J){this.v=Z,this.k=J}OQ.exports=S61,OQ.exports.__esModule=!0,OQ.exports.default=OQ.exports});var Ww=L((yI1,j9)=>{function tG(Z,J,X,$){var Y=Object.defineProperty;try{Y({},"",{})}catch(Q){Y=0}j9.exports=tG=function(W,K,z,G){function H(V,F){tG(W,V,function(B){return this._invoke(V,F,B)})}K?Y?Y(W,K,{value:z,enumerable:!G,configurable:!G,writable:!G}):W[K]=z:(H("next",0),H("throw",1),H("return",2))},j9.exports.__esModule=!0,j9.exports.default=j9.exports,tG(Z,J,X,$)}j9.exports=tG,j9.exports.__esModule=!0,j9.exports.default=j9.exports});var Kw=L((SI1,M9)=>{var P5=Ww();function WX0(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */var Z,J,X=typeof Symbol=="function"?Symbol:{},$=X.iterator||"@@iterator",Y=X.toStringTag||"@@toStringTag";function Q(B,U,D,_){var O=U&&U.prototype instanceof K?U:K,w=Object.create(O.prototype);return P5(w,"_invoke",function(j,q,R){var T,y,i,s=0,O0=R||[],d0=!1,b0={p:0,n:0,v:Z,a:G0,f:G0.bind(Z,4),d:function(f0,k0){return T=f0,y=0,i=Z,b0.n=k0,W}};function G0(E0,f0){for(y=E0,i=f0,J=0;!d0&&s&&!k0&&J<O0.length;J++){var k0,e0=O0[J],y6=b0.p,i4=e0[2];E0>3?(k0=i4===f0)&&(i=e0[(y=e0[4])?5:(y=3,3)],e0[4]=e0[5]=Z):e0[0]<=y6&&((k0=E0<2&&y6<e0[1])?(y=0,b0.v=f0,b0.n=e0[1]):y6<i4&&(k0=E0<3||e0[0]>f0||f0>i4)&&(e0[4]=E0,e0[5]=f0,b0.n=i4,y=0))}if(k0||E0>1)return W;throw d0=!0,f0}return function(E0,f0,k0){if(s>1)throw TypeError("Generator is already running");for(d0&&f0===1&&G0(f0,k0),y=f0,i=k0;(J=y<2?Z:i)||!d0;){T||(y?y<3?(y>1&&(b0.n=-1),G0(y,i)):b0.n=i:b0.v=i);try{if(s=2,T){if(y||(E0="next"),J=T[E0]){if(!(J=J.call(T,i)))throw TypeError("iterator result is not an object");if(!J.done)return J;i=J.value,y<2&&(y=0)}else y===1&&(J=T.return)&&J.call(T),y<2&&(i=TypeError("The iterator does not provide a '"+E0+"' method"),y=1);T=Z}else if((J=(d0=b0.n<0)?i:j.call(q,b0))!==W)break}catch(e0){T=Z,y=1,i=e0}finally{s=1}}return{value:J,done:d0}}}(B,D,_),!0),w}var W={};function K(){}function z(){}function G(){}J=Object.getPrototypeOf;var H=[][$]?J(J([][$]())):(P5(J={},$,function(){return this}),J),V=G.prototype=K.prototype=Object.create(H);function F(B){return Object.setPrototypeOf?Object.setPrototypeOf(B,G):(B.__proto__=G,P5(B,Y,"GeneratorFunction")),B.prototype=Object.create(V),B}return z.prototype=G,P5(V,"constructor",G),P5(G,"constructor",z),z.displayName="GeneratorFunction",P5(G,Y,"GeneratorFunction"),P5(V),P5(V,Y,"Generator"),P5(V,$,function(){return this}),P5(V,"toString",function(){return"[object Generator]"}),(M9.exports=WX0=function(){return{w:Q,m:F}},M9.exports.__esModule=!0,M9.exports.default=M9.exports)()}M9.exports=WX0,M9.exports.__esModule=!0,M9.exports.default=M9.exports});var Hw=L((kI1,wQ)=>{var k61=Qw(),zw=Ww();function Gw(Z,J){function X(Y,Q,W,K){try{var z=Z[Y](Q),G=z.value;return G instanceof k61?J.resolve(G.v).then(function(H){X("next",H,W,K)},function(H){X("throw",H,W,K)}):J.resolve(G).then(function(H){z.value=H,W(z)},function(H){return X("throw",H,W,K)})}catch(H){K(H)}}var $;this.next||(zw(Gw.prototype),zw(Gw.prototype,typeof Symbol=="function"&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),zw(this,"_invoke",function(Y,Q,W){function K(){return new J(function(z,G){X(Y,W,z,G)})}return $=$?$.then(K,K):K()},!0)}wQ.exports=Gw,wQ.exports.__esModule=!0,wQ.exports.default=wQ.exports});var Vw=L((xI1,jQ)=>{var x61=Kw(),v61=Hw();function h61(Z,J,X,$,Y){return new v61(x61().w(Z,J,X,$),Y||Promise)}jQ.exports=h61,jQ.exports.__esModule=!0,jQ.exports.default=jQ.exports});var KX0=L((vI1,MQ)=>{var f61=Vw();function b61(Z,J,X,$,Y){var Q=f61(Z,J,X,$,Y);return Q.next().then(function(W){return W.done?W.value:Q.next()})}MQ.exports=b61,MQ.exports.__esModule=!0,MQ.exports.default=MQ.exports});var zX0=L((hI1,AQ)=>{function g61(Z){var J=Object(Z),X=[];for(var $ in J)X.unshift($);return function Y(){for(;X.length;)if(($=X.pop())in J)return Y.value=$,Y.done=!1,Y;return Y.done=!0,Y}}AQ.exports=g61,AQ.exports.__esModule=!0,AQ.exports.default=AQ.exports});var GX0=L((fI1,TQ)=>{var m61=KQ().default;function d61(Z){if(Z!=null){var J=Z[typeof Symbol=="function"&&Symbol.iterator||"@@iterator"],X=0;if(J)return J.call(Z);if(typeof Z.next=="function")return Z;if(!isNaN(Z.length))return{next:function(){return Z&&X>=Z.length&&(Z=void 0),{value:Z&&Z[X++],done:!Z}}}}throw TypeError(m61(Z)+" is not iterable")}TQ.exports=d61,TQ.exports.__esModule=!0,TQ.exports.default=TQ.exports});var VX0=L((bI1,A9)=>{var u61=Qw(),c61=Kw(),l61=KX0(),p61=Vw(),i61=Hw(),n61=zX0(),HX0=GX0();function Fw(){var Z=c61(),J=Z.m(Fw),X=(Object.getPrototypeOf?Object.getPrototypeOf(J):J.__proto__).constructor;function $(W){var K=typeof W=="function"&&W.constructor;return!!K&&(K===X||(K.displayName||K.name)==="GeneratorFunction")}var Y={throw:1,return:2,break:3,continue:3};function Q(W){var K,z;return function(G){K||(K={stop:function(){return z(G.a,2)},catch:function(){return G.v},abrupt:function(V,F){return z(G.a,Y[V],F)},delegateYield:function(V,F,B){return K.resultName=F,z(G.d,HX0(V),B)},finish:function(V){return z(G.f,V)}},z=function(V,F,B){G.p=K.prev,G.n=K.next;try{return V(F,B)}finally{K.next=G.n}}),K.resultName&&(K[K.resultName]=G.v,K.resultName=void 0),K.sent=G.v,K.next=G.n;try{return W.call(this,K)}finally{G.p=K.prev,G.n=K.next}}}return(A9.exports=Fw=function(){return{wrap:function(z,G,H,V){return Z.w(Q(z),G,H,V&&V.reverse())},isGeneratorFunction:$,mark:Z.m,awrap:function(z,G){return new u61(z,G)},AsyncIterator:i61,async:function(z,G,H,V,F){return($(G)?p61:l61)(Q(z),G,H,V,F)},keys:n61,values:HX0}},A9.exports.__esModule=!0,A9.exports.default=A9.exports)()}A9.exports=Fw,A9.exports.__esModule=!0,A9.exports.default=A9.exports});var BX0=L((gI1,FX0)=>{var eG=VX0()();FX0.exports=eG;try{regeneratorRuntime=eG}catch(Z){if(typeof globalThis==="object")globalThis.regeneratorRuntime=eG;else Function("r","regeneratorRuntime = r")(eG)}});var LX0=L((ZH,UX0)=>{(function(Z,J){typeof ZH==="object"&&typeof UX0<"u"?J(ZH,vJ0(),uJ0(),Yw(),QX0(),BX0()):typeof define==="function"&&define.amd?define(["exports","@babel/runtime/helpers/defineProperty","@babel/runtime/helpers/slicedToArray","fast-unique-numbers","@babel/runtime/helpers/asyncToGenerator","@babel/runtime/regenerator"],J):(Z=typeof globalThis<"u"?globalThis:Z||self,J(Z.brokerFactory={},Z._defineProperty,Z._slicedToArray,Z.fastUniqueNumbers,Z._asyncToGenerator,Z._regeneratorRuntime))})(ZH,function(Z,J,X,$,Y,Q){var W=function(O){return typeof O.start==="function"},K=new WeakMap;function z(_,O){var w=Object.keys(_);if(Object.getOwnPropertySymbols){var j=Object.getOwnPropertySymbols(_);O&&(j=j.filter(function(q){return Object.getOwnPropertyDescriptor(_,q).enumerable})),w.push.apply(w,j)}return w}function G(_){for(var O=1;O<arguments.length;O++){var w=arguments[O]!=null?arguments[O]:{};O%2?z(Object(w),!0).forEach(function(j){J(_,j,w[j])}):Object.getOwnPropertyDescriptors?Object.defineProperties(_,Object.getOwnPropertyDescriptors(w)):z(Object(w)).forEach(function(j){Object.defineProperty(_,j,Object.getOwnPropertyDescriptor(w,j))})}return _}var H=function(O){return G(G({},O),{},{connect:function(j){var q=j.call;return Y(Q.mark(function R(){var T,y,i,s;return Q.wrap(function(O0){while(!0)switch(O0.prev=O0.next){case 0:return T=new MessageChannel,y=T.port1,i=T.port2,O0.next=1,q("connect",{port:y},[y]);case 1:return s=O0.sent,K.set(i,s),O0.abrupt("return",i);case 2:case"end":return O0.stop()}},R)}))},disconnect:function(j){var q=j.call;return function(){var R=Y(Q.mark(function T(y){var i;return Q.wrap(function(s){while(!0)switch(s.prev=s.next){case 0:if(i=K.get(y),i!==void 0){s.next=1;break}throw Error("The given port is not connected.");case 1:return s.next=2,q("disconnect",{portId:i});case 2:case"end":return s.stop()}},T)}));return function(T){return R.apply(this,arguments)}}()},isSupported:function(j){var q=j.call;return function(){return q("isSupported")}}})};function V(_,O){var w=Object.keys(_);if(Object.getOwnPropertySymbols){var j=Object.getOwnPropertySymbols(_);O&&(j=j.filter(function(q){return Object.getOwnPropertyDescriptor(_,q).enumerable})),w.push.apply(w,j)}return w}function F(_){for(var O=1;O<arguments.length;O++){var w=arguments[O]!=null?arguments[O]:{};O%2?V(Object(w),!0).forEach(function(j){J(_,j,w[j])}):Object.getOwnPropertyDescriptors?Object.defineProperties(_,Object.getOwnPropertyDescriptors(w)):V(Object(w)).forEach(function(j){Object.defineProperty(_,j,Object.getOwnPropertyDescriptor(w,j))})}return _}var B=new WeakMap,U=function(O){if(B.has(O))return B.get(O);var w=new Map;return B.set(O,w),w},D=function(O){var w=H(O);return function(j){var q=U(j);if(j.addEventListener("message",function(G0){var E0=G0.data,f0=E0.id;if(f0!==null&&q.has(f0)){var k0=q.get(f0),e0=k0.reject,y6=k0.resolve;if(q.delete(f0),E0.error===void 0)y6(E0.result);else e0(Error(E0.error.message))}}),W(j))j.start();var R=function(E0){var f0=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,k0=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return new Promise(function(e0,y6){var i4=$.generateUniqueNumber(q);if(q.set(i4,{reject:y6,resolve:e0}),f0===null)j.postMessage({id:i4,method:E0},k0);else j.postMessage({id:i4,method:E0,params:f0},k0)})},T=function(E0,f0){var k0=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];j.postMessage({id:null,method:E0,params:f0},k0)},y={};for(var i=0,s=Object.entries(w);i<s.length;i++){var O0=X(s[i],2),d0=O0[0],b0=O0[1];y=F(F({},y),{},J({},d0,b0({call:R,notify:T})))}return F({},y)}};Z.createBroker=D})});var _X0=L((JH,DX0)=>{(function(Z,J){typeof JH==="object"&&typeof DX0<"u"?J(JH,KQ(),LX0(),Yw()):typeof define==="function"&&define.amd?define(["exports","@babel/runtime/helpers/typeof","broker-factory","fast-unique-numbers"],J):(Z=typeof globalThis<"u"?globalThis:Z||self,J(Z.workerTimersBroker={},Z._typeof,Z.brokerFactory,Z.fastUniqueNumbers))})(JH,function(Z,J,X,$){var Y=new Map([[0,null]]),Q=new Map([[0,null]]),W=X.createBroker({clearInterval:function(G){var H=G.call;return function(V){if(J(Y.get(V))==="symbol")Y.set(V,null),H("clear",{timerId:V,timerType:"interval"}).then(function(){Y.delete(V)})}},clearTimeout:function(G){var H=G.call;return function(V){if(J(Q.get(V))==="symbol")Q.set(V,null),H("clear",{timerId:V,timerType:"timeout"}).then(function(){Q.delete(V)})}},setInterval:function(G){var H=G.call;return function(V){var F=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;for(var B=arguments.length,U=Array(B>2?B-2:0),D=2;D<B;D++)U[D-2]=arguments[D];var _=Symbol(),O=$.generateUniqueNumber(Y);Y.set(O,_);var w=function(){return H("set",{delay:F,now:performance.timeOrigin+performance.now(),timerId:O,timerType:"interval"}).then(function(){var q=Y.get(O);if(q===void 0)throw Error("The timer is in an undefined state.");if(q===_){if(V.apply(void 0,U),Y.get(O)===_)w()}})};return w(),O}},setTimeout:function(G){var H=G.call;return function(V){var F=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;for(var B=arguments.length,U=Array(B>2?B-2:0),D=2;D<B;D++)U[D-2]=arguments[D];var _=Symbol(),O=$.generateUniqueNumber(Q);return Q.set(O,_),H("set",{delay:F,now:performance.timeOrigin+performance.now(),timerId:O,timerType:"timeout"}).then(function(){var w=Q.get(O);if(w===void 0)throw Error("The timer is in an undefined state.");if(w===_)Q.delete(O),V.apply(void 0,U)}),O}}}),K=function(G){var H=new Worker(G);return W(H)};Z.load=K,Z.wrap=W})});var wX0=L((XH,OX0)=>{(function(Z,J){typeof XH==="object"&&typeof OX0<"u"?J(XH,_X0()):typeof define==="function"&&define.amd?define(["exports","worker-timers-broker"],J):(Z=typeof globalThis<"u"?globalThis:Z||self,J(Z.workerTimers={},Z.workerTimersBroker))})(XH,function(Z,J){var X=function(H,V){var F=null;return function(){if(F!==null)return F;var B=new Blob([V],{type:"application/javascript; charset=utf-8"}),U=URL.createObjectURL(B);return F=H(U),setTimeout(function(){return URL.revokeObjectURL(U)}),F}},$='(()=>{var e={45:(e,t,r)=>{var n=r(738).default;e.exports=function(e,t){if("object"!=n(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var o=r.call(e,t||"default");if("object"!=n(o))return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)},e.exports.__esModule=!0,e.exports.default=e.exports},79:e=>{e.exports=function(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n},e.exports.__esModule=!0,e.exports.default=e.exports},122:(e,t,r)=>{var n=r(79);e.exports=function(e,t){if(e){if("string"==typeof e)return n(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?n(e,t):void 0}},e.exports.__esModule=!0,e.exports.default=e.exports},156:e=>{e.exports=function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,u,a,i=[],s=!0,c=!1;try{if(u=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;s=!1}else for(;!(s=(n=u.call(r)).done)&&(i.push(n.value),i.length!==t);s=!0);}catch(e){c=!0,o=e}finally{try{if(!s&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(c)throw o}}return i}},e.exports.__esModule=!0,e.exports.default=e.exports},172:e=>{e.exports=function(e,t){this.v=e,this.k=t},e.exports.__esModule=!0,e.exports.default=e.exports},293:e=>{function t(e,t,r,n,o,u,a){try{var i=e[u](a),s=i.value}catch(e){return void r(e)}i.done?t(s):Promise.resolve(s).then(n,o)}e.exports=function(e){return function(){var r=this,n=arguments;return new Promise(function(o,u){var a=e.apply(r,n);function i(e){t(a,o,u,i,s,"next",e)}function s(e){t(a,o,u,i,s,"throw",e)}i(void 0)})}},e.exports.__esModule=!0,e.exports.default=e.exports},373:e=>{e.exports=function(e){var t=Object(e),r=[];for(var n in t)r.unshift(n);return function e(){for(;r.length;)if((n=r.pop())in t)return e.value=n,e.done=!1,e;return e.done=!0,e}},e.exports.__esModule=!0,e.exports.default=e.exports},389:function(e,t){!function(e){"use strict";var t=function(e){return function(t){var r=e(t);return t.add(r),r}},r=function(e){return function(t,r){return e.set(t,r),r}},n=void 0===Number.MAX_SAFE_INTEGER?9007199254740991:Number.MAX_SAFE_INTEGER,o=536870912,u=2*o,a=function(e,t){return function(r){var a=t.get(r),i=void 0===a?r.size:a<u?a+1:0;if(!r.has(i))return e(r,i);if(r.size<o){for(;r.has(i);)i=Math.floor(Math.random()*u);return e(r,i)}if(r.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;r.has(i);)i=Math.floor(Math.random()*n);return e(r,i)}},i=new WeakMap,s=r(i),c=a(s,i),f=t(c);e.addUniqueNumber=f,e.generateUniqueNumber=c}(t)},472:function(e,t,r){!function(e,t,r,n){"use strict";var o=function(e,t){return function(r){var o=t.get(r);if(void 0===o)return Promise.resolve(!1);var u=n(o,2),a=u[0],i=u[1];return e(a),t.delete(r),i(!1),Promise.resolve(!0)}},u=function(e,t){var r=function(n,o,u,a){var i=n-e.now();i>0?o.set(a,[t(r,i,n,o,u,a),u]):(o.delete(a),u(!0))};return r},a=function(e,t,r,n){return function(o,u,a){var i=o+u-t.timeOrigin,s=i-t.now();return new Promise(function(t){e.set(a,[r(n,s,i,e,t,a),t])})}},i=new Map,s=o(globalThis.clearTimeout,i),c=new Map,f=o(globalThis.clearTimeout,c),l=u(performance,globalThis.setTimeout),p=a(i,performance,globalThis.setTimeout,l),d=a(c,performance,globalThis.setTimeout,l);r.createWorker(self,{clear:function(){var r=e(t.mark(function e(r){var n,o,u;return t.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.timerId,o=r.timerType,e.next=1,"interval"===o?s(n):f(n);case 1:return u=e.sent,e.abrupt("return",{result:u});case 2:case"end":return e.stop()}},e)}));function n(e){return r.apply(this,arguments)}return n}(),set:function(){var r=e(t.mark(function e(r){var n,o,u,a,i;return t.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.delay,o=r.now,u=r.timerId,a=r.timerType,e.next=1,("interval"===a?p:d)(n,o,u);case 1:return i=e.sent,e.abrupt("return",{result:i});case 2:case"end":return e.stop()}},e)}));function n(e){return r.apply(this,arguments)}return n}()})}(r(293),r(756),r(623),r(715))},546:e=>{function t(r,n,o,u){var a=Object.defineProperty;try{a({},"",{})}catch(r){a=0}e.exports=t=function(e,r,n,o){function u(r,n){t(e,r,function(e){return this._invoke(r,n,e)})}r?a?a(e,r,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[r]=n:(u("next",0),u("throw",1),u("return",2))},e.exports.__esModule=!0,e.exports.default=e.exports,t(r,n,o,u)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports},579:(e,t,r)=>{var n=r(738).default;e.exports=function(e){if(null!=e){var t=e["function"==typeof Symbol&&Symbol.iterator||"@@iterator"],r=0;if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length))return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}throw new TypeError(n(e)+" is not iterable")},e.exports.__esModule=!0,e.exports.default=e.exports},623:function(e,t,r){!function(e,t,r,n,o){"use strict";var u={INTERNAL_ERROR:-32603,INVALID_PARAMS:-32602,METHOD_NOT_FOUND:-32601},a=function(e,t){return Object.assign(new Error(e),{status:t})},i=function(e){return a(\'The requested method called "\'.concat(e,\'" is not supported.\'),u.METHOD_NOT_FOUND)},s=function(e){return a(\'The handler of the method called "\'.concat(e,\'" returned no required result.\'),u.INTERNAL_ERROR)},c=function(e){return a(\'The handler of the method called "\'.concat(e,\'" returned an unexpected result.\'),u.INTERNAL_ERROR)},f=function(e){return a(\'The specified parameter called "portId" with the given value "\'.concat(e,\'" does not identify a port connected to this worker.\'),u.INVALID_PARAMS)},l=function(e,n){return function(){var o=t(r.mark(function t(o){var u,a,f,l,p,d,v,x,y,b,h,m,_,g,w;return r.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(u=o.data,a=u.id,f=u.method,l=u.params,p=n[f],t.prev=1,void 0!==p){t.next=2;break}throw i(f);case 2:if(void 0!==(d=void 0===l?p():p(l))){t.next=3;break}throw s(f);case 3:if(!(d instanceof Promise)){t.next=5;break}return t.next=4,d;case 4:g=t.sent,t.next=6;break;case 5:g=d;case 6:if(v=g,null!==a){t.next=8;break}if(void 0===v.result){t.next=7;break}throw c(f);case 7:t.next=10;break;case 8:if(void 0!==v.result){t.next=9;break}throw c(f);case 9:x=v.result,y=v.transferables,b=void 0===y?[]:y,e.postMessage({id:a,result:x},b);case 10:t.next=12;break;case 11:t.prev=11,w=t.catch(1),h=w.message,m=w.status,_=void 0===m?-32603:m,e.postMessage({error:{code:_,message:h},id:a});case 12:case"end":return t.stop()}},t,null,[[1,11]])}));return function(e){return o.apply(this,arguments)}}()},p=function(){return new Promise(function(e){var t=new ArrayBuffer(0),r=new MessageChannel,n=r.port1,o=r.port2;n.onmessage=function(t){var r=t.data;return e(null!==r)},o.postMessage(t,[t])})};function d(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function v(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?d(Object(r),!0).forEach(function(t){n(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):d(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}var x=new Map,y=function(e,n,u){return v(v({},n),{},{connect:function(t){var r=t.port;r.start();var u=e(r,n),a=o.generateUniqueNumber(x);return x.set(a,function(){u(),r.close(),x.delete(a)}),{result:a}},disconnect:function(e){var t=e.portId,r=x.get(t);if(void 0===r)throw f(t);return r(),{result:null}},isSupported:function(){var e=t(r.mark(function e(){var t,n,o;return r.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=1,p();case 1:if(!e.sent){e.next=5;break}if(!((t=u())instanceof Promise)){e.next=3;break}return e.next=2,t;case 2:o=e.sent,e.next=4;break;case 3:o=t;case 4:return n=o,e.abrupt("return",{result:n});case 5:return e.abrupt("return",{result:!1});case 6:case"end":return e.stop()}},e)}));function n(){return e.apply(this,arguments)}return n}()})},b=function(e,t){var r=y(b,t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:function(){return!0}),n=l(e,r);return e.addEventListener("message",n),function(){return e.removeEventListener("message",n)}};e.createWorker=b,e.isSupported=p}(t,r(293),r(756),r(693),r(389))},633:(e,t,r)=>{var n=r(172),o=r(993),u=r(869),a=r(887),i=r(791),s=r(373),c=r(579);function f(){"use strict";var t=o(),r=t.m(f),l=(Object.getPrototypeOf?Object.getPrototypeOf(r):r.__proto__).constructor;function p(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===l||"GeneratorFunction"===(t.displayName||t.name))}var d={throw:1,return:2,break:3,continue:3};function v(e){var t,r;return function(n){t||(t={stop:function(){return r(n.a,2)},catch:function(){return n.v},abrupt:function(e,t){return r(n.a,d[e],t)},delegateYield:function(e,o,u){return t.resultName=o,r(n.d,c(e),u)},finish:function(e){return r(n.f,e)}},r=function(e,r,o){n.p=t.prev,n.n=t.next;try{return e(r,o)}finally{t.next=n.n}}),t.resultName&&(t[t.resultName]=n.v,t.resultName=void 0),t.sent=n.v,t.next=n.n;try{return e.call(this,t)}finally{n.p=t.prev,n.n=t.next}}}return(e.exports=f=function(){return{wrap:function(e,r,n,o){return t.w(v(e),r,n,o&&o.reverse())},isGeneratorFunction:p,mark:t.m,awrap:function(e,t){return new n(e,t)},AsyncIterator:i,async:function(e,t,r,n,o){return(p(t)?a:u)(v(e),t,r,n,o)},keys:s,values:c}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=f,e.exports.__esModule=!0,e.exports.default=e.exports},693:(e,t,r)=>{var n=r(736);e.exports=function(e,t,r){return(t=n(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e},e.exports.__esModule=!0,e.exports.default=e.exports},715:(e,t,r)=>{var n=r(987),o=r(156),u=r(122),a=r(752);e.exports=function(e,t){return n(e)||o(e,t)||u(e,t)||a()},e.exports.__esModule=!0,e.exports.default=e.exports},736:(e,t,r)=>{var n=r(738).default,o=r(45);e.exports=function(e){var t=o(e,"string");return"symbol"==n(t)?t:t+""},e.exports.__esModule=!0,e.exports.default=e.exports},738:e=>{function t(r){return e.exports=t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e.exports.__esModule=!0,e.exports.default=e.exports,t(r)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports},752:e=>{e.exports=function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")},e.exports.__esModule=!0,e.exports.default=e.exports},756:(e,t,r)=>{var n=r(633)();e.exports=n;try{regeneratorRuntime=n}catch(e){"object"==typeof globalThis?globalThis.regeneratorRuntime=n:Function("r","regeneratorRuntime = r")(n)}},791:(e,t,r)=>{var n=r(172),o=r(546);e.exports=function e(t,r){function u(e,o,a,i){try{var s=t[e](o),c=s.value;return c instanceof n?r.resolve(c.v).then(function(e){u("next",e,a,i)},function(e){u("throw",e,a,i)}):r.resolve(c).then(function(e){s.value=e,a(s)},function(e){return u("throw",e,a,i)})}catch(e){i(e)}}var a;this.next||(o(e.prototype),o(e.prototype,"function"==typeof Symbol&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),o(this,"_invoke",function(e,t,n){function o(){return new r(function(t,r){u(e,n,t,r)})}return a=a?a.then(o,o):o()},!0)},e.exports.__esModule=!0,e.exports.default=e.exports},869:(e,t,r)=>{var n=r(887);e.exports=function(e,t,r,o,u){var a=n(e,t,r,o,u);return a.next().then(function(e){return e.done?e.value:a.next()})},e.exports.__esModule=!0,e.exports.default=e.exports},887:(e,t,r)=>{var n=r(993),o=r(791);e.exports=function(e,t,r,u,a){return new o(n().w(e,t,r,u),a||Promise)},e.exports.__esModule=!0,e.exports.default=e.exports},987:e=>{e.exports=function(e){if(Array.isArray(e))return e},e.exports.__esModule=!0,e.exports.default=e.exports},993:(e,t,r)=>{var n=r(546);function o(){var t,r,u="function"==typeof Symbol?Symbol:{},a=u.iterator||"@@iterator",i=u.toStringTag||"@@toStringTag";function s(e,o,u,a){var i=o&&o.prototype instanceof f?o:f,s=Object.create(i.prototype);return n(s,"_invoke",function(e,n,o){var u,a,i,s=0,f=o||[],l=!1,p={p:0,n:0,v:t,a:d,f:d.bind(t,4),d:function(e,r){return u=e,a=0,i=t,p.n=r,c}};function d(e,n){for(a=e,i=n,r=0;!l&&s&&!o&&r<f.length;r++){var o,u=f[r],d=p.p,v=u[2];e>3?(o=v===n)&&(i=u[(a=u[4])?5:(a=3,3)],u[4]=u[5]=t):u[0]<=d&&((o=e<2&&d<u[1])?(a=0,p.v=n,p.n=u[1]):d<v&&(o=e<3||u[0]>n||n>v)&&(u[4]=e,u[5]=n,p.n=v,a=0))}if(o||e>1)return c;throw l=!0,n}return function(o,f,v){if(s>1)throw TypeError("Generator is already running");for(l&&1===f&&d(f,v),a=f,i=v;(r=a<2?t:i)||!l;){u||(a?a<3?(a>1&&(p.n=-1),d(a,i)):p.n=i:p.v=i);try{if(s=2,u){if(a||(o="next"),r=u[o]){if(!(r=r.call(u,i)))throw TypeError("iterator result is not an object");if(!r.done)return r;i=r.value,a<2&&(a=0)}else 1===a&&(r=u.return)&&r.call(u),a<2&&(i=TypeError("The iterator does not provide a \'"+o+"\' method"),a=1);u=t}else if((r=(l=p.n<0)?i:e.call(n,p))!==c)break}catch(e){u=t,a=1,i=e}finally{s=1}}return{value:r,done:l}}}(e,u,a),!0),s}var c={};function f(){}function l(){}function p(){}r=Object.getPrototypeOf;var d=[][a]?r(r([][a]())):(n(r={},a,function(){return this}),r),v=p.prototype=f.prototype=Object.create(d);function x(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,p):(e.__proto__=p,n(e,i,"GeneratorFunction")),e.prototype=Object.create(v),e}return l.prototype=p,n(v,"constructor",p),n(p,"constructor",l),l.displayName="GeneratorFunction",n(p,i,"GeneratorFunction"),n(v),n(v,i,"Generator"),n(v,a,function(){return this}),n(v,"toString",function(){return"[object Generator]"}),(e.exports=o=function(){return{w:s,m:x}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=o,e.exports.__esModule=!0,e.exports.default=e.exports}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var u=t[n]={exports:{}};return e[n].call(u.exports,u,u.exports,r),u.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{"use strict";r(472)})()})();',Y=X(J.load,$),Q=function(H){return Y().clearInterval(H)},W=function(H){return Y().clearTimeout(H)},K=function(){var H;return(H=Y()).setInterval.apply(H,arguments)},z=function(){var H;return(H=Y()).setTimeout.apply(H,arguments)};Z.clearInterval=Q,Z.clearTimeout=W,Z.setInterval=K,Z.setTimeout=z})});var qQ=L((AX0)=>{Object.defineProperty(AX0,"__esModule",{value:!0});AX0.isReactNativeBrowser=AX0.isWebWorker=void 0;var o61=()=>{if(typeof window<"u"){if(typeof navigator<"u"&&navigator.userAgent?.toLowerCase().indexOf(" electron/")>-1&&process?.versions)return!Object.prototype.hasOwnProperty.call(process.versions,"electron");return typeof window.document<"u"}return!1},jX0=()=>Boolean(typeof self==="object"&&self?.constructor?.name?.includes("WorkerGlobalScope")&&typeof Deno>"u"),MX0=()=>typeof navigator<"u"&&navigator.product==="ReactNative",a61=o61()||jX0()||MX0();AX0.isWebWorker=jX0();AX0.isReactNativeBrowser=MX0();AX0.default=a61});var RX0=L((T9)=>{var t61=T9&&T9.__createBinding||(Object.create?function(Z,J,X,$){if($===void 0)$=X;var Y=Object.getOwnPropertyDescriptor(J,X);if(!Y||("get"in Y?!J.__esModule:Y.writable||Y.configurable))Y={enumerable:!0,get:function(){return J[X]}};Object.defineProperty(Z,$,Y)}:function(Z,J,X,$){if($===void 0)$=X;Z[$]=J[X]}),e61=T9&&T9.__setModuleDefault||(Object.create?function(Z,J){Object.defineProperty(Z,"default",{enumerable:!0,value:J})}:function(Z,J){Z.default=J}),Z81=T9&&T9.__importStar||function(){var Z=function(J){return Z=Object.getOwnPropertyNames||function(X){var $=[];for(var Y in X)if(Object.prototype.hasOwnProperty.call(X,Y))$[$.length]=Y;return $},Z(J)};return function(J){if(J&&J.__esModule)return J;var X={};if(J!=null){for(var $=Z(J),Y=0;Y<$.length;Y++)if($[Y]!=="default")t61(X,J,$[Y])}return e61(X,J),X}}();Object.defineProperty(T9,"__esModule",{value:!0});var qX0=wX0(),Bw=Z81(qQ()),CX0={set:qX0.setInterval,clear:qX0.clearInterval},NX0={set:(Z,J)=>setInterval(Z,J),clear:(Z)=>clearInterval(Z)},J81=(Z)=>{switch(Z){case"native":return NX0;case"worker":return CX0;case"auto":default:return Bw.default&&!Bw.isWebWorker&&!Bw.isReactNativeBrowser?CX0:NX0}};T9.default=J81});var Uw=L((CQ)=>{var X81=CQ&&CQ.__importDefault||function(Z){return Z&&Z.__esModule?Z:{default:Z}};Object.defineProperty(CQ,"__esModule",{value:!0});var $81=X81(RX0());class PX0{_keepalive;timerId;timer;destroyed=!1;counter;client;_keepaliveTimeoutTimestamp;_intervalEvery;get keepaliveTimeoutTimestamp(){return this._keepaliveTimeoutTimestamp}get intervalEvery(){return this._intervalEvery}get keepalive(){return this._keepalive}constructor(Z,J){this.client=Z,this.timer=typeof J==="object"&&"set"in J&&"clear"in J?J:(0,$81.default)(J),this.setKeepalive(Z.options.keepalive)}clear(){if(this.timerId)this.timer.clear(this.timerId),this.timerId=null}setKeepalive(Z){if(Z*=1000,isNaN(Z)||Z<=0||Z>2147483647)throw Error(`Keepalive value must be an integer between 0 and 2147483647. Provided value is ${Z}`);this._keepalive=Z,this.reschedule(),this.client.log(`KeepaliveManager: set keepalive to ${Z}ms`)}destroy(){this.clear(),this.destroyed=!0}reschedule(){if(this.destroyed)return;this.clear(),this.counter=0;let Z=Math.ceil(this._keepalive*1.5);this._keepaliveTimeoutTimestamp=Date.now()+Z,this._intervalEvery=Math.ceil(this._keepalive/2),this.timerId=this.timer.set(()=>{if(this.destroyed)return;if(this.counter+=1,this.counter===2)this.client.sendPing();else if(this.counter>2)this.client.onKeepaliveTimeout()},this._intervalEvery)}}CQ.default=PX0});var YH=L((u8)=>{var Y81=u8&&u8.__createBinding||(Object.create?function(Z,J,X,$){if($===void 0)$=X;var Y=Object.getOwnPropertyDescriptor(J,X);if(!Y||("get"in Y?!J.__esModule:Y.writable||Y.configurable))Y={enumerable:!0,get:function(){return J[X]}};Object.defineProperty(Z,$,Y)}:function(Z,J,X,$){if($===void 0)$=X;Z[$]=J[X]}),Q81=u8&&u8.__setModuleDefault||(Object.create?function(Z,J){Object.defineProperty(Z,"default",{enumerable:!0,value:J})}:function(Z,J){Z.default=J}),kX0=u8&&u8.__importStar||function(){var Z=function(J){return Z=Object.getOwnPropertyNames||function(X){var $=[];for(var Y in X)if(Object.prototype.hasOwnProperty.call(X,Y))$[$.length]=Y;return $},Z(J)};return function(J){if(J&&J.__esModule)return J;var X={};if(J!=null){for(var $=Z(J),Y=0;Y<$.length;Y++)if($[Y]!=="default")Y81(X,J,$[Y])}return Q81(X,J),X}}(),k7=u8&&u8.__importDefault||function(Z){return Z&&Z.__esModule?Z:{default:Z}};Object.defineProperty(u8,"__esModule",{value:!0});var Lw=k7(bG()),W81=R7(),EX0=k7(N70()),K81=k7(h6()),IX0=kX0(E70()),V$=k7(dO()),z81=k7(CJ0()),G81=k7(Jw()),H81=k7(IJ0()),NQ=ZJ(),V81=yJ0(),F81=k7(Uw()),yX0=kX0(qQ()),Dw=globalThis.setImmediate||((...Z)=>{let J=Z.shift();(0,NQ.nextTick)(()=>{J(...Z)})}),SX0={keepalive:60,reschedulePings:!0,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:1000,connectTimeout:30000,clean:!0,resubscribe:!0,subscribeBatchSize:null,writeCache:!0,timerVariant:"auto"};class $H extends V81.TypedEventEmitter{static VERSION=NQ.MQTTJS_VERSION;connected;disconnecting;disconnected;reconnecting;incomingStore;outgoingStore;options;queueQoSZero;_reconnectCount;log;messageIdProvider;outgoing;messageIdToTopic;noop;keepaliveManager;stream;queue;streamBuilder;_resubscribeTopics;connackTimer;reconnectTimer;_storeProcessing;_packetIdsDuringStoreProcessing;_storeProcessingQueue;_firstConnection;topicAliasRecv;topicAliasSend;_deferredReconnect;connackPacket;static defaultId(){return`mqttjs_${Math.random().toString(16).substr(2,8)}`}constructor(Z,J){super();this.options=J||{};for(let X in SX0)if(typeof this.options[X]>"u")this.options[X]=SX0[X];else this.options[X]=J[X];if(this.log=this.options.log||(0,K81.default)("mqttjs:client"),this.noop=this._noop.bind(this),this.log("MqttClient :: version:",$H.VERSION),yX0.isWebWorker)this.log("MqttClient :: environment","webworker");else this.log("MqttClient :: environment",yX0.default?"browser":"node");if(this.log("MqttClient :: options.protocol",J.protocol),this.log("MqttClient :: options.protocolVersion",J.protocolVersion),this.log("MqttClient :: options.username",J.username),this.log("MqttClient :: options.keepalive",J.keepalive),this.log("MqttClient :: options.reconnectPeriod",J.reconnectPeriod),this.log("MqttClient :: options.rejectUnauthorized",J.rejectUnauthorized),this.log("MqttClient :: options.properties.topicAliasMaximum",J.properties?J.properties.topicAliasMaximum:void 0),this.options.clientId=typeof J.clientId==="string"?J.clientId:$H.defaultId(),this.log("MqttClient :: clientId",this.options.clientId),this.options.customHandleAcks=J.protocolVersion===5&&J.customHandleAcks?J.customHandleAcks:(...X)=>{X[3](null,0)},!this.options.writeCache)Lw.default.writeToStream.cacheNumbers=!1;if(this.streamBuilder=Z,this.messageIdProvider=typeof this.options.messageIdProvider>"u"?new G81.default:this.options.messageIdProvider,this.outgoingStore=J.outgoingStore||new V$.default,this.incomingStore=J.incomingStore||new V$.default,this.queueQoSZero=J.queueQoSZero===void 0?!0:J.queueQoSZero,this._resubscribeTopics={},this.messageIdToTopic={},this.keepaliveManager=null,this.connected=!1,this.disconnecting=!1,this.reconnecting=!1,this.queue=[],this.connackTimer=null,this.reconnectTimer=null,this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={},this._storeProcessingQueue=[],this.outgoing={},this._firstConnection=!0,J.properties&&J.properties.topicAliasMaximum>0)if(J.properties.topicAliasMaximum>65535)this.log("MqttClient :: options.properties.topicAliasMaximum is out of range");else this.topicAliasRecv=new H81.default(J.properties.topicAliasMaximum);if(this.on("connect",()=>{let{queue:X}=this,$=()=>{let Y=X.shift();this.log("deliver :: entry %o",Y);let Q=null;if(!Y){this._resubscribe();return}Q=Y.packet,this.log("deliver :: call _sendPacket for %o",Q);let W=!0;if(Q.messageId&&Q.messageId!==0){if(!this.messageIdProvider.register(Q.messageId))W=!1}if(W)this._sendPacket(Q,(K)=>{if(Y.cb)Y.cb(K);$()});else this.log("messageId: %d has already used. The message is skipped and removed.",Q.messageId),$()};this.log("connect :: sending queued packets"),$()}),this.on("close",()=>{if(this.log("close :: connected set to `false`"),this.connected=!1,this.log("close :: clearing connackTimer"),clearTimeout(this.connackTimer),this._destroyKeepaliveManager(),this.topicAliasRecv)this.topicAliasRecv.clear();this.log("close :: calling _setupReconnect"),this._setupReconnect()}),!this.options.manualConnect)this.log("MqttClient :: setting up stream"),this.connect()}handleAuth(Z,J){J()}handleMessage(Z,J){J()}_nextId(){return this.messageIdProvider.allocate()}getLastMessageId(){return this.messageIdProvider.getLastAllocated()}connect(){let Z=new W81.Writable,J=Lw.default.parser(this.options),X=null,$=[];if(this.log("connect :: calling method to clear reconnect"),this._clearReconnect(),this.disconnected&&!this.reconnecting)this.incomingStore=this.options.incomingStore||new V$.default,this.outgoingStore=this.options.outgoingStore||new V$.default,this.disconnecting=!1,this.disconnected=!1;this.log("connect :: using streamBuilder provided to client to create stream"),this.stream=this.streamBuilder(this),J.on("packet",(z)=>{this.log("parser :: on packet push to packets array."),$.push(z)});let Y=()=>{this.log("work :: getting next packet in queue");let z=$.shift();if(z)this.log("work :: packet pulled from queue"),(0,z81.default)(this,z,Q);else{this.log("work :: no packets in queue");let G=X;if(X=null,this.log("work :: done flag is %s",!!G),G)G()}},Q=()=>{if($.length)(0,NQ.nextTick)(Y);else{let z=X;X=null,z()}};Z._write=(z,G,H)=>{X=H,this.log("writable stream :: parsing buffer"),J.parse(z),Y()};let W=(z)=>{if(this.log("streamErrorHandler :: error",z.message),z.code)this.log("streamErrorHandler :: emitting error"),this.emit("error",z);else this.noop(z)};this.log("connect :: pipe stream to writable stream"),this.stream.pipe(Z),this.stream.on("error",W),this.stream.on("close",()=>{this.log("(%s)stream :: on close",this.options.clientId),this._flushVolatile(),this.log("stream: emit close to MqttClient"),this.emit("close")}),this.log("connect: sending packet `connect`");let K={cmd:"connect",protocolId:this.options.protocolId,protocolVersion:this.options.protocolVersion,clean:this.options.clean,clientId:this.options.clientId,keepalive:this.options.keepalive,username:this.options.username,password:this.options.password,properties:this.options.properties};if(this.options.will)K.will={...this.options.will,payload:this.options.will?.payload};if(this.topicAliasRecv){if(!K.properties)K.properties={};if(this.topicAliasRecv)K.properties.topicAliasMaximum=this.topicAliasRecv.max}if(this._writePacket(K),J.on("error",this.emit.bind(this,"error")),this.options.properties){if(!this.options.properties.authenticationMethod&&this.options.properties.authenticationData)return this.end(()=>this.emit("error",Error("Packet has no Authentication Method"))),this;if(this.options.properties.authenticationMethod&&this.options.authPacket&&typeof this.options.authPacket==="object"){let z={cmd:"auth",reasonCode:0,...this.options.authPacket};this._writePacket(z)}}return this.stream.setMaxListeners(1000),clearTimeout(this.connackTimer),this.connackTimer=setTimeout(()=>{this.log("!!connectTimeout hit!! Calling _cleanUp with force `true`"),this.emit("error",Error("connack timeout")),this._cleanUp(!0)},this.options.connectTimeout),this}publish(Z,J,X,$){this.log("publish :: message `%s` to topic `%s`",J,Z);let{options:Y}=this;if(typeof X==="function")$=X,X=null;X=X||{},X={...{qos:0,retain:!1,dup:!1},...X};let{qos:W,retain:K,dup:z,properties:G,cbStorePut:H}=X;if(this._checkDisconnecting($))return this;let V=()=>{let F=0;if(W===1||W===2){if(F=this._nextId(),F===null)return this.log("No messageId left"),!1}let B={cmd:"publish",topic:Z,payload:J,qos:W,retain:K,messageId:F,dup:z};if(Y.protocolVersion===5)B.properties=G;switch(this.log("publish :: qos",W),W){case 1:case 2:this.outgoing[B.messageId]={volatile:!1,cb:$||this.noop},this.log("MqttClient:publish: packet cmd: %s",B.cmd),this._sendPacket(B,void 0,H);break;default:this.log("MqttClient:publish: packet cmd: %s",B.cmd),this._sendPacket(B,$,H);break}return!0};if(this._storeProcessing||this._storeProcessingQueue.length>0||!V())this._storeProcessingQueue.push({invoke:V,cbStorePut:X.cbStorePut,callback:$});return this}publishAsync(Z,J,X){return new Promise(($,Y)=>{this.publish(Z,J,X,(Q,W)=>{if(Q)Y(Q);else $(W)})})}subscribe(Z,J,X){let $=this.options.protocolVersion;if(typeof J==="function")X=J;X=X||this.noop;let Y=!1,Q=[];if(typeof Z==="string")Z=[Z],Q=Z;else if(Array.isArray(Z))Q=Z;else if(typeof Z==="object")Y=Z.resubscribe,delete Z.resubscribe,Q=Object.keys(Z);let W=IX0.validateTopics(Q);if(W!==null)return Dw(X,Error(`Invalid topic ${W}`)),this;if(this._checkDisconnecting(X))return this.log("subscribe: discconecting true"),this;let K={qos:0};if($===5)K.nl=!1,K.rap=!1,K.rh=0;J={...K,...J};let{properties:z}=J,G=[],H=(B,U)=>{if(U=U||J,!Object.prototype.hasOwnProperty.call(this._resubscribeTopics,B)||this._resubscribeTopics[B].qos<U.qos||Y){let D={topic:B,qos:U.qos};if($===5)D.nl=U.nl,D.rap=U.rap,D.rh=U.rh,D.properties=z;this.log("subscribe: pushing topic `%s` and qos `%s` to subs list",D.topic,D.qos),G.push(D)}};if(Array.isArray(Z))Z.forEach((B)=>{this.log("subscribe: array topic %s",B),H(B)});else Object.keys(Z).forEach((B)=>{this.log("subscribe: object topic %s, %o",B,Z[B]),H(B,Z[B])});if(!G.length)return X(null,[]),this;let V=(B,U)=>{let D={cmd:"subscribe",subscriptions:B,messageId:U};if(z)D.properties=z;if(this.options.resubscribe){this.log("subscribe :: resubscribe true");let O=[];B.forEach((w)=>{if(this.options.reconnectPeriod>0){let j={qos:w.qos};if($===5)j.nl=w.nl||!1,j.rap=w.rap||!1,j.rh=w.rh||0,j.properties=w.properties;this._resubscribeTopics[w.topic]=j,O.push(w.topic)}}),this.messageIdToTopic[D.messageId]=O}let _=new Promise((O,w)=>{this.outgoing[D.messageId]={volatile:!0,cb(j,q){if(!j){let{granted:R}=q;for(let T=0;T<R.length;T+=1)B[T].qos=R[T]}if(!j)O(q);else w(new NQ.ErrorWithSubackPacket(j.message,q))}}});return this.log("subscribe :: call _sendPacket"),this._sendPacket(D),_},F=()=>{let B=this.options.subscribeBatchSize??G.length,U=[];for(let D=0;D<G.length;D+=B){let _=G.slice(D,D+B),O=this._nextId();if(O===null)return this.log("No messageId left"),!1;U.push(V(_,O))}return Promise.all(U).then((D)=>{X(null,G,D.at(-1))}).catch((D)=>{X(D,G,D.packet)}),!0};if(this._storeProcessing||this._storeProcessingQueue.length>0||!F())this._storeProcessingQueue.push({invoke:F,callback:X});return this}subscribeAsync(Z,J){return new Promise((X,$)=>{this.subscribe(Z,J,(Y,Q)=>{if(Y)$(Y);else X(Q)})})}unsubscribe(Z,J,X){if(typeof Z==="string")Z=[Z];if(typeof J==="function")X=J;X=X||this.noop;let $=IX0.validateTopics(Z);if($!==null)return Dw(X,Error(`Invalid topic ${$}`)),this;if(this._checkDisconnecting(X))return this;let Y=()=>{let Q=this._nextId();if(Q===null)return this.log("No messageId left"),!1;let W={cmd:"unsubscribe",messageId:Q,unsubscriptions:[]};if(typeof Z==="string")W.unsubscriptions=[Z];else if(Array.isArray(Z))W.unsubscriptions=Z;if(this.options.resubscribe)W.unsubscriptions.forEach((K)=>{delete this._resubscribeTopics[K]});if(typeof J==="object"&&J.properties)W.properties=J.properties;return this.outgoing[W.messageId]={volatile:!0,cb:X},this.log("unsubscribe: call _sendPacket"),this._sendPacket(W),!0};if(this._storeProcessing||this._storeProcessingQueue.length>0||!Y())this._storeProcessingQueue.push({invoke:Y,callback:X});return this}unsubscribeAsync(Z,J){return new Promise((X,$)=>{this.unsubscribe(Z,J,(Y,Q)=>{if(Y)$(Y);else X(Q)})})}end(Z,J,X){if(this.log("end :: (%s)",this.options.clientId),Z==null||typeof Z!=="boolean")X=X||J,J=Z,Z=!1;if(typeof J!=="object")X=X||J,J=null;if(this.log("end :: cb? %s",!!X),!X||typeof X!=="function")X=this.noop;let $=()=>{if(this.log("end :: closeStores: closing incoming and outgoing stores"),this.disconnected=!0,this.incomingStore.close((Q)=>{this.outgoingStore.close((W)=>{if(this.log("end :: closeStores: emitting end"),this.emit("end"),X){let K=Q||W;this.log("end :: closeStores: invoking callback with args"),X(K)}})}),this._deferredReconnect)this._deferredReconnect();else if(this.options.reconnectPeriod===0||this.options.manualConnect)this.disconnecting=!1},Y=()=>{this.log("end :: (%s) :: finish :: calling _cleanUp with force %s",this.options.clientId,Z),this._cleanUp(Z,()=>{this.log("end :: finish :: calling process.nextTick on closeStores"),(0,NQ.nextTick)($)},J)};if(this.disconnecting)return X(),this;if(this._clearReconnect(),this.disconnecting=!0,!Z&&Object.keys(this.outgoing).length>0)this.log("end :: (%s) :: calling finish in 10ms once outgoing is empty",this.options.clientId),this.once("outgoingEmpty",setTimeout.bind(null,Y,10));else this.log("end :: (%s) :: immediately calling finish",this.options.clientId),Y();return this}endAsync(Z,J){return new Promise((X,$)=>{this.end(Z,J,(Y)=>{if(Y)$(Y);else X()})})}removeOutgoingMessage(Z){if(this.outgoing[Z]){let{cb:J}=this.outgoing[Z];this._removeOutgoingAndStoreMessage(Z,()=>{J(Error("Message removed"))})}return this}reconnect(Z){this.log("client reconnect");let J=()=>{if(Z)this.options.incomingStore=Z.incomingStore,this.options.outgoingStore=Z.outgoingStore;else this.options.incomingStore=null,this.options.outgoingStore=null;this.incomingStore=this.options.incomingStore||new V$.default,this.outgoingStore=this.options.outgoingStore||new V$.default,this.disconnecting=!1,this.disconnected=!1,this._deferredReconnect=null,this._reconnect()};if(this.disconnecting&&!this.disconnected)this._deferredReconnect=J;else J();return this}_flushVolatile(){if(this.outgoing)this.log("_flushVolatile :: deleting volatile messages from the queue and setting their callbacks as error function"),Object.keys(this.outgoing).forEach((Z)=>{if(this.outgoing[Z].volatile&&typeof this.outgoing[Z].cb==="function")this.outgoing[Z].cb(Error("Connection closed")),delete this.outgoing[Z]})}_flush(){if(this.outgoing)this.log("_flush: queue exists? %b",!!this.outgoing),Object.keys(this.outgoing).forEach((Z)=>{if(typeof this.outgoing[Z].cb==="function")this.outgoing[Z].cb(Error("Connection closed")),delete this.outgoing[Z]})}_removeTopicAliasAndRecoverTopicName(Z){let J;if(Z.properties)J=Z.properties.topicAlias;let X=Z.topic.toString();if(this.log("_removeTopicAliasAndRecoverTopicName :: alias %d, topic %o",J,X),X.length===0){if(typeof J>"u")return Error("Unregistered Topic Alias");if(X=this.topicAliasSend.getTopicByAlias(J),typeof X>"u")return Error("Unregistered Topic Alias");Z.topic=X}if(J)delete Z.properties.topicAlias}_checkDisconnecting(Z){if(this.disconnecting)if(Z&&Z!==this.noop)Z(Error("client disconnecting"));else this.emit("error",Error("client disconnecting"));return this.disconnecting}_reconnect(){if(this.log("_reconnect: emitting reconnect to client"),this.emit("reconnect"),this.connected)this.end(()=>{this.connect()}),this.log("client already connected. disconnecting first.");else this.log("_reconnect: calling connect"),this.connect()}_setupReconnect(){if(!this.disconnecting&&!this.reconnectTimer&&this.options.reconnectPeriod>0){if(!this.reconnecting)this.log("_setupReconnect :: emit `offline` state"),this.emit("offline"),this.log("_setupReconnect :: set `reconnecting` to `true`"),this.reconnecting=!0;this.log("_setupReconnect :: setting reconnectTimer for %d ms",this.options.reconnectPeriod),this.reconnectTimer=setInterval(()=>{this.log("reconnectTimer :: reconnect triggered!"),this._reconnect()},this.options.reconnectPeriod)}else this.log("_setupReconnect :: doing nothing...")}_clearReconnect(){if(this.log("_clearReconnect : clearing reconnect timer"),this.reconnectTimer)clearInterval(this.reconnectTimer),this.reconnectTimer=null}_cleanUp(Z,J,X={}){if(J)this.log("_cleanUp :: done callback provided for on stream close"),this.stream.on("close",J);if(this.log("_cleanUp :: forced? %s",Z),Z){if(this.options.reconnectPeriod===0&&this.options.clean)this._flush();this.log("_cleanUp :: (%s) :: destroying stream",this.options.clientId),this.stream.destroy()}else{let $={cmd:"disconnect",...X};this.log("_cleanUp :: (%s) :: call _sendPacket with disconnect packet",this.options.clientId),this._sendPacket($,()=>{this.log("_cleanUp :: (%s) :: destroying stream",this.options.clientId),Dw(()=>{this.stream.end(()=>{this.log("_cleanUp :: (%s) :: stream destroyed",this.options.clientId)})})})}if(!this.disconnecting&&!this.reconnecting)this.log("_cleanUp :: client not disconnecting/reconnecting. Clearing and resetting reconnect."),this._clearReconnect(),this._setupReconnect();if(this._destroyKeepaliveManager(),J&&!this.connected)this.log("_cleanUp :: (%s) :: removing stream `done` callback `close` listener",this.options.clientId),this.stream.removeListener("close",J),J()}_storeAndSend(Z,J,X){this.log("storeAndSend :: store packet with cmd %s to outgoingStore",Z.cmd);let $=Z,Y;if($.cmd==="publish"){if($=(0,EX0.default)(Z),Y=this._removeTopicAliasAndRecoverTopicName($),Y)return J&&J(Y)}this.outgoingStore.put($,(Q)=>{if(Q)return J&&J(Q);X(),this._writePacket(Z,J)})}_applyTopicAlias(Z){if(this.options.protocolVersion===5){if(Z.cmd==="publish"){let J;if(Z.properties)J=Z.properties.topicAlias;let X=Z.topic.toString();if(this.topicAliasSend){if(J){if(X.length!==0){if(this.log("applyTopicAlias :: register topic: %s - alias: %d",X,J),!this.topicAliasSend.put(X,J))return this.log("applyTopicAlias :: error out of range. topic: %s - alias: %d",X,J),Error("Sending Topic Alias out of range")}}else if(X.length!==0){if(this.options.autoAssignTopicAlias)if(J=this.topicAliasSend.getAliasByTopic(X),J)Z.topic="",Z.properties={...Z.properties,topicAlias:J},this.log("applyTopicAlias :: auto assign(use) topic: %s - alias: %d",X,J);else J=this.topicAliasSend.getLruAlias(),this.topicAliasSend.put(X,J),Z.properties={...Z.properties,topicAlias:J},this.log("applyTopicAlias :: auto assign topic: %s - alias: %d",X,J);else if(this.options.autoUseTopicAlias){if(J=this.topicAliasSend.getAliasByTopic(X),J)Z.topic="",Z.properties={...Z.properties,topicAlias:J},this.log("applyTopicAlias :: auto use topic: %s - alias: %d",X,J)}}}else if(J)return this.log("applyTopicAlias :: error out of range. topic: %s - alias: %d",X,J),Error("Sending Topic Alias out of range")}}}_noop(Z){this.log("noop ::",Z)}_writePacket(Z,J){this.log("_writePacket :: packet: %O",Z),this.log("_writePacket :: emitting `packetsend`"),this.emit("packetsend",Z),this.log("_writePacket :: writing to stream");let X=Lw.default.writeToStream(Z,this.stream,this.options);if(this.log("_writePacket :: writeToStream result %s",X),!X&&J&&J!==this.noop)this.log("_writePacket :: handle events on `drain` once through callback."),this.stream.once("drain",J);else if(J)this.log("_writePacket :: invoking cb"),J()}_sendPacket(Z,J,X,$){this.log("_sendPacket :: (%s) :: start",this.options.clientId),X=X||this.noop,J=J||this.noop;let Y=this._applyTopicAlias(Z);if(Y){J(Y);return}if(!this.connected){if(Z.cmd==="auth"){this._writePacket(Z,J);return}this.log("_sendPacket :: client not connected. Storing packet offline."),this._storePacket(Z,J,X);return}if($){this._writePacket(Z,J);return}switch(Z.cmd){case"publish":break;case"pubrel":this._storeAndSend(Z,J,X);return;default:this._writePacket(Z,J);return}switch(Z.qos){case 2:case 1:this._storeAndSend(Z,J,X);break;case 0:default:this._writePacket(Z,J);break}this.log("_sendPacket :: (%s) :: end",this.options.clientId)}_storePacket(Z,J,X){this.log("_storePacket :: packet: %o",Z),this.log("_storePacket :: cb? %s",!!J),X=X||this.noop;let $=Z;if($.cmd==="publish"){$=(0,EX0.default)(Z);let Q=this._removeTopicAliasAndRecoverTopicName($);if(Q)return J&&J(Q)}let Y=$.qos||0;if(Y===0&&this.queueQoSZero||$.cmd!=="publish")this.queue.push({packet:$,cb:J});else if(Y>0)J=this.outgoing[$.messageId]?this.outgoing[$.messageId].cb:null,this.outgoingStore.put($,(Q)=>{if(Q)return J&&J(Q);X()});else if(J)J(Error("No connection to broker"))}_setupKeepaliveManager(){if(this.log("_setupKeepaliveManager :: keepalive %d (seconds)",this.options.keepalive),!this.keepaliveManager&&this.options.keepalive)this.keepaliveManager=new F81.default(this,this.options.timerVariant)}_destroyKeepaliveManager(){if(this.keepaliveManager)this.log("_destroyKeepaliveManager :: destroying keepalive manager"),this.keepaliveManager.destroy(),this.keepaliveManager=null}reschedulePing(Z=!1){if(this.keepaliveManager&&this.options.keepalive&&(Z||this.options.reschedulePings))this._reschedulePing()}_reschedulePing(){this.log("_reschedulePing :: rescheduling ping"),this.keepaliveManager.reschedule()}sendPing(){this.log("_sendPing :: sending pingreq"),this._sendPacket({cmd:"pingreq"})}onKeepaliveTimeout(){this.emit("error",Error("Keepalive timeout")),this.log("onKeepaliveTimeout :: calling _cleanUp with force true"),this._cleanUp(!0)}_resubscribe(){this.log("_resubscribe");let Z=Object.keys(this._resubscribeTopics);if(!this._firstConnection&&(this.options.clean||this.options.protocolVersion>=4&&!this.connackPacket.sessionPresent)&&Z.length>0)if(this.options.resubscribe)if(this.options.protocolVersion===5){this.log("_resubscribe: protocolVersion 5");for(let J=0;J<Z.length;J++){let X={};X[Z[J]]=this._resubscribeTopics[Z[J]],X.resubscribe=!0,this.subscribe(X,{properties:X[Z[J]].properties})}}else this._resubscribeTopics.resubscribe=!0,this.subscribe(this._resubscribeTopics);else this._resubscribeTopics={};this._firstConnection=!1}_onConnect(Z){if(this.disconnected){this.emit("connect",Z);return}this.connackPacket=Z,this.messageIdProvider.clear(),this._setupKeepaliveManager(),this.connected=!0;let J=()=>{let X=this.outgoingStore.createStream(),$=()=>{X.destroy(),X=null,this._flushStoreProcessingQueue(),Y()},Y=()=>{this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={}};this.once("close",$),X.on("error",(W)=>{Y(),this._flushStoreProcessingQueue(),this.removeListener("close",$),this.emit("error",W)});let Q=()=>{if(!X)return;let W=X.read(1),K;if(!W){X.once("readable",Q);return}if(this._storeProcessing=!0,this._packetIdsDuringStoreProcessing[W.messageId]){Q();return}if(!this.disconnecting&&!this.reconnectTimer)if(K=this.outgoing[W.messageId]?this.outgoing[W.messageId].cb:null,this.outgoing[W.messageId]={volatile:!1,cb(z,G){if(K)K(z,G);Q()}},this._packetIdsDuringStoreProcessing[W.messageId]=!0,this.messageIdProvider.register(W.messageId))this._sendPacket(W,void 0,void 0,!0);else this.log("messageId: %d has already used.",W.messageId);else if(X.destroy)X.destroy()};X.on("end",()=>{let W=!0;for(let K in this._packetIdsDuringStoreProcessing)if(!this._packetIdsDuringStoreProcessing[K]){W=!1;break}if(this.removeListener("close",$),W)Y(),this._invokeAllStoreProcessingQueue(),this.emit("connect",Z);else J()}),Q()};J()}_invokeStoreProcessingQueue(){if(!this._storeProcessing&&this._storeProcessingQueue.length>0){let Z=this._storeProcessingQueue[0];if(Z&&Z.invoke())return this._storeProcessingQueue.shift(),!0}return!1}_invokeAllStoreProcessingQueue(){while(this._invokeStoreProcessingQueue());}_flushStoreProcessingQueue(){for(let Z of this._storeProcessingQueue){if(Z.cbStorePut)Z.cbStorePut(Error("Connection closed"));if(Z.callback)Z.callback(Error("Connection closed"))}this._storeProcessingQueue.splice(0)}_removeOutgoingAndStoreMessage(Z,J){delete this.outgoing[Z],this.outgoingStore.del({messageId:Z},(X,$)=>{J(X,$),this.messageIdProvider.deallocate(Z),this._invokeStoreProcessingQueue()})}}u8.default=$H});var hX0=L((vX0)=>{Object.defineProperty(vX0,"__esModule",{value:!0});var B81=Zw();class xX0{numberAllocator;lastId;constructor(){this.numberAllocator=new B81.NumberAllocator(1,65535)}allocate(){return this.lastId=this.numberAllocator.alloc(),this.lastId}getLastAllocated(){return this.lastId}register(Z){return this.numberAllocator.use(Z)}deallocate(Z){this.numberAllocator.free(Z)}clear(){this.numberAllocator.clear()}}vX0.default=xX0});var QH=L((mX0)=>{Object.defineProperty(mX0,"__esModule",{value:!0});mX0.BufferedDuplex=void 0;mX0.writev=bX0;var L81=R7(),fX0=N("buffer");function bX0(Z,J){let X=Array(Z.length);for(let $=0;$<Z.length;$++)if(typeof Z[$].chunk==="string")X[$]=fX0.Buffer.from(Z[$].chunk,"utf8");else X[$]=Z[$].chunk;this._write(fX0.Buffer.concat(X),"binary",J)}class gX0 extends L81.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(Z,J,X){super({objectMode:!0});if(this.proxy=J,this.socket=X,this.writeQueue=[],!Z.objectMode)this._writev=bX0.bind(this);this.isSocketOpen=!1,this.proxy.on("data",($)=>{if(!this.destroyed&&this.readable)this.push($)})}_read(Z){this.proxy.read(Z)}_write(Z,J,X){if(!this.isSocketOpen)this.writeQueue.push({chunk:Z,encoding:J,cb:X});else this.writeToProxy(Z,J,X)}_final(Z){this.writeQueue=[],this.proxy.end(Z)}_destroy(Z,J){this.writeQueue=[],this.proxy.destroy(),J(Z)}socketReady(){this.emit("connect"),this.isSocketOpen=!0,this.processWriteQueue()}writeToProxy(Z,J,X){if(this.proxy.write(Z,J)===!1)this.proxy.once("drain",X);else X()}processWriteQueue(){while(this.writeQueue.length>0){let{chunk:Z,encoding:J,cb:X}=this.writeQueue.shift();this.writeToProxy(Z,J,X)}}}mX0.BufferedDuplex=gX0});var RQ=L((v7)=>{var Ow=v7&&v7.__importDefault||function(Z){return Z&&Z.__esModule?Z:{default:Z}};Object.defineProperty(v7,"__esModule",{value:!0});v7.streamBuilder=v7.browserStreamBuilder=void 0;var WH=N("buffer"),uX0=Ow(N("ws")),_81=Ow(h6()),O81=R7(),w81=Ow(qQ()),_w=QH(),x7=(0,_81.default)("mqttjs:ws"),j81=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];function cX0(Z,J){let X=`${Z.protocol}://${Z.hostname}:${Z.port}${Z.path}`;if(typeof Z.transformWsUrl==="function")X=Z.transformWsUrl(X,Z,J);return X}function lX0(Z){let J=Z;if(!Z.port)if(Z.protocol==="wss")J.port=443;else J.port=80;if(!Z.path)J.path="/";if(!Z.wsOptions)J.wsOptions={};if(!w81.default&&!Z.forceNativeWebSocket&&Z.protocol==="wss")j81.forEach((X)=>{if(Object.prototype.hasOwnProperty.call(Z,X)&&!Object.prototype.hasOwnProperty.call(Z.wsOptions,X))J.wsOptions[X]=Z[X]});return J}function M81(Z){let J=lX0(Z);if(!J.hostname)J.hostname=J.host;if(!J.hostname){if(typeof document>"u")throw Error("Could not determine host. Specify host manually.");let X=new URL(document.URL);if(J.hostname=X.hostname,!J.port)J.port=Number(X.port)}if(J.objectMode===void 0)J.objectMode=!(J.binary===!0||J.binary===void 0);return J}function A81(Z,J,X){x7("createWebSocket"),x7(`protocol: ${X.protocolId} ${X.protocolVersion}`);let $=X.protocolId==="MQIsdp"&&X.protocolVersion===3?"mqttv3.1":"mqtt";x7(`creating new Websocket for url: ${J} and protocol: ${$}`);let Y;if(X.createWebsocket)Y=X.createWebsocket(J,[$],X);else Y=new uX0.default(J,[$],X.wsOptions);return Y}function T81(Z,J){let X=J.protocolId==="MQIsdp"&&J.protocolVersion===3?"mqttv3.1":"mqtt",$=cX0(J,Z),Y;if(J.createWebsocket)Y=J.createWebsocket($,[X],J);else Y=new WebSocket($,[X]);return Y.binaryType="arraybuffer",Y}var q81=(Z,J)=>{x7("streamBuilder");let X=lX0(J);X.hostname=X.hostname||X.host||"localhost";let $=cX0(X,Z),Y=A81(Z,$,X),Q=uX0.default.createWebSocketStream(Y,X.wsOptions);return Q.url=$,Y.on("close",()=>{Q.destroy()}),Q};v7.streamBuilder=q81;var C81=(Z,J)=>{x7("browserStreamBuilder");let X,Y=M81(J).browserBufferSize||524288,Q=J.browserBufferTimeout||1000,W=!J.objectMode,K=T81(Z,J),z=H(J,D,_);if(!J.objectMode)z._writev=_w.writev.bind(z);z.on("close",()=>{K.close()});let G=typeof K.addEventListener<"u";if(K.readyState===K.OPEN)X=z,X.socket=K;else if(X=new _w.BufferedDuplex(J,z,K),G)K.addEventListener("open",V);else K.onopen=V;if(G)K.addEventListener("close",F),K.addEventListener("error",B),K.addEventListener("message",U);else K.onclose=F,K.onerror=B,K.onmessage=U;function H(O,w,j){let q=new O81.Transform({objectMode:O.objectMode});return q._write=w,q._flush=j,q}function V(){if(x7("WebSocket onOpen"),X instanceof _w.BufferedDuplex)X.socketReady()}function F(O){x7("WebSocket onClose",O),X.end(),X.destroy()}function B(O){x7("WebSocket onError",O);let w=Error("WebSocket error");w.event=O,X.destroy(w)}async function U(O){if(!z||!z.readable||!z.writable)return;let{data:w}=O;if(w instanceof ArrayBuffer)w=WH.Buffer.from(w);else if(w instanceof Blob)w=WH.Buffer.from(await new Response(w).arrayBuffer());else w=WH.Buffer.from(w,"utf8");z.push(w)}function D(O,w,j){if(K.bufferedAmount>Y){setTimeout(D,Q,O,w,j);return}if(W&&typeof O==="string")O=WH.Buffer.from(O,"utf8");try{K.send(O)}catch(q){return j(q)}j()}function _(O){K.close(),O()}return X};v7.browserStreamBuilder=C81});var aX0=L((oX0)=>{Object.defineProperty(oX0,"__esModule",{value:!0});var pX0=N("buffer"),KJ={INVALID_ENCODING:"Invalid encoding provided. Please specify a valid encoding the internal Node.js Buffer supports.",INVALID_SMARTBUFFER_SIZE:"Invalid size provided. Size must be a valid integer greater than zero.",INVALID_SMARTBUFFER_BUFFER:"Invalid Buffer provided in SmartBufferOptions.",INVALID_SMARTBUFFER_OBJECT:"Invalid SmartBufferOptions object supplied to SmartBuffer constructor or factory methods.",INVALID_OFFSET:"An invalid offset value was provided.",INVALID_OFFSET_NON_NUMBER:"An invalid offset value was provided. A numeric value is required.",INVALID_LENGTH:"An invalid length value was provided.",INVALID_LENGTH_NON_NUMBER:"An invalid length value was provived. A numeric value is required.",INVALID_TARGET_OFFSET:"Target offset is beyond the bounds of the internal SmartBuffer data.",INVALID_TARGET_LENGTH:"Specified length value moves cursor beyong the bounds of the internal SmartBuffer data.",INVALID_READ_BEYOND_BOUNDS:"Attempted to read beyond the bounds of the managed data.",INVALID_WRITE_BEYOND_BOUNDS:"Attempted to write beyond the bounds of the managed data."};oX0.ERRORS=KJ;function N81(Z){if(!pX0.Buffer.isEncoding(Z))throw Error(KJ.INVALID_ENCODING)}oX0.checkEncoding=N81;function iX0(Z){return typeof Z==="number"&&isFinite(Z)&&I81(Z)}oX0.isFiniteInteger=iX0;function nX0(Z,J){if(typeof Z==="number"){if(!iX0(Z)||Z<0)throw Error(J?KJ.INVALID_OFFSET:KJ.INVALID_LENGTH)}else throw Error(J?KJ.INVALID_OFFSET_NON_NUMBER:KJ.INVALID_LENGTH_NON_NUMBER)}function R81(Z){nX0(Z,!1)}oX0.checkLengthValue=R81;function P81(Z){nX0(Z,!0)}oX0.checkOffsetValue=P81;function E81(Z,J){if(Z<0||Z>J.length)throw Error(KJ.INVALID_TARGET_OFFSET)}oX0.checkTargetOffset=E81;function I81(Z){return typeof Z==="number"&&isFinite(Z)&&Math.floor(Z)===Z}function y81(Z){if(typeof BigInt>"u")throw Error("Platform does not support JS BigInt type.");if(typeof pX0.Buffer.prototype[Z]>"u")throw Error(`Platform does not support Buffer.prototype.${Z}.`)}oX0.bigIntAndBufferInt64Check=y81});var tX0=L((sX0)=>{Object.defineProperty(sX0,"__esModule",{value:!0});var C0=aX0(),rX0=4096,g81="utf8";class ww{constructor(Z){if(this.length=0,this._encoding=g81,this._writeOffset=0,this._readOffset=0,ww.isSmartBufferOptions(Z)){if(Z.encoding)C0.checkEncoding(Z.encoding),this._encoding=Z.encoding;if(Z.size)if(C0.isFiniteInteger(Z.size)&&Z.size>0)this._buff=Buffer.allocUnsafe(Z.size);else throw Error(C0.ERRORS.INVALID_SMARTBUFFER_SIZE);else if(Z.buff)if(Buffer.isBuffer(Z.buff))this._buff=Z.buff,this.length=Z.buff.length;else throw Error(C0.ERRORS.INVALID_SMARTBUFFER_BUFFER);else this._buff=Buffer.allocUnsafe(rX0)}else{if(typeof Z<"u")throw Error(C0.ERRORS.INVALID_SMARTBUFFER_OBJECT);this._buff=Buffer.allocUnsafe(rX0)}}static fromSize(Z,J){return new this({size:Z,encoding:J})}static fromBuffer(Z,J){return new this({buff:Z,encoding:J})}static fromOptions(Z){return new this(Z)}static isSmartBufferOptions(Z){let J=Z;return J&&(J.encoding!==void 0||J.size!==void 0||J.buff!==void 0)}readInt8(Z){return this._readNumberValue(Buffer.prototype.readInt8,1,Z)}readInt16BE(Z){return this._readNumberValue(Buffer.prototype.readInt16BE,2,Z)}readInt16LE(Z){return this._readNumberValue(Buffer.prototype.readInt16LE,2,Z)}readInt32BE(Z){return this._readNumberValue(Buffer.prototype.readInt32BE,4,Z)}readInt32LE(Z){return this._readNumberValue(Buffer.prototype.readInt32LE,4,Z)}readBigInt64BE(Z){return C0.bigIntAndBufferInt64Check("readBigInt64BE"),this._readNumberValue(Buffer.prototype.readBigInt64BE,8,Z)}readBigInt64LE(Z){return C0.bigIntAndBufferInt64Check("readBigInt64LE"),this._readNumberValue(Buffer.prototype.readBigInt64LE,8,Z)}writeInt8(Z,J){return this._writeNumberValue(Buffer.prototype.writeInt8,1,Z,J),this}insertInt8(Z,J){return this._insertNumberValue(Buffer.prototype.writeInt8,1,Z,J)}writeInt16BE(Z,J){return this._writeNumberValue(Buffer.prototype.writeInt16BE,2,Z,J)}insertInt16BE(Z,J){return this._insertNumberValue(Buffer.prototype.writeInt16BE,2,Z,J)}writeInt16LE(Z,J){return this._writeNumberValue(Buffer.prototype.writeInt16LE,2,Z,J)}insertInt16LE(Z,J){return this._insertNumberValue(Buffer.prototype.writeInt16LE,2,Z,J)}writeInt32BE(Z,J){return this._writeNumberValue(Buffer.prototype.writeInt32BE,4,Z,J)}insertInt32BE(Z,J){return this._insertNumberValue(Buffer.prototype.writeInt32BE,4,Z,J)}writeInt32LE(Z,J){return this._writeNumberValue(Buffer.prototype.writeInt32LE,4,Z,J)}insertInt32LE(Z,J){return this._insertNumberValue(Buffer.prototype.writeInt32LE,4,Z,J)}writeBigInt64BE(Z,J){return C0.bigIntAndBufferInt64Check("writeBigInt64BE"),this._writeNumberValue(Buffer.prototype.writeBigInt64BE,8,Z,J)}insertBigInt64BE(Z,J){return C0.bigIntAndBufferInt64Check("writeBigInt64BE"),this._insertNumberValue(Buffer.prototype.writeBigInt64BE,8,Z,J)}writeBigInt64LE(Z,J){return C0.bigIntAndBufferInt64Check("writeBigInt64LE"),this._writeNumberValue(Buffer.prototype.writeBigInt64LE,8,Z,J)}insertBigInt64LE(Z,J){return C0.bigIntAndBufferInt64Check("writeBigInt64LE"),this._insertNumberValue(Buffer.prototype.writeBigInt64LE,8,Z,J)}readUInt8(Z){return this._readNumberValue(Buffer.prototype.readUInt8,1,Z)}readUInt16BE(Z){return this._readNumberValue(Buffer.prototype.readUInt16BE,2,Z)}readUInt16LE(Z){return this._readNumberValue(Buffer.prototype.readUInt16LE,2,Z)}readUInt32BE(Z){return this._readNumberValue(Buffer.prototype.readUInt32BE,4,Z)}readUInt32LE(Z){return this._readNumberValue(Buffer.prototype.readUInt32LE,4,Z)}readBigUInt64BE(Z){return C0.bigIntAndBufferInt64Check("readBigUInt64BE"),this._readNumberValue(Buffer.prototype.readBigUInt64BE,8,Z)}readBigUInt64LE(Z){return C0.bigIntAndBufferInt64Check("readBigUInt64LE"),this._readNumberValue(Buffer.prototype.readBigUInt64LE,8,Z)}writeUInt8(Z,J){return this._writeNumberValue(Buffer.prototype.writeUInt8,1,Z,J)}insertUInt8(Z,J){return this._insertNumberValue(Buffer.prototype.writeUInt8,1,Z,J)}writeUInt16BE(Z,J){return this._writeNumberValue(Buffer.prototype.writeUInt16BE,2,Z,J)}insertUInt16BE(Z,J){return this._insertNumberValue(Buffer.prototype.writeUInt16BE,2,Z,J)}writeUInt16LE(Z,J){return this._writeNumberValue(Buffer.prototype.writeUInt16LE,2,Z,J)}insertUInt16LE(Z,J){return this._insertNumberValue(Buffer.prototype.writeUInt16LE,2,Z,J)}writeUInt32BE(Z,J){return this._writeNumberValue(Buffer.prototype.writeUInt32BE,4,Z,J)}insertUInt32BE(Z,J){return this._insertNumberValue(Buffer.prototype.writeUInt32BE,4,Z,J)}writeUInt32LE(Z,J){return this._writeNumberValue(Buffer.prototype.writeUInt32LE,4,Z,J)}insertUInt32LE(Z,J){return this._insertNumberValue(Buffer.prototype.writeUInt32LE,4,Z,J)}writeBigUInt64BE(Z,J){return C0.bigIntAndBufferInt64Check("writeBigUInt64BE"),this._writeNumberValue(Buffer.prototype.writeBigUInt64BE,8,Z,J)}insertBigUInt64BE(Z,J){return C0.bigIntAndBufferInt64Check("writeBigUInt64BE"),this._insertNumberValue(Buffer.prototype.writeBigUInt64BE,8,Z,J)}writeBigUInt64LE(Z,J){return C0.bigIntAndBufferInt64Check("writeBigUInt64LE"),this._writeNumberValue(Buffer.prototype.writeBigUInt64LE,8,Z,J)}insertBigUInt64LE(Z,J){return C0.bigIntAndBufferInt64Check("writeBigUInt64LE"),this._insertNumberValue(Buffer.prototype.writeBigUInt64LE,8,Z,J)}readFloatBE(Z){return this._readNumberValue(Buffer.prototype.readFloatBE,4,Z)}readFloatLE(Z){return this._readNumberValue(Buffer.prototype.readFloatLE,4,Z)}writeFloatBE(Z,J){return this._writeNumberValue(Buffer.prototype.writeFloatBE,4,Z,J)}insertFloatBE(Z,J){return this._insertNumberValue(Buffer.prototype.writeFloatBE,4,Z,J)}writeFloatLE(Z,J){return this._writeNumberValue(Buffer.prototype.writeFloatLE,4,Z,J)}insertFloatLE(Z,J){return this._insertNumberValue(Buffer.prototype.writeFloatLE,4,Z,J)}readDoubleBE(Z){return this._readNumberValue(Buffer.prototype.readDoubleBE,8,Z)}readDoubleLE(Z){return this._readNumberValue(Buffer.prototype.readDoubleLE,8,Z)}writeDoubleBE(Z,J){return this._writeNumberValue(Buffer.prototype.writeDoubleBE,8,Z,J)}insertDoubleBE(Z,J){return this._insertNumberValue(Buffer.prototype.writeDoubleBE,8,Z,J)}writeDoubleLE(Z,J){return this._writeNumberValue(Buffer.prototype.writeDoubleLE,8,Z,J)}insertDoubleLE(Z,J){return this._insertNumberValue(Buffer.prototype.writeDoubleLE,8,Z,J)}readString(Z,J){let X;if(typeof Z==="number")C0.checkLengthValue(Z),X=Math.min(Z,this.length-this._readOffset);else J=Z,X=this.length-this._readOffset;if(typeof J<"u")C0.checkEncoding(J);let $=this._buff.slice(this._readOffset,this._readOffset+X).toString(J||this._encoding);return this._readOffset+=X,$}insertString(Z,J,X){return C0.checkOffsetValue(J),this._handleString(Z,!0,J,X)}writeString(Z,J,X){return this._handleString(Z,!1,J,X)}readStringNT(Z){if(typeof Z<"u")C0.checkEncoding(Z);let J=this.length;for(let $=this._readOffset;$<this.length;$++)if(this._buff[$]===0){J=$;break}let X=this._buff.slice(this._readOffset,J);return this._readOffset=J+1,X.toString(Z||this._encoding)}insertStringNT(Z,J,X){return C0.checkOffsetValue(J),this.insertString(Z,J,X),this.insertUInt8(0,J+Z.length),this}writeStringNT(Z,J,X){return this.writeString(Z,J,X),this.writeUInt8(0,typeof J==="number"?J+Z.length:this.writeOffset),this}readBuffer(Z){if(typeof Z<"u")C0.checkLengthValue(Z);let J=typeof Z==="number"?Z:this.length,X=Math.min(this.length,this._readOffset+J),$=this._buff.slice(this._readOffset,X);return this._readOffset=X,$}insertBuffer(Z,J){return C0.checkOffsetValue(J),this._handleBuffer(Z,!0,J)}writeBuffer(Z,J){return this._handleBuffer(Z,!1,J)}readBufferNT(){let Z=this.length;for(let X=this._readOffset;X<this.length;X++)if(this._buff[X]===0){Z=X;break}let J=this._buff.slice(this._readOffset,Z);return this._readOffset=Z+1,J}insertBufferNT(Z,J){return C0.checkOffsetValue(J),this.insertBuffer(Z,J),this.insertUInt8(0,J+Z.length),this}writeBufferNT(Z,J){if(typeof J<"u")C0.checkOffsetValue(J);return this.writeBuffer(Z,J),this.writeUInt8(0,typeof J==="number"?J+Z.length:this._writeOffset),this}clear(){return this._writeOffset=0,this._readOffset=0,this.length=0,this}remaining(){return this.length-this._readOffset}get readOffset(){return this._readOffset}set readOffset(Z){C0.checkOffsetValue(Z),C0.checkTargetOffset(Z,this),this._readOffset=Z}get writeOffset(){return this._writeOffset}set writeOffset(Z){C0.checkOffsetValue(Z),C0.checkTargetOffset(Z,this),this._writeOffset=Z}get encoding(){return this._encoding}set encoding(Z){C0.checkEncoding(Z),this._encoding=Z}get internalBuffer(){return this._buff}toBuffer(){return this._buff.slice(0,this.length)}toString(Z){let J=typeof Z==="string"?Z:this._encoding;return C0.checkEncoding(J),this._buff.toString(J,0,this.length)}destroy(){return this.clear(),this}_handleString(Z,J,X,$){let Y=this._writeOffset,Q=this._encoding;if(typeof X==="number")Y=X;else if(typeof X==="string")C0.checkEncoding(X),Q=X;if(typeof $==="string")C0.checkEncoding($),Q=$;let W=Buffer.byteLength(Z,Q);if(J)this.ensureInsertable(W,Y);else this._ensureWriteable(W,Y);if(this._buff.write(Z,Y,W,Q),J)this._writeOffset+=W;else if(typeof X==="number")this._writeOffset=Math.max(this._writeOffset,Y+W);else this._writeOffset+=W;return this}_handleBuffer(Z,J,X){let $=typeof X==="number"?X:this._writeOffset;if(J)this.ensureInsertable(Z.length,$);else this._ensureWriteable(Z.length,$);if(Z.copy(this._buff,$),J)this._writeOffset+=Z.length;else if(typeof X==="number")this._writeOffset=Math.max(this._writeOffset,$+Z.length);else this._writeOffset+=Z.length;return this}ensureReadable(Z,J){let X=this._readOffset;if(typeof J<"u")C0.checkOffsetValue(J),X=J;if(X<0||X+Z>this.length)throw Error(C0.ERRORS.INVALID_READ_BEYOND_BOUNDS)}ensureInsertable(Z,J){if(C0.checkOffsetValue(J),this._ensureCapacity(this.length+Z),J<this.length)this._buff.copy(this._buff,J+Z,J,this._buff.length);if(J+Z>this.length)this.length=J+Z;else this.length+=Z}_ensureWriteable(Z,J){let X=typeof J==="number"?J:this._writeOffset;if(this._ensureCapacity(X+Z),X+Z>this.length)this.length=X+Z}_ensureCapacity(Z){let J=this._buff.length;if(Z>J){let X=this._buff,$=J*3/2+1;if($<Z)$=Z;this._buff=Buffer.allocUnsafe($),X.copy(this._buff,0,0,J)}}_readNumberValue(Z,J,X){this.ensureReadable(J,X);let $=Z.call(this._buff,typeof X==="number"?X:this._readOffset);if(typeof X>"u")this._readOffset+=J;return $}_insertNumberValue(Z,J,X,$){return C0.checkOffsetValue($),this.ensureInsertable(J,$),Z.call(this._buff,X,$),this._writeOffset+=J,this}_writeNumberValue(Z,J,X,$){if(typeof $==="number"){if($<0)throw Error(C0.ERRORS.INVALID_WRITE_BEYOND_BOUNDS);C0.checkOffsetValue($)}let Y=typeof $==="number"?$:this._writeOffset;if(this._ensureWriteable(J,Y),Z.call(this._buff,X,Y),typeof $==="number")this._writeOffset=Math.max(this._writeOffset,Y+J);else this._writeOffset+=J;return this}}sX0.SmartBuffer=ww});var jw=L((Q$0)=>{Object.defineProperty(Q$0,"__esModule",{value:!0});Q$0.SOCKS5_NO_ACCEPTABLE_AUTH=Q$0.SOCKS5_CUSTOM_AUTH_END=Q$0.SOCKS5_CUSTOM_AUTH_START=Q$0.SOCKS_INCOMING_PACKET_SIZES=Q$0.SocksClientState=Q$0.Socks5Response=Q$0.Socks5HostType=Q$0.Socks5Auth=Q$0.Socks4Response=Q$0.SocksCommand=Q$0.ERRORS=Q$0.DEFAULT_TIMEOUT=void 0;var d81=30000;Q$0.DEFAULT_TIMEOUT=d81;var u81={InvalidSocksCommand:"An invalid SOCKS command was provided. Valid options are connect, bind, and associate.",InvalidSocksCommandForOperation:"An invalid SOCKS command was provided. Only a subset of commands are supported for this operation.",InvalidSocksCommandChain:"An invalid SOCKS command was provided. Chaining currently only supports the connect command.",InvalidSocksClientOptionsDestination:"An invalid destination host was provided.",InvalidSocksClientOptionsExistingSocket:"An invalid existing socket was provided. This should be an instance of stream.Duplex.",InvalidSocksClientOptionsProxy:"Invalid SOCKS proxy details were provided.",InvalidSocksClientOptionsTimeout:"An invalid timeout value was provided. Please enter a value above 0 (in ms).",InvalidSocksClientOptionsProxiesLength:"At least two socks proxies must be provided for chaining.",InvalidSocksClientOptionsCustomAuthRange:"Custom auth must be a value between 0x80 and 0xFE.",InvalidSocksClientOptionsCustomAuthOptions:"When a custom_auth_method is provided, custom_auth_request_handler, custom_auth_response_size, and custom_auth_response_handler must also be provided and valid.",NegotiationError:"Negotiation error",SocketClosed:"Socket closed",ProxyConnectionTimedOut:"Proxy connection timed out",InternalError:"SocksClient internal error (this should not happen)",InvalidSocks4HandshakeResponse:"Received invalid Socks4 handshake response",Socks4ProxyRejectedConnection:"Socks4 Proxy rejected connection",InvalidSocks4IncomingConnectionResponse:"Socks4 invalid incoming connection response",Socks4ProxyRejectedIncomingBoundConnection:"Socks4 Proxy rejected incoming bound connection",InvalidSocks5InitialHandshakeResponse:"Received invalid Socks5 initial handshake response",InvalidSocks5IntiailHandshakeSocksVersion:"Received invalid Socks5 initial handshake (invalid socks version)",InvalidSocks5InitialHandshakeNoAcceptedAuthType:"Received invalid Socks5 initial handshake (no accepted authentication type)",InvalidSocks5InitialHandshakeUnknownAuthType:"Received invalid Socks5 initial handshake (unknown authentication type)",Socks5AuthenticationFailed:"Socks5 Authentication failed",InvalidSocks5FinalHandshake:"Received invalid Socks5 final handshake response",InvalidSocks5FinalHandshakeRejected:"Socks5 proxy rejected connection",InvalidSocks5IncomingConnectionResponse:"Received invalid Socks5 incoming connection response",Socks5ProxyRejectedIncomingBoundConnection:"Socks5 Proxy rejected incoming bound connection"};Q$0.ERRORS=u81;var c81={Socks5InitialHandshakeResponse:2,Socks5UserPassAuthenticationResponse:2,Socks5ResponseHeader:5,Socks5ResponseIPv4:10,Socks5ResponseIPv6:22,Socks5ResponseHostname:(Z)=>Z+7,Socks4Response:8};Q$0.SOCKS_INCOMING_PACKET_SIZES=c81;var eX0;(function(Z){Z[Z.connect=1]="connect",Z[Z.bind=2]="bind",Z[Z.associate=3]="associate"})(eX0||(Q$0.SocksCommand=eX0={}));var Z$0;(function(Z){Z[Z.Granted=90]="Granted",Z[Z.Failed=91]="Failed",Z[Z.Rejected=92]="Rejected",Z[Z.RejectedIdent=93]="RejectedIdent"})(Z$0||(Q$0.Socks4Response=Z$0={}));var J$0;(function(Z){Z[Z.NoAuth=0]="NoAuth",Z[Z.GSSApi=1]="GSSApi",Z[Z.UserPass=2]="UserPass"})(J$0||(Q$0.Socks5Auth=J$0={}));var l81=128;Q$0.SOCKS5_CUSTOM_AUTH_START=l81;var p81=254;Q$0.SOCKS5_CUSTOM_AUTH_END=p81;var i81=255;Q$0.SOCKS5_NO_ACCEPTABLE_AUTH=i81;var X$0;(function(Z){Z[Z.Granted=0]="Granted",Z[Z.Failure=1]="Failure",Z[Z.NotAllowed=2]="NotAllowed",Z[Z.NetworkUnreachable=3]="NetworkUnreachable",Z[Z.HostUnreachable=4]="HostUnreachable",Z[Z.ConnectionRefused=5]="ConnectionRefused",Z[Z.TTLExpired=6]="TTLExpired",Z[Z.CommandNotSupported=7]="CommandNotSupported",Z[Z.AddressNotSupported=8]="AddressNotSupported"})(X$0||(Q$0.Socks5Response=X$0={}));var $$0;(function(Z){Z[Z.IPv4=1]="IPv4",Z[Z.Hostname=3]="Hostname",Z[Z.IPv6=4]="IPv6"})($$0||(Q$0.Socks5HostType=$$0={}));var Y$0;(function(Z){Z[Z.Created=0]="Created",Z[Z.Connecting=1]="Connecting",Z[Z.Connected=2]="Connected",Z[Z.SentInitialHandshake=3]="SentInitialHandshake",Z[Z.ReceivedInitialHandshakeResponse=4]="ReceivedInitialHandshakeResponse",Z[Z.SentAuthentication=5]="SentAuthentication",Z[Z.ReceivedAuthenticationResponse=6]="ReceivedAuthenticationResponse",Z[Z.SentFinalHandshake=7]="SentFinalHandshake",Z[Z.ReceivedFinalResponse=8]="ReceivedFinalResponse",Z[Z.BoundWaitingForConnection=9]="BoundWaitingForConnection",Z[Z.Established=10]="Established",Z[Z.Disconnected=11]="Disconnected",Z[Z.Error=99]="Error"})(Y$0||(Q$0.SocksClientState=Y$0={}))});var Mw=L((z$0)=>{Object.defineProperty(z$0,"__esModule",{value:!0});z$0.shuffleArray=z$0.SocksClientError=void 0;class K$0 extends Error{constructor(Z,J){super(Z);this.options=J}}z$0.SocksClientError=K$0;function Y51(Z){for(let J=Z.length-1;J>0;J--){let X=Math.floor(Math.random()*(J+1));[Z[J],Z[X]]=[Z[X],Z[J]]}}z$0.shuffleArray=Y51});var KH=L((V$0)=>{Object.defineProperty(V$0,"__esModule",{value:!0});V$0.isInSubnet=W51;V$0.isCorrect=K51;V$0.numberToPaddedHex=H$0;V$0.stringToPaddedHex=z51;V$0.testBit=G51;function W51(Z){if(this.subnetMask<Z.subnetMask)return!1;if(this.mask(Z.subnetMask)===Z.mask())return!0;return!1}function K51(Z){return function(){if(this.addressMinusSuffix!==this.correctForm())return!1;if(this.subnetMask===Z&&!this.parsedSubnet)return!0;return this.parsedSubnet===String(this.subnetMask)}}function H$0(Z){return Z.toString(16).padStart(2,"0")}function z51(Z){return H$0(parseInt(Z,10))}function G51(Z,J){let{length:X}=Z;if(J>X)return!1;let $=X-J;return Z.substring($,$+1)==="1"}});var Aw=L((F$0)=>{Object.defineProperty(F$0,"__esModule",{value:!0});F$0.RE_SUBNET_STRING=F$0.RE_ADDRESS=F$0.GROUPS=F$0.BITS=void 0;F$0.BITS=32;F$0.GROUPS=4;F$0.RE_ADDRESS=/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/g;F$0.RE_SUBNET_STRING=/\/\d{1,2}$/});var zH=L((L$0)=>{Object.defineProperty(L$0,"__esModule",{value:!0});L$0.AddressError=void 0;class U$0 extends Error{constructor(Z,J){super(Z);this.name="AddressError",this.parseMessage=J}}L$0.AddressError=U$0});var Tw=L((E5)=>{var O51=E5&&E5.__createBinding||(Object.create?function(Z,J,X,$){if($===void 0)$=X;var Y=Object.getOwnPropertyDescriptor(J,X);if(!Y||("get"in Y?!J.__esModule:Y.writable||Y.configurable))Y={enumerable:!0,get:function(){return J[X]}};Object.defineProperty(Z,$,Y)}:function(Z,J,X,$){if($===void 0)$=X;Z[$]=J[X]}),w51=E5&&E5.__setModuleDefault||(Object.create?function(Z,J){Object.defineProperty(Z,"default",{enumerable:!0,value:J})}:function(Z,J){Z.default=J}),_$0=E5&&E5.__importStar||function(Z){if(Z&&Z.__esModule)return Z;var J={};if(Z!=null){for(var X in Z)if(X!=="default"&&Object.prototype.hasOwnProperty.call(Z,X))O51(J,Z,X)}return w51(J,Z),J};Object.defineProperty(E5,"__esModule",{value:!0});E5.Address4=void 0;var F$=_$0(KH()),c8=_$0(Aw()),PQ=zH();class R6{constructor(Z){this.groups=c8.GROUPS,this.parsedAddress=[],this.parsedSubnet="",this.subnet="/32",this.subnetMask=32,this.v4=!0,this.isCorrect=F$.isCorrect(c8.BITS),this.isInSubnet=F$.isInSubnet,this.address=Z;let J=c8.RE_SUBNET_STRING.exec(Z);if(J){if(this.parsedSubnet=J[0].replace("/",""),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,this.subnetMask<0||this.subnetMask>c8.BITS)throw new PQ.AddressError("Invalid subnet mask.");Z=Z.replace(c8.RE_SUBNET_STRING,"")}this.addressMinusSuffix=Z,this.parsedAddress=this.parse(Z)}static isValid(Z){try{return new R6(Z),!0}catch(J){return!1}}parse(Z){let J=Z.split(".");if(!Z.match(c8.RE_ADDRESS))throw new PQ.AddressError("Invalid IPv4 address.");return J}correctForm(){return this.parsedAddress.map((Z)=>parseInt(Z,10)).join(".")}static fromHex(Z){let J=Z.replace(/:/g,"").padStart(8,"0"),X=[],$;for($=0;$<8;$+=2){let Y=J.slice($,$+2);X.push(parseInt(Y,16))}return new R6(X.join("."))}static fromInteger(Z){return R6.fromHex(Z.toString(16))}static fromArpa(Z){let X=Z.replace(/(\.in-addr\.arpa)?\.$/,"").split(".").reverse().join(".");return new R6(X)}toHex(){return this.parsedAddress.map((Z)=>F$.stringToPaddedHex(Z)).join(":")}toArray(){return this.parsedAddress.map((Z)=>parseInt(Z,10))}toGroup6(){let Z=[],J;for(J=0;J<c8.GROUPS;J+=2)Z.push(`${F$.stringToPaddedHex(this.parsedAddress[J])}${F$.stringToPaddedHex(this.parsedAddress[J+1])}`);return Z.join(":")}bigInt(){return BigInt(`0x${this.parsedAddress.map((Z)=>F$.stringToPaddedHex(Z)).join("")}`)}_startAddress(){return BigInt(`0b${this.mask()+"0".repeat(c8.BITS-this.subnetMask)}`)}startAddress(){return R6.fromBigInt(this._startAddress())}startAddressExclusive(){let Z=BigInt("1");return R6.fromBigInt(this._startAddress()+Z)}_endAddress(){return BigInt(`0b${this.mask()+"1".repeat(c8.BITS-this.subnetMask)}`)}endAddress(){return R6.fromBigInt(this._endAddress())}endAddressExclusive(){let Z=BigInt("1");return R6.fromBigInt(this._endAddress()-Z)}static fromBigInt(Z){return R6.fromHex(Z.toString(16))}static fromByteArray(Z){if(Z.length!==4)throw new PQ.AddressError("IPv4 addresses require exactly 4 bytes");for(let J=0;J<Z.length;J++)if(!Number.isInteger(Z[J])||Z[J]<0||Z[J]>255)throw new PQ.AddressError("All bytes must be integers between 0 and 255");return this.fromUnsignedByteArray(Z)}static fromUnsignedByteArray(Z){if(Z.length!==4)throw new PQ.AddressError("IPv4 addresses require exactly 4 bytes");let J=Z.join(".");return new R6(J)}mask(Z){if(Z===void 0)Z=this.subnetMask;return this.getBitsBase2(0,Z)}getBitsBase2(Z,J){return this.binaryZeroPad().slice(Z,J)}reverseForm(Z){if(!Z)Z={};let J=this.correctForm().split(".").reverse().join(".");if(Z.omitSuffix)return J;return`${J}.in-addr.arpa.`}isMulticast(){return this.isInSubnet(new R6("224.0.0.0/4"))}binaryZeroPad(){return this.bigInt().toString(2).padStart(c8.BITS,"0")}groupForV6(){let Z=this.parsedAddress;return this.address.replace(c8.RE_ADDRESS,`<span class="hover-group group-v4 group-6">${Z.slice(0,2).join(".")}</span>.<span class="hover-group group-v4 group-7">${Z.slice(2,4).join(".")}</span>`)}}E5.Address4=R6});var qw=L((O$0)=>{Object.defineProperty(O$0,"__esModule",{value:!0});O$0.RE_URL_WITH_PORT=O$0.RE_URL=O$0.RE_ZONE_STRING=O$0.RE_SUBNET_STRING=O$0.RE_BAD_ADDRESS=O$0.RE_BAD_CHARACTERS=O$0.TYPES=O$0.SCOPES=O$0.GROUPS=O$0.BITS=void 0;O$0.BITS=128;O$0.GROUPS=8;O$0.SCOPES={0:"Reserved",1:"Interface local",2:"Link local",4:"Admin local",5:"Site local",8:"Organization local",14:"Global",15:"Reserved"};O$0.TYPES={"ff01::1/128":"Multicast (All nodes on this interface)","ff01::2/128":"Multicast (All routers on this interface)","ff02::1/128":"Multicast (All nodes on this link)","ff02::2/128":"Multicast (All routers on this link)","ff05::2/128":"Multicast (All routers in this site)","ff02::5/128":"Multicast (OSPFv3 AllSPF routers)","ff02::6/128":"Multicast (OSPFv3 AllDR routers)","ff02::9/128":"Multicast (RIP routers)","ff02::a/128":"Multicast (EIGRP routers)","ff02::d/128":"Multicast (PIM routers)","ff02::16/128":"Multicast (MLDv2 reports)","ff01::fb/128":"Multicast (mDNSv6)","ff02::fb/128":"Multicast (mDNSv6)","ff05::fb/128":"Multicast (mDNSv6)","ff02::1:2/128":"Multicast (All DHCP servers and relay agents on this link)","ff05::1:2/128":"Multicast (All DHCP servers and relay agents in this site)","ff02::1:3/128":"Multicast (All DHCP servers on this link)","ff05::1:3/128":"Multicast (All DHCP servers in this site)","::/128":"Unspecified","::1/128":"Loopback","ff00::/8":"Multicast","fe80::/10":"Link-local unicast"};O$0.RE_BAD_CHARACTERS=/([^0-9a-f:/%])/gi;O$0.RE_BAD_ADDRESS=/([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi;O$0.RE_SUBNET_STRING=/\/\d{1,3}(?=%|$)/;O$0.RE_ZONE_STRING=/%.*$/;O$0.RE_URL=/^\[{0,1}([0-9a-f:]+)\]{0,1}/;O$0.RE_URL_WITH_PORT=/\[([0-9a-f:]+)\]:([0-9]{1,5})/});var Cw=L((A$0)=>{Object.defineProperty(A$0,"__esModule",{value:!0});A$0.spanAllZeroes=j$0;A$0.spanAll=E51;A$0.spanLeadingZeroes=I51;A$0.simpleGroup=y51;function j$0(Z){return Z.replace(/(0+)/g,'<span class="zero">$1</span>')}function E51(Z,J=0){return Z.split("").map(($,Y)=>`<span class="digit value-${$} position-${Y+J}">${j$0($)}</span>`).join("")}function M$0(Z){return Z.replace(/^(0+)/,'<span class="zero">$1</span>')}function I51(Z){return Z.split(":").map((X)=>M$0(X)).join(":")}function y51(Z,J=0){return Z.split(":").map(($,Y)=>{if(/group-v4/.test($))return $;return`<span class="hover-group group-${Y+J}">${M$0($)}</span>`})}});var T$0=L((H6)=>{var h51=H6&&H6.__createBinding||(Object.create?function(Z,J,X,$){if($===void 0)$=X;var Y=Object.getOwnPropertyDescriptor(J,X);if(!Y||("get"in Y?!J.__esModule:Y.writable||Y.configurable))Y={enumerable:!0,get:function(){return J[X]}};Object.defineProperty(Z,$,Y)}:function(Z,J,X,$){if($===void 0)$=X;Z[$]=J[X]}),f51=H6&&H6.__setModuleDefault||(Object.create?function(Z,J){Object.defineProperty(Z,"default",{enumerable:!0,value:J})}:function(Z,J){Z.default=J}),b51=H6&&H6.__importStar||function(Z){if(Z&&Z.__esModule)return Z;var J={};if(Z!=null){for(var X in Z)if(X!=="default"&&Object.prototype.hasOwnProperty.call(Z,X))h51(J,Z,X)}return f51(J,Z),J};Object.defineProperty(H6,"__esModule",{value:!0});H6.ADDRESS_BOUNDARY=void 0;H6.groupPossibilities=HH;H6.padGroup=GH;H6.simpleRegularExpression=m51;H6.possibleElisions=d51;var g51=b51(qw());function HH(Z){return`(${Z.join("|")})`}function GH(Z){if(Z.length<4)return`0{0,${4-Z.length}}${Z}`;return Z}H6.ADDRESS_BOUNDARY="[^A-Fa-f0-9:]";function m51(Z){let J=[];Z.forEach(($,Y)=>{if(parseInt($,16)===0)J.push(Y)});let X=J.map(($)=>Z.map((Y,Q)=>{if(Q===$){let W=Q===0||Q===g51.GROUPS-1?":":"";return HH([GH(Y),W])}return GH(Y)}).join(":"));return X.push(Z.map(GH).join(":")),HH(X)}function d51(Z,J,X){let $=J?"":":",Y=X?"":":",Q=[];if(!J&&!X)Q.push("::");if(J&&X)Q.push("");if(X&&!J||!X&&J)Q.push(":");Q.push(`${$}(:0{1,4}){1,${Z-1}}`),Q.push(`(0{1,4}:){1,${Z-1}}${Y}`),Q.push(`(0{1,4}:){${Z-1}}0{1,4}`);for(let W=1;W<Z-1;W++)for(let K=1;K<Z-W;K++)Q.push(`(0{1,4}:){${K}}:(0{1,4}:){${Z-K-W-1}}0{1,4}`);return HH(Q)}});var R$0=L((I5)=>{var u51=I5&&I5.__createBinding||(Object.create?function(Z,J,X,$){if($===void 0)$=X;var Y=Object.getOwnPropertyDescriptor(J,X);if(!Y||("get"in Y?!J.__esModule:Y.writable||Y.configurable))Y={enumerable:!0,get:function(){return J[X]}};Object.defineProperty(Z,$,Y)}:function(Z,J,X,$){if($===void 0)$=X;Z[$]=J[X]}),c51=I5&&I5.__setModuleDefault||(Object.create?function(Z,J){Object.defineProperty(Z,"default",{enumerable:!0,value:J})}:function(Z,J){Z.default=J}),BH=I5&&I5.__importStar||function(Z){if(Z&&Z.__esModule)return Z;var J={};if(Z!=null){for(var X in Z)if(X!=="default"&&Object.prototype.hasOwnProperty.call(Z,X))u51(J,Z,X)}return c51(J,Z),J};Object.defineProperty(I5,"__esModule",{value:!0});I5.Address6=void 0;var q$0=BH(KH()),Nw=BH(Aw()),Z1=BH(qw()),Rw=BH(Cw()),zJ=Tw(),GJ=T$0(),q9=zH(),VH=KH();function FH(Z){if(!Z)throw Error("Assertion failed.")}function l51(Z){let J=/(\d+)(\d{3})/;while(J.test(Z))Z=Z.replace(J,"$1,$2");return Z}function p51(Z){return Z=Z.replace(/^(0{1,})([1-9]+)$/,'<span class="parse-error">$1</span>$2'),Z=Z.replace(/^(0{1,})(0)$/,'<span class="parse-error">$1</span>$2'),Z}function i51(Z,J){let X=[],$=[],Y;for(Y=0;Y<Z.length;Y++)if(Y<J[0])X.push(Z[Y]);else if(Y>J[1])$.push(Z[Y]);return X.concat(["compact"]).concat($)}function C$0(Z){return parseInt(Z,16).toString(16).padStart(4,"0")}function N$0(Z){return Z&255}class X4{constructor(Z,J){if(this.addressMinusSuffix="",this.parsedSubnet="",this.subnet="/128",this.subnetMask=128,this.v4=!1,this.zone="",this.isInSubnet=q$0.isInSubnet,this.isCorrect=q$0.isCorrect(Z1.BITS),J===void 0)this.groups=Z1.GROUPS;else this.groups=J;this.address=Z;let X=Z1.RE_SUBNET_STRING.exec(Z);if(X){if(this.parsedSubnet=X[0].replace("/",""),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,Number.isNaN(this.subnetMask)||this.subnetMask<0||this.subnetMask>Z1.BITS)throw new q9.AddressError("Invalid subnet mask.");Z=Z.replace(Z1.RE_SUBNET_STRING,"")}else if(/\//.test(Z))throw new q9.AddressError("Invalid subnet mask.");let $=Z1.RE_ZONE_STRING.exec(Z);if($)this.zone=$[0],Z=Z.replace(Z1.RE_ZONE_STRING,"");this.addressMinusSuffix=Z,this.parsedAddress=this.parse(this.addressMinusSuffix)}static isValid(Z){try{return new X4(Z),!0}catch(J){return!1}}static fromBigInt(Z){let J=Z.toString(16).padStart(32,"0"),X=[],$;for($=0;$<Z1.GROUPS;$++)X.push(J.slice($*4,($+1)*4));return new X4(X.join(":"))}static fromURL(Z){let J,X=null,$;if(Z.indexOf("[")!==-1&&Z.indexOf("]:")!==-1){if($=Z1.RE_URL_WITH_PORT.exec(Z),$===null)return{error:"failed to parse address with port",address:null,port:null};J=$[1],X=$[2]}else if(Z.indexOf("/")!==-1){if(Z=Z.replace(/^[a-z0-9]+:\/\//,""),$=Z1.RE_URL.exec(Z),$===null)return{error:"failed to parse address from URL",address:null,port:null};J=$[1]}else J=Z;if(X){if(X=parseInt(X,10),X<0||X>65536)X=null}else X=null;return{address:new X4(J),port:X}}static fromAddress4(Z){let J=new zJ.Address4(Z),X=Z1.BITS-(Nw.BITS-J.subnetMask);return new X4(`::ffff:${J.correctForm()}/${X}`)}static fromArpa(Z){let J=Z.replace(/(\.ip6\.arpa)?\.$/,""),X=7;if(J.length!==63)throw new q9.AddressError("Invalid 'ip6.arpa' form.");let $=J.split(".").reverse();for(let Y=X;Y>0;Y--){let Q=Y*4;$.splice(Q,0,":")}return J=$.join(""),new X4(J)}microsoftTranscription(){return`${this.correctForm().replace(/:/g,"-")}.ipv6-literal.net`}mask(Z=this.subnetMask){return this.getBitsBase2(0,Z)}possibleSubnets(Z=128){let J=Z1.BITS-this.subnetMask,X=Math.abs(Z-Z1.BITS),$=J-X;if($<0)return"0";return l51((BigInt("2")**BigInt($)).toString(10))}_startAddress(){return BigInt(`0b${this.mask()+"0".repeat(Z1.BITS-this.subnetMask)}`)}startAddress(){return X4.fromBigInt(this._startAddress())}startAddressExclusive(){let Z=BigInt("1");return X4.fromBigInt(this._startAddress()+Z)}_endAddress(){return BigInt(`0b${this.mask()+"1".repeat(Z1.BITS-this.subnetMask)}`)}endAddress(){return X4.fromBigInt(this._endAddress())}endAddressExclusive(){let Z=BigInt("1");return X4.fromBigInt(this._endAddress()-Z)}getScope(){let Z=Z1.SCOPES[parseInt(this.getBits(12,16).toString(10),10)];if(this.getType()==="Global unicast"&&Z!=="Link local")Z="Global";return Z||"Unknown"}getType(){for(let Z of Object.keys(Z1.TYPES))if(this.isInSubnet(new X4(Z)))return Z1.TYPES[Z];return"Global unicast"}getBits(Z,J){return BigInt(`0b${this.getBitsBase2(Z,J)}`)}getBitsBase2(Z,J){return this.binaryZeroPad().slice(Z,J)}getBitsBase16(Z,J){let X=J-Z;if(X%4!==0)throw Error("Length of bits to retrieve must be divisible by four");return this.getBits(Z,J).toString(16).padStart(X/4,"0")}getBitsPastSubnet(){return this.getBitsBase2(this.subnetMask,Z1.BITS)}reverseForm(Z){if(!Z)Z={};let J=Math.floor(this.subnetMask/4),X=this.canonicalForm().replace(/:/g,"").split("").slice(0,J).reverse().join(".");if(J>0){if(Z.omitSuffix)return X;return`${X}.ip6.arpa.`}if(Z.omitSuffix)return"";return"ip6.arpa."}correctForm(){let Z,J=[],X=0,$=[];for(Z=0;Z<this.parsedAddress.length;Z++){let W=parseInt(this.parsedAddress[Z],16);if(W===0)X++;if(W!==0&&X>0){if(X>1)$.push([Z-X,Z-1]);X=0}}if(X>1)$.push([this.parsedAddress.length-X,this.parsedAddress.length-1]);let Y=$.map((W)=>W[1]-W[0]+1);if($.length>0){let W=Y.indexOf(Math.max(...Y));J=i51(this.parsedAddress,$[W])}else J=this.parsedAddress;for(Z=0;Z<J.length;Z++)if(J[Z]!=="compact")J[Z]=parseInt(J[Z],16).toString(16);let Q=J.join(":");return Q=Q.replace(/^compact$/,"::"),Q=Q.replace(/(^compact)|(compact$)/,":"),Q=Q.replace(/compact/,""),Q}binaryZeroPad(){return this.bigInt().toString(2).padStart(Z1.BITS,"0")}parse4in6(Z){let J=Z.split(":"),$=J.slice(-1)[0].match(Nw.RE_ADDRESS);if($){this.parsedAddress4=$[0],this.address4=new zJ.Address4(this.parsedAddress4);for(let Y=0;Y<this.address4.groups;Y++)if(/^0[0-9]+/.test(this.address4.parsedAddress[Y]))throw new q9.AddressError("IPv4 addresses can't have leading zeroes.",Z.replace(Nw.RE_ADDRESS,this.address4.parsedAddress.map(p51).join(".")));this.v4=!0,J[J.length-1]=this.address4.toGroup6(),Z=J.join(":")}return Z}parse(Z){Z=this.parse4in6(Z);let J=Z.match(Z1.RE_BAD_CHARACTERS);if(J)throw new q9.AddressError(`Bad character${J.length>1?"s":""} detected in address: ${J.join("")}`,Z.replace(Z1.RE_BAD_CHARACTERS,'<span class="parse-error">$1</span>'));let X=Z.match(Z1.RE_BAD_ADDRESS);if(X)throw new q9.AddressError(`Address failed regex: ${X.join("")}`,Z.replace(Z1.RE_BAD_ADDRESS,'<span class="parse-error">$1</span>'));let $=[],Y=Z.split("::");if(Y.length===2){let Q=Y[0].split(":"),W=Y[1].split(":");if(Q.length===1&&Q[0]==="")Q=[];if(W.length===1&&W[0]==="")W=[];let K=this.groups-(Q.length+W.length);if(!K)throw new q9.AddressError("Error parsing groups");this.elidedGroups=K,this.elisionBegin=Q.length,this.elisionEnd=Q.length+this.elidedGroups,$=$.concat(Q);for(let z=0;z<K;z++)$.push("0");$=$.concat(W)}else if(Y.length===1)$=Z.split(":"),this.elidedGroups=0;else throw new q9.AddressError("Too many :: groups found");if($=$.map((Q)=>parseInt(Q,16).toString(16)),$.length!==this.groups)throw new q9.AddressError("Incorrect number of groups found");return $}canonicalForm(){return this.parsedAddress.map(C$0).join(":")}decimal(){return this.parsedAddress.map((Z)=>parseInt(Z,16).toString(10).padStart(5,"0")).join(":")}bigInt(){return BigInt(`0x${this.parsedAddress.map(C$0).join("")}`)}to4(){let Z=this.binaryZeroPad().split("");return zJ.Address4.fromHex(BigInt(`0b${Z.slice(96,128).join("")}`).toString(16))}to4in6(){let Z=this.to4(),X=new X4(this.parsedAddress.slice(0,6).join(":"),6).correctForm(),$="";if(!/:$/.test(X))$=":";return X+$+Z.address}inspectTeredo(){let Z=this.getBitsBase16(0,32),X=(this.getBits(80,96)^BigInt("0xffff")).toString(),$=zJ.Address4.fromHex(this.getBitsBase16(32,64)),Y=this.getBits(96,128),Q=zJ.Address4.fromHex((Y^BigInt("0xffffffff")).toString(16)),W=this.getBitsBase2(64,80),K=(0,VH.testBit)(W,15),z=(0,VH.testBit)(W,14),G=(0,VH.testBit)(W,8),H=(0,VH.testBit)(W,9),V=BigInt(`0b${W.slice(2,6)+W.slice(8,16)}`).toString(10);return{prefix:`${Z.slice(0,4)}:${Z.slice(4,8)}`,server4:$.address,client4:Q.address,flags:W,coneNat:K,microsoft:{reserved:z,universalLocal:H,groupIndividual:G,nonce:V},udpPort:X}}inspect6to4(){let Z=this.getBitsBase16(0,16),J=zJ.Address4.fromHex(this.getBitsBase16(16,48));return{prefix:Z.slice(0,4),gateway:J.address}}to6to4(){if(!this.is4())return null;let Z=["2002",this.getBitsBase16(96,112),this.getBitsBase16(112,128),"","/16"].join(":");return new X4(Z)}toByteArray(){let Z=this.bigInt().toString(16),X=`${"0".repeat(Z.length%2)}${Z}`,$=[];for(let Y=0,Q=X.length;Y<Q;Y+=2)$.push(parseInt(X.substring(Y,Y+2),16));return $}toUnsignedByteArray(){return this.toByteArray().map(N$0)}static fromByteArray(Z){return this.fromUnsignedByteArray(Z.map(N$0))}static fromUnsignedByteArray(Z){let J=BigInt("256"),X=BigInt("0"),$=BigInt("1");for(let Y=Z.length-1;Y>=0;Y--)X+=$*BigInt(Z[Y].toString(10)),$*=J;return X4.fromBigInt(X)}isCanonical(){return this.addressMinusSuffix===this.canonicalForm()}isLinkLocal(){if(this.getBitsBase2(0,64)==="1111111010000000000000000000000000000000000000000000000000000000")return!0;return!1}isMulticast(){return this.getType()==="Multicast"}is4(){return this.v4}isTeredo(){return this.isInSubnet(new X4("2001::/32"))}is6to4(){return this.isInSubnet(new X4("2002::/16"))}isLoopback(){return this.getType()==="Loopback"}href(Z){if(Z===void 0)Z="";else Z=`:${Z}`;return`http://[${this.correctForm()}]${Z}/`}link(Z){if(!Z)Z={};if(Z.className===void 0)Z.className="";if(Z.prefix===void 0)Z.prefix="/#address=";if(Z.v4===void 0)Z.v4=!1;let J=this.correctForm;if(Z.v4)J=this.to4in6;let X=J.call(this);if(Z.className)return`<a href="${Z.prefix}${X}" class="${Z.className}">${X}</a>`;return`<a href="${Z.prefix}${X}">${X}</a>`}group(){if(this.elidedGroups===0)return Rw.simpleGroup(this.address).join(":");FH(typeof this.elidedGroups==="number"),FH(typeof this.elisionBegin==="number");let Z=[],[J,X]=this.address.split("::");if(J.length)Z.push(...Rw.simpleGroup(J));else Z.push("");let $=["hover-group"];for(let Y=this.elisionBegin;Y<this.elisionBegin+this.elidedGroups;Y++)$.push(`group-${Y}`);if(Z.push(`<span class="${$.join(" ")}"></span>`),X.length)Z.push(...Rw.simpleGroup(X,this.elisionEnd));else Z.push("");if(this.is4())FH(this.address4 instanceof zJ.Address4),Z.pop(),Z.push(this.address4.groupForV6());return Z.join(":")}regularExpressionString(Z=!1){let J=[],X=new X4(this.correctForm());if(X.elidedGroups===0)J.push((0,GJ.simpleRegularExpression)(X.parsedAddress));else if(X.elidedGroups===Z1.GROUPS)J.push((0,GJ.possibleElisions)(Z1.GROUPS));else{let $=X.address.split("::");if($[0].length)J.push((0,GJ.simpleRegularExpression)($[0].split(":")));if(FH(typeof X.elidedGroups==="number"),J.push((0,GJ.possibleElisions)(X.elidedGroups,$[0].length!==0,$[1].length!==0)),$[1].length)J.push((0,GJ.simpleRegularExpression)($[1].split(":")));J=[J.join(":")]}if(!Z)J=["(?=^|",GJ.ADDRESS_BOUNDARY,"|[^\\w\\:])(",...J,")(?=[^\\w\\:]|",GJ.ADDRESS_BOUNDARY,"|$)"];return J.join("")}regularExpression(Z=!1){return new RegExp(this.regularExpressionString(Z),"i")}}I5.Address6=X4});var Pw=L((N4)=>{var n51=N4&&N4.__createBinding||(Object.create?function(Z,J,X,$){if($===void 0)$=X;var Y=Object.getOwnPropertyDescriptor(J,X);if(!Y||("get"in Y?!J.__esModule:Y.writable||Y.configurable))Y={enumerable:!0,get:function(){return J[X]}};Object.defineProperty(Z,$,Y)}:function(Z,J,X,$){if($===void 0)$=X;Z[$]=J[X]}),o51=N4&&N4.__setModuleDefault||(Object.create?function(Z,J){Object.defineProperty(Z,"default",{enumerable:!0,value:J})}:function(Z,J){Z.default=J}),a51=N4&&N4.__importStar||function(Z){if(Z&&Z.__esModule)return Z;var J={};if(Z!=null){for(var X in Z)if(X!=="default"&&Object.prototype.hasOwnProperty.call(Z,X))n51(J,Z,X)}return o51(J,Z),J};Object.defineProperty(N4,"__esModule",{value:!0});N4.v6=N4.AddressError=N4.Address6=N4.Address4=void 0;var r51=Tw();Object.defineProperty(N4,"Address4",{enumerable:!0,get:function(){return r51.Address4}});var s51=R$0();Object.defineProperty(N4,"Address6",{enumerable:!0,get:function(){return s51.Address6}});var t51=zH();Object.defineProperty(N4,"AddressError",{enumerable:!0,get:function(){return t51.AddressError}});var e51=a51(Cw());N4.v6={helpers:e51}});var v$0=L((k$0)=>{Object.defineProperty(k$0,"__esModule",{value:!0});k$0.ipToBuffer=k$0.int32ToIpv4=k$0.ipv4ToInt32=k$0.validateSocksClientChainOptions=k$0.validateSocksClientOptions=void 0;var d4=Mw(),$4=jw(),Z91=N("stream"),Ew=Pw(),P$0=N("net");function J91(Z,J=["connect","bind","associate"]){if(!$4.SocksCommand[Z.command])throw new d4.SocksClientError($4.ERRORS.InvalidSocksCommand,Z);if(J.indexOf(Z.command)===-1)throw new d4.SocksClientError($4.ERRORS.InvalidSocksCommandForOperation,Z);if(!I$0(Z.destination))throw new d4.SocksClientError($4.ERRORS.InvalidSocksClientOptionsDestination,Z);if(!y$0(Z.proxy))throw new d4.SocksClientError($4.ERRORS.InvalidSocksClientOptionsProxy,Z);if(E$0(Z.proxy,Z),Z.timeout&&!S$0(Z.timeout))throw new d4.SocksClientError($4.ERRORS.InvalidSocksClientOptionsTimeout,Z);if(Z.existing_socket&&!(Z.existing_socket instanceof Z91.Duplex))throw new d4.SocksClientError($4.ERRORS.InvalidSocksClientOptionsExistingSocket,Z)}k$0.validateSocksClientOptions=J91;function X91(Z){if(Z.command!=="connect")throw new d4.SocksClientError($4.ERRORS.InvalidSocksCommandChain,Z);if(!I$0(Z.destination))throw new d4.SocksClientError($4.ERRORS.InvalidSocksClientOptionsDestination,Z);if(!(Z.proxies&&Array.isArray(Z.proxies)&&Z.proxies.length>=2))throw new d4.SocksClientError($4.ERRORS.InvalidSocksClientOptionsProxiesLength,Z);if(Z.proxies.forEach((J)=>{if(!y$0(J))throw new d4.SocksClientError($4.ERRORS.InvalidSocksClientOptionsProxy,Z);E$0(J,Z)}),Z.timeout&&!S$0(Z.timeout))throw new d4.SocksClientError($4.ERRORS.InvalidSocksClientOptionsTimeout,Z)}k$0.validateSocksClientChainOptions=X91;function E$0(Z,J){if(Z.custom_auth_method!==void 0){if(Z.custom_auth_method<$4.SOCKS5_CUSTOM_AUTH_START||Z.custom_auth_method>$4.SOCKS5_CUSTOM_AUTH_END)throw new d4.SocksClientError($4.ERRORS.InvalidSocksClientOptionsCustomAuthRange,J);if(Z.custom_auth_request_handler===void 0||typeof Z.custom_auth_request_handler!=="function")throw new d4.SocksClientError($4.ERRORS.InvalidSocksClientOptionsCustomAuthOptions,J);if(Z.custom_auth_response_size===void 0)throw new d4.SocksClientError($4.ERRORS.InvalidSocksClientOptionsCustomAuthOptions,J);if(Z.custom_auth_response_handler===void 0||typeof Z.custom_auth_response_handler!=="function")throw new d4.SocksClientError($4.ERRORS.InvalidSocksClientOptionsCustomAuthOptions,J)}}function I$0(Z){return Z&&typeof Z.host==="string"&&Buffer.byteLength(Z.host)<256&&typeof Z.port==="number"&&Z.port>=0&&Z.port<=65535}function y$0(Z){return Z&&(typeof Z.host==="string"||typeof Z.ipaddress==="string")&&typeof Z.port==="number"&&Z.port>=0&&Z.port<=65535&&(Z.type===4||Z.type===5)}function S$0(Z){return typeof Z==="number"&&Z>0}function $91(Z){return new Ew.Address4(Z).toArray().reduce((X,$)=>(X<<8)+$,0)>>>0}k$0.ipv4ToInt32=$91;function Y91(Z){let J=Z>>>24&255,X=Z>>>16&255,$=Z>>>8&255,Y=Z&255;return[J,X,$,Y].join(".")}k$0.int32ToIpv4=Y91;function Q91(Z){if(P$0.isIPv4(Z)){let J=new Ew.Address4(Z);return Buffer.from(J.toArray())}else if(P$0.isIPv6(Z)){let J=new Ew.Address6(Z);return Buffer.from(J.canonicalForm().split(":").map((X)=>X.padStart(4,"0")).join(""),"hex")}else throw Error("Invalid IP address format")}k$0.ipToBuffer=Q91});var g$0=L((f$0)=>{Object.defineProperty(f$0,"__esModule",{value:!0});f$0.ReceiveBuffer=void 0;class h$0{constructor(Z=4096){this.buffer=Buffer.allocUnsafe(Z),this.offset=0,this.originalSize=Z}get length(){return this.offset}append(Z){if(!Buffer.isBuffer(Z))throw Error("Attempted to append a non-buffer instance to ReceiveBuffer.");if(this.offset+Z.length>=this.buffer.length){let J=this.buffer;this.buffer=Buffer.allocUnsafe(Math.max(this.buffer.length+this.originalSize,this.buffer.length+Z.length)),J.copy(this.buffer)}return Z.copy(this.buffer,this.offset),this.offset+=Z.length}peek(Z){if(Z>this.offset)throw Error("Attempted to read beyond the bounds of the managed internal data.");return this.buffer.slice(0,Z)}get(Z){if(Z>this.offset)throw Error("Attempted to read beyond the bounds of the managed internal data.");let J=Buffer.allocUnsafe(Z);return this.buffer.slice(0,Z).copy(J),this.buffer.copyWithin(0,Z,Z+this.offset-Z),this.offset-=Z,J}}f$0.ReceiveBuffer=h$0});var m$0=L((h7)=>{var B$=h7&&h7.__awaiter||function(Z,J,X,$){function Y(Q){return Q instanceof X?Q:new X(function(W){W(Q)})}return new(X||(X=Promise))(function(Q,W){function K(H){try{G($.next(H))}catch(V){W(V)}}function z(H){try{G($.throw(H))}catch(V){W(V)}}function G(H){H.done?Q(H.value):Y(H.value).then(K,z)}G(($=$.apply(Z,J||[])).next())})};Object.defineProperty(h7,"__esModule",{value:!0});h7.SocksClientError=h7.SocksClient=void 0;var H91=N("events"),U$=N("net"),V6=tX0(),v=jw(),P6=v$0(),V91=g$0(),yw=Mw();Object.defineProperty(h7,"SocksClientError",{enumerable:!0,get:function(){return yw.SocksClientError}});var Iw=Pw();class UH extends H91.EventEmitter{constructor(Z){super();this.options=Object.assign({},Z),(0,P6.validateSocksClientOptions)(Z),this.setState(v.SocksClientState.Created)}static createConnection(Z,J){return new Promise((X,$)=>{try{(0,P6.validateSocksClientOptions)(Z,["connect"])}catch(Q){if(typeof J==="function")return J(Q),X(Q);else return $(Q)}let Y=new UH(Z);Y.connect(Z.existing_socket),Y.once("established",(Q)=>{if(Y.removeAllListeners(),typeof J==="function")J(null,Q),X(Q);else X(Q)}),Y.once("error",(Q)=>{if(Y.removeAllListeners(),typeof J==="function")J(Q),X(Q);else $(Q)})})}static createConnectionChain(Z,J){return new Promise((X,$)=>B$(this,void 0,void 0,function*(){try{(0,P6.validateSocksClientChainOptions)(Z)}catch(Y){if(typeof J==="function")return J(Y),X(Y);else return $(Y)}if(Z.randomizeChain)(0,yw.shuffleArray)(Z.proxies);try{let Y;for(let Q=0;Q<Z.proxies.length;Q++){let W=Z.proxies[Q],K=Q===Z.proxies.length-1?Z.destination:{host:Z.proxies[Q+1].host||Z.proxies[Q+1].ipaddress,port:Z.proxies[Q+1].port},z=yield UH.createConnection({command:"connect",proxy:W,destination:K,existing_socket:Y});Y=Y||z.socket}if(typeof J==="function")J(null,{socket:Y}),X({socket:Y});else X({socket:Y})}catch(Y){if(typeof J==="function")J(Y),X(Y);else $(Y)}}))}static createUDPFrame(Z){let J=new V6.SmartBuffer;if(J.writeUInt16BE(0),J.writeUInt8(Z.frameNumber||0),U$.isIPv4(Z.remoteHost.host))J.writeUInt8(v.Socks5HostType.IPv4),J.writeUInt32BE((0,P6.ipv4ToInt32)(Z.remoteHost.host));else if(U$.isIPv6(Z.remoteHost.host))J.writeUInt8(v.Socks5HostType.IPv6),J.writeBuffer((0,P6.ipToBuffer)(Z.remoteHost.host));else J.writeUInt8(v.Socks5HostType.Hostname),J.writeUInt8(Buffer.byteLength(Z.remoteHost.host)),J.writeString(Z.remoteHost.host);return J.writeUInt16BE(Z.remoteHost.port),J.writeBuffer(Z.data),J.toBuffer()}static parseUDPFrame(Z){let J=V6.SmartBuffer.fromBuffer(Z);J.readOffset=2;let X=J.readUInt8(),$=J.readUInt8(),Y;if($===v.Socks5HostType.IPv4)Y=(0,P6.int32ToIpv4)(J.readUInt32BE());else if($===v.Socks5HostType.IPv6)Y=Iw.Address6.fromByteArray(Array.from(J.readBuffer(16))).canonicalForm();else Y=J.readString(J.readUInt8());let Q=J.readUInt16BE();return{frameNumber:X,remoteHost:{host:Y,port:Q},data:J.readBuffer()}}setState(Z){if(this.state!==v.SocksClientState.Error)this.state=Z}connect(Z){this.onDataReceived=(X)=>this.onDataReceivedHandler(X),this.onClose=()=>this.onCloseHandler(),this.onError=(X)=>this.onErrorHandler(X),this.onConnect=()=>this.onConnectHandler();let J=setTimeout(()=>this.onEstablishedTimeout(),this.options.timeout||v.DEFAULT_TIMEOUT);if(J.unref&&typeof J.unref==="function")J.unref();if(Z)this.socket=Z;else this.socket=new U$.Socket;if(this.socket.once("close",this.onClose),this.socket.once("error",this.onError),this.socket.once("connect",this.onConnect),this.socket.on("data",this.onDataReceived),this.setState(v.SocksClientState.Connecting),this.receiveBuffer=new V91.ReceiveBuffer,Z)this.socket.emit("connect");else if(this.socket.connect(this.getSocketOptions()),this.options.set_tcp_nodelay!==void 0&&this.options.set_tcp_nodelay!==null)this.socket.setNoDelay(!!this.options.set_tcp_nodelay);this.prependOnceListener("established",(X)=>{setImmediate(()=>{if(this.receiveBuffer.length>0){let $=this.receiveBuffer.get(this.receiveBuffer.length);X.socket.emit("data",$)}X.socket.resume()})})}getSocketOptions(){return Object.assign(Object.assign({},this.options.socket_options),{host:this.options.proxy.host||this.options.proxy.ipaddress,port:this.options.proxy.port})}onEstablishedTimeout(){if(this.state!==v.SocksClientState.Established&&this.state!==v.SocksClientState.BoundWaitingForConnection)this.closeSocket(v.ERRORS.ProxyConnectionTimedOut)}onConnectHandler(){if(this.setState(v.SocksClientState.Connected),this.options.proxy.type===4)this.sendSocks4InitialHandshake();else this.sendSocks5InitialHandshake();this.setState(v.SocksClientState.SentInitialHandshake)}onDataReceivedHandler(Z){this.receiveBuffer.append(Z),this.processData()}processData(){while(this.state!==v.SocksClientState.Established&&this.state!==v.SocksClientState.Error&&this.receiveBuffer.length>=this.nextRequiredPacketBufferSize)if(this.state===v.SocksClientState.SentInitialHandshake)if(this.options.proxy.type===4)this.handleSocks4FinalHandshakeResponse();else this.handleInitialSocks5HandshakeResponse();else if(this.state===v.SocksClientState.SentAuthentication)this.handleInitialSocks5AuthenticationHandshakeResponse();else if(this.state===v.SocksClientState.SentFinalHandshake)this.handleSocks5FinalHandshakeResponse();else if(this.state===v.SocksClientState.BoundWaitingForConnection)if(this.options.proxy.type===4)this.handleSocks4IncomingConnectionResponse();else this.handleSocks5IncomingConnectionResponse();else{this.closeSocket(v.ERRORS.InternalError);break}}onCloseHandler(){this.closeSocket(v.ERRORS.SocketClosed)}onErrorHandler(Z){this.closeSocket(Z.message)}removeInternalSocketHandlers(){this.socket.pause(),this.socket.removeListener("data",this.onDataReceived),this.socket.removeListener("close",this.onClose),this.socket.removeListener("error",this.onError),this.socket.removeListener("connect",this.onConnect)}closeSocket(Z){if(this.state!==v.SocksClientState.Error)this.setState(v.SocksClientState.Error),this.socket.destroy(),this.removeInternalSocketHandlers(),this.emit("error",new yw.SocksClientError(Z,this.options))}sendSocks4InitialHandshake(){let Z=this.options.proxy.userId||"",J=new V6.SmartBuffer;if(J.writeUInt8(4),J.writeUInt8(v.SocksCommand[this.options.command]),J.writeUInt16BE(this.options.destination.port),U$.isIPv4(this.options.destination.host))J.writeBuffer((0,P6.ipToBuffer)(this.options.destination.host)),J.writeStringNT(Z);else J.writeUInt8(0),J.writeUInt8(0),J.writeUInt8(0),J.writeUInt8(1),J.writeStringNT(Z),J.writeStringNT(this.options.destination.host);this.nextRequiredPacketBufferSize=v.SOCKS_INCOMING_PACKET_SIZES.Socks4Response,this.socket.write(J.toBuffer())}handleSocks4FinalHandshakeResponse(){let Z=this.receiveBuffer.get(8);if(Z[1]!==v.Socks4Response.Granted)this.closeSocket(`${v.ERRORS.Socks4ProxyRejectedConnection} - (${v.Socks4Response[Z[1]]})`);else if(v.SocksCommand[this.options.command]===v.SocksCommand.bind){let J=V6.SmartBuffer.fromBuffer(Z);J.readOffset=2;let X={port:J.readUInt16BE(),host:(0,P6.int32ToIpv4)(J.readUInt32BE())};if(X.host==="0.0.0.0")X.host=this.options.proxy.ipaddress;this.setState(v.SocksClientState.BoundWaitingForConnection),this.emit("bound",{remoteHost:X,socket:this.socket})}else this.setState(v.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{socket:this.socket})}handleSocks4IncomingConnectionResponse(){let Z=this.receiveBuffer.get(8);if(Z[1]!==v.Socks4Response.Granted)this.closeSocket(`${v.ERRORS.Socks4ProxyRejectedIncomingBoundConnection} - (${v.Socks4Response[Z[1]]})`);else{let J=V6.SmartBuffer.fromBuffer(Z);J.readOffset=2;let X={port:J.readUInt16BE(),host:(0,P6.int32ToIpv4)(J.readUInt32BE())};this.setState(v.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost:X,socket:this.socket})}}sendSocks5InitialHandshake(){let Z=new V6.SmartBuffer,J=[v.Socks5Auth.NoAuth];if(this.options.proxy.userId||this.options.proxy.password)J.push(v.Socks5Auth.UserPass);if(this.options.proxy.custom_auth_method!==void 0)J.push(this.options.proxy.custom_auth_method);Z.writeUInt8(5),Z.writeUInt8(J.length);for(let X of J)Z.writeUInt8(X);this.nextRequiredPacketBufferSize=v.SOCKS_INCOMING_PACKET_SIZES.Socks5InitialHandshakeResponse,this.socket.write(Z.toBuffer()),this.setState(v.SocksClientState.SentInitialHandshake)}handleInitialSocks5HandshakeResponse(){let Z=this.receiveBuffer.get(2);if(Z[0]!==5)this.closeSocket(v.ERRORS.InvalidSocks5IntiailHandshakeSocksVersion);else if(Z[1]===v.SOCKS5_NO_ACCEPTABLE_AUTH)this.closeSocket(v.ERRORS.InvalidSocks5InitialHandshakeNoAcceptedAuthType);else if(Z[1]===v.Socks5Auth.NoAuth)this.socks5ChosenAuthType=v.Socks5Auth.NoAuth,this.sendSocks5CommandRequest();else if(Z[1]===v.Socks5Auth.UserPass)this.socks5ChosenAuthType=v.Socks5Auth.UserPass,this.sendSocks5UserPassAuthentication();else if(Z[1]===this.options.proxy.custom_auth_method)this.socks5ChosenAuthType=this.options.proxy.custom_auth_method,this.sendSocks5CustomAuthentication();else this.closeSocket(v.ERRORS.InvalidSocks5InitialHandshakeUnknownAuthType)}sendSocks5UserPassAuthentication(){let Z=this.options.proxy.userId||"",J=this.options.proxy.password||"",X=new V6.SmartBuffer;X.writeUInt8(1),X.writeUInt8(Buffer.byteLength(Z)),X.writeString(Z),X.writeUInt8(Buffer.byteLength(J)),X.writeString(J),this.nextRequiredPacketBufferSize=v.SOCKS_INCOMING_PACKET_SIZES.Socks5UserPassAuthenticationResponse,this.socket.write(X.toBuffer()),this.setState(v.SocksClientState.SentAuthentication)}sendSocks5CustomAuthentication(){return B$(this,void 0,void 0,function*(){this.nextRequiredPacketBufferSize=this.options.proxy.custom_auth_response_size,this.socket.write(yield this.options.proxy.custom_auth_request_handler()),this.setState(v.SocksClientState.SentAuthentication)})}handleSocks5CustomAuthHandshakeResponse(Z){return B$(this,void 0,void 0,function*(){return yield this.options.proxy.custom_auth_response_handler(Z)})}handleSocks5AuthenticationNoAuthHandshakeResponse(Z){return B$(this,void 0,void 0,function*(){return Z[1]===0})}handleSocks5AuthenticationUserPassHandshakeResponse(Z){return B$(this,void 0,void 0,function*(){return Z[1]===0})}handleInitialSocks5AuthenticationHandshakeResponse(){return B$(this,void 0,void 0,function*(){this.setState(v.SocksClientState.ReceivedAuthenticationResponse);let Z=!1;if(this.socks5ChosenAuthType===v.Socks5Auth.NoAuth)Z=yield this.handleSocks5AuthenticationNoAuthHandshakeResponse(this.receiveBuffer.get(2));else if(this.socks5ChosenAuthType===v.Socks5Auth.UserPass)Z=yield this.handleSocks5AuthenticationUserPassHandshakeResponse(this.receiveBuffer.get(2));else if(this.socks5ChosenAuthType===this.options.proxy.custom_auth_method)Z=yield this.handleSocks5CustomAuthHandshakeResponse(this.receiveBuffer.get(this.options.proxy.custom_auth_response_size));if(!Z)this.closeSocket(v.ERRORS.Socks5AuthenticationFailed);else this.sendSocks5CommandRequest()})}sendSocks5CommandRequest(){let Z=new V6.SmartBuffer;if(Z.writeUInt8(5),Z.writeUInt8(v.SocksCommand[this.options.command]),Z.writeUInt8(0),U$.isIPv4(this.options.destination.host))Z.writeUInt8(v.Socks5HostType.IPv4),Z.writeBuffer((0,P6.ipToBuffer)(this.options.destination.host));else if(U$.isIPv6(this.options.destination.host))Z.writeUInt8(v.Socks5HostType.IPv6),Z.writeBuffer((0,P6.ipToBuffer)(this.options.destination.host));else Z.writeUInt8(v.Socks5HostType.Hostname),Z.writeUInt8(this.options.destination.host.length),Z.writeString(this.options.destination.host);Z.writeUInt16BE(this.options.destination.port),this.nextRequiredPacketBufferSize=v.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader,this.socket.write(Z.toBuffer()),this.setState(v.SocksClientState.SentFinalHandshake)}handleSocks5FinalHandshakeResponse(){let Z=this.receiveBuffer.peek(5);if(Z[0]!==5||Z[1]!==v.Socks5Response.Granted)this.closeSocket(`${v.ERRORS.InvalidSocks5FinalHandshakeRejected} - ${v.Socks5Response[Z[1]]}`);else{let J=Z[3],X,$;if(J===v.Socks5HostType.IPv4){let Y=v.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4;if(this.receiveBuffer.length<Y){this.nextRequiredPacketBufferSize=Y;return}if($=V6.SmartBuffer.fromBuffer(this.receiveBuffer.get(Y).slice(4)),X={host:(0,P6.int32ToIpv4)($.readUInt32BE()),port:$.readUInt16BE()},X.host==="0.0.0.0")X.host=this.options.proxy.ipaddress}else if(J===v.Socks5HostType.Hostname){let Y=Z[4],Q=v.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(Y);if(this.receiveBuffer.length<Q){this.nextRequiredPacketBufferSize=Q;return}$=V6.SmartBuffer.fromBuffer(this.receiveBuffer.get(Q).slice(5)),X={host:$.readString(Y),port:$.readUInt16BE()}}else if(J===v.Socks5HostType.IPv6){let Y=v.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6;if(this.receiveBuffer.length<Y){this.nextRequiredPacketBufferSize=Y;return}$=V6.SmartBuffer.fromBuffer(this.receiveBuffer.get(Y).slice(4)),X={host:Iw.Address6.fromByteArray(Array.from($.readBuffer(16))).canonicalForm(),port:$.readUInt16BE()}}if(this.setState(v.SocksClientState.ReceivedFinalResponse),v.SocksCommand[this.options.command]===v.SocksCommand.connect)this.setState(v.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost:X,socket:this.socket});else if(v.SocksCommand[this.options.command]===v.SocksCommand.bind)this.setState(v.SocksClientState.BoundWaitingForConnection),this.nextRequiredPacketBufferSize=v.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader,this.emit("bound",{remoteHost:X,socket:this.socket});else if(v.SocksCommand[this.options.command]===v.SocksCommand.associate)this.setState(v.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost:X,socket:this.socket})}}handleSocks5IncomingConnectionResponse(){let Z=this.receiveBuffer.peek(5);if(Z[0]!==5||Z[1]!==v.Socks5Response.Granted)this.closeSocket(`${v.ERRORS.Socks5ProxyRejectedIncomingBoundConnection} - ${v.Socks5Response[Z[1]]}`);else{let J=Z[3],X,$;if(J===v.Socks5HostType.IPv4){let Y=v.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4;if(this.receiveBuffer.length<Y){this.nextRequiredPacketBufferSize=Y;return}if($=V6.SmartBuffer.fromBuffer(this.receiveBuffer.get(Y).slice(4)),X={host:(0,P6.int32ToIpv4)($.readUInt32BE()),port:$.readUInt16BE()},X.host==="0.0.0.0")X.host=this.options.proxy.ipaddress}else if(J===v.Socks5HostType.Hostname){let Y=Z[4],Q=v.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(Y);if(this.receiveBuffer.length<Q){this.nextRequiredPacketBufferSize=Q;return}$=V6.SmartBuffer.fromBuffer(this.receiveBuffer.get(Q).slice(5)),X={host:$.readString(Y),port:$.readUInt16BE()}}else if(J===v.Socks5HostType.IPv6){let Y=v.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6;if(this.receiveBuffer.length<Y){this.nextRequiredPacketBufferSize=Y;return}$=V6.SmartBuffer.fromBuffer(this.receiveBuffer.get(Y).slice(4)),X={host:Iw.Address6.fromByteArray(Array.from($.readBuffer(16))).canonicalForm(),port:$.readUInt16BE()}}this.setState(v.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost:X,socket:this.socket})}}get socksClientOptions(){return Object.assign({},this.options)}}h7.SocksClient=UH});var d$0=L((HJ)=>{var F91=HJ&&HJ.__createBinding||(Object.create?function(Z,J,X,$){if($===void 0)$=X;var Y=Object.getOwnPropertyDescriptor(J,X);if(!Y||("get"in Y?!J.__esModule:Y.writable||Y.configurable))Y={enumerable:!0,get:function(){return J[X]}};Object.defineProperty(Z,$,Y)}:function(Z,J,X,$){if($===void 0)$=X;Z[$]=J[X]}),B91=HJ&&HJ.__exportStar||function(Z,J){for(var X in Z)if(X!=="default"&&!Object.prototype.hasOwnProperty.call(J,X))F91(J,Z,X)};Object.defineProperty(HJ,"__esModule",{value:!0});B91(m$0(),HJ)});var kw=L((l8)=>{var U91=l8&&l8.__createBinding||(Object.create?function(Z,J,X,$){if($===void 0)$=X;var Y=Object.getOwnPropertyDescriptor(J,X);if(!Y||("get"in Y?!J.__esModule:Y.writable||Y.configurable))Y={enumerable:!0,get:function(){return J[X]}};Object.defineProperty(Z,$,Y)}:function(Z,J,X,$){if($===void 0)$=X;Z[$]=J[X]}),L91=l8&&l8.__setModuleDefault||(Object.create?function(Z,J){Object.defineProperty(Z,"default",{enumerable:!0,value:J})}:function(Z,J){Z.default=J}),D91=l8&&l8.__importStar||function(){var Z=function(J){return Z=Object.getOwnPropertyNames||function(X){var $=[];for(var Y in X)if(Object.prototype.hasOwnProperty.call(X,Y))$[$.length]=Y;return $},Z(J)};return function(J){if(J&&J.__esModule)return J;var X={};if(J!=null){for(var $=Z(J),Y=0;Y<$.length;Y++)if($[Y]!=="default")U91(X,J,$[Y])}return L91(X,J),X}}(),u$0=l8&&l8.__importDefault||function(Z){return Z&&Z.__esModule?Z:{default:Z}};Object.defineProperty(l8,"__esModule",{value:!0});l8.default=C91;var _91=u$0(h6()),O91=N("stream"),w91=d$0(),j91=D91(N("dns")),M91=N("util"),Sw=u$0(N("assert")),C9=(0,_91.default)("mqttjs:socks");class c$0 extends O91.Duplex{_flowing=!1;_socket;constructor(){super({autoDestroy:!1});this.cork()}_start(Z){if(C9("proxy stream started"),(0,Sw.default)(!this._socket),this.destroyed){Z.destroy(this.errored);return}if(this._socket=Z,!this._flowing)Z.pause();Z.on("data",this._onData),Z.on("end",this._onEnd),Z.on("error",this._onError),Z.on("close",this._onClose),Z.emit("connect"),this.uncork()}_write(Z,J,X){(0,Sw.default)(this._socket),this._socket.write(Z,X)}_read(Z){this._flowing=!0,this._socket?.resume?.()}_destroy(Z,J){this._socket?.destroy?.(Z),J(Z)}_onData=(Z)=>{if((0,Sw.default)(this._socket),this._flowing=this.push(Z),!this._flowing)this._socket.pause()};_onEnd=()=>{C9("proxy stream received EOF"),this.push(null)};_onClose=()=>{C9("proxy stream closed"),this.destroy()};_onError=(Z)=>{C9("proxy stream died with error %s",Z),this.destroy(Z)}}function LH(Z){try{if(Z.code===void 0)Z.code="SOCKS";return Z}catch{return Z}}function A91(Z){switch(Z){case"socks5h:":return[5,!0];case"socks4a:":return[4,!0];case"socks5:":return[5,!1];case"socks4:":return[4,!1];default:return[void 0,!1]}}function T91(Z){let J=new URL(Z);if(J.pathname||J.hash||J.search)throw LH(Error("bad SOCKS URL"));let[X,$]=A91(J.protocol);if(!X)throw LH(Error("bad SOCKS URL: invalid protocol"));let Y=parseInt(J.port,10);if(Number.isNaN(Y))throw LH(Error("bad SOCKS URL: invalid port"));return[{host:J.hostname,port:Y,type:X},$]}async function q91(Z,J,X,$,Y={}){let Q=Y.lookup??(0,M91.promisify)(j91.lookup),[W,K]=T91(X);if(!K)C9("resolving %s locally",Z),Z=(await Q(Z,{family:W.type===4?4:0})).address;C9("establishing SOCKS%d connection to %s:%d via %s:%d",W.type,Z,J,W.host,W.port);let z=new w91.SocksClient({command:"connect",destination:{host:Z,port:J},proxy:{...W},timeout:Y.timeout});z.connect(),z.on("established",({socket:G})=>$._start(G)),z.on("error",(G)=>{C9("SOCKS failed: %s",G),$.destroy(LH(G))})}function C91(Z,J,X,$){C9("SOCKS connection to %s:%d via %s",Z,J,X);let Y=new c$0;return q91(Z,J,X,Y,$).catch((Q)=>{C9("SOCKS failed: %s",Q),Y.destroy(Q)}),Y}});var vw=L((EQ)=>{var xw=EQ&&EQ.__importDefault||function(Z){return Z&&Z.__esModule?Z:{default:Z}};Object.defineProperty(EQ,"__esModule",{value:!0});var N91=xw(N("net")),R91=xw(h6()),P91=xw(kw()),E91=(0,R91.default)("mqttjs:tcp"),I91=(Z,J)=>{if(J.port=J.port||1883,J.hostname=J.hostname||J.host||"localhost",J.socksProxy)return(0,P91.default)(J.hostname,J.port,J.socksProxy,{timeout:J.socksTimeout});let{port:X,path:$}=J,Y=J.hostname;return E91("port %d and host %s",X,Y),N91.default.createConnection({port:X,host:Y,path:$})};EQ.default=I91});var fw=L((IQ)=>{var hw=IQ&&IQ.__importDefault||function(Z){return Z&&Z.__esModule?Z:{default:Z}};Object.defineProperty(IQ,"__esModule",{value:!0});var l$0=N("tls"),y91=hw(N("net")),S91=hw(h6()),k91=hw(kw()),x91=(0,S91.default)("mqttjs:tls");function v91(Z){let{host:J,port:X,socksProxy:$,...Y}=Z;if($!==void 0){let Q=(0,k91.default)(J,X,$,{timeout:Z.socksTimeout});return(0,l$0.connect)({...Y,socket:Q})}return(0,l$0.connect)(Z)}var h91=(Z,J)=>{if(J.port=J.port||8883,J.host=J.hostname||J.host||"localhost",y91.default.isIP(J.host)===0)J.servername=J.host;J.rejectUnauthorized=J.rejectUnauthorized!==!1,delete J.path,x91("port %d host %s rejectUnauthorized %b",J.port,J.host,J.rejectUnauthorized);let X=v91(J);X.on("secureConnect",()=>{if(J.rejectUnauthorized&&!X.authorized)X.emit("error",Error("TLS not authorized"));else X.removeListener("error",$)});function $(Y){if(J.rejectUnauthorized)Z.emit("error",Y);X.end()}return X.on("error",$),X};IQ.default=h91});var gw=L((i$0)=>{Object.defineProperty(i$0,"__esModule",{value:!0});var p$0=N("buffer"),f91=R7(),b91=QH(),y5,bw,E6;function g91(){let Z=new f91.Transform;return Z._write=(J,X,$)=>{y5.send({data:J.buffer,success(){$()},fail(Y){$(Error(Y))}})},Z._flush=(J)=>{y5.close({success(){J()}})},Z}function m91(Z){if(!Z.hostname)Z.hostname="localhost";if(!Z.path)Z.path="/";if(!Z.wsOptions)Z.wsOptions={}}function d91(Z,J){let X=Z.protocol==="wxs"?"wss":"ws",$=`${X}://${Z.hostname}${Z.path}`;if(Z.port&&Z.port!==80&&Z.port!==443)$=`${X}://${Z.hostname}:${Z.port}${Z.path}`;if(typeof Z.transformWsUrl==="function")$=Z.transformWsUrl($,Z,J);return $}function u91(){y5.onOpen(()=>{E6.socketReady()}),y5.onMessage((Z)=>{let{data:J}=Z;if(J instanceof ArrayBuffer)J=p$0.Buffer.from(J);else J=p$0.Buffer.from(J,"utf8");bw.push(J)}),y5.onClose(()=>{E6.emit("close"),E6.end(),E6.destroy()}),y5.onError((Z)=>{let J=Error(Z.errMsg);E6.destroy(J)})}var c91=(Z,J)=>{if(J.hostname=J.hostname||J.host,!J.hostname)throw Error("Could not determine host. Specify host manually.");let X=J.protocolId==="MQIsdp"&&J.protocolVersion===3?"mqttv3.1":"mqtt";m91(J);let $=d91(J,Z);y5=wx.connectSocket({url:$,protocols:[X]}),bw=g91(),E6=new b91.BufferedDuplex(J,bw,y5),E6._destroy=(Q,W)=>{y5.close({success(){if(W)W(Q)}})};let Y=E6.destroy;return E6.destroy=(Q,W)=>{return E6.destroy=Y,setTimeout(()=>{y5.close({fail(){E6._destroy(Q,W)}})},0),E6},u91(),E6};i$0.default=c91});var dw=L((o$0)=>{Object.defineProperty(o$0,"__esModule",{value:!0});var mw=N("buffer"),p91=R7(),i91=QH(),N9,yQ,L$,n$0=!1;function n91(){let Z=new p91.Transform;return Z._write=(J,X,$)=>{N9.sendSocketMessage({data:J.buffer,success(){$()},fail(){$(Error())}})},Z._flush=(J)=>{N9.closeSocket({success(){J()}})},Z}function o91(Z){if(!Z.hostname)Z.hostname="localhost";if(!Z.path)Z.path="/";if(!Z.wsOptions)Z.wsOptions={}}function a91(Z,J){let X=Z.protocol==="alis"?"wss":"ws",$=`${X}://${Z.hostname}${Z.path}`;if(Z.port&&Z.port!==80&&Z.port!==443)$=`${X}://${Z.hostname}:${Z.port}${Z.path}`;if(typeof Z.transformWsUrl==="function")$=Z.transformWsUrl($,Z,J);return $}function r91(){if(n$0)return;n$0=!0,N9.onSocketOpen(()=>{L$.socketReady()}),N9.onSocketMessage((Z)=>{if(typeof Z.data==="string"){let J=mw.Buffer.from(Z.data,"base64");yQ.push(J)}else{let J=new FileReader;J.addEventListener("load",()=>{if(J.result instanceof ArrayBuffer){yQ.push(mw.Buffer.from(J.result));return}yQ.push(mw.Buffer.from(J.result,"utf-8"))}),J.readAsArrayBuffer(Z.data)}}),N9.onSocketClose(()=>{L$.end(),L$.destroy()}),N9.onSocketError((Z)=>{L$.destroy(Z)})}var s91=(Z,J)=>{if(J.hostname=J.hostname||J.host,!J.hostname)throw Error("Could not determine host. Specify host manually.");let X=J.protocolId==="MQIsdp"&&J.protocolVersion===3?"mqttv3.1":"mqtt";o91(J);let $=a91(J,Z);return N9=J.my,N9.connectSocket({url:$,protocols:X}),yQ=n91(),L$=new i91.BufferedDuplex(J,yQ,N9),r91(),L$};o$0.default=s91});var t$0=L((D$)=>{var DH=D$&&D$.__importDefault||function(Z){return Z&&Z.__esModule?Z:{default:Z}};Object.defineProperty(D$,"__esModule",{value:!0});D$.connectAsync=$71;var e91=DH(h6()),Z71=DH(N("url")),J71=DH(YH()),a$0=DH(qQ());if(typeof process?.nextTick!=="function")process.nextTick=setImmediate;var r$0=(0,e91.default)("mqttjs"),o1=null;function X71(Z){let J;if(Z.auth)if(J=Z.auth.match(/^(.+):(.+)$/),J){let[,X,$]=J;Z.username=X,Z.password=$}else Z.username=Z.auth}function s$0(Z,J){if(r$0("connecting to an MQTT broker..."),typeof Z==="object"&&!J)J=Z,Z="";if(J=J||{},Z&&typeof Z==="string"){let Y=Z71.default.parse(Z,!0),Q={};if(Y.port!=null)Q.port=Number(Y.port);if(Q.host=Y.hostname,Q.query=Y.query,Q.auth=Y.auth,Q.protocol=Y.protocol,Q.path=Y.path,J={...Q,...J},!J.protocol)throw Error("Missing protocol");J.protocol=J.protocol.replace(/:$/,"")}if(J.unixSocket=J.unixSocket||J.protocol?.includes("+unix"),J.unixSocket)J.protocol=J.protocol.replace("+unix","");else if(!J.protocol?.startsWith("ws")&&!J.protocol?.startsWith("wx"))delete J.path;if(X71(J),J.query&&typeof J.query.clientId==="string")J.clientId=J.query.clientId;if(a$0.default||J.unixSocket)J.socksProxy=void 0;else if(J.socksProxy===void 0&&typeof process<"u")J.socksProxy=process.env.MQTTJS_SOCKS_PROXY;if(J.cert&&J.key)if(J.protocol){if(["mqtts","wss","wxs","alis"].indexOf(J.protocol)===-1)switch(J.protocol){case"mqtt":J.protocol="mqtts";break;case"ws":J.protocol="wss";break;case"wx":J.protocol="wxs";break;case"ali":J.protocol="alis";break;default:throw Error(`Unknown protocol for secure connection: "${J.protocol}"!`)}}else throw Error("Missing secure protocol key");if(!o1)if(o1={},!a$0.default&&!J.forceNativeWebSocket)o1.ws=RQ().streamBuilder,o1.wss=RQ().streamBuilder,o1.mqtt=vw().default,o1.tcp=vw().default,o1.ssl=fw().default,o1.tls=o1.ssl,o1.mqtts=fw().default;else o1.ws=RQ().browserStreamBuilder,o1.wss=RQ().browserStreamBuilder,o1.wx=gw().default,o1.wxs=gw().default,o1.ali=dw().default,o1.alis=dw().default;if(!o1[J.protocol]){let Y=["mqtts","wss"].indexOf(J.protocol)!==-1;J.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((Q,W)=>{if(Y&&W%2===0)return!1;return typeof o1[Q]==="function"})[0]}if(J.clean===!1&&!J.clientId)throw Error("Missing clientId for unclean clients");if(J.protocol)J.defaultProtocol=J.protocol;function X(Y){if(J.servers){if(!Y._reconnectCount||Y._reconnectCount===J.servers.length)Y._reconnectCount=0;J.host=J.servers[Y._reconnectCount].host,J.port=J.servers[Y._reconnectCount].port,J.protocol=!J.servers[Y._reconnectCount].protocol?J.defaultProtocol:J.servers[Y._reconnectCount].protocol,J.hostname=J.host,Y._reconnectCount++}return r$0("calling streambuilder for",J.protocol),o1[J.protocol](Y,J)}let $=new J71.default(X,J);return $.on("error",()=>{}),$}function $71(Z,J,X=!0){return new Promise(($,Y)=>{let Q=s$0(Z,J),W={connect:(z)=>{K(),$(Q)},end:()=>{K(),$(Q)},error:(z)=>{K(),Q.end(),Y(z)}};if(X===!1)W.close=()=>{W.error(Error("Couldn't connect to server"))};function K(){Object.keys(W).forEach((z)=>{Q.off(z,W[z])})}Object.keys(W).forEach((z)=>{Q.on(z,W[z])})})}D$.default=s$0});var uw=L((m0)=>{var e$0=m0&&m0.__createBinding||(Object.create?function(Z,J,X,$){if($===void 0)$=X;var Y=Object.getOwnPropertyDescriptor(J,X);if(!Y||("get"in Y?!J.__esModule:Y.writable||Y.configurable))Y={enumerable:!0,get:function(){return J[X]}};Object.defineProperty(Z,$,Y)}:function(Z,J,X,$){if($===void 0)$=X;Z[$]=J[X]}),Y71=m0&&m0.__setModuleDefault||(Object.create?function(Z,J){Object.defineProperty(Z,"default",{enumerable:!0,value:J})}:function(Z,J){Z.default=J}),Q71=m0&&m0.__importStar||function(){var Z=function(J){return Z=Object.getOwnPropertyNames||function(X){var $=[];for(var Y in X)if(Object.prototype.hasOwnProperty.call(X,Y))$[$.length]=Y;return $},Z(J)};return function(J){if(J&&J.__esModule)return J;var X={};if(J!=null){for(var $=Z(J),Y=0;Y<$.length;Y++)if($[Y]!=="default")e$0(X,J,$[Y])}return Y71(X,J),X}}(),ZY0=m0&&m0.__exportStar||function(Z,J){for(var X in Z)if(X!=="default"&&!Object.prototype.hasOwnProperty.call(J,X))e$0(J,Z,X)},SQ=m0&&m0.__importDefault||function(Z){return Z&&Z.__esModule?Z:{default:Z}};Object.defineProperty(m0,"__esModule",{value:!0});m0.ReasonCodes=m0.KeepaliveManager=m0.UniqueMessageIdProvider=m0.DefaultMessageIdProvider=m0.Store=m0.MqttClient=m0.connectAsync=m0.connect=m0.Client=void 0;var JY0=SQ(YH());m0.MqttClient=JY0.default;var W71=SQ(Jw());m0.DefaultMessageIdProvider=W71.default;var K71=SQ(hX0());m0.UniqueMessageIdProvider=K71.default;var z71=SQ(dO());m0.Store=z71.default;var XY0=Q71(t$0());m0.connect=XY0.default;Object.defineProperty(m0,"connectAsync",{enumerable:!0,get:function(){return XY0.connectAsync}});var G71=SQ(Uw());m0.KeepaliveManager=G71.default;m0.Client=JY0.default;ZY0(YH(),m0);ZY0(ZJ(),m0);var H71=JQ();Object.defineProperty(m0,"ReasonCodes",{enumerable:!0,get:function(){return H71.ReasonCodes}})});var YY0=L((K8)=>{var $Y0=K8&&K8.__createBinding||(Object.create?function(Z,J,X,$){if($===void 0)$=X;var Y=Object.getOwnPropertyDescriptor(J,X);if(!Y||("get"in Y?!J.__esModule:Y.writable||Y.configurable))Y={enumerable:!0,get:function(){return J[X]}};Object.defineProperty(Z,$,Y)}:function(Z,J,X,$){if($===void 0)$=X;Z[$]=J[X]}),V71=K8&&K8.__setModuleDefault||(Object.create?function(Z,J){Object.defineProperty(Z,"default",{enumerable:!0,value:J})}:function(Z,J){Z.default=J}),F71=K8&&K8.__importStar||function(){var Z=function(J){return Z=Object.getOwnPropertyNames||function(X){var $=[];for(var Y in X)if(Object.prototype.hasOwnProperty.call(X,Y))$[$.length]=Y;return $},Z(J)};return function(J){if(J&&J.__esModule)return J;var X={};if(J!=null){for(var $=Z(J),Y=0;Y<$.length;Y++)if($[Y]!=="default")$Y0(X,J,$[Y])}return V71(X,J),X}}(),B71=K8&&K8.__exportStar||function(Z,J){for(var X in Z)if(X!=="default"&&!Object.prototype.hasOwnProperty.call(J,X))$Y0(J,Z,X)};Object.defineProperty(K8,"__esModule",{value:!0});var U71=F71(uw());K8.default=U71;B71(uw(),K8)});var pw=L((py1,HY0)=>{HY0.exports={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8}});var BY0=L((iy1,FY0)=>{var A71=pw();function VY0(Z){this.mode=A71.MODE_8BIT_BYTE,this.data=Z}VY0.prototype={getLength:function(){return this.data.length},write:function(Z){for(var J=0;J<this.data.length;J++)Z.put(this.data.charCodeAt(J),8)}};FY0.exports=VY0});var iw=L((ny1,UY0)=>{var p8={glog:function(Z){if(Z<1)throw Error("glog("+Z+")");return p8.LOG_TABLE[Z]},gexp:function(Z){while(Z<0)Z+=255;while(Z>=256)Z-=255;return p8.EXP_TABLE[Z]},EXP_TABLE:Array(256),LOG_TABLE:Array(256)};for(A1=0;A1<8;A1++)p8.EXP_TABLE[A1]=1<<A1;var A1;for(A1=8;A1<256;A1++)p8.EXP_TABLE[A1]=p8.EXP_TABLE[A1-4]^p8.EXP_TABLE[A1-5]^p8.EXP_TABLE[A1-6]^p8.EXP_TABLE[A1-8];var A1;for(A1=0;A1<255;A1++)p8.LOG_TABLE[p8.EXP_TABLE[A1]]=A1;var A1;UY0.exports=p8});var nw=L((oy1,LY0)=>{var VJ=iw();function TH(Z,J){if(Z.length===void 0)throw Error(Z.length+"/"+J);var X=0;while(X<Z.length&&Z[X]===0)X++;this.num=Array(Z.length-X+J);for(var $=0;$<Z.length-X;$++)this.num[$]=Z[$+X]}TH.prototype={get:function(Z){return this.num[Z]},getLength:function(){return this.num.length},multiply:function(Z){var J=Array(this.getLength()+Z.getLength()-1);for(var X=0;X<this.getLength();X++)for(var $=0;$<Z.getLength();$++)J[X+$]^=VJ.gexp(VJ.glog(this.get(X))+VJ.glog(Z.get($)));return new TH(J,0)},mod:function(Z){if(this.getLength()-Z.getLength()<0)return this;var J=VJ.glog(this.get(0))-VJ.glog(Z.get(0)),X=Array(this.getLength());for(var $=0;$<this.getLength();$++)X[$]=this.get($);for(var Y=0;Y<Z.getLength();Y++)X[Y]^=VJ.gexp(VJ.glog(Z.get(Y))+J);return new TH(X,0).mod(Z)}};LY0.exports=TH});var _Y0=L((ay1,DY0)=>{DY0.exports={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7}});var jY0=L((ry1,wY0)=>{var z8=pw(),OY0=nw(),T71=iw(),f7=_Y0(),D4={PATTERN_POSITION_TABLE:[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],G15:1335,G18:7973,G15_MASK:21522,getBCHTypeInfo:function(Z){var J=Z<<10;while(D4.getBCHDigit(J)-D4.getBCHDigit(D4.G15)>=0)J^=D4.G15<<D4.getBCHDigit(J)-D4.getBCHDigit(D4.G15);return(Z<<10|J)^D4.G15_MASK},getBCHTypeNumber:function(Z){var J=Z<<12;while(D4.getBCHDigit(J)-D4.getBCHDigit(D4.G18)>=0)J^=D4.G18<<D4.getBCHDigit(J)-D4.getBCHDigit(D4.G18);return Z<<12|J},getBCHDigit:function(Z){var J=0;while(Z!==0)J++,Z>>>=1;return J},getPatternPosition:function(Z){return D4.PATTERN_POSITION_TABLE[Z-1]},getMask:function(Z,J,X){switch(Z){case f7.PATTERN000:return(J+X)%2===0;case f7.PATTERN001:return J%2===0;case f7.PATTERN010:return X%3===0;case f7.PATTERN011:return(J+X)%3===0;case f7.PATTERN100:return(Math.floor(J/2)+Math.floor(X/3))%2===0;case f7.PATTERN101:return J*X%2+J*X%3===0;case f7.PATTERN110:return(J*X%2+J*X%3)%2===0;case f7.PATTERN111:return(J*X%3+(J+X)%2)%2===0;default:throw Error("bad maskPattern:"+Z)}},getErrorCorrectPolynomial:function(Z){var J=new OY0([1],0);for(var X=0;X<Z;X++)J=J.multiply(new OY0([1,T71.gexp(X)],0));return J},getLengthInBits:function(Z,J){if(1<=J&&J<10)switch(Z){case z8.MODE_NUMBER:return 10;case z8.MODE_ALPHA_NUM:return 9;case z8.MODE_8BIT_BYTE:return 8;case z8.MODE_KANJI:return 8;default:throw Error("mode:"+Z)}else if(J<27)switch(Z){case z8.MODE_NUMBER:return 12;case z8.MODE_ALPHA_NUM:return 11;case z8.MODE_8BIT_BYTE:return 16;case z8.MODE_KANJI:return 10;default:throw Error("mode:"+Z)}else if(J<41)switch(Z){case z8.MODE_NUMBER:return 14;case z8.MODE_ALPHA_NUM:return 13;case z8.MODE_8BIT_BYTE:return 16;case z8.MODE_KANJI:return 12;default:throw Error("mode:"+Z)}else throw Error("type:"+J)},getLostPoint:function(Z){var J=Z.getModuleCount(),X=0,$=0,Y=0;for($=0;$<J;$++)for(Y=0;Y<J;Y++){var Q=0,W=Z.isDark($,Y);for(var K=-1;K<=1;K++){if($+K<0||J<=$+K)continue;for(var z=-1;z<=1;z++){if(Y+z<0||J<=Y+z)continue;if(K===0&&z===0)continue;if(W===Z.isDark($+K,Y+z))Q++}}if(Q>5)X+=3+Q-5}for($=0;$<J-1;$++)for(Y=0;Y<J-1;Y++){var G=0;if(Z.isDark($,Y))G++;if(Z.isDark($+1,Y))G++;if(Z.isDark($,Y+1))G++;if(Z.isDark($+1,Y+1))G++;if(G===0||G===4)X+=3}for($=0;$<J;$++)for(Y=0;Y<J-6;Y++)if(Z.isDark($,Y)&&!Z.isDark($,Y+1)&&Z.isDark($,Y+2)&&Z.isDark($,Y+3)&&Z.isDark($,Y+4)&&!Z.isDark($,Y+5)&&Z.isDark($,Y+6))X+=40;for(Y=0;Y<J;Y++)for($=0;$<J-6;$++)if(Z.isDark($,Y)&&!Z.isDark($+1,Y)&&Z.isDark($+2,Y)&&Z.isDark($+3,Y)&&Z.isDark($+4,Y)&&!Z.isDark($+5,Y)&&Z.isDark($+6,Y))X+=40;var H=0;for(Y=0;Y<J;Y++)for($=0;$<J;$++)if(Z.isDark($,Y))H++;var V=Math.abs(100*H/J/J-50)/5;return X+=V*10,X}};wY0.exports=D4});var ow=L((sy1,MY0)=>{MY0.exports={L:1,M:0,Q:3,H:2}});var TY0=L((ty1,AY0)=>{var qH=ow();function S5(Z,J){this.totalCount=Z,this.dataCount=J}S5.RS_BLOCK_TABLE=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12],[5,122,98,1,123,99],[7,73,45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]];S5.getRSBlocks=function(Z,J){var X=S5.getRsBlockTable(Z,J);if(X===void 0)throw Error("bad rs block @ typeNumber:"+Z+"/errorCorrectLevel:"+J);var $=X.length/3,Y=[];for(var Q=0;Q<$;Q++){var W=X[Q*3+0],K=X[Q*3+1],z=X[Q*3+2];for(var G=0;G<W;G++)Y.push(new S5(K,z))}return Y};S5.getRsBlockTable=function(Z,J){switch(J){case qH.L:return S5.RS_BLOCK_TABLE[(Z-1)*4+0];case qH.M:return S5.RS_BLOCK_TABLE[(Z-1)*4+1];case qH.Q:return S5.RS_BLOCK_TABLE[(Z-1)*4+2];case qH.H:return S5.RS_BLOCK_TABLE[(Z-1)*4+3];default:return}};AY0.exports=S5});var NY0=L((ey1,CY0)=>{function qY0(){this.buffer=[],this.length=0}qY0.prototype={get:function(Z){var J=Math.floor(Z/8);return(this.buffer[J]>>>7-Z%8&1)==1},put:function(Z,J){for(var X=0;X<J;X++)this.putBit((Z>>>J-X-1&1)==1)},getLengthInBits:function(){return this.length},putBit:function(Z){var J=Math.floor(this.length/8);if(this.buffer.length<=J)this.buffer.push(0);if(Z)this.buffer[J]|=128>>>this.length%8;this.length++}};CY0.exports=qY0});var IY0=L((ZS1,EY0)=>{var q71=BY0(),b7=jY0(),C71=nw(),RY0=TY0(),PY0=NY0();function k5(Z,J){this.typeNumber=Z,this.errorCorrectLevel=J,this.modules=null,this.moduleCount=0,this.dataCache=null,this.dataList=[]}k5.prototype={addData:function(Z){var J=new q71(Z);this.dataList.push(J),this.dataCache=null},isDark:function(Z,J){if(Z<0||this.moduleCount<=Z||J<0||this.moduleCount<=J)throw Error(Z+","+J);return this.modules[Z][J]},getModuleCount:function(){return this.moduleCount},make:function(){if(this.typeNumber<1){var Z=1;for(Z=1;Z<40;Z++){var J=RY0.getRSBlocks(Z,this.errorCorrectLevel),X=new PY0,$=0;for(var Y=0;Y<J.length;Y++)$+=J[Y].dataCount;for(var Q=0;Q<this.dataList.length;Q++){var W=this.dataList[Q];X.put(W.mode,4),X.put(W.getLength(),b7.getLengthInBits(W.mode,Z)),W.write(X)}if(X.getLengthInBits()<=$*8)break}this.typeNumber=Z}this.makeImpl(!1,this.getBestMaskPattern())},makeImpl:function(Z,J){this.moduleCount=this.typeNumber*4+17,this.modules=Array(this.moduleCount);for(var X=0;X<this.moduleCount;X++){this.modules[X]=Array(this.moduleCount);for(var $=0;$<this.moduleCount;$++)this.modules[X][$]=null}if(this.setupPositionProbePattern(0,0),this.setupPositionProbePattern(this.moduleCount-7,0),this.setupPositionProbePattern(0,this.moduleCount-7),this.setupPositionAdjustPattern(),this.setupTimingPattern(),this.setupTypeInfo(Z,J),this.typeNumber>=7)this.setupTypeNumber(Z);if(this.dataCache===null)this.dataCache=k5.createData(this.typeNumber,this.errorCorrectLevel,this.dataList);this.mapData(this.dataCache,J)},setupPositionProbePattern:function(Z,J){for(var X=-1;X<=7;X++){if(Z+X<=-1||this.moduleCount<=Z+X)continue;for(var $=-1;$<=7;$++){if(J+$<=-1||this.moduleCount<=J+$)continue;if(0<=X&&X<=6&&($===0||$===6)||0<=$&&$<=6&&(X===0||X===6)||2<=X&&X<=4&&2<=$&&$<=4)this.modules[Z+X][J+$]=!0;else this.modules[Z+X][J+$]=!1}}},getBestMaskPattern:function(){var Z=0,J=0;for(var X=0;X<8;X++){this.makeImpl(!0,X);var $=b7.getLostPoint(this);if(X===0||Z>$)Z=$,J=X}return J},createMovieClip:function(Z,J,X){var $=Z.createEmptyMovieClip(J,X),Y=1;this.make();for(var Q=0;Q<this.modules.length;Q++){var W=Q*Y;for(var K=0;K<this.modules[Q].length;K++){var z=K*Y,G=this.modules[Q][K];if(G)$.beginFill(0,100),$.moveTo(z,W),$.lineTo(z+Y,W),$.lineTo(z+Y,W+Y),$.lineTo(z,W+Y),$.endFill()}}return $},setupTimingPattern:function(){for(var Z=8;Z<this.moduleCount-8;Z++){if(this.modules[Z][6]!==null)continue;this.modules[Z][6]=Z%2===0}for(var J=8;J<this.moduleCount-8;J++){if(this.modules[6][J]!==null)continue;this.modules[6][J]=J%2===0}},setupPositionAdjustPattern:function(){var Z=b7.getPatternPosition(this.typeNumber);for(var J=0;J<Z.length;J++)for(var X=0;X<Z.length;X++){var $=Z[J],Y=Z[X];if(this.modules[$][Y]!==null)continue;for(var Q=-2;Q<=2;Q++)for(var W=-2;W<=2;W++)if(Math.abs(Q)===2||Math.abs(W)===2||Q===0&&W===0)this.modules[$+Q][Y+W]=!0;else this.modules[$+Q][Y+W]=!1}},setupTypeNumber:function(Z){var J=b7.getBCHTypeNumber(this.typeNumber),X;for(var $=0;$<18;$++)X=!Z&&(J>>$&1)===1,this.modules[Math.floor($/3)][$%3+this.moduleCount-8-3]=X;for(var Y=0;Y<18;Y++)X=!Z&&(J>>Y&1)===1,this.modules[Y%3+this.moduleCount-8-3][Math.floor(Y/3)]=X},setupTypeInfo:function(Z,J){var X=this.errorCorrectLevel<<3|J,$=b7.getBCHTypeInfo(X),Y;for(var Q=0;Q<15;Q++)if(Y=!Z&&($>>Q&1)===1,Q<6)this.modules[Q][8]=Y;else if(Q<8)this.modules[Q+1][8]=Y;else this.modules[this.moduleCount-15+Q][8]=Y;for(var W=0;W<15;W++)if(Y=!Z&&($>>W&1)===1,W<8)this.modules[8][this.moduleCount-W-1]=Y;else if(W<9)this.modules[8][15-W-1+1]=Y;else this.modules[8][15-W-1]=Y;this.modules[this.moduleCount-8][8]=!Z},mapData:function(Z,J){var X=-1,$=this.moduleCount-1,Y=7,Q=0;for(var W=this.moduleCount-1;W>0;W-=2){if(W===6)W--;while(!0){for(var K=0;K<2;K++)if(this.modules[$][W-K]===null){var z=!1;if(Q<Z.length)z=(Z[Q]>>>Y&1)===1;var G=b7.getMask(J,$,W-K);if(G)z=!z;if(this.modules[$][W-K]=z,Y--,Y===-1)Q++,Y=7}if($+=X,$<0||this.moduleCount<=$){$-=X,X=-X;break}}}}};k5.PAD0=236;k5.PAD1=17;k5.createData=function(Z,J,X){var $=RY0.getRSBlocks(Z,J),Y=new PY0;for(var Q=0;Q<X.length;Q++){var W=X[Q];Y.put(W.mode,4),Y.put(W.getLength(),b7.getLengthInBits(W.mode,Z)),W.write(Y)}var K=0;for(var z=0;z<$.length;z++)K+=$[z].dataCount;if(Y.getLengthInBits()>K*8)throw Error("code length overflow. ("+Y.getLengthInBits()+">"+K*8+")");if(Y.getLengthInBits()+4<=K*8)Y.put(0,4);while(Y.getLengthInBits()%8!==0)Y.putBit(!1);while(!0){if(Y.getLengthInBits()>=K*8)break;if(Y.put(k5.PAD0,8),Y.getLengthInBits()>=K*8)break;Y.put(k5.PAD1,8)}return k5.createBytes(Y,$)};k5.createBytes=function(Z,J){var X=0,$=0,Y=0,Q=Array(J.length),W=Array(J.length);for(var K=0;K<J.length;K++){var z=J[K].dataCount,G=J[K].totalCount-z;$=Math.max($,z),Y=Math.max(Y,G),Q[K]=Array(z);for(var H=0;H<Q[K].length;H++)Q[K][H]=255&Z.buffer[H+X];X+=z;var V=b7.getErrorCorrectPolynomial(G),F=new C71(Q[K],V.getLength()-1),B=F.mod(V);W[K]=Array(V.getLength()-1);for(var U=0;U<W[K].length;U++){var D=U+B.getLength()-W[K].length;W[K][U]=D>=0?B.get(D):0}}var _=0;for(var O=0;O<J.length;O++)_+=J[O].totalCount;var w=Array(_),j=0;for(var q=0;q<$;q++)for(var R=0;R<J.length;R++)if(q<Q[R].length)w[j++]=Q[R][q];for(var T=0;T<Y;T++)for(var y=0;y<J.length;y++)if(T<W[y].length)w[j++]=W[y][T];return w};EY0.exports=k5});var kY0=L((JS1,SY0)=>{var N71=IY0(),yY0=ow(),R71="\x1B[40m \x1B[0m",CH="\x1B[47m \x1B[0m",P71=function(Z){return Z?R71:CH},aw=function(Z){return{times:function(J){return Array(J).join(Z)}}},E71=function(Z,J){var X=Array(Z);for(var $=0;$<Z;$++)X[$]=J;return X};SY0.exports={error:yY0.L,generate:function(Z,J,X){if(typeof J==="function")X=J,J={};var $=new N71(-1,this.error);$.addData(Z),$.make();var Y="";if(J&&J.small){var Q=!0,W=!1,K=$.getModuleCount(),z=$.modules.slice(),G=K%2===1;if(G)z.push(E71(K,W));var H={WHITE_ALL:"\u2588",WHITE_BLACK:"\u2580",BLACK_WHITE:"\u2584",BLACK_ALL:" "},V=aw(H.BLACK_WHITE).times(K+3),F=aw(H.WHITE_BLACK).times(K+3);Y+=V+`
18
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}LQ.exports=D61,LQ.exports.__esModule=!0,LQ.exports.default=LQ.exports});var uJ0=L((TI1,DQ)=>{var _61=hJ0(),O61=fJ0(),w61=mJ0(),j61=dJ0();function M61(Z,J){return _61(Z)||O61(Z,J)||w61(Z,J)||j61()}DQ.exports=M61,DQ.exports.__esModule=!0,DQ.exports.default=DQ.exports});var pJ0=L((cJ0)=>{Object.defineProperty(cJ0,"__esModule",{value:!0});cJ0.createAddUniqueNumber=void 0;var A61=(Z)=>{return(J)=>{let X=Z(J);return J.add(X),X}};cJ0.createAddUniqueNumber=A61});var oJ0=L((iJ0)=>{Object.defineProperty(iJ0,"__esModule",{value:!0});iJ0.createCache=void 0;var T61=(Z)=>{return(J,X)=>{return Z.set(J,X),X}};iJ0.createCache=T61});var ZX0=L((tJ0)=>{Object.defineProperty(tJ0,"__esModule",{value:!0});tJ0.createGenerateUniqueNumber=void 0;var aJ0=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,sJ0=536870912,rJ0=sJ0*2,q61=(Z,J)=>{return(X)=>{let $=J.get(X),Y=$===void 0?X.size:$<rJ0?$+1:0;if(!X.has(Y))return Z(X,Y);if(X.size<sJ0){while(X.has(Y))Y=Math.floor(Math.random()*rJ0);return Z(X,Y)}if(X.size>aJ0)throw Error("Congratulations, you created a collection of unique numbers which uses all available integers!");while(X.has(Y))Y=Math.floor(Math.random()*aJ0);return Z(X,Y)}};tJ0.createGenerateUniqueNumber=q61});var Yw=L((XX0)=>{Object.defineProperty(XX0,"__esModule",{value:!0});XX0.generateUniqueNumber=XX0.addUniqueNumber=void 0;var C61=pJ0(),N61=oJ0(),R61=ZX0(),JX0=new WeakMap,P61=(0,N61.createCache)(JX0),E61=XX0.generateUniqueNumber=(0,R61.createGenerateUniqueNumber)(P61,JX0),RI1=XX0.addUniqueNumber=(0,C61.createAddUniqueNumber)(E61)});var QX0=L((EI1,_Q)=>{function YX0(Z,J,X,$,Y,Q,W){try{var K=Z[Q](W),z=K.value}catch(G){return void X(G)}K.done?J(z):Promise.resolve(z).then($,Y)}function y61(Z){return function(){var J=this,X=arguments;return new Promise(function($,Y){var Q=Z.apply(J,X);function W(z){YX0(Q,$,Y,W,K,"next",z)}function K(z){YX0(Q,$,Y,W,K,"throw",z)}W(void 0)})}}_Q.exports=y61,_Q.exports.__esModule=!0,_Q.exports.default=_Q.exports});var Qw=L((II1,OQ)=>{function S61(Z,J){this.v=Z,this.k=J}OQ.exports=S61,OQ.exports.__esModule=!0,OQ.exports.default=OQ.exports});var Ww=L((yI1,j9)=>{function tG(Z,J,X,$){var Y=Object.defineProperty;try{Y({},"",{})}catch(Q){Y=0}j9.exports=tG=function(W,K,z,G){function H(V,F){tG(W,V,function(B){return this._invoke(V,F,B)})}K?Y?Y(W,K,{value:z,enumerable:!G,configurable:!G,writable:!G}):W[K]=z:(H("next",0),H("throw",1),H("return",2))},j9.exports.__esModule=!0,j9.exports.default=j9.exports,tG(Z,J,X,$)}j9.exports=tG,j9.exports.__esModule=!0,j9.exports.default=j9.exports});var Kw=L((SI1,M9)=>{var P5=Ww();function WX0(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */var Z,J,X=typeof Symbol=="function"?Symbol:{},$=X.iterator||"@@iterator",Y=X.toStringTag||"@@toStringTag";function Q(B,U,D,_){var O=U&&U.prototype instanceof K?U:K,w=Object.create(O.prototype);return P5(w,"_invoke",function(j,q,R){var T,y,i,s=0,O0=R||[],d0=!1,b0={p:0,n:0,v:Z,a:G0,f:G0.bind(Z,4),d:function(f0,k0){return T=f0,y=0,i=Z,b0.n=k0,W}};function G0(E0,f0){for(y=E0,i=f0,J=0;!d0&&s&&!k0&&J<O0.length;J++){var k0,e0=O0[J],y6=b0.p,i4=e0[2];E0>3?(k0=i4===f0)&&(i=e0[(y=e0[4])?5:(y=3,3)],e0[4]=e0[5]=Z):e0[0]<=y6&&((k0=E0<2&&y6<e0[1])?(y=0,b0.v=f0,b0.n=e0[1]):y6<i4&&(k0=E0<3||e0[0]>f0||f0>i4)&&(e0[4]=E0,e0[5]=f0,b0.n=i4,y=0))}if(k0||E0>1)return W;throw d0=!0,f0}return function(E0,f0,k0){if(s>1)throw TypeError("Generator is already running");for(d0&&f0===1&&G0(f0,k0),y=f0,i=k0;(J=y<2?Z:i)||!d0;){T||(y?y<3?(y>1&&(b0.n=-1),G0(y,i)):b0.n=i:b0.v=i);try{if(s=2,T){if(y||(E0="next"),J=T[E0]){if(!(J=J.call(T,i)))throw TypeError("iterator result is not an object");if(!J.done)return J;i=J.value,y<2&&(y=0)}else y===1&&(J=T.return)&&J.call(T),y<2&&(i=TypeError("The iterator does not provide a '"+E0+"' method"),y=1);T=Z}else if((J=(d0=b0.n<0)?i:j.call(q,b0))!==W)break}catch(e0){T=Z,y=1,i=e0}finally{s=1}}return{value:J,done:d0}}}(B,D,_),!0),w}var W={};function K(){}function z(){}function G(){}J=Object.getPrototypeOf;var H=[][$]?J(J([][$]())):(P5(J={},$,function(){return this}),J),V=G.prototype=K.prototype=Object.create(H);function F(B){return Object.setPrototypeOf?Object.setPrototypeOf(B,G):(B.__proto__=G,P5(B,Y,"GeneratorFunction")),B.prototype=Object.create(V),B}return z.prototype=G,P5(V,"constructor",G),P5(G,"constructor",z),z.displayName="GeneratorFunction",P5(G,Y,"GeneratorFunction"),P5(V),P5(V,Y,"Generator"),P5(V,$,function(){return this}),P5(V,"toString",function(){return"[object Generator]"}),(M9.exports=WX0=function(){return{w:Q,m:F}},M9.exports.__esModule=!0,M9.exports.default=M9.exports)()}M9.exports=WX0,M9.exports.__esModule=!0,M9.exports.default=M9.exports});var Hw=L((kI1,wQ)=>{var k61=Qw(),zw=Ww();function Gw(Z,J){function X(Y,Q,W,K){try{var z=Z[Y](Q),G=z.value;return G instanceof k61?J.resolve(G.v).then(function(H){X("next",H,W,K)},function(H){X("throw",H,W,K)}):J.resolve(G).then(function(H){z.value=H,W(z)},function(H){return X("throw",H,W,K)})}catch(H){K(H)}}var $;this.next||(zw(Gw.prototype),zw(Gw.prototype,typeof Symbol=="function"&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),zw(this,"_invoke",function(Y,Q,W){function K(){return new J(function(z,G){X(Y,W,z,G)})}return $=$?$.then(K,K):K()},!0)}wQ.exports=Gw,wQ.exports.__esModule=!0,wQ.exports.default=wQ.exports});var Vw=L((xI1,jQ)=>{var x61=Kw(),v61=Hw();function h61(Z,J,X,$,Y){return new v61(x61().w(Z,J,X,$),Y||Promise)}jQ.exports=h61,jQ.exports.__esModule=!0,jQ.exports.default=jQ.exports});var KX0=L((vI1,MQ)=>{var f61=Vw();function b61(Z,J,X,$,Y){var Q=f61(Z,J,X,$,Y);return Q.next().then(function(W){return W.done?W.value:Q.next()})}MQ.exports=b61,MQ.exports.__esModule=!0,MQ.exports.default=MQ.exports});var zX0=L((hI1,AQ)=>{function g61(Z){var J=Object(Z),X=[];for(var $ in J)X.unshift($);return function Y(){for(;X.length;)if(($=X.pop())in J)return Y.value=$,Y.done=!1,Y;return Y.done=!0,Y}}AQ.exports=g61,AQ.exports.__esModule=!0,AQ.exports.default=AQ.exports});var GX0=L((fI1,TQ)=>{var m61=KQ().default;function d61(Z){if(Z!=null){var J=Z[typeof Symbol=="function"&&Symbol.iterator||"@@iterator"],X=0;if(J)return J.call(Z);if(typeof Z.next=="function")return Z;if(!isNaN(Z.length))return{next:function(){return Z&&X>=Z.length&&(Z=void 0),{value:Z&&Z[X++],done:!Z}}}}throw TypeError(m61(Z)+" is not iterable")}TQ.exports=d61,TQ.exports.__esModule=!0,TQ.exports.default=TQ.exports});var VX0=L((bI1,A9)=>{var u61=Qw(),c61=Kw(),l61=KX0(),p61=Vw(),i61=Hw(),n61=zX0(),HX0=GX0();function Fw(){var Z=c61(),J=Z.m(Fw),X=(Object.getPrototypeOf?Object.getPrototypeOf(J):J.__proto__).constructor;function $(W){var K=typeof W=="function"&&W.constructor;return!!K&&(K===X||(K.displayName||K.name)==="GeneratorFunction")}var Y={throw:1,return:2,break:3,continue:3};function Q(W){var K,z;return function(G){K||(K={stop:function(){return z(G.a,2)},catch:function(){return G.v},abrupt:function(V,F){return z(G.a,Y[V],F)},delegateYield:function(V,F,B){return K.resultName=F,z(G.d,HX0(V),B)},finish:function(V){return z(G.f,V)}},z=function(V,F,B){G.p=K.prev,G.n=K.next;try{return V(F,B)}finally{K.next=G.n}}),K.resultName&&(K[K.resultName]=G.v,K.resultName=void 0),K.sent=G.v,K.next=G.n;try{return W.call(this,K)}finally{G.p=K.prev,G.n=K.next}}}return(A9.exports=Fw=function(){return{wrap:function(z,G,H,V){return Z.w(Q(z),G,H,V&&V.reverse())},isGeneratorFunction:$,mark:Z.m,awrap:function(z,G){return new u61(z,G)},AsyncIterator:i61,async:function(z,G,H,V,F){return($(G)?p61:l61)(Q(z),G,H,V,F)},keys:n61,values:HX0}},A9.exports.__esModule=!0,A9.exports.default=A9.exports)()}A9.exports=Fw,A9.exports.__esModule=!0,A9.exports.default=A9.exports});var BX0=L((gI1,FX0)=>{var eG=VX0()();FX0.exports=eG;try{regeneratorRuntime=eG}catch(Z){if(typeof globalThis==="object")globalThis.regeneratorRuntime=eG;else Function("r","regeneratorRuntime = r")(eG)}});var LX0=L((ZH,UX0)=>{(function(Z,J){typeof ZH==="object"&&typeof UX0<"u"?J(ZH,vJ0(),uJ0(),Yw(),QX0(),BX0()):typeof define==="function"&&define.amd?define(["exports","@babel/runtime/helpers/defineProperty","@babel/runtime/helpers/slicedToArray","fast-unique-numbers","@babel/runtime/helpers/asyncToGenerator","@babel/runtime/regenerator"],J):(Z=typeof globalThis<"u"?globalThis:Z||self,J(Z.brokerFactory={},Z._defineProperty,Z._slicedToArray,Z.fastUniqueNumbers,Z._asyncToGenerator,Z._regeneratorRuntime))})(ZH,function(Z,J,X,$,Y,Q){var W=function(O){return typeof O.start==="function"},K=new WeakMap;function z(_,O){var w=Object.keys(_);if(Object.getOwnPropertySymbols){var j=Object.getOwnPropertySymbols(_);O&&(j=j.filter(function(q){return Object.getOwnPropertyDescriptor(_,q).enumerable})),w.push.apply(w,j)}return w}function G(_){for(var O=1;O<arguments.length;O++){var w=arguments[O]!=null?arguments[O]:{};O%2?z(Object(w),!0).forEach(function(j){J(_,j,w[j])}):Object.getOwnPropertyDescriptors?Object.defineProperties(_,Object.getOwnPropertyDescriptors(w)):z(Object(w)).forEach(function(j){Object.defineProperty(_,j,Object.getOwnPropertyDescriptor(w,j))})}return _}var H=function(O){return G(G({},O),{},{connect:function(j){var q=j.call;return Y(Q.mark(function R(){var T,y,i,s;return Q.wrap(function(O0){while(!0)switch(O0.prev=O0.next){case 0:return T=new MessageChannel,y=T.port1,i=T.port2,O0.next=1,q("connect",{port:y},[y]);case 1:return s=O0.sent,K.set(i,s),O0.abrupt("return",i);case 2:case"end":return O0.stop()}},R)}))},disconnect:function(j){var q=j.call;return function(){var R=Y(Q.mark(function T(y){var i;return Q.wrap(function(s){while(!0)switch(s.prev=s.next){case 0:if(i=K.get(y),i!==void 0){s.next=1;break}throw Error("The given port is not connected.");case 1:return s.next=2,q("disconnect",{portId:i});case 2:case"end":return s.stop()}},T)}));return function(T){return R.apply(this,arguments)}}()},isSupported:function(j){var q=j.call;return function(){return q("isSupported")}}})};function V(_,O){var w=Object.keys(_);if(Object.getOwnPropertySymbols){var j=Object.getOwnPropertySymbols(_);O&&(j=j.filter(function(q){return Object.getOwnPropertyDescriptor(_,q).enumerable})),w.push.apply(w,j)}return w}function F(_){for(var O=1;O<arguments.length;O++){var w=arguments[O]!=null?arguments[O]:{};O%2?V(Object(w),!0).forEach(function(j){J(_,j,w[j])}):Object.getOwnPropertyDescriptors?Object.defineProperties(_,Object.getOwnPropertyDescriptors(w)):V(Object(w)).forEach(function(j){Object.defineProperty(_,j,Object.getOwnPropertyDescriptor(w,j))})}return _}var B=new WeakMap,U=function(O){if(B.has(O))return B.get(O);var w=new Map;return B.set(O,w),w},D=function(O){var w=H(O);return function(j){var q=U(j);if(j.addEventListener("message",function(G0){var E0=G0.data,f0=E0.id;if(f0!==null&&q.has(f0)){var k0=q.get(f0),e0=k0.reject,y6=k0.resolve;if(q.delete(f0),E0.error===void 0)y6(E0.result);else e0(Error(E0.error.message))}}),W(j))j.start();var R=function(E0){var f0=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,k0=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return new Promise(function(e0,y6){var i4=$.generateUniqueNumber(q);if(q.set(i4,{reject:y6,resolve:e0}),f0===null)j.postMessage({id:i4,method:E0},k0);else j.postMessage({id:i4,method:E0,params:f0},k0)})},T=function(E0,f0){var k0=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];j.postMessage({id:null,method:E0,params:f0},k0)},y={};for(var i=0,s=Object.entries(w);i<s.length;i++){var O0=X(s[i],2),d0=O0[0],b0=O0[1];y=F(F({},y),{},J({},d0,b0({call:R,notify:T})))}return F({},y)}};Z.createBroker=D})});var _X0=L((JH,DX0)=>{(function(Z,J){typeof JH==="object"&&typeof DX0<"u"?J(JH,KQ(),LX0(),Yw()):typeof define==="function"&&define.amd?define(["exports","@babel/runtime/helpers/typeof","broker-factory","fast-unique-numbers"],J):(Z=typeof globalThis<"u"?globalThis:Z||self,J(Z.workerTimersBroker={},Z._typeof,Z.brokerFactory,Z.fastUniqueNumbers))})(JH,function(Z,J,X,$){var Y=new Map([[0,null]]),Q=new Map([[0,null]]),W=X.createBroker({clearInterval:function(G){var H=G.call;return function(V){if(J(Y.get(V))==="symbol")Y.set(V,null),H("clear",{timerId:V,timerType:"interval"}).then(function(){Y.delete(V)})}},clearTimeout:function(G){var H=G.call;return function(V){if(J(Q.get(V))==="symbol")Q.set(V,null),H("clear",{timerId:V,timerType:"timeout"}).then(function(){Q.delete(V)})}},setInterval:function(G){var H=G.call;return function(V){var F=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;for(var B=arguments.length,U=Array(B>2?B-2:0),D=2;D<B;D++)U[D-2]=arguments[D];var _=Symbol(),O=$.generateUniqueNumber(Y);Y.set(O,_);var w=function(){return H("set",{delay:F,now:performance.timeOrigin+performance.now(),timerId:O,timerType:"interval"}).then(function(){var q=Y.get(O);if(q===void 0)throw Error("The timer is in an undefined state.");if(q===_){if(V.apply(void 0,U),Y.get(O)===_)w()}})};return w(),O}},setTimeout:function(G){var H=G.call;return function(V){var F=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;for(var B=arguments.length,U=Array(B>2?B-2:0),D=2;D<B;D++)U[D-2]=arguments[D];var _=Symbol(),O=$.generateUniqueNumber(Q);return Q.set(O,_),H("set",{delay:F,now:performance.timeOrigin+performance.now(),timerId:O,timerType:"timeout"}).then(function(){var w=Q.get(O);if(w===void 0)throw Error("The timer is in an undefined state.");if(w===_)Q.delete(O),V.apply(void 0,U)}),O}}}),K=function(G){var H=new Worker(G);return W(H)};Z.load=K,Z.wrap=W})});var wX0=L((XH,OX0)=>{(function(Z,J){typeof XH==="object"&&typeof OX0<"u"?J(XH,_X0()):typeof define==="function"&&define.amd?define(["exports","worker-timers-broker"],J):(Z=typeof globalThis<"u"?globalThis:Z||self,J(Z.workerTimers={},Z.workerTimersBroker))})(XH,function(Z,J){var X=function(H,V){var F=null;return function(){if(F!==null)return F;var B=new Blob([V],{type:"application/javascript; charset=utf-8"}),U=URL.createObjectURL(B);return F=H(U),setTimeout(function(){return URL.revokeObjectURL(U)}),F}},$='(()=>{var e={45:(e,t,r)=>{var n=r(738).default;e.exports=function(e,t){if("object"!=n(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var o=r.call(e,t||"default");if("object"!=n(o))return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)},e.exports.__esModule=!0,e.exports.default=e.exports},79:e=>{e.exports=function(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n},e.exports.__esModule=!0,e.exports.default=e.exports},122:(e,t,r)=>{var n=r(79);e.exports=function(e,t){if(e){if("string"==typeof e)return n(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?n(e,t):void 0}},e.exports.__esModule=!0,e.exports.default=e.exports},156:e=>{e.exports=function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,u,a,i=[],s=!0,c=!1;try{if(u=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;s=!1}else for(;!(s=(n=u.call(r)).done)&&(i.push(n.value),i.length!==t);s=!0);}catch(e){c=!0,o=e}finally{try{if(!s&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(c)throw o}}return i}},e.exports.__esModule=!0,e.exports.default=e.exports},172:e=>{e.exports=function(e,t){this.v=e,this.k=t},e.exports.__esModule=!0,e.exports.default=e.exports},293:e=>{function t(e,t,r,n,o,u,a){try{var i=e[u](a),s=i.value}catch(e){return void r(e)}i.done?t(s):Promise.resolve(s).then(n,o)}e.exports=function(e){return function(){var r=this,n=arguments;return new Promise(function(o,u){var a=e.apply(r,n);function i(e){t(a,o,u,i,s,"next",e)}function s(e){t(a,o,u,i,s,"throw",e)}i(void 0)})}},e.exports.__esModule=!0,e.exports.default=e.exports},373:e=>{e.exports=function(e){var t=Object(e),r=[];for(var n in t)r.unshift(n);return function e(){for(;r.length;)if((n=r.pop())in t)return e.value=n,e.done=!1,e;return e.done=!0,e}},e.exports.__esModule=!0,e.exports.default=e.exports},389:function(e,t){!function(e){"use strict";var t=function(e){return function(t){var r=e(t);return t.add(r),r}},r=function(e){return function(t,r){return e.set(t,r),r}},n=void 0===Number.MAX_SAFE_INTEGER?9007199254740991:Number.MAX_SAFE_INTEGER,o=536870912,u=2*o,a=function(e,t){return function(r){var a=t.get(r),i=void 0===a?r.size:a<u?a+1:0;if(!r.has(i))return e(r,i);if(r.size<o){for(;r.has(i);)i=Math.floor(Math.random()*u);return e(r,i)}if(r.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;r.has(i);)i=Math.floor(Math.random()*n);return e(r,i)}},i=new WeakMap,s=r(i),c=a(s,i),f=t(c);e.addUniqueNumber=f,e.generateUniqueNumber=c}(t)},472:function(e,t,r){!function(e,t,r,n){"use strict";var o=function(e,t){return function(r){var o=t.get(r);if(void 0===o)return Promise.resolve(!1);var u=n(o,2),a=u[0],i=u[1];return e(a),t.delete(r),i(!1),Promise.resolve(!0)}},u=function(e,t){var r=function(n,o,u,a){var i=n-e.now();i>0?o.set(a,[t(r,i,n,o,u,a),u]):(o.delete(a),u(!0))};return r},a=function(e,t,r,n){return function(o,u,a){var i=o+u-t.timeOrigin,s=i-t.now();return new Promise(function(t){e.set(a,[r(n,s,i,e,t,a),t])})}},i=new Map,s=o(globalThis.clearTimeout,i),c=new Map,f=o(globalThis.clearTimeout,c),l=u(performance,globalThis.setTimeout),p=a(i,performance,globalThis.setTimeout,l),d=a(c,performance,globalThis.setTimeout,l);r.createWorker(self,{clear:function(){var r=e(t.mark(function e(r){var n,o,u;return t.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.timerId,o=r.timerType,e.next=1,"interval"===o?s(n):f(n);case 1:return u=e.sent,e.abrupt("return",{result:u});case 2:case"end":return e.stop()}},e)}));function n(e){return r.apply(this,arguments)}return n}(),set:function(){var r=e(t.mark(function e(r){var n,o,u,a,i;return t.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.delay,o=r.now,u=r.timerId,a=r.timerType,e.next=1,("interval"===a?p:d)(n,o,u);case 1:return i=e.sent,e.abrupt("return",{result:i});case 2:case"end":return e.stop()}},e)}));function n(e){return r.apply(this,arguments)}return n}()})}(r(293),r(756),r(623),r(715))},546:e=>{function t(r,n,o,u){var a=Object.defineProperty;try{a({},"",{})}catch(r){a=0}e.exports=t=function(e,r,n,o){function u(r,n){t(e,r,function(e){return this._invoke(r,n,e)})}r?a?a(e,r,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[r]=n:(u("next",0),u("throw",1),u("return",2))},e.exports.__esModule=!0,e.exports.default=e.exports,t(r,n,o,u)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports},579:(e,t,r)=>{var n=r(738).default;e.exports=function(e){if(null!=e){var t=e["function"==typeof Symbol&&Symbol.iterator||"@@iterator"],r=0;if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length))return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}throw new TypeError(n(e)+" is not iterable")},e.exports.__esModule=!0,e.exports.default=e.exports},623:function(e,t,r){!function(e,t,r,n,o){"use strict";var u={INTERNAL_ERROR:-32603,INVALID_PARAMS:-32602,METHOD_NOT_FOUND:-32601},a=function(e,t){return Object.assign(new Error(e),{status:t})},i=function(e){return a(\'The requested method called "\'.concat(e,\'" is not supported.\'),u.METHOD_NOT_FOUND)},s=function(e){return a(\'The handler of the method called "\'.concat(e,\'" returned no required result.\'),u.INTERNAL_ERROR)},c=function(e){return a(\'The handler of the method called "\'.concat(e,\'" returned an unexpected result.\'),u.INTERNAL_ERROR)},f=function(e){return a(\'The specified parameter called "portId" with the given value "\'.concat(e,\'" does not identify a port connected to this worker.\'),u.INVALID_PARAMS)},l=function(e,n){return function(){var o=t(r.mark(function t(o){var u,a,f,l,p,d,v,x,y,b,h,m,_,g,w;return r.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(u=o.data,a=u.id,f=u.method,l=u.params,p=n[f],t.prev=1,void 0!==p){t.next=2;break}throw i(f);case 2:if(void 0!==(d=void 0===l?p():p(l))){t.next=3;break}throw s(f);case 3:if(!(d instanceof Promise)){t.next=5;break}return t.next=4,d;case 4:g=t.sent,t.next=6;break;case 5:g=d;case 6:if(v=g,null!==a){t.next=8;break}if(void 0===v.result){t.next=7;break}throw c(f);case 7:t.next=10;break;case 8:if(void 0!==v.result){t.next=9;break}throw c(f);case 9:x=v.result,y=v.transferables,b=void 0===y?[]:y,e.postMessage({id:a,result:x},b);case 10:t.next=12;break;case 11:t.prev=11,w=t.catch(1),h=w.message,m=w.status,_=void 0===m?-32603:m,e.postMessage({error:{code:_,message:h},id:a});case 12:case"end":return t.stop()}},t,null,[[1,11]])}));return function(e){return o.apply(this,arguments)}}()},p=function(){return new Promise(function(e){var t=new ArrayBuffer(0),r=new MessageChannel,n=r.port1,o=r.port2;n.onmessage=function(t){var r=t.data;return e(null!==r)},o.postMessage(t,[t])})};function d(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function v(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?d(Object(r),!0).forEach(function(t){n(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):d(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}var x=new Map,y=function(e,n,u){return v(v({},n),{},{connect:function(t){var r=t.port;r.start();var u=e(r,n),a=o.generateUniqueNumber(x);return x.set(a,function(){u(),r.close(),x.delete(a)}),{result:a}},disconnect:function(e){var t=e.portId,r=x.get(t);if(void 0===r)throw f(t);return r(),{result:null}},isSupported:function(){var e=t(r.mark(function e(){var t,n,o;return r.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=1,p();case 1:if(!e.sent){e.next=5;break}if(!((t=u())instanceof Promise)){e.next=3;break}return e.next=2,t;case 2:o=e.sent,e.next=4;break;case 3:o=t;case 4:return n=o,e.abrupt("return",{result:n});case 5:return e.abrupt("return",{result:!1});case 6:case"end":return e.stop()}},e)}));function n(){return e.apply(this,arguments)}return n}()})},b=function(e,t){var r=y(b,t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:function(){return!0}),n=l(e,r);return e.addEventListener("message",n),function(){return e.removeEventListener("message",n)}};e.createWorker=b,e.isSupported=p}(t,r(293),r(756),r(693),r(389))},633:(e,t,r)=>{var n=r(172),o=r(993),u=r(869),a=r(887),i=r(791),s=r(373),c=r(579);function f(){"use strict";var t=o(),r=t.m(f),l=(Object.getPrototypeOf?Object.getPrototypeOf(r):r.__proto__).constructor;function p(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===l||"GeneratorFunction"===(t.displayName||t.name))}var d={throw:1,return:2,break:3,continue:3};function v(e){var t,r;return function(n){t||(t={stop:function(){return r(n.a,2)},catch:function(){return n.v},abrupt:function(e,t){return r(n.a,d[e],t)},delegateYield:function(e,o,u){return t.resultName=o,r(n.d,c(e),u)},finish:function(e){return r(n.f,e)}},r=function(e,r,o){n.p=t.prev,n.n=t.next;try{return e(r,o)}finally{t.next=n.n}}),t.resultName&&(t[t.resultName]=n.v,t.resultName=void 0),t.sent=n.v,t.next=n.n;try{return e.call(this,t)}finally{n.p=t.prev,n.n=t.next}}}return(e.exports=f=function(){return{wrap:function(e,r,n,o){return t.w(v(e),r,n,o&&o.reverse())},isGeneratorFunction:p,mark:t.m,awrap:function(e,t){return new n(e,t)},AsyncIterator:i,async:function(e,t,r,n,o){return(p(t)?a:u)(v(e),t,r,n,o)},keys:s,values:c}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=f,e.exports.__esModule=!0,e.exports.default=e.exports},693:(e,t,r)=>{var n=r(736);e.exports=function(e,t,r){return(t=n(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e},e.exports.__esModule=!0,e.exports.default=e.exports},715:(e,t,r)=>{var n=r(987),o=r(156),u=r(122),a=r(752);e.exports=function(e,t){return n(e)||o(e,t)||u(e,t)||a()},e.exports.__esModule=!0,e.exports.default=e.exports},736:(e,t,r)=>{var n=r(738).default,o=r(45);e.exports=function(e){var t=o(e,"string");return"symbol"==n(t)?t:t+""},e.exports.__esModule=!0,e.exports.default=e.exports},738:e=>{function t(r){return e.exports=t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e.exports.__esModule=!0,e.exports.default=e.exports,t(r)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports},752:e=>{e.exports=function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")},e.exports.__esModule=!0,e.exports.default=e.exports},756:(e,t,r)=>{var n=r(633)();e.exports=n;try{regeneratorRuntime=n}catch(e){"object"==typeof globalThis?globalThis.regeneratorRuntime=n:Function("r","regeneratorRuntime = r")(n)}},791:(e,t,r)=>{var n=r(172),o=r(546);e.exports=function e(t,r){function u(e,o,a,i){try{var s=t[e](o),c=s.value;return c instanceof n?r.resolve(c.v).then(function(e){u("next",e,a,i)},function(e){u("throw",e,a,i)}):r.resolve(c).then(function(e){s.value=e,a(s)},function(e){return u("throw",e,a,i)})}catch(e){i(e)}}var a;this.next||(o(e.prototype),o(e.prototype,"function"==typeof Symbol&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),o(this,"_invoke",function(e,t,n){function o(){return new r(function(t,r){u(e,n,t,r)})}return a=a?a.then(o,o):o()},!0)},e.exports.__esModule=!0,e.exports.default=e.exports},869:(e,t,r)=>{var n=r(887);e.exports=function(e,t,r,o,u){var a=n(e,t,r,o,u);return a.next().then(function(e){return e.done?e.value:a.next()})},e.exports.__esModule=!0,e.exports.default=e.exports},887:(e,t,r)=>{var n=r(993),o=r(791);e.exports=function(e,t,r,u,a){return new o(n().w(e,t,r,u),a||Promise)},e.exports.__esModule=!0,e.exports.default=e.exports},987:e=>{e.exports=function(e){if(Array.isArray(e))return e},e.exports.__esModule=!0,e.exports.default=e.exports},993:(e,t,r)=>{var n=r(546);function o(){var t,r,u="function"==typeof Symbol?Symbol:{},a=u.iterator||"@@iterator",i=u.toStringTag||"@@toStringTag";function s(e,o,u,a){var i=o&&o.prototype instanceof f?o:f,s=Object.create(i.prototype);return n(s,"_invoke",function(e,n,o){var u,a,i,s=0,f=o||[],l=!1,p={p:0,n:0,v:t,a:d,f:d.bind(t,4),d:function(e,r){return u=e,a=0,i=t,p.n=r,c}};function d(e,n){for(a=e,i=n,r=0;!l&&s&&!o&&r<f.length;r++){var o,u=f[r],d=p.p,v=u[2];e>3?(o=v===n)&&(i=u[(a=u[4])?5:(a=3,3)],u[4]=u[5]=t):u[0]<=d&&((o=e<2&&d<u[1])?(a=0,p.v=n,p.n=u[1]):d<v&&(o=e<3||u[0]>n||n>v)&&(u[4]=e,u[5]=n,p.n=v,a=0))}if(o||e>1)return c;throw l=!0,n}return function(o,f,v){if(s>1)throw TypeError("Generator is already running");for(l&&1===f&&d(f,v),a=f,i=v;(r=a<2?t:i)||!l;){u||(a?a<3?(a>1&&(p.n=-1),d(a,i)):p.n=i:p.v=i);try{if(s=2,u){if(a||(o="next"),r=u[o]){if(!(r=r.call(u,i)))throw TypeError("iterator result is not an object");if(!r.done)return r;i=r.value,a<2&&(a=0)}else 1===a&&(r=u.return)&&r.call(u),a<2&&(i=TypeError("The iterator does not provide a \'"+o+"\' method"),a=1);u=t}else if((r=(l=p.n<0)?i:e.call(n,p))!==c)break}catch(e){u=t,a=1,i=e}finally{s=1}}return{value:r,done:l}}}(e,u,a),!0),s}var c={};function f(){}function l(){}function p(){}r=Object.getPrototypeOf;var d=[][a]?r(r([][a]())):(n(r={},a,function(){return this}),r),v=p.prototype=f.prototype=Object.create(d);function x(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,p):(e.__proto__=p,n(e,i,"GeneratorFunction")),e.prototype=Object.create(v),e}return l.prototype=p,n(v,"constructor",p),n(p,"constructor",l),l.displayName="GeneratorFunction",n(p,i,"GeneratorFunction"),n(v),n(v,i,"Generator"),n(v,a,function(){return this}),n(v,"toString",function(){return"[object Generator]"}),(e.exports=o=function(){return{w:s,m:x}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=o,e.exports.__esModule=!0,e.exports.default=e.exports}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var u=t[n]={exports:{}};return e[n].call(u.exports,u,u.exports,r),u.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{"use strict";r(472)})()})();',Y=X(J.load,$),Q=function(H){return Y().clearInterval(H)},W=function(H){return Y().clearTimeout(H)},K=function(){var H;return(H=Y()).setInterval.apply(H,arguments)},z=function(){var H;return(H=Y()).setTimeout.apply(H,arguments)};Z.clearInterval=Q,Z.clearTimeout=W,Z.setInterval=K,Z.setTimeout=z})});var qQ=L((AX0)=>{Object.defineProperty(AX0,"__esModule",{value:!0});AX0.isReactNativeBrowser=AX0.isWebWorker=void 0;var o61=()=>{if(typeof window<"u"){if(typeof navigator<"u"&&navigator.userAgent?.toLowerCase().indexOf(" electron/")>-1&&process?.versions)return!Object.prototype.hasOwnProperty.call(process.versions,"electron");return typeof window.document<"u"}return!1},jX0=()=>Boolean(typeof self==="object"&&self?.constructor?.name?.includes("WorkerGlobalScope")&&typeof Deno>"u"),MX0=()=>typeof navigator<"u"&&navigator.product==="ReactNative",a61=o61()||jX0()||MX0();AX0.isWebWorker=jX0();AX0.isReactNativeBrowser=MX0();AX0.default=a61});var RX0=L((T9)=>{var t61=T9&&T9.__createBinding||(Object.create?function(Z,J,X,$){if($===void 0)$=X;var Y=Object.getOwnPropertyDescriptor(J,X);if(!Y||("get"in Y?!J.__esModule:Y.writable||Y.configurable))Y={enumerable:!0,get:function(){return J[X]}};Object.defineProperty(Z,$,Y)}:function(Z,J,X,$){if($===void 0)$=X;Z[$]=J[X]}),e61=T9&&T9.__setModuleDefault||(Object.create?function(Z,J){Object.defineProperty(Z,"default",{enumerable:!0,value:J})}:function(Z,J){Z.default=J}),Z81=T9&&T9.__importStar||function(){var Z=function(J){return Z=Object.getOwnPropertyNames||function(X){var $=[];for(var Y in X)if(Object.prototype.hasOwnProperty.call(X,Y))$[$.length]=Y;return $},Z(J)};return function(J){if(J&&J.__esModule)return J;var X={};if(J!=null){for(var $=Z(J),Y=0;Y<$.length;Y++)if($[Y]!=="default")t61(X,J,$[Y])}return e61(X,J),X}}();Object.defineProperty(T9,"__esModule",{value:!0});var qX0=wX0(),Bw=Z81(qQ()),CX0={set:qX0.setInterval,clear:qX0.clearInterval},NX0={set:(Z,J)=>setInterval(Z,J),clear:(Z)=>clearInterval(Z)},J81=(Z)=>{switch(Z){case"native":return NX0;case"worker":return CX0;case"auto":default:return Bw.default&&!Bw.isWebWorker&&!Bw.isReactNativeBrowser?CX0:NX0}};T9.default=J81});var Uw=L((CQ)=>{var X81=CQ&&CQ.__importDefault||function(Z){return Z&&Z.__esModule?Z:{default:Z}};Object.defineProperty(CQ,"__esModule",{value:!0});var $81=X81(RX0());class PX0{_keepalive;timerId;timer;destroyed=!1;counter;client;_keepaliveTimeoutTimestamp;_intervalEvery;get keepaliveTimeoutTimestamp(){return this._keepaliveTimeoutTimestamp}get intervalEvery(){return this._intervalEvery}get keepalive(){return this._keepalive}constructor(Z,J){this.client=Z,this.timer=typeof J==="object"&&"set"in J&&"clear"in J?J:(0,$81.default)(J),this.setKeepalive(Z.options.keepalive)}clear(){if(this.timerId)this.timer.clear(this.timerId),this.timerId=null}setKeepalive(Z){if(Z*=1000,isNaN(Z)||Z<=0||Z>2147483647)throw Error(`Keepalive value must be an integer between 0 and 2147483647. Provided value is ${Z}`);this._keepalive=Z,this.reschedule(),this.client.log(`KeepaliveManager: set keepalive to ${Z}ms`)}destroy(){this.clear(),this.destroyed=!0}reschedule(){if(this.destroyed)return;this.clear(),this.counter=0;let Z=Math.ceil(this._keepalive*1.5);this._keepaliveTimeoutTimestamp=Date.now()+Z,this._intervalEvery=Math.ceil(this._keepalive/2),this.timerId=this.timer.set(()=>{if(this.destroyed)return;if(this.counter+=1,this.counter===2)this.client.sendPing();else if(this.counter>2)this.client.onKeepaliveTimeout()},this._intervalEvery)}}CQ.default=PX0});var YH=L((u8)=>{var Y81=u8&&u8.__createBinding||(Object.create?function(Z,J,X,$){if($===void 0)$=X;var Y=Object.getOwnPropertyDescriptor(J,X);if(!Y||("get"in Y?!J.__esModule:Y.writable||Y.configurable))Y={enumerable:!0,get:function(){return J[X]}};Object.defineProperty(Z,$,Y)}:function(Z,J,X,$){if($===void 0)$=X;Z[$]=J[X]}),Q81=u8&&u8.__setModuleDefault||(Object.create?function(Z,J){Object.defineProperty(Z,"default",{enumerable:!0,value:J})}:function(Z,J){Z.default=J}),kX0=u8&&u8.__importStar||function(){var Z=function(J){return Z=Object.getOwnPropertyNames||function(X){var $=[];for(var Y in X)if(Object.prototype.hasOwnProperty.call(X,Y))$[$.length]=Y;return $},Z(J)};return function(J){if(J&&J.__esModule)return J;var X={};if(J!=null){for(var $=Z(J),Y=0;Y<$.length;Y++)if($[Y]!=="default")Y81(X,J,$[Y])}return Q81(X,J),X}}(),k7=u8&&u8.__importDefault||function(Z){return Z&&Z.__esModule?Z:{default:Z}};Object.defineProperty(u8,"__esModule",{value:!0});var Lw=k7(bG()),W81=R7(),EX0=k7(N70()),K81=k7(h6()),IX0=kX0(E70()),V$=k7(dO()),z81=k7(CJ0()),G81=k7(Jw()),H81=k7(IJ0()),NQ=ZJ(),V81=yJ0(),F81=k7(Uw()),yX0=kX0(qQ()),Dw=globalThis.setImmediate||((...Z)=>{let J=Z.shift();(0,NQ.nextTick)(()=>{J(...Z)})}),SX0={keepalive:60,reschedulePings:!0,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:1000,connectTimeout:30000,clean:!0,resubscribe:!0,subscribeBatchSize:null,writeCache:!0,timerVariant:"auto"};class $H extends V81.TypedEventEmitter{static VERSION=NQ.MQTTJS_VERSION;connected;disconnecting;disconnected;reconnecting;incomingStore;outgoingStore;options;queueQoSZero;_reconnectCount;log;messageIdProvider;outgoing;messageIdToTopic;noop;keepaliveManager;stream;queue;streamBuilder;_resubscribeTopics;connackTimer;reconnectTimer;_storeProcessing;_packetIdsDuringStoreProcessing;_storeProcessingQueue;_firstConnection;topicAliasRecv;topicAliasSend;_deferredReconnect;connackPacket;static defaultId(){return`mqttjs_${Math.random().toString(16).substr(2,8)}`}constructor(Z,J){super();this.options=J||{};for(let X in SX0)if(typeof this.options[X]>"u")this.options[X]=SX0[X];else this.options[X]=J[X];if(this.log=this.options.log||(0,K81.default)("mqttjs:client"),this.noop=this._noop.bind(this),this.log("MqttClient :: version:",$H.VERSION),yX0.isWebWorker)this.log("MqttClient :: environment","webworker");else this.log("MqttClient :: environment",yX0.default?"browser":"node");if(this.log("MqttClient :: options.protocol",J.protocol),this.log("MqttClient :: options.protocolVersion",J.protocolVersion),this.log("MqttClient :: options.username",J.username),this.log("MqttClient :: options.keepalive",J.keepalive),this.log("MqttClient :: options.reconnectPeriod",J.reconnectPeriod),this.log("MqttClient :: options.rejectUnauthorized",J.rejectUnauthorized),this.log("MqttClient :: options.properties.topicAliasMaximum",J.properties?J.properties.topicAliasMaximum:void 0),this.options.clientId=typeof J.clientId==="string"?J.clientId:$H.defaultId(),this.log("MqttClient :: clientId",this.options.clientId),this.options.customHandleAcks=J.protocolVersion===5&&J.customHandleAcks?J.customHandleAcks:(...X)=>{X[3](null,0)},!this.options.writeCache)Lw.default.writeToStream.cacheNumbers=!1;if(this.streamBuilder=Z,this.messageIdProvider=typeof this.options.messageIdProvider>"u"?new G81.default:this.options.messageIdProvider,this.outgoingStore=J.outgoingStore||new V$.default,this.incomingStore=J.incomingStore||new V$.default,this.queueQoSZero=J.queueQoSZero===void 0?!0:J.queueQoSZero,this._resubscribeTopics={},this.messageIdToTopic={},this.keepaliveManager=null,this.connected=!1,this.disconnecting=!1,this.reconnecting=!1,this.queue=[],this.connackTimer=null,this.reconnectTimer=null,this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={},this._storeProcessingQueue=[],this.outgoing={},this._firstConnection=!0,J.properties&&J.properties.topicAliasMaximum>0)if(J.properties.topicAliasMaximum>65535)this.log("MqttClient :: options.properties.topicAliasMaximum is out of range");else this.topicAliasRecv=new H81.default(J.properties.topicAliasMaximum);if(this.on("connect",()=>{let{queue:X}=this,$=()=>{let Y=X.shift();this.log("deliver :: entry %o",Y);let Q=null;if(!Y){this._resubscribe();return}Q=Y.packet,this.log("deliver :: call _sendPacket for %o",Q);let W=!0;if(Q.messageId&&Q.messageId!==0){if(!this.messageIdProvider.register(Q.messageId))W=!1}if(W)this._sendPacket(Q,(K)=>{if(Y.cb)Y.cb(K);$()});else this.log("messageId: %d has already used. The message is skipped and removed.",Q.messageId),$()};this.log("connect :: sending queued packets"),$()}),this.on("close",()=>{if(this.log("close :: connected set to `false`"),this.connected=!1,this.log("close :: clearing connackTimer"),clearTimeout(this.connackTimer),this._destroyKeepaliveManager(),this.topicAliasRecv)this.topicAliasRecv.clear();this.log("close :: calling _setupReconnect"),this._setupReconnect()}),!this.options.manualConnect)this.log("MqttClient :: setting up stream"),this.connect()}handleAuth(Z,J){J()}handleMessage(Z,J){J()}_nextId(){return this.messageIdProvider.allocate()}getLastMessageId(){return this.messageIdProvider.getLastAllocated()}connect(){let Z=new W81.Writable,J=Lw.default.parser(this.options),X=null,$=[];if(this.log("connect :: calling method to clear reconnect"),this._clearReconnect(),this.disconnected&&!this.reconnecting)this.incomingStore=this.options.incomingStore||new V$.default,this.outgoingStore=this.options.outgoingStore||new V$.default,this.disconnecting=!1,this.disconnected=!1;this.log("connect :: using streamBuilder provided to client to create stream"),this.stream=this.streamBuilder(this),J.on("packet",(z)=>{this.log("parser :: on packet push to packets array."),$.push(z)});let Y=()=>{this.log("work :: getting next packet in queue");let z=$.shift();if(z)this.log("work :: packet pulled from queue"),(0,z81.default)(this,z,Q);else{this.log("work :: no packets in queue");let G=X;if(X=null,this.log("work :: done flag is %s",!!G),G)G()}},Q=()=>{if($.length)(0,NQ.nextTick)(Y);else{let z=X;X=null,z()}};Z._write=(z,G,H)=>{X=H,this.log("writable stream :: parsing buffer"),J.parse(z),Y()};let W=(z)=>{if(this.log("streamErrorHandler :: error",z.message),z.code)this.log("streamErrorHandler :: emitting error"),this.emit("error",z);else this.noop(z)};this.log("connect :: pipe stream to writable stream"),this.stream.pipe(Z),this.stream.on("error",W),this.stream.on("close",()=>{this.log("(%s)stream :: on close",this.options.clientId),this._flushVolatile(),this.log("stream: emit close to MqttClient"),this.emit("close")}),this.log("connect: sending packet `connect`");let K={cmd:"connect",protocolId:this.options.protocolId,protocolVersion:this.options.protocolVersion,clean:this.options.clean,clientId:this.options.clientId,keepalive:this.options.keepalive,username:this.options.username,password:this.options.password,properties:this.options.properties};if(this.options.will)K.will={...this.options.will,payload:this.options.will?.payload};if(this.topicAliasRecv){if(!K.properties)K.properties={};if(this.topicAliasRecv)K.properties.topicAliasMaximum=this.topicAliasRecv.max}if(this._writePacket(K),J.on("error",this.emit.bind(this,"error")),this.options.properties){if(!this.options.properties.authenticationMethod&&this.options.properties.authenticationData)return this.end(()=>this.emit("error",Error("Packet has no Authentication Method"))),this;if(this.options.properties.authenticationMethod&&this.options.authPacket&&typeof this.options.authPacket==="object"){let z={cmd:"auth",reasonCode:0,...this.options.authPacket};this._writePacket(z)}}return this.stream.setMaxListeners(1000),clearTimeout(this.connackTimer),this.connackTimer=setTimeout(()=>{this.log("!!connectTimeout hit!! Calling _cleanUp with force `true`"),this.emit("error",Error("connack timeout")),this._cleanUp(!0)},this.options.connectTimeout),this}publish(Z,J,X,$){this.log("publish :: message `%s` to topic `%s`",J,Z);let{options:Y}=this;if(typeof X==="function")$=X,X=null;X=X||{},X={...{qos:0,retain:!1,dup:!1},...X};let{qos:W,retain:K,dup:z,properties:G,cbStorePut:H}=X;if(this._checkDisconnecting($))return this;let V=()=>{let F=0;if(W===1||W===2){if(F=this._nextId(),F===null)return this.log("No messageId left"),!1}let B={cmd:"publish",topic:Z,payload:J,qos:W,retain:K,messageId:F,dup:z};if(Y.protocolVersion===5)B.properties=G;switch(this.log("publish :: qos",W),W){case 1:case 2:this.outgoing[B.messageId]={volatile:!1,cb:$||this.noop},this.log("MqttClient:publish: packet cmd: %s",B.cmd),this._sendPacket(B,void 0,H);break;default:this.log("MqttClient:publish: packet cmd: %s",B.cmd),this._sendPacket(B,$,H);break}return!0};if(this._storeProcessing||this._storeProcessingQueue.length>0||!V())this._storeProcessingQueue.push({invoke:V,cbStorePut:X.cbStorePut,callback:$});return this}publishAsync(Z,J,X){return new Promise(($,Y)=>{this.publish(Z,J,X,(Q,W)=>{if(Q)Y(Q);else $(W)})})}subscribe(Z,J,X){let $=this.options.protocolVersion;if(typeof J==="function")X=J;X=X||this.noop;let Y=!1,Q=[];if(typeof Z==="string")Z=[Z],Q=Z;else if(Array.isArray(Z))Q=Z;else if(typeof Z==="object")Y=Z.resubscribe,delete Z.resubscribe,Q=Object.keys(Z);let W=IX0.validateTopics(Q);if(W!==null)return Dw(X,Error(`Invalid topic ${W}`)),this;if(this._checkDisconnecting(X))return this.log("subscribe: discconecting true"),this;let K={qos:0};if($===5)K.nl=!1,K.rap=!1,K.rh=0;J={...K,...J};let{properties:z}=J,G=[],H=(B,U)=>{if(U=U||J,!Object.prototype.hasOwnProperty.call(this._resubscribeTopics,B)||this._resubscribeTopics[B].qos<U.qos||Y){let D={topic:B,qos:U.qos};if($===5)D.nl=U.nl,D.rap=U.rap,D.rh=U.rh,D.properties=z;this.log("subscribe: pushing topic `%s` and qos `%s` to subs list",D.topic,D.qos),G.push(D)}};if(Array.isArray(Z))Z.forEach((B)=>{this.log("subscribe: array topic %s",B),H(B)});else Object.keys(Z).forEach((B)=>{this.log("subscribe: object topic %s, %o",B,Z[B]),H(B,Z[B])});if(!G.length)return X(null,[]),this;let V=(B,U)=>{let D={cmd:"subscribe",subscriptions:B,messageId:U};if(z)D.properties=z;if(this.options.resubscribe){this.log("subscribe :: resubscribe true");let O=[];B.forEach((w)=>{if(this.options.reconnectPeriod>0){let j={qos:w.qos};if($===5)j.nl=w.nl||!1,j.rap=w.rap||!1,j.rh=w.rh||0,j.properties=w.properties;this._resubscribeTopics[w.topic]=j,O.push(w.topic)}}),this.messageIdToTopic[D.messageId]=O}let _=new Promise((O,w)=>{this.outgoing[D.messageId]={volatile:!0,cb(j,q){if(!j){let{granted:R}=q;for(let T=0;T<R.length;T+=1)B[T].qos=R[T]}if(!j)O(q);else w(new NQ.ErrorWithSubackPacket(j.message,q))}}});return this.log("subscribe :: call _sendPacket"),this._sendPacket(D),_},F=()=>{let B=this.options.subscribeBatchSize??G.length,U=[];for(let D=0;D<G.length;D+=B){let _=G.slice(D,D+B),O=this._nextId();if(O===null)return this.log("No messageId left"),!1;U.push(V(_,O))}return Promise.all(U).then((D)=>{X(null,G,D.at(-1))}).catch((D)=>{X(D,G,D.packet)}),!0};if(this._storeProcessing||this._storeProcessingQueue.length>0||!F())this._storeProcessingQueue.push({invoke:F,callback:X});return this}subscribeAsync(Z,J){return new Promise((X,$)=>{this.subscribe(Z,J,(Y,Q)=>{if(Y)$(Y);else X(Q)})})}unsubscribe(Z,J,X){if(typeof Z==="string")Z=[Z];if(typeof J==="function")X=J;X=X||this.noop;let $=IX0.validateTopics(Z);if($!==null)return Dw(X,Error(`Invalid topic ${$}`)),this;if(this._checkDisconnecting(X))return this;let Y=()=>{let Q=this._nextId();if(Q===null)return this.log("No messageId left"),!1;let W={cmd:"unsubscribe",messageId:Q,unsubscriptions:[]};if(typeof Z==="string")W.unsubscriptions=[Z];else if(Array.isArray(Z))W.unsubscriptions=Z;if(this.options.resubscribe)W.unsubscriptions.forEach((K)=>{delete this._resubscribeTopics[K]});if(typeof J==="object"&&J.properties)W.properties=J.properties;return this.outgoing[W.messageId]={volatile:!0,cb:X},this.log("unsubscribe: call _sendPacket"),this._sendPacket(W),!0};if(this._storeProcessing||this._storeProcessingQueue.length>0||!Y())this._storeProcessingQueue.push({invoke:Y,callback:X});return this}unsubscribeAsync(Z,J){return new Promise((X,$)=>{this.unsubscribe(Z,J,(Y,Q)=>{if(Y)$(Y);else X(Q)})})}end(Z,J,X){if(this.log("end :: (%s)",this.options.clientId),Z==null||typeof Z!=="boolean")X=X||J,J=Z,Z=!1;if(typeof J!=="object")X=X||J,J=null;if(this.log("end :: cb? %s",!!X),!X||typeof X!=="function")X=this.noop;let $=()=>{if(this.log("end :: closeStores: closing incoming and outgoing stores"),this.disconnected=!0,this.incomingStore.close((Q)=>{this.outgoingStore.close((W)=>{if(this.log("end :: closeStores: emitting end"),this.emit("end"),X){let K=Q||W;this.log("end :: closeStores: invoking callback with args"),X(K)}})}),this._deferredReconnect)this._deferredReconnect();else if(this.options.reconnectPeriod===0||this.options.manualConnect)this.disconnecting=!1},Y=()=>{this.log("end :: (%s) :: finish :: calling _cleanUp with force %s",this.options.clientId,Z),this._cleanUp(Z,()=>{this.log("end :: finish :: calling process.nextTick on closeStores"),(0,NQ.nextTick)($)},J)};if(this.disconnecting)return X(),this;if(this._clearReconnect(),this.disconnecting=!0,!Z&&Object.keys(this.outgoing).length>0)this.log("end :: (%s) :: calling finish in 10ms once outgoing is empty",this.options.clientId),this.once("outgoingEmpty",setTimeout.bind(null,Y,10));else this.log("end :: (%s) :: immediately calling finish",this.options.clientId),Y();return this}endAsync(Z,J){return new Promise((X,$)=>{this.end(Z,J,(Y)=>{if(Y)$(Y);else X()})})}removeOutgoingMessage(Z){if(this.outgoing[Z]){let{cb:J}=this.outgoing[Z];this._removeOutgoingAndStoreMessage(Z,()=>{J(Error("Message removed"))})}return this}reconnect(Z){this.log("client reconnect");let J=()=>{if(Z)this.options.incomingStore=Z.incomingStore,this.options.outgoingStore=Z.outgoingStore;else this.options.incomingStore=null,this.options.outgoingStore=null;this.incomingStore=this.options.incomingStore||new V$.default,this.outgoingStore=this.options.outgoingStore||new V$.default,this.disconnecting=!1,this.disconnected=!1,this._deferredReconnect=null,this._reconnect()};if(this.disconnecting&&!this.disconnected)this._deferredReconnect=J;else J();return this}_flushVolatile(){if(this.outgoing)this.log("_flushVolatile :: deleting volatile messages from the queue and setting their callbacks as error function"),Object.keys(this.outgoing).forEach((Z)=>{if(this.outgoing[Z].volatile&&typeof this.outgoing[Z].cb==="function")this.outgoing[Z].cb(Error("Connection closed")),delete this.outgoing[Z]})}_flush(){if(this.outgoing)this.log("_flush: queue exists? %b",!!this.outgoing),Object.keys(this.outgoing).forEach((Z)=>{if(typeof this.outgoing[Z].cb==="function")this.outgoing[Z].cb(Error("Connection closed")),delete this.outgoing[Z]})}_removeTopicAliasAndRecoverTopicName(Z){let J;if(Z.properties)J=Z.properties.topicAlias;let X=Z.topic.toString();if(this.log("_removeTopicAliasAndRecoverTopicName :: alias %d, topic %o",J,X),X.length===0){if(typeof J>"u")return Error("Unregistered Topic Alias");if(X=this.topicAliasSend.getTopicByAlias(J),typeof X>"u")return Error("Unregistered Topic Alias");Z.topic=X}if(J)delete Z.properties.topicAlias}_checkDisconnecting(Z){if(this.disconnecting)if(Z&&Z!==this.noop)Z(Error("client disconnecting"));else this.emit("error",Error("client disconnecting"));return this.disconnecting}_reconnect(){if(this.log("_reconnect: emitting reconnect to client"),this.emit("reconnect"),this.connected)this.end(()=>{this.connect()}),this.log("client already connected. disconnecting first.");else this.log("_reconnect: calling connect"),this.connect()}_setupReconnect(){if(!this.disconnecting&&!this.reconnectTimer&&this.options.reconnectPeriod>0){if(!this.reconnecting)this.log("_setupReconnect :: emit `offline` state"),this.emit("offline"),this.log("_setupReconnect :: set `reconnecting` to `true`"),this.reconnecting=!0;this.log("_setupReconnect :: setting reconnectTimer for %d ms",this.options.reconnectPeriod),this.reconnectTimer=setInterval(()=>{this.log("reconnectTimer :: reconnect triggered!"),this._reconnect()},this.options.reconnectPeriod)}else this.log("_setupReconnect :: doing nothing...")}_clearReconnect(){if(this.log("_clearReconnect : clearing reconnect timer"),this.reconnectTimer)clearInterval(this.reconnectTimer),this.reconnectTimer=null}_cleanUp(Z,J,X={}){if(J)this.log("_cleanUp :: done callback provided for on stream close"),this.stream.on("close",J);if(this.log("_cleanUp :: forced? %s",Z),Z){if(this.options.reconnectPeriod===0&&this.options.clean)this._flush();this.log("_cleanUp :: (%s) :: destroying stream",this.options.clientId),this.stream.destroy()}else{let $={cmd:"disconnect",...X};this.log("_cleanUp :: (%s) :: call _sendPacket with disconnect packet",this.options.clientId),this._sendPacket($,()=>{this.log("_cleanUp :: (%s) :: destroying stream",this.options.clientId),Dw(()=>{this.stream.end(()=>{this.log("_cleanUp :: (%s) :: stream destroyed",this.options.clientId)})})})}if(!this.disconnecting&&!this.reconnecting)this.log("_cleanUp :: client not disconnecting/reconnecting. Clearing and resetting reconnect."),this._clearReconnect(),this._setupReconnect();if(this._destroyKeepaliveManager(),J&&!this.connected)this.log("_cleanUp :: (%s) :: removing stream `done` callback `close` listener",this.options.clientId),this.stream.removeListener("close",J),J()}_storeAndSend(Z,J,X){this.log("storeAndSend :: store packet with cmd %s to outgoingStore",Z.cmd);let $=Z,Y;if($.cmd==="publish"){if($=(0,EX0.default)(Z),Y=this._removeTopicAliasAndRecoverTopicName($),Y)return J&&J(Y)}this.outgoingStore.put($,(Q)=>{if(Q)return J&&J(Q);X(),this._writePacket(Z,J)})}_applyTopicAlias(Z){if(this.options.protocolVersion===5){if(Z.cmd==="publish"){let J;if(Z.properties)J=Z.properties.topicAlias;let X=Z.topic.toString();if(this.topicAliasSend){if(J){if(X.length!==0){if(this.log("applyTopicAlias :: register topic: %s - alias: %d",X,J),!this.topicAliasSend.put(X,J))return this.log("applyTopicAlias :: error out of range. topic: %s - alias: %d",X,J),Error("Sending Topic Alias out of range")}}else if(X.length!==0){if(this.options.autoAssignTopicAlias)if(J=this.topicAliasSend.getAliasByTopic(X),J)Z.topic="",Z.properties={...Z.properties,topicAlias:J},this.log("applyTopicAlias :: auto assign(use) topic: %s - alias: %d",X,J);else J=this.topicAliasSend.getLruAlias(),this.topicAliasSend.put(X,J),Z.properties={...Z.properties,topicAlias:J},this.log("applyTopicAlias :: auto assign topic: %s - alias: %d",X,J);else if(this.options.autoUseTopicAlias){if(J=this.topicAliasSend.getAliasByTopic(X),J)Z.topic="",Z.properties={...Z.properties,topicAlias:J},this.log("applyTopicAlias :: auto use topic: %s - alias: %d",X,J)}}}else if(J)return this.log("applyTopicAlias :: error out of range. topic: %s - alias: %d",X,J),Error("Sending Topic Alias out of range")}}}_noop(Z){this.log("noop ::",Z)}_writePacket(Z,J){this.log("_writePacket :: packet: %O",Z),this.log("_writePacket :: emitting `packetsend`"),this.emit("packetsend",Z),this.log("_writePacket :: writing to stream");let X=Lw.default.writeToStream(Z,this.stream,this.options);if(this.log("_writePacket :: writeToStream result %s",X),!X&&J&&J!==this.noop)this.log("_writePacket :: handle events on `drain` once through callback."),this.stream.once("drain",J);else if(J)this.log("_writePacket :: invoking cb"),J()}_sendPacket(Z,J,X,$){this.log("_sendPacket :: (%s) :: start",this.options.clientId),X=X||this.noop,J=J||this.noop;let Y=this._applyTopicAlias(Z);if(Y){J(Y);return}if(!this.connected){if(Z.cmd==="auth"){this._writePacket(Z,J);return}this.log("_sendPacket :: client not connected. Storing packet offline."),this._storePacket(Z,J,X);return}if($){this._writePacket(Z,J);return}switch(Z.cmd){case"publish":break;case"pubrel":this._storeAndSend(Z,J,X);return;default:this._writePacket(Z,J);return}switch(Z.qos){case 2:case 1:this._storeAndSend(Z,J,X);break;case 0:default:this._writePacket(Z,J);break}this.log("_sendPacket :: (%s) :: end",this.options.clientId)}_storePacket(Z,J,X){this.log("_storePacket :: packet: %o",Z),this.log("_storePacket :: cb? %s",!!J),X=X||this.noop;let $=Z;if($.cmd==="publish"){$=(0,EX0.default)(Z);let Q=this._removeTopicAliasAndRecoverTopicName($);if(Q)return J&&J(Q)}let Y=$.qos||0;if(Y===0&&this.queueQoSZero||$.cmd!=="publish")this.queue.push({packet:$,cb:J});else if(Y>0)J=this.outgoing[$.messageId]?this.outgoing[$.messageId].cb:null,this.outgoingStore.put($,(Q)=>{if(Q)return J&&J(Q);X()});else if(J)J(Error("No connection to broker"))}_setupKeepaliveManager(){if(this.log("_setupKeepaliveManager :: keepalive %d (seconds)",this.options.keepalive),!this.keepaliveManager&&this.options.keepalive)this.keepaliveManager=new F81.default(this,this.options.timerVariant)}_destroyKeepaliveManager(){if(this.keepaliveManager)this.log("_destroyKeepaliveManager :: destroying keepalive manager"),this.keepaliveManager.destroy(),this.keepaliveManager=null}reschedulePing(Z=!1){if(this.keepaliveManager&&this.options.keepalive&&(Z||this.options.reschedulePings))this._reschedulePing()}_reschedulePing(){this.log("_reschedulePing :: rescheduling ping"),this.keepaliveManager.reschedule()}sendPing(){this.log("_sendPing :: sending pingreq"),this._sendPacket({cmd:"pingreq"})}onKeepaliveTimeout(){this.emit("error",Error("Keepalive timeout")),this.log("onKeepaliveTimeout :: calling _cleanUp with force true"),this._cleanUp(!0)}_resubscribe(){this.log("_resubscribe");let Z=Object.keys(this._resubscribeTopics);if(!this._firstConnection&&(this.options.clean||this.options.protocolVersion>=4&&!this.connackPacket.sessionPresent)&&Z.length>0)if(this.options.resubscribe)if(this.options.protocolVersion===5){this.log("_resubscribe: protocolVersion 5");for(let J=0;J<Z.length;J++){let X={};X[Z[J]]=this._resubscribeTopics[Z[J]],X.resubscribe=!0,this.subscribe(X,{properties:X[Z[J]].properties})}}else this._resubscribeTopics.resubscribe=!0,this.subscribe(this._resubscribeTopics);else this._resubscribeTopics={};this._firstConnection=!1}_onConnect(Z){if(this.disconnected){this.emit("connect",Z);return}this.connackPacket=Z,this.messageIdProvider.clear(),this._setupKeepaliveManager(),this.connected=!0;let J=()=>{let X=this.outgoingStore.createStream(),$=()=>{X.destroy(),X=null,this._flushStoreProcessingQueue(),Y()},Y=()=>{this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={}};this.once("close",$),X.on("error",(W)=>{Y(),this._flushStoreProcessingQueue(),this.removeListener("close",$),this.emit("error",W)});let Q=()=>{if(!X)return;let W=X.read(1),K;if(!W){X.once("readable",Q);return}if(this._storeProcessing=!0,this._packetIdsDuringStoreProcessing[W.messageId]){Q();return}if(!this.disconnecting&&!this.reconnectTimer)if(K=this.outgoing[W.messageId]?this.outgoing[W.messageId].cb:null,this.outgoing[W.messageId]={volatile:!1,cb(z,G){if(K)K(z,G);Q()}},this._packetIdsDuringStoreProcessing[W.messageId]=!0,this.messageIdProvider.register(W.messageId))this._sendPacket(W,void 0,void 0,!0);else this.log("messageId: %d has already used.",W.messageId);else if(X.destroy)X.destroy()};X.on("end",()=>{let W=!0;for(let K in this._packetIdsDuringStoreProcessing)if(!this._packetIdsDuringStoreProcessing[K]){W=!1;break}if(this.removeListener("close",$),W)Y(),this._invokeAllStoreProcessingQueue(),this.emit("connect",Z);else J()}),Q()};J()}_invokeStoreProcessingQueue(){if(!this._storeProcessing&&this._storeProcessingQueue.length>0){let Z=this._storeProcessingQueue[0];if(Z&&Z.invoke())return this._storeProcessingQueue.shift(),!0}return!1}_invokeAllStoreProcessingQueue(){while(this._invokeStoreProcessingQueue());}_flushStoreProcessingQueue(){for(let Z of this._storeProcessingQueue){if(Z.cbStorePut)Z.cbStorePut(Error("Connection closed"));if(Z.callback)Z.callback(Error("Connection closed"))}this._storeProcessingQueue.splice(0)}_removeOutgoingAndStoreMessage(Z,J){delete this.outgoing[Z],this.outgoingStore.del({messageId:Z},(X,$)=>{J(X,$),this.messageIdProvider.deallocate(Z),this._invokeStoreProcessingQueue()})}}u8.default=$H});var hX0=L((vX0)=>{Object.defineProperty(vX0,"__esModule",{value:!0});var B81=Zw();class xX0{numberAllocator;lastId;constructor(){this.numberAllocator=new B81.NumberAllocator(1,65535)}allocate(){return this.lastId=this.numberAllocator.alloc(),this.lastId}getLastAllocated(){return this.lastId}register(Z){return this.numberAllocator.use(Z)}deallocate(Z){this.numberAllocator.free(Z)}clear(){this.numberAllocator.clear()}}vX0.default=xX0});var QH=L((mX0)=>{Object.defineProperty(mX0,"__esModule",{value:!0});mX0.BufferedDuplex=void 0;mX0.writev=bX0;var L81=R7(),fX0=N("buffer");function bX0(Z,J){let X=Array(Z.length);for(let $=0;$<Z.length;$++)if(typeof Z[$].chunk==="string")X[$]=fX0.Buffer.from(Z[$].chunk,"utf8");else X[$]=Z[$].chunk;this._write(fX0.Buffer.concat(X),"binary",J)}class gX0 extends L81.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(Z,J,X){super({objectMode:!0});if(this.proxy=J,this.socket=X,this.writeQueue=[],!Z.objectMode)this._writev=bX0.bind(this);this.isSocketOpen=!1,this.proxy.on("data",($)=>{if(!this.destroyed&&this.readable)this.push($)})}_read(Z){this.proxy.read(Z)}_write(Z,J,X){if(!this.isSocketOpen)this.writeQueue.push({chunk:Z,encoding:J,cb:X});else this.writeToProxy(Z,J,X)}_final(Z){this.writeQueue=[],this.proxy.end(Z)}_destroy(Z,J){this.writeQueue=[],this.proxy.destroy(),J(Z)}socketReady(){this.emit("connect"),this.isSocketOpen=!0,this.processWriteQueue()}writeToProxy(Z,J,X){if(this.proxy.write(Z,J)===!1)this.proxy.once("drain",X);else X()}processWriteQueue(){while(this.writeQueue.length>0){let{chunk:Z,encoding:J,cb:X}=this.writeQueue.shift();this.writeToProxy(Z,J,X)}}}mX0.BufferedDuplex=gX0});var RQ=L((v7)=>{var Ow=v7&&v7.__importDefault||function(Z){return Z&&Z.__esModule?Z:{default:Z}};Object.defineProperty(v7,"__esModule",{value:!0});v7.streamBuilder=v7.browserStreamBuilder=void 0;var WH=N("buffer"),uX0=Ow(N("ws")),_81=Ow(h6()),O81=R7(),w81=Ow(qQ()),_w=QH(),x7=(0,_81.default)("mqttjs:ws"),j81=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];function cX0(Z,J){let X=`${Z.protocol}://${Z.hostname}:${Z.port}${Z.path}`;if(typeof Z.transformWsUrl==="function")X=Z.transformWsUrl(X,Z,J);return X}function lX0(Z){let J=Z;if(!Z.port)if(Z.protocol==="wss")J.port=443;else J.port=80;if(!Z.path)J.path="/";if(!Z.wsOptions)J.wsOptions={};if(!w81.default&&!Z.forceNativeWebSocket&&Z.protocol==="wss")j81.forEach((X)=>{if(Object.prototype.hasOwnProperty.call(Z,X)&&!Object.prototype.hasOwnProperty.call(Z.wsOptions,X))J.wsOptions[X]=Z[X]});return J}function M81(Z){let J=lX0(Z);if(!J.hostname)J.hostname=J.host;if(!J.hostname){if(typeof document>"u")throw Error("Could not determine host. Specify host manually.");let X=new URL(document.URL);if(J.hostname=X.hostname,!J.port)J.port=Number(X.port)}if(J.objectMode===void 0)J.objectMode=!(J.binary===!0||J.binary===void 0);return J}function A81(Z,J,X){x7("createWebSocket"),x7(`protocol: ${X.protocolId} ${X.protocolVersion}`);let $=X.protocolId==="MQIsdp"&&X.protocolVersion===3?"mqttv3.1":"mqtt";x7(`creating new Websocket for url: ${J} and protocol: ${$}`);let Y;if(X.createWebsocket)Y=X.createWebsocket(J,[$],X);else Y=new uX0.default(J,[$],X.wsOptions);return Y}function T81(Z,J){let X=J.protocolId==="MQIsdp"&&J.protocolVersion===3?"mqttv3.1":"mqtt",$=cX0(J,Z),Y;if(J.createWebsocket)Y=J.createWebsocket($,[X],J);else Y=new WebSocket($,[X]);return Y.binaryType="arraybuffer",Y}var q81=(Z,J)=>{x7("streamBuilder");let X=lX0(J);X.hostname=X.hostname||X.host||"localhost";let $=cX0(X,Z),Y=A81(Z,$,X),Q=uX0.default.createWebSocketStream(Y,X.wsOptions);return Q.url=$,Y.on("close",()=>{Q.destroy()}),Q};v7.streamBuilder=q81;var C81=(Z,J)=>{x7("browserStreamBuilder");let X,Y=M81(J).browserBufferSize||524288,Q=J.browserBufferTimeout||1000,W=!J.objectMode,K=T81(Z,J),z=H(J,D,_);if(!J.objectMode)z._writev=_w.writev.bind(z);z.on("close",()=>{K.close()});let G=typeof K.addEventListener<"u";if(K.readyState===K.OPEN)X=z,X.socket=K;else if(X=new _w.BufferedDuplex(J,z,K),G)K.addEventListener("open",V);else K.onopen=V;if(G)K.addEventListener("close",F),K.addEventListener("error",B),K.addEventListener("message",U);else K.onclose=F,K.onerror=B,K.onmessage=U;function H(O,w,j){let q=new O81.Transform({objectMode:O.objectMode});return q._write=w,q._flush=j,q}function V(){if(x7("WebSocket onOpen"),X instanceof _w.BufferedDuplex)X.socketReady()}function F(O){x7("WebSocket onClose",O),X.end(),X.destroy()}function B(O){x7("WebSocket onError",O);let w=Error("WebSocket error");w.event=O,X.destroy(w)}async function U(O){if(!z||!z.readable||!z.writable)return;let{data:w}=O;if(w instanceof ArrayBuffer)w=WH.Buffer.from(w);else if(w instanceof Blob)w=WH.Buffer.from(await new Response(w).arrayBuffer());else w=WH.Buffer.from(w,"utf8");z.push(w)}function D(O,w,j){if(K.bufferedAmount>Y){setTimeout(D,Q,O,w,j);return}if(W&&typeof O==="string")O=WH.Buffer.from(O,"utf8");try{K.send(O)}catch(q){return j(q)}j()}function _(O){K.close(),O()}return X};v7.browserStreamBuilder=C81});var aX0=L((oX0)=>{Object.defineProperty(oX0,"__esModule",{value:!0});var pX0=N("buffer"),KJ={INVALID_ENCODING:"Invalid encoding provided. Please specify a valid encoding the internal Node.js Buffer supports.",INVALID_SMARTBUFFER_SIZE:"Invalid size provided. Size must be a valid integer greater than zero.",INVALID_SMARTBUFFER_BUFFER:"Invalid Buffer provided in SmartBufferOptions.",INVALID_SMARTBUFFER_OBJECT:"Invalid SmartBufferOptions object supplied to SmartBuffer constructor or factory methods.",INVALID_OFFSET:"An invalid offset value was provided.",INVALID_OFFSET_NON_NUMBER:"An invalid offset value was provided. A numeric value is required.",INVALID_LENGTH:"An invalid length value was provided.",INVALID_LENGTH_NON_NUMBER:"An invalid length value was provived. A numeric value is required.",INVALID_TARGET_OFFSET:"Target offset is beyond the bounds of the internal SmartBuffer data.",INVALID_TARGET_LENGTH:"Specified length value moves cursor beyong the bounds of the internal SmartBuffer data.",INVALID_READ_BEYOND_BOUNDS:"Attempted to read beyond the bounds of the managed data.",INVALID_WRITE_BEYOND_BOUNDS:"Attempted to write beyond the bounds of the managed data."};oX0.ERRORS=KJ;function N81(Z){if(!pX0.Buffer.isEncoding(Z))throw Error(KJ.INVALID_ENCODING)}oX0.checkEncoding=N81;function iX0(Z){return typeof Z==="number"&&isFinite(Z)&&I81(Z)}oX0.isFiniteInteger=iX0;function nX0(Z,J){if(typeof Z==="number"){if(!iX0(Z)||Z<0)throw Error(J?KJ.INVALID_OFFSET:KJ.INVALID_LENGTH)}else throw Error(J?KJ.INVALID_OFFSET_NON_NUMBER:KJ.INVALID_LENGTH_NON_NUMBER)}function R81(Z){nX0(Z,!1)}oX0.checkLengthValue=R81;function P81(Z){nX0(Z,!0)}oX0.checkOffsetValue=P81;function E81(Z,J){if(Z<0||Z>J.length)throw Error(KJ.INVALID_TARGET_OFFSET)}oX0.checkTargetOffset=E81;function I81(Z){return typeof Z==="number"&&isFinite(Z)&&Math.floor(Z)===Z}function y81(Z){if(typeof BigInt>"u")throw Error("Platform does not support JS BigInt type.");if(typeof pX0.Buffer.prototype[Z]>"u")throw Error(`Platform does not support Buffer.prototype.${Z}.`)}oX0.bigIntAndBufferInt64Check=y81});var tX0=L((sX0)=>{Object.defineProperty(sX0,"__esModule",{value:!0});var C0=aX0(),rX0=4096,g81="utf8";class ww{constructor(Z){if(this.length=0,this._encoding=g81,this._writeOffset=0,this._readOffset=0,ww.isSmartBufferOptions(Z)){if(Z.encoding)C0.checkEncoding(Z.encoding),this._encoding=Z.encoding;if(Z.size)if(C0.isFiniteInteger(Z.size)&&Z.size>0)this._buff=Buffer.allocUnsafe(Z.size);else throw Error(C0.ERRORS.INVALID_SMARTBUFFER_SIZE);else if(Z.buff)if(Buffer.isBuffer(Z.buff))this._buff=Z.buff,this.length=Z.buff.length;else throw Error(C0.ERRORS.INVALID_SMARTBUFFER_BUFFER);else this._buff=Buffer.allocUnsafe(rX0)}else{if(typeof Z<"u")throw Error(C0.ERRORS.INVALID_SMARTBUFFER_OBJECT);this._buff=Buffer.allocUnsafe(rX0)}}static fromSize(Z,J){return new this({size:Z,encoding:J})}static fromBuffer(Z,J){return new this({buff:Z,encoding:J})}static fromOptions(Z){return new this(Z)}static isSmartBufferOptions(Z){let J=Z;return J&&(J.encoding!==void 0||J.size!==void 0||J.buff!==void 0)}readInt8(Z){return this._readNumberValue(Buffer.prototype.readInt8,1,Z)}readInt16BE(Z){return this._readNumberValue(Buffer.prototype.readInt16BE,2,Z)}readInt16LE(Z){return this._readNumberValue(Buffer.prototype.readInt16LE,2,Z)}readInt32BE(Z){return this._readNumberValue(Buffer.prototype.readInt32BE,4,Z)}readInt32LE(Z){return this._readNumberValue(Buffer.prototype.readInt32LE,4,Z)}readBigInt64BE(Z){return C0.bigIntAndBufferInt64Check("readBigInt64BE"),this._readNumberValue(Buffer.prototype.readBigInt64BE,8,Z)}readBigInt64LE(Z){return C0.bigIntAndBufferInt64Check("readBigInt64LE"),this._readNumberValue(Buffer.prototype.readBigInt64LE,8,Z)}writeInt8(Z,J){return this._writeNumberValue(Buffer.prototype.writeInt8,1,Z,J),this}insertInt8(Z,J){return this._insertNumberValue(Buffer.prototype.writeInt8,1,Z,J)}writeInt16BE(Z,J){return this._writeNumberValue(Buffer.prototype.writeInt16BE,2,Z,J)}insertInt16BE(Z,J){return this._insertNumberValue(Buffer.prototype.writeInt16BE,2,Z,J)}writeInt16LE(Z,J){return this._writeNumberValue(Buffer.prototype.writeInt16LE,2,Z,J)}insertInt16LE(Z,J){return this._insertNumberValue(Buffer.prototype.writeInt16LE,2,Z,J)}writeInt32BE(Z,J){return this._writeNumberValue(Buffer.prototype.writeInt32BE,4,Z,J)}insertInt32BE(Z,J){return this._insertNumberValue(Buffer.prototype.writeInt32BE,4,Z,J)}writeInt32LE(Z,J){return this._writeNumberValue(Buffer.prototype.writeInt32LE,4,Z,J)}insertInt32LE(Z,J){return this._insertNumberValue(Buffer.prototype.writeInt32LE,4,Z,J)}writeBigInt64BE(Z,J){return C0.bigIntAndBufferInt64Check("writeBigInt64BE"),this._writeNumberValue(Buffer.prototype.writeBigInt64BE,8,Z,J)}insertBigInt64BE(Z,J){return C0.bigIntAndBufferInt64Check("writeBigInt64BE"),this._insertNumberValue(Buffer.prototype.writeBigInt64BE,8,Z,J)}writeBigInt64LE(Z,J){return C0.bigIntAndBufferInt64Check("writeBigInt64LE"),this._writeNumberValue(Buffer.prototype.writeBigInt64LE,8,Z,J)}insertBigInt64LE(Z,J){return C0.bigIntAndBufferInt64Check("writeBigInt64LE"),this._insertNumberValue(Buffer.prototype.writeBigInt64LE,8,Z,J)}readUInt8(Z){return this._readNumberValue(Buffer.prototype.readUInt8,1,Z)}readUInt16BE(Z){return this._readNumberValue(Buffer.prototype.readUInt16BE,2,Z)}readUInt16LE(Z){return this._readNumberValue(Buffer.prototype.readUInt16LE,2,Z)}readUInt32BE(Z){return this._readNumberValue(Buffer.prototype.readUInt32BE,4,Z)}readUInt32LE(Z){return this._readNumberValue(Buffer.prototype.readUInt32LE,4,Z)}readBigUInt64BE(Z){return C0.bigIntAndBufferInt64Check("readBigUInt64BE"),this._readNumberValue(Buffer.prototype.readBigUInt64BE,8,Z)}readBigUInt64LE(Z){return C0.bigIntAndBufferInt64Check("readBigUInt64LE"),this._readNumberValue(Buffer.prototype.readBigUInt64LE,8,Z)}writeUInt8(Z,J){return this._writeNumberValue(Buffer.prototype.writeUInt8,1,Z,J)}insertUInt8(Z,J){return this._insertNumberValue(Buffer.prototype.writeUInt8,1,Z,J)}writeUInt16BE(Z,J){return this._writeNumberValue(Buffer.prototype.writeUInt16BE,2,Z,J)}insertUInt16BE(Z,J){return this._insertNumberValue(Buffer.prototype.writeUInt16BE,2,Z,J)}writeUInt16LE(Z,J){return this._writeNumberValue(Buffer.prototype.writeUInt16LE,2,Z,J)}insertUInt16LE(Z,J){return this._insertNumberValue(Buffer.prototype.writeUInt16LE,2,Z,J)}writeUInt32BE(Z,J){return this._writeNumberValue(Buffer.prototype.writeUInt32BE,4,Z,J)}insertUInt32BE(Z,J){return this._insertNumberValue(Buffer.prototype.writeUInt32BE,4,Z,J)}writeUInt32LE(Z,J){return this._writeNumberValue(Buffer.prototype.writeUInt32LE,4,Z,J)}insertUInt32LE(Z,J){return this._insertNumberValue(Buffer.prototype.writeUInt32LE,4,Z,J)}writeBigUInt64BE(Z,J){return C0.bigIntAndBufferInt64Check("writeBigUInt64BE"),this._writeNumberValue(Buffer.prototype.writeBigUInt64BE,8,Z,J)}insertBigUInt64BE(Z,J){return C0.bigIntAndBufferInt64Check("writeBigUInt64BE"),this._insertNumberValue(Buffer.prototype.writeBigUInt64BE,8,Z,J)}writeBigUInt64LE(Z,J){return C0.bigIntAndBufferInt64Check("writeBigUInt64LE"),this._writeNumberValue(Buffer.prototype.writeBigUInt64LE,8,Z,J)}insertBigUInt64LE(Z,J){return C0.bigIntAndBufferInt64Check("writeBigUInt64LE"),this._insertNumberValue(Buffer.prototype.writeBigUInt64LE,8,Z,J)}readFloatBE(Z){return this._readNumberValue(Buffer.prototype.readFloatBE,4,Z)}readFloatLE(Z){return this._readNumberValue(Buffer.prototype.readFloatLE,4,Z)}writeFloatBE(Z,J){return this._writeNumberValue(Buffer.prototype.writeFloatBE,4,Z,J)}insertFloatBE(Z,J){return this._insertNumberValue(Buffer.prototype.writeFloatBE,4,Z,J)}writeFloatLE(Z,J){return this._writeNumberValue(Buffer.prototype.writeFloatLE,4,Z,J)}insertFloatLE(Z,J){return this._insertNumberValue(Buffer.prototype.writeFloatLE,4,Z,J)}readDoubleBE(Z){return this._readNumberValue(Buffer.prototype.readDoubleBE,8,Z)}readDoubleLE(Z){return this._readNumberValue(Buffer.prototype.readDoubleLE,8,Z)}writeDoubleBE(Z,J){return this._writeNumberValue(Buffer.prototype.writeDoubleBE,8,Z,J)}insertDoubleBE(Z,J){return this._insertNumberValue(Buffer.prototype.writeDoubleBE,8,Z,J)}writeDoubleLE(Z,J){return this._writeNumberValue(Buffer.prototype.writeDoubleLE,8,Z,J)}insertDoubleLE(Z,J){return this._insertNumberValue(Buffer.prototype.writeDoubleLE,8,Z,J)}readString(Z,J){let X;if(typeof Z==="number")C0.checkLengthValue(Z),X=Math.min(Z,this.length-this._readOffset);else J=Z,X=this.length-this._readOffset;if(typeof J<"u")C0.checkEncoding(J);let $=this._buff.slice(this._readOffset,this._readOffset+X).toString(J||this._encoding);return this._readOffset+=X,$}insertString(Z,J,X){return C0.checkOffsetValue(J),this._handleString(Z,!0,J,X)}writeString(Z,J,X){return this._handleString(Z,!1,J,X)}readStringNT(Z){if(typeof Z<"u")C0.checkEncoding(Z);let J=this.length;for(let $=this._readOffset;$<this.length;$++)if(this._buff[$]===0){J=$;break}let X=this._buff.slice(this._readOffset,J);return this._readOffset=J+1,X.toString(Z||this._encoding)}insertStringNT(Z,J,X){return C0.checkOffsetValue(J),this.insertString(Z,J,X),this.insertUInt8(0,J+Z.length),this}writeStringNT(Z,J,X){return this.writeString(Z,J,X),this.writeUInt8(0,typeof J==="number"?J+Z.length:this.writeOffset),this}readBuffer(Z){if(typeof Z<"u")C0.checkLengthValue(Z);let J=typeof Z==="number"?Z:this.length,X=Math.min(this.length,this._readOffset+J),$=this._buff.slice(this._readOffset,X);return this._readOffset=X,$}insertBuffer(Z,J){return C0.checkOffsetValue(J),this._handleBuffer(Z,!0,J)}writeBuffer(Z,J){return this._handleBuffer(Z,!1,J)}readBufferNT(){let Z=this.length;for(let X=this._readOffset;X<this.length;X++)if(this._buff[X]===0){Z=X;break}let J=this._buff.slice(this._readOffset,Z);return this._readOffset=Z+1,J}insertBufferNT(Z,J){return C0.checkOffsetValue(J),this.insertBuffer(Z,J),this.insertUInt8(0,J+Z.length),this}writeBufferNT(Z,J){if(typeof J<"u")C0.checkOffsetValue(J);return this.writeBuffer(Z,J),this.writeUInt8(0,typeof J==="number"?J+Z.length:this._writeOffset),this}clear(){return this._writeOffset=0,this._readOffset=0,this.length=0,this}remaining(){return this.length-this._readOffset}get readOffset(){return this._readOffset}set readOffset(Z){C0.checkOffsetValue(Z),C0.checkTargetOffset(Z,this),this._readOffset=Z}get writeOffset(){return this._writeOffset}set writeOffset(Z){C0.checkOffsetValue(Z),C0.checkTargetOffset(Z,this),this._writeOffset=Z}get encoding(){return this._encoding}set encoding(Z){C0.checkEncoding(Z),this._encoding=Z}get internalBuffer(){return this._buff}toBuffer(){return this._buff.slice(0,this.length)}toString(Z){let J=typeof Z==="string"?Z:this._encoding;return C0.checkEncoding(J),this._buff.toString(J,0,this.length)}destroy(){return this.clear(),this}_handleString(Z,J,X,$){let Y=this._writeOffset,Q=this._encoding;if(typeof X==="number")Y=X;else if(typeof X==="string")C0.checkEncoding(X),Q=X;if(typeof $==="string")C0.checkEncoding($),Q=$;let W=Buffer.byteLength(Z,Q);if(J)this.ensureInsertable(W,Y);else this._ensureWriteable(W,Y);if(this._buff.write(Z,Y,W,Q),J)this._writeOffset+=W;else if(typeof X==="number")this._writeOffset=Math.max(this._writeOffset,Y+W);else this._writeOffset+=W;return this}_handleBuffer(Z,J,X){let $=typeof X==="number"?X:this._writeOffset;if(J)this.ensureInsertable(Z.length,$);else this._ensureWriteable(Z.length,$);if(Z.copy(this._buff,$),J)this._writeOffset+=Z.length;else if(typeof X==="number")this._writeOffset=Math.max(this._writeOffset,$+Z.length);else this._writeOffset+=Z.length;return this}ensureReadable(Z,J){let X=this._readOffset;if(typeof J<"u")C0.checkOffsetValue(J),X=J;if(X<0||X+Z>this.length)throw Error(C0.ERRORS.INVALID_READ_BEYOND_BOUNDS)}ensureInsertable(Z,J){if(C0.checkOffsetValue(J),this._ensureCapacity(this.length+Z),J<this.length)this._buff.copy(this._buff,J+Z,J,this._buff.length);if(J+Z>this.length)this.length=J+Z;else this.length+=Z}_ensureWriteable(Z,J){let X=typeof J==="number"?J:this._writeOffset;if(this._ensureCapacity(X+Z),X+Z>this.length)this.length=X+Z}_ensureCapacity(Z){let J=this._buff.length;if(Z>J){let X=this._buff,$=J*3/2+1;if($<Z)$=Z;this._buff=Buffer.allocUnsafe($),X.copy(this._buff,0,0,J)}}_readNumberValue(Z,J,X){this.ensureReadable(J,X);let $=Z.call(this._buff,typeof X==="number"?X:this._readOffset);if(typeof X>"u")this._readOffset+=J;return $}_insertNumberValue(Z,J,X,$){return C0.checkOffsetValue($),this.ensureInsertable(J,$),Z.call(this._buff,X,$),this._writeOffset+=J,this}_writeNumberValue(Z,J,X,$){if(typeof $==="number"){if($<0)throw Error(C0.ERRORS.INVALID_WRITE_BEYOND_BOUNDS);C0.checkOffsetValue($)}let Y=typeof $==="number"?$:this._writeOffset;if(this._ensureWriteable(J,Y),Z.call(this._buff,X,Y),typeof $==="number")this._writeOffset=Math.max(this._writeOffset,Y+J);else this._writeOffset+=J;return this}}sX0.SmartBuffer=ww});var jw=L((Q$0)=>{Object.defineProperty(Q$0,"__esModule",{value:!0});Q$0.SOCKS5_NO_ACCEPTABLE_AUTH=Q$0.SOCKS5_CUSTOM_AUTH_END=Q$0.SOCKS5_CUSTOM_AUTH_START=Q$0.SOCKS_INCOMING_PACKET_SIZES=Q$0.SocksClientState=Q$0.Socks5Response=Q$0.Socks5HostType=Q$0.Socks5Auth=Q$0.Socks4Response=Q$0.SocksCommand=Q$0.ERRORS=Q$0.DEFAULT_TIMEOUT=void 0;var d81=30000;Q$0.DEFAULT_TIMEOUT=d81;var u81={InvalidSocksCommand:"An invalid SOCKS command was provided. Valid options are connect, bind, and associate.",InvalidSocksCommandForOperation:"An invalid SOCKS command was provided. Only a subset of commands are supported for this operation.",InvalidSocksCommandChain:"An invalid SOCKS command was provided. Chaining currently only supports the connect command.",InvalidSocksClientOptionsDestination:"An invalid destination host was provided.",InvalidSocksClientOptionsExistingSocket:"An invalid existing socket was provided. This should be an instance of stream.Duplex.",InvalidSocksClientOptionsProxy:"Invalid SOCKS proxy details were provided.",InvalidSocksClientOptionsTimeout:"An invalid timeout value was provided. Please enter a value above 0 (in ms).",InvalidSocksClientOptionsProxiesLength:"At least two socks proxies must be provided for chaining.",InvalidSocksClientOptionsCustomAuthRange:"Custom auth must be a value between 0x80 and 0xFE.",InvalidSocksClientOptionsCustomAuthOptions:"When a custom_auth_method is provided, custom_auth_request_handler, custom_auth_response_size, and custom_auth_response_handler must also be provided and valid.",NegotiationError:"Negotiation error",SocketClosed:"Socket closed",ProxyConnectionTimedOut:"Proxy connection timed out",InternalError:"SocksClient internal error (this should not happen)",InvalidSocks4HandshakeResponse:"Received invalid Socks4 handshake response",Socks4ProxyRejectedConnection:"Socks4 Proxy rejected connection",InvalidSocks4IncomingConnectionResponse:"Socks4 invalid incoming connection response",Socks4ProxyRejectedIncomingBoundConnection:"Socks4 Proxy rejected incoming bound connection",InvalidSocks5InitialHandshakeResponse:"Received invalid Socks5 initial handshake response",InvalidSocks5IntiailHandshakeSocksVersion:"Received invalid Socks5 initial handshake (invalid socks version)",InvalidSocks5InitialHandshakeNoAcceptedAuthType:"Received invalid Socks5 initial handshake (no accepted authentication type)",InvalidSocks5InitialHandshakeUnknownAuthType:"Received invalid Socks5 initial handshake (unknown authentication type)",Socks5AuthenticationFailed:"Socks5 Authentication failed",InvalidSocks5FinalHandshake:"Received invalid Socks5 final handshake response",InvalidSocks5FinalHandshakeRejected:"Socks5 proxy rejected connection",InvalidSocks5IncomingConnectionResponse:"Received invalid Socks5 incoming connection response",Socks5ProxyRejectedIncomingBoundConnection:"Socks5 Proxy rejected incoming bound connection"};Q$0.ERRORS=u81;var c81={Socks5InitialHandshakeResponse:2,Socks5UserPassAuthenticationResponse:2,Socks5ResponseHeader:5,Socks5ResponseIPv4:10,Socks5ResponseIPv6:22,Socks5ResponseHostname:(Z)=>Z+7,Socks4Response:8};Q$0.SOCKS_INCOMING_PACKET_SIZES=c81;var eX0;(function(Z){Z[Z.connect=1]="connect",Z[Z.bind=2]="bind",Z[Z.associate=3]="associate"})(eX0||(Q$0.SocksCommand=eX0={}));var Z$0;(function(Z){Z[Z.Granted=90]="Granted",Z[Z.Failed=91]="Failed",Z[Z.Rejected=92]="Rejected",Z[Z.RejectedIdent=93]="RejectedIdent"})(Z$0||(Q$0.Socks4Response=Z$0={}));var J$0;(function(Z){Z[Z.NoAuth=0]="NoAuth",Z[Z.GSSApi=1]="GSSApi",Z[Z.UserPass=2]="UserPass"})(J$0||(Q$0.Socks5Auth=J$0={}));var l81=128;Q$0.SOCKS5_CUSTOM_AUTH_START=l81;var p81=254;Q$0.SOCKS5_CUSTOM_AUTH_END=p81;var i81=255;Q$0.SOCKS5_NO_ACCEPTABLE_AUTH=i81;var X$0;(function(Z){Z[Z.Granted=0]="Granted",Z[Z.Failure=1]="Failure",Z[Z.NotAllowed=2]="NotAllowed",Z[Z.NetworkUnreachable=3]="NetworkUnreachable",Z[Z.HostUnreachable=4]="HostUnreachable",Z[Z.ConnectionRefused=5]="ConnectionRefused",Z[Z.TTLExpired=6]="TTLExpired",Z[Z.CommandNotSupported=7]="CommandNotSupported",Z[Z.AddressNotSupported=8]="AddressNotSupported"})(X$0||(Q$0.Socks5Response=X$0={}));var $$0;(function(Z){Z[Z.IPv4=1]="IPv4",Z[Z.Hostname=3]="Hostname",Z[Z.IPv6=4]="IPv6"})($$0||(Q$0.Socks5HostType=$$0={}));var Y$0;(function(Z){Z[Z.Created=0]="Created",Z[Z.Connecting=1]="Connecting",Z[Z.Connected=2]="Connected",Z[Z.SentInitialHandshake=3]="SentInitialHandshake",Z[Z.ReceivedInitialHandshakeResponse=4]="ReceivedInitialHandshakeResponse",Z[Z.SentAuthentication=5]="SentAuthentication",Z[Z.ReceivedAuthenticationResponse=6]="ReceivedAuthenticationResponse",Z[Z.SentFinalHandshake=7]="SentFinalHandshake",Z[Z.ReceivedFinalResponse=8]="ReceivedFinalResponse",Z[Z.BoundWaitingForConnection=9]="BoundWaitingForConnection",Z[Z.Established=10]="Established",Z[Z.Disconnected=11]="Disconnected",Z[Z.Error=99]="Error"})(Y$0||(Q$0.SocksClientState=Y$0={}))});var Mw=L((z$0)=>{Object.defineProperty(z$0,"__esModule",{value:!0});z$0.shuffleArray=z$0.SocksClientError=void 0;class K$0 extends Error{constructor(Z,J){super(Z);this.options=J}}z$0.SocksClientError=K$0;function Y51(Z){for(let J=Z.length-1;J>0;J--){let X=Math.floor(Math.random()*(J+1));[Z[J],Z[X]]=[Z[X],Z[J]]}}z$0.shuffleArray=Y51});var KH=L((V$0)=>{Object.defineProperty(V$0,"__esModule",{value:!0});V$0.isInSubnet=W51;V$0.isCorrect=K51;V$0.numberToPaddedHex=H$0;V$0.stringToPaddedHex=z51;V$0.testBit=G51;function W51(Z){if(this.subnetMask<Z.subnetMask)return!1;if(this.mask(Z.subnetMask)===Z.mask())return!0;return!1}function K51(Z){return function(){if(this.addressMinusSuffix!==this.correctForm())return!1;if(this.subnetMask===Z&&!this.parsedSubnet)return!0;return this.parsedSubnet===String(this.subnetMask)}}function H$0(Z){return Z.toString(16).padStart(2,"0")}function z51(Z){return H$0(parseInt(Z,10))}function G51(Z,J){let{length:X}=Z;if(J>X)return!1;let $=X-J;return Z.substring($,$+1)==="1"}});var Aw=L((F$0)=>{Object.defineProperty(F$0,"__esModule",{value:!0});F$0.RE_SUBNET_STRING=F$0.RE_ADDRESS=F$0.GROUPS=F$0.BITS=void 0;F$0.BITS=32;F$0.GROUPS=4;F$0.RE_ADDRESS=/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/g;F$0.RE_SUBNET_STRING=/\/\d{1,2}$/});var zH=L((L$0)=>{Object.defineProperty(L$0,"__esModule",{value:!0});L$0.AddressError=void 0;class U$0 extends Error{constructor(Z,J){super(Z);this.name="AddressError",this.parseMessage=J}}L$0.AddressError=U$0});var Tw=L((E5)=>{var O51=E5&&E5.__createBinding||(Object.create?function(Z,J,X,$){if($===void 0)$=X;var Y=Object.getOwnPropertyDescriptor(J,X);if(!Y||("get"in Y?!J.__esModule:Y.writable||Y.configurable))Y={enumerable:!0,get:function(){return J[X]}};Object.defineProperty(Z,$,Y)}:function(Z,J,X,$){if($===void 0)$=X;Z[$]=J[X]}),w51=E5&&E5.__setModuleDefault||(Object.create?function(Z,J){Object.defineProperty(Z,"default",{enumerable:!0,value:J})}:function(Z,J){Z.default=J}),_$0=E5&&E5.__importStar||function(Z){if(Z&&Z.__esModule)return Z;var J={};if(Z!=null){for(var X in Z)if(X!=="default"&&Object.prototype.hasOwnProperty.call(Z,X))O51(J,Z,X)}return w51(J,Z),J};Object.defineProperty(E5,"__esModule",{value:!0});E5.Address4=void 0;var F$=_$0(KH()),c8=_$0(Aw()),PQ=zH();class R6{constructor(Z){this.groups=c8.GROUPS,this.parsedAddress=[],this.parsedSubnet="",this.subnet="/32",this.subnetMask=32,this.v4=!0,this.isCorrect=F$.isCorrect(c8.BITS),this.isInSubnet=F$.isInSubnet,this.address=Z;let J=c8.RE_SUBNET_STRING.exec(Z);if(J){if(this.parsedSubnet=J[0].replace("/",""),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,this.subnetMask<0||this.subnetMask>c8.BITS)throw new PQ.AddressError("Invalid subnet mask.");Z=Z.replace(c8.RE_SUBNET_STRING,"")}this.addressMinusSuffix=Z,this.parsedAddress=this.parse(Z)}static isValid(Z){try{return new R6(Z),!0}catch(J){return!1}}parse(Z){let J=Z.split(".");if(!Z.match(c8.RE_ADDRESS))throw new PQ.AddressError("Invalid IPv4 address.");return J}correctForm(){return this.parsedAddress.map((Z)=>parseInt(Z,10)).join(".")}static fromHex(Z){let J=Z.replace(/:/g,"").padStart(8,"0"),X=[],$;for($=0;$<8;$+=2){let Y=J.slice($,$+2);X.push(parseInt(Y,16))}return new R6(X.join("."))}static fromInteger(Z){return R6.fromHex(Z.toString(16))}static fromArpa(Z){let X=Z.replace(/(\.in-addr\.arpa)?\.$/,"").split(".").reverse().join(".");return new R6(X)}toHex(){return this.parsedAddress.map((Z)=>F$.stringToPaddedHex(Z)).join(":")}toArray(){return this.parsedAddress.map((Z)=>parseInt(Z,10))}toGroup6(){let Z=[],J;for(J=0;J<c8.GROUPS;J+=2)Z.push(`${F$.stringToPaddedHex(this.parsedAddress[J])}${F$.stringToPaddedHex(this.parsedAddress[J+1])}`);return Z.join(":")}bigInt(){return BigInt(`0x${this.parsedAddress.map((Z)=>F$.stringToPaddedHex(Z)).join("")}`)}_startAddress(){return BigInt(`0b${this.mask()+"0".repeat(c8.BITS-this.subnetMask)}`)}startAddress(){return R6.fromBigInt(this._startAddress())}startAddressExclusive(){let Z=BigInt("1");return R6.fromBigInt(this._startAddress()+Z)}_endAddress(){return BigInt(`0b${this.mask()+"1".repeat(c8.BITS-this.subnetMask)}`)}endAddress(){return R6.fromBigInt(this._endAddress())}endAddressExclusive(){let Z=BigInt("1");return R6.fromBigInt(this._endAddress()-Z)}static fromBigInt(Z){return R6.fromHex(Z.toString(16))}static fromByteArray(Z){if(Z.length!==4)throw new PQ.AddressError("IPv4 addresses require exactly 4 bytes");for(let J=0;J<Z.length;J++)if(!Number.isInteger(Z[J])||Z[J]<0||Z[J]>255)throw new PQ.AddressError("All bytes must be integers between 0 and 255");return this.fromUnsignedByteArray(Z)}static fromUnsignedByteArray(Z){if(Z.length!==4)throw new PQ.AddressError("IPv4 addresses require exactly 4 bytes");let J=Z.join(".");return new R6(J)}mask(Z){if(Z===void 0)Z=this.subnetMask;return this.getBitsBase2(0,Z)}getBitsBase2(Z,J){return this.binaryZeroPad().slice(Z,J)}reverseForm(Z){if(!Z)Z={};let J=this.correctForm().split(".").reverse().join(".");if(Z.omitSuffix)return J;return`${J}.in-addr.arpa.`}isMulticast(){return this.isInSubnet(new R6("224.0.0.0/4"))}binaryZeroPad(){return this.bigInt().toString(2).padStart(c8.BITS,"0")}groupForV6(){let Z=this.parsedAddress;return this.address.replace(c8.RE_ADDRESS,`<span class="hover-group group-v4 group-6">${Z.slice(0,2).join(".")}</span>.<span class="hover-group group-v4 group-7">${Z.slice(2,4).join(".")}</span>`)}}E5.Address4=R6});var qw=L((O$0)=>{Object.defineProperty(O$0,"__esModule",{value:!0});O$0.RE_URL_WITH_PORT=O$0.RE_URL=O$0.RE_ZONE_STRING=O$0.RE_SUBNET_STRING=O$0.RE_BAD_ADDRESS=O$0.RE_BAD_CHARACTERS=O$0.TYPES=O$0.SCOPES=O$0.GROUPS=O$0.BITS=void 0;O$0.BITS=128;O$0.GROUPS=8;O$0.SCOPES={0:"Reserved",1:"Interface local",2:"Link local",4:"Admin local",5:"Site local",8:"Organization local",14:"Global",15:"Reserved"};O$0.TYPES={"ff01::1/128":"Multicast (All nodes on this interface)","ff01::2/128":"Multicast (All routers on this interface)","ff02::1/128":"Multicast (All nodes on this link)","ff02::2/128":"Multicast (All routers on this link)","ff05::2/128":"Multicast (All routers in this site)","ff02::5/128":"Multicast (OSPFv3 AllSPF routers)","ff02::6/128":"Multicast (OSPFv3 AllDR routers)","ff02::9/128":"Multicast (RIP routers)","ff02::a/128":"Multicast (EIGRP routers)","ff02::d/128":"Multicast (PIM routers)","ff02::16/128":"Multicast (MLDv2 reports)","ff01::fb/128":"Multicast (mDNSv6)","ff02::fb/128":"Multicast (mDNSv6)","ff05::fb/128":"Multicast (mDNSv6)","ff02::1:2/128":"Multicast (All DHCP servers and relay agents on this link)","ff05::1:2/128":"Multicast (All DHCP servers and relay agents in this site)","ff02::1:3/128":"Multicast (All DHCP servers on this link)","ff05::1:3/128":"Multicast (All DHCP servers in this site)","::/128":"Unspecified","::1/128":"Loopback","ff00::/8":"Multicast","fe80::/10":"Link-local unicast"};O$0.RE_BAD_CHARACTERS=/([^0-9a-f:/%])/gi;O$0.RE_BAD_ADDRESS=/([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi;O$0.RE_SUBNET_STRING=/\/\d{1,3}(?=%|$)/;O$0.RE_ZONE_STRING=/%.*$/;O$0.RE_URL=/^\[{0,1}([0-9a-f:]+)\]{0,1}/;O$0.RE_URL_WITH_PORT=/\[([0-9a-f:]+)\]:([0-9]{1,5})/});var Cw=L((A$0)=>{Object.defineProperty(A$0,"__esModule",{value:!0});A$0.spanAllZeroes=j$0;A$0.spanAll=E51;A$0.spanLeadingZeroes=I51;A$0.simpleGroup=y51;function j$0(Z){return Z.replace(/(0+)/g,'<span class="zero">$1</span>')}function E51(Z,J=0){return Z.split("").map(($,Y)=>`<span class="digit value-${$} position-${Y+J}">${j$0($)}</span>`).join("")}function M$0(Z){return Z.replace(/^(0+)/,'<span class="zero">$1</span>')}function I51(Z){return Z.split(":").map((X)=>M$0(X)).join(":")}function y51(Z,J=0){return Z.split(":").map(($,Y)=>{if(/group-v4/.test($))return $;return`<span class="hover-group group-${Y+J}">${M$0($)}</span>`})}});var T$0=L((H6)=>{var h51=H6&&H6.__createBinding||(Object.create?function(Z,J,X,$){if($===void 0)$=X;var Y=Object.getOwnPropertyDescriptor(J,X);if(!Y||("get"in Y?!J.__esModule:Y.writable||Y.configurable))Y={enumerable:!0,get:function(){return J[X]}};Object.defineProperty(Z,$,Y)}:function(Z,J,X,$){if($===void 0)$=X;Z[$]=J[X]}),f51=H6&&H6.__setModuleDefault||(Object.create?function(Z,J){Object.defineProperty(Z,"default",{enumerable:!0,value:J})}:function(Z,J){Z.default=J}),b51=H6&&H6.__importStar||function(Z){if(Z&&Z.__esModule)return Z;var J={};if(Z!=null){for(var X in Z)if(X!=="default"&&Object.prototype.hasOwnProperty.call(Z,X))h51(J,Z,X)}return f51(J,Z),J};Object.defineProperty(H6,"__esModule",{value:!0});H6.ADDRESS_BOUNDARY=void 0;H6.groupPossibilities=HH;H6.padGroup=GH;H6.simpleRegularExpression=m51;H6.possibleElisions=d51;var g51=b51(qw());function HH(Z){return`(${Z.join("|")})`}function GH(Z){if(Z.length<4)return`0{0,${4-Z.length}}${Z}`;return Z}H6.ADDRESS_BOUNDARY="[^A-Fa-f0-9:]";function m51(Z){let J=[];Z.forEach(($,Y)=>{if(parseInt($,16)===0)J.push(Y)});let X=J.map(($)=>Z.map((Y,Q)=>{if(Q===$){let W=Q===0||Q===g51.GROUPS-1?":":"";return HH([GH(Y),W])}return GH(Y)}).join(":"));return X.push(Z.map(GH).join(":")),HH(X)}function d51(Z,J,X){let $=J?"":":",Y=X?"":":",Q=[];if(!J&&!X)Q.push("::");if(J&&X)Q.push("");if(X&&!J||!X&&J)Q.push(":");Q.push(`${$}(:0{1,4}){1,${Z-1}}`),Q.push(`(0{1,4}:){1,${Z-1}}${Y}`),Q.push(`(0{1,4}:){${Z-1}}0{1,4}`);for(let W=1;W<Z-1;W++)for(let K=1;K<Z-W;K++)Q.push(`(0{1,4}:){${K}}:(0{1,4}:){${Z-K-W-1}}0{1,4}`);return HH(Q)}});var R$0=L((I5)=>{var u51=I5&&I5.__createBinding||(Object.create?function(Z,J,X,$){if($===void 0)$=X;var Y=Object.getOwnPropertyDescriptor(J,X);if(!Y||("get"in Y?!J.__esModule:Y.writable||Y.configurable))Y={enumerable:!0,get:function(){return J[X]}};Object.defineProperty(Z,$,Y)}:function(Z,J,X,$){if($===void 0)$=X;Z[$]=J[X]}),c51=I5&&I5.__setModuleDefault||(Object.create?function(Z,J){Object.defineProperty(Z,"default",{enumerable:!0,value:J})}:function(Z,J){Z.default=J}),BH=I5&&I5.__importStar||function(Z){if(Z&&Z.__esModule)return Z;var J={};if(Z!=null){for(var X in Z)if(X!=="default"&&Object.prototype.hasOwnProperty.call(Z,X))u51(J,Z,X)}return c51(J,Z),J};Object.defineProperty(I5,"__esModule",{value:!0});I5.Address6=void 0;var q$0=BH(KH()),Nw=BH(Aw()),Z1=BH(qw()),Rw=BH(Cw()),zJ=Tw(),GJ=T$0(),q9=zH(),VH=KH();function FH(Z){if(!Z)throw Error("Assertion failed.")}function l51(Z){let J=/(\d+)(\d{3})/;while(J.test(Z))Z=Z.replace(J,"$1,$2");return Z}function p51(Z){return Z=Z.replace(/^(0{1,})([1-9]+)$/,'<span class="parse-error">$1</span>$2'),Z=Z.replace(/^(0{1,})(0)$/,'<span class="parse-error">$1</span>$2'),Z}function i51(Z,J){let X=[],$=[],Y;for(Y=0;Y<Z.length;Y++)if(Y<J[0])X.push(Z[Y]);else if(Y>J[1])$.push(Z[Y]);return X.concat(["compact"]).concat($)}function C$0(Z){return parseInt(Z,16).toString(16).padStart(4,"0")}function N$0(Z){return Z&255}class X4{constructor(Z,J){if(this.addressMinusSuffix="",this.parsedSubnet="",this.subnet="/128",this.subnetMask=128,this.v4=!1,this.zone="",this.isInSubnet=q$0.isInSubnet,this.isCorrect=q$0.isCorrect(Z1.BITS),J===void 0)this.groups=Z1.GROUPS;else this.groups=J;this.address=Z;let X=Z1.RE_SUBNET_STRING.exec(Z);if(X){if(this.parsedSubnet=X[0].replace("/",""),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,Number.isNaN(this.subnetMask)||this.subnetMask<0||this.subnetMask>Z1.BITS)throw new q9.AddressError("Invalid subnet mask.");Z=Z.replace(Z1.RE_SUBNET_STRING,"")}else if(/\//.test(Z))throw new q9.AddressError("Invalid subnet mask.");let $=Z1.RE_ZONE_STRING.exec(Z);if($)this.zone=$[0],Z=Z.replace(Z1.RE_ZONE_STRING,"");this.addressMinusSuffix=Z,this.parsedAddress=this.parse(this.addressMinusSuffix)}static isValid(Z){try{return new X4(Z),!0}catch(J){return!1}}static fromBigInt(Z){let J=Z.toString(16).padStart(32,"0"),X=[],$;for($=0;$<Z1.GROUPS;$++)X.push(J.slice($*4,($+1)*4));return new X4(X.join(":"))}static fromURL(Z){let J,X=null,$;if(Z.indexOf("[")!==-1&&Z.indexOf("]:")!==-1){if($=Z1.RE_URL_WITH_PORT.exec(Z),$===null)return{error:"failed to parse address with port",address:null,port:null};J=$[1],X=$[2]}else if(Z.indexOf("/")!==-1){if(Z=Z.replace(/^[a-z0-9]+:\/\//,""),$=Z1.RE_URL.exec(Z),$===null)return{error:"failed to parse address from URL",address:null,port:null};J=$[1]}else J=Z;if(X){if(X=parseInt(X,10),X<0||X>65536)X=null}else X=null;return{address:new X4(J),port:X}}static fromAddress4(Z){let J=new zJ.Address4(Z),X=Z1.BITS-(Nw.BITS-J.subnetMask);return new X4(`::ffff:${J.correctForm()}/${X}`)}static fromArpa(Z){let J=Z.replace(/(\.ip6\.arpa)?\.$/,""),X=7;if(J.length!==63)throw new q9.AddressError("Invalid 'ip6.arpa' form.");let $=J.split(".").reverse();for(let Y=X;Y>0;Y--){let Q=Y*4;$.splice(Q,0,":")}return J=$.join(""),new X4(J)}microsoftTranscription(){return`${this.correctForm().replace(/:/g,"-")}.ipv6-literal.net`}mask(Z=this.subnetMask){return this.getBitsBase2(0,Z)}possibleSubnets(Z=128){let J=Z1.BITS-this.subnetMask,X=Math.abs(Z-Z1.BITS),$=J-X;if($<0)return"0";return l51((BigInt("2")**BigInt($)).toString(10))}_startAddress(){return BigInt(`0b${this.mask()+"0".repeat(Z1.BITS-this.subnetMask)}`)}startAddress(){return X4.fromBigInt(this._startAddress())}startAddressExclusive(){let Z=BigInt("1");return X4.fromBigInt(this._startAddress()+Z)}_endAddress(){return BigInt(`0b${this.mask()+"1".repeat(Z1.BITS-this.subnetMask)}`)}endAddress(){return X4.fromBigInt(this._endAddress())}endAddressExclusive(){let Z=BigInt("1");return X4.fromBigInt(this._endAddress()-Z)}getScope(){let Z=Z1.SCOPES[parseInt(this.getBits(12,16).toString(10),10)];if(this.getType()==="Global unicast"&&Z!=="Link local")Z="Global";return Z||"Unknown"}getType(){for(let Z of Object.keys(Z1.TYPES))if(this.isInSubnet(new X4(Z)))return Z1.TYPES[Z];return"Global unicast"}getBits(Z,J){return BigInt(`0b${this.getBitsBase2(Z,J)}`)}getBitsBase2(Z,J){return this.binaryZeroPad().slice(Z,J)}getBitsBase16(Z,J){let X=J-Z;if(X%4!==0)throw Error("Length of bits to retrieve must be divisible by four");return this.getBits(Z,J).toString(16).padStart(X/4,"0")}getBitsPastSubnet(){return this.getBitsBase2(this.subnetMask,Z1.BITS)}reverseForm(Z){if(!Z)Z={};let J=Math.floor(this.subnetMask/4),X=this.canonicalForm().replace(/:/g,"").split("").slice(0,J).reverse().join(".");if(J>0){if(Z.omitSuffix)return X;return`${X}.ip6.arpa.`}if(Z.omitSuffix)return"";return"ip6.arpa."}correctForm(){let Z,J=[],X=0,$=[];for(Z=0;Z<this.parsedAddress.length;Z++){let W=parseInt(this.parsedAddress[Z],16);if(W===0)X++;if(W!==0&&X>0){if(X>1)$.push([Z-X,Z-1]);X=0}}if(X>1)$.push([this.parsedAddress.length-X,this.parsedAddress.length-1]);let Y=$.map((W)=>W[1]-W[0]+1);if($.length>0){let W=Y.indexOf(Math.max(...Y));J=i51(this.parsedAddress,$[W])}else J=this.parsedAddress;for(Z=0;Z<J.length;Z++)if(J[Z]!=="compact")J[Z]=parseInt(J[Z],16).toString(16);let Q=J.join(":");return Q=Q.replace(/^compact$/,"::"),Q=Q.replace(/(^compact)|(compact$)/,":"),Q=Q.replace(/compact/,""),Q}binaryZeroPad(){return this.bigInt().toString(2).padStart(Z1.BITS,"0")}parse4in6(Z){let J=Z.split(":"),$=J.slice(-1)[0].match(Nw.RE_ADDRESS);if($){this.parsedAddress4=$[0],this.address4=new zJ.Address4(this.parsedAddress4);for(let Y=0;Y<this.address4.groups;Y++)if(/^0[0-9]+/.test(this.address4.parsedAddress[Y]))throw new q9.AddressError("IPv4 addresses can't have leading zeroes.",Z.replace(Nw.RE_ADDRESS,this.address4.parsedAddress.map(p51).join(".")));this.v4=!0,J[J.length-1]=this.address4.toGroup6(),Z=J.join(":")}return Z}parse(Z){Z=this.parse4in6(Z);let J=Z.match(Z1.RE_BAD_CHARACTERS);if(J)throw new q9.AddressError(`Bad character${J.length>1?"s":""} detected in address: ${J.join("")}`,Z.replace(Z1.RE_BAD_CHARACTERS,'<span class="parse-error">$1</span>'));let X=Z.match(Z1.RE_BAD_ADDRESS);if(X)throw new q9.AddressError(`Address failed regex: ${X.join("")}`,Z.replace(Z1.RE_BAD_ADDRESS,'<span class="parse-error">$1</span>'));let $=[],Y=Z.split("::");if(Y.length===2){let Q=Y[0].split(":"),W=Y[1].split(":");if(Q.length===1&&Q[0]==="")Q=[];if(W.length===1&&W[0]==="")W=[];let K=this.groups-(Q.length+W.length);if(!K)throw new q9.AddressError("Error parsing groups");this.elidedGroups=K,this.elisionBegin=Q.length,this.elisionEnd=Q.length+this.elidedGroups,$=$.concat(Q);for(let z=0;z<K;z++)$.push("0");$=$.concat(W)}else if(Y.length===1)$=Z.split(":"),this.elidedGroups=0;else throw new q9.AddressError("Too many :: groups found");if($=$.map((Q)=>parseInt(Q,16).toString(16)),$.length!==this.groups)throw new q9.AddressError("Incorrect number of groups found");return $}canonicalForm(){return this.parsedAddress.map(C$0).join(":")}decimal(){return this.parsedAddress.map((Z)=>parseInt(Z,16).toString(10).padStart(5,"0")).join(":")}bigInt(){return BigInt(`0x${this.parsedAddress.map(C$0).join("")}`)}to4(){let Z=this.binaryZeroPad().split("");return zJ.Address4.fromHex(BigInt(`0b${Z.slice(96,128).join("")}`).toString(16))}to4in6(){let Z=this.to4(),X=new X4(this.parsedAddress.slice(0,6).join(":"),6).correctForm(),$="";if(!/:$/.test(X))$=":";return X+$+Z.address}inspectTeredo(){let Z=this.getBitsBase16(0,32),X=(this.getBits(80,96)^BigInt("0xffff")).toString(),$=zJ.Address4.fromHex(this.getBitsBase16(32,64)),Y=this.getBits(96,128),Q=zJ.Address4.fromHex((Y^BigInt("0xffffffff")).toString(16)),W=this.getBitsBase2(64,80),K=(0,VH.testBit)(W,15),z=(0,VH.testBit)(W,14),G=(0,VH.testBit)(W,8),H=(0,VH.testBit)(W,9),V=BigInt(`0b${W.slice(2,6)+W.slice(8,16)}`).toString(10);return{prefix:`${Z.slice(0,4)}:${Z.slice(4,8)}`,server4:$.address,client4:Q.address,flags:W,coneNat:K,microsoft:{reserved:z,universalLocal:H,groupIndividual:G,nonce:V},udpPort:X}}inspect6to4(){let Z=this.getBitsBase16(0,16),J=zJ.Address4.fromHex(this.getBitsBase16(16,48));return{prefix:Z.slice(0,4),gateway:J.address}}to6to4(){if(!this.is4())return null;let Z=["2002",this.getBitsBase16(96,112),this.getBitsBase16(112,128),"","/16"].join(":");return new X4(Z)}toByteArray(){let Z=this.bigInt().toString(16),X=`${"0".repeat(Z.length%2)}${Z}`,$=[];for(let Y=0,Q=X.length;Y<Q;Y+=2)$.push(parseInt(X.substring(Y,Y+2),16));return $}toUnsignedByteArray(){return this.toByteArray().map(N$0)}static fromByteArray(Z){return this.fromUnsignedByteArray(Z.map(N$0))}static fromUnsignedByteArray(Z){let J=BigInt("256"),X=BigInt("0"),$=BigInt("1");for(let Y=Z.length-1;Y>=0;Y--)X+=$*BigInt(Z[Y].toString(10)),$*=J;return X4.fromBigInt(X)}isCanonical(){return this.addressMinusSuffix===this.canonicalForm()}isLinkLocal(){if(this.getBitsBase2(0,64)==="1111111010000000000000000000000000000000000000000000000000000000")return!0;return!1}isMulticast(){return this.getType()==="Multicast"}is4(){return this.v4}isTeredo(){return this.isInSubnet(new X4("2001::/32"))}is6to4(){return this.isInSubnet(new X4("2002::/16"))}isLoopback(){return this.getType()==="Loopback"}href(Z){if(Z===void 0)Z="";else Z=`:${Z}`;return`http://[${this.correctForm()}]${Z}/`}link(Z){if(!Z)Z={};if(Z.className===void 0)Z.className="";if(Z.prefix===void 0)Z.prefix="/#address=";if(Z.v4===void 0)Z.v4=!1;let J=this.correctForm;if(Z.v4)J=this.to4in6;let X=J.call(this);if(Z.className)return`<a href="${Z.prefix}${X}" class="${Z.className}">${X}</a>`;return`<a href="${Z.prefix}${X}">${X}</a>`}group(){if(this.elidedGroups===0)return Rw.simpleGroup(this.address).join(":");FH(typeof this.elidedGroups==="number"),FH(typeof this.elisionBegin==="number");let Z=[],[J,X]=this.address.split("::");if(J.length)Z.push(...Rw.simpleGroup(J));else Z.push("");let $=["hover-group"];for(let Y=this.elisionBegin;Y<this.elisionBegin+this.elidedGroups;Y++)$.push(`group-${Y}`);if(Z.push(`<span class="${$.join(" ")}"></span>`),X.length)Z.push(...Rw.simpleGroup(X,this.elisionEnd));else Z.push("");if(this.is4())FH(this.address4 instanceof zJ.Address4),Z.pop(),Z.push(this.address4.groupForV6());return Z.join(":")}regularExpressionString(Z=!1){let J=[],X=new X4(this.correctForm());if(X.elidedGroups===0)J.push((0,GJ.simpleRegularExpression)(X.parsedAddress));else if(X.elidedGroups===Z1.GROUPS)J.push((0,GJ.possibleElisions)(Z1.GROUPS));else{let $=X.address.split("::");if($[0].length)J.push((0,GJ.simpleRegularExpression)($[0].split(":")));if(FH(typeof X.elidedGroups==="number"),J.push((0,GJ.possibleElisions)(X.elidedGroups,$[0].length!==0,$[1].length!==0)),$[1].length)J.push((0,GJ.simpleRegularExpression)($[1].split(":")));J=[J.join(":")]}if(!Z)J=["(?=^|",GJ.ADDRESS_BOUNDARY,"|[^\\w\\:])(",...J,")(?=[^\\w\\:]|",GJ.ADDRESS_BOUNDARY,"|$)"];return J.join("")}regularExpression(Z=!1){return new RegExp(this.regularExpressionString(Z),"i")}}I5.Address6=X4});var Pw=L((N4)=>{var n51=N4&&N4.__createBinding||(Object.create?function(Z,J,X,$){if($===void 0)$=X;var Y=Object.getOwnPropertyDescriptor(J,X);if(!Y||("get"in Y?!J.__esModule:Y.writable||Y.configurable))Y={enumerable:!0,get:function(){return J[X]}};Object.defineProperty(Z,$,Y)}:function(Z,J,X,$){if($===void 0)$=X;Z[$]=J[X]}),o51=N4&&N4.__setModuleDefault||(Object.create?function(Z,J){Object.defineProperty(Z,"default",{enumerable:!0,value:J})}:function(Z,J){Z.default=J}),a51=N4&&N4.__importStar||function(Z){if(Z&&Z.__esModule)return Z;var J={};if(Z!=null){for(var X in Z)if(X!=="default"&&Object.prototype.hasOwnProperty.call(Z,X))n51(J,Z,X)}return o51(J,Z),J};Object.defineProperty(N4,"__esModule",{value:!0});N4.v6=N4.AddressError=N4.Address6=N4.Address4=void 0;var r51=Tw();Object.defineProperty(N4,"Address4",{enumerable:!0,get:function(){return r51.Address4}});var s51=R$0();Object.defineProperty(N4,"Address6",{enumerable:!0,get:function(){return s51.Address6}});var t51=zH();Object.defineProperty(N4,"AddressError",{enumerable:!0,get:function(){return t51.AddressError}});var e51=a51(Cw());N4.v6={helpers:e51}});var v$0=L((k$0)=>{Object.defineProperty(k$0,"__esModule",{value:!0});k$0.ipToBuffer=k$0.int32ToIpv4=k$0.ipv4ToInt32=k$0.validateSocksClientChainOptions=k$0.validateSocksClientOptions=void 0;var d4=Mw(),$4=jw(),Z91=N("stream"),Ew=Pw(),P$0=N("net");function J91(Z,J=["connect","bind","associate"]){if(!$4.SocksCommand[Z.command])throw new d4.SocksClientError($4.ERRORS.InvalidSocksCommand,Z);if(J.indexOf(Z.command)===-1)throw new d4.SocksClientError($4.ERRORS.InvalidSocksCommandForOperation,Z);if(!I$0(Z.destination))throw new d4.SocksClientError($4.ERRORS.InvalidSocksClientOptionsDestination,Z);if(!y$0(Z.proxy))throw new d4.SocksClientError($4.ERRORS.InvalidSocksClientOptionsProxy,Z);if(E$0(Z.proxy,Z),Z.timeout&&!S$0(Z.timeout))throw new d4.SocksClientError($4.ERRORS.InvalidSocksClientOptionsTimeout,Z);if(Z.existing_socket&&!(Z.existing_socket instanceof Z91.Duplex))throw new d4.SocksClientError($4.ERRORS.InvalidSocksClientOptionsExistingSocket,Z)}k$0.validateSocksClientOptions=J91;function X91(Z){if(Z.command!=="connect")throw new d4.SocksClientError($4.ERRORS.InvalidSocksCommandChain,Z);if(!I$0(Z.destination))throw new d4.SocksClientError($4.ERRORS.InvalidSocksClientOptionsDestination,Z);if(!(Z.proxies&&Array.isArray(Z.proxies)&&Z.proxies.length>=2))throw new d4.SocksClientError($4.ERRORS.InvalidSocksClientOptionsProxiesLength,Z);if(Z.proxies.forEach((J)=>{if(!y$0(J))throw new d4.SocksClientError($4.ERRORS.InvalidSocksClientOptionsProxy,Z);E$0(J,Z)}),Z.timeout&&!S$0(Z.timeout))throw new d4.SocksClientError($4.ERRORS.InvalidSocksClientOptionsTimeout,Z)}k$0.validateSocksClientChainOptions=X91;function E$0(Z,J){if(Z.custom_auth_method!==void 0){if(Z.custom_auth_method<$4.SOCKS5_CUSTOM_AUTH_START||Z.custom_auth_method>$4.SOCKS5_CUSTOM_AUTH_END)throw new d4.SocksClientError($4.ERRORS.InvalidSocksClientOptionsCustomAuthRange,J);if(Z.custom_auth_request_handler===void 0||typeof Z.custom_auth_request_handler!=="function")throw new d4.SocksClientError($4.ERRORS.InvalidSocksClientOptionsCustomAuthOptions,J);if(Z.custom_auth_response_size===void 0)throw new d4.SocksClientError($4.ERRORS.InvalidSocksClientOptionsCustomAuthOptions,J);if(Z.custom_auth_response_handler===void 0||typeof Z.custom_auth_response_handler!=="function")throw new d4.SocksClientError($4.ERRORS.InvalidSocksClientOptionsCustomAuthOptions,J)}}function I$0(Z){return Z&&typeof Z.host==="string"&&Buffer.byteLength(Z.host)<256&&typeof Z.port==="number"&&Z.port>=0&&Z.port<=65535}function y$0(Z){return Z&&(typeof Z.host==="string"||typeof Z.ipaddress==="string")&&typeof Z.port==="number"&&Z.port>=0&&Z.port<=65535&&(Z.type===4||Z.type===5)}function S$0(Z){return typeof Z==="number"&&Z>0}function $91(Z){return new Ew.Address4(Z).toArray().reduce((X,$)=>(X<<8)+$,0)>>>0}k$0.ipv4ToInt32=$91;function Y91(Z){let J=Z>>>24&255,X=Z>>>16&255,$=Z>>>8&255,Y=Z&255;return[J,X,$,Y].join(".")}k$0.int32ToIpv4=Y91;function Q91(Z){if(P$0.isIPv4(Z)){let J=new Ew.Address4(Z);return Buffer.from(J.toArray())}else if(P$0.isIPv6(Z)){let J=new Ew.Address6(Z);return Buffer.from(J.canonicalForm().split(":").map((X)=>X.padStart(4,"0")).join(""),"hex")}else throw Error("Invalid IP address format")}k$0.ipToBuffer=Q91});var g$0=L((f$0)=>{Object.defineProperty(f$0,"__esModule",{value:!0});f$0.ReceiveBuffer=void 0;class h$0{constructor(Z=4096){this.buffer=Buffer.allocUnsafe(Z),this.offset=0,this.originalSize=Z}get length(){return this.offset}append(Z){if(!Buffer.isBuffer(Z))throw Error("Attempted to append a non-buffer instance to ReceiveBuffer.");if(this.offset+Z.length>=this.buffer.length){let J=this.buffer;this.buffer=Buffer.allocUnsafe(Math.max(this.buffer.length+this.originalSize,this.buffer.length+Z.length)),J.copy(this.buffer)}return Z.copy(this.buffer,this.offset),this.offset+=Z.length}peek(Z){if(Z>this.offset)throw Error("Attempted to read beyond the bounds of the managed internal data.");return this.buffer.slice(0,Z)}get(Z){if(Z>this.offset)throw Error("Attempted to read beyond the bounds of the managed internal data.");let J=Buffer.allocUnsafe(Z);return this.buffer.slice(0,Z).copy(J),this.buffer.copyWithin(0,Z,Z+this.offset-Z),this.offset-=Z,J}}f$0.ReceiveBuffer=h$0});var m$0=L((h7)=>{var B$=h7&&h7.__awaiter||function(Z,J,X,$){function Y(Q){return Q instanceof X?Q:new X(function(W){W(Q)})}return new(X||(X=Promise))(function(Q,W){function K(H){try{G($.next(H))}catch(V){W(V)}}function z(H){try{G($.throw(H))}catch(V){W(V)}}function G(H){H.done?Q(H.value):Y(H.value).then(K,z)}G(($=$.apply(Z,J||[])).next())})};Object.defineProperty(h7,"__esModule",{value:!0});h7.SocksClientError=h7.SocksClient=void 0;var H91=N("events"),U$=N("net"),V6=tX0(),v=jw(),P6=v$0(),V91=g$0(),yw=Mw();Object.defineProperty(h7,"SocksClientError",{enumerable:!0,get:function(){return yw.SocksClientError}});var Iw=Pw();class UH extends H91.EventEmitter{constructor(Z){super();this.options=Object.assign({},Z),(0,P6.validateSocksClientOptions)(Z),this.setState(v.SocksClientState.Created)}static createConnection(Z,J){return new Promise((X,$)=>{try{(0,P6.validateSocksClientOptions)(Z,["connect"])}catch(Q){if(typeof J==="function")return J(Q),X(Q);else return $(Q)}let Y=new UH(Z);Y.connect(Z.existing_socket),Y.once("established",(Q)=>{if(Y.removeAllListeners(),typeof J==="function")J(null,Q),X(Q);else X(Q)}),Y.once("error",(Q)=>{if(Y.removeAllListeners(),typeof J==="function")J(Q),X(Q);else $(Q)})})}static createConnectionChain(Z,J){return new Promise((X,$)=>B$(this,void 0,void 0,function*(){try{(0,P6.validateSocksClientChainOptions)(Z)}catch(Y){if(typeof J==="function")return J(Y),X(Y);else return $(Y)}if(Z.randomizeChain)(0,yw.shuffleArray)(Z.proxies);try{let Y;for(let Q=0;Q<Z.proxies.length;Q++){let W=Z.proxies[Q],K=Q===Z.proxies.length-1?Z.destination:{host:Z.proxies[Q+1].host||Z.proxies[Q+1].ipaddress,port:Z.proxies[Q+1].port},z=yield UH.createConnection({command:"connect",proxy:W,destination:K,existing_socket:Y});Y=Y||z.socket}if(typeof J==="function")J(null,{socket:Y}),X({socket:Y});else X({socket:Y})}catch(Y){if(typeof J==="function")J(Y),X(Y);else $(Y)}}))}static createUDPFrame(Z){let J=new V6.SmartBuffer;if(J.writeUInt16BE(0),J.writeUInt8(Z.frameNumber||0),U$.isIPv4(Z.remoteHost.host))J.writeUInt8(v.Socks5HostType.IPv4),J.writeUInt32BE((0,P6.ipv4ToInt32)(Z.remoteHost.host));else if(U$.isIPv6(Z.remoteHost.host))J.writeUInt8(v.Socks5HostType.IPv6),J.writeBuffer((0,P6.ipToBuffer)(Z.remoteHost.host));else J.writeUInt8(v.Socks5HostType.Hostname),J.writeUInt8(Buffer.byteLength(Z.remoteHost.host)),J.writeString(Z.remoteHost.host);return J.writeUInt16BE(Z.remoteHost.port),J.writeBuffer(Z.data),J.toBuffer()}static parseUDPFrame(Z){let J=V6.SmartBuffer.fromBuffer(Z);J.readOffset=2;let X=J.readUInt8(),$=J.readUInt8(),Y;if($===v.Socks5HostType.IPv4)Y=(0,P6.int32ToIpv4)(J.readUInt32BE());else if($===v.Socks5HostType.IPv6)Y=Iw.Address6.fromByteArray(Array.from(J.readBuffer(16))).canonicalForm();else Y=J.readString(J.readUInt8());let Q=J.readUInt16BE();return{frameNumber:X,remoteHost:{host:Y,port:Q},data:J.readBuffer()}}setState(Z){if(this.state!==v.SocksClientState.Error)this.state=Z}connect(Z){this.onDataReceived=(X)=>this.onDataReceivedHandler(X),this.onClose=()=>this.onCloseHandler(),this.onError=(X)=>this.onErrorHandler(X),this.onConnect=()=>this.onConnectHandler();let J=setTimeout(()=>this.onEstablishedTimeout(),this.options.timeout||v.DEFAULT_TIMEOUT);if(J.unref&&typeof J.unref==="function")J.unref();if(Z)this.socket=Z;else this.socket=new U$.Socket;if(this.socket.once("close",this.onClose),this.socket.once("error",this.onError),this.socket.once("connect",this.onConnect),this.socket.on("data",this.onDataReceived),this.setState(v.SocksClientState.Connecting),this.receiveBuffer=new V91.ReceiveBuffer,Z)this.socket.emit("connect");else if(this.socket.connect(this.getSocketOptions()),this.options.set_tcp_nodelay!==void 0&&this.options.set_tcp_nodelay!==null)this.socket.setNoDelay(!!this.options.set_tcp_nodelay);this.prependOnceListener("established",(X)=>{setImmediate(()=>{if(this.receiveBuffer.length>0){let $=this.receiveBuffer.get(this.receiveBuffer.length);X.socket.emit("data",$)}X.socket.resume()})})}getSocketOptions(){return Object.assign(Object.assign({},this.options.socket_options),{host:this.options.proxy.host||this.options.proxy.ipaddress,port:this.options.proxy.port})}onEstablishedTimeout(){if(this.state!==v.SocksClientState.Established&&this.state!==v.SocksClientState.BoundWaitingForConnection)this.closeSocket(v.ERRORS.ProxyConnectionTimedOut)}onConnectHandler(){if(this.setState(v.SocksClientState.Connected),this.options.proxy.type===4)this.sendSocks4InitialHandshake();else this.sendSocks5InitialHandshake();this.setState(v.SocksClientState.SentInitialHandshake)}onDataReceivedHandler(Z){this.receiveBuffer.append(Z),this.processData()}processData(){while(this.state!==v.SocksClientState.Established&&this.state!==v.SocksClientState.Error&&this.receiveBuffer.length>=this.nextRequiredPacketBufferSize)if(this.state===v.SocksClientState.SentInitialHandshake)if(this.options.proxy.type===4)this.handleSocks4FinalHandshakeResponse();else this.handleInitialSocks5HandshakeResponse();else if(this.state===v.SocksClientState.SentAuthentication)this.handleInitialSocks5AuthenticationHandshakeResponse();else if(this.state===v.SocksClientState.SentFinalHandshake)this.handleSocks5FinalHandshakeResponse();else if(this.state===v.SocksClientState.BoundWaitingForConnection)if(this.options.proxy.type===4)this.handleSocks4IncomingConnectionResponse();else this.handleSocks5IncomingConnectionResponse();else{this.closeSocket(v.ERRORS.InternalError);break}}onCloseHandler(){this.closeSocket(v.ERRORS.SocketClosed)}onErrorHandler(Z){this.closeSocket(Z.message)}removeInternalSocketHandlers(){this.socket.pause(),this.socket.removeListener("data",this.onDataReceived),this.socket.removeListener("close",this.onClose),this.socket.removeListener("error",this.onError),this.socket.removeListener("connect",this.onConnect)}closeSocket(Z){if(this.state!==v.SocksClientState.Error)this.setState(v.SocksClientState.Error),this.socket.destroy(),this.removeInternalSocketHandlers(),this.emit("error",new yw.SocksClientError(Z,this.options))}sendSocks4InitialHandshake(){let Z=this.options.proxy.userId||"",J=new V6.SmartBuffer;if(J.writeUInt8(4),J.writeUInt8(v.SocksCommand[this.options.command]),J.writeUInt16BE(this.options.destination.port),U$.isIPv4(this.options.destination.host))J.writeBuffer((0,P6.ipToBuffer)(this.options.destination.host)),J.writeStringNT(Z);else J.writeUInt8(0),J.writeUInt8(0),J.writeUInt8(0),J.writeUInt8(1),J.writeStringNT(Z),J.writeStringNT(this.options.destination.host);this.nextRequiredPacketBufferSize=v.SOCKS_INCOMING_PACKET_SIZES.Socks4Response,this.socket.write(J.toBuffer())}handleSocks4FinalHandshakeResponse(){let Z=this.receiveBuffer.get(8);if(Z[1]!==v.Socks4Response.Granted)this.closeSocket(`${v.ERRORS.Socks4ProxyRejectedConnection} - (${v.Socks4Response[Z[1]]})`);else if(v.SocksCommand[this.options.command]===v.SocksCommand.bind){let J=V6.SmartBuffer.fromBuffer(Z);J.readOffset=2;let X={port:J.readUInt16BE(),host:(0,P6.int32ToIpv4)(J.readUInt32BE())};if(X.host==="0.0.0.0")X.host=this.options.proxy.ipaddress;this.setState(v.SocksClientState.BoundWaitingForConnection),this.emit("bound",{remoteHost:X,socket:this.socket})}else this.setState(v.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{socket:this.socket})}handleSocks4IncomingConnectionResponse(){let Z=this.receiveBuffer.get(8);if(Z[1]!==v.Socks4Response.Granted)this.closeSocket(`${v.ERRORS.Socks4ProxyRejectedIncomingBoundConnection} - (${v.Socks4Response[Z[1]]})`);else{let J=V6.SmartBuffer.fromBuffer(Z);J.readOffset=2;let X={port:J.readUInt16BE(),host:(0,P6.int32ToIpv4)(J.readUInt32BE())};this.setState(v.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost:X,socket:this.socket})}}sendSocks5InitialHandshake(){let Z=new V6.SmartBuffer,J=[v.Socks5Auth.NoAuth];if(this.options.proxy.userId||this.options.proxy.password)J.push(v.Socks5Auth.UserPass);if(this.options.proxy.custom_auth_method!==void 0)J.push(this.options.proxy.custom_auth_method);Z.writeUInt8(5),Z.writeUInt8(J.length);for(let X of J)Z.writeUInt8(X);this.nextRequiredPacketBufferSize=v.SOCKS_INCOMING_PACKET_SIZES.Socks5InitialHandshakeResponse,this.socket.write(Z.toBuffer()),this.setState(v.SocksClientState.SentInitialHandshake)}handleInitialSocks5HandshakeResponse(){let Z=this.receiveBuffer.get(2);if(Z[0]!==5)this.closeSocket(v.ERRORS.InvalidSocks5IntiailHandshakeSocksVersion);else if(Z[1]===v.SOCKS5_NO_ACCEPTABLE_AUTH)this.closeSocket(v.ERRORS.InvalidSocks5InitialHandshakeNoAcceptedAuthType);else if(Z[1]===v.Socks5Auth.NoAuth)this.socks5ChosenAuthType=v.Socks5Auth.NoAuth,this.sendSocks5CommandRequest();else if(Z[1]===v.Socks5Auth.UserPass)this.socks5ChosenAuthType=v.Socks5Auth.UserPass,this.sendSocks5UserPassAuthentication();else if(Z[1]===this.options.proxy.custom_auth_method)this.socks5ChosenAuthType=this.options.proxy.custom_auth_method,this.sendSocks5CustomAuthentication();else this.closeSocket(v.ERRORS.InvalidSocks5InitialHandshakeUnknownAuthType)}sendSocks5UserPassAuthentication(){let Z=this.options.proxy.userId||"",J=this.options.proxy.password||"",X=new V6.SmartBuffer;X.writeUInt8(1),X.writeUInt8(Buffer.byteLength(Z)),X.writeString(Z),X.writeUInt8(Buffer.byteLength(J)),X.writeString(J),this.nextRequiredPacketBufferSize=v.SOCKS_INCOMING_PACKET_SIZES.Socks5UserPassAuthenticationResponse,this.socket.write(X.toBuffer()),this.setState(v.SocksClientState.SentAuthentication)}sendSocks5CustomAuthentication(){return B$(this,void 0,void 0,function*(){this.nextRequiredPacketBufferSize=this.options.proxy.custom_auth_response_size,this.socket.write(yield this.options.proxy.custom_auth_request_handler()),this.setState(v.SocksClientState.SentAuthentication)})}handleSocks5CustomAuthHandshakeResponse(Z){return B$(this,void 0,void 0,function*(){return yield this.options.proxy.custom_auth_response_handler(Z)})}handleSocks5AuthenticationNoAuthHandshakeResponse(Z){return B$(this,void 0,void 0,function*(){return Z[1]===0})}handleSocks5AuthenticationUserPassHandshakeResponse(Z){return B$(this,void 0,void 0,function*(){return Z[1]===0})}handleInitialSocks5AuthenticationHandshakeResponse(){return B$(this,void 0,void 0,function*(){this.setState(v.SocksClientState.ReceivedAuthenticationResponse);let Z=!1;if(this.socks5ChosenAuthType===v.Socks5Auth.NoAuth)Z=yield this.handleSocks5AuthenticationNoAuthHandshakeResponse(this.receiveBuffer.get(2));else if(this.socks5ChosenAuthType===v.Socks5Auth.UserPass)Z=yield this.handleSocks5AuthenticationUserPassHandshakeResponse(this.receiveBuffer.get(2));else if(this.socks5ChosenAuthType===this.options.proxy.custom_auth_method)Z=yield this.handleSocks5CustomAuthHandshakeResponse(this.receiveBuffer.get(this.options.proxy.custom_auth_response_size));if(!Z)this.closeSocket(v.ERRORS.Socks5AuthenticationFailed);else this.sendSocks5CommandRequest()})}sendSocks5CommandRequest(){let Z=new V6.SmartBuffer;if(Z.writeUInt8(5),Z.writeUInt8(v.SocksCommand[this.options.command]),Z.writeUInt8(0),U$.isIPv4(this.options.destination.host))Z.writeUInt8(v.Socks5HostType.IPv4),Z.writeBuffer((0,P6.ipToBuffer)(this.options.destination.host));else if(U$.isIPv6(this.options.destination.host))Z.writeUInt8(v.Socks5HostType.IPv6),Z.writeBuffer((0,P6.ipToBuffer)(this.options.destination.host));else Z.writeUInt8(v.Socks5HostType.Hostname),Z.writeUInt8(this.options.destination.host.length),Z.writeString(this.options.destination.host);Z.writeUInt16BE(this.options.destination.port),this.nextRequiredPacketBufferSize=v.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader,this.socket.write(Z.toBuffer()),this.setState(v.SocksClientState.SentFinalHandshake)}handleSocks5FinalHandshakeResponse(){let Z=this.receiveBuffer.peek(5);if(Z[0]!==5||Z[1]!==v.Socks5Response.Granted)this.closeSocket(`${v.ERRORS.InvalidSocks5FinalHandshakeRejected} - ${v.Socks5Response[Z[1]]}`);else{let J=Z[3],X,$;if(J===v.Socks5HostType.IPv4){let Y=v.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4;if(this.receiveBuffer.length<Y){this.nextRequiredPacketBufferSize=Y;return}if($=V6.SmartBuffer.fromBuffer(this.receiveBuffer.get(Y).slice(4)),X={host:(0,P6.int32ToIpv4)($.readUInt32BE()),port:$.readUInt16BE()},X.host==="0.0.0.0")X.host=this.options.proxy.ipaddress}else if(J===v.Socks5HostType.Hostname){let Y=Z[4],Q=v.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(Y);if(this.receiveBuffer.length<Q){this.nextRequiredPacketBufferSize=Q;return}$=V6.SmartBuffer.fromBuffer(this.receiveBuffer.get(Q).slice(5)),X={host:$.readString(Y),port:$.readUInt16BE()}}else if(J===v.Socks5HostType.IPv6){let Y=v.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6;if(this.receiveBuffer.length<Y){this.nextRequiredPacketBufferSize=Y;return}$=V6.SmartBuffer.fromBuffer(this.receiveBuffer.get(Y).slice(4)),X={host:Iw.Address6.fromByteArray(Array.from($.readBuffer(16))).canonicalForm(),port:$.readUInt16BE()}}if(this.setState(v.SocksClientState.ReceivedFinalResponse),v.SocksCommand[this.options.command]===v.SocksCommand.connect)this.setState(v.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost:X,socket:this.socket});else if(v.SocksCommand[this.options.command]===v.SocksCommand.bind)this.setState(v.SocksClientState.BoundWaitingForConnection),this.nextRequiredPacketBufferSize=v.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader,this.emit("bound",{remoteHost:X,socket:this.socket});else if(v.SocksCommand[this.options.command]===v.SocksCommand.associate)this.setState(v.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost:X,socket:this.socket})}}handleSocks5IncomingConnectionResponse(){let Z=this.receiveBuffer.peek(5);if(Z[0]!==5||Z[1]!==v.Socks5Response.Granted)this.closeSocket(`${v.ERRORS.Socks5ProxyRejectedIncomingBoundConnection} - ${v.Socks5Response[Z[1]]}`);else{let J=Z[3],X,$;if(J===v.Socks5HostType.IPv4){let Y=v.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4;if(this.receiveBuffer.length<Y){this.nextRequiredPacketBufferSize=Y;return}if($=V6.SmartBuffer.fromBuffer(this.receiveBuffer.get(Y).slice(4)),X={host:(0,P6.int32ToIpv4)($.readUInt32BE()),port:$.readUInt16BE()},X.host==="0.0.0.0")X.host=this.options.proxy.ipaddress}else if(J===v.Socks5HostType.Hostname){let Y=Z[4],Q=v.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(Y);if(this.receiveBuffer.length<Q){this.nextRequiredPacketBufferSize=Q;return}$=V6.SmartBuffer.fromBuffer(this.receiveBuffer.get(Q).slice(5)),X={host:$.readString(Y),port:$.readUInt16BE()}}else if(J===v.Socks5HostType.IPv6){let Y=v.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6;if(this.receiveBuffer.length<Y){this.nextRequiredPacketBufferSize=Y;return}$=V6.SmartBuffer.fromBuffer(this.receiveBuffer.get(Y).slice(4)),X={host:Iw.Address6.fromByteArray(Array.from($.readBuffer(16))).canonicalForm(),port:$.readUInt16BE()}}this.setState(v.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost:X,socket:this.socket})}}get socksClientOptions(){return Object.assign({},this.options)}}h7.SocksClient=UH});var d$0=L((HJ)=>{var F91=HJ&&HJ.__createBinding||(Object.create?function(Z,J,X,$){if($===void 0)$=X;var Y=Object.getOwnPropertyDescriptor(J,X);if(!Y||("get"in Y?!J.__esModule:Y.writable||Y.configurable))Y={enumerable:!0,get:function(){return J[X]}};Object.defineProperty(Z,$,Y)}:function(Z,J,X,$){if($===void 0)$=X;Z[$]=J[X]}),B91=HJ&&HJ.__exportStar||function(Z,J){for(var X in Z)if(X!=="default"&&!Object.prototype.hasOwnProperty.call(J,X))F91(J,Z,X)};Object.defineProperty(HJ,"__esModule",{value:!0});B91(m$0(),HJ)});var kw=L((l8)=>{var U91=l8&&l8.__createBinding||(Object.create?function(Z,J,X,$){if($===void 0)$=X;var Y=Object.getOwnPropertyDescriptor(J,X);if(!Y||("get"in Y?!J.__esModule:Y.writable||Y.configurable))Y={enumerable:!0,get:function(){return J[X]}};Object.defineProperty(Z,$,Y)}:function(Z,J,X,$){if($===void 0)$=X;Z[$]=J[X]}),L91=l8&&l8.__setModuleDefault||(Object.create?function(Z,J){Object.defineProperty(Z,"default",{enumerable:!0,value:J})}:function(Z,J){Z.default=J}),D91=l8&&l8.__importStar||function(){var Z=function(J){return Z=Object.getOwnPropertyNames||function(X){var $=[];for(var Y in X)if(Object.prototype.hasOwnProperty.call(X,Y))$[$.length]=Y;return $},Z(J)};return function(J){if(J&&J.__esModule)return J;var X={};if(J!=null){for(var $=Z(J),Y=0;Y<$.length;Y++)if($[Y]!=="default")U91(X,J,$[Y])}return L91(X,J),X}}(),u$0=l8&&l8.__importDefault||function(Z){return Z&&Z.__esModule?Z:{default:Z}};Object.defineProperty(l8,"__esModule",{value:!0});l8.default=C91;var _91=u$0(h6()),O91=N("stream"),w91=d$0(),j91=D91(N("dns")),M91=N("util"),Sw=u$0(N("assert")),C9=(0,_91.default)("mqttjs:socks");class c$0 extends O91.Duplex{_flowing=!1;_socket;constructor(){super({autoDestroy:!1});this.cork()}_start(Z){if(C9("proxy stream started"),(0,Sw.default)(!this._socket),this.destroyed){Z.destroy(this.errored);return}if(this._socket=Z,!this._flowing)Z.pause();Z.on("data",this._onData),Z.on("end",this._onEnd),Z.on("error",this._onError),Z.on("close",this._onClose),Z.emit("connect"),this.uncork()}_write(Z,J,X){(0,Sw.default)(this._socket),this._socket.write(Z,X)}_read(Z){this._flowing=!0,this._socket?.resume?.()}_destroy(Z,J){this._socket?.destroy?.(Z),J(Z)}_onData=(Z)=>{if((0,Sw.default)(this._socket),this._flowing=this.push(Z),!this._flowing)this._socket.pause()};_onEnd=()=>{C9("proxy stream received EOF"),this.push(null)};_onClose=()=>{C9("proxy stream closed"),this.destroy()};_onError=(Z)=>{C9("proxy stream died with error %s",Z),this.destroy(Z)}}function LH(Z){try{if(Z.code===void 0)Z.code="SOCKS";return Z}catch{return Z}}function A91(Z){switch(Z){case"socks5h:":return[5,!0];case"socks4a:":return[4,!0];case"socks5:":return[5,!1];case"socks4:":return[4,!1];default:return[void 0,!1]}}function T91(Z){let J=new URL(Z);if(J.pathname||J.hash||J.search)throw LH(Error("bad SOCKS URL"));let[X,$]=A91(J.protocol);if(!X)throw LH(Error("bad SOCKS URL: invalid protocol"));let Y=parseInt(J.port,10);if(Number.isNaN(Y))throw LH(Error("bad SOCKS URL: invalid port"));return[{host:J.hostname,port:Y,type:X},$]}async function q91(Z,J,X,$,Y={}){let Q=Y.lookup??(0,M91.promisify)(j91.lookup),[W,K]=T91(X);if(!K)C9("resolving %s locally",Z),Z=(await Q(Z,{family:W.type===4?4:0})).address;C9("establishing SOCKS%d connection to %s:%d via %s:%d",W.type,Z,J,W.host,W.port);let z=new w91.SocksClient({command:"connect",destination:{host:Z,port:J},proxy:{...W},timeout:Y.timeout});z.connect(),z.on("established",({socket:G})=>$._start(G)),z.on("error",(G)=>{C9("SOCKS failed: %s",G),$.destroy(LH(G))})}function C91(Z,J,X,$){C9("SOCKS connection to %s:%d via %s",Z,J,X);let Y=new c$0;return q91(Z,J,X,Y,$).catch((Q)=>{C9("SOCKS failed: %s",Q),Y.destroy(Q)}),Y}});var vw=L((EQ)=>{var xw=EQ&&EQ.__importDefault||function(Z){return Z&&Z.__esModule?Z:{default:Z}};Object.defineProperty(EQ,"__esModule",{value:!0});var N91=xw(N("net")),R91=xw(h6()),P91=xw(kw()),E91=(0,R91.default)("mqttjs:tcp"),I91=(Z,J)=>{if(J.port=J.port||1883,J.hostname=J.hostname||J.host||"localhost",J.socksProxy)return(0,P91.default)(J.hostname,J.port,J.socksProxy,{timeout:J.socksTimeout});let{port:X,path:$}=J,Y=J.hostname;return E91("port %d and host %s",X,Y),N91.default.createConnection({port:X,host:Y,path:$})};EQ.default=I91});var fw=L((IQ)=>{var hw=IQ&&IQ.__importDefault||function(Z){return Z&&Z.__esModule?Z:{default:Z}};Object.defineProperty(IQ,"__esModule",{value:!0});var l$0=N("tls"),y91=hw(N("net")),S91=hw(h6()),k91=hw(kw()),x91=(0,S91.default)("mqttjs:tls");function v91(Z){let{host:J,port:X,socksProxy:$,...Y}=Z;if($!==void 0){let Q=(0,k91.default)(J,X,$,{timeout:Z.socksTimeout});return(0,l$0.connect)({...Y,socket:Q})}return(0,l$0.connect)(Z)}var h91=(Z,J)=>{if(J.port=J.port||8883,J.host=J.hostname||J.host||"localhost",y91.default.isIP(J.host)===0)J.servername=J.host;J.rejectUnauthorized=J.rejectUnauthorized!==!1,delete J.path,x91("port %d host %s rejectUnauthorized %b",J.port,J.host,J.rejectUnauthorized);let X=v91(J);X.on("secureConnect",()=>{if(J.rejectUnauthorized&&!X.authorized)X.emit("error",Error("TLS not authorized"));else X.removeListener("error",$)});function $(Y){if(J.rejectUnauthorized)Z.emit("error",Y);X.end()}return X.on("error",$),X};IQ.default=h91});var gw=L((i$0)=>{Object.defineProperty(i$0,"__esModule",{value:!0});var p$0=N("buffer"),f91=R7(),b91=QH(),y5,bw,E6;function g91(){let Z=new f91.Transform;return Z._write=(J,X,$)=>{y5.send({data:J.buffer,success(){$()},fail(Y){$(Error(Y))}})},Z._flush=(J)=>{y5.close({success(){J()}})},Z}function m91(Z){if(!Z.hostname)Z.hostname="localhost";if(!Z.path)Z.path="/";if(!Z.wsOptions)Z.wsOptions={}}function d91(Z,J){let X=Z.protocol==="wxs"?"wss":"ws",$=`${X}://${Z.hostname}${Z.path}`;if(Z.port&&Z.port!==80&&Z.port!==443)$=`${X}://${Z.hostname}:${Z.port}${Z.path}`;if(typeof Z.transformWsUrl==="function")$=Z.transformWsUrl($,Z,J);return $}function u91(){y5.onOpen(()=>{E6.socketReady()}),y5.onMessage((Z)=>{let{data:J}=Z;if(J instanceof ArrayBuffer)J=p$0.Buffer.from(J);else J=p$0.Buffer.from(J,"utf8");bw.push(J)}),y5.onClose(()=>{E6.emit("close"),E6.end(),E6.destroy()}),y5.onError((Z)=>{let J=Error(Z.errMsg);E6.destroy(J)})}var c91=(Z,J)=>{if(J.hostname=J.hostname||J.host,!J.hostname)throw Error("Could not determine host. Specify host manually.");let X=J.protocolId==="MQIsdp"&&J.protocolVersion===3?"mqttv3.1":"mqtt";m91(J);let $=d91(J,Z);y5=wx.connectSocket({url:$,protocols:[X]}),bw=g91(),E6=new b91.BufferedDuplex(J,bw,y5),E6._destroy=(Q,W)=>{y5.close({success(){if(W)W(Q)}})};let Y=E6.destroy;return E6.destroy=(Q,W)=>{return E6.destroy=Y,setTimeout(()=>{y5.close({fail(){E6._destroy(Q,W)}})},0),E6},u91(),E6};i$0.default=c91});var dw=L((o$0)=>{Object.defineProperty(o$0,"__esModule",{value:!0});var mw=N("buffer"),p91=R7(),i91=QH(),N9,yQ,L$,n$0=!1;function n91(){let Z=new p91.Transform;return Z._write=(J,X,$)=>{N9.sendSocketMessage({data:J.buffer,success(){$()},fail(){$(Error())}})},Z._flush=(J)=>{N9.closeSocket({success(){J()}})},Z}function o91(Z){if(!Z.hostname)Z.hostname="localhost";if(!Z.path)Z.path="/";if(!Z.wsOptions)Z.wsOptions={}}function a91(Z,J){let X=Z.protocol==="alis"?"wss":"ws",$=`${X}://${Z.hostname}${Z.path}`;if(Z.port&&Z.port!==80&&Z.port!==443)$=`${X}://${Z.hostname}:${Z.port}${Z.path}`;if(typeof Z.transformWsUrl==="function")$=Z.transformWsUrl($,Z,J);return $}function r91(){if(n$0)return;n$0=!0,N9.onSocketOpen(()=>{L$.socketReady()}),N9.onSocketMessage((Z)=>{if(typeof Z.data==="string"){let J=mw.Buffer.from(Z.data,"base64");yQ.push(J)}else{let J=new FileReader;J.addEventListener("load",()=>{if(J.result instanceof ArrayBuffer){yQ.push(mw.Buffer.from(J.result));return}yQ.push(mw.Buffer.from(J.result,"utf-8"))}),J.readAsArrayBuffer(Z.data)}}),N9.onSocketClose(()=>{L$.end(),L$.destroy()}),N9.onSocketError((Z)=>{L$.destroy(Z)})}var s91=(Z,J)=>{if(J.hostname=J.hostname||J.host,!J.hostname)throw Error("Could not determine host. Specify host manually.");let X=J.protocolId==="MQIsdp"&&J.protocolVersion===3?"mqttv3.1":"mqtt";o91(J);let $=a91(J,Z);return N9=J.my,N9.connectSocket({url:$,protocols:X}),yQ=n91(),L$=new i91.BufferedDuplex(J,yQ,N9),r91(),L$};o$0.default=s91});var t$0=L((D$)=>{var DH=D$&&D$.__importDefault||function(Z){return Z&&Z.__esModule?Z:{default:Z}};Object.defineProperty(D$,"__esModule",{value:!0});D$.connectAsync=$71;var e91=DH(h6()),Z71=DH(N("url")),J71=DH(YH()),a$0=DH(qQ());if(typeof process?.nextTick!=="function")process.nextTick=setImmediate;var r$0=(0,e91.default)("mqttjs"),a1=null;function X71(Z){let J;if(Z.auth)if(J=Z.auth.match(/^(.+):(.+)$/),J){let[,X,$]=J;Z.username=X,Z.password=$}else Z.username=Z.auth}function s$0(Z,J){if(r$0("connecting to an MQTT broker..."),typeof Z==="object"&&!J)J=Z,Z="";if(J=J||{},Z&&typeof Z==="string"){let Y=Z71.default.parse(Z,!0),Q={};if(Y.port!=null)Q.port=Number(Y.port);if(Q.host=Y.hostname,Q.query=Y.query,Q.auth=Y.auth,Q.protocol=Y.protocol,Q.path=Y.path,J={...Q,...J},!J.protocol)throw Error("Missing protocol");J.protocol=J.protocol.replace(/:$/,"")}if(J.unixSocket=J.unixSocket||J.protocol?.includes("+unix"),J.unixSocket)J.protocol=J.protocol.replace("+unix","");else if(!J.protocol?.startsWith("ws")&&!J.protocol?.startsWith("wx"))delete J.path;if(X71(J),J.query&&typeof J.query.clientId==="string")J.clientId=J.query.clientId;if(a$0.default||J.unixSocket)J.socksProxy=void 0;else if(J.socksProxy===void 0&&typeof process<"u")J.socksProxy=process.env.MQTTJS_SOCKS_PROXY;if(J.cert&&J.key)if(J.protocol){if(["mqtts","wss","wxs","alis"].indexOf(J.protocol)===-1)switch(J.protocol){case"mqtt":J.protocol="mqtts";break;case"ws":J.protocol="wss";break;case"wx":J.protocol="wxs";break;case"ali":J.protocol="alis";break;default:throw Error(`Unknown protocol for secure connection: "${J.protocol}"!`)}}else throw Error("Missing secure protocol key");if(!a1)if(a1={},!a$0.default&&!J.forceNativeWebSocket)a1.ws=RQ().streamBuilder,a1.wss=RQ().streamBuilder,a1.mqtt=vw().default,a1.tcp=vw().default,a1.ssl=fw().default,a1.tls=a1.ssl,a1.mqtts=fw().default;else a1.ws=RQ().browserStreamBuilder,a1.wss=RQ().browserStreamBuilder,a1.wx=gw().default,a1.wxs=gw().default,a1.ali=dw().default,a1.alis=dw().default;if(!a1[J.protocol]){let Y=["mqtts","wss"].indexOf(J.protocol)!==-1;J.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((Q,W)=>{if(Y&&W%2===0)return!1;return typeof a1[Q]==="function"})[0]}if(J.clean===!1&&!J.clientId)throw Error("Missing clientId for unclean clients");if(J.protocol)J.defaultProtocol=J.protocol;function X(Y){if(J.servers){if(!Y._reconnectCount||Y._reconnectCount===J.servers.length)Y._reconnectCount=0;J.host=J.servers[Y._reconnectCount].host,J.port=J.servers[Y._reconnectCount].port,J.protocol=!J.servers[Y._reconnectCount].protocol?J.defaultProtocol:J.servers[Y._reconnectCount].protocol,J.hostname=J.host,Y._reconnectCount++}return r$0("calling streambuilder for",J.protocol),a1[J.protocol](Y,J)}let $=new J71.default(X,J);return $.on("error",()=>{}),$}function $71(Z,J,X=!0){return new Promise(($,Y)=>{let Q=s$0(Z,J),W={connect:(z)=>{K(),$(Q)},end:()=>{K(),$(Q)},error:(z)=>{K(),Q.end(),Y(z)}};if(X===!1)W.close=()=>{W.error(Error("Couldn't connect to server"))};function K(){Object.keys(W).forEach((z)=>{Q.off(z,W[z])})}Object.keys(W).forEach((z)=>{Q.on(z,W[z])})})}D$.default=s$0});var uw=L((m0)=>{var e$0=m0&&m0.__createBinding||(Object.create?function(Z,J,X,$){if($===void 0)$=X;var Y=Object.getOwnPropertyDescriptor(J,X);if(!Y||("get"in Y?!J.__esModule:Y.writable||Y.configurable))Y={enumerable:!0,get:function(){return J[X]}};Object.defineProperty(Z,$,Y)}:function(Z,J,X,$){if($===void 0)$=X;Z[$]=J[X]}),Y71=m0&&m0.__setModuleDefault||(Object.create?function(Z,J){Object.defineProperty(Z,"default",{enumerable:!0,value:J})}:function(Z,J){Z.default=J}),Q71=m0&&m0.__importStar||function(){var Z=function(J){return Z=Object.getOwnPropertyNames||function(X){var $=[];for(var Y in X)if(Object.prototype.hasOwnProperty.call(X,Y))$[$.length]=Y;return $},Z(J)};return function(J){if(J&&J.__esModule)return J;var X={};if(J!=null){for(var $=Z(J),Y=0;Y<$.length;Y++)if($[Y]!=="default")e$0(X,J,$[Y])}return Y71(X,J),X}}(),ZY0=m0&&m0.__exportStar||function(Z,J){for(var X in Z)if(X!=="default"&&!Object.prototype.hasOwnProperty.call(J,X))e$0(J,Z,X)},SQ=m0&&m0.__importDefault||function(Z){return Z&&Z.__esModule?Z:{default:Z}};Object.defineProperty(m0,"__esModule",{value:!0});m0.ReasonCodes=m0.KeepaliveManager=m0.UniqueMessageIdProvider=m0.DefaultMessageIdProvider=m0.Store=m0.MqttClient=m0.connectAsync=m0.connect=m0.Client=void 0;var JY0=SQ(YH());m0.MqttClient=JY0.default;var W71=SQ(Jw());m0.DefaultMessageIdProvider=W71.default;var K71=SQ(hX0());m0.UniqueMessageIdProvider=K71.default;var z71=SQ(dO());m0.Store=z71.default;var XY0=Q71(t$0());m0.connect=XY0.default;Object.defineProperty(m0,"connectAsync",{enumerable:!0,get:function(){return XY0.connectAsync}});var G71=SQ(Uw());m0.KeepaliveManager=G71.default;m0.Client=JY0.default;ZY0(YH(),m0);ZY0(ZJ(),m0);var H71=JQ();Object.defineProperty(m0,"ReasonCodes",{enumerable:!0,get:function(){return H71.ReasonCodes}})});var YY0=L((K8)=>{var $Y0=K8&&K8.__createBinding||(Object.create?function(Z,J,X,$){if($===void 0)$=X;var Y=Object.getOwnPropertyDescriptor(J,X);if(!Y||("get"in Y?!J.__esModule:Y.writable||Y.configurable))Y={enumerable:!0,get:function(){return J[X]}};Object.defineProperty(Z,$,Y)}:function(Z,J,X,$){if($===void 0)$=X;Z[$]=J[X]}),V71=K8&&K8.__setModuleDefault||(Object.create?function(Z,J){Object.defineProperty(Z,"default",{enumerable:!0,value:J})}:function(Z,J){Z.default=J}),F71=K8&&K8.__importStar||function(){var Z=function(J){return Z=Object.getOwnPropertyNames||function(X){var $=[];for(var Y in X)if(Object.prototype.hasOwnProperty.call(X,Y))$[$.length]=Y;return $},Z(J)};return function(J){if(J&&J.__esModule)return J;var X={};if(J!=null){for(var $=Z(J),Y=0;Y<$.length;Y++)if($[Y]!=="default")$Y0(X,J,$[Y])}return V71(X,J),X}}(),B71=K8&&K8.__exportStar||function(Z,J){for(var X in Z)if(X!=="default"&&!Object.prototype.hasOwnProperty.call(J,X))$Y0(J,Z,X)};Object.defineProperty(K8,"__esModule",{value:!0});var U71=F71(uw());K8.default=U71;B71(uw(),K8)});var pw=L((py1,HY0)=>{HY0.exports={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8}});var BY0=L((iy1,FY0)=>{var A71=pw();function VY0(Z){this.mode=A71.MODE_8BIT_BYTE,this.data=Z}VY0.prototype={getLength:function(){return this.data.length},write:function(Z){for(var J=0;J<this.data.length;J++)Z.put(this.data.charCodeAt(J),8)}};FY0.exports=VY0});var iw=L((ny1,UY0)=>{var p8={glog:function(Z){if(Z<1)throw Error("glog("+Z+")");return p8.LOG_TABLE[Z]},gexp:function(Z){while(Z<0)Z+=255;while(Z>=256)Z-=255;return p8.EXP_TABLE[Z]},EXP_TABLE:Array(256),LOG_TABLE:Array(256)};for(A1=0;A1<8;A1++)p8.EXP_TABLE[A1]=1<<A1;var A1;for(A1=8;A1<256;A1++)p8.EXP_TABLE[A1]=p8.EXP_TABLE[A1-4]^p8.EXP_TABLE[A1-5]^p8.EXP_TABLE[A1-6]^p8.EXP_TABLE[A1-8];var A1;for(A1=0;A1<255;A1++)p8.LOG_TABLE[p8.EXP_TABLE[A1]]=A1;var A1;UY0.exports=p8});var nw=L((oy1,LY0)=>{var VJ=iw();function TH(Z,J){if(Z.length===void 0)throw Error(Z.length+"/"+J);var X=0;while(X<Z.length&&Z[X]===0)X++;this.num=Array(Z.length-X+J);for(var $=0;$<Z.length-X;$++)this.num[$]=Z[$+X]}TH.prototype={get:function(Z){return this.num[Z]},getLength:function(){return this.num.length},multiply:function(Z){var J=Array(this.getLength()+Z.getLength()-1);for(var X=0;X<this.getLength();X++)for(var $=0;$<Z.getLength();$++)J[X+$]^=VJ.gexp(VJ.glog(this.get(X))+VJ.glog(Z.get($)));return new TH(J,0)},mod:function(Z){if(this.getLength()-Z.getLength()<0)return this;var J=VJ.glog(this.get(0))-VJ.glog(Z.get(0)),X=Array(this.getLength());for(var $=0;$<this.getLength();$++)X[$]=this.get($);for(var Y=0;Y<Z.getLength();Y++)X[Y]^=VJ.gexp(VJ.glog(Z.get(Y))+J);return new TH(X,0).mod(Z)}};LY0.exports=TH});var _Y0=L((ay1,DY0)=>{DY0.exports={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7}});var jY0=L((ry1,wY0)=>{var z8=pw(),OY0=nw(),T71=iw(),f7=_Y0(),D4={PATTERN_POSITION_TABLE:[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],G15:1335,G18:7973,G15_MASK:21522,getBCHTypeInfo:function(Z){var J=Z<<10;while(D4.getBCHDigit(J)-D4.getBCHDigit(D4.G15)>=0)J^=D4.G15<<D4.getBCHDigit(J)-D4.getBCHDigit(D4.G15);return(Z<<10|J)^D4.G15_MASK},getBCHTypeNumber:function(Z){var J=Z<<12;while(D4.getBCHDigit(J)-D4.getBCHDigit(D4.G18)>=0)J^=D4.G18<<D4.getBCHDigit(J)-D4.getBCHDigit(D4.G18);return Z<<12|J},getBCHDigit:function(Z){var J=0;while(Z!==0)J++,Z>>>=1;return J},getPatternPosition:function(Z){return D4.PATTERN_POSITION_TABLE[Z-1]},getMask:function(Z,J,X){switch(Z){case f7.PATTERN000:return(J+X)%2===0;case f7.PATTERN001:return J%2===0;case f7.PATTERN010:return X%3===0;case f7.PATTERN011:return(J+X)%3===0;case f7.PATTERN100:return(Math.floor(J/2)+Math.floor(X/3))%2===0;case f7.PATTERN101:return J*X%2+J*X%3===0;case f7.PATTERN110:return(J*X%2+J*X%3)%2===0;case f7.PATTERN111:return(J*X%3+(J+X)%2)%2===0;default:throw Error("bad maskPattern:"+Z)}},getErrorCorrectPolynomial:function(Z){var J=new OY0([1],0);for(var X=0;X<Z;X++)J=J.multiply(new OY0([1,T71.gexp(X)],0));return J},getLengthInBits:function(Z,J){if(1<=J&&J<10)switch(Z){case z8.MODE_NUMBER:return 10;case z8.MODE_ALPHA_NUM:return 9;case z8.MODE_8BIT_BYTE:return 8;case z8.MODE_KANJI:return 8;default:throw Error("mode:"+Z)}else if(J<27)switch(Z){case z8.MODE_NUMBER:return 12;case z8.MODE_ALPHA_NUM:return 11;case z8.MODE_8BIT_BYTE:return 16;case z8.MODE_KANJI:return 10;default:throw Error("mode:"+Z)}else if(J<41)switch(Z){case z8.MODE_NUMBER:return 14;case z8.MODE_ALPHA_NUM:return 13;case z8.MODE_8BIT_BYTE:return 16;case z8.MODE_KANJI:return 12;default:throw Error("mode:"+Z)}else throw Error("type:"+J)},getLostPoint:function(Z){var J=Z.getModuleCount(),X=0,$=0,Y=0;for($=0;$<J;$++)for(Y=0;Y<J;Y++){var Q=0,W=Z.isDark($,Y);for(var K=-1;K<=1;K++){if($+K<0||J<=$+K)continue;for(var z=-1;z<=1;z++){if(Y+z<0||J<=Y+z)continue;if(K===0&&z===0)continue;if(W===Z.isDark($+K,Y+z))Q++}}if(Q>5)X+=3+Q-5}for($=0;$<J-1;$++)for(Y=0;Y<J-1;Y++){var G=0;if(Z.isDark($,Y))G++;if(Z.isDark($+1,Y))G++;if(Z.isDark($,Y+1))G++;if(Z.isDark($+1,Y+1))G++;if(G===0||G===4)X+=3}for($=0;$<J;$++)for(Y=0;Y<J-6;Y++)if(Z.isDark($,Y)&&!Z.isDark($,Y+1)&&Z.isDark($,Y+2)&&Z.isDark($,Y+3)&&Z.isDark($,Y+4)&&!Z.isDark($,Y+5)&&Z.isDark($,Y+6))X+=40;for(Y=0;Y<J;Y++)for($=0;$<J-6;$++)if(Z.isDark($,Y)&&!Z.isDark($+1,Y)&&Z.isDark($+2,Y)&&Z.isDark($+3,Y)&&Z.isDark($+4,Y)&&!Z.isDark($+5,Y)&&Z.isDark($+6,Y))X+=40;var H=0;for(Y=0;Y<J;Y++)for($=0;$<J;$++)if(Z.isDark($,Y))H++;var V=Math.abs(100*H/J/J-50)/5;return X+=V*10,X}};wY0.exports=D4});var ow=L((sy1,MY0)=>{MY0.exports={L:1,M:0,Q:3,H:2}});var TY0=L((ty1,AY0)=>{var qH=ow();function S5(Z,J){this.totalCount=Z,this.dataCount=J}S5.RS_BLOCK_TABLE=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12],[5,122,98,1,123,99],[7,73,45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]];S5.getRSBlocks=function(Z,J){var X=S5.getRsBlockTable(Z,J);if(X===void 0)throw Error("bad rs block @ typeNumber:"+Z+"/errorCorrectLevel:"+J);var $=X.length/3,Y=[];for(var Q=0;Q<$;Q++){var W=X[Q*3+0],K=X[Q*3+1],z=X[Q*3+2];for(var G=0;G<W;G++)Y.push(new S5(K,z))}return Y};S5.getRsBlockTable=function(Z,J){switch(J){case qH.L:return S5.RS_BLOCK_TABLE[(Z-1)*4+0];case qH.M:return S5.RS_BLOCK_TABLE[(Z-1)*4+1];case qH.Q:return S5.RS_BLOCK_TABLE[(Z-1)*4+2];case qH.H:return S5.RS_BLOCK_TABLE[(Z-1)*4+3];default:return}};AY0.exports=S5});var NY0=L((ey1,CY0)=>{function qY0(){this.buffer=[],this.length=0}qY0.prototype={get:function(Z){var J=Math.floor(Z/8);return(this.buffer[J]>>>7-Z%8&1)==1},put:function(Z,J){for(var X=0;X<J;X++)this.putBit((Z>>>J-X-1&1)==1)},getLengthInBits:function(){return this.length},putBit:function(Z){var J=Math.floor(this.length/8);if(this.buffer.length<=J)this.buffer.push(0);if(Z)this.buffer[J]|=128>>>this.length%8;this.length++}};CY0.exports=qY0});var IY0=L((ZS1,EY0)=>{var q71=BY0(),b7=jY0(),C71=nw(),RY0=TY0(),PY0=NY0();function k5(Z,J){this.typeNumber=Z,this.errorCorrectLevel=J,this.modules=null,this.moduleCount=0,this.dataCache=null,this.dataList=[]}k5.prototype={addData:function(Z){var J=new q71(Z);this.dataList.push(J),this.dataCache=null},isDark:function(Z,J){if(Z<0||this.moduleCount<=Z||J<0||this.moduleCount<=J)throw Error(Z+","+J);return this.modules[Z][J]},getModuleCount:function(){return this.moduleCount},make:function(){if(this.typeNumber<1){var Z=1;for(Z=1;Z<40;Z++){var J=RY0.getRSBlocks(Z,this.errorCorrectLevel),X=new PY0,$=0;for(var Y=0;Y<J.length;Y++)$+=J[Y].dataCount;for(var Q=0;Q<this.dataList.length;Q++){var W=this.dataList[Q];X.put(W.mode,4),X.put(W.getLength(),b7.getLengthInBits(W.mode,Z)),W.write(X)}if(X.getLengthInBits()<=$*8)break}this.typeNumber=Z}this.makeImpl(!1,this.getBestMaskPattern())},makeImpl:function(Z,J){this.moduleCount=this.typeNumber*4+17,this.modules=Array(this.moduleCount);for(var X=0;X<this.moduleCount;X++){this.modules[X]=Array(this.moduleCount);for(var $=0;$<this.moduleCount;$++)this.modules[X][$]=null}if(this.setupPositionProbePattern(0,0),this.setupPositionProbePattern(this.moduleCount-7,0),this.setupPositionProbePattern(0,this.moduleCount-7),this.setupPositionAdjustPattern(),this.setupTimingPattern(),this.setupTypeInfo(Z,J),this.typeNumber>=7)this.setupTypeNumber(Z);if(this.dataCache===null)this.dataCache=k5.createData(this.typeNumber,this.errorCorrectLevel,this.dataList);this.mapData(this.dataCache,J)},setupPositionProbePattern:function(Z,J){for(var X=-1;X<=7;X++){if(Z+X<=-1||this.moduleCount<=Z+X)continue;for(var $=-1;$<=7;$++){if(J+$<=-1||this.moduleCount<=J+$)continue;if(0<=X&&X<=6&&($===0||$===6)||0<=$&&$<=6&&(X===0||X===6)||2<=X&&X<=4&&2<=$&&$<=4)this.modules[Z+X][J+$]=!0;else this.modules[Z+X][J+$]=!1}}},getBestMaskPattern:function(){var Z=0,J=0;for(var X=0;X<8;X++){this.makeImpl(!0,X);var $=b7.getLostPoint(this);if(X===0||Z>$)Z=$,J=X}return J},createMovieClip:function(Z,J,X){var $=Z.createEmptyMovieClip(J,X),Y=1;this.make();for(var Q=0;Q<this.modules.length;Q++){var W=Q*Y;for(var K=0;K<this.modules[Q].length;K++){var z=K*Y,G=this.modules[Q][K];if(G)$.beginFill(0,100),$.moveTo(z,W),$.lineTo(z+Y,W),$.lineTo(z+Y,W+Y),$.lineTo(z,W+Y),$.endFill()}}return $},setupTimingPattern:function(){for(var Z=8;Z<this.moduleCount-8;Z++){if(this.modules[Z][6]!==null)continue;this.modules[Z][6]=Z%2===0}for(var J=8;J<this.moduleCount-8;J++){if(this.modules[6][J]!==null)continue;this.modules[6][J]=J%2===0}},setupPositionAdjustPattern:function(){var Z=b7.getPatternPosition(this.typeNumber);for(var J=0;J<Z.length;J++)for(var X=0;X<Z.length;X++){var $=Z[J],Y=Z[X];if(this.modules[$][Y]!==null)continue;for(var Q=-2;Q<=2;Q++)for(var W=-2;W<=2;W++)if(Math.abs(Q)===2||Math.abs(W)===2||Q===0&&W===0)this.modules[$+Q][Y+W]=!0;else this.modules[$+Q][Y+W]=!1}},setupTypeNumber:function(Z){var J=b7.getBCHTypeNumber(this.typeNumber),X;for(var $=0;$<18;$++)X=!Z&&(J>>$&1)===1,this.modules[Math.floor($/3)][$%3+this.moduleCount-8-3]=X;for(var Y=0;Y<18;Y++)X=!Z&&(J>>Y&1)===1,this.modules[Y%3+this.moduleCount-8-3][Math.floor(Y/3)]=X},setupTypeInfo:function(Z,J){var X=this.errorCorrectLevel<<3|J,$=b7.getBCHTypeInfo(X),Y;for(var Q=0;Q<15;Q++)if(Y=!Z&&($>>Q&1)===1,Q<6)this.modules[Q][8]=Y;else if(Q<8)this.modules[Q+1][8]=Y;else this.modules[this.moduleCount-15+Q][8]=Y;for(var W=0;W<15;W++)if(Y=!Z&&($>>W&1)===1,W<8)this.modules[8][this.moduleCount-W-1]=Y;else if(W<9)this.modules[8][15-W-1+1]=Y;else this.modules[8][15-W-1]=Y;this.modules[this.moduleCount-8][8]=!Z},mapData:function(Z,J){var X=-1,$=this.moduleCount-1,Y=7,Q=0;for(var W=this.moduleCount-1;W>0;W-=2){if(W===6)W--;while(!0){for(var K=0;K<2;K++)if(this.modules[$][W-K]===null){var z=!1;if(Q<Z.length)z=(Z[Q]>>>Y&1)===1;var G=b7.getMask(J,$,W-K);if(G)z=!z;if(this.modules[$][W-K]=z,Y--,Y===-1)Q++,Y=7}if($+=X,$<0||this.moduleCount<=$){$-=X,X=-X;break}}}}};k5.PAD0=236;k5.PAD1=17;k5.createData=function(Z,J,X){var $=RY0.getRSBlocks(Z,J),Y=new PY0;for(var Q=0;Q<X.length;Q++){var W=X[Q];Y.put(W.mode,4),Y.put(W.getLength(),b7.getLengthInBits(W.mode,Z)),W.write(Y)}var K=0;for(var z=0;z<$.length;z++)K+=$[z].dataCount;if(Y.getLengthInBits()>K*8)throw Error("code length overflow. ("+Y.getLengthInBits()+">"+K*8+")");if(Y.getLengthInBits()+4<=K*8)Y.put(0,4);while(Y.getLengthInBits()%8!==0)Y.putBit(!1);while(!0){if(Y.getLengthInBits()>=K*8)break;if(Y.put(k5.PAD0,8),Y.getLengthInBits()>=K*8)break;Y.put(k5.PAD1,8)}return k5.createBytes(Y,$)};k5.createBytes=function(Z,J){var X=0,$=0,Y=0,Q=Array(J.length),W=Array(J.length);for(var K=0;K<J.length;K++){var z=J[K].dataCount,G=J[K].totalCount-z;$=Math.max($,z),Y=Math.max(Y,G),Q[K]=Array(z);for(var H=0;H<Q[K].length;H++)Q[K][H]=255&Z.buffer[H+X];X+=z;var V=b7.getErrorCorrectPolynomial(G),F=new C71(Q[K],V.getLength()-1),B=F.mod(V);W[K]=Array(V.getLength()-1);for(var U=0;U<W[K].length;U++){var D=U+B.getLength()-W[K].length;W[K][U]=D>=0?B.get(D):0}}var _=0;for(var O=0;O<J.length;O++)_+=J[O].totalCount;var w=Array(_),j=0;for(var q=0;q<$;q++)for(var R=0;R<J.length;R++)if(q<Q[R].length)w[j++]=Q[R][q];for(var T=0;T<Y;T++)for(var y=0;y<J.length;y++)if(T<W[y].length)w[j++]=W[y][T];return w};EY0.exports=k5});var kY0=L((JS1,SY0)=>{var N71=IY0(),yY0=ow(),R71="\x1B[40m \x1B[0m",CH="\x1B[47m \x1B[0m",P71=function(Z){return Z?R71:CH},aw=function(Z){return{times:function(J){return Array(J).join(Z)}}},E71=function(Z,J){var X=Array(Z);for(var $=0;$<Z;$++)X[$]=J;return X};SY0.exports={error:yY0.L,generate:function(Z,J,X){if(typeof J==="function")X=J,J={};var $=new N71(-1,this.error);$.addData(Z),$.make();var Y="";if(J&&J.small){var Q=!0,W=!1,K=$.getModuleCount(),z=$.modules.slice(),G=K%2===1;if(G)z.push(E71(K,W));var H={WHITE_ALL:"\u2588",WHITE_BLACK:"\u2580",BLACK_WHITE:"\u2584",BLACK_ALL:" "},V=aw(H.BLACK_WHITE).times(K+3),F=aw(H.WHITE_BLACK).times(K+3);Y+=V+`
19
19
  `;for(var B=0;B<K;B+=2){Y+=H.WHITE_ALL;for(var U=0;U<K;U++)if(z[B][U]===W&&z[B+1][U]===W)Y+=H.WHITE_ALL;else if(z[B][U]===W&&z[B+1][U]===Q)Y+=H.WHITE_BLACK;else if(z[B][U]===Q&&z[B+1][U]===W)Y+=H.BLACK_WHITE;else Y+=H.BLACK_ALL;Y+=H.WHITE_ALL+`
20
20
  `}if(!G)Y+=F}else{var D=aw(CH).times($.getModuleCount()+3);Y+=D+`
21
21
  `,$.modules.forEach(function(_){Y+=CH,Y+=_.map(P71).join(""),Y+=CH+`
@@ -25,19 +25,19 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
25
25
  `);for(let K=$;K<W.length;K++){let z=W[K];if(z.length>1024)z=z.slice(0,1024);let G=$h.test(z)?z.replace($h,"$1"):z;if(G.match(/\S*Error: /))continue;for(let H of J){let V=H(G);if(V){Q.push(V);break}}if(Q.length>=50+Y)break}return Qh(Q.slice(Y))}}function HB(Z){if(Array.isArray(Z))return CW(...Z);return Z}function Qh(Z){if(!Z.length)return[];let J=Array.from(Z);if(/sentryWrapped/.test(qW(J).function||""))J.pop();if(J.reverse(),Yh.test(qW(J).function||"")){if(J.pop(),Yh.test(qW(J).function||""))J.pop()}return J.slice(0,50).map((X)=>({...X,filename:X.filename||qW(J).filename,function:X.function||"?"}))}function qW(Z){return Z[Z.length-1]||{}}var zB="<anonymous>";function i$(Z){try{if(!Z||typeof Z!=="function")return zB;return Z.name||zB}catch{return zB}}function NW(Z){return"__v_isVNode"in Z&&Z.__v_isVNode?"[VueVNode]":"[VueViewModel]"}var RW={},Wh={};function EJ(Z,J){RW[Z]=RW[Z]||[],RW[Z].push(J)}function IJ(Z,J){if(!Wh[Z]){Wh[Z]=!0;try{J()}catch(X){l&&A.error(`Error while instrumenting ${Z}`,X)}}}function yJ(Z,J){let X=Z&&RW[Z];if(!X)return;for(let $ of X)try{$(J)}catch(Y){l&&A.error(`Error while triggering instrumentation handler.
26
26
  Type: ${Z}
27
27
  Name: ${i$($)}
28
- Error:`,Y)}}var VB=null;function Kh(Z){EJ("error",Z),IJ("error",Bq0)}function Bq0(){VB=Q0.onerror,Q0.onerror=function(Z,J,X,$,Y){if(yJ("error",{column:$,error:Y,line:X,msg:Z,url:J}),VB)return VB.apply(this,arguments);return!1},Q0.onerror.__SENTRY_INSTRUMENTED__=!0}var FB=null;function zh(Z){EJ("unhandledrejection",Z),IJ("unhandledrejection",Uq0)}function Uq0(){FB=Q0.onunhandledrejection,Q0.onunhandledrejection=function(Z){if(yJ("unhandledrejection",Z),FB)return FB.apply(this,arguments);return!0},Q0.onunhandledrejection.__SENTRY_INSTRUMENTED__=!0}var Gh=Object.prototype.toString;function a8(Z){switch(Gh.call(Z)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return r8(Z,Error)}}function PW(Z,J){return Gh.call(Z)===`[object ${J}]`}function BB(Z){return PW(Z,"ErrorEvent")}function x9(Z){return PW(Z,"String")}function SJ(Z){return typeof Z==="object"&&Z!==null&&"__sentry_template_string__"in Z&&"__sentry_template_values__"in Z}function n$(Z){return Z===null||SJ(Z)||typeof Z!=="object"&&typeof Z!=="function"}function d5(Z){return PW(Z,"Object")}function UB(Z){return typeof Event<"u"&&r8(Z,Event)}function LB(Z){return typeof Element<"u"&&r8(Z,Element)}function DB(Z){return PW(Z,"RegExp")}function I4(Z){return Boolean(Z?.then&&typeof Z.then==="function")}function _B(Z){return d5(Z)&&"nativeEvent"in Z&&"preventDefault"in Z&&"stopPropagation"in Z}function r8(Z,J){try{return Z instanceof J}catch{return!1}}function o$(Z){return!!(typeof Z==="object"&&Z!==null&&(Z.__isVue||Z._isVue||Z.__v_isVNode))}var Lq0=Q0,Dq0=80;function Hh(Z,J={}){if(!Z)return"<unknown>";try{let X=Z,$=5,Y=[],Q=0,W=0,K=" > ",z=K.length,G,H=Array.isArray(J)?J:J.keyAttrs,V=!Array.isArray(J)&&J.maxStringLength||Dq0;while(X&&Q++<$){if(G=_q0(X,H),G==="html"||Q>1&&W+Y.length*z+G.length>=V)break;Y.push(G),W+=G.length,X=X.parentNode}return Y.reverse().join(K)}catch{return"<unknown>"}}function _q0(Z,J){let X=Z,$=[];if(!X?.tagName)return"";if(Lq0.HTMLElement){if(X instanceof HTMLElement&&X.dataset){if(X.dataset.sentryComponent)return X.dataset.sentryComponent;if(X.dataset.sentryElement)return X.dataset.sentryElement}}$.push(X.tagName.toLowerCase());let Y=J?.length?J.filter((W)=>X.getAttribute(W)).map((W)=>[W,X.getAttribute(W)]):null;if(Y?.length)Y.forEach((W)=>{$.push(`[${W[0]}="${W[1]}"]`)});else{if(X.id)$.push(`#${X.id}`);let W=X.className;if(W&&x9(W)){let K=W.split(/\s+/);for(let z of K)$.push(`.${z}`)}}let Q=["aria-label","type","name","title","alt"];for(let W of Q){let K=X.getAttribute(W);if(K)$.push(`[${W}="${K}"]`)}return $.join("")}function OB(Z,J,X){if(!(J in Z))return;let $=Z[J];if(typeof $!=="function")return;let Y=X($);if(typeof Y==="function")Bh(Y,$);try{Z[J]=Y}catch{l&&A.log(`Failed to replace method "${J}" in object`,Z)}}function f1(Z,J,X){try{Object.defineProperty(Z,J,{value:X,writable:!0,configurable:!0})}catch{l&&A.log(`Failed to add non-enumerable property "${J}" to object`,Z)}}function Bh(Z,J){try{let X=J.prototype||{};Z.prototype=J.prototype=X,f1(Z,"__sentry_original__",J)}catch{}}function wB(Z){return Z.__sentry_original__}function EW(Z){if(a8(Z))return{message:Z.message,name:Z.name,stack:Z.stack,...Fh(Z)};else if(UB(Z)){let J={type:Z.type,target:Vh(Z.target),currentTarget:Vh(Z.currentTarget),...Fh(Z)};if(typeof CustomEvent<"u"&&r8(Z,CustomEvent))J.detail=Z.detail;return J}else return Z}function Vh(Z){try{return LB(Z)?Hh(Z):Object.prototype.toString.call(Z)}catch{return"<unknown>"}}function Fh(Z){if(typeof Z==="object"&&Z!==null){let J={};for(let X in Z)if(Object.prototype.hasOwnProperty.call(Z,X))J[X]=Z[X];return J}else return{}}function jB(Z){let J=Object.keys(EW(Z));return J.sort(),!J[0]?"[object has no keys]":J.join(", ")}var kJ;function QZ(Z){if(kJ!==void 0)return kJ?kJ(Z):Z();let J=Symbol.for("__SENTRY_SAFE_RANDOM_ID_WRAPPER__"),X=Q0;if(J in X&&typeof X[J]==="function")return kJ=X[J],kJ(Z);return kJ=null,Z()}function K4(){return QZ(()=>Math.random())}function f6(){return QZ(()=>Date.now())}function v9(Z,J=0){if(typeof Z!=="string"||J===0)return Z;return Z.length<=J?Z:`${Z.slice(0,J)}...`}function MB(Z,J){let X=Z,$=X.length;if($<=150)return X;if(J>$)J=$;let Y=Math.max(J-60,0);if(Y<5)Y=0;let Q=Math.min(Y+140,$);if(Q>$-5)Q=$;if(Q===$)Y=Math.max(Q-140,0);if(X=X.slice(Y,Q),Y>0)X=`'{snip} ${X}`;if(Q<$)X+=" {snip}";return X}function AB(Z,J){if(!Array.isArray(Z))return"";let X=[];for(let $=0;$<Z.length;$++){let Y=Z[$];try{if(o$(Y))X.push(NW(Y));else X.push(String(Y))}catch{X.push("[value cannot be serialized]")}}return X.join(J)}function u5(Z,J,X=!1){if(!x9(Z))return!1;if(DB(J))return J.test(Z);if(x9(J))return X?Z===J:Z.includes(J);return!1}function h9(Z,J=[],X=!1){return J.some(($)=>u5(Z,$,X))}function Oq0(){let Z=Q0;return Z.crypto||Z.msCrypto}var TB;function wq0(){return K4()*16}function c1(Z=Oq0()){try{if(Z?.randomUUID)return QZ(()=>Z.randomUUID()).replace(/-/g,"")}catch{}if(!TB)TB=[1e7]+1000+4000+8000+100000000000;return TB.replace(/[018]/g,(J)=>(J^(wq0()&15)>>J/4).toString(16))}function Uh(Z){return Z.exception?.values?.[0]}function f9(Z){let{message:J,event_id:X}=Z;if(J)return J;let $=Uh(Z);if($){if($.type&&$.value)return`${$.type}: ${$.value}`;return $.type||$.value||X||"<unknown>"}return X||"<unknown>"}function CB(Z,J,X){let $=Z.exception=Z.exception||{},Y=$.values=$.values||[],Q=Y[0]=Y[0]||{};if(!Q.value)Q.value=J||"";if(!Q.type)Q.type=X||"Error"}function xJ(Z,J){let X=Uh(Z);if(!X)return;let $={type:"generic",handled:!0},Y=X.mechanism;if(X.mechanism={...$,...Y,...J},J&&"data"in J){let Q={...Y?.data,...J.data};X.mechanism.data=Q}}var jq0=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;function qB(Z){return parseInt(Z||"",10)}function NB(Z){let J=Z.match(jq0)||[],X=qB(J[1]),$=qB(J[2]),Y=qB(J[3]);return{buildmetadata:J[5],major:isNaN(X)?void 0:X,minor:isNaN($)?void 0:$,patch:isNaN(Y)?void 0:Y,prerelease:J[4]}}function IW(Z){if(Mq0(Z))return!0;try{f1(Z,"__sentry_captured__",!0)}catch{}return!1}function Mq0(Z){try{return Z.__sentry_captured__}catch{}}var Dh=1000;function c5(){return f6()/Dh}function Aq0(){let{performance:Z}=Q0;if(!Z?.now||!Z.timeOrigin)return c5;let J=Z.timeOrigin;return()=>{return(J+QZ(()=>Z.now()))/Dh}}var Lh;function b9(){return(Lh??(Lh=Aq0()))()}function _h(Z){let J=b9(),X={sid:c1(),init:!0,timestamp:J,started:J,duration:0,status:"ok",errors:0,ignoreDuration:!1,toJSON:()=>Tq0(X)};if(Z)l5(X,Z);return X}function l5(Z,J={}){if(J.user){if(!Z.ipAddress&&J.user.ip_address)Z.ipAddress=J.user.ip_address;if(!Z.did&&!J.did)Z.did=J.user.id||J.user.email||J.user.username}if(Z.timestamp=J.timestamp||b9(),J.abnormal_mechanism)Z.abnormal_mechanism=J.abnormal_mechanism;if(J.ignoreDuration)Z.ignoreDuration=J.ignoreDuration;if(J.sid)Z.sid=J.sid.length===32?J.sid:c1();if(J.init!==void 0)Z.init=J.init;if(!Z.did&&J.did)Z.did=`${J.did}`;if(typeof J.started==="number")Z.started=J.started;if(Z.ignoreDuration)Z.duration=void 0;else if(typeof J.duration==="number")Z.duration=J.duration;else{let X=Z.timestamp-Z.started;Z.duration=X>=0?X:0}if(J.release)Z.release=J.release;if(J.environment)Z.environment=J.environment;if(!Z.ipAddress&&J.ipAddress)Z.ipAddress=J.ipAddress;if(!Z.userAgent&&J.userAgent)Z.userAgent=J.userAgent;if(typeof J.errors==="number")Z.errors=J.errors;if(J.status)Z.status=J.status}function Oh(Z,J){let X={};if(J)X={status:J};else if(Z.status==="ok")X={status:"exited"};l5(Z,X)}function Tq0(Z){return{sid:`${Z.sid}`,init:Z.init,started:new Date(Z.started*1000).toISOString(),timestamp:new Date(Z.timestamp*1000).toISOString(),status:Z.status,errors:Z.errors,did:typeof Z.did==="number"||typeof Z.did==="string"?`${Z.did}`:void 0,duration:Z.duration,abnormal_mechanism:Z.abnormal_mechanism,attrs:{release:Z.release,environment:Z.environment,ip_address:Z.ipAddress,user_agent:Z.userAgent}}}function g9(Z,J,X=2){if(!J||typeof J!=="object"||X<=0)return J;if(Z&&Object.keys(J).length===0)return Z;let $={...Z};for(let Y in J)if(Object.prototype.hasOwnProperty.call(J,Y))$[Y]=g9($[Y],J[Y],X-1);return $}function a4(){return c1()}function r4(){return c1().substring(16)}var RB="_sentrySpan";function m9(Z,J){if(J)f1(Z,RB,J);else delete Z[RB]}function WZ(Z){return Z[RB]}var qq0=100;class y4{constructor(){this._notifyingListeners=!1,this._scopeListeners=[],this._eventProcessors=[],this._breadcrumbs=[],this._attachments=[],this._user={},this._tags={},this._attributes={},this._extra={},this._contexts={},this._sdkProcessingMetadata={},this._propagationContext={traceId:a4(),sampleRand:K4()}}clone(){let Z=new y4;if(Z._breadcrumbs=[...this._breadcrumbs],Z._tags={...this._tags},Z._attributes={...this._attributes},Z._extra={...this._extra},Z._contexts={...this._contexts},this._contexts.flags)Z._contexts.flags={values:[...this._contexts.flags.values]};return Z._user=this._user,Z._level=this._level,Z._session=this._session,Z._transactionName=this._transactionName,Z._fingerprint=this._fingerprint,Z._eventProcessors=[...this._eventProcessors],Z._attachments=[...this._attachments],Z._sdkProcessingMetadata={...this._sdkProcessingMetadata},Z._propagationContext={...this._propagationContext},Z._client=this._client,Z._lastEventId=this._lastEventId,m9(Z,WZ(this)),Z}setClient(Z){this._client=Z}setLastEventId(Z){this._lastEventId=Z}getClient(){return this._client}lastEventId(){return this._lastEventId}addScopeListener(Z){this._scopeListeners.push(Z)}addEventProcessor(Z){return this._eventProcessors.push(Z),this}setUser(Z){if(this._user=Z||{email:void 0,id:void 0,ip_address:void 0,username:void 0},this._session)l5(this._session,{user:Z});return this._notifyScopeListeners(),this}getUser(){return this._user}setTags(Z){return this._tags={...this._tags,...Z},this._notifyScopeListeners(),this}setTag(Z,J){return this.setTags({[Z]:J})}setAttributes(Z){return this._attributes={...this._attributes,...Z},this._notifyScopeListeners(),this}setAttribute(Z,J){return this.setAttributes({[Z]:J})}removeAttribute(Z){if(Z in this._attributes)delete this._attributes[Z],this._notifyScopeListeners();return this}setExtras(Z){return this._extra={...this._extra,...Z},this._notifyScopeListeners(),this}setExtra(Z,J){return this._extra={...this._extra,[Z]:J},this._notifyScopeListeners(),this}setFingerprint(Z){return this._fingerprint=Z,this._notifyScopeListeners(),this}setLevel(Z){return this._level=Z,this._notifyScopeListeners(),this}setTransactionName(Z){return this._transactionName=Z,this._notifyScopeListeners(),this}setContext(Z,J){if(J===null)delete this._contexts[Z];else this._contexts[Z]=J;return this._notifyScopeListeners(),this}setSession(Z){if(!Z)delete this._session;else this._session=Z;return this._notifyScopeListeners(),this}getSession(){return this._session}update(Z){if(!Z)return this;let J=typeof Z==="function"?Z(this):Z,X=J instanceof y4?J.getScopeData():d5(J)?Z:void 0,{tags:$,attributes:Y,extra:Q,user:W,contexts:K,level:z,fingerprint:G=[],propagationContext:H}=X||{};if(this._tags={...this._tags,...$},this._attributes={...this._attributes,...Y},this._extra={...this._extra,...Q},this._contexts={...this._contexts,...K},W&&Object.keys(W).length)this._user=W;if(z)this._level=z;if(G.length)this._fingerprint=G;if(H)this._propagationContext=H;return this}clear(){return this._breadcrumbs=[],this._tags={},this._attributes={},this._extra={},this._user={},this._contexts={},this._level=void 0,this._transactionName=void 0,this._fingerprint=void 0,this._session=void 0,m9(this,void 0),this._attachments=[],this.setPropagationContext({traceId:a4(),sampleRand:K4()}),this._notifyScopeListeners(),this}addBreadcrumb(Z,J){let X=typeof J==="number"?J:qq0;if(X<=0)return this;let $={timestamp:c5(),...Z,message:Z.message?v9(Z.message,2048):Z.message};if(this._breadcrumbs.push($),this._breadcrumbs.length>X)this._breadcrumbs=this._breadcrumbs.slice(-X),this._client?.recordDroppedEvent("buffer_overflow","log_item");return this._notifyScopeListeners(),this}getLastBreadcrumb(){return this._breadcrumbs[this._breadcrumbs.length-1]}clearBreadcrumbs(){return this._breadcrumbs=[],this._notifyScopeListeners(),this}addAttachment(Z){return this._attachments.push(Z),this}clearAttachments(){return this._attachments=[],this}getScopeData(){return{breadcrumbs:this._breadcrumbs,attachments:this._attachments,contexts:this._contexts,tags:this._tags,attributes:this._attributes,extra:this._extra,user:this._user,level:this._level,fingerprint:this._fingerprint||[],eventProcessors:this._eventProcessors,propagationContext:this._propagationContext,sdkProcessingMetadata:this._sdkProcessingMetadata,transactionName:this._transactionName,span:WZ(this)}}setSDKProcessingMetadata(Z){return this._sdkProcessingMetadata=g9(this._sdkProcessingMetadata,Z,2),this}setPropagationContext(Z){return this._propagationContext=Z,this}getPropagationContext(){return this._propagationContext}captureException(Z,J){let X=J?.event_id||c1();if(!this._client)return l&&A.warn("No client configured on scope - will not capture exception!"),X;let $=Error("Sentry syntheticException");return this._client.captureException(Z,{originalException:Z,syntheticException:$,...J,event_id:X},this),X}captureMessage(Z,J,X){let $=X?.event_id||c1();if(!this._client)return l&&A.warn("No client configured on scope - will not capture message!"),$;let Y=X?.syntheticException??Error(Z);return this._client.captureMessage(Z,J,{originalException:Z,syntheticException:Y,...X,event_id:$},this),$}captureEvent(Z,J){let X=J?.event_id||c1();if(!this._client)return l&&A.warn("No client configured on scope - will not capture event!"),X;return this._client.captureEvent(Z,{...J,event_id:X},this),X}_notifyScopeListeners(){if(!this._notifyingListeners)this._notifyingListeners=!0,this._scopeListeners.forEach((Z)=>{Z(this)}),this._notifyingListeners=!1}}function vJ(){return j8("defaultCurrentScope",()=>new y4)}function B6(){return j8("defaultIsolationScope",()=>new y4)}class jh{constructor(Z,J){let X;if(!Z)X=new y4;else X=Z;let $;if(!J)$=new y4;else $=J;this._stack=[{scope:X}],this._isolationScope=$}withScope(Z){let J=this._pushScope(),X;try{X=Z(J)}catch($){throw this._popScope(),$}if(I4(X))return X.then(($)=>{return this._popScope(),$},($)=>{throw this._popScope(),$});return this._popScope(),X}getClient(){return this.getStackTop().client}getScope(){return this.getStackTop().scope}getIsolationScope(){return this._isolationScope}getStackTop(){return this._stack[this._stack.length-1]}_pushScope(){let Z=this.getScope().clone();return this._stack.push({client:this.getClient(),scope:Z}),Z}_popScope(){if(this._stack.length<=1)return!1;return!!this._stack.pop()}}function hJ(){let Z=O4(),J=k9(Z);return J.stack=J.stack||new jh(vJ(),B6())}function Cq0(Z){return hJ().withScope(Z)}function Nq0(Z,J){let X=hJ();return X.withScope(()=>{return X.getStackTop().scope=Z,J(Z)})}function wh(Z){return hJ().withScope(()=>{return Z(hJ().getIsolationScope())})}function Mh(){return{withIsolationScope:wh,withScope:Cq0,withSetScope:Nq0,withSetIsolationScope:(Z,J)=>{return wh(J)},getCurrentScope:()=>hJ().getScope(),getIsolationScope:()=>hJ().getIsolationScope()}}function PB(Z){let J=O4(),X=k9(J);X.acs=Z}function b6(Z){let J=k9(Z);if(J.acs)return J.acs;return Mh()}function u0(){let Z=O4();return b6(Z).getCurrentScope()}function R0(){let Z=O4();return b6(Z).getIsolationScope()}function yW(){return j8("globalScope",()=>new y4)}function s4(...Z){let J=O4(),X=b6(J);if(Z.length===2){let[$,Y]=Z;if(!$)return X.withScope(Y);return X.withSetScope($,Y)}return X.withScope(Z[0])}function KZ(...Z){let J=O4(),X=b6(J);if(Z.length===2){let[$,Y]=Z;if(!$)return X.withIsolationScope(Y);return X.withSetIsolationScope($,Y)}return X.withIsolationScope(Z[0])}function u(){return u0().getClient()}function zZ(Z){let J=Z.getPropagationContext(),{traceId:X,parentSpanId:$,propagationSpanId:Y}=J,Q={trace_id:X,span_id:Y||r4()};if($)Q.parent_span_id=$;return Q}var U1="sentry.source",M8="sentry.sample_rate",EB="sentry.previous_trace_sample_rate",K0="sentry.op",X0="sentry.origin";var IB="sentry.measurement_unit",yB="sentry.measurement_value",s8="sentry.custom_span_name",fJ="sentry.profile_id",bJ="sentry.exclusive_time",SB="cache.hit",kB="cache.key",xB="cache.item_size",vB="http.request.method";var hB=0,gJ=1,A0=2;function d9(Z){if(Z<400&&Z>=100)return{code:1};if(Z>=400&&Z<500)switch(Z){case 401:return{code:2,message:"unauthenticated"};case 403:return{code:2,message:"permission_denied"};case 404:return{code:2,message:"not_found"};case 409:return{code:2,message:"already_exists"};case 413:return{code:2,message:"failed_precondition"};case 429:return{code:2,message:"resource_exhausted"};case 499:return{code:2,message:"cancelled"};default:return{code:2,message:"invalid_argument"}}if(Z>=500&&Z<600)switch(Z){case 501:return{code:2,message:"unimplemented"};case 503:return{code:2,message:"unavailable"};case 504:return{code:2,message:"deadline_exceeded"};default:return{code:2,message:"internal_error"}}return{code:2,message:"internal_error"}}function SW(Z,J){Z.setAttribute("http.response.status_code",J);let X=d9(J);if(X.message!=="unknown_error")Z.setStatus(X)}var Ah="_sentryScope",Th="_sentryIsolationScope";function Rq0(Z){try{let J=Q0.WeakRef;if(typeof J==="function")return new J(Z)}catch{}return Z}function Pq0(Z){if(!Z)return;if(typeof Z==="object"&&"deref"in Z&&typeof Z.deref==="function")try{return Z.deref()}catch{return}return Z}function a$(Z,J,X){if(Z)f1(Z,Th,Rq0(X)),f1(Z,Ah,J)}function A8(Z){let J=Z;return{scope:J[Ah],isolationScope:Pq0(J[Th])}}var r$="sentry-",Ch=/^sentry-/,Nh=8192;function T8(Z){let J=HZ(Z);if(!J)return;let X=Object.entries(J).reduce(($,[Y,Q])=>{if(Y.match(Ch)){let W=Y.slice(r$.length);$[W]=Q}return $},{});if(Object.keys(X).length>0)return X;else return}function GZ(Z){if(!Z)return;let J=Object.entries(Z).reduce((X,[$,Y])=>{if(Y)X[`${r$}${$}`]=Y;return X},{});return kW(J)}function HZ(Z){if(!Z||!x9(Z)&&!Array.isArray(Z))return;if(Array.isArray(Z))return Z.reduce((J,X)=>{let $=qh(X);return Object.entries($).forEach(([Y,Q])=>{J[Y]=Q}),J},{});return qh(Z)}function qh(Z){return Z.split(",").map((J)=>{let X=J.indexOf("=");if(X===-1)return[];let $=J.slice(0,X),Y=J.slice(X+1);return[$,Y].map((Q)=>{try{return decodeURIComponent(Q.trim())}catch{return}})}).reduce((J,[X,$])=>{if(X&&$)J[X]=$;return J},{})}function kW(Z){if(Object.keys(Z).length===0)return;return Object.entries(Z).reduce((J,[X,$],Y)=>{let Q=`${encodeURIComponent(X)}=${encodeURIComponent($)}`,W=Y===0?Q:`${J},${Q}`;if(W.length>Nh)return l&&A.warn(`Not adding key: ${X} with val: ${$} to baggage header due to exceeding baggage size limits.`),J;else return W},"")}var Eq0=/^o(\d+)\./,Iq0=/^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)((?:\[[:.%\w]+\]|[\w.-]+))(?::(\d+))?\/(.+)/;function yq0(Z){return Z==="http"||Z==="https"}function U6(Z,J=!1){let{host:X,path:$,pass:Y,port:Q,projectId:W,protocol:K,publicKey:z}=Z;return`${K}://${z}${J&&Y?`:${Y}`:""}@${X}${Q?`:${Q}`:""}/${$?`${$}/`:$}${W}`}function Sq0(Z){let J=Iq0.exec(Z);if(!J){y1(()=>{console.error(`Invalid Sentry Dsn: ${Z}`)});return}let[X,$,Y="",Q="",W="",K=""]=J.slice(1),z="",G=K,H=G.split("/");if(H.length>1)z=H.slice(0,-1).join("/"),G=H.pop();if(G){let V=G.match(/^\d+/);if(V)G=V[0]}return Rh({host:Q,pass:Y,path:z,projectId:G,port:W,protocol:X,publicKey:$})}function Rh(Z){return{protocol:Z.protocol,publicKey:Z.publicKey||"",pass:Z.pass||"",host:Z.host,port:Z.port||"",path:Z.path||"",projectId:Z.projectId}}function kq0(Z){if(!l)return!0;let{port:J,projectId:X,protocol:$}=Z;if(["protocol","publicKey","host","projectId"].find((W)=>{if(!Z[W])return A.error(`Invalid Sentry Dsn: ${W} missing`),!0;return!1}))return!1;if(!X.match(/^\d+$/))return A.error(`Invalid Sentry Dsn: Invalid projectId ${X}`),!1;if(!yq0($))return A.error(`Invalid Sentry Dsn: Invalid protocol ${$}`),!1;if(J&&isNaN(parseInt(J,10)))return A.error(`Invalid Sentry Dsn: Invalid port ${J}`),!1;return!0}function xq0(Z){return Z.match(Eq0)?.[1]}function xW(Z){let J=Z.getOptions(),{host:X}=Z.getDsn()||{},$;if(J.orgId)$=String(J.orgId);else if(X)$=xq0(X);return $}function Ph(Z){let J=typeof Z==="string"?Sq0(Z):Rh(Z);if(!J||!kq0(J))return;return J}function L6(Z){if(typeof Z==="boolean")return Number(Z);let J=typeof Z==="string"?parseFloat(Z):Z;if(typeof J!=="number"||isNaN(J)||J<0||J>1)return;return J}var s$=new RegExp("^[ \\t]*([0-9a-f]{32})?-?([0-9a-f]{16})?-?([01])?[ \\t]*$");function Eh(Z){if(!Z)return;let J=Z.match(s$);if(!J)return;let X;if(J[3]==="1")X=!0;else if(J[3]==="0")X=!1;return{traceId:J[1],parentSampled:X,parentSpanId:J[2]}}function VZ(Z,J){let X=Eh(Z),$=T8(J);if(!X?.traceId)return{traceId:a4(),sampleRand:K4()};let Y=vq0(X,$);if($)$.sample_rand=Y.toString();let{traceId:Q,parentSpanId:W,parentSampled:K}=X;return{traceId:Q,parentSpanId:W,sampled:K,dsc:$||{},sampleRand:Y}}function u9(Z=a4(),J=r4(),X){let $="";if(X!==void 0)$=X?"-1":"-0";return`${Z}-${J}${$}`}function c9(Z=a4(),J=r4(),X){return`00-${Z}-${J}-${X?"01":"00"}`}function vq0(Z,J){let X=L6(J?.sample_rand);if(X!==void 0)return X;let $=L6(J?.sample_rate);if($&&Z?.parentSampled!==void 0)return Z.parentSampled?K4()*$:$+K4()*(1-$);else return K4()}function t$(Z,J){let X=xW(Z);if(J&&X&&J!==X)return A.log(`Won't continue trace because org IDs don't match (incoming baggage: ${J}, SDK options: ${X})`),!1;if(Z.getOptions().strictTraceContinuation||!1){if(J&&!X||!J&&X)return A.log(`Starting a new trace because strict trace continuation is enabled but one org ID is missing (incoming baggage: ${J}, Sentry client: ${X})`),!1}return!0}var vW=0,hW=1,Ih=!1;function Sh(Z){let{spanId:J,traceId:X}=Z.spanContext(),{data:$,op:Y,parent_span_id:Q,status:W,origin:K,links:z}=J0(Z);return{parent_span_id:Q,span_id:J,trace_id:X,data:$,op:Y,status:W,origin:K,links:z}}function l9(Z){let{spanId:J,traceId:X,isRemote:$}=Z.spanContext(),Y=$?J:J0(Z).parent_span_id,Q=A8(Z).scope,W=$?Q?.getPropagationContext().propagationSpanId||r4():J;return{parent_span_id:Y,span_id:W,trace_id:X}}function fW(Z){let{traceId:J,spanId:X}=Z.spanContext(),$=q8(Z);return u9(J,X,$)}function kh(Z){let{traceId:J,spanId:X}=Z.spanContext(),$=q8(Z);return c9(J,X,$)}function FZ(Z){if(Z&&Z.length>0)return Z.map(({context:{spanId:J,traceId:X,traceFlags:$,...Y},attributes:Q})=>({span_id:J,trace_id:X,sampled:$===hW,attributes:Q,...Y}));else return}function t4(Z){if(typeof Z==="number")return yh(Z);if(Array.isArray(Z))return Z[0]+Z[1]/1e9;if(Z instanceof Date)return yh(Z.getTime());return b9()}function yh(Z){return Z>9999999999?Z/1000:Z}function J0(Z){if(fq0(Z))return Z.getSpanJSON();let{spanId:J,traceId:X}=Z.spanContext();if(hq0(Z)){let{attributes:$,startTime:Y,name:Q,endTime:W,status:K,links:z}=Z,G="parentSpanId"in Z?Z.parentSpanId:("parentSpanContext"in Z)?Z.parentSpanContext?.spanId:void 0;return{span_id:J,trace_id:X,data:$,description:Q,parent_span_id:G,start_timestamp:t4(Y),timestamp:t4(W)||void 0,status:BZ(K),op:$[K0],origin:$[X0],links:FZ(z)}}return{span_id:J,trace_id:X,start_timestamp:0,data:{}}}function hq0(Z){let J=Z;return!!J.attributes&&!!J.startTime&&!!J.name&&!!J.endTime&&!!J.status}function fq0(Z){return typeof Z.getSpanJSON==="function"}function q8(Z){let{traceFlags:J}=Z.spanContext();return J===hW}function BZ(Z){if(!Z||Z.code===hB)return;if(Z.code===gJ)return"ok";return Z.message||"internal_error"}var e$="_sentryChildSpans",fB="_sentryRootSpan";function mJ(Z,J){let X=Z[fB]||Z;if(f1(J,fB,X),Z[e$])Z[e$].add(J);else f1(Z,e$,new Set([J]))}function bW(Z){let J=new Set;function X($){if(J.has($))return;else if(q8($)){J.add($);let Y=$[e$]?Array.from($[e$]):[];for(let Q of Y)X(Q)}}return X(Z),Array.from(J)}function q1(Z){return Z[fB]||Z}function t8(){let Z=O4(),J=b6(Z);if(J.getActiveSpan)return J.getActiveSpan();return WZ(u0())}function ZY(){if(!Ih)y1(()=>{console.warn("[Sentry] Returning null from `beforeSendSpan` is disallowed. To drop certain spans, configure the respective integrations directly or use `ignoreSpans`.")}),Ih=!0}var xh=!1;function vh(){if(xh)return;function Z(){let J=t8(),X=J&&q1(J);if(X)l&&A.log("[Tracing] Root span: internal_error -> Global error occurred"),X.setStatus({code:A0,message:"internal_error"})}Z.tag="sentry_tracingErrorCallback",xh=!0,Kh(Z),zh(Z)}function L1(Z){if(typeof __SENTRY_TRACING__==="boolean"&&!__SENTRY_TRACING__)return!1;let J=Z||u()?.getOptions();return!!J&&(J.tracesSampleRate!=null||!!J.tracesSampler)}function hh(Z){A.log(`Ignoring span ${Z.op} - ${Z.description} because it matches \`ignoreSpans\`.`)}function JY(Z,J){if(!J?.length||!Z.description)return!1;for(let X of J){if(bq0(X)){if(u5(Z.description,X))return l&&hh(Z),!0;continue}if(!X.name&&!X.op)continue;let $=X.name?u5(Z.description,X.name):!0,Y=X.op?Z.op&&u5(Z.op,X.op):!0;if($&&Y)return l&&hh(Z),!0}return!1}function fh(Z,J){let{parent_span_id:X,span_id:$}=J;if(!X)return;for(let Y of Z)if(Y.parent_span_id===$)Y.parent_span_id=X}function bq0(Z){return typeof Z==="string"||Z instanceof RegExp}var dJ="production";var bh="_frozenDsc";function gW(Z,J){f1(Z,bh,J)}function bB(Z,J){let X=J.getOptions(),{publicKey:$}=J.getDsn()||{},Y={environment:X.environment||dJ,release:X.release,public_key:$,trace_id:Z,org_id:xW(J)};return J.emit("createDsc",Y),Y}function e8(Z,J){let X=J.getPropagationContext();return X.dsc||bB(X.traceId,Z)}function S1(Z){let J=u();if(!J)return{};let X=q1(Z),$=J0(X),Y=$.data,Q=X.spanContext().traceState,W=Q?.get("sentry.sample_rate")??Y[M8]??Y[EB];function K(U){if(typeof W==="number"||typeof W==="string")U.sample_rate=`${W}`;return U}let z=X[bh];if(z)return K(z);let G=Q?.get("sentry.dsc"),H=G&&T8(G);if(H)return K(H);let V=bB(Z.spanContext().traceId,J),F=Y[U1],B=$.description;if(F!=="url"&&B)V.transaction=B;if(L1())V.sampled=String(q8(X)),V.sample_rand=Q?.get("sentry.sample_rand")??A8(X).scope?.getPropagationContext().sampleRand.toString();return K(V),J.emit("createDsc",V,X),V}class uJ{constructor(Z={}){this._traceId=Z.traceId||a4(),this._spanId=Z.spanId||r4()}spanContext(){return{spanId:this._spanId,traceId:this._traceId,traceFlags:vW}}end(Z){}setAttribute(Z,J){return this}setAttributes(Z){return this}setStatus(Z){return this}updateName(Z){return this}isRecording(){return!1}addEvent(Z,J,X){return this}addLink(Z){return this}addLinks(Z){return this}recordException(Z,J){}}function C8(Z,J=100,X=1/0){try{return gB("",Z,J,X)}catch($){return{ERROR:`**non-serializable** (${$})`}}}function mB(Z,J=3,X=102400){let $=C8(Z,J);if(uq0($)>X)return mB(Z,J-1,X);return $}function gB(Z,J,X=1/0,$=1/0,Y=cq0()){let[Q,W]=Y;if(J==null||["boolean","string"].includes(typeof J)||typeof J==="number"&&Number.isFinite(J))return J;let K=gq0(Z,J);if(!K.startsWith("[object "))return K;if(J.__sentry_skip_normalization__)return J;let z=typeof J.__sentry_override_normalization_depth__==="number"?J.__sentry_override_normalization_depth__:X;if(z===0)return K.replace("object ","");if(Q(J))return"[Circular ~]";let G=J;if(G&&typeof G.toJSON==="function")try{let B=G.toJSON();return gB("",B,z-1,$,Y)}catch{}let H=Array.isArray(J)?[]:{},V=0,F=EW(J);for(let B in F){if(!Object.prototype.hasOwnProperty.call(F,B))continue;if(V>=$){H[B]="[MaxProperties ~]";break}let U=F[B];H[B]=gB(B,U,z-1,$,Y),V++}return W(J),H}function gq0(Z,J){try{if(Z==="domain"&&J&&typeof J==="object"&&J._events)return"[Domain]";if(Z==="domainEmitter")return"[DomainEmitter]";if(typeof global<"u"&&J===global)return"[Global]";if(typeof window<"u"&&J===window)return"[Window]";if(typeof document<"u"&&J===document)return"[Document]";if(o$(J))return NW(J);if(_B(J))return"[SyntheticEvent]";if(typeof J==="number"&&!Number.isFinite(J))return`[${J}]`;if(typeof J==="function")return`[Function: ${i$(J)}]`;if(typeof J==="symbol")return`[${String(J)}]`;if(typeof J==="bigint")return`[BigInt: ${String(J)}]`;let X=mq0(J);if(/^HTML(\w*)Element$/.test(X))return`[HTMLElement: ${X}]`;return`[object ${X}]`}catch(X){return`**non-serializable** (${X})`}}function mq0(Z){let J=Object.getPrototypeOf(Z);return J?.constructor?J.constructor.name:"null prototype"}function dq0(Z){return~-encodeURI(Z).split(/%..|./).length}function uq0(Z){return dq0(JSON.stringify(Z))}function cq0(){let Z=new WeakSet;function J($){if(Z.has($))return!0;return Z.add($),!1}function X($){Z.delete($)}return[J,X]}function S4(Z,J=[]){return[Z,J]}function uB(Z,J){let[X,$]=Z;return[X,[...$,J]]}function XY(Z,J){let X=Z[1];for(let $ of X){let Y=$[0].type;if(J($,Y))return!0}return!1}function cB(Z,J){return XY(Z,(X,$)=>J.includes($))}function dB(Z){let J=k9(Q0);return J.encodePolyfill?J.encodePolyfill(Z):new TextEncoder().encode(Z)}function $Y(Z){let[J,X]=Z,$=JSON.stringify(J);function Y(Q){if(typeof $==="string")$=typeof Q==="string"?$+Q:[dB($),Q];else $.push(typeof Q==="string"?dB(Q):Q)}for(let Q of X){let[W,K]=Q;if(Y(`
28
+ Error:`,Y)}}var VB=null;function Kh(Z){EJ("error",Z),IJ("error",Bq0)}function Bq0(){VB=Q0.onerror,Q0.onerror=function(Z,J,X,$,Y){if(yJ("error",{column:$,error:Y,line:X,msg:Z,url:J}),VB)return VB.apply(this,arguments);return!1},Q0.onerror.__SENTRY_INSTRUMENTED__=!0}var FB=null;function zh(Z){EJ("unhandledrejection",Z),IJ("unhandledrejection",Uq0)}function Uq0(){FB=Q0.onunhandledrejection,Q0.onunhandledrejection=function(Z){if(yJ("unhandledrejection",Z),FB)return FB.apply(this,arguments);return!0},Q0.onunhandledrejection.__SENTRY_INSTRUMENTED__=!0}var Gh=Object.prototype.toString;function a8(Z){switch(Gh.call(Z)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return r8(Z,Error)}}function PW(Z,J){return Gh.call(Z)===`[object ${J}]`}function BB(Z){return PW(Z,"ErrorEvent")}function x9(Z){return PW(Z,"String")}function SJ(Z){return typeof Z==="object"&&Z!==null&&"__sentry_template_string__"in Z&&"__sentry_template_values__"in Z}function n$(Z){return Z===null||SJ(Z)||typeof Z!=="object"&&typeof Z!=="function"}function d5(Z){return PW(Z,"Object")}function UB(Z){return typeof Event<"u"&&r8(Z,Event)}function LB(Z){return typeof Element<"u"&&r8(Z,Element)}function DB(Z){return PW(Z,"RegExp")}function I4(Z){return Boolean(Z?.then&&typeof Z.then==="function")}function _B(Z){return d5(Z)&&"nativeEvent"in Z&&"preventDefault"in Z&&"stopPropagation"in Z}function r8(Z,J){try{return Z instanceof J}catch{return!1}}function o$(Z){return!!(typeof Z==="object"&&Z!==null&&(Z.__isVue||Z._isVue||Z.__v_isVNode))}var Lq0=Q0,Dq0=80;function Hh(Z,J={}){if(!Z)return"<unknown>";try{let X=Z,$=5,Y=[],Q=0,W=0,K=" > ",z=K.length,G,H=Array.isArray(J)?J:J.keyAttrs,V=!Array.isArray(J)&&J.maxStringLength||Dq0;while(X&&Q++<$){if(G=_q0(X,H),G==="html"||Q>1&&W+Y.length*z+G.length>=V)break;Y.push(G),W+=G.length,X=X.parentNode}return Y.reverse().join(K)}catch{return"<unknown>"}}function _q0(Z,J){let X=Z,$=[];if(!X?.tagName)return"";if(Lq0.HTMLElement){if(X instanceof HTMLElement&&X.dataset){if(X.dataset.sentryComponent)return X.dataset.sentryComponent;if(X.dataset.sentryElement)return X.dataset.sentryElement}}$.push(X.tagName.toLowerCase());let Y=J?.length?J.filter((W)=>X.getAttribute(W)).map((W)=>[W,X.getAttribute(W)]):null;if(Y?.length)Y.forEach((W)=>{$.push(`[${W[0]}="${W[1]}"]`)});else{if(X.id)$.push(`#${X.id}`);let W=X.className;if(W&&x9(W)){let K=W.split(/\s+/);for(let z of K)$.push(`.${z}`)}}let Q=["aria-label","type","name","title","alt"];for(let W of Q){let K=X.getAttribute(W);if(K)$.push(`[${W}="${K}"]`)}return $.join("")}function OB(Z,J,X){if(!(J in Z))return;let $=Z[J];if(typeof $!=="function")return;let Y=X($);if(typeof Y==="function")Bh(Y,$);try{Z[J]=Y}catch{l&&A.log(`Failed to replace method "${J}" in object`,Z)}}function f1(Z,J,X){try{Object.defineProperty(Z,J,{value:X,writable:!0,configurable:!0})}catch{l&&A.log(`Failed to add non-enumerable property "${J}" to object`,Z)}}function Bh(Z,J){try{let X=J.prototype||{};Z.prototype=J.prototype=X,f1(Z,"__sentry_original__",J)}catch{}}function wB(Z){return Z.__sentry_original__}function EW(Z){if(a8(Z))return{message:Z.message,name:Z.name,stack:Z.stack,...Fh(Z)};else if(UB(Z)){let J={type:Z.type,target:Vh(Z.target),currentTarget:Vh(Z.currentTarget),...Fh(Z)};if(typeof CustomEvent<"u"&&r8(Z,CustomEvent))J.detail=Z.detail;return J}else return Z}function Vh(Z){try{return LB(Z)?Hh(Z):Object.prototype.toString.call(Z)}catch{return"<unknown>"}}function Fh(Z){if(typeof Z==="object"&&Z!==null){let J={};for(let X in Z)if(Object.prototype.hasOwnProperty.call(Z,X))J[X]=Z[X];return J}else return{}}function jB(Z){let J=Object.keys(EW(Z));return J.sort(),!J[0]?"[object has no keys]":J.join(", ")}var kJ;function QZ(Z){if(kJ!==void 0)return kJ?kJ(Z):Z();let J=Symbol.for("__SENTRY_SAFE_RANDOM_ID_WRAPPER__"),X=Q0;if(J in X&&typeof X[J]==="function")return kJ=X[J],kJ(Z);return kJ=null,Z()}function K4(){return QZ(()=>Math.random())}function f6(){return QZ(()=>Date.now())}function v9(Z,J=0){if(typeof Z!=="string"||J===0)return Z;return Z.length<=J?Z:`${Z.slice(0,J)}...`}function MB(Z,J){let X=Z,$=X.length;if($<=150)return X;if(J>$)J=$;let Y=Math.max(J-60,0);if(Y<5)Y=0;let Q=Math.min(Y+140,$);if(Q>$-5)Q=$;if(Q===$)Y=Math.max(Q-140,0);if(X=X.slice(Y,Q),Y>0)X=`'{snip} ${X}`;if(Q<$)X+=" {snip}";return X}function AB(Z,J){if(!Array.isArray(Z))return"";let X=[];for(let $=0;$<Z.length;$++){let Y=Z[$];try{if(o$(Y))X.push(NW(Y));else X.push(String(Y))}catch{X.push("[value cannot be serialized]")}}return X.join(J)}function u5(Z,J,X=!1){if(!x9(Z))return!1;if(DB(J))return J.test(Z);if(x9(J))return X?Z===J:Z.includes(J);return!1}function h9(Z,J=[],X=!1){return J.some(($)=>u5(Z,$,X))}function Oq0(){let Z=Q0;return Z.crypto||Z.msCrypto}var TB;function wq0(){return K4()*16}function l1(Z=Oq0()){try{if(Z?.randomUUID)return QZ(()=>Z.randomUUID()).replace(/-/g,"")}catch{}if(!TB)TB=[1e7]+1000+4000+8000+100000000000;return TB.replace(/[018]/g,(J)=>(J^(wq0()&15)>>J/4).toString(16))}function Uh(Z){return Z.exception?.values?.[0]}function f9(Z){let{message:J,event_id:X}=Z;if(J)return J;let $=Uh(Z);if($){if($.type&&$.value)return`${$.type}: ${$.value}`;return $.type||$.value||X||"<unknown>"}return X||"<unknown>"}function CB(Z,J,X){let $=Z.exception=Z.exception||{},Y=$.values=$.values||[],Q=Y[0]=Y[0]||{};if(!Q.value)Q.value=J||"";if(!Q.type)Q.type=X||"Error"}function xJ(Z,J){let X=Uh(Z);if(!X)return;let $={type:"generic",handled:!0},Y=X.mechanism;if(X.mechanism={...$,...Y,...J},J&&"data"in J){let Q={...Y?.data,...J.data};X.mechanism.data=Q}}var jq0=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;function qB(Z){return parseInt(Z||"",10)}function NB(Z){let J=Z.match(jq0)||[],X=qB(J[1]),$=qB(J[2]),Y=qB(J[3]);return{buildmetadata:J[5],major:isNaN(X)?void 0:X,minor:isNaN($)?void 0:$,patch:isNaN(Y)?void 0:Y,prerelease:J[4]}}function IW(Z){if(Mq0(Z))return!0;try{f1(Z,"__sentry_captured__",!0)}catch{}return!1}function Mq0(Z){try{return Z.__sentry_captured__}catch{}}var Dh=1000;function c5(){return f6()/Dh}function Aq0(){let{performance:Z}=Q0;if(!Z?.now||!Z.timeOrigin)return c5;let J=Z.timeOrigin;return()=>{return(J+QZ(()=>Z.now()))/Dh}}var Lh;function b9(){return(Lh??(Lh=Aq0()))()}function _h(Z){let J=b9(),X={sid:l1(),init:!0,timestamp:J,started:J,duration:0,status:"ok",errors:0,ignoreDuration:!1,toJSON:()=>Tq0(X)};if(Z)l5(X,Z);return X}function l5(Z,J={}){if(J.user){if(!Z.ipAddress&&J.user.ip_address)Z.ipAddress=J.user.ip_address;if(!Z.did&&!J.did)Z.did=J.user.id||J.user.email||J.user.username}if(Z.timestamp=J.timestamp||b9(),J.abnormal_mechanism)Z.abnormal_mechanism=J.abnormal_mechanism;if(J.ignoreDuration)Z.ignoreDuration=J.ignoreDuration;if(J.sid)Z.sid=J.sid.length===32?J.sid:l1();if(J.init!==void 0)Z.init=J.init;if(!Z.did&&J.did)Z.did=`${J.did}`;if(typeof J.started==="number")Z.started=J.started;if(Z.ignoreDuration)Z.duration=void 0;else if(typeof J.duration==="number")Z.duration=J.duration;else{let X=Z.timestamp-Z.started;Z.duration=X>=0?X:0}if(J.release)Z.release=J.release;if(J.environment)Z.environment=J.environment;if(!Z.ipAddress&&J.ipAddress)Z.ipAddress=J.ipAddress;if(!Z.userAgent&&J.userAgent)Z.userAgent=J.userAgent;if(typeof J.errors==="number")Z.errors=J.errors;if(J.status)Z.status=J.status}function Oh(Z,J){let X={};if(J)X={status:J};else if(Z.status==="ok")X={status:"exited"};l5(Z,X)}function Tq0(Z){return{sid:`${Z.sid}`,init:Z.init,started:new Date(Z.started*1000).toISOString(),timestamp:new Date(Z.timestamp*1000).toISOString(),status:Z.status,errors:Z.errors,did:typeof Z.did==="number"||typeof Z.did==="string"?`${Z.did}`:void 0,duration:Z.duration,abnormal_mechanism:Z.abnormal_mechanism,attrs:{release:Z.release,environment:Z.environment,ip_address:Z.ipAddress,user_agent:Z.userAgent}}}function g9(Z,J,X=2){if(!J||typeof J!=="object"||X<=0)return J;if(Z&&Object.keys(J).length===0)return Z;let $={...Z};for(let Y in J)if(Object.prototype.hasOwnProperty.call(J,Y))$[Y]=g9($[Y],J[Y],X-1);return $}function a4(){return l1()}function r4(){return l1().substring(16)}var RB="_sentrySpan";function m9(Z,J){if(J)f1(Z,RB,J);else delete Z[RB]}function WZ(Z){return Z[RB]}var qq0=100;class y4{constructor(){this._notifyingListeners=!1,this._scopeListeners=[],this._eventProcessors=[],this._breadcrumbs=[],this._attachments=[],this._user={},this._tags={},this._attributes={},this._extra={},this._contexts={},this._sdkProcessingMetadata={},this._propagationContext={traceId:a4(),sampleRand:K4()}}clone(){let Z=new y4;if(Z._breadcrumbs=[...this._breadcrumbs],Z._tags={...this._tags},Z._attributes={...this._attributes},Z._extra={...this._extra},Z._contexts={...this._contexts},this._contexts.flags)Z._contexts.flags={values:[...this._contexts.flags.values]};return Z._user=this._user,Z._level=this._level,Z._session=this._session,Z._transactionName=this._transactionName,Z._fingerprint=this._fingerprint,Z._eventProcessors=[...this._eventProcessors],Z._attachments=[...this._attachments],Z._sdkProcessingMetadata={...this._sdkProcessingMetadata},Z._propagationContext={...this._propagationContext},Z._client=this._client,Z._lastEventId=this._lastEventId,m9(Z,WZ(this)),Z}setClient(Z){this._client=Z}setLastEventId(Z){this._lastEventId=Z}getClient(){return this._client}lastEventId(){return this._lastEventId}addScopeListener(Z){this._scopeListeners.push(Z)}addEventProcessor(Z){return this._eventProcessors.push(Z),this}setUser(Z){if(this._user=Z||{email:void 0,id:void 0,ip_address:void 0,username:void 0},this._session)l5(this._session,{user:Z});return this._notifyScopeListeners(),this}getUser(){return this._user}setTags(Z){return this._tags={...this._tags,...Z},this._notifyScopeListeners(),this}setTag(Z,J){return this.setTags({[Z]:J})}setAttributes(Z){return this._attributes={...this._attributes,...Z},this._notifyScopeListeners(),this}setAttribute(Z,J){return this.setAttributes({[Z]:J})}removeAttribute(Z){if(Z in this._attributes)delete this._attributes[Z],this._notifyScopeListeners();return this}setExtras(Z){return this._extra={...this._extra,...Z},this._notifyScopeListeners(),this}setExtra(Z,J){return this._extra={...this._extra,[Z]:J},this._notifyScopeListeners(),this}setFingerprint(Z){return this._fingerprint=Z,this._notifyScopeListeners(),this}setLevel(Z){return this._level=Z,this._notifyScopeListeners(),this}setTransactionName(Z){return this._transactionName=Z,this._notifyScopeListeners(),this}setContext(Z,J){if(J===null)delete this._contexts[Z];else this._contexts[Z]=J;return this._notifyScopeListeners(),this}setSession(Z){if(!Z)delete this._session;else this._session=Z;return this._notifyScopeListeners(),this}getSession(){return this._session}update(Z){if(!Z)return this;let J=typeof Z==="function"?Z(this):Z,X=J instanceof y4?J.getScopeData():d5(J)?Z:void 0,{tags:$,attributes:Y,extra:Q,user:W,contexts:K,level:z,fingerprint:G=[],propagationContext:H}=X||{};if(this._tags={...this._tags,...$},this._attributes={...this._attributes,...Y},this._extra={...this._extra,...Q},this._contexts={...this._contexts,...K},W&&Object.keys(W).length)this._user=W;if(z)this._level=z;if(G.length)this._fingerprint=G;if(H)this._propagationContext=H;return this}clear(){return this._breadcrumbs=[],this._tags={},this._attributes={},this._extra={},this._user={},this._contexts={},this._level=void 0,this._transactionName=void 0,this._fingerprint=void 0,this._session=void 0,m9(this,void 0),this._attachments=[],this.setPropagationContext({traceId:a4(),sampleRand:K4()}),this._notifyScopeListeners(),this}addBreadcrumb(Z,J){let X=typeof J==="number"?J:qq0;if(X<=0)return this;let $={timestamp:c5(),...Z,message:Z.message?v9(Z.message,2048):Z.message};if(this._breadcrumbs.push($),this._breadcrumbs.length>X)this._breadcrumbs=this._breadcrumbs.slice(-X),this._client?.recordDroppedEvent("buffer_overflow","log_item");return this._notifyScopeListeners(),this}getLastBreadcrumb(){return this._breadcrumbs[this._breadcrumbs.length-1]}clearBreadcrumbs(){return this._breadcrumbs=[],this._notifyScopeListeners(),this}addAttachment(Z){return this._attachments.push(Z),this}clearAttachments(){return this._attachments=[],this}getScopeData(){return{breadcrumbs:this._breadcrumbs,attachments:this._attachments,contexts:this._contexts,tags:this._tags,attributes:this._attributes,extra:this._extra,user:this._user,level:this._level,fingerprint:this._fingerprint||[],eventProcessors:this._eventProcessors,propagationContext:this._propagationContext,sdkProcessingMetadata:this._sdkProcessingMetadata,transactionName:this._transactionName,span:WZ(this)}}setSDKProcessingMetadata(Z){return this._sdkProcessingMetadata=g9(this._sdkProcessingMetadata,Z,2),this}setPropagationContext(Z){return this._propagationContext=Z,this}getPropagationContext(){return this._propagationContext}captureException(Z,J){let X=J?.event_id||l1();if(!this._client)return l&&A.warn("No client configured on scope - will not capture exception!"),X;let $=Error("Sentry syntheticException");return this._client.captureException(Z,{originalException:Z,syntheticException:$,...J,event_id:X},this),X}captureMessage(Z,J,X){let $=X?.event_id||l1();if(!this._client)return l&&A.warn("No client configured on scope - will not capture message!"),$;let Y=X?.syntheticException??Error(Z);return this._client.captureMessage(Z,J,{originalException:Z,syntheticException:Y,...X,event_id:$},this),$}captureEvent(Z,J){let X=J?.event_id||l1();if(!this._client)return l&&A.warn("No client configured on scope - will not capture event!"),X;return this._client.captureEvent(Z,{...J,event_id:X},this),X}_notifyScopeListeners(){if(!this._notifyingListeners)this._notifyingListeners=!0,this._scopeListeners.forEach((Z)=>{Z(this)}),this._notifyingListeners=!1}}function vJ(){return j8("defaultCurrentScope",()=>new y4)}function B6(){return j8("defaultIsolationScope",()=>new y4)}class jh{constructor(Z,J){let X;if(!Z)X=new y4;else X=Z;let $;if(!J)$=new y4;else $=J;this._stack=[{scope:X}],this._isolationScope=$}withScope(Z){let J=this._pushScope(),X;try{X=Z(J)}catch($){throw this._popScope(),$}if(I4(X))return X.then(($)=>{return this._popScope(),$},($)=>{throw this._popScope(),$});return this._popScope(),X}getClient(){return this.getStackTop().client}getScope(){return this.getStackTop().scope}getIsolationScope(){return this._isolationScope}getStackTop(){return this._stack[this._stack.length-1]}_pushScope(){let Z=this.getScope().clone();return this._stack.push({client:this.getClient(),scope:Z}),Z}_popScope(){if(this._stack.length<=1)return!1;return!!this._stack.pop()}}function hJ(){let Z=O4(),J=k9(Z);return J.stack=J.stack||new jh(vJ(),B6())}function Cq0(Z){return hJ().withScope(Z)}function Nq0(Z,J){let X=hJ();return X.withScope(()=>{return X.getStackTop().scope=Z,J(Z)})}function wh(Z){return hJ().withScope(()=>{return Z(hJ().getIsolationScope())})}function Mh(){return{withIsolationScope:wh,withScope:Cq0,withSetScope:Nq0,withSetIsolationScope:(Z,J)=>{return wh(J)},getCurrentScope:()=>hJ().getScope(),getIsolationScope:()=>hJ().getIsolationScope()}}function PB(Z){let J=O4(),X=k9(J);X.acs=Z}function b6(Z){let J=k9(Z);if(J.acs)return J.acs;return Mh()}function u0(){let Z=O4();return b6(Z).getCurrentScope()}function R0(){let Z=O4();return b6(Z).getIsolationScope()}function yW(){return j8("globalScope",()=>new y4)}function s4(...Z){let J=O4(),X=b6(J);if(Z.length===2){let[$,Y]=Z;if(!$)return X.withScope(Y);return X.withSetScope($,Y)}return X.withScope(Z[0])}function KZ(...Z){let J=O4(),X=b6(J);if(Z.length===2){let[$,Y]=Z;if(!$)return X.withIsolationScope(Y);return X.withSetIsolationScope($,Y)}return X.withIsolationScope(Z[0])}function u(){return u0().getClient()}function zZ(Z){let J=Z.getPropagationContext(),{traceId:X,parentSpanId:$,propagationSpanId:Y}=J,Q={trace_id:X,span_id:Y||r4()};if($)Q.parent_span_id=$;return Q}var U1="sentry.source",M8="sentry.sample_rate",EB="sentry.previous_trace_sample_rate",K0="sentry.op",X0="sentry.origin";var IB="sentry.measurement_unit",yB="sentry.measurement_value",s8="sentry.custom_span_name",fJ="sentry.profile_id",bJ="sentry.exclusive_time",SB="cache.hit",kB="cache.key",xB="cache.item_size",vB="http.request.method";var hB=0,gJ=1,A0=2;function d9(Z){if(Z<400&&Z>=100)return{code:1};if(Z>=400&&Z<500)switch(Z){case 401:return{code:2,message:"unauthenticated"};case 403:return{code:2,message:"permission_denied"};case 404:return{code:2,message:"not_found"};case 409:return{code:2,message:"already_exists"};case 413:return{code:2,message:"failed_precondition"};case 429:return{code:2,message:"resource_exhausted"};case 499:return{code:2,message:"cancelled"};default:return{code:2,message:"invalid_argument"}}if(Z>=500&&Z<600)switch(Z){case 501:return{code:2,message:"unimplemented"};case 503:return{code:2,message:"unavailable"};case 504:return{code:2,message:"deadline_exceeded"};default:return{code:2,message:"internal_error"}}return{code:2,message:"internal_error"}}function SW(Z,J){Z.setAttribute("http.response.status_code",J);let X=d9(J);if(X.message!=="unknown_error")Z.setStatus(X)}var Ah="_sentryScope",Th="_sentryIsolationScope";function Rq0(Z){try{let J=Q0.WeakRef;if(typeof J==="function")return new J(Z)}catch{}return Z}function Pq0(Z){if(!Z)return;if(typeof Z==="object"&&"deref"in Z&&typeof Z.deref==="function")try{return Z.deref()}catch{return}return Z}function a$(Z,J,X){if(Z)f1(Z,Th,Rq0(X)),f1(Z,Ah,J)}function A8(Z){let J=Z;return{scope:J[Ah],isolationScope:Pq0(J[Th])}}var r$="sentry-",Ch=/^sentry-/,Nh=8192;function T8(Z){let J=HZ(Z);if(!J)return;let X=Object.entries(J).reduce(($,[Y,Q])=>{if(Y.match(Ch)){let W=Y.slice(r$.length);$[W]=Q}return $},{});if(Object.keys(X).length>0)return X;else return}function GZ(Z){if(!Z)return;let J=Object.entries(Z).reduce((X,[$,Y])=>{if(Y)X[`${r$}${$}`]=Y;return X},{});return kW(J)}function HZ(Z){if(!Z||!x9(Z)&&!Array.isArray(Z))return;if(Array.isArray(Z))return Z.reduce((J,X)=>{let $=qh(X);return Object.entries($).forEach(([Y,Q])=>{J[Y]=Q}),J},{});return qh(Z)}function qh(Z){return Z.split(",").map((J)=>{let X=J.indexOf("=");if(X===-1)return[];let $=J.slice(0,X),Y=J.slice(X+1);return[$,Y].map((Q)=>{try{return decodeURIComponent(Q.trim())}catch{return}})}).reduce((J,[X,$])=>{if(X&&$)J[X]=$;return J},{})}function kW(Z){if(Object.keys(Z).length===0)return;return Object.entries(Z).reduce((J,[X,$],Y)=>{let Q=`${encodeURIComponent(X)}=${encodeURIComponent($)}`,W=Y===0?Q:`${J},${Q}`;if(W.length>Nh)return l&&A.warn(`Not adding key: ${X} with val: ${$} to baggage header due to exceeding baggage size limits.`),J;else return W},"")}var Eq0=/^o(\d+)\./,Iq0=/^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)((?:\[[:.%\w]+\]|[\w.-]+))(?::(\d+))?\/(.+)/;function yq0(Z){return Z==="http"||Z==="https"}function U6(Z,J=!1){let{host:X,path:$,pass:Y,port:Q,projectId:W,protocol:K,publicKey:z}=Z;return`${K}://${z}${J&&Y?`:${Y}`:""}@${X}${Q?`:${Q}`:""}/${$?`${$}/`:$}${W}`}function Sq0(Z){let J=Iq0.exec(Z);if(!J){y1(()=>{console.error(`Invalid Sentry Dsn: ${Z}`)});return}let[X,$,Y="",Q="",W="",K=""]=J.slice(1),z="",G=K,H=G.split("/");if(H.length>1)z=H.slice(0,-1).join("/"),G=H.pop();if(G){let V=G.match(/^\d+/);if(V)G=V[0]}return Rh({host:Q,pass:Y,path:z,projectId:G,port:W,protocol:X,publicKey:$})}function Rh(Z){return{protocol:Z.protocol,publicKey:Z.publicKey||"",pass:Z.pass||"",host:Z.host,port:Z.port||"",path:Z.path||"",projectId:Z.projectId}}function kq0(Z){if(!l)return!0;let{port:J,projectId:X,protocol:$}=Z;if(["protocol","publicKey","host","projectId"].find((W)=>{if(!Z[W])return A.error(`Invalid Sentry Dsn: ${W} missing`),!0;return!1}))return!1;if(!X.match(/^\d+$/))return A.error(`Invalid Sentry Dsn: Invalid projectId ${X}`),!1;if(!yq0($))return A.error(`Invalid Sentry Dsn: Invalid protocol ${$}`),!1;if(J&&isNaN(parseInt(J,10)))return A.error(`Invalid Sentry Dsn: Invalid port ${J}`),!1;return!0}function xq0(Z){return Z.match(Eq0)?.[1]}function xW(Z){let J=Z.getOptions(),{host:X}=Z.getDsn()||{},$;if(J.orgId)$=String(J.orgId);else if(X)$=xq0(X);return $}function Ph(Z){let J=typeof Z==="string"?Sq0(Z):Rh(Z);if(!J||!kq0(J))return;return J}function L6(Z){if(typeof Z==="boolean")return Number(Z);let J=typeof Z==="string"?parseFloat(Z):Z;if(typeof J!=="number"||isNaN(J)||J<0||J>1)return;return J}var s$=new RegExp("^[ \\t]*([0-9a-f]{32})?-?([0-9a-f]{16})?-?([01])?[ \\t]*$");function Eh(Z){if(!Z)return;let J=Z.match(s$);if(!J)return;let X;if(J[3]==="1")X=!0;else if(J[3]==="0")X=!1;return{traceId:J[1],parentSampled:X,parentSpanId:J[2]}}function VZ(Z,J){let X=Eh(Z),$=T8(J);if(!X?.traceId)return{traceId:a4(),sampleRand:K4()};let Y=vq0(X,$);if($)$.sample_rand=Y.toString();let{traceId:Q,parentSpanId:W,parentSampled:K}=X;return{traceId:Q,parentSpanId:W,sampled:K,dsc:$||{},sampleRand:Y}}function u9(Z=a4(),J=r4(),X){let $="";if(X!==void 0)$=X?"-1":"-0";return`${Z}-${J}${$}`}function c9(Z=a4(),J=r4(),X){return`00-${Z}-${J}-${X?"01":"00"}`}function vq0(Z,J){let X=L6(J?.sample_rand);if(X!==void 0)return X;let $=L6(J?.sample_rate);if($&&Z?.parentSampled!==void 0)return Z.parentSampled?K4()*$:$+K4()*(1-$);else return K4()}function t$(Z,J){let X=xW(Z);if(J&&X&&J!==X)return A.log(`Won't continue trace because org IDs don't match (incoming baggage: ${J}, SDK options: ${X})`),!1;if(Z.getOptions().strictTraceContinuation||!1){if(J&&!X||!J&&X)return A.log(`Starting a new trace because strict trace continuation is enabled but one org ID is missing (incoming baggage: ${J}, Sentry client: ${X})`),!1}return!0}var vW=0,hW=1,Ih=!1;function Sh(Z){let{spanId:J,traceId:X}=Z.spanContext(),{data:$,op:Y,parent_span_id:Q,status:W,origin:K,links:z}=J0(Z);return{parent_span_id:Q,span_id:J,trace_id:X,data:$,op:Y,status:W,origin:K,links:z}}function l9(Z){let{spanId:J,traceId:X,isRemote:$}=Z.spanContext(),Y=$?J:J0(Z).parent_span_id,Q=A8(Z).scope,W=$?Q?.getPropagationContext().propagationSpanId||r4():J;return{parent_span_id:Y,span_id:W,trace_id:X}}function fW(Z){let{traceId:J,spanId:X}=Z.spanContext(),$=q8(Z);return u9(J,X,$)}function kh(Z){let{traceId:J,spanId:X}=Z.spanContext(),$=q8(Z);return c9(J,X,$)}function FZ(Z){if(Z&&Z.length>0)return Z.map(({context:{spanId:J,traceId:X,traceFlags:$,...Y},attributes:Q})=>({span_id:J,trace_id:X,sampled:$===hW,attributes:Q,...Y}));else return}function t4(Z){if(typeof Z==="number")return yh(Z);if(Array.isArray(Z))return Z[0]+Z[1]/1e9;if(Z instanceof Date)return yh(Z.getTime());return b9()}function yh(Z){return Z>9999999999?Z/1000:Z}function J0(Z){if(fq0(Z))return Z.getSpanJSON();let{spanId:J,traceId:X}=Z.spanContext();if(hq0(Z)){let{attributes:$,startTime:Y,name:Q,endTime:W,status:K,links:z}=Z,G="parentSpanId"in Z?Z.parentSpanId:("parentSpanContext"in Z)?Z.parentSpanContext?.spanId:void 0;return{span_id:J,trace_id:X,data:$,description:Q,parent_span_id:G,start_timestamp:t4(Y),timestamp:t4(W)||void 0,status:BZ(K),op:$[K0],origin:$[X0],links:FZ(z)}}return{span_id:J,trace_id:X,start_timestamp:0,data:{}}}function hq0(Z){let J=Z;return!!J.attributes&&!!J.startTime&&!!J.name&&!!J.endTime&&!!J.status}function fq0(Z){return typeof Z.getSpanJSON==="function"}function q8(Z){let{traceFlags:J}=Z.spanContext();return J===hW}function BZ(Z){if(!Z||Z.code===hB)return;if(Z.code===gJ)return"ok";return Z.message||"internal_error"}var e$="_sentryChildSpans",fB="_sentryRootSpan";function mJ(Z,J){let X=Z[fB]||Z;if(f1(J,fB,X),Z[e$])Z[e$].add(J);else f1(Z,e$,new Set([J]))}function bW(Z){let J=new Set;function X($){if(J.has($))return;else if(q8($)){J.add($);let Y=$[e$]?Array.from($[e$]):[];for(let Q of Y)X(Q)}}return X(Z),Array.from(J)}function q1(Z){return Z[fB]||Z}function t8(){let Z=O4(),J=b6(Z);if(J.getActiveSpan)return J.getActiveSpan();return WZ(u0())}function ZY(){if(!Ih)y1(()=>{console.warn("[Sentry] Returning null from `beforeSendSpan` is disallowed. To drop certain spans, configure the respective integrations directly or use `ignoreSpans`.")}),Ih=!0}var xh=!1;function vh(){if(xh)return;function Z(){let J=t8(),X=J&&q1(J);if(X)l&&A.log("[Tracing] Root span: internal_error -> Global error occurred"),X.setStatus({code:A0,message:"internal_error"})}Z.tag="sentry_tracingErrorCallback",xh=!0,Kh(Z),zh(Z)}function L1(Z){if(typeof __SENTRY_TRACING__==="boolean"&&!__SENTRY_TRACING__)return!1;let J=Z||u()?.getOptions();return!!J&&(J.tracesSampleRate!=null||!!J.tracesSampler)}function hh(Z){A.log(`Ignoring span ${Z.op} - ${Z.description} because it matches \`ignoreSpans\`.`)}function JY(Z,J){if(!J?.length||!Z.description)return!1;for(let X of J){if(bq0(X)){if(u5(Z.description,X))return l&&hh(Z),!0;continue}if(!X.name&&!X.op)continue;let $=X.name?u5(Z.description,X.name):!0,Y=X.op?Z.op&&u5(Z.op,X.op):!0;if($&&Y)return l&&hh(Z),!0}return!1}function fh(Z,J){let{parent_span_id:X,span_id:$}=J;if(!X)return;for(let Y of Z)if(Y.parent_span_id===$)Y.parent_span_id=X}function bq0(Z){return typeof Z==="string"||Z instanceof RegExp}var dJ="production";var bh="_frozenDsc";function gW(Z,J){f1(Z,bh,J)}function bB(Z,J){let X=J.getOptions(),{publicKey:$}=J.getDsn()||{},Y={environment:X.environment||dJ,release:X.release,public_key:$,trace_id:Z,org_id:xW(J)};return J.emit("createDsc",Y),Y}function e8(Z,J){let X=J.getPropagationContext();return X.dsc||bB(X.traceId,Z)}function S1(Z){let J=u();if(!J)return{};let X=q1(Z),$=J0(X),Y=$.data,Q=X.spanContext().traceState,W=Q?.get("sentry.sample_rate")??Y[M8]??Y[EB];function K(U){if(typeof W==="number"||typeof W==="string")U.sample_rate=`${W}`;return U}let z=X[bh];if(z)return K(z);let G=Q?.get("sentry.dsc"),H=G&&T8(G);if(H)return K(H);let V=bB(Z.spanContext().traceId,J),F=Y[U1],B=$.description;if(F!=="url"&&B)V.transaction=B;if(L1())V.sampled=String(q8(X)),V.sample_rand=Q?.get("sentry.sample_rand")??A8(X).scope?.getPropagationContext().sampleRand.toString();return K(V),J.emit("createDsc",V,X),V}class uJ{constructor(Z={}){this._traceId=Z.traceId||a4(),this._spanId=Z.spanId||r4()}spanContext(){return{spanId:this._spanId,traceId:this._traceId,traceFlags:vW}}end(Z){}setAttribute(Z,J){return this}setAttributes(Z){return this}setStatus(Z){return this}updateName(Z){return this}isRecording(){return!1}addEvent(Z,J,X){return this}addLink(Z){return this}addLinks(Z){return this}recordException(Z,J){}}function C8(Z,J=100,X=1/0){try{return gB("",Z,J,X)}catch($){return{ERROR:`**non-serializable** (${$})`}}}function mB(Z,J=3,X=102400){let $=C8(Z,J);if(uq0($)>X)return mB(Z,J-1,X);return $}function gB(Z,J,X=1/0,$=1/0,Y=cq0()){let[Q,W]=Y;if(J==null||["boolean","string"].includes(typeof J)||typeof J==="number"&&Number.isFinite(J))return J;let K=gq0(Z,J);if(!K.startsWith("[object "))return K;if(J.__sentry_skip_normalization__)return J;let z=typeof J.__sentry_override_normalization_depth__==="number"?J.__sentry_override_normalization_depth__:X;if(z===0)return K.replace("object ","");if(Q(J))return"[Circular ~]";let G=J;if(G&&typeof G.toJSON==="function")try{let B=G.toJSON();return gB("",B,z-1,$,Y)}catch{}let H=Array.isArray(J)?[]:{},V=0,F=EW(J);for(let B in F){if(!Object.prototype.hasOwnProperty.call(F,B))continue;if(V>=$){H[B]="[MaxProperties ~]";break}let U=F[B];H[B]=gB(B,U,z-1,$,Y),V++}return W(J),H}function gq0(Z,J){try{if(Z==="domain"&&J&&typeof J==="object"&&J._events)return"[Domain]";if(Z==="domainEmitter")return"[DomainEmitter]";if(typeof global<"u"&&J===global)return"[Global]";if(typeof window<"u"&&J===window)return"[Window]";if(typeof document<"u"&&J===document)return"[Document]";if(o$(J))return NW(J);if(_B(J))return"[SyntheticEvent]";if(typeof J==="number"&&!Number.isFinite(J))return`[${J}]`;if(typeof J==="function")return`[Function: ${i$(J)}]`;if(typeof J==="symbol")return`[${String(J)}]`;if(typeof J==="bigint")return`[BigInt: ${String(J)}]`;let X=mq0(J);if(/^HTML(\w*)Element$/.test(X))return`[HTMLElement: ${X}]`;return`[object ${X}]`}catch(X){return`**non-serializable** (${X})`}}function mq0(Z){let J=Object.getPrototypeOf(Z);return J?.constructor?J.constructor.name:"null prototype"}function dq0(Z){return~-encodeURI(Z).split(/%..|./).length}function uq0(Z){return dq0(JSON.stringify(Z))}function cq0(){let Z=new WeakSet;function J($){if(Z.has($))return!0;return Z.add($),!1}function X($){Z.delete($)}return[J,X]}function S4(Z,J=[]){return[Z,J]}function uB(Z,J){let[X,$]=Z;return[X,[...$,J]]}function XY(Z,J){let X=Z[1];for(let $ of X){let Y=$[0].type;if(J($,Y))return!0}return!1}function cB(Z,J){return XY(Z,(X,$)=>J.includes($))}function dB(Z){let J=k9(Q0);return J.encodePolyfill?J.encodePolyfill(Z):new TextEncoder().encode(Z)}function $Y(Z){let[J,X]=Z,$=JSON.stringify(J);function Y(Q){if(typeof $==="string")$=typeof Q==="string"?$+Q:[dB($),Q];else $.push(typeof Q==="string"?dB(Q):Q)}for(let Q of X){let[W,K]=Q;if(Y(`
29
29
  ${JSON.stringify(W)}
30
30
  `),typeof K==="string"||K instanceof Uint8Array)Y(K);else{let z;try{z=JSON.stringify(K)}catch{z=JSON.stringify(C8(K))}Y(z)}}return typeof $==="string"?$:lq0($)}function lq0(Z){let J=Z.reduce((Y,Q)=>Y+Q.length,0),X=new Uint8Array(J),$=0;for(let Y of Z)X.set(Y,$),$+=Y.length;return X}function lB(Z){return[{type:"span"},Z]}function pB(Z){let J=typeof Z.data==="string"?dB(Z.data):Z.data;return[{type:"attachment",length:J.length,filename:Z.filename,content_type:Z.contentType,attachment_type:Z.attachmentType},J]}var pq0={session:"session",sessions:"session",attachment:"attachment",transaction:"transaction",event:"error",client_report:"internal",user_report:"default",profile:"profile",profile_chunk:"profile",replay_event:"replay",replay_recording:"replay",check_in:"monitor",feedback:"feedback",span:"span",raw_security:"security",log:"log_item",metric:"metric",trace_metric:"metric"};function mW(Z){return pq0[Z]}function dW(Z){if(!Z?.sdk)return;let{name:J,version:X}=Z.sdk;return{name:J,version:X}}function iB(Z,J,X,$){let Y=Z.sdkProcessingMetadata?.dynamicSamplingContext;return{event_id:Z.event_id,sent_at:new Date().toISOString(),...J&&{sdk:J},...!!X&&$&&{dsn:U6($)},...Y&&{trace:Y}}}function iq0(Z,J){if(!J)return Z;let X=Z.sdk||{};return Z.sdk={...X,name:X.name||J.name,version:X.version||J.version,integrations:[...Z.sdk?.integrations||[],...J.integrations||[]],packages:[...Z.sdk?.packages||[],...J.packages||[]],settings:Z.sdk?.settings||J.settings?{...Z.sdk?.settings,...J.settings}:void 0},Z}function gh(Z,J,X,$){let Y=dW(X),Q={sent_at:new Date().toISOString(),...Y&&{sdk:Y},...!!$&&J&&{dsn:U6(J)}},W="aggregates"in Z?[{type:"sessions"},Z]:[{type:"session"},Z.toJSON()];return S4(Q,[W])}function mh(Z,J,X,$){let Y=dW(X),Q=Z.type&&Z.type!=="replay_event"?Z.type:"event";iq0(Z,X?.sdk);let W=iB(Z,Y,$,J);return delete Z.sdkProcessingMetadata,S4(W,[[{type:Q},Z]])}function dh(Z,J){function X(B){return!!B.trace_id&&!!B.public_key}let $=S1(Z[0]),Y=J?.getDsn(),Q=J?.getOptions().tunnel,W={sent_at:new Date().toISOString(),...X($)&&{trace:$},...!!Q&&Y&&{dsn:U6(Y)}},{beforeSendSpan:K,ignoreSpans:z}=J?.getOptions()||{},G=z?.length?Z.filter((B)=>!JY(J0(B),z)):Z,H=Z.length-G.length;if(H)J?.recordDroppedEvent("before_send","span",H);let V=K?(B)=>{let U=J0(B),D=K(U);if(!D)return ZY(),U;return D}:J0,F=[];for(let B of G){let U=V(B);if(U)F.push(lB(U))}return S4(W,F)}function YY(Z){if(!l)return;let{description:J="< unknown name >",op:X="< unknown op >",parent_span_id:$}=J0(Z),{spanId:Y}=Z.spanContext(),Q=q8(Z),W=q1(Z),K=W===Z,z=`[Tracing] Starting ${Q?"sampled":"unsampled"} ${K?"root ":""}span`,G=[`op: ${X}`,`name: ${J}`,`ID: ${Y}`];if($)G.push(`parent ID: ${$}`);if(!K){let{op:H,description:V}=J0(W);if(G.push(`root ID: ${W.spanContext().spanId}`),H)G.push(`root op: ${H}`);if(V)G.push(`root description: ${V}`)}A.log(`${z}
31
31
  ${G.join(`
32
- `)}`)}function QY(Z){if(!l)return;let{description:J="< unknown name >",op:X="< unknown op >"}=J0(Z),{spanId:$}=Z.spanContext(),Q=q1(Z)===Z,W=`[Tracing] Finishing "${X}" ${Q?"root ":""}span "${J}" with ID ${$}`;A.log(W)}function UZ(Z){if(!Z||Z.length===0)return;let J={};return Z.forEach((X)=>{let $=X.attributes||{},Y=$[IB],Q=$[yB];if(typeof Y==="string"&&typeof Q==="number")J[X.name]={value:Q,unit:Y}}),J}var uh=1000;class WY{constructor(Z={}){if(this._traceId=Z.traceId||a4(),this._spanId=Z.spanId||r4(),this._startTime=Z.startTimestamp||b9(),this._links=Z.links,this._attributes={},this.setAttributes({[X0]:"manual",[K0]:Z.op,...Z.attributes}),this._name=Z.name,Z.parentSpanId)this._parentSpanId=Z.parentSpanId;if("sampled"in Z)this._sampled=Z.sampled;if(Z.endTimestamp)this._endTime=Z.endTimestamp;if(this._events=[],this._isStandaloneSpan=Z.isStandalone,this._endTime)this._onSpanEnded()}addLink(Z){if(this._links)this._links.push(Z);else this._links=[Z];return this}addLinks(Z){if(this._links)this._links.push(...Z);else this._links=Z;return this}recordException(Z,J){}spanContext(){let{_spanId:Z,_traceId:J,_sampled:X}=this;return{spanId:Z,traceId:J,traceFlags:X?hW:vW}}setAttribute(Z,J){if(J===void 0)delete this._attributes[Z];else this._attributes[Z]=J;return this}setAttributes(Z){return Object.keys(Z).forEach((J)=>this.setAttribute(J,Z[J])),this}updateStartTime(Z){this._startTime=t4(Z)}setStatus(Z){return this._status=Z,this}updateName(Z){return this._name=Z,this.setAttribute(U1,"custom"),this}end(Z){if(this._endTime)return;this._endTime=t4(Z),QY(this),this._onSpanEnded()}getSpanJSON(){return{data:this._attributes,description:this._name,op:this._attributes[K0],parent_span_id:this._parentSpanId,span_id:this._spanId,start_timestamp:this._startTime,status:BZ(this._status),timestamp:this._endTime,trace_id:this._traceId,origin:this._attributes[X0],profile_id:this._attributes[fJ],exclusive_time:this._attributes[bJ],measurements:UZ(this._events),is_segment:this._isStandaloneSpan&&q1(this)===this||void 0,segment_id:this._isStandaloneSpan?q1(this).spanContext().spanId:void 0,links:FZ(this._links)}}isRecording(){return!this._endTime&&!!this._sampled}addEvent(Z,J,X){l&&A.log("[Tracing] Adding an event to span:",Z);let $=ch(J)?J:X||b9(),Y=ch(J)?{}:J||{},Q={name:Z,time:t4($),attributes:Y};return this._events.push(Q),this}isStandaloneSpan(){return!!this._isStandaloneSpan}_onSpanEnded(){let Z=u();if(Z)Z.emit("spanEnd",this);if(!(this._isStandaloneSpan||this===q1(this)))return;if(this._isStandaloneSpan){if(this._sampled)oq0(dh([this],Z));else if(l&&A.log("[Tracing] Discarding standalone span because its trace was not chosen to be sampled."),Z)Z.recordDroppedEvent("sample_rate","span");return}let X=this._convertSpanToTransaction();if(X)(A8(this).scope||u0()).captureEvent(X)}_convertSpanToTransaction(){if(!lh(J0(this)))return;if(!this._name)l&&A.warn("Transaction has no name, falling back to `<unlabeled transaction>`."),this._name="<unlabeled transaction>";let{scope:Z,isolationScope:J}=A8(this),X=Z?.getScopeData().sdkProcessingMetadata?.normalizedRequest;if(this._sampled!==!0)return;let Y=bW(this).filter((G)=>G!==this&&!nq0(G)).map((G)=>J0(G)).filter(lh),Q=this._attributes[U1];delete this._attributes[s8],Y.forEach((G)=>{delete G.data[s8]});let W={contexts:{trace:Sh(this)},spans:Y.length>uh?Y.sort((G,H)=>G.start_timestamp-H.start_timestamp).slice(0,uh):Y,start_timestamp:this._startTime,timestamp:this._endTime,transaction:this._name,type:"transaction",sdkProcessingMetadata:{capturedSpanScope:Z,capturedSpanIsolationScope:J,dynamicSamplingContext:S1(this)},request:X,...Q&&{transaction_info:{source:Q}}},K=UZ(this._events);if(K&&Object.keys(K).length)l&&A.log("[Measurements] Adding measurements to transaction event",JSON.stringify(K,void 0,2)),W.measurements=K;return W}}function ch(Z){return Z&&typeof Z==="number"||Z instanceof Date||Array.isArray(Z)}function lh(Z){return!!Z.start_timestamp&&!!Z.timestamp&&!!Z.span_id&&!!Z.trace_id}function nq0(Z){return Z instanceof WY&&Z.isStandaloneSpan()}function oq0(Z){let J=u();if(!J)return;let X=Z[1];if(!X||X.length===0){J.recordDroppedEvent("before_send","span");return}J.sendEnvelope(Z)}function D6(Z,J,X=()=>{},$=()=>{}){let Y;try{Y=Z()}catch(Q){throw J(Q),X(),Q}return aq0(Y,J,X,$)}function aq0(Z,J,X,$){if(I4(Z))return Z.then((Y)=>{return X(),$(Y),Y},(Y)=>{throw J(Y),X(),Y});return X(),$(Z),Z}function KY(Z,J,X){if(!L1(Z))return[!1];let $=void 0,Y;if(typeof Z.tracesSampler==="function")Y=Z.tracesSampler({...J,inheritOrSampleWith:(K)=>{if(typeof J.parentSampleRate==="number")return J.parentSampleRate;if(typeof J.parentSampled==="boolean")return Number(J.parentSampled);return K}}),$=!0;else if(J.parentSampled!==void 0)Y=J.parentSampled;else if(typeof Z.tracesSampleRate<"u")Y=Z.tracesSampleRate,$=!0;let Q=L6(Y);if(Q===void 0)return l&&A.warn(`[Tracing] Discarding root span because of invalid sample rate. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(Y)} of type ${JSON.stringify(typeof Y)}.`),[!1];if(!Q)return l&&A.log(`[Tracing] Discarding transaction because ${typeof Z.tracesSampler==="function"?"tracesSampler returned 0 or false":"a negative sampling decision was inherited or tracesSampleRate is set to 0"}`),[!1,Q,$];let W=X<Q;if(!W)l&&A.log(`[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = ${Number(Y)})`);return[W,Q,$]}var uW="__SENTRY_SUPPRESS_TRACING__";function _6(Z,J){let X=lW();if(X.startSpan)return X.startSpan(Z,J);let $=nh(Z),{forceTransaction:Y,parentSpan:Q,scope:W}=Z,K=W?.clone();return s4(K,()=>{return ah(Q)(()=>{let G=u0(),H=oh(G,Q),F=Z.onlyIfParent&&!H?new uJ:ih({parentSpan:H,spanArguments:$,forceTransaction:Y,scope:G});return m9(G,F),D6(()=>J(F),()=>{let{status:B}=J0(F);if(F.isRecording()&&(!B||B==="ok"))F.setStatus({code:A0,message:"internal_error"})},()=>{F.end()})})})}function z4(Z,J){let X=lW();if(X.startSpanManual)return X.startSpanManual(Z,J);let $=nh(Z),{forceTransaction:Y,parentSpan:Q,scope:W}=Z,K=W?.clone();return s4(K,()=>{return ah(Q)(()=>{let G=u0(),H=oh(G,Q),F=Z.onlyIfParent&&!H?new uJ:ih({parentSpan:H,spanArguments:$,forceTransaction:Y,scope:G});return m9(G,F),D6(()=>J(F,()=>F.end()),()=>{let{status:B}=J0(F);if(F.isRecording()&&(!B||B==="ok"))F.setStatus({code:A0,message:"internal_error"})})})})}var cW=(Z,J)=>{let X=O4(),$=b6(X);if($.continueTrace)return $.continueTrace(Z,J);let{sentryTrace:Y,baggage:Q}=Z,W=u(),K=T8(Q);if(W&&!t$(W,K?.org_id))return nB(J);return s4((z)=>{let G=VZ(Y,Q);return z.setPropagationContext(G),m9(z,void 0),J()})};function cJ(Z,J){let X=lW();if(X.withActiveSpan)return X.withActiveSpan(Z,J);return s4(($)=>{return m9($,Z||void 0),J($)})}function p9(Z){let J=lW();if(J.suppressTracing)return J.suppressTracing(Z);return s4((X)=>{X.setSDKProcessingMetadata({[uW]:!0});let $=Z();return X.setSDKProcessingMetadata({[uW]:void 0}),$})}function nB(Z){return s4((J)=>{return J.setPropagationContext({traceId:a4(),sampleRand:K4()}),l&&A.log(`Starting a new trace with id ${J.getPropagationContext().traceId}`),cJ(null,Z)})}function ih({parentSpan:Z,spanArguments:J,forceTransaction:X,scope:$}){if(!L1()){let W=new uJ;if(X||!Z){let K={sampled:"false",sample_rate:"0",transaction:J.name,...S1(W)};gW(W,K)}return W}let Y=R0(),Q;if(Z&&!X)Q=rq0(Z,$,J),mJ(Z,Q);else if(Z){let W=S1(Z),{traceId:K,spanId:z}=Z.spanContext(),G=q8(Z);Q=ph({traceId:K,parentSpanId:z,...J},$,G),gW(Q,W)}else{let{traceId:W,dsc:K,parentSpanId:z,sampled:G}={...Y.getPropagationContext(),...$.getPropagationContext()};if(Q=ph({traceId:W,parentSpanId:z,...J},$,G),K)gW(Q,K)}return YY(Q),a$(Q,$,Y),Q}function nh(Z){let X={isStandalone:(Z.experimental||{}).standalone,...Z};if(Z.startTime){let $={...X};return $.startTimestamp=t4(Z.startTime),delete $.startTime,$}return X}function lW(){let Z=O4();return b6(Z)}function ph(Z,J,X){let $=u(),Y=$?.getOptions()||{},{name:Q=""}=Z,W={spanAttributes:{...Z.attributes},spanName:Q,parentSampled:X};$?.emit("beforeSampling",W,{decision:!1});let K=W.parentSampled??X,z=W.spanAttributes,G=J.getPropagationContext(),[H,V,F]=J.getScopeData().sdkProcessingMetadata[uW]?[!1]:KY(Y,{name:Q,parentSampled:K,attributes:z,parentSampleRate:L6(G.dsc?.sample_rate)},G.sampleRand),B=new WY({...Z,attributes:{[U1]:"custom",[M8]:V!==void 0&&F?V:void 0,...z},sampled:H});if(!H&&$)l&&A.log("[Tracing] Discarding root span because its trace was not chosen to be sampled."),$.recordDroppedEvent("sample_rate","transaction");if($)$.emit("spanStart",B);return B}function rq0(Z,J,X){let{spanId:$,traceId:Y}=Z.spanContext(),Q=J.getScopeData().sdkProcessingMetadata[uW]?!1:q8(Z),W=Q?new WY({...X,parentSpanId:$,traceId:Y,sampled:Q}):new uJ({traceId:Y});mJ(Z,W);let K=u();if(K){if(K.emit("spanStart",W),X.endTimestamp)K.emit("spanEnd",W)}return W}function oh(Z,J){if(J)return J;if(J===null)return;let X=WZ(Z);if(!X)return;let $=u();if(($?$.getOptions():{}).parentSpanIsAlwaysRootSpan)return q1(X);return X}function ah(Z){return Z!==void 0?(J)=>{return cJ(Z,J)}:(J)=>J()}var oB=0,rh=1,sh=2;function LZ(Z){return new zY((J)=>{J(Z)})}function lJ(Z){return new zY((J,X)=>{X(Z)})}class zY{constructor(Z){this._state=oB,this._handlers=[],this._runExecutor(Z)}then(Z,J){return new zY((X,$)=>{this._handlers.push([!1,(Y)=>{if(!Z)X(Y);else try{X(Z(Y))}catch(Q){$(Q)}},(Y)=>{if(!J)$(Y);else try{X(J(Y))}catch(Q){$(Q)}}]),this._executeHandlers()})}catch(Z){return this.then((J)=>J,Z)}finally(Z){return new zY((J,X)=>{let $,Y;return this.then((Q)=>{if(Y=!1,$=Q,Z)Z()},(Q)=>{if(Y=!0,$=Q,Z)Z()}).then(()=>{if(Y){X($);return}J($)})})}_executeHandlers(){if(this._state===oB)return;let Z=this._handlers.slice();this._handlers=[],Z.forEach((J)=>{if(J[0])return;if(this._state===rh)J[1](this._value);if(this._state===sh)J[2](this._value);J[0]=!0})}_runExecutor(Z){let J=(Y,Q)=>{if(this._state!==oB)return;if(I4(Q)){Q.then(X,$);return}this._state=Y,this._value=Q,this._executeHandlers()},X=(Y)=>{J(rh,Y)},$=(Y)=>{J(sh,Y)};try{Z(X,$)}catch(Y){$(Y)}}}function th(Z,J,X,$=0){try{let Y=aB(J,X,Z,$);return I4(Y)?Y:LZ(Y)}catch(Y){return lJ(Y)}}function aB(Z,J,X,$){let Y=X[$];if(!Z||!Y)return Z;let Q=Y({...Z},J);if(l&&Q===null&&A.log(`Event processor "${Y.id||"?"}" dropped event`),I4(Q))return Q.then((W)=>aB(W,J,X,$+1));return aB(Q,J,X,$+1)}var DZ,eh,Zf,i9;function Jf(Z){let J=Q0._sentryDebugIds,X=Q0._debugIds;if(!J&&!X)return{};let $=J?Object.keys(J):[],Y=X?Object.keys(X):[];if(i9&&$.length===eh&&Y.length===Zf)return i9;if(eh=$.length,Zf=Y.length,i9={},!DZ)DZ={};let Q=(W,K)=>{for(let z of W){let G=K[z],H=DZ?.[z];if(H&&i9&&G){if(i9[H[0]]=G,DZ)DZ[z]=[H[0],G]}else if(G){let V=Z(z);for(let F=V.length-1;F>=0;F--){let U=V[F]?.filename;if(U&&i9&&DZ){i9[U]=G,DZ[z]=[U,G];break}}}}};if(J)Q($,J);if(X)Q(Y,X);return i9}function $f(Z,J){let{fingerprint:X,span:$,breadcrumbs:Y,sdkProcessingMetadata:Q}=J;if(sq0(Z,J),$)ZC0(Z,$);JC0(Z,X),tq0(Z,Y),eq0(Z,Q)}function Xf(Z,J){let{extra:X,tags:$,attributes:Y,user:Q,contexts:W,level:K,sdkProcessingMetadata:z,breadcrumbs:G,fingerprint:H,eventProcessors:V,attachments:F,propagationContext:B,transactionName:U,span:D}=J;if(GY(Z,"extra",X),GY(Z,"tags",$),GY(Z,"attributes",Y),GY(Z,"user",Q),GY(Z,"contexts",W),Z.sdkProcessingMetadata=g9(Z.sdkProcessingMetadata,z,2),K)Z.level=K;if(U)Z.transactionName=U;if(D)Z.span=D;if(G.length)Z.breadcrumbs=[...Z.breadcrumbs,...G];if(H.length)Z.fingerprint=[...Z.fingerprint,...H];if(V.length)Z.eventProcessors=[...Z.eventProcessors,...V];if(F.length)Z.attachments=[...Z.attachments,...F];Z.propagationContext={...Z.propagationContext,...B}}function GY(Z,J,X){Z[J]=g9(Z[J],X,1)}function Yf(Z,J){let X=yW().getScopeData();return Z&&Xf(X,Z.getScopeData()),J&&Xf(X,J.getScopeData()),X}function sq0(Z,J){let{extra:X,tags:$,user:Y,contexts:Q,level:W,transactionName:K}=J;if(Object.keys(X).length)Z.extra={...X,...Z.extra};if(Object.keys($).length)Z.tags={...$,...Z.tags};if(Object.keys(Y).length)Z.user={...Y,...Z.user};if(Object.keys(Q).length)Z.contexts={...Q,...Z.contexts};if(W)Z.level=W;if(K&&Z.type!=="transaction")Z.transaction=K}function tq0(Z,J){let X=[...Z.breadcrumbs||[],...J];Z.breadcrumbs=X.length?X:void 0}function eq0(Z,J){Z.sdkProcessingMetadata={...Z.sdkProcessingMetadata,...J}}function ZC0(Z,J){Z.contexts={trace:l9(J),...Z.contexts},Z.sdkProcessingMetadata={dynamicSamplingContext:S1(J),...Z.sdkProcessingMetadata};let X=q1(J),$=J0(X).description;if($&&!Z.transaction&&Z.type==="transaction")Z.transaction=$}function JC0(Z,J){if(Z.fingerprint=Z.fingerprint?Array.isArray(Z.fingerprint)?Z.fingerprint:[Z.fingerprint]:[],J)Z.fingerprint=Z.fingerprint.concat(J);if(!Z.fingerprint.length)delete Z.fingerprint}function Qf(Z,J,X,$,Y,Q){let{normalizeDepth:W=3,normalizeMaxBreadth:K=1000}=Z,z={...J,event_id:J.event_id||X.event_id||c1(),timestamp:J.timestamp||c5()},G=X.integrations||Z.integrations.map((_)=>_.name);if(XC0(z,Z),QC0(z,G),Y)Y.emit("applyFrameMetadata",J);if(J.type===void 0)$C0(z,Z.stackParser);let H=KC0($,X.captureContext);if(X.mechanism)xJ(z,X.mechanism);let V=Y?Y.getEventProcessors():[],F=Yf(Q,H),B=[...X.attachments||[],...F.attachments];if(B.length)X.attachments=B;$f(z,F);let U=[...V,...F.eventProcessors];return th(U,z,X).then((_)=>{if(_)YC0(_);if(typeof W==="number"&&W>0)return WC0(_,W,K);return _})}function XC0(Z,J){let{environment:X,release:$,dist:Y,maxValueLength:Q}=J;if(Z.environment=Z.environment||X||dJ,!Z.release&&$)Z.release=$;if(!Z.dist&&Y)Z.dist=Y;let W=Z.request;if(W?.url&&Q)W.url=v9(W.url,Q);if(Q)Z.exception?.values?.forEach((K)=>{if(K.value)K.value=v9(K.value,Q)})}function $C0(Z,J){let X=Jf(J);Z.exception?.values?.forEach(($)=>{$.stacktrace?.frames?.forEach((Y)=>{if(Y.filename)Y.debug_id=X[Y.filename]})})}function YC0(Z){let J={};if(Z.exception?.values?.forEach(($)=>{$.stacktrace?.frames?.forEach((Y)=>{if(Y.debug_id){if(Y.abs_path)J[Y.abs_path]=Y.debug_id;else if(Y.filename)J[Y.filename]=Y.debug_id;delete Y.debug_id}})}),Object.keys(J).length===0)return;Z.debug_meta=Z.debug_meta||{},Z.debug_meta.images=Z.debug_meta.images||[];let X=Z.debug_meta.images;Object.entries(J).forEach(([$,Y])=>{X.push({type:"sourcemap",code_file:$,debug_id:Y})})}function QC0(Z,J){if(J.length>0)Z.sdk=Z.sdk||{},Z.sdk.integrations=[...Z.sdk.integrations||[],...J]}function WC0(Z,J,X){if(!Z)return null;let $={...Z,...Z.breadcrumbs&&{breadcrumbs:Z.breadcrumbs.map((Y)=>({...Y,...Y.data&&{data:C8(Y.data,J,X)}}))},...Z.user&&{user:C8(Z.user,J,X)},...Z.contexts&&{contexts:C8(Z.contexts,J,X)},...Z.extra&&{extra:C8(Z.extra,J,X)}};if(Z.contexts?.trace&&$.contexts){if($.contexts.trace=Z.contexts.trace,Z.contexts.trace.data)$.contexts.trace.data=C8(Z.contexts.trace.data,J,X)}if(Z.spans)$.spans=Z.spans.map((Y)=>{return{...Y,...Y.data&&{data:C8(Y.data,J,X)}}});if(Z.contexts?.flags&&$.contexts)$.contexts.flags=C8(Z.contexts.flags,3,X);return $}function KC0(Z,J){if(!J)return Z;let X=Z?Z.clone():new y4;return X.update(J),X}function Wf(Z){if(!Z)return;if(zC0(Z))return{captureContext:Z};if(HC0(Z))return{captureContext:Z};return Z}function zC0(Z){return Z instanceof y4||typeof Z==="function"}var GC0=["user","level","extra","contexts","tags","fingerprint","propagationContext"];function HC0(Z){return Object.keys(Z).some((J)=>GC0.includes(J))}function V0(Z,J){return u0().captureException(Z,Wf(J))}function pW(Z,J){return u0().captureEvent(Z,J)}async function iW(Z){let J=u();if(J)return J.flush(Z);return l&&A.warn("Cannot flush events. No client defined."),Promise.resolve(!1)}function nW(){let Z=u();return Z?.getOptions().enabled!==!1&&!!Z?.getTransport()}function oW(Z){let J=R0(),X=u0(),{userAgent:$}=Q0.navigator||{},Y=_h({user:X.getUser()||J.getUser(),...$&&{userAgent:$},...Z}),Q=J.getSession();if(Q?.status==="ok")l5(Q,{status:"exited"});return HY(),J.setSession(Y),Y}function HY(){let Z=R0(),X=u0().getSession()||Z.getSession();if(X)Oh(X);VC0(),Z.setSession()}function VC0(){let Z=R0(),J=u(),X=Z.getSession();if(X&&J)J.captureSession(X)}var FC0="7";function BC0(Z){let J=Z.protocol?`${Z.protocol}:`:"",X=Z.port?`:${Z.port}`:"";return`${J}//${Z.host}${X}${Z.path?`/${Z.path}`:""}/api/`}function UC0(Z){return`${BC0(Z)}${Z.projectId}/envelope/`}function LC0(Z,J){let X={sentry_version:FC0};if(Z.publicKey)X.sentry_key=Z.publicKey;if(J)X.sentry_client=`${J.name}/${J.version}`;return new URLSearchParams(X).toString()}function Kf(Z,J,X){return J?J:`${UC0(Z)}?${LC0(Z,X)}`}var rB=[];function DC0(Z){let J={};return Z.forEach((X)=>{let{name:$}=X,Y=J[$];if(Y&&!Y.isDefaultInstance&&X.isDefaultInstance)return;J[$]=X}),Object.values(J)}function sB(Z){let J=Z.defaultIntegrations||[],X=Z.integrations;J.forEach((Y)=>{Y.isDefaultInstance=!0});let $;if(Array.isArray(X))$=[...J,...X];else if(typeof X==="function"){let Y=X(J);$=Array.isArray(Y)?Y:[Y]}else $=J;return DC0($)}function zf(Z,J){let X={};return J.forEach(($)=>{if($)eB(Z,$,X)}),X}function tB(Z,J){for(let X of J)if(X?.afterAllSetup)X.afterAllSetup(Z)}function eB(Z,J,X){if(X[J.name]){l&&A.log(`Integration skipped because it was already installed: ${J.name}`);return}if(X[J.name]=J,!rB.includes(J.name)&&typeof J.setupOnce==="function")J.setupOnce(),rB.push(J.name);if(J.setup&&typeof J.setup==="function")J.setup(Z);if(typeof J.preprocessEvent==="function"){let $=J.preprocessEvent.bind(J);Z.on("preprocessEvent",(Y,Q)=>$(Y,Q,Z))}if(typeof J.processEvent==="function"){let $=J.processEvent.bind(J),Y=Object.assign((Q,W)=>$(Q,W,Z),{id:J.name});Z.addEventProcessor(Y)}l&&A.log(`Integration installed: ${J.name}`)}function S(Z){return Z}function Gf(Z,J){if(!J)return[void 0,void 0];return s4(J,()=>{let X=t8(),$=X?l9(X):zZ(J);return[X?S1(X):e8(Z,J),$]})}function _C0(Z){return[{type:"log",item_count:Z.length,content_type:"application/vnd.sentry.items.log+json"},{items:Z}]}function Hf(Z,J,X,$){let Y={};if(J?.sdk)Y.sdk={name:J.sdk.name,version:J.sdk.version};if(!!X&&!!$)Y.dsn=U6($);return S4(Y,[_C0(Z)])}function VY(Z,J){let X=J??OC0(Z)??[];if(X.length===0)return;let $=Z.getOptions(),Y=Hf(X,$._metadata,$.tunnel,Z.getDsn());Vf().set(Z,[]),Z.emit("flushLogs"),Z.sendEnvelope(Y)}function OC0(Z){return Vf().get(Z)}function Vf(){return j8("clientToLogBufferMap",()=>new WeakMap)}function wC0(Z){return[{type:"trace_metric",item_count:Z.length,content_type:"application/vnd.sentry.items.trace-metric+json"},{items:Z}]}function Ff(Z,J,X,$){let Y={};if(J?.sdk)Y.sdk={name:J.sdk.name,version:J.sdk.version};if(!!X&&!!$)Y.dsn=U6($);return S4(Y,[wC0(Z)])}function Bf(Z,J){let X=J??jC0(Z)??[];if(X.length===0)return;let $=Z.getOptions(),Y=Ff(X,$._metadata,$.tunnel,Z.getDsn());Uf().set(Z,[]),Z.emit("flushMetrics"),Z.sendEnvelope(Y)}function jC0(Z){return Uf().get(Z)}function Uf(){return j8("clientToMetricBufferMap",()=>new WeakMap)}var FY=Symbol.for("SentryBufferFullError");function aW(Z=100){let J=new Set;function X(){return J.size<Z}function $(W){J.delete(W)}function Y(W){if(!X())return lJ(FY);let K=W();return J.add(K),K.then(()=>$(K),()=>$(K)),K}function Q(W){if(!J.size)return LZ(!0);let K=Promise.allSettled(Array.from(J)).then(()=>!0);if(!W)return K;let z=[K,new Promise((G)=>setTimeout(()=>G(!1),W))];return Promise.race(z)}return{get $(){return Array.from(J)},add:Y,drain:Q}}var MC0=60000;function AC0(Z,J=f6()){let X=parseInt(`${Z}`,10);if(!isNaN(X))return X*1000;let $=Date.parse(`${Z}`);if(!isNaN($))return $-J;return MC0}function TC0(Z,J){return Z[J]||Z.all||0}function Lf(Z,J,X=f6()){return TC0(Z,J)>X}function Df(Z,{statusCode:J,headers:X},$=f6()){let Y={...Z},Q=X?.["x-sentry-rate-limits"],W=X?.["retry-after"];if(Q)for(let K of Q.trim().split(",")){let[z,G,,,H]=K.split(":",5),V=parseInt(z,10),F=(!isNaN(V)?V:60)*1000;if(!G)Y.all=$+F;else for(let B of G.split(";"))if(B==="metric_bucket"){if(!H||H.split(";").includes("custom"))Y[B]=$+F}else Y[B]=$+F}else if(W)Y.all=$+AC0(W,$);else if(J===429)Y.all=$+60000;return Y}var ZU=64;function _Z(Z,J,X=aW(Z.bufferSize||ZU)){let $={},Y=(W)=>X.drain(W);function Q(W){let K=[];if(XY(W,(V,F)=>{let B=mW(F);if(Lf($,B))Z.recordDroppedEvent("ratelimit_backoff",B);else K.push(V)}),K.length===0)return Promise.resolve({});let z=S4(W[0],K),G=(V)=>{if(cB(z,["client_report"])){l&&A.warn(`Dropping client report. Will not send outcomes (reason: ${V}).`);return}XY(z,(F,B)=>{Z.recordDroppedEvent(V,mW(B))})},H=()=>J({body:$Y(z)}).then((V)=>{if(V.statusCode!==void 0&&(V.statusCode<200||V.statusCode>=300))l&&A.warn(`Sentry responded with status code ${V.statusCode} to sent event.`);return $=Df($,V),V},(V)=>{throw G("network_error"),l&&A.error("Encountered error running transport request:",V),V});return X.add(H).then((V)=>V,(V)=>{if(V===FY)return l&&A.error("Skipped sending event because buffer is full."),G("queue_overflow"),Promise.resolve({});else throw V})}return{send:Q,flush:Y}}function _f(Z,J,X){let $=[{type:"client_report"},{timestamp:X||c5(),discarded_events:Z}];return S4(J?{dsn:J}:{},[$])}function rW(Z){let J=[];if(Z.message)J.push(Z.message);try{let X=Z.exception.values[Z.exception.values.length-1];if(X?.value){if(J.push(X.value),X.type)J.push(`${X.type}: ${X.value}`)}}catch{}return J}function Of(Z){let{trace_id:J,parent_span_id:X,span_id:$,status:Y,origin:Q,data:W,op:K}=Z.contexts?.trace??{};return{data:W??{},description:Z.transaction,op:K,parent_span_id:X,span_id:$??"",start_timestamp:Z.start_timestamp??0,status:Y,timestamp:Z.timestamp,trace_id:J??"",origin:Q,profile_id:W?.[fJ],exclusive_time:W?.[bJ],measurements:Z.measurements,is_segment:!0}}function wf(Z){return{type:"transaction",timestamp:Z.timestamp,start_timestamp:Z.start_timestamp,transaction:Z.description,contexts:{trace:{trace_id:Z.trace_id,span_id:Z.span_id,parent_span_id:Z.parent_span_id,op:Z.op,status:Z.status,origin:Z.origin,data:{...Z.data,...Z.profile_id&&{[fJ]:Z.profile_id},...Z.exclusive_time&&{[bJ]:Z.exclusive_time}}}},measurements:Z.measurements}}var jf="Not capturing exception because it's already been captured.",Mf="Discarded session because of missing or non-string release",Rf=Symbol.for("SentryInternalError"),Pf=Symbol.for("SentryDoNotSendEventError"),qC0=5000;function sW(Z){return{message:Z,[Rf]:!0}}function JU(Z){return{message:Z,[Pf]:!0}}function Af(Z){return!!Z&&typeof Z==="object"&&Rf in Z}function Tf(Z){return!!Z&&typeof Z==="object"&&Pf in Z}function qf(Z,J,X,$,Y){let Q=0,W,K=!1;Z.on(X,()=>{Q=0,clearTimeout(W),K=!1}),Z.on(J,(z)=>{if(Q+=$(z),Q>=800000)Y(Z);else if(!K)K=!0,W=setTimeout(()=>{Y(Z)},qC0)}),Z.on("flush",()=>{Y(Z)})}class $U{constructor(Z){if(this._options=Z,this._integrations={},this._numProcessing=0,this._outcomes={},this._hooks={},this._eventProcessors=[],this._promiseBuffer=aW(Z.transportOptions?.bufferSize??ZU),Z.dsn)this._dsn=Ph(Z.dsn);else l&&A.warn("No DSN provided, client will not send events.");if(this._dsn){let X=Kf(this._dsn,Z.tunnel,Z._metadata?Z._metadata.sdk:void 0);this._transport=Z.transport({tunnel:this._options.tunnel,recordDroppedEvent:this.recordDroppedEvent.bind(this),...Z.transportOptions,url:X})}if(this._options.enableLogs=this._options.enableLogs??this._options._experiments?.enableLogs,this._options.enableLogs)qf(this,"afterCaptureLog","flushLogs",PC0,VY);if(this._options.enableMetrics??this._options._experiments?.enableMetrics??!0)qf(this,"afterCaptureMetric","flushMetrics",RC0,Bf)}captureException(Z,J,X){let $=c1();if(IW(Z))return l&&A.log(jf),$;let Y={event_id:$,...J};return this._process(()=>this.eventFromException(Z,Y).then((Q)=>this._captureEvent(Q,Y,X)).then((Q)=>Q),"error"),Y.event_id}captureMessage(Z,J,X,$){let Y={event_id:c1(),...X},Q=SJ(Z)?Z:String(Z),W=n$(Z),K=W?this.eventFromMessage(Q,J,Y):this.eventFromException(Z,Y);return this._process(()=>K.then((z)=>this._captureEvent(z,Y,$)),W?"unknown":"error"),Y.event_id}captureEvent(Z,J,X){let $=c1();if(J?.originalException&&IW(J.originalException))return l&&A.log(jf),$;let Y={event_id:$,...J},Q=Z.sdkProcessingMetadata||{},W=Q.capturedSpanScope,K=Q.capturedSpanIsolationScope,z=Cf(Z.type);return this._process(()=>this._captureEvent(Z,Y,W||X,K),z),Y.event_id}captureSession(Z){this.sendSession(Z),l5(Z,{init:!1})}getDsn(){return this._dsn}getOptions(){return this._options}getSdkMetadata(){return this._options._metadata}getTransport(){return this._transport}async flush(Z){let J=this._transport;if(!J)return!0;this.emit("flush");let X=await this._isClientDoneProcessing(Z),$=await J.flush(Z);return X&&$}async close(Z){let J=await this.flush(Z);return this.getOptions().enabled=!1,this.emit("close"),J}getEventProcessors(){return this._eventProcessors}addEventProcessor(Z){this._eventProcessors.push(Z)}init(){if(this._isEnabled()||this._options.integrations.some(({name:Z})=>Z.startsWith("Spotlight")))this._setupIntegrations()}getIntegrationByName(Z){return this._integrations[Z]}addIntegration(Z){let J=this._integrations[Z.name];if(eB(this,Z,this._integrations),!J)tB(this,[Z])}sendEvent(Z,J={}){this.emit("beforeSendEvent",Z,J);let X=mh(Z,this._dsn,this._options._metadata,this._options.tunnel);for(let $ of J.attachments||[])X=uB(X,pB($));this.sendEnvelope(X).then(($)=>this.emit("afterSendEvent",Z,$))}sendSession(Z){let{release:J,environment:X=dJ}=this._options;if("aggregates"in Z){let Y=Z.attrs||{};if(!Y.release&&!J){l&&A.warn(Mf);return}Y.release=Y.release||J,Y.environment=Y.environment||X,Z.attrs=Y}else{if(!Z.release&&!J){l&&A.warn(Mf);return}Z.release=Z.release||J,Z.environment=Z.environment||X}this.emit("beforeSendSession",Z);let $=gh(Z,this._dsn,this._options._metadata,this._options.tunnel);this.sendEnvelope($)}recordDroppedEvent(Z,J,X=1){if(this._options.sendClientReports){let $=`${Z}:${J}`;l&&A.log(`Recording outcome: "${$}"${X>1?` (${X} times)`:""}`),this._outcomes[$]=(this._outcomes[$]||0)+X}}on(Z,J){let X=this._hooks[Z]=this._hooks[Z]||new Set,$=(...Y)=>J(...Y);return X.add($),()=>{X.delete($)}}emit(Z,...J){let X=this._hooks[Z];if(X)X.forEach(($)=>$(...J))}async sendEnvelope(Z){if(this.emit("beforeEnvelope",Z),this._isEnabled()&&this._transport)try{return await this._transport.send(Z)}catch(J){return l&&A.error("Error while sending envelope:",J),{}}return l&&A.error("Transport disabled"),{}}_setupIntegrations(){let{integrations:Z}=this._options;this._integrations=zf(this,Z),tB(this,Z)}_updateSessionFromEvent(Z,J){let X=J.level==="fatal",$=!1,Y=J.exception?.values;if(Y){$=!0,X=!1;for(let K of Y)if(K.mechanism?.handled===!1){X=!0;break}}let Q=Z.status==="ok";if(Q&&Z.errors===0||Q&&X)l5(Z,{...X&&{status:"crashed"},errors:Z.errors||Number($||X)}),this.captureSession(Z)}async _isClientDoneProcessing(Z){let J=0;while(!Z||J<Z){if(await new Promise((X)=>setTimeout(X,1)),!this._numProcessing)return!0;J++}return!1}_isEnabled(){return this.getOptions().enabled!==!1&&this._transport!==void 0}_prepareEvent(Z,J,X,$){let Y=this.getOptions(),Q=Object.keys(this._integrations);if(!J.integrations&&Q?.length)J.integrations=Q;if(this.emit("preprocessEvent",Z,J),!Z.type)$.setLastEventId(Z.event_id||J.event_id);return Qf(Y,Z,J,X,this,$).then((W)=>{if(W===null)return W;this.emit("postprocessEvent",W,J),W.contexts={trace:zZ(X),...W.contexts};let K=e8(this,X);return W.sdkProcessingMetadata={dynamicSamplingContext:K,...W.sdkProcessingMetadata},W})}_captureEvent(Z,J={},X=u0(),$=R0()){if(l&&XU(Z))A.log(`Captured error event \`${rW(Z)[0]||"<unknown>"}\``);return this._processEvent(Z,J,X,$).then((Y)=>{return Y.event_id},(Y)=>{if(l)if(Tf(Y))A.log(Y.message);else if(Af(Y))A.warn(Y.message);else A.warn(Y);return})}_processEvent(Z,J,X,$){let Y=this.getOptions(),{sampleRate:Q}=Y,W=Ef(Z),K=XU(Z),G=`before send for type \`${Z.type||"error"}\``,H=typeof Q>"u"?void 0:L6(Q);if(K&&typeof H==="number"&&K4()>H)return this.recordDroppedEvent("sample_rate","error"),lJ(JU(`Discarding event because it's not included in the random sample (sampling rate = ${Q})`));let V=Cf(Z.type);return this._prepareEvent(Z,J,X,$).then((F)=>{if(F===null)throw this.recordDroppedEvent("event_processor",V),JU("An event processor returned `null`, will not send event.");if(J.data&&J.data.__sentry__===!0)return F;let U=NC0(this,Y,F,J);return CC0(U,G)}).then((F)=>{if(F===null){if(this.recordDroppedEvent("before_send",V),W){let _=1+(Z.spans||[]).length;this.recordDroppedEvent("before_send","span",_)}throw JU(`${G} returned \`null\`, will not send event.`)}let B=X.getSession()||$.getSession();if(K&&B)this._updateSessionFromEvent(B,F);if(W){let D=F.sdkProcessingMetadata?.spanCountBeforeProcessing||0,_=F.spans?F.spans.length:0,O=D-_;if(O>0)this.recordDroppedEvent("before_send","span",O)}let U=F.transaction_info;if(W&&U&&F.transaction!==Z.transaction)F.transaction_info={...U,source:"custom"};return this.sendEvent(F,J),F}).then(null,(F)=>{if(Tf(F)||Af(F))throw F;throw this.captureException(F,{mechanism:{handled:!1,type:"internal"},data:{__sentry__:!0},originalException:F}),sW(`Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.
33
- Reason: ${F}`)})}_process(Z,J){this._numProcessing++,this._promiseBuffer.add(Z).then((X)=>{return this._numProcessing--,X},(X)=>{if(this._numProcessing--,X===FY)this.recordDroppedEvent("queue_overflow",J);return X})}_clearOutcomes(){let Z=this._outcomes;return this._outcomes={},Object.entries(Z).map(([J,X])=>{let[$,Y]=J.split(":");return{reason:$,category:Y,quantity:X}})}_flushOutcomes(){l&&A.log("Flushing outcomes...");let Z=this._clearOutcomes();if(Z.length===0){l&&A.log("No outcomes to send");return}if(!this._dsn){l&&A.log("No dsn provided, will not send outcomes");return}l&&A.log("Sending outcomes:",Z);let J=_f(Z,this._options.tunnel&&U6(this._dsn));this.sendEnvelope(J)}}function Cf(Z){return Z==="replay_event"?"replay":Z||"error"}function CC0(Z,J){let X=`${J} must return \`null\` or a valid event.`;if(I4(Z))return Z.then(($)=>{if(!d5($)&&$!==null)throw sW(X);return $},($)=>{throw sW(`${J} rejected with ${$}`)});else if(!d5(Z)&&Z!==null)throw sW(X);return Z}function NC0(Z,J,X,$){let{beforeSend:Y,beforeSendTransaction:Q,beforeSendSpan:W,ignoreSpans:K}=J,z=X;if(XU(z)&&Y)return Y(z,$);if(Ef(z)){if(W||K){let G=Of(z);if(K?.length&&JY(G,K))return null;if(W){let H=W(G);if(!H)ZY();else z=g9(X,wf(H))}if(z.spans){let H=[],V=z.spans;for(let B of V){if(K?.length&&JY(B,K)){fh(V,B);continue}if(W){let U=W(B);if(!U)ZY(),H.push(B);else H.push(U)}else H.push(B)}let F=z.spans.length-H.length;if(F)Z.recordDroppedEvent("before_send","span",F);z.spans=H}}if(Q){if(z.spans){let G=z.spans.length;z.sdkProcessingMetadata={...X.sdkProcessingMetadata,spanCountBeforeProcessing:G}}return Q(z,$)}}return z}function XU(Z){return Z.type===void 0}function Ef(Z){return Z.type==="transaction"}function RC0(Z){let J=0;if(Z.name)J+=Z.name.length*2;return J+=8,J+If(Z.attributes)}function PC0(Z){let J=0;if(Z.message)J+=Z.message.length*2;return J+If(Z.attributes)}function If(Z){if(!Z)return 0;let J=0;return Object.values(Z).forEach((X)=>{if(Array.isArray(X))J+=X.length*Nf(X[0]);else if(n$(X))J+=Nf(X);else J+=100}),J}function Nf(Z){if(typeof Z==="string")return Z.length*2;else if(typeof Z==="number")return 8;else if(typeof Z==="boolean")return 4;return 0}function yf(Z,J,X,$,Y){let Q={sent_at:new Date().toISOString()};if(X?.sdk)Q.sdk={name:X.sdk.name,version:X.sdk.version};if(!!$&&!!Y)Q.dsn=U6(Y);if(J)Q.trace=J;let W=EC0(Z);return S4(Q,[W])}function EC0(Z){return[{type:"check_in"},Z]}function Sf(Z){let J=Z._metadata?.sdk,X=J?.name&&J?.version?`${J?.name}/${J?.version}`:void 0;Z.transportOptions={...Z.transportOptions,headers:{...X&&{"user-agent":X},...Z.transportOptions?.headers}}}function kf(Z,J){return Z(J.stack||"",1)}function IC0(Z){return a8(Z)&&"__sentry_fetch_url_host__"in Z&&typeof Z.__sentry_fetch_url_host__==="string"}function yC0(Z){if(IC0(Z))return`${Z.message} (${Z.__sentry_fetch_url_host__})`;return Z.message}function YU(Z,J){let X={type:J.name||J.constructor.name,value:yC0(J)},$=kf(Z,J);if($.length)X.stacktrace={frames:$};return X}function SC0(Z){for(let J in Z)if(Object.prototype.hasOwnProperty.call(Z,J)){let X=Z[J];if(X instanceof Error)return X}return}function kC0(Z){if("name"in Z&&typeof Z.name==="string"){let $=`'${Z.name}' captured as exception`;if("message"in Z&&typeof Z.message==="string")$+=` with message '${Z.message}'`;return $}else if("message"in Z&&typeof Z.message==="string")return Z.message;let J=jB(Z);if(BB(Z))return`Event \`ErrorEvent\` captured as exception with message \`${Z.message}\``;let X=xC0(Z);return`${X&&X!=="Object"?`'${X}'`:"Object"} captured as exception with keys: ${J}`}function xC0(Z){try{let J=Object.getPrototypeOf(Z);return J?J.constructor.name:void 0}catch{}}function vC0(Z,J,X,$){if(a8(X))return[X,void 0];if(J.synthetic=!0,d5(X)){let Q=Z?.getOptions().normalizeDepth,W={["__serialized__"]:mB(X,Q)},K=SC0(X);if(K)return[K,W];let z=kC0(X),G=$?.syntheticException||Error(z);return G.message=z,[G,W]}let Y=$?.syntheticException||Error(X);return Y.message=`${X}`,[Y,void 0]}function xf(Z,J,X,$){let Q=$?.data&&$.data.mechanism||{handled:!0,type:"generic"},[W,K]=vC0(Z,Q,X,$),z={exception:{values:[YU(J,W)]}};if(K)z.extra=K;return CB(z,void 0,void 0),xJ(z,Q),{...z,event_id:$?.event_id}}function vf(Z,J,X="info",$,Y){let Q={event_id:$?.event_id,level:X};if(Y&&$?.syntheticException){let W=kf(Z,$.syntheticException);if(W.length)Q.exception={values:[{value:J,stacktrace:{frames:W}}]},xJ(Q,{synthetic:!0})}if(SJ(J)){let{__sentry_template_string__:W,__sentry_template_values__:K}=J;return Q.logentry={message:W,params:K},Q}return Q.message=J,Q}class tW extends $U{constructor(Z){vh(),Sf(Z);super(Z);this._setUpMetricsProcessing()}eventFromException(Z,J){let X=xf(this,this._options.stackParser,Z,J);return X.level="error",LZ(X)}eventFromMessage(Z,J="info",X){return LZ(vf(this._options.stackParser,Z,J,X,this._options.attachStacktrace))}captureException(Z,J,X){return hf(J),super.captureException(Z,J,X)}captureEvent(Z,J,X){if(!Z.type&&Z.exception?.values&&Z.exception.values.length>0)hf(J);return super.captureEvent(Z,J,X)}captureCheckIn(Z,J,X){let $="checkInId"in Z&&Z.checkInId?Z.checkInId:c1();if(!this._isEnabled())return l&&A.warn("SDK not enabled, will not capture check-in."),$;let Y=this.getOptions(),{release:Q,environment:W,tunnel:K}=Y,z={check_in_id:$,monitor_slug:Z.monitorSlug,status:Z.status,release:Q,environment:W};if("duration"in Z)z.duration=Z.duration;if(J)z.monitor_config={schedule:J.schedule,checkin_margin:J.checkinMargin,max_runtime:J.maxRuntime,timezone:J.timezone,failure_issue_threshold:J.failureIssueThreshold,recovery_threshold:J.recoveryThreshold};let[G,H]=Gf(this,X);if(H)z.contexts={trace:H};let V=yf(z,G,this.getSdkMetadata(),K,this.getDsn());return l&&A.log("Sending checkin:",Z.monitorSlug,Z.status),this.sendEnvelope(V),$}_prepareEvent(Z,J,X,$){if(this._options.platform)Z.platform=Z.platform||this._options.platform;if(this._options.runtime)Z.contexts={...Z.contexts,runtime:Z.contexts?.runtime||this._options.runtime};if(this._options.serverName)Z.server_name=Z.server_name||this._options.serverName;return super._prepareEvent(Z,J,X,$)}_setUpMetricsProcessing(){this.on("processMetric",(Z)=>{if(this._options.serverName)Z.attributes={"server.address":this._options.serverName,...Z.attributes}})}}function hf(Z){let J=R0().getScopeData().sdkProcessingMetadata.requestSession;if(J){let X=Z?.mechanism?.handled??!0;if(X&&J.status!=="crashed")J.status="errored";else if(!X)J.status="crashed"}}var QU=new Set;function WU(Z){Z.forEach((J)=>{QU.add(J),l&&A.log(`AI provider "${J}" wrapping will be skipped`)})}function OZ(Z){return QU.has(Z)}function KU(){QU.clear(),l&&A.log("Cleared AI provider skip registrations")}var hC0="thismessage:/";function zU(Z){return"isRelative"in Z}function BY(Z,J){let X=Z.indexOf("://")<=0&&Z.indexOf("//")!==0,$=J??(X?hC0:void 0);try{if("canParse"in URL&&!URL.canParse(Z,$))return;let Y=new URL(Z,$);if(X)return{isRelative:X,pathname:Y.pathname,search:Y.search,hash:Y.hash};return Y}catch{}return}function n9(Z){if(!Z)return{};let J=Z.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!J)return{};let X=J[6]||"",$=J[8]||"";return{host:J[4],path:J[5],protocol:J[2],search:X,hash:$,relative:J[5]+X+$}}function p5(Z){return Z.split(/[?#]/,1)[0]}function o9(Z){let{protocol:J,host:X,path:$}=Z,Y=X?.replace(/^.*@/,"[filtered]:[filtered]@").replace(/(:80)$/,"").replace(/(:443)$/,"")||"";return`${J?`${J}://`:""}${Y}${$}`}function i5(Z,J,X=[J],$="npm"){let Y=Z._metadata||{};if(!Y.sdk)Y.sdk={name:`sentry.javascript.${J}`,packages:X.map((Q)=>({name:`${$}:@sentry/${Q}`,version:N0})),version:N0};Z._metadata=Y}function pJ(Z={}){let J=Z.client||u();if(!nW()||!J)return{};let X=O4(),$=b6(X);if($.getTraceData)return $.getTraceData(Z);let Y=Z.scope||u0(),Q=Z.span||t8(),W=Q?fW(Q):fC0(Y),K=Q?S1(Q):e8(J,Y),z=GZ(K);if(!s$.test(W))return A.warn("Invalid sentry-trace data. Cannot generate trace data"),{};let H={"sentry-trace":W,baggage:z};if(Z.propagateTraceparent)H.traceparent=Q?kh(Q):bC0(Y);return H}function fC0(Z){let{traceId:J,sampled:X,propagationSpanId:$}=Z.getPropagationContext();return u9(J,$,X)}function bC0(Z){let{traceId:J,sampled:X,propagationSpanId:$}=Z.getPropagationContext();return c9(J,$,X)}function GU(Z,J,X){let $,Y,Q,W=X?.maxWait?Math.max(X.maxWait,J):0,K=X?.setTimeoutImpl||setTimeout;function z(){return G(),$=Z(),$}function G(){Y!==void 0&&clearTimeout(Y),Q!==void 0&&clearTimeout(Q),Y=Q=void 0}function H(){if(Y!==void 0||Q!==void 0)return z();return $}function V(){if(Y)clearTimeout(Y);if(Y=K(z,J),W&&Q===void 0)Q=K(z,W);return $}return V.cancel=G,V.flush=H,V}function gf(Z){let J=Object.create(null);try{Object.entries(Z).forEach(([X,$])=>{if(typeof $==="string")J[X]=$})}catch{}return J}function UY(Z){let J=Z.headers||{},$=(typeof J["x-forwarded-host"]==="string"?J["x-forwarded-host"]:void 0)||(typeof J.host==="string"?J.host:void 0),Q=(typeof J["x-forwarded-proto"]==="string"?J["x-forwarded-proto"]:void 0)||Z.protocol||(Z.socket?.encrypted?"https":"http"),W=Z.url||"",K=gC0({url:W,host:$,protocol:Q}),z=Z.body||void 0,G=Z.cookies;return{url:K,method:Z.method,query_string:mf(W),headers:gf(J),cookies:G,data:z}}function gC0({url:Z,protocol:J,host:X}){if(Z?.startsWith("http"))return Z;if(Z&&X)return`${J}://${X}${Z}`;return}var ff=["auth","token","secret","session","password","passwd","pwd","key","jwt","bearer","sso","saml","csrf","xsrf","credentials","set-cookie","cookie"],mC0=["x-forwarded-","-user"];function iJ(Z,J=!1){let X={};try{Object.entries(Z).forEach(([$,Y])=>{if(Y==null)return;let Q=$.toLowerCase();if((Q==="cookie"||Q==="set-cookie")&&typeof Y==="string"&&Y!==""){let K=Q==="set-cookie",z=Y.indexOf(";"),G=K&&z!==-1?Y.substring(0,z):Y,H=K?[G]:G.split("; ");for(let V of H){let F=V.indexOf("="),B=F!==-1?V.substring(0,F):V,U=F!==-1?V.substring(F+1):"",D=B.toLowerCase();bf(X,Q,D,U,J)}}else bf(X,Q,"",Y,J)})}catch{}return X}function HU(Z){return Z.replace(/-/g,"_")}function bf(Z,J,X,$,Y){let Q=X?`http.request.header.${HU(J)}.${HU(X)}`:`http.request.header.${HU(J)}`,W=dC0(X||J,$,Y);if(W!==void 0)Z[Q]=W}function dC0(Z,J,X){if(X?ff.some((Y)=>Z.includes(Y)):[...mC0,...ff].some((Y)=>Z.includes(Y)))return"[Filtered]";else if(Array.isArray(J))return J.map((Y)=>Y!=null?String(Y):Y).join(";");else if(typeof J==="string")return J;return}function mf(Z){if(!Z)return;try{let J=new URL(Z,"http://s.io").search.slice(1);return J.length?J:void 0}catch{return}}var uC0=100;function g6(Z,J){let X=u(),$=R0();if(!X)return;let{beforeBreadcrumb:Y=null,maxBreadcrumbs:Q=uC0}=X.getOptions();if(Q<=0)return;let K={timestamp:c5(),...Z},z=Y?y1(()=>Y(K,J)):K;if(z===null)return;if(X.emit)X.emit("beforeAddBreadcrumb",z,J);$.addBreadcrumb(z,Q)}var df,cC0="FunctionToString",uf=new WeakMap,lC0=()=>{return{name:cC0,setupOnce(){df=Function.prototype.toString;try{Function.prototype.toString=function(...Z){let J=wB(this),X=uf.has(u())&&J!==void 0?J:this;return df.apply(X,Z)}}catch{}},setup(Z){uf.set(Z,!0)}}},nJ=S(lC0);var pC0=[/^Script error\.?$/,/^Javascript error: Script error\.? on line 0$/,/^ResizeObserver loop completed with undelivered notifications.$/,/^Cannot redefine property: googletag$/,/^Can't find variable: gmo$/,/^undefined is not an object \(evaluating 'a\.[A-Z]'\)$/,`can't redefine non-configurable property "solana"`,"vv().getRestrictions is not a function. (In 'vv().getRestrictions(1,a)', 'vv().getRestrictions' is undefined)","Can't find variable: _AutofillCallbackHandler",/^Non-Error promise rejection captured with value: Object Not Found Matching Id:\d+, MethodName:simulateEvent, ParamCount:\d+$/,/^Java exception was raised during method invocation$/],iC0="EventFilters",VU=S((Z={})=>{let J;return{name:iC0,setup(X){let $=X.getOptions();J=cf(Z,$)},processEvent(X,$,Y){if(!J){let Q=Y.getOptions();J=cf(Z,Q)}return nC0(X,J)?null:X}}}),oJ=S((Z={})=>{return{...VU(Z),name:"InboundFilters"}});function cf(Z={},J={}){return{allowUrls:[...Z.allowUrls||[],...J.allowUrls||[]],denyUrls:[...Z.denyUrls||[],...J.denyUrls||[]],ignoreErrors:[...Z.ignoreErrors||[],...J.ignoreErrors||[],...Z.disableErrorDefaults?[]:pC0],ignoreTransactions:[...Z.ignoreTransactions||[],...J.ignoreTransactions||[]]}}function nC0(Z,J){if(!Z.type){if(oC0(Z,J.ignoreErrors))return l&&A.warn(`Event dropped due to being matched by \`ignoreErrors\` option.
32
+ `)}`)}function QY(Z){if(!l)return;let{description:J="< unknown name >",op:X="< unknown op >"}=J0(Z),{spanId:$}=Z.spanContext(),Q=q1(Z)===Z,W=`[Tracing] Finishing "${X}" ${Q?"root ":""}span "${J}" with ID ${$}`;A.log(W)}function UZ(Z){if(!Z||Z.length===0)return;let J={};return Z.forEach((X)=>{let $=X.attributes||{},Y=$[IB],Q=$[yB];if(typeof Y==="string"&&typeof Q==="number")J[X.name]={value:Q,unit:Y}}),J}var uh=1000;class WY{constructor(Z={}){if(this._traceId=Z.traceId||a4(),this._spanId=Z.spanId||r4(),this._startTime=Z.startTimestamp||b9(),this._links=Z.links,this._attributes={},this.setAttributes({[X0]:"manual",[K0]:Z.op,...Z.attributes}),this._name=Z.name,Z.parentSpanId)this._parentSpanId=Z.parentSpanId;if("sampled"in Z)this._sampled=Z.sampled;if(Z.endTimestamp)this._endTime=Z.endTimestamp;if(this._events=[],this._isStandaloneSpan=Z.isStandalone,this._endTime)this._onSpanEnded()}addLink(Z){if(this._links)this._links.push(Z);else this._links=[Z];return this}addLinks(Z){if(this._links)this._links.push(...Z);else this._links=Z;return this}recordException(Z,J){}spanContext(){let{_spanId:Z,_traceId:J,_sampled:X}=this;return{spanId:Z,traceId:J,traceFlags:X?hW:vW}}setAttribute(Z,J){if(J===void 0)delete this._attributes[Z];else this._attributes[Z]=J;return this}setAttributes(Z){return Object.keys(Z).forEach((J)=>this.setAttribute(J,Z[J])),this}updateStartTime(Z){this._startTime=t4(Z)}setStatus(Z){return this._status=Z,this}updateName(Z){return this._name=Z,this.setAttribute(U1,"custom"),this}end(Z){if(this._endTime)return;this._endTime=t4(Z),QY(this),this._onSpanEnded()}getSpanJSON(){return{data:this._attributes,description:this._name,op:this._attributes[K0],parent_span_id:this._parentSpanId,span_id:this._spanId,start_timestamp:this._startTime,status:BZ(this._status),timestamp:this._endTime,trace_id:this._traceId,origin:this._attributes[X0],profile_id:this._attributes[fJ],exclusive_time:this._attributes[bJ],measurements:UZ(this._events),is_segment:this._isStandaloneSpan&&q1(this)===this||void 0,segment_id:this._isStandaloneSpan?q1(this).spanContext().spanId:void 0,links:FZ(this._links)}}isRecording(){return!this._endTime&&!!this._sampled}addEvent(Z,J,X){l&&A.log("[Tracing] Adding an event to span:",Z);let $=ch(J)?J:X||b9(),Y=ch(J)?{}:J||{},Q={name:Z,time:t4($),attributes:Y};return this._events.push(Q),this}isStandaloneSpan(){return!!this._isStandaloneSpan}_onSpanEnded(){let Z=u();if(Z)Z.emit("spanEnd",this);if(!(this._isStandaloneSpan||this===q1(this)))return;if(this._isStandaloneSpan){if(this._sampled)oq0(dh([this],Z));else if(l&&A.log("[Tracing] Discarding standalone span because its trace was not chosen to be sampled."),Z)Z.recordDroppedEvent("sample_rate","span");return}let X=this._convertSpanToTransaction();if(X)(A8(this).scope||u0()).captureEvent(X)}_convertSpanToTransaction(){if(!lh(J0(this)))return;if(!this._name)l&&A.warn("Transaction has no name, falling back to `<unlabeled transaction>`."),this._name="<unlabeled transaction>";let{scope:Z,isolationScope:J}=A8(this),X=Z?.getScopeData().sdkProcessingMetadata?.normalizedRequest;if(this._sampled!==!0)return;let Y=bW(this).filter((G)=>G!==this&&!nq0(G)).map((G)=>J0(G)).filter(lh),Q=this._attributes[U1];delete this._attributes[s8],Y.forEach((G)=>{delete G.data[s8]});let W={contexts:{trace:Sh(this)},spans:Y.length>uh?Y.sort((G,H)=>G.start_timestamp-H.start_timestamp).slice(0,uh):Y,start_timestamp:this._startTime,timestamp:this._endTime,transaction:this._name,type:"transaction",sdkProcessingMetadata:{capturedSpanScope:Z,capturedSpanIsolationScope:J,dynamicSamplingContext:S1(this)},request:X,...Q&&{transaction_info:{source:Q}}},K=UZ(this._events);if(K&&Object.keys(K).length)l&&A.log("[Measurements] Adding measurements to transaction event",JSON.stringify(K,void 0,2)),W.measurements=K;return W}}function ch(Z){return Z&&typeof Z==="number"||Z instanceof Date||Array.isArray(Z)}function lh(Z){return!!Z.start_timestamp&&!!Z.timestamp&&!!Z.span_id&&!!Z.trace_id}function nq0(Z){return Z instanceof WY&&Z.isStandaloneSpan()}function oq0(Z){let J=u();if(!J)return;let X=Z[1];if(!X||X.length===0){J.recordDroppedEvent("before_send","span");return}J.sendEnvelope(Z)}function D6(Z,J,X=()=>{},$=()=>{}){let Y;try{Y=Z()}catch(Q){throw J(Q),X(),Q}return aq0(Y,J,X,$)}function aq0(Z,J,X,$){if(I4(Z))return Z.then((Y)=>{return X(),$(Y),Y},(Y)=>{throw J(Y),X(),Y});return X(),$(Z),Z}function KY(Z,J,X){if(!L1(Z))return[!1];let $=void 0,Y;if(typeof Z.tracesSampler==="function")Y=Z.tracesSampler({...J,inheritOrSampleWith:(K)=>{if(typeof J.parentSampleRate==="number")return J.parentSampleRate;if(typeof J.parentSampled==="boolean")return Number(J.parentSampled);return K}}),$=!0;else if(J.parentSampled!==void 0)Y=J.parentSampled;else if(typeof Z.tracesSampleRate<"u")Y=Z.tracesSampleRate,$=!0;let Q=L6(Y);if(Q===void 0)return l&&A.warn(`[Tracing] Discarding root span because of invalid sample rate. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(Y)} of type ${JSON.stringify(typeof Y)}.`),[!1];if(!Q)return l&&A.log(`[Tracing] Discarding transaction because ${typeof Z.tracesSampler==="function"?"tracesSampler returned 0 or false":"a negative sampling decision was inherited or tracesSampleRate is set to 0"}`),[!1,Q,$];let W=X<Q;if(!W)l&&A.log(`[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = ${Number(Y)})`);return[W,Q,$]}var uW="__SENTRY_SUPPRESS_TRACING__";function _6(Z,J){let X=lW();if(X.startSpan)return X.startSpan(Z,J);let $=nh(Z),{forceTransaction:Y,parentSpan:Q,scope:W}=Z,K=W?.clone();return s4(K,()=>{return ah(Q)(()=>{let G=u0(),H=oh(G,Q),F=Z.onlyIfParent&&!H?new uJ:ih({parentSpan:H,spanArguments:$,forceTransaction:Y,scope:G});return m9(G,F),D6(()=>J(F),()=>{let{status:B}=J0(F);if(F.isRecording()&&(!B||B==="ok"))F.setStatus({code:A0,message:"internal_error"})},()=>{F.end()})})})}function z4(Z,J){let X=lW();if(X.startSpanManual)return X.startSpanManual(Z,J);let $=nh(Z),{forceTransaction:Y,parentSpan:Q,scope:W}=Z,K=W?.clone();return s4(K,()=>{return ah(Q)(()=>{let G=u0(),H=oh(G,Q),F=Z.onlyIfParent&&!H?new uJ:ih({parentSpan:H,spanArguments:$,forceTransaction:Y,scope:G});return m9(G,F),D6(()=>J(F,()=>F.end()),()=>{let{status:B}=J0(F);if(F.isRecording()&&(!B||B==="ok"))F.setStatus({code:A0,message:"internal_error"})})})})}var cW=(Z,J)=>{let X=O4(),$=b6(X);if($.continueTrace)return $.continueTrace(Z,J);let{sentryTrace:Y,baggage:Q}=Z,W=u(),K=T8(Q);if(W&&!t$(W,K?.org_id))return nB(J);return s4((z)=>{let G=VZ(Y,Q);return z.setPropagationContext(G),m9(z,void 0),J()})};function cJ(Z,J){let X=lW();if(X.withActiveSpan)return X.withActiveSpan(Z,J);return s4(($)=>{return m9($,Z||void 0),J($)})}function p9(Z){let J=lW();if(J.suppressTracing)return J.suppressTracing(Z);return s4((X)=>{X.setSDKProcessingMetadata({[uW]:!0});let $=Z();return X.setSDKProcessingMetadata({[uW]:void 0}),$})}function nB(Z){return s4((J)=>{return J.setPropagationContext({traceId:a4(),sampleRand:K4()}),l&&A.log(`Starting a new trace with id ${J.getPropagationContext().traceId}`),cJ(null,Z)})}function ih({parentSpan:Z,spanArguments:J,forceTransaction:X,scope:$}){if(!L1()){let W=new uJ;if(X||!Z){let K={sampled:"false",sample_rate:"0",transaction:J.name,...S1(W)};gW(W,K)}return W}let Y=R0(),Q;if(Z&&!X)Q=rq0(Z,$,J),mJ(Z,Q);else if(Z){let W=S1(Z),{traceId:K,spanId:z}=Z.spanContext(),G=q8(Z);Q=ph({traceId:K,parentSpanId:z,...J},$,G),gW(Q,W)}else{let{traceId:W,dsc:K,parentSpanId:z,sampled:G}={...Y.getPropagationContext(),...$.getPropagationContext()};if(Q=ph({traceId:W,parentSpanId:z,...J},$,G),K)gW(Q,K)}return YY(Q),a$(Q,$,Y),Q}function nh(Z){let X={isStandalone:(Z.experimental||{}).standalone,...Z};if(Z.startTime){let $={...X};return $.startTimestamp=t4(Z.startTime),delete $.startTime,$}return X}function lW(){let Z=O4();return b6(Z)}function ph(Z,J,X){let $=u(),Y=$?.getOptions()||{},{name:Q=""}=Z,W={spanAttributes:{...Z.attributes},spanName:Q,parentSampled:X};$?.emit("beforeSampling",W,{decision:!1});let K=W.parentSampled??X,z=W.spanAttributes,G=J.getPropagationContext(),[H,V,F]=J.getScopeData().sdkProcessingMetadata[uW]?[!1]:KY(Y,{name:Q,parentSampled:K,attributes:z,parentSampleRate:L6(G.dsc?.sample_rate)},G.sampleRand),B=new WY({...Z,attributes:{[U1]:"custom",[M8]:V!==void 0&&F?V:void 0,...z},sampled:H});if(!H&&$)l&&A.log("[Tracing] Discarding root span because its trace was not chosen to be sampled."),$.recordDroppedEvent("sample_rate","transaction");if($)$.emit("spanStart",B);return B}function rq0(Z,J,X){let{spanId:$,traceId:Y}=Z.spanContext(),Q=J.getScopeData().sdkProcessingMetadata[uW]?!1:q8(Z),W=Q?new WY({...X,parentSpanId:$,traceId:Y,sampled:Q}):new uJ({traceId:Y});mJ(Z,W);let K=u();if(K){if(K.emit("spanStart",W),X.endTimestamp)K.emit("spanEnd",W)}return W}function oh(Z,J){if(J)return J;if(J===null)return;let X=WZ(Z);if(!X)return;let $=u();if(($?$.getOptions():{}).parentSpanIsAlwaysRootSpan)return q1(X);return X}function ah(Z){return Z!==void 0?(J)=>{return cJ(Z,J)}:(J)=>J()}var oB=0,rh=1,sh=2;function LZ(Z){return new zY((J)=>{J(Z)})}function lJ(Z){return new zY((J,X)=>{X(Z)})}class zY{constructor(Z){this._state=oB,this._handlers=[],this._runExecutor(Z)}then(Z,J){return new zY((X,$)=>{this._handlers.push([!1,(Y)=>{if(!Z)X(Y);else try{X(Z(Y))}catch(Q){$(Q)}},(Y)=>{if(!J)$(Y);else try{X(J(Y))}catch(Q){$(Q)}}]),this._executeHandlers()})}catch(Z){return this.then((J)=>J,Z)}finally(Z){return new zY((J,X)=>{let $,Y;return this.then((Q)=>{if(Y=!1,$=Q,Z)Z()},(Q)=>{if(Y=!0,$=Q,Z)Z()}).then(()=>{if(Y){X($);return}J($)})})}_executeHandlers(){if(this._state===oB)return;let Z=this._handlers.slice();this._handlers=[],Z.forEach((J)=>{if(J[0])return;if(this._state===rh)J[1](this._value);if(this._state===sh)J[2](this._value);J[0]=!0})}_runExecutor(Z){let J=(Y,Q)=>{if(this._state!==oB)return;if(I4(Q)){Q.then(X,$);return}this._state=Y,this._value=Q,this._executeHandlers()},X=(Y)=>{J(rh,Y)},$=(Y)=>{J(sh,Y)};try{Z(X,$)}catch(Y){$(Y)}}}function th(Z,J,X,$=0){try{let Y=aB(J,X,Z,$);return I4(Y)?Y:LZ(Y)}catch(Y){return lJ(Y)}}function aB(Z,J,X,$){let Y=X[$];if(!Z||!Y)return Z;let Q=Y({...Z},J);if(l&&Q===null&&A.log(`Event processor "${Y.id||"?"}" dropped event`),I4(Q))return Q.then((W)=>aB(W,J,X,$+1));return aB(Q,J,X,$+1)}var DZ,eh,Zf,i9;function Jf(Z){let J=Q0._sentryDebugIds,X=Q0._debugIds;if(!J&&!X)return{};let $=J?Object.keys(J):[],Y=X?Object.keys(X):[];if(i9&&$.length===eh&&Y.length===Zf)return i9;if(eh=$.length,Zf=Y.length,i9={},!DZ)DZ={};let Q=(W,K)=>{for(let z of W){let G=K[z],H=DZ?.[z];if(H&&i9&&G){if(i9[H[0]]=G,DZ)DZ[z]=[H[0],G]}else if(G){let V=Z(z);for(let F=V.length-1;F>=0;F--){let U=V[F]?.filename;if(U&&i9&&DZ){i9[U]=G,DZ[z]=[U,G];break}}}}};if(J)Q($,J);if(X)Q(Y,X);return i9}function $f(Z,J){let{fingerprint:X,span:$,breadcrumbs:Y,sdkProcessingMetadata:Q}=J;if(sq0(Z,J),$)ZC0(Z,$);JC0(Z,X),tq0(Z,Y),eq0(Z,Q)}function Xf(Z,J){let{extra:X,tags:$,attributes:Y,user:Q,contexts:W,level:K,sdkProcessingMetadata:z,breadcrumbs:G,fingerprint:H,eventProcessors:V,attachments:F,propagationContext:B,transactionName:U,span:D}=J;if(GY(Z,"extra",X),GY(Z,"tags",$),GY(Z,"attributes",Y),GY(Z,"user",Q),GY(Z,"contexts",W),Z.sdkProcessingMetadata=g9(Z.sdkProcessingMetadata,z,2),K)Z.level=K;if(U)Z.transactionName=U;if(D)Z.span=D;if(G.length)Z.breadcrumbs=[...Z.breadcrumbs,...G];if(H.length)Z.fingerprint=[...Z.fingerprint,...H];if(V.length)Z.eventProcessors=[...Z.eventProcessors,...V];if(F.length)Z.attachments=[...Z.attachments,...F];Z.propagationContext={...Z.propagationContext,...B}}function GY(Z,J,X){Z[J]=g9(Z[J],X,1)}function Yf(Z,J){let X=yW().getScopeData();return Z&&Xf(X,Z.getScopeData()),J&&Xf(X,J.getScopeData()),X}function sq0(Z,J){let{extra:X,tags:$,user:Y,contexts:Q,level:W,transactionName:K}=J;if(Object.keys(X).length)Z.extra={...X,...Z.extra};if(Object.keys($).length)Z.tags={...$,...Z.tags};if(Object.keys(Y).length)Z.user={...Y,...Z.user};if(Object.keys(Q).length)Z.contexts={...Q,...Z.contexts};if(W)Z.level=W;if(K&&Z.type!=="transaction")Z.transaction=K}function tq0(Z,J){let X=[...Z.breadcrumbs||[],...J];Z.breadcrumbs=X.length?X:void 0}function eq0(Z,J){Z.sdkProcessingMetadata={...Z.sdkProcessingMetadata,...J}}function ZC0(Z,J){Z.contexts={trace:l9(J),...Z.contexts},Z.sdkProcessingMetadata={dynamicSamplingContext:S1(J),...Z.sdkProcessingMetadata};let X=q1(J),$=J0(X).description;if($&&!Z.transaction&&Z.type==="transaction")Z.transaction=$}function JC0(Z,J){if(Z.fingerprint=Z.fingerprint?Array.isArray(Z.fingerprint)?Z.fingerprint:[Z.fingerprint]:[],J)Z.fingerprint=Z.fingerprint.concat(J);if(!Z.fingerprint.length)delete Z.fingerprint}function Qf(Z,J,X,$,Y,Q){let{normalizeDepth:W=3,normalizeMaxBreadth:K=1000}=Z,z={...J,event_id:J.event_id||X.event_id||l1(),timestamp:J.timestamp||c5()},G=X.integrations||Z.integrations.map((_)=>_.name);if(XC0(z,Z),QC0(z,G),Y)Y.emit("applyFrameMetadata",J);if(J.type===void 0)$C0(z,Z.stackParser);let H=KC0($,X.captureContext);if(X.mechanism)xJ(z,X.mechanism);let V=Y?Y.getEventProcessors():[],F=Yf(Q,H),B=[...X.attachments||[],...F.attachments];if(B.length)X.attachments=B;$f(z,F);let U=[...V,...F.eventProcessors];return th(U,z,X).then((_)=>{if(_)YC0(_);if(typeof W==="number"&&W>0)return WC0(_,W,K);return _})}function XC0(Z,J){let{environment:X,release:$,dist:Y,maxValueLength:Q}=J;if(Z.environment=Z.environment||X||dJ,!Z.release&&$)Z.release=$;if(!Z.dist&&Y)Z.dist=Y;let W=Z.request;if(W?.url&&Q)W.url=v9(W.url,Q);if(Q)Z.exception?.values?.forEach((K)=>{if(K.value)K.value=v9(K.value,Q)})}function $C0(Z,J){let X=Jf(J);Z.exception?.values?.forEach(($)=>{$.stacktrace?.frames?.forEach((Y)=>{if(Y.filename)Y.debug_id=X[Y.filename]})})}function YC0(Z){let J={};if(Z.exception?.values?.forEach(($)=>{$.stacktrace?.frames?.forEach((Y)=>{if(Y.debug_id){if(Y.abs_path)J[Y.abs_path]=Y.debug_id;else if(Y.filename)J[Y.filename]=Y.debug_id;delete Y.debug_id}})}),Object.keys(J).length===0)return;Z.debug_meta=Z.debug_meta||{},Z.debug_meta.images=Z.debug_meta.images||[];let X=Z.debug_meta.images;Object.entries(J).forEach(([$,Y])=>{X.push({type:"sourcemap",code_file:$,debug_id:Y})})}function QC0(Z,J){if(J.length>0)Z.sdk=Z.sdk||{},Z.sdk.integrations=[...Z.sdk.integrations||[],...J]}function WC0(Z,J,X){if(!Z)return null;let $={...Z,...Z.breadcrumbs&&{breadcrumbs:Z.breadcrumbs.map((Y)=>({...Y,...Y.data&&{data:C8(Y.data,J,X)}}))},...Z.user&&{user:C8(Z.user,J,X)},...Z.contexts&&{contexts:C8(Z.contexts,J,X)},...Z.extra&&{extra:C8(Z.extra,J,X)}};if(Z.contexts?.trace&&$.contexts){if($.contexts.trace=Z.contexts.trace,Z.contexts.trace.data)$.contexts.trace.data=C8(Z.contexts.trace.data,J,X)}if(Z.spans)$.spans=Z.spans.map((Y)=>{return{...Y,...Y.data&&{data:C8(Y.data,J,X)}}});if(Z.contexts?.flags&&$.contexts)$.contexts.flags=C8(Z.contexts.flags,3,X);return $}function KC0(Z,J){if(!J)return Z;let X=Z?Z.clone():new y4;return X.update(J),X}function Wf(Z){if(!Z)return;if(zC0(Z))return{captureContext:Z};if(HC0(Z))return{captureContext:Z};return Z}function zC0(Z){return Z instanceof y4||typeof Z==="function"}var GC0=["user","level","extra","contexts","tags","fingerprint","propagationContext"];function HC0(Z){return Object.keys(Z).some((J)=>GC0.includes(J))}function V0(Z,J){return u0().captureException(Z,Wf(J))}function pW(Z,J){return u0().captureEvent(Z,J)}async function iW(Z){let J=u();if(J)return J.flush(Z);return l&&A.warn("Cannot flush events. No client defined."),Promise.resolve(!1)}function nW(){let Z=u();return Z?.getOptions().enabled!==!1&&!!Z?.getTransport()}function oW(Z){let J=R0(),X=u0(),{userAgent:$}=Q0.navigator||{},Y=_h({user:X.getUser()||J.getUser(),...$&&{userAgent:$},...Z}),Q=J.getSession();if(Q?.status==="ok")l5(Q,{status:"exited"});return HY(),J.setSession(Y),Y}function HY(){let Z=R0(),X=u0().getSession()||Z.getSession();if(X)Oh(X);VC0(),Z.setSession()}function VC0(){let Z=R0(),J=u(),X=Z.getSession();if(X&&J)J.captureSession(X)}var FC0="7";function BC0(Z){let J=Z.protocol?`${Z.protocol}:`:"",X=Z.port?`:${Z.port}`:"";return`${J}//${Z.host}${X}${Z.path?`/${Z.path}`:""}/api/`}function UC0(Z){return`${BC0(Z)}${Z.projectId}/envelope/`}function LC0(Z,J){let X={sentry_version:FC0};if(Z.publicKey)X.sentry_key=Z.publicKey;if(J)X.sentry_client=`${J.name}/${J.version}`;return new URLSearchParams(X).toString()}function Kf(Z,J,X){return J?J:`${UC0(Z)}?${LC0(Z,X)}`}var rB=[];function DC0(Z){let J={};return Z.forEach((X)=>{let{name:$}=X,Y=J[$];if(Y&&!Y.isDefaultInstance&&X.isDefaultInstance)return;J[$]=X}),Object.values(J)}function sB(Z){let J=Z.defaultIntegrations||[],X=Z.integrations;J.forEach((Y)=>{Y.isDefaultInstance=!0});let $;if(Array.isArray(X))$=[...J,...X];else if(typeof X==="function"){let Y=X(J);$=Array.isArray(Y)?Y:[Y]}else $=J;return DC0($)}function zf(Z,J){let X={};return J.forEach(($)=>{if($)eB(Z,$,X)}),X}function tB(Z,J){for(let X of J)if(X?.afterAllSetup)X.afterAllSetup(Z)}function eB(Z,J,X){if(X[J.name]){l&&A.log(`Integration skipped because it was already installed: ${J.name}`);return}if(X[J.name]=J,!rB.includes(J.name)&&typeof J.setupOnce==="function")J.setupOnce(),rB.push(J.name);if(J.setup&&typeof J.setup==="function")J.setup(Z);if(typeof J.preprocessEvent==="function"){let $=J.preprocessEvent.bind(J);Z.on("preprocessEvent",(Y,Q)=>$(Y,Q,Z))}if(typeof J.processEvent==="function"){let $=J.processEvent.bind(J),Y=Object.assign((Q,W)=>$(Q,W,Z),{id:J.name});Z.addEventProcessor(Y)}l&&A.log(`Integration installed: ${J.name}`)}function S(Z){return Z}function Gf(Z,J){if(!J)return[void 0,void 0];return s4(J,()=>{let X=t8(),$=X?l9(X):zZ(J);return[X?S1(X):e8(Z,J),$]})}function _C0(Z){return[{type:"log",item_count:Z.length,content_type:"application/vnd.sentry.items.log+json"},{items:Z}]}function Hf(Z,J,X,$){let Y={};if(J?.sdk)Y.sdk={name:J.sdk.name,version:J.sdk.version};if(!!X&&!!$)Y.dsn=U6($);return S4(Y,[_C0(Z)])}function VY(Z,J){let X=J??OC0(Z)??[];if(X.length===0)return;let $=Z.getOptions(),Y=Hf(X,$._metadata,$.tunnel,Z.getDsn());Vf().set(Z,[]),Z.emit("flushLogs"),Z.sendEnvelope(Y)}function OC0(Z){return Vf().get(Z)}function Vf(){return j8("clientToLogBufferMap",()=>new WeakMap)}function wC0(Z){return[{type:"trace_metric",item_count:Z.length,content_type:"application/vnd.sentry.items.trace-metric+json"},{items:Z}]}function Ff(Z,J,X,$){let Y={};if(J?.sdk)Y.sdk={name:J.sdk.name,version:J.sdk.version};if(!!X&&!!$)Y.dsn=U6($);return S4(Y,[wC0(Z)])}function Bf(Z,J){let X=J??jC0(Z)??[];if(X.length===0)return;let $=Z.getOptions(),Y=Ff(X,$._metadata,$.tunnel,Z.getDsn());Uf().set(Z,[]),Z.emit("flushMetrics"),Z.sendEnvelope(Y)}function jC0(Z){return Uf().get(Z)}function Uf(){return j8("clientToMetricBufferMap",()=>new WeakMap)}var FY=Symbol.for("SentryBufferFullError");function aW(Z=100){let J=new Set;function X(){return J.size<Z}function $(W){J.delete(W)}function Y(W){if(!X())return lJ(FY);let K=W();return J.add(K),K.then(()=>$(K),()=>$(K)),K}function Q(W){if(!J.size)return LZ(!0);let K=Promise.allSettled(Array.from(J)).then(()=>!0);if(!W)return K;let z=[K,new Promise((G)=>setTimeout(()=>G(!1),W))];return Promise.race(z)}return{get $(){return Array.from(J)},add:Y,drain:Q}}var MC0=60000;function AC0(Z,J=f6()){let X=parseInt(`${Z}`,10);if(!isNaN(X))return X*1000;let $=Date.parse(`${Z}`);if(!isNaN($))return $-J;return MC0}function TC0(Z,J){return Z[J]||Z.all||0}function Lf(Z,J,X=f6()){return TC0(Z,J)>X}function Df(Z,{statusCode:J,headers:X},$=f6()){let Y={...Z},Q=X?.["x-sentry-rate-limits"],W=X?.["retry-after"];if(Q)for(let K of Q.trim().split(",")){let[z,G,,,H]=K.split(":",5),V=parseInt(z,10),F=(!isNaN(V)?V:60)*1000;if(!G)Y.all=$+F;else for(let B of G.split(";"))if(B==="metric_bucket"){if(!H||H.split(";").includes("custom"))Y[B]=$+F}else Y[B]=$+F}else if(W)Y.all=$+AC0(W,$);else if(J===429)Y.all=$+60000;return Y}var ZU=64;function _Z(Z,J,X=aW(Z.bufferSize||ZU)){let $={},Y=(W)=>X.drain(W);function Q(W){let K=[];if(XY(W,(V,F)=>{let B=mW(F);if(Lf($,B))Z.recordDroppedEvent("ratelimit_backoff",B);else K.push(V)}),K.length===0)return Promise.resolve({});let z=S4(W[0],K),G=(V)=>{if(cB(z,["client_report"])){l&&A.warn(`Dropping client report. Will not send outcomes (reason: ${V}).`);return}XY(z,(F,B)=>{Z.recordDroppedEvent(V,mW(B))})},H=()=>J({body:$Y(z)}).then((V)=>{if(V.statusCode!==void 0&&(V.statusCode<200||V.statusCode>=300))l&&A.warn(`Sentry responded with status code ${V.statusCode} to sent event.`);return $=Df($,V),V},(V)=>{throw G("network_error"),l&&A.error("Encountered error running transport request:",V),V});return X.add(H).then((V)=>V,(V)=>{if(V===FY)return l&&A.error("Skipped sending event because buffer is full."),G("queue_overflow"),Promise.resolve({});else throw V})}return{send:Q,flush:Y}}function _f(Z,J,X){let $=[{type:"client_report"},{timestamp:X||c5(),discarded_events:Z}];return S4(J?{dsn:J}:{},[$])}function rW(Z){let J=[];if(Z.message)J.push(Z.message);try{let X=Z.exception.values[Z.exception.values.length-1];if(X?.value){if(J.push(X.value),X.type)J.push(`${X.type}: ${X.value}`)}}catch{}return J}function Of(Z){let{trace_id:J,parent_span_id:X,span_id:$,status:Y,origin:Q,data:W,op:K}=Z.contexts?.trace??{};return{data:W??{},description:Z.transaction,op:K,parent_span_id:X,span_id:$??"",start_timestamp:Z.start_timestamp??0,status:Y,timestamp:Z.timestamp,trace_id:J??"",origin:Q,profile_id:W?.[fJ],exclusive_time:W?.[bJ],measurements:Z.measurements,is_segment:!0}}function wf(Z){return{type:"transaction",timestamp:Z.timestamp,start_timestamp:Z.start_timestamp,transaction:Z.description,contexts:{trace:{trace_id:Z.trace_id,span_id:Z.span_id,parent_span_id:Z.parent_span_id,op:Z.op,status:Z.status,origin:Z.origin,data:{...Z.data,...Z.profile_id&&{[fJ]:Z.profile_id},...Z.exclusive_time&&{[bJ]:Z.exclusive_time}}}},measurements:Z.measurements}}var jf="Not capturing exception because it's already been captured.",Mf="Discarded session because of missing or non-string release",Rf=Symbol.for("SentryInternalError"),Pf=Symbol.for("SentryDoNotSendEventError"),qC0=5000;function sW(Z){return{message:Z,[Rf]:!0}}function JU(Z){return{message:Z,[Pf]:!0}}function Af(Z){return!!Z&&typeof Z==="object"&&Rf in Z}function Tf(Z){return!!Z&&typeof Z==="object"&&Pf in Z}function qf(Z,J,X,$,Y){let Q=0,W,K=!1;Z.on(X,()=>{Q=0,clearTimeout(W),K=!1}),Z.on(J,(z)=>{if(Q+=$(z),Q>=800000)Y(Z);else if(!K)K=!0,W=setTimeout(()=>{Y(Z)},qC0)}),Z.on("flush",()=>{Y(Z)})}class $U{constructor(Z){if(this._options=Z,this._integrations={},this._numProcessing=0,this._outcomes={},this._hooks={},this._eventProcessors=[],this._promiseBuffer=aW(Z.transportOptions?.bufferSize??ZU),Z.dsn)this._dsn=Ph(Z.dsn);else l&&A.warn("No DSN provided, client will not send events.");if(this._dsn){let X=Kf(this._dsn,Z.tunnel,Z._metadata?Z._metadata.sdk:void 0);this._transport=Z.transport({tunnel:this._options.tunnel,recordDroppedEvent:this.recordDroppedEvent.bind(this),...Z.transportOptions,url:X})}if(this._options.enableLogs=this._options.enableLogs??this._options._experiments?.enableLogs,this._options.enableLogs)qf(this,"afterCaptureLog","flushLogs",PC0,VY);if(this._options.enableMetrics??this._options._experiments?.enableMetrics??!0)qf(this,"afterCaptureMetric","flushMetrics",RC0,Bf)}captureException(Z,J,X){let $=l1();if(IW(Z))return l&&A.log(jf),$;let Y={event_id:$,...J};return this._process(()=>this.eventFromException(Z,Y).then((Q)=>this._captureEvent(Q,Y,X)).then((Q)=>Q),"error"),Y.event_id}captureMessage(Z,J,X,$){let Y={event_id:l1(),...X},Q=SJ(Z)?Z:String(Z),W=n$(Z),K=W?this.eventFromMessage(Q,J,Y):this.eventFromException(Z,Y);return this._process(()=>K.then((z)=>this._captureEvent(z,Y,$)),W?"unknown":"error"),Y.event_id}captureEvent(Z,J,X){let $=l1();if(J?.originalException&&IW(J.originalException))return l&&A.log(jf),$;let Y={event_id:$,...J},Q=Z.sdkProcessingMetadata||{},W=Q.capturedSpanScope,K=Q.capturedSpanIsolationScope,z=Cf(Z.type);return this._process(()=>this._captureEvent(Z,Y,W||X,K),z),Y.event_id}captureSession(Z){this.sendSession(Z),l5(Z,{init:!1})}getDsn(){return this._dsn}getOptions(){return this._options}getSdkMetadata(){return this._options._metadata}getTransport(){return this._transport}async flush(Z){let J=this._transport;if(!J)return!0;this.emit("flush");let X=await this._isClientDoneProcessing(Z),$=await J.flush(Z);return X&&$}async close(Z){let J=await this.flush(Z);return this.getOptions().enabled=!1,this.emit("close"),J}getEventProcessors(){return this._eventProcessors}addEventProcessor(Z){this._eventProcessors.push(Z)}init(){if(this._isEnabled()||this._options.integrations.some(({name:Z})=>Z.startsWith("Spotlight")))this._setupIntegrations()}getIntegrationByName(Z){return this._integrations[Z]}addIntegration(Z){let J=this._integrations[Z.name];if(eB(this,Z,this._integrations),!J)tB(this,[Z])}sendEvent(Z,J={}){this.emit("beforeSendEvent",Z,J);let X=mh(Z,this._dsn,this._options._metadata,this._options.tunnel);for(let $ of J.attachments||[])X=uB(X,pB($));this.sendEnvelope(X).then(($)=>this.emit("afterSendEvent",Z,$))}sendSession(Z){let{release:J,environment:X=dJ}=this._options;if("aggregates"in Z){let Y=Z.attrs||{};if(!Y.release&&!J){l&&A.warn(Mf);return}Y.release=Y.release||J,Y.environment=Y.environment||X,Z.attrs=Y}else{if(!Z.release&&!J){l&&A.warn(Mf);return}Z.release=Z.release||J,Z.environment=Z.environment||X}this.emit("beforeSendSession",Z);let $=gh(Z,this._dsn,this._options._metadata,this._options.tunnel);this.sendEnvelope($)}recordDroppedEvent(Z,J,X=1){if(this._options.sendClientReports){let $=`${Z}:${J}`;l&&A.log(`Recording outcome: "${$}"${X>1?` (${X} times)`:""}`),this._outcomes[$]=(this._outcomes[$]||0)+X}}on(Z,J){let X=this._hooks[Z]=this._hooks[Z]||new Set,$=(...Y)=>J(...Y);return X.add($),()=>{X.delete($)}}emit(Z,...J){let X=this._hooks[Z];if(X)X.forEach(($)=>$(...J))}async sendEnvelope(Z){if(this.emit("beforeEnvelope",Z),this._isEnabled()&&this._transport)try{return await this._transport.send(Z)}catch(J){return l&&A.error("Error while sending envelope:",J),{}}return l&&A.error("Transport disabled"),{}}_setupIntegrations(){let{integrations:Z}=this._options;this._integrations=zf(this,Z),tB(this,Z)}_updateSessionFromEvent(Z,J){let X=J.level==="fatal",$=!1,Y=J.exception?.values;if(Y){$=!0,X=!1;for(let K of Y)if(K.mechanism?.handled===!1){X=!0;break}}let Q=Z.status==="ok";if(Q&&Z.errors===0||Q&&X)l5(Z,{...X&&{status:"crashed"},errors:Z.errors||Number($||X)}),this.captureSession(Z)}async _isClientDoneProcessing(Z){let J=0;while(!Z||J<Z){if(await new Promise((X)=>setTimeout(X,1)),!this._numProcessing)return!0;J++}return!1}_isEnabled(){return this.getOptions().enabled!==!1&&this._transport!==void 0}_prepareEvent(Z,J,X,$){let Y=this.getOptions(),Q=Object.keys(this._integrations);if(!J.integrations&&Q?.length)J.integrations=Q;if(this.emit("preprocessEvent",Z,J),!Z.type)$.setLastEventId(Z.event_id||J.event_id);return Qf(Y,Z,J,X,this,$).then((W)=>{if(W===null)return W;this.emit("postprocessEvent",W,J),W.contexts={trace:zZ(X),...W.contexts};let K=e8(this,X);return W.sdkProcessingMetadata={dynamicSamplingContext:K,...W.sdkProcessingMetadata},W})}_captureEvent(Z,J={},X=u0(),$=R0()){if(l&&XU(Z))A.log(`Captured error event \`${rW(Z)[0]||"<unknown>"}\``);return this._processEvent(Z,J,X,$).then((Y)=>{return Y.event_id},(Y)=>{if(l)if(Tf(Y))A.log(Y.message);else if(Af(Y))A.warn(Y.message);else A.warn(Y);return})}_processEvent(Z,J,X,$){let Y=this.getOptions(),{sampleRate:Q}=Y,W=Ef(Z),K=XU(Z),G=`before send for type \`${Z.type||"error"}\``,H=typeof Q>"u"?void 0:L6(Q);if(K&&typeof H==="number"&&K4()>H)return this.recordDroppedEvent("sample_rate","error"),lJ(JU(`Discarding event because it's not included in the random sample (sampling rate = ${Q})`));let V=Cf(Z.type);return this._prepareEvent(Z,J,X,$).then((F)=>{if(F===null)throw this.recordDroppedEvent("event_processor",V),JU("An event processor returned `null`, will not send event.");if(J.data&&J.data.__sentry__===!0)return F;let U=NC0(this,Y,F,J);return CC0(U,G)}).then((F)=>{if(F===null){if(this.recordDroppedEvent("before_send",V),W){let _=1+(Z.spans||[]).length;this.recordDroppedEvent("before_send","span",_)}throw JU(`${G} returned \`null\`, will not send event.`)}let B=X.getSession()||$.getSession();if(K&&B)this._updateSessionFromEvent(B,F);if(W){let D=F.sdkProcessingMetadata?.spanCountBeforeProcessing||0,_=F.spans?F.spans.length:0,O=D-_;if(O>0)this.recordDroppedEvent("before_send","span",O)}let U=F.transaction_info;if(W&&U&&F.transaction!==Z.transaction)F.transaction_info={...U,source:"custom"};return this.sendEvent(F,J),F}).then(null,(F)=>{if(Tf(F)||Af(F))throw F;throw this.captureException(F,{mechanism:{handled:!1,type:"internal"},data:{__sentry__:!0},originalException:F}),sW(`Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.
33
+ Reason: ${F}`)})}_process(Z,J){this._numProcessing++,this._promiseBuffer.add(Z).then((X)=>{return this._numProcessing--,X},(X)=>{if(this._numProcessing--,X===FY)this.recordDroppedEvent("queue_overflow",J);return X})}_clearOutcomes(){let Z=this._outcomes;return this._outcomes={},Object.entries(Z).map(([J,X])=>{let[$,Y]=J.split(":");return{reason:$,category:Y,quantity:X}})}_flushOutcomes(){l&&A.log("Flushing outcomes...");let Z=this._clearOutcomes();if(Z.length===0){l&&A.log("No outcomes to send");return}if(!this._dsn){l&&A.log("No dsn provided, will not send outcomes");return}l&&A.log("Sending outcomes:",Z);let J=_f(Z,this._options.tunnel&&U6(this._dsn));this.sendEnvelope(J)}}function Cf(Z){return Z==="replay_event"?"replay":Z||"error"}function CC0(Z,J){let X=`${J} must return \`null\` or a valid event.`;if(I4(Z))return Z.then(($)=>{if(!d5($)&&$!==null)throw sW(X);return $},($)=>{throw sW(`${J} rejected with ${$}`)});else if(!d5(Z)&&Z!==null)throw sW(X);return Z}function NC0(Z,J,X,$){let{beforeSend:Y,beforeSendTransaction:Q,beforeSendSpan:W,ignoreSpans:K}=J,z=X;if(XU(z)&&Y)return Y(z,$);if(Ef(z)){if(W||K){let G=Of(z);if(K?.length&&JY(G,K))return null;if(W){let H=W(G);if(!H)ZY();else z=g9(X,wf(H))}if(z.spans){let H=[],V=z.spans;for(let B of V){if(K?.length&&JY(B,K)){fh(V,B);continue}if(W){let U=W(B);if(!U)ZY(),H.push(B);else H.push(U)}else H.push(B)}let F=z.spans.length-H.length;if(F)Z.recordDroppedEvent("before_send","span",F);z.spans=H}}if(Q){if(z.spans){let G=z.spans.length;z.sdkProcessingMetadata={...X.sdkProcessingMetadata,spanCountBeforeProcessing:G}}return Q(z,$)}}return z}function XU(Z){return Z.type===void 0}function Ef(Z){return Z.type==="transaction"}function RC0(Z){let J=0;if(Z.name)J+=Z.name.length*2;return J+=8,J+If(Z.attributes)}function PC0(Z){let J=0;if(Z.message)J+=Z.message.length*2;return J+If(Z.attributes)}function If(Z){if(!Z)return 0;let J=0;return Object.values(Z).forEach((X)=>{if(Array.isArray(X))J+=X.length*Nf(X[0]);else if(n$(X))J+=Nf(X);else J+=100}),J}function Nf(Z){if(typeof Z==="string")return Z.length*2;else if(typeof Z==="number")return 8;else if(typeof Z==="boolean")return 4;return 0}function yf(Z,J,X,$,Y){let Q={sent_at:new Date().toISOString()};if(X?.sdk)Q.sdk={name:X.sdk.name,version:X.sdk.version};if(!!$&&!!Y)Q.dsn=U6(Y);if(J)Q.trace=J;let W=EC0(Z);return S4(Q,[W])}function EC0(Z){return[{type:"check_in"},Z]}function Sf(Z){let J=Z._metadata?.sdk,X=J?.name&&J?.version?`${J?.name}/${J?.version}`:void 0;Z.transportOptions={...Z.transportOptions,headers:{...X&&{"user-agent":X},...Z.transportOptions?.headers}}}function kf(Z,J){return Z(J.stack||"",1)}function IC0(Z){return a8(Z)&&"__sentry_fetch_url_host__"in Z&&typeof Z.__sentry_fetch_url_host__==="string"}function yC0(Z){if(IC0(Z))return`${Z.message} (${Z.__sentry_fetch_url_host__})`;return Z.message}function YU(Z,J){let X={type:J.name||J.constructor.name,value:yC0(J)},$=kf(Z,J);if($.length)X.stacktrace={frames:$};return X}function SC0(Z){for(let J in Z)if(Object.prototype.hasOwnProperty.call(Z,J)){let X=Z[J];if(X instanceof Error)return X}return}function kC0(Z){if("name"in Z&&typeof Z.name==="string"){let $=`'${Z.name}' captured as exception`;if("message"in Z&&typeof Z.message==="string")$+=` with message '${Z.message}'`;return $}else if("message"in Z&&typeof Z.message==="string")return Z.message;let J=jB(Z);if(BB(Z))return`Event \`ErrorEvent\` captured as exception with message \`${Z.message}\``;let X=xC0(Z);return`${X&&X!=="Object"?`'${X}'`:"Object"} captured as exception with keys: ${J}`}function xC0(Z){try{let J=Object.getPrototypeOf(Z);return J?J.constructor.name:void 0}catch{}}function vC0(Z,J,X,$){if(a8(X))return[X,void 0];if(J.synthetic=!0,d5(X)){let Q=Z?.getOptions().normalizeDepth,W={["__serialized__"]:mB(X,Q)},K=SC0(X);if(K)return[K,W];let z=kC0(X),G=$?.syntheticException||Error(z);return G.message=z,[G,W]}let Y=$?.syntheticException||Error(X);return Y.message=`${X}`,[Y,void 0]}function xf(Z,J,X,$){let Q=$?.data&&$.data.mechanism||{handled:!0,type:"generic"},[W,K]=vC0(Z,Q,X,$),z={exception:{values:[YU(J,W)]}};if(K)z.extra=K;return CB(z,void 0,void 0),xJ(z,Q),{...z,event_id:$?.event_id}}function vf(Z,J,X="info",$,Y){let Q={event_id:$?.event_id,level:X};if(Y&&$?.syntheticException){let W=kf(Z,$.syntheticException);if(W.length)Q.exception={values:[{value:J,stacktrace:{frames:W}}]},xJ(Q,{synthetic:!0})}if(SJ(J)){let{__sentry_template_string__:W,__sentry_template_values__:K}=J;return Q.logentry={message:W,params:K},Q}return Q.message=J,Q}class tW extends $U{constructor(Z){vh(),Sf(Z);super(Z);this._setUpMetricsProcessing()}eventFromException(Z,J){let X=xf(this,this._options.stackParser,Z,J);return X.level="error",LZ(X)}eventFromMessage(Z,J="info",X){return LZ(vf(this._options.stackParser,Z,J,X,this._options.attachStacktrace))}captureException(Z,J,X){return hf(J),super.captureException(Z,J,X)}captureEvent(Z,J,X){if(!Z.type&&Z.exception?.values&&Z.exception.values.length>0)hf(J);return super.captureEvent(Z,J,X)}captureCheckIn(Z,J,X){let $="checkInId"in Z&&Z.checkInId?Z.checkInId:l1();if(!this._isEnabled())return l&&A.warn("SDK not enabled, will not capture check-in."),$;let Y=this.getOptions(),{release:Q,environment:W,tunnel:K}=Y,z={check_in_id:$,monitor_slug:Z.monitorSlug,status:Z.status,release:Q,environment:W};if("duration"in Z)z.duration=Z.duration;if(J)z.monitor_config={schedule:J.schedule,checkin_margin:J.checkinMargin,max_runtime:J.maxRuntime,timezone:J.timezone,failure_issue_threshold:J.failureIssueThreshold,recovery_threshold:J.recoveryThreshold};let[G,H]=Gf(this,X);if(H)z.contexts={trace:H};let V=yf(z,G,this.getSdkMetadata(),K,this.getDsn());return l&&A.log("Sending checkin:",Z.monitorSlug,Z.status),this.sendEnvelope(V),$}_prepareEvent(Z,J,X,$){if(this._options.platform)Z.platform=Z.platform||this._options.platform;if(this._options.runtime)Z.contexts={...Z.contexts,runtime:Z.contexts?.runtime||this._options.runtime};if(this._options.serverName)Z.server_name=Z.server_name||this._options.serverName;return super._prepareEvent(Z,J,X,$)}_setUpMetricsProcessing(){this.on("processMetric",(Z)=>{if(this._options.serverName)Z.attributes={"server.address":this._options.serverName,...Z.attributes}})}}function hf(Z){let J=R0().getScopeData().sdkProcessingMetadata.requestSession;if(J){let X=Z?.mechanism?.handled??!0;if(X&&J.status!=="crashed")J.status="errored";else if(!X)J.status="crashed"}}var QU=new Set;function WU(Z){Z.forEach((J)=>{QU.add(J),l&&A.log(`AI provider "${J}" wrapping will be skipped`)})}function OZ(Z){return QU.has(Z)}function KU(){QU.clear(),l&&A.log("Cleared AI provider skip registrations")}var hC0="thismessage:/";function zU(Z){return"isRelative"in Z}function BY(Z,J){let X=Z.indexOf("://")<=0&&Z.indexOf("//")!==0,$=J??(X?hC0:void 0);try{if("canParse"in URL&&!URL.canParse(Z,$))return;let Y=new URL(Z,$);if(X)return{isRelative:X,pathname:Y.pathname,search:Y.search,hash:Y.hash};return Y}catch{}return}function n9(Z){if(!Z)return{};let J=Z.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!J)return{};let X=J[6]||"",$=J[8]||"";return{host:J[4],path:J[5],protocol:J[2],search:X,hash:$,relative:J[5]+X+$}}function p5(Z){return Z.split(/[?#]/,1)[0]}function o9(Z){let{protocol:J,host:X,path:$}=Z,Y=X?.replace(/^.*@/,"[filtered]:[filtered]@").replace(/(:80)$/,"").replace(/(:443)$/,"")||"";return`${J?`${J}://`:""}${Y}${$}`}function i5(Z,J,X=[J],$="npm"){let Y=Z._metadata||{};if(!Y.sdk)Y.sdk={name:`sentry.javascript.${J}`,packages:X.map((Q)=>({name:`${$}:@sentry/${Q}`,version:N0})),version:N0};Z._metadata=Y}function pJ(Z={}){let J=Z.client||u();if(!nW()||!J)return{};let X=O4(),$=b6(X);if($.getTraceData)return $.getTraceData(Z);let Y=Z.scope||u0(),Q=Z.span||t8(),W=Q?fW(Q):fC0(Y),K=Q?S1(Q):e8(J,Y),z=GZ(K);if(!s$.test(W))return A.warn("Invalid sentry-trace data. Cannot generate trace data"),{};let H={"sentry-trace":W,baggage:z};if(Z.propagateTraceparent)H.traceparent=Q?kh(Q):bC0(Y);return H}function fC0(Z){let{traceId:J,sampled:X,propagationSpanId:$}=Z.getPropagationContext();return u9(J,$,X)}function bC0(Z){let{traceId:J,sampled:X,propagationSpanId:$}=Z.getPropagationContext();return c9(J,$,X)}function GU(Z,J,X){let $,Y,Q,W=X?.maxWait?Math.max(X.maxWait,J):0,K=X?.setTimeoutImpl||setTimeout;function z(){return G(),$=Z(),$}function G(){Y!==void 0&&clearTimeout(Y),Q!==void 0&&clearTimeout(Q),Y=Q=void 0}function H(){if(Y!==void 0||Q!==void 0)return z();return $}function V(){if(Y)clearTimeout(Y);if(Y=K(z,J),W&&Q===void 0)Q=K(z,W);return $}return V.cancel=G,V.flush=H,V}function gf(Z){let J=Object.create(null);try{Object.entries(Z).forEach(([X,$])=>{if(typeof $==="string")J[X]=$})}catch{}return J}function UY(Z){let J=Z.headers||{},$=(typeof J["x-forwarded-host"]==="string"?J["x-forwarded-host"]:void 0)||(typeof J.host==="string"?J.host:void 0),Q=(typeof J["x-forwarded-proto"]==="string"?J["x-forwarded-proto"]:void 0)||Z.protocol||(Z.socket?.encrypted?"https":"http"),W=Z.url||"",K=gC0({url:W,host:$,protocol:Q}),z=Z.body||void 0,G=Z.cookies;return{url:K,method:Z.method,query_string:mf(W),headers:gf(J),cookies:G,data:z}}function gC0({url:Z,protocol:J,host:X}){if(Z?.startsWith("http"))return Z;if(Z&&X)return`${J}://${X}${Z}`;return}var ff=["auth","token","secret","session","password","passwd","pwd","key","jwt","bearer","sso","saml","csrf","xsrf","credentials","set-cookie","cookie"],mC0=["x-forwarded-","-user"];function iJ(Z,J=!1){let X={};try{Object.entries(Z).forEach(([$,Y])=>{if(Y==null)return;let Q=$.toLowerCase();if((Q==="cookie"||Q==="set-cookie")&&typeof Y==="string"&&Y!==""){let K=Q==="set-cookie",z=Y.indexOf(";"),G=K&&z!==-1?Y.substring(0,z):Y,H=K?[G]:G.split("; ");for(let V of H){let F=V.indexOf("="),B=F!==-1?V.substring(0,F):V,U=F!==-1?V.substring(F+1):"",D=B.toLowerCase();bf(X,Q,D,U,J)}}else bf(X,Q,"",Y,J)})}catch{}return X}function HU(Z){return Z.replace(/-/g,"_")}function bf(Z,J,X,$,Y){let Q=X?`http.request.header.${HU(J)}.${HU(X)}`:`http.request.header.${HU(J)}`,W=dC0(X||J,$,Y);if(W!==void 0)Z[Q]=W}function dC0(Z,J,X){if(X?ff.some((Y)=>Z.includes(Y)):[...mC0,...ff].some((Y)=>Z.includes(Y)))return"[Filtered]";else if(Array.isArray(J))return J.map((Y)=>Y!=null?String(Y):Y).join(";");else if(typeof J==="string")return J;return}function mf(Z){if(!Z)return;try{let J=new URL(Z,"http://s.io").search.slice(1);return J.length?J:void 0}catch{return}}var uC0=100;function g6(Z,J){let X=u(),$=R0();if(!X)return;let{beforeBreadcrumb:Y=null,maxBreadcrumbs:Q=uC0}=X.getOptions();if(Q<=0)return;let K={timestamp:c5(),...Z},z=Y?y1(()=>Y(K,J)):K;if(z===null)return;if(X.emit)X.emit("beforeAddBreadcrumb",z,J);$.addBreadcrumb(z,Q)}var df,cC0="FunctionToString",uf=new WeakMap,lC0=()=>{return{name:cC0,setupOnce(){df=Function.prototype.toString;try{Function.prototype.toString=function(...Z){let J=wB(this),X=uf.has(u())&&J!==void 0?J:this;return df.apply(X,Z)}}catch{}},setup(Z){uf.set(Z,!0)}}},nJ=S(lC0);var pC0=[/^Script error\.?$/,/^Javascript error: Script error\.? on line 0$/,/^ResizeObserver loop completed with undelivered notifications.$/,/^Cannot redefine property: googletag$/,/^Can't find variable: gmo$/,/^undefined is not an object \(evaluating 'a\.[A-Z]'\)$/,`can't redefine non-configurable property "solana"`,"vv().getRestrictions is not a function. (In 'vv().getRestrictions(1,a)', 'vv().getRestrictions' is undefined)","Can't find variable: _AutofillCallbackHandler",/^Non-Error promise rejection captured with value: Object Not Found Matching Id:\d+, MethodName:simulateEvent, ParamCount:\d+$/,/^Java exception was raised during method invocation$/],iC0="EventFilters",VU=S((Z={})=>{let J;return{name:iC0,setup(X){let $=X.getOptions();J=cf(Z,$)},processEvent(X,$,Y){if(!J){let Q=Y.getOptions();J=cf(Z,Q)}return nC0(X,J)?null:X}}}),oJ=S((Z={})=>{return{...VU(Z),name:"InboundFilters"}});function cf(Z={},J={}){return{allowUrls:[...Z.allowUrls||[],...J.allowUrls||[]],denyUrls:[...Z.denyUrls||[],...J.denyUrls||[]],ignoreErrors:[...Z.ignoreErrors||[],...J.ignoreErrors||[],...Z.disableErrorDefaults?[]:pC0],ignoreTransactions:[...Z.ignoreTransactions||[],...J.ignoreTransactions||[]]}}function nC0(Z,J){if(!Z.type){if(oC0(Z,J.ignoreErrors))return l&&A.warn(`Event dropped due to being matched by \`ignoreErrors\` option.
34
34
  Event: ${f9(Z)}`),!0;if(eC0(Z))return l&&A.warn(`Event dropped due to not having an error message, error type or stacktrace.
35
35
  Event: ${f9(Z)}`),!0;if(rC0(Z,J.denyUrls))return l&&A.warn(`Event dropped due to being matched by \`denyUrls\` option.
36
36
  Event: ${f9(Z)}.
37
37
  Url: ${eW(Z)}`),!0;if(!sC0(Z,J.allowUrls))return l&&A.warn(`Event dropped due to not being matched by \`allowUrls\` option.
38
38
  Event: ${f9(Z)}.
39
39
  Url: ${eW(Z)}`),!0}else if(Z.type==="transaction"){if(aC0(Z,J.ignoreTransactions))return l&&A.warn(`Event dropped due to being matched by \`ignoreTransactions\` option.
40
- Event: ${f9(Z)}`),!0}return!1}function oC0(Z,J){if(!J?.length)return!1;return rW(Z).some((X)=>h9(X,J))}function aC0(Z,J){if(!J?.length)return!1;let X=Z.transaction;return X?h9(X,J):!1}function rC0(Z,J){if(!J?.length)return!1;let X=eW(Z);return!X?!1:h9(X,J)}function sC0(Z,J){if(!J?.length)return!0;let X=eW(Z);return!X?!0:h9(X,J)}function tC0(Z=[]){for(let J=Z.length-1;J>=0;J--){let X=Z[J];if(X&&X.filename!=="<anonymous>"&&X.filename!=="[native code]")return X.filename||null}return null}function eW(Z){try{let X=[...Z.exception?.values??[]].reverse().find(($)=>$.mechanism?.parent_id===void 0&&$.stacktrace?.frames?.length)?.stacktrace?.frames;return X?tC0(X):null}catch{return l&&A.error(`Cannot extract url for event ${f9(Z)}`),null}}function eC0(Z){if(!Z.exception?.values?.length)return!1;return!Z.message&&!Z.exception.values.some((J)=>J.stacktrace||J.type&&J.type!=="Error"||J.value)}function nf(Z,J,X,$,Y,Q){if(!Y.exception?.values||!Q||!r8(Q.originalException,Error))return;let W=Y.exception.values.length>0?Y.exception.values[Y.exception.values.length-1]:void 0;if(W)Y.exception.values=FU(Z,J,$,Q.originalException,X,Y.exception.values,W,0)}function FU(Z,J,X,$,Y,Q,W,K){if(Q.length>=X+1)return Q;let z=[...Q];if(r8($[Y],Error)){lf(W,K);let G=Z(J,$[Y]),H=z.length;pf(G,Y,H,K),z=FU(Z,J,X,$[Y],Y,[G,...z],G,H)}if(Array.isArray($.errors))$.errors.forEach((G,H)=>{if(r8(G,Error)){lf(W,K);let V=Z(J,G),F=z.length;pf(V,`errors[${H}]`,F,K),z=FU(Z,J,X,G,Y,[V,...z],V,F)}});return z}function lf(Z,J){Z.mechanism={handled:!0,type:"auto.core.linked_errors",...Z.mechanism,...Z.type==="AggregateError"&&{is_exception_group:!0},exception_id:J}}function pf(Z,J,X,$){Z.mechanism={handled:!0,...Z.mechanism,type:"chained",source:J,exception_id:X,parent_id:$}}var ZN0="cause",JN0=5,XN0="LinkedErrors",$N0=(Z={})=>{let J=Z.limit||JN0,X=Z.key||ZN0;return{name:XN0,preprocessEvent($,Y,Q){let W=Q.getOptions();nf(YU,W.stackParser,X,J,$,Y)}}},aJ=S($N0);function of(Z){let J={},X=0;while(X<Z.length){let $=Z.indexOf("=",X);if($===-1)break;let Y=Z.indexOf(";",X);if(Y===-1)Y=Z.length;else if(Y<$){X=Z.lastIndexOf(";",$-1)+1;continue}let Q=Z.slice(X,$).trim();if(J[Q]===void 0){let W=Z.slice($+1,Y).trim();if(W.charCodeAt(0)===34)W=W.slice(1,-1);try{J[Q]=W.indexOf("%")!==-1?decodeURIComponent(W):W}catch{J[Q]=W}}X=Y+1}return J}var BU=["X-Client-IP","X-Forwarded-For","Fly-Client-IP","CF-Connecting-IP","Fastly-Client-Ip","True-Client-Ip","X-Real-IP","X-Cluster-Client-IP","X-Forwarded","Forwarded-For","Forwarded","X-Vercel-Forwarded-For"];function af(Z){return BU.map((Y)=>{let Q=Z[Y],W=Array.isArray(Q)?Q.join(";"):Q;if(Y==="Forwarded")return YN0(W);return W?.split(",").map((K)=>K.trim())}).reduce((Y,Q)=>{if(!Q)return Y;return Y.concat(Q)},[]).find((Y)=>Y!==null&&QN0(Y))||null}function YN0(Z){if(!Z)return null;for(let J of Z.split(";"))if(J.startsWith("for="))return J.slice(4);return null}function QN0(Z){return/(?:^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$)|(?:^(?:(?:[a-fA-F\d]{1,4}:){7}(?:[a-fA-F\d]{1,4}|:)|(?:[a-fA-F\d]{1,4}:){6}(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|:[a-fA-F\d]{1,4}|:)|(?:[a-fA-F\d]{1,4}:){5}(?::(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,2}|:)|(?:[a-fA-F\d]{1,4}:){4}(?:(?::[a-fA-F\d]{1,4}){0,1}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,3}|:)|(?:[a-fA-F\d]{1,4}:){3}(?:(?::[a-fA-F\d]{1,4}){0,2}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,4}|:)|(?:[a-fA-F\d]{1,4}:){2}(?:(?::[a-fA-F\d]{1,4}){0,3}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,5}|:)|(?:[a-fA-F\d]{1,4}:){1}(?:(?::[a-fA-F\d]{1,4}){0,4}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,6}|:)|(?::(?:(?::[a-fA-F\d]{1,4}){0,5}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,7}|:)))(?:%[0-9a-zA-Z]{1,})?$)/.test(Z)}var WN0={cookies:!0,data:!0,headers:!0,query_string:!0,url:!0},KN0="RequestData",zN0=(Z={})=>{let J={...WN0,...Z.include};return{name:KN0,processEvent(X,$,Y){let{sdkProcessingMetadata:Q={}}=X,{normalizedRequest:W,ipAddress:K}=Q,z={...J,ip:J.ip??Y.getOptions().sendDefaultPii};if(W)GN0(X,W,{ipAddress:K},z);return X}}},rJ=S(zN0);function GN0(Z,J,X,$){if(Z.request={...Z.request,...HN0(J,$)},$.ip){let Y=J.headers&&af(J.headers)||X.ipAddress;if(Y)Z.user={...Z.user,ip_address:Y}}}function HN0(Z,J){let X={},$={...Z.headers};if(J.headers){if(X.headers=$,!J.cookies)delete $.cookie;if(!J.ip)BU.forEach((Y)=>{delete $[Y]})}if(X.method=Z.method,J.url)X.url=Z.url;if(J.cookies){let Y=Z.cookies||($?.cookie?of($.cookie):void 0);X.cookies=Y||{}}if(J.query_string)X.query_string=Z.query_string;if(J.data)X.data=Z.data;return X}function rf(Z){EJ("console",Z),IJ("console",VN0)}function VN0(){if(!("console"in Q0))return;p$.forEach(function(Z){if(!(Z in Q0.console))return;OB(Q0.console,Z,function(J){return PJ[Z]=J,function(...X){yJ("console",{args:X,level:Z}),PJ[Z]?.apply(Q0.console,X)}})})}function sf(Z){return Z==="warn"?"warning":["fatal","error","warning","log","info","debug"].includes(Z)?Z:"log"}var FN0=/^(\S+:\\|\/?)([\s\S]*?)((?:\.{1,2}|[^/\\]+?|)(\.[^./\\]*|))(?:[/\\]*)$/;function BN0(Z){let J=Z.length>1024?`<truncated>${Z.slice(-1024)}`:Z,X=FN0.exec(J);return X?X.slice(1):[]}function UU(Z){let J=BN0(Z),X=J[0]||"",$=J[1];if(!X&&!$)return".";if($)$=$.slice(0,$.length-1);return X+$}var UN0="Console",sJ=S((Z={})=>{let J=new Set(Z.levels||p$);return{name:UN0,setup(X){rf(({args:$,level:Y})=>{if(u()!==X||!J.has(Y))return;LN0(Y,$)})}}});function LN0(Z,J){let X={category:"console",data:{arguments:J,logger:"console"},level:sf(Z),message:tf(J)};if(Z==="assert")if(J[0]===!1){let $=J.slice(1);X.message=$.length>0?`Assertion failed: ${tf($)}`:"Assertion failed",X.data.arguments=$}else return;g6(X,{input:J,level:Z})}function tf(Z){return"util"in Q0&&typeof Q0.util.format==="function"?Q0.util.format(...Z):AB(Z," ")}var ef="gen_ai.prompt",a9="gen_ai.system",C1="gen_ai.request.model",tJ="gen_ai.request.stream",r9="gen_ai.request.temperature",eJ="gen_ai.request.max_tokens",s9="gen_ai.request.frequency_penalty",ZX="gen_ai.request.presence_penalty",t9="gen_ai.request.top_p",ZK="gen_ai.request.top_k",Zb="gen_ai.request.encoding_format",Jb="gen_ai.request.dimensions",e4="gen_ai.response.finish_reasons",l1="gen_ai.response.model",m6="gen_ai.response.id",Xb="gen_ai.response.stop_reason",D1="gen_ai.usage.input_tokens",b1="gen_ai.usage.output_tokens",O6="gen_ai.usage.total_tokens",w4="gen_ai.operation.name",Z6="gen_ai.request.messages.original_length",G4="gen_ai.request.messages",g1="gen_ai.response.text",e9="gen_ai.request.available_tools",wZ="gen_ai.response.streaming",t1="gen_ai.response.tool_calls",LU="gen_ai.agent.name",$b="gen_ai.pipeline.name",LY="gen_ai.conversation.id",Yb="gen_ai.usage.cache_creation_input_tokens",Qb="gen_ai.usage.cache_read_input_tokens",DU="gen_ai.usage.input_tokens.cache_write",Z7="gen_ai.usage.input_tokens.cached",JK="gen_ai.invoke_agent",Wb="gen_ai.generate_text",Kb="gen_ai.stream_text",zb="gen_ai.generate_object",Gb="gen_ai.stream_object",Hb="gen_ai.embed",Vb="gen_ai.embed_many",Fb="gen_ai.execute_tool",_U="openai.response.id",OU="openai.response.model",wU="openai.response.timestamp",Bb="openai.usage.completion_tokens",Ub="openai.usage.prompt_tokens",DY={CHAT:"chat",RESPONSES:"responses",EMBEDDINGS:"embeddings",CONVERSATIONS:"conversations"},jU="anthropic.response.timestamp";var _Y=new Map;var $K=(Z)=>{return new TextEncoder().encode(Z).length},YK=(Z)=>{return $K(JSON.stringify(Z))};function AU(Z,J){if($K(Z)<=J)return Z;let X=0,$=Z.length,Y="";while(X<=$){let Q=Math.floor((X+$)/2),W=Z.slice(0,Q);if($K(W)<=J)Y=W,X=Q+1;else $=Q-1}return Y}function DN0(Z){if(typeof Z==="string")return Z;if("text"in Z)return Z.text;return""}function Lb(Z,J){if(typeof Z==="string")return J;return{...Z,text:J}}function _N0(Z){return Z!==null&&typeof Z==="object"&&"content"in Z&&typeof Z.content==="string"}function ON0(Z){return Z!==null&&typeof Z==="object"&&"content"in Z&&Array.isArray(Z.content)}function OY(Z){if(!Z||typeof Z!=="object")return!1;return wN0(Z)||_b(Z)||"media_type"in Z&&typeof Z.media_type==="string"&&"data"in Z||"image_url"in Z&&typeof Z.image_url==="string"&&Z.image_url.startsWith("data:")||"type"in Z&&(Z.type==="blob"||Z.type==="base64")||"b64_json"in Z||"type"in Z&&"result"in Z&&Z.type==="image_generation"||"uri"in Z&&typeof Z.uri==="string"&&Z.uri.startsWith("data:")}function wN0(Z){return"type"in Z&&typeof Z.type==="string"&&"source"in Z&&OY(Z.source)}function _b(Z){return"inlineData"in Z&&!!Z.inlineData&&typeof Z.inlineData==="object"&&"data"in Z.inlineData&&typeof Z.inlineData.data==="string"}function Ob(Z){return Z!==null&&typeof Z==="object"&&"parts"in Z&&Array.isArray(Z.parts)&&Z.parts.length>0}function jN0(Z,J){let X={...Z,content:""},$=YK(X),Y=J-$;if(Y<=0)return[];let Q=AU(Z.content,Y);return[{...Z,content:Q}]}function MN0(Z,J){let{parts:X}=Z,$=X.map((K)=>Lb(K,"")),Y=YK({...Z,parts:$}),Q=J-Y;if(Q<=0)return[];let W=[];for(let K of X){let z=DN0(K),G=$K(z);if(G<=Q)W.push(K),Q-=G;else if(W.length===0){let H=AU(z,Q);if(H)W.push(Lb(K,H));break}else break}if(W.length<=0)return[];else return[{...Z,parts:W}]}function AN0(Z,J){if(!Z||typeof Z!=="object")return[];if(_N0(Z))return jN0(Z,J);if(Ob(Z))return MN0(Z,J);return[]}var Db="[Filtered]",TN0=["image_url","data","content","b64_json","result","uri"];function XK(Z){let J={...Z};if(OY(J.source))J.source=XK(J.source);if(_b(Z))J.inlineData={...Z.inlineData,data:Db};for(let X of TN0)if(typeof J[X]==="string")J[X]=Db;return J}function MU(Z){return Z.map((X)=>{let $=void 0;if(!!X&&typeof X==="object"){if(ON0(X))$={...X,content:MU(X.content)};else if("content"in X&&OY(X.content))$={...X,content:XK(X.content)};if(Ob(X))$={...$??X,parts:MU(X.parts)};if(OY($))$=XK($);else if(OY(X))$=XK(X)}return $??X})}function qN0(Z,J){if(!Array.isArray(Z)||Z.length===0)return Z;let X=MU(Z);if(YK(X)<=J)return X;let Y=X.map(YK),Q=0,W=X.length;for(let K=X.length-1;K>=0;K--){let z=Y[K];if(z&&Q+z>J)break;if(z)Q+=z;W=K}if(W===X.length){let K=X[X.length-1];return AN0(K,J)}return X.slice(W)}function J7(Z){return qN0(Z,20000)}function wb(Z){return AU(Z,20000)}function jZ(Z){if(Z.includes("messages"))return"messages";if(Z.includes("completions"))return"completions";if(Z.includes("models"))return"models";if(Z.includes("chat"))return"chat";return Z.split(".").pop()||"unknown"}function JX(Z){return`gen_ai.${jZ(Z)}`}function QK(Z,J){return Z?`${Z}.${J}`:J}function wY(Z,J,X,$,Y){if(J!==void 0)Z.setAttributes({[D1]:J});if(X!==void 0)Z.setAttributes({[b1]:X});if(J!==void 0||X!==void 0||$!==void 0||Y!==void 0){let Q=(J??0)+(X??0)+($??0)+(Y??0);Z.setAttributes({[O6]:Q})}}function X7(Z){if(typeof Z==="string")return wb(Z);if(Array.isArray(Z)){let J=J7(Z);return JSON.stringify(J)}return JSON.stringify(Z)}var jb="operation.name",WK="ai.prompt",Mb="ai.schema",Ab="ai.response.object",Tb="ai.response.text",qb="ai.response.toolCalls",MZ="ai.prompt.messages",XX="ai.prompt.tools",jY="ai.model.id",Cb="ai.response.providerMetadata",Nb="ai.usage.cachedInputTokens",Rb="ai.telemetry.functionId",Pb="ai.usage.completionTokens",Eb="ai.usage.promptTokens",TU="ai.toolCall.name",qU="ai.toolCall.id",Ib="ai.toolCall.args",yb="ai.toolCall.result";function Sb(Z,J){let X=Z.parent_span_id;if(!X)return;let $=Z.data[D1],Y=Z.data[b1];if(typeof $==="number"||typeof Y==="number"){let Q=J.get(X)||{inputTokens:0,outputTokens:0};if(typeof $==="number")Q.inputTokens+=$;if(typeof Y==="number")Q.outputTokens+=Y;J.set(X,Q)}}function CU(Z,J){let X=J.get(Z.span_id);if(!X||!Z.data)return;if(X.inputTokens>0)Z.data[D1]=X.inputTokens;if(X.outputTokens>0)Z.data[b1]=X.outputTokens;if(X.inputTokens>0||X.outputTokens>0)Z.data["gen_ai.usage.total_tokens"]=X.inputTokens+X.outputTokens}function NU(Z){return _Y.get(Z)}function RU(Z){_Y.delete(Z)}function kb(Z){let J=Z.map((X)=>{if(typeof X==="string")try{return JSON.parse(X)}catch{return X}return X});return JSON.stringify(J)}function CN0(Z){try{let J=JSON.parse(Z);if(!!J&&typeof J==="object"){let{prompt:X,system:$}=J;if(typeof X==="string"||typeof $==="string"){let Y=[];if(typeof $==="string")Y.push({role:"system",content:$});if(typeof X==="string")Y.push({role:"user",content:X});return Y}}}catch{}return[]}function xb(Z,J){if(J[WK]){let $=X7(J[WK]);Z.setAttribute("gen_ai.prompt",$)}let X=J[WK];if(typeof X==="string"&&!J[G4]&&!J[MZ]){let $=CN0(X);if($.length)Z.setAttributes({[G4]:X7($),[Z6]:$.length})}else if(typeof J[MZ]==="string")try{let $=JSON.parse(J[MZ]);if(Array.isArray($))Z.setAttributes({[MZ]:void 0,[G4]:X7($),[Z6]:$.length})}catch{}}function vb(Z){switch(Z){case"ai.generateText":case"ai.streamText":case"ai.generateObject":case"ai.streamObject":case"ai.embed":case"ai.embedMany":return JK;case"ai.generateText.doGenerate":return Wb;case"ai.streamText.doStream":return Kb;case"ai.generateObject.doGenerate":return zb;case"ai.streamObject.doStream":return Gb;case"ai.embed.doEmbed":return Hb;case"ai.embedMany.doEmbed":return Vb;case"ai.toolCall":return Fb;default:if(Z.startsWith("ai.stream"))return"ai.run";return}}function hb(Z,J){Z.setAttribute(X0,J)}function NN0(Z){let{data:J,description:X}=J0(Z);if(!X)return;if(J[TU]&&J[qU]&&X==="ai.toolCall"){EN0(Z,J);return}if(!X.startsWith("ai."))return;IN0(Z,X,J)}function RN0(Z){if(Z.type==="transaction"&&Z.spans){let J=new Map;for(let $ of Z.spans)PN0($),Sb($,J);for(let $ of Z.spans){if($.op!=="gen_ai.invoke_agent")continue;CU($,J)}let X=Z.contexts?.trace;if(X&&X.op==="gen_ai.invoke_agent")CU(X,J)}return Z}function PN0(Z){let{data:J,origin:X}=Z;if(X!=="auto.vercelai.otel")return;if(j4(J,Pb,b1),j4(J,Eb,D1),j4(J,Nb,Z7),typeof J[D1]==="number"&&typeof J[Z7]==="number")J[D1]=J[D1]+J[Z7];if(typeof J[b1]==="number"&&typeof J[D1]==="number")J["gen_ai.usage.total_tokens"]=J[b1]+J[D1];if(J[XX]&&Array.isArray(J[XX]))J[XX]=kb(J[XX]);j4(J,jb,w4),j4(J,MZ,G4),j4(J,Tb,"gen_ai.response.text"),j4(J,qb,"gen_ai.response.tool_calls"),j4(J,Ab,"gen_ai.response.object"),j4(J,XX,"gen_ai.request.available_tools"),j4(J,Ib,"gen_ai.tool.input"),j4(J,yb,"gen_ai.tool.output"),j4(J,Mb,"gen_ai.request.schema"),j4(J,jY,C1),yN0(J);for(let $ of Object.keys(J))if($.startsWith("ai."))j4(J,$,`vercel.${$}`)}function j4(Z,J,X){if(Z[J]!=null)Z[X]=Z[J],delete Z[J]}function EN0(Z,J){hb(Z,"auto.vercelai.otel"),Z.setAttribute(K0,"gen_ai.execute_tool"),j4(J,TU,"gen_ai.tool.name"),j4(J,qU,"gen_ai.tool.call.id");let X=J["gen_ai.tool.call.id"];if(typeof X==="string")_Y.set(X,Z);if(!J["gen_ai.tool.type"])Z.setAttribute("gen_ai.tool.type","function");let $=J["gen_ai.tool.name"];if($)Z.updateName(`execute_tool ${$}`)}function IN0(Z,J,X){hb(Z,"auto.vercelai.otel");let $=J.replace("ai.","");Z.setAttribute("ai.pipeline.name",$),Z.updateName($);let Y=X[Rb];if(Y&&typeof Y==="string")Z.updateName(`${$} ${Y}`),Z.setAttribute("gen_ai.function_id",Y);if(xb(Z,X),X[jY]&&!X[l1])Z.setAttribute(l1,X[jY]);Z.setAttribute("ai.streaming",J.includes("stream"));let Q=vb(J);if(Q)Z.setAttribute(K0,Q);let W=X[jY];if(W)switch(J){case"ai.generateText.doGenerate":Z.updateName(`generate_text ${W}`);break;case"ai.streamText.doStream":Z.updateName(`stream_text ${W}`);break;case"ai.generateObject.doGenerate":Z.updateName(`generate_object ${W}`);break;case"ai.streamObject.doStream":Z.updateName(`stream_object ${W}`);break;case"ai.embed.doEmbed":Z.updateName(`embed ${W}`);break;case"ai.embedMany.doEmbed":Z.updateName(`embed_many ${W}`);break}}function KK(Z){Z.on("spanStart",NN0),Z.addEventProcessor(Object.assign(RN0,{id:"VercelAiEventProcessor"}))}function yN0(Z){let J=Z[Cb];if(J)try{let X=JSON.parse(J),$=X.openai??X.azure;if($)N8(Z,Z7,$.cachedPromptTokens),N8(Z,"gen_ai.usage.output_tokens.reasoning",$.reasoningTokens),N8(Z,"gen_ai.usage.output_tokens.prediction_accepted",$.acceptedPredictionTokens),N8(Z,"gen_ai.usage.output_tokens.prediction_rejected",$.rejectedPredictionTokens),N8(Z,"gen_ai.conversation.id",$.responseId);if(X.anthropic){let Y=X.anthropic.usage?.cache_read_input_tokens??X.anthropic.cacheReadInputTokens;N8(Z,Z7,Y);let Q=X.anthropic.usage?.cache_creation_input_tokens??X.anthropic.cacheCreationInputTokens;N8(Z,DU,Q)}if(X.bedrock?.usage)N8(Z,Z7,X.bedrock.usage.cacheReadInputTokens),N8(Z,DU,X.bedrock.usage.cacheWriteInputTokens);if(X.deepseek)N8(Z,Z7,X.deepseek.promptCacheHitTokens),N8(Z,"gen_ai.usage.input_tokens.cache_miss",X.deepseek.promptCacheMissTokens)}catch{}}function N8(Z,J,X){if(X!=null)Z[J]=X}var $7="OpenAI",fb=["responses.create","chat.completions.create","embeddings.create","conversations.create"],SN0=["response.output_item.added","response.function_call_arguments.delta","response.function_call_arguments.done","response.output_item.done"],bb=["response.created","response.in_progress","response.failed","response.completed","response.incomplete","response.queued","response.output_text.delta",...SN0];function zK(Z){if(Z.includes("chat.completions"))return DY.CHAT;if(Z.includes("responses"))return DY.RESPONSES;if(Z.includes("embeddings"))return DY.EMBEDDINGS;if(Z.includes("conversations"))return DY.CONVERSATIONS;return Z.split(".").pop()||"unknown"}function PU(Z){return`gen_ai.${zK(Z)}`}function gb(Z){return fb.includes(Z)}function mb(Z,J){return Z?`${Z}.${J}`:J}function db(Z){return Z!==null&&typeof Z==="object"&&"object"in Z&&Z.object==="chat.completion"}function ub(Z){return Z!==null&&typeof Z==="object"&&"object"in Z&&Z.object==="response"}function cb(Z){if(Z===null||typeof Z!=="object"||!("object"in Z))return!1;let J=Z;return J.object==="list"&&typeof J.model==="string"&&J.model.toLowerCase().includes("embedding")}function lb(Z){return Z!==null&&typeof Z==="object"&&"object"in Z&&Z.object==="conversation"}function pb(Z){return Z!==null&&typeof Z==="object"&&"type"in Z&&typeof Z.type==="string"&&Z.type.startsWith("response.")}function ib(Z){return Z!==null&&typeof Z==="object"&&"object"in Z&&Z.object==="chat.completion.chunk"}function nb(Z,J,X){if(GK(Z,J.id,J.model,J.created),J.usage)MY(Z,J.usage.prompt_tokens,J.usage.completion_tokens,J.usage.total_tokens);if(Array.isArray(J.choices)){let $=J.choices.map((Y)=>Y.finish_reason).filter((Y)=>Y!==null);if($.length>0)Z.setAttributes({[e4]:JSON.stringify($)});if(X){let Y=J.choices.map((Q)=>Q.message?.tool_calls).filter((Q)=>Array.isArray(Q)&&Q.length>0).flat();if(Y.length>0)Z.setAttributes({[t1]:JSON.stringify(Y)})}}}function ob(Z,J,X){if(GK(Z,J.id,J.model,J.created_at),J.status)Z.setAttributes({[e4]:JSON.stringify([J.status])});if(J.usage)MY(Z,J.usage.input_tokens,J.usage.output_tokens,J.usage.total_tokens);if(X){let $=J;if(Array.isArray($.output)&&$.output.length>0){let Y=$.output.filter((Q)=>typeof Q==="object"&&Q!==null&&Q.type==="function_call");if(Y.length>0)Z.setAttributes({[t1]:JSON.stringify(Y)})}}}function ab(Z,J){if(Z.setAttributes({[OU]:J.model,[l1]:J.model}),J.usage)MY(Z,J.usage.prompt_tokens,void 0,J.usage.total_tokens)}function rb(Z,J){let{id:X,created_at:$}=J;if(Z.setAttributes({[_U]:X,[m6]:X,[LY]:X}),$)Z.setAttributes({[wU]:new Date($*1000).toISOString()})}function MY(Z,J,X,$){if(J!==void 0)Z.setAttributes({[Ub]:J,[D1]:J});if(X!==void 0)Z.setAttributes({[Bb]:X,[b1]:X});if($!==void 0)Z.setAttributes({[O6]:$})}function GK(Z,J,X,$){Z.setAttributes({[_U]:J,[m6]:J}),Z.setAttributes({[OU]:X,[l1]:X}),Z.setAttributes({[wU]:new Date($*1000).toISOString()})}function kN0(Z){if("conversation"in Z&&typeof Z.conversation==="string")return Z.conversation;if("previous_response_id"in Z&&typeof Z.previous_response_id==="string")return Z.previous_response_id;return}function sb(Z){let J={[C1]:Z.model??"unknown"};if("temperature"in Z)J[r9]=Z.temperature;if("top_p"in Z)J[t9]=Z.top_p;if("frequency_penalty"in Z)J[s9]=Z.frequency_penalty;if("presence_penalty"in Z)J[ZX]=Z.presence_penalty;if("stream"in Z)J[tJ]=Z.stream;if("encoding_format"in Z)J[Zb]=Z.encoding_format;if("dimensions"in Z)J[Jb]=Z.dimensions;let X=kN0(Z);if(X)J[LY]=X;return J}function xN0(Z,J){for(let X of Z){let $=X.index;if($===void 0||!X.function)continue;if(!($ in J.chatCompletionToolCalls))J.chatCompletionToolCalls[$]={...X,function:{name:X.function.name,arguments:X.function.arguments||""}};else{let Y=J.chatCompletionToolCalls[$];if(X.function.arguments&&Y?.function)Y.function.arguments+=X.function.arguments}}}function vN0(Z,J,X){if(J.responseId=Z.id??J.responseId,J.responseModel=Z.model??J.responseModel,J.responseTimestamp=Z.created??J.responseTimestamp,Z.usage)J.promptTokens=Z.usage.prompt_tokens,J.completionTokens=Z.usage.completion_tokens,J.totalTokens=Z.usage.total_tokens;for(let $ of Z.choices??[]){if(X){if($.delta?.content)J.responseTexts.push($.delta.content);if($.delta?.tool_calls)xN0($.delta.tool_calls,J)}if($.finish_reason)J.finishReasons.push($.finish_reason)}}function hN0(Z,J,X,$){if(!(Z&&typeof Z==="object")){J.eventTypes.push("unknown:non-object");return}if(Z instanceof Error){$.setStatus({code:A0,message:"internal_error"}),V0(Z,{mechanism:{handled:!1,type:"auto.ai.openai.stream-response"}});return}if(!("type"in Z))return;let Y=Z;if(!bb.includes(Y.type)){J.eventTypes.push(Y.type);return}if(X){if(Y.type==="response.output_item.done"&&"item"in Y)J.responsesApiToolCalls.push(Y.item);if(Y.type==="response.output_text.delta"&&"delta"in Y&&Y.delta){J.responseTexts.push(Y.delta);return}}if("response"in Y){let{response:Q}=Y;if(J.responseId=Q.id??J.responseId,J.responseModel=Q.model??J.responseModel,J.responseTimestamp=Q.created_at??J.responseTimestamp,Q.usage)J.promptTokens=Q.usage.input_tokens,J.completionTokens=Q.usage.output_tokens,J.totalTokens=Q.usage.total_tokens;if(Q.status)J.finishReasons.push(Q.status);if(X&&Q.output_text)J.responseTexts.push(Q.output_text)}}async function*tb(Z,J,X){let $={eventTypes:[],responseTexts:[],finishReasons:[],responseId:"",responseModel:"",responseTimestamp:0,promptTokens:void 0,completionTokens:void 0,totalTokens:void 0,chatCompletionToolCalls:{},responsesApiToolCalls:[]};try{for await(let Y of Z){if(ib(Y))vN0(Y,$,X);else if(pb(Y))hN0(Y,$,X,J);yield Y}}finally{if(GK(J,$.responseId,$.responseModel,$.responseTimestamp),MY(J,$.promptTokens,$.completionTokens,$.totalTokens),J.setAttributes({[wZ]:!0}),$.finishReasons.length)J.setAttributes({[e4]:JSON.stringify($.finishReasons)});if(X&&$.responseTexts.length)J.setAttributes({[g1]:$.responseTexts.join("")});let Q=[...Object.values($.chatCompletionToolCalls),...$.responsesApiToolCalls];if(Q.length>0)J.setAttributes({[t1]:JSON.stringify(Q)});J.end()}}function fN0(Z){let J=Array.isArray(Z.tools)?Z.tools:[],$=Z.web_search_options&&typeof Z.web_search_options==="object"?[{type:"web_search_options",...Z.web_search_options}]:[],Y=[...J,...$];return Y.length>0?JSON.stringify(Y):void 0}function bN0(Z,J){let X={[a9]:"openai",[w4]:zK(J),[X0]:"auto.ai.openai"};if(Z.length>0&&typeof Z[0]==="object"&&Z[0]!==null){let $=Z[0],Y=fN0($);if(Y)X[e9]=Y;Object.assign(X,sb($))}else X[C1]="unknown";return X}function gN0(Z,J,X){if(!J||typeof J!=="object")return;let $=J;if(db($)){if(nb(Z,$,X),X&&$.choices?.length){let Y=$.choices.map((Q)=>Q.message?.content||"");Z.setAttributes({[g1]:JSON.stringify(Y)})}}else if(ub($)){if(ob(Z,$,X),X&&$.output_text)Z.setAttributes({[g1]:$.output_text})}else if(cb($))ab(Z,$);else if(lb($))rb(Z,$)}function eb(Z,J){let X="input"in J?J.input:("messages"in J)?J.messages:void 0,$=Array.isArray(X)?X.length:void 0;if(X&&$!==0){let Y=X7(X);if(Z.setAttribute(G4,Y),$)Z.setAttribute(Z6,$)}}function mN0(Z,J,X,$){return async function(...Q){let W=bN0(Q,J),K=W[C1]||"unknown",z=zK(J),G=Q[0];if(G&&typeof G==="object"&&G.stream===!0)return z4({name:`${z} ${K} stream-response`,op:PU(J),attributes:W},async(V)=>{try{if($.recordInputs&&G)eb(V,G);let F=await Z.apply(X,Q);return tb(F,V,$.recordOutputs??!1)}catch(F){throw V.setStatus({code:A0,message:"internal_error"}),V0(F,{mechanism:{handled:!1,type:"auto.ai.openai.stream",data:{function:J}}}),V.end(),F}});else return _6({name:`${z} ${K}`,op:PU(J),attributes:W},async(V)=>{try{if($.recordInputs&&G)eb(V,G);let F=await Z.apply(X,Q);return gN0(V,F,$.recordOutputs),F}catch(F){throw V0(F,{mechanism:{handled:!1,type:"auto.ai.openai",data:{function:J}}}),F}})}}function Zg(Z,J="",X){return new Proxy(Z,{get($,Y){let Q=$[Y],W=mb(J,String(Y));if(typeof Q==="function"&&gb(W))return mN0(Q,W,$,X);if(typeof Q==="function")return Q.bind($);if(Q&&typeof Q==="object")return Zg(Q,W,X);return Q}})}function HK(Z,J){let X=Boolean(u()?.getOptions().sendDefaultPii),$={recordInputs:X,recordOutputs:X,...J};return Zg(Z,"",$)}function dN0(Z,J){if("type"in Z&&typeof Z.type==="string"){if(Z.type==="error")return J.setStatus({code:A0,message:Z.error?.type??"internal_error"}),V0(Z.error,{mechanism:{handled:!1,type:"auto.ai.anthropic.anthropic_error"}}),!0}return!1}function uN0(Z,J){if(Z.type==="message_delta"&&Z.usage){if("output_tokens"in Z.usage&&typeof Z.usage.output_tokens==="number")J.completionTokens=Z.usage.output_tokens}if(Z.message){let X=Z.message;if(X.id)J.responseId=X.id;if(X.model)J.responseModel=X.model;if(X.stop_reason)J.finishReasons.push(X.stop_reason);if(X.usage){if(typeof X.usage.input_tokens==="number")J.promptTokens=X.usage.input_tokens;if(typeof X.usage.cache_creation_input_tokens==="number")J.cacheCreationInputTokens=X.usage.cache_creation_input_tokens;if(typeof X.usage.cache_read_input_tokens==="number")J.cacheReadInputTokens=X.usage.cache_read_input_tokens}}}function cN0(Z,J){if(Z.type!=="content_block_start"||typeof Z.index!=="number"||!Z.content_block)return;if(Z.content_block.type==="tool_use"||Z.content_block.type==="server_tool_use")J.activeToolBlocks[Z.index]={id:Z.content_block.id,name:Z.content_block.name,inputJsonParts:[]}}function lN0(Z,J,X){if(Z.type!=="content_block_delta"||!Z.delta)return;if(typeof Z.index==="number"&&"partial_json"in Z.delta&&typeof Z.delta.partial_json==="string"){let $=J.activeToolBlocks[Z.index];if($)$.inputJsonParts.push(Z.delta.partial_json)}if(X&&typeof Z.delta.text==="string")J.responseTexts.push(Z.delta.text)}function pN0(Z,J){if(Z.type!=="content_block_stop"||typeof Z.index!=="number")return;let X=J.activeToolBlocks[Z.index];if(!X)return;let $=X.inputJsonParts.join(""),Y;try{Y=$?JSON.parse($):{}}catch{Y={__unparsed:$}}J.toolCalls.push({type:"tool_use",id:X.id,name:X.name,input:Y}),delete J.activeToolBlocks[Z.index]}function Jg(Z,J,X,$){if(!(Z&&typeof Z==="object"))return;if(dN0(Z,$))return;uN0(Z,J),cN0(Z,J),lN0(Z,J,X),pN0(Z,J)}function iN0(Z,J,X){if(!J.isRecording())return;if(Z.responseId)J.setAttributes({[m6]:Z.responseId});if(Z.responseModel)J.setAttributes({[l1]:Z.responseModel});if(wY(J,Z.promptTokens,Z.completionTokens,Z.cacheCreationInputTokens,Z.cacheReadInputTokens),J.setAttributes({[wZ]:!0}),Z.finishReasons.length>0)J.setAttributes({[e4]:JSON.stringify(Z.finishReasons)});if(X&&Z.responseTexts.length>0)J.setAttributes({[g1]:Z.responseTexts.join("")});if(X&&Z.toolCalls.length>0)J.setAttributes({[t1]:JSON.stringify(Z.toolCalls)});J.end()}async function*Xg(Z,J,X){let $={responseTexts:[],finishReasons:[],responseId:"",responseModel:"",promptTokens:void 0,completionTokens:void 0,cacheCreationInputTokens:void 0,cacheReadInputTokens:void 0,toolCalls:[],activeToolBlocks:{}};try{for await(let Y of Z)Jg(Y,$,X,J),yield Y}finally{if($.responseId)J.setAttributes({[m6]:$.responseId});if($.responseModel)J.setAttributes({[l1]:$.responseModel});if(wY(J,$.promptTokens,$.completionTokens,$.cacheCreationInputTokens,$.cacheReadInputTokens),J.setAttributes({[wZ]:!0}),$.finishReasons.length>0)J.setAttributes({[e4]:JSON.stringify($.finishReasons)});if(X&&$.responseTexts.length>0)J.setAttributes({[g1]:$.responseTexts.join("")});if(X&&$.toolCalls.length>0)J.setAttributes({[t1]:JSON.stringify($.toolCalls)});J.end()}}function $g(Z,J,X){let $={responseTexts:[],finishReasons:[],responseId:"",responseModel:"",promptTokens:void 0,completionTokens:void 0,cacheCreationInputTokens:void 0,cacheReadInputTokens:void 0,toolCalls:[],activeToolBlocks:{}};return Z.on("streamEvent",(Y)=>{Jg(Y,$,X,J)}),Z.on("message",()=>{iN0($,J,X)}),Z.on("error",(Y)=>{if(V0(Y,{mechanism:{handled:!1,type:"auto.ai.anthropic.stream_error"}}),J.isRecording())J.setStatus({code:A0,message:"stream_error"}),J.end()}),Z}var Y7="Anthropic_AI",Yg=["messages.create","messages.stream","messages.countTokens","models.get","completions.create","models.retrieve","beta.messages.create"];function Qg(Z){return Yg.includes(Z)}function Wg(Z,J){let X=Array.isArray(J)?J.length:void 0;if(X!==0)Z.setAttributes({[G4]:X7(J),[Z6]:X})}function Kg(Z,J){if(J.error)Z.setStatus({code:A0,message:J.error.type||"internal_error"}),V0(J.error,{mechanism:{handled:!1,type:"auto.ai.anthropic.anthropic_error"}})}function zg(Z){let{system:J,messages:X,input:$}=Z,Y=typeof J==="string"?[{role:"system",content:Z.system}]:[],Q=Array.isArray($)?$:$!=null?[$]:void 0,W=Array.isArray(X)?X:X!=null?[X]:[],K=Q??W;return[...Y,...K]}function nN0(Z,J){let X={[a9]:"anthropic",[w4]:jZ(J),[X0]:"auto.ai.anthropic"};if(Z.length>0&&typeof Z[0]==="object"&&Z[0]!==null){let $=Z[0];if($.tools&&Array.isArray($.tools))X[e9]=JSON.stringify($.tools);if(X[C1]=$.model??"unknown","temperature"in $)X[r9]=$.temperature;if("top_p"in $)X[t9]=$.top_p;if("stream"in $)X[tJ]=$.stream;if("top_k"in $)X[ZK]=$.top_k;if("frequency_penalty"in $)X[s9]=$.frequency_penalty;if("max_tokens"in $)X[eJ]=$.max_tokens}else if(J==="models.retrieve"||J==="models.get")X[C1]=Z[0];else X[C1]="unknown";return X}function EU(Z,J){let X=zg(J);if(Wg(Z,X),"prompt"in J)Z.setAttributes({[ef]:JSON.stringify(J.prompt)})}function oN0(Z,J){if("content"in J){if(Array.isArray(J.content)){Z.setAttributes({[g1]:J.content.map(($)=>$.text).filter(($)=>!!$).join("")});let X=[];for(let $ of J.content)if($.type==="tool_use"||$.type==="server_tool_use")X.push($);if(X.length>0)Z.setAttributes({[t1]:JSON.stringify(X)})}}if("completion"in J)Z.setAttributes({[g1]:J.completion});if("input_tokens"in J)Z.setAttributes({[g1]:JSON.stringify(J.input_tokens)})}function aN0(Z,J){if("id"in J&&"model"in J){if(Z.setAttributes({[m6]:J.id,[l1]:J.model}),"created"in J&&typeof J.created==="number")Z.setAttributes({[jU]:new Date(J.created*1000).toISOString()});if("created_at"in J&&typeof J.created_at==="number")Z.setAttributes({[jU]:new Date(J.created_at*1000).toISOString()});if("usage"in J&&J.usage)wY(Z,J.usage.input_tokens,J.usage.output_tokens,J.usage.cache_creation_input_tokens,J.usage.cache_read_input_tokens)}}function rN0(Z,J,X){if(!J||typeof J!=="object")return;if("type"in J&&J.type==="error"){Kg(Z,J);return}if(X)oN0(Z,J);aN0(Z,J)}function Gg(Z,J,X){if(V0(Z,{mechanism:{handled:!1,type:"auto.ai.anthropic",data:{function:X}}}),J.isRecording())J.setStatus({code:A0,message:"internal_error"}),J.end();throw Z}function sN0(Z,J,X,$,Y,Q,W,K,z,G,H){let V=Y[C1]??"unknown",F={name:`${Q} ${V} stream-response`,op:JX(W),attributes:Y};if(G&&!H)return z4(F,async(B)=>{try{if(z.recordInputs&&K)EU(B,K);let U=await Z.apply(X,$);return Xg(U,B,z.recordOutputs??!1)}catch(U){return Gg(U,B,W)}});else return z4(F,(B)=>{try{if(z.recordInputs&&K)EU(B,K);let U=J.apply(X,$);return $g(U,B,z.recordOutputs??!1)}catch(U){return Gg(U,B,W)}})}function tN0(Z,J,X,$){return new Proxy(Z,{apply(Y,Q,W){let K=nN0(W,J),z=K[C1]??"unknown",G=jZ(J),H=typeof W[0]==="object"?W[0]:void 0,V=Boolean(H?.stream),F=J==="messages.stream";if(V||F)return sN0(Z,Y,X,W,K,G,J,H,$,V,F);return _6({name:`${G} ${z}`,op:JX(J),attributes:K},(B)=>{if($.recordInputs&&H)EU(B,H);return D6(()=>Y.apply(X,W),(U)=>{V0(U,{mechanism:{handled:!1,type:"auto.ai.anthropic",data:{function:J}}})},()=>{},(U)=>rN0(B,U,$.recordOutputs))})}})}function Hg(Z,J="",X){return new Proxy(Z,{get($,Y){let Q=$[Y],W=QK(J,String(Y));if(typeof Q==="function"&&Qg(W))return tN0(Q,W,$,X);if(typeof Q==="function")return Q.bind($);if(Q&&typeof Q==="object")return Hg(Q,W,X);return Q}})}function IU(Z,J){let X=Boolean(u()?.getOptions().sendDefaultPii),$={recordInputs:X,recordOutputs:X,...J};return Hg(Z,"",$)}var Q7="Google_GenAI",yU=["models.generateContent","models.generateContentStream","chats.create","sendMessage","sendMessageStream"],Vg="google_genai",SU="chats.create",Fg="chat";function eN0(Z,J){let X=Z?.promptFeedback;if(X?.blockReason){let $=X.blockReasonMessage??X.blockReason;return J.setStatus({code:A0,message:`Content blocked: ${$}`}),V0(`Content blocked: ${$}`,{mechanism:{handled:!1,type:"auto.ai.google_genai"}}),!0}return!1}function ZR0(Z,J){if(typeof Z.responseId==="string")J.responseId=Z.responseId;if(typeof Z.modelVersion==="string")J.responseModel=Z.modelVersion;let X=Z.usageMetadata;if(X){if(typeof X.promptTokenCount==="number")J.promptTokens=X.promptTokenCount;if(typeof X.candidatesTokenCount==="number")J.completionTokens=X.candidatesTokenCount;if(typeof X.totalTokenCount==="number")J.totalTokens=X.totalTokenCount}}function JR0(Z,J,X){if(Array.isArray(Z.functionCalls))J.toolCalls.push(...Z.functionCalls);for(let $ of Z.candidates??[]){if($?.finishReason&&!J.finishReasons.includes($.finishReason))J.finishReasons.push($.finishReason);for(let Y of $?.content?.parts??[]){if(X&&Y.text)J.responseTexts.push(Y.text);if(Y.functionCall)J.toolCalls.push({type:"function",id:Y.functionCall.id,name:Y.functionCall.name,arguments:Y.functionCall.args})}}}function XR0(Z,J,X,$){if(!Z||eN0(Z,$))return;ZR0(Z,J),JR0(Z,J,X)}async function*Bg(Z,J,X){let $={responseTexts:[],finishReasons:[],toolCalls:[]};try{for await(let Y of Z)XR0(Y,$,X,J),yield Y}finally{let Y={[wZ]:!0};if($.responseId)Y[m6]=$.responseId;if($.responseModel)Y[l1]=$.responseModel;if($.promptTokens!==void 0)Y[D1]=$.promptTokens;if($.completionTokens!==void 0)Y[b1]=$.completionTokens;if($.totalTokens!==void 0)Y[O6]=$.totalTokens;if($.finishReasons.length)Y[e4]=JSON.stringify($.finishReasons);if(X&&$.responseTexts.length)Y[g1]=$.responseTexts.join("");if(X&&$.toolCalls.length)Y[t1]=JSON.stringify($.toolCalls);J.setAttributes(Y),J.end()}}function Ug(Z){if(yU.includes(Z))return!0;let J=Z.split(".").pop();return yU.includes(J)}function Lg(Z){return Z.includes("Stream")}function $X(Z,J="user"){if(typeof Z==="string")return[{role:J,content:Z}];if(Array.isArray(Z))return Z.flatMap((X)=>$X(X,J));if(typeof Z!=="object"||!Z)return[];if("role"in Z&&typeof Z.role==="string")return[Z];if("parts"in Z)return[{...Z,role:J}];return[{role:J,content:Z}]}function Dg(Z,J){if("model"in Z&&typeof Z.model==="string")return Z.model;if(J&&typeof J==="object"){let X=J;if("model"in X&&typeof X.model==="string")return X.model;if("modelVersion"in X&&typeof X.modelVersion==="string")return X.modelVersion}return"unknown"}function $R0(Z){let J={};if("temperature"in Z&&typeof Z.temperature==="number")J[r9]=Z.temperature;if("topP"in Z&&typeof Z.topP==="number")J[t9]=Z.topP;if("topK"in Z&&typeof Z.topK==="number")J[ZK]=Z.topK;if("maxOutputTokens"in Z&&typeof Z.maxOutputTokens==="number")J[eJ]=Z.maxOutputTokens;if("frequencyPenalty"in Z&&typeof Z.frequencyPenalty==="number")J[s9]=Z.frequencyPenalty;if("presencePenalty"in Z&&typeof Z.presencePenalty==="number")J[ZX]=Z.presencePenalty;return J}function YR0(Z,J,X){let $={[a9]:Vg,[w4]:jZ(Z),[X0]:"auto.ai.google_genai"};if(J){if($[C1]=Dg(J,X),"config"in J&&typeof J.config==="object"&&J.config){let Y=J.config;if(Object.assign($,$R0(Y)),"tools"in Y&&Array.isArray(Y.tools)){let Q=Y.tools.flatMap((W)=>W.functionDeclarations);$[e9]=JSON.stringify(Q)}}}else $[C1]=Dg({},X);return $}function _g(Z,J){let X=[];if("config"in J&&J.config&&typeof J.config==="object"&&"systemInstruction"in J.config&&J.config.systemInstruction)X.push(...$X(J.config.systemInstruction,"system"));if("history"in J)X.push(...$X(J.history,"user"));if("contents"in J)X.push(...$X(J.contents,"user"));if("message"in J)X.push(...$X(J.message,"user"));if(Array.isArray(X)&&X.length)Z.setAttributes({[Z6]:X.length,[G4]:JSON.stringify(J7(X))})}function QR0(Z,J,X){if(!J||typeof J!=="object")return;if(J.modelVersion)Z.setAttribute(l1,J.modelVersion);if(J.usageMetadata&&typeof J.usageMetadata==="object"){let $=J.usageMetadata;if(typeof $.promptTokenCount==="number")Z.setAttributes({[D1]:$.promptTokenCount});if(typeof $.candidatesTokenCount==="number")Z.setAttributes({[b1]:$.candidatesTokenCount});if(typeof $.totalTokenCount==="number")Z.setAttributes({[O6]:$.totalTokenCount})}if(X&&Array.isArray(J.candidates)&&J.candidates.length>0){let $=J.candidates.map((Y)=>{if(Y.content?.parts&&Array.isArray(Y.content.parts))return Y.content.parts.map((Q)=>typeof Q.text==="string"?Q.text:"").filter((Q)=>Q.length>0).join("");return""}).filter((Y)=>Y.length>0);if($.length>0)Z.setAttributes({[g1]:$.join("")})}if(X&&J.functionCalls){let $=J.functionCalls;if(Array.isArray($)&&$.length>0)Z.setAttributes({[t1]:JSON.stringify($)})}}function Og(Z,J,X,$){let Y=J===SU;return new Proxy(Z,{apply(Q,W,K){let z=K[0],G=YR0(J,z,X),H=G[C1]??"unknown",V=jZ(J);if(Lg(J))return z4({name:`${V} ${H} stream-response`,op:JX(J),attributes:G},async(F)=>{try{if($.recordInputs&&z)_g(F,z);let B=await Q.apply(X,K);return Bg(B,F,Boolean($.recordOutputs))}catch(B){throw F.setStatus({code:A0,message:"internal_error"}),V0(B,{mechanism:{handled:!1,type:"auto.ai.google_genai",data:{function:J}}}),F.end(),B}});return _6({name:Y?`${V} ${H} create`:`${V} ${H}`,op:JX(J),attributes:G},(F)=>{if($.recordInputs&&z)_g(F,z);return D6(()=>Q.apply(X,K),(B)=>{V0(B,{mechanism:{handled:!1,type:"auto.ai.google_genai",data:{function:J}}})},()=>{},(B)=>{if(!Y)QR0(F,B,$.recordOutputs)})})}})}function kU(Z,J="",X){return new Proxy(Z,{get:($,Y,Q)=>{let W=Reflect.get($,Y,Q),K=QK(J,String(Y));if(typeof W==="function"&&Ug(K)){if(K===SU){let z=Og(W,K,$,X);return function(...H){let V=z(...H);if(V&&typeof V==="object")return kU(V,Fg,X);return V}}return Og(W,K,$,X)}if(typeof W==="function")return W.bind($);if(W&&typeof W==="object")return kU(W,K,X);return W}})}function xU(Z,J){let X=Boolean(u()?.getOptions().sendDefaultPii),$={recordInputs:X,recordOutputs:X,...J};return kU(Z,"",$)}var VK="LangChain",AZ="auto.ai.langchain",wg={human:"user",ai:"assistant",assistant:"assistant",system:"system",function:"function",tool:"tool"};var R8=(Z,J,X)=>{if(X!=null)Z[J]=X},w6=(Z,J,X)=>{let $=Number(X);if(!Number.isNaN($))Z[J]=$};function J6(Z){if(typeof Z==="string")return Z;try{return JSON.stringify(Z)}catch{return String(Z)}}function AY(Z){let J=Z.toLowerCase();return wg[J]??J}function jg(Z){if(Z.includes("System"))return"system";if(Z.includes("Human"))return"user";if(Z.includes("AI")||Z.includes("Assistant"))return"assistant";if(Z.includes("Function"))return"function";if(Z.includes("Tool"))return"tool";return"user"}function vU(Z){if(!Z||Array.isArray(Z))return;return Z.invocation_params}function TY(Z){return Z.map((J)=>{let X=J._getType;if(typeof X==="function"){let Y=X.call(J);return{role:AY(Y),content:J6(J.content)}}let $=J.constructor?.name;if($)return{role:AY(jg($)),content:J6(J.content)};if(J.type){let Y=String(J.type).toLowerCase();return{role:AY(Y),content:J6(J.content)}}if(J.role)return{role:AY(String(J.role)),content:J6(J.content)};if(J.lc===1&&J.kwargs){let Y=J.id,Q=Array.isArray(Y)&&Y.length>0?Y[Y.length-1]:"",W=typeof Q==="string"?jg(Q):"user";return{role:AY(W),content:J6(J.kwargs?.content)}}return{role:"user",content:J6(J.content)}})}function WR0(Z,J,X){let $={},Y="kwargs"in Z?Z.kwargs:void 0,Q=J?.temperature??X?.ls_temperature??Y?.temperature;w6($,r9,Q);let W=J?.max_tokens??X?.ls_max_tokens??Y?.max_tokens;w6($,eJ,W);let K=J?.top_p??Y?.top_p;w6($,t9,K);let z=J?.frequency_penalty;w6($,s9,z);let G=J?.presence_penalty;if(w6($,ZX,G),J&&"stream"in J)R8($,tJ,Boolean(J.stream));return $}function Mg(Z,J,X,$,Y,Q){return{[a9]:J6(Z??"langchain"),[w4]:X,[C1]:J6(J),[X0]:AZ,...WR0($,Y,Q)}}function Ag(Z,J,X,$,Y){let Q=Y?.ls_provider,W=$?.model??Y?.ls_model_name??"unknown",K=Mg(Q,W,"pipeline",Z,$,Y);if(X&&Array.isArray(J)&&J.length>0){R8(K,Z6,J.length);let z=J.map((G)=>({role:"user",content:G}));R8(K,G4,J6(z))}return K}function Tg(Z,J,X,$,Y){let Q=Y?.ls_provider??Z.id?.[2],W=$?.model??Y?.ls_model_name??"unknown",K=Mg(Q,W,"chat",Z,$,Y);if(X&&Array.isArray(J)&&J.length>0){let z=TY(J.flat());R8(K,Z6,z.length);let G=J7(z);R8(K,G4,J6(G))}return K}function KR0(Z,J){let X=[],$=Z.flat();for(let Y of $){let Q=Y.message?.content;if(Array.isArray(Q))for(let W of Q){let K=W;if(K.type==="tool_use")X.push(K)}}if(X.length>0)R8(J,t1,J6(X))}function zR0(Z,J){if(!Z)return;let{tokenUsage:X,usage:$}=Z;if(X)w6(J,D1,X.promptTokens),w6(J,b1,X.completionTokens),w6(J,O6,X.totalTokens);else if($){w6(J,D1,$.input_tokens),w6(J,b1,$.output_tokens);let Y=Number($.input_tokens),Q=Number($.output_tokens),W=(Number.isNaN(Y)?0:Y)+(Number.isNaN(Q)?0:Q);if(W>0)w6(J,O6,W);if($.cache_creation_input_tokens!==void 0)w6(J,Yb,$.cache_creation_input_tokens);if($.cache_read_input_tokens!==void 0)w6(J,Qb,$.cache_read_input_tokens)}}function qg(Z,J){if(!Z)return;let X={};if(Array.isArray(Z.generations)){let G=Z.generations.flat().map((H)=>{if(H.generationInfo?.finish_reason)return H.generationInfo.finish_reason;if(H.generation_info?.finish_reason)return H.generation_info.finish_reason;return null}).filter((H)=>typeof H==="string");if(G.length>0)R8(X,e4,J6(G));if(KR0(Z.generations,X),J){let H=Z.generations.flat().map((V)=>V.text??V.message?.content).filter((V)=>typeof V==="string");if(H.length>0)R8(X,g1,J6(H))}}zR0(Z.llmOutput,X);let $=Z.llmOutput,Q=Z.generations?.[0]?.[0]?.message,W=$?.model_name??$?.model??Q?.response_metadata?.model_name;if(W)R8(X,l1,W);let K=$?.id??Q?.id;if(K)R8(X,m6,K);let z=$?.stop_reason??Q?.response_metadata?.finish_reason;if(z)R8(X,Xb,J6(z));return X}function FK(Z={}){let J=Z.recordInputs??!1,X=Z.recordOutputs??!1,$=new Map,Y=(W)=>{let K=$.get(W);if(K?.isRecording())K.end(),$.delete(W)},Q={lc_serializable:!1,lc_namespace:["langchain_core","callbacks","sentry"],lc_secrets:void 0,lc_attributes:void 0,lc_aliases:void 0,lc_serializable_keys:void 0,lc_id:["langchain_core","callbacks","sentry"],lc_kwargs:{},name:"SentryCallbackHandler",ignoreLLM:!1,ignoreChain:!1,ignoreAgent:!1,ignoreRetriever:!1,ignoreCustomEvent:!1,raiseError:!1,awaitHandlers:!0,handleLLMStart(W,K,z,G,H,V,F,B){let U=vU(V),D=Ag(W,K,J,U,F),_=D[C1],O=D[w4];z4({name:`${O} ${_}`,op:"gen_ai.pipeline",attributes:{...D,[K0]:"gen_ai.pipeline"}},(w)=>{return $.set(z,w),w})},handleChatModelStart(W,K,z,G,H,V,F,B){let U=vU(V),D=Tg(W,K,J,U,F),_=D[C1],O=D[w4];z4({name:`${O} ${_}`,op:"gen_ai.chat",attributes:{...D,[K0]:"gen_ai.chat"}},(w)=>{return $.set(z,w),w})},handleLLMEnd(W,K,z,G,H){let V=$.get(K);if(V?.isRecording()){let F=qg(W,X);if(F)V.setAttributes(F);Y(K)}},handleLLMError(W,K){let z=$.get(K);if(z?.isRecording())z.setStatus({code:A0,message:"llm_error"}),Y(K);V0(W,{mechanism:{handled:!1,type:`${AZ}.llm_error_handler`}})},handleChainStart(W,K,z,G){let H=W.name||"unknown_chain",V={[X0]:"auto.ai.langchain","langchain.chain.name":H};if(J)V["langchain.chain.inputs"]=JSON.stringify(K);z4({name:`chain ${H}`,op:"gen_ai.invoke_agent",attributes:{...V,[K0]:"gen_ai.invoke_agent"}},(F)=>{return $.set(z,F),F})},handleChainEnd(W,K){let z=$.get(K);if(z?.isRecording()){if(X)z.setAttributes({"langchain.chain.outputs":JSON.stringify(W)});Y(K)}},handleChainError(W,K){let z=$.get(K);if(z?.isRecording())z.setStatus({code:A0,message:"chain_error"}),Y(K);V0(W,{mechanism:{handled:!1,type:`${AZ}.chain_error_handler`}})},handleToolStart(W,K,z,G){let H=W.name||"unknown_tool",V={[X0]:AZ,"gen_ai.tool.name":H};if(J)V["gen_ai.tool.input"]=K;z4({name:`execute_tool ${H}`,op:"gen_ai.execute_tool",attributes:{...V,[K0]:"gen_ai.execute_tool"}},(F)=>{return $.set(z,F),F})},handleToolEnd(W,K){let z=$.get(K);if(z?.isRecording()){if(X)z.setAttributes({"gen_ai.tool.output":JSON.stringify(W)});Y(K)}},handleToolError(W,K){let z=$.get(K);if(z?.isRecording())z.setStatus({code:A0,message:"tool_error"}),Y(K);V0(W,{mechanism:{handled:!1,type:`${AZ}.tool_error_handler`}})},copy(){return Q},toJSON(){return{lc:1,type:"not_implemented",id:Q.lc_id}},toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:Q.lc_id}}};return Q}var BK="LangGraph",hU="auto.ai.langgraph";function GR0(Z){if(!Z||Z.length===0)return null;let J=[];for(let X of Z)if(X&&typeof X==="object"){let $=X.tool_calls;if($&&Array.isArray($))J.push(...$)}return J.length>0?J:null}function HR0(Z){let J=Z,X=0,$=0,Y=0;if(J.usage_metadata&&typeof J.usage_metadata==="object"){let Q=J.usage_metadata;if(typeof Q.input_tokens==="number")X=Q.input_tokens;if(typeof Q.output_tokens==="number")$=Q.output_tokens;if(typeof Q.total_tokens==="number")Y=Q.total_tokens;return{inputTokens:X,outputTokens:$,totalTokens:Y}}if(J.response_metadata&&typeof J.response_metadata==="object"){let Q=J.response_metadata;if(Q.tokenUsage&&typeof Q.tokenUsage==="object"){let W=Q.tokenUsage;if(typeof W.promptTokens==="number")X=W.promptTokens;if(typeof W.completionTokens==="number")$=W.completionTokens;if(typeof W.totalTokens==="number")Y=W.totalTokens}}return{inputTokens:X,outputTokens:$,totalTokens:Y}}function VR0(Z,J){let X=J;if(X.response_metadata&&typeof X.response_metadata==="object"){let $=X.response_metadata;if($.model_name&&typeof $.model_name==="string")Z.setAttribute(l1,$.model_name);if($.finish_reason&&typeof $.finish_reason==="string")Z.setAttribute(e4,[$.finish_reason])}}function Cg(Z){if(!Z.builder?.nodes?.tools?.runnable?.tools)return null;let J=Z.builder?.nodes?.tools?.runnable?.tools;if(!J||!Array.isArray(J)||J.length===0)return null;return J.map((X)=>({name:X.lc_kwargs?.name,description:X.lc_kwargs?.description,schema:X.lc_kwargs?.schema}))}function Ng(Z,J,X){let Y=X?.messages;if(!Y||!Array.isArray(Y))return;let Q=J?.length??0,W=Y.length>Q?Y.slice(Q):[];if(W.length===0)return;let K=GR0(W);if(K)Z.setAttribute(t1,JSON.stringify(K));let z=TY(W);Z.setAttribute(g1,JSON.stringify(z));let G=0,H=0,V=0;for(let F of W){let B=HR0(F);G+=B.inputTokens,H+=B.outputTokens,V+=B.totalTokens,VR0(Z,F)}if(G>0)Z.setAttribute(D1,G);if(H>0)Z.setAttribute(b1,H);if(V>0)Z.setAttribute(O6,V)}function fU(Z,J){return new Proxy(Z,{apply(X,$,Y){return _6({op:"gen_ai.create_agent",name:"create_agent",attributes:{[X0]:hU,[K0]:"gen_ai.create_agent",[w4]:"create_agent"}},(Q)=>{try{let W=Reflect.apply(X,$,Y),K=Y.length>0?Y[0]:{};if(K?.name&&typeof K.name==="string")Q.setAttribute(LU,K.name),Q.updateName(`create_agent ${K.name}`);let z=W.invoke;if(z&&typeof z==="function")W.invoke=FR0(z.bind(W),W,K,J);return W}catch(W){throw Q.setStatus({code:A0,message:"internal_error"}),V0(W,{mechanism:{handled:!1,type:"auto.ai.langgraph.error"}}),W}})}})}function FR0(Z,J,X,$){return new Proxy(Z,{apply(Y,Q,W){return _6({op:"gen_ai.invoke_agent",name:"invoke_agent",attributes:{[X0]:hU,[K0]:JK,[w4]:"invoke_agent"}},async(K)=>{try{let z=X?.name;if(z&&typeof z==="string")K.setAttribute($b,z),K.setAttribute(LU,z),K.updateName(`invoke_agent ${z}`);let V=(W.length>1?W[1]:void 0)?.configurable?.thread_id;if(V&&typeof V==="string")K.setAttribute(LY,V);let F=Cg(J);if(F)K.setAttribute(e9,JSON.stringify(F));let{recordInputs:B,recordOutputs:U}=$,D=W.length>0?W[0].messages??[]:[];if(D&&B){let O=TY(D),w=J7(O);K.setAttributes({[G4]:JSON.stringify(w),[Z6]:O.length})}let _=await Reflect.apply(Y,Q,W);if(U)Ng(K,D??null,_);return _}catch(z){throw K.setStatus({code:A0,message:"internal_error"}),V0(z,{mechanism:{handled:!1,type:"auto.ai.langgraph.error"}}),z}})}})}function qY(Z){if(Z===void 0)return;else if(Z>=400&&Z<500)return"warning";else if(Z>=500)return"error";else return}function CY(Z,J,X){let $=Z[J];if(typeof $!=="function")return;try{Z[J]=X}catch(Y){Object.defineProperty(Z,J,{value:X,writable:!0,configurable:!0,enumerable:!0})}if(Z.default===$)try{Z.default=X}catch(Y){Object.defineProperty(Z,"default",{value:X,writable:!0,configurable:!0,enumerable:!0})}}function Pg(Z,J=!1){return!(J||Z&&!Z.startsWith("/")&&!Z.match(/^[A-Z]:/)&&!Z.startsWith(".")&&!Z.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&Z!==void 0&&!Z.includes("node_modules/")}function Eg(Z){let J=/^\s*[-]{4,}$/,X=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,$=/at (?:async )?(.+?) \(data:(.*?),/;return(Y)=>{let Q=Y.match($);if(Q)return{filename:`<data:${Q[2]}>`,function:Q[1]};let W=Y.match(X);if(W){let K,z,G,H,V;if(W[1]){G=W[1];let U=G.lastIndexOf(".");if(G[U-1]===".")U--;if(U>0){K=G.slice(0,U),z=G.slice(U+1);let D=K.indexOf(".Module");if(D>0)G=G.slice(D+1),K=K.slice(0,D)}H=void 0}if(z)H=K,V=z;if(z==="<anonymous>")V=void 0,G=void 0;if(G===void 0)V=V||GB,G=H?`${H}.${V}`:V;let F=W[2]?.startsWith("file://")?W[2].slice(7):W[2],B=W[5]==="native";if(F?.match(/\/[A-Z]:/))F=F.slice(1);if(!F&&W[5]&&!B)F=W[5];return{filename:F?decodeURI(F):void 0,module:Z?Z(F):void 0,function:G,lineno:Rg(W[3]),colno:Rg(W[4]),in_app:Pg(F||"",B)}}if(Y.match(J))return{filename:Y};return}}function bU(Z){return[90,Eg(Z)]}function Rg(Z){return parseInt(Z||"",10)||void 0}class j6{constructor(Z){this._maxSize=Z,this._cache=new Map}get size(){return this._cache.size}get(Z){let J=this._cache.get(Z);if(J===void 0)return;return this._cache.delete(Z),this._cache.set(Z,J),J}set(Z,J){if(this._cache.size>=this._maxSize){let X=this._cache.keys().next().value;this._cache.delete(X)}this._cache.set(Z,J)}remove(Z){let J=this._cache.get(Z);if(J)this._cache.delete(Z);return J}clear(){this._cache.clear()}keys(){return Array.from(this._cache.keys())}values(){let Z=[];return this._cache.forEach((J)=>Z.push(J)),Z}}var gU=k(H0(),1),NY={};function a(Z,J,X){if(X)return xR0(Z,J,X);return kR0(Z,J)}function kR0(Z,J){return Object.assign((X)=>{let $=NY[Z];if($){if(X)$.setConfig(X);return $}let Y=J(X);return NY[Z]=Y,gU.registerInstrumentations({instrumentations:[Y]}),Y},{id:Z})}function xR0(Z,J,X){return Object.assign(($)=>{let Y=X($),Q=NY[Z];if(Q)return Q.setConfig(Y),Q;let W=new J(Y);return NY[Z]=W,gU.registerInstrumentations({instrumentations:[W]}),W},{id:Z})}function RY(Z){let J=!1,X=[];if(!vR0(Z))J=!0;else{let Y=Z._wrap;Z._wrap=(...Q)=>{return J=!0,X.forEach((W)=>W()),X=[],Y(...Q)}}return(Y)=>{if(J)Y();else X.push(Y)}}function vR0(Z){return typeof Z._wrap==="function"}var K7=k(f(),1);import{subscribe as hR0}from"diagnostics_channel";var _0=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;var Z5="@sentry/instrumentation-http",Ig=1048576;var yg=K7.createContextKey("sentry_http_server_instrumented"),W7="Http.Server",mU=new Map,Sg=new WeakSet;function kg(Z,J){f1(Z,"_startSpanCallback",new WeakRef(J))}var fR0=(Z={})=>{let J={sessions:Z.sessions??!0,sessionFlushingDelayMS:Z.sessionFlushingDelayMS??60000,maxRequestBodySize:Z.maxRequestBodySize??"medium",ignoreRequestBody:Z.ignoreRequestBody};return{name:W7,setupOnce(){hR0("http.server.request.start",($)=>{bR0($.server,J)})},afterAllSetup(X){if(_0&&X.getIntegrationByName("Http"))A.warn("It seems that you have manually added `httpServerIntegration` while `httpIntegration` is also present. Make sure to remove `httpServerIntegration` when adding `httpIntegration`.")}}},YX=fR0;function bR0(Z,{ignoreRequestBody:J,maxRequestBodySize:X,sessions:$,sessionFlushingDelayMS:Y}){let Q=Z.emit;if(Sg.has(Q))return;let W=new Proxy(Q,{apply(K,z,G){if(G[0]!=="request")return K.apply(z,G);let H=u();if(K7.context.active().getValue(yg)||!H)return K.apply(z,G);_0&&A.log(W7,"Handling incoming request");let V=R0().clone(),F=G[1],B=G[2],U=UY(F),D=F.ip||F.socket?.remoteAddress,_=F.url||"/";if(X!=="none"&&!J?.(_,F))mR0(F,V,X);V.setSDKProcessingMetadata({normalizedRequest:U,ipAddress:D});let O=(F.method||"GET").toUpperCase(),w=p5(_),j=`${O} ${w}`;if(V.setTransactionName(j),$&&H)gR0(H,{requestIsolationScope:V,response:B,sessionFlushingDelayMS:Y??60000});return KZ(V,()=>{u0().getPropagationContext().propagationSpanId=r4();let q=K7.propagation.extract(K7.context.active(),U.headers).setValue(yg,!0);return K7.context.with(q,()=>{H.emit("httpServerRequest",F,B,U);let R=F._startSpanCallback?.deref();if(R)return R(()=>K.apply(z,G));return K.apply(z,G)})})}});Sg.add(W),Z.emit=W}function gR0(Z,{requestIsolationScope:J,response:X,sessionFlushingDelayMS:$}){J.setSDKProcessingMetadata({requestSession:{status:"ok"}}),X.once("close",()=>{let Y=J.getScopeData().sdkProcessingMetadata.requestSession;if(Z&&Y){_0&&A.log(`Recorded request session with status: ${Y.status}`);let Q=new Date;Q.setSeconds(0,0);let W=Q.toISOString(),K=mU.get(Z),z=K?.[W]||{exited:0,crashed:0,errored:0};if(z[{ok:"exited",crashed:"crashed",errored:"errored"}[Y.status]]++,K)K[W]=z;else{_0&&A.log("Opened new request session aggregate.");let G={[W]:z};mU.set(Z,G);let H=()=>{clearTimeout(F),V(),mU.delete(Z);let B=Object.entries(G).map(([U,D])=>({started:U,exited:D.exited,errored:D.errored,crashed:D.crashed}));Z.sendSession({aggregates:B})},V=Z.on("flush",()=>{_0&&A.log("Sending request session aggregate due to client flush"),H()}),F=setTimeout(()=>{_0&&A.log("Sending request session aggregate due to flushing schedule"),H()},$).unref()}}})}function mR0(Z,J,X){let $=0,Y=[];_0&&A.log(W7,"Patching request.on");let Q=new WeakMap,W=X==="small"?1000:X==="medium"?1e4:Ig;try{Z.on=new Proxy(Z.on,{apply:(K,z,G)=>{let[H,V,...F]=G;if(H==="data"){_0&&A.log(W7,`Handling request.on("data") with maximum body size of ${W}b`);let B=new Proxy(V,{apply:(U,D,_)=>{try{let O=_[0],w=Buffer.from(O);if($<W)Y.push(w),$+=w.byteLength;else if(_0)A.log(W7,`Dropping request body chunk because maximum body length of ${W}b is exceeded.`)}catch(O){_0&&A.error(W7,"Encountered error while storing body chunk.")}return Reflect.apply(U,D,_)}});return Q.set(V,B),Reflect.apply(K,z,[H,B,...F])}return Reflect.apply(K,z,G)}}),Z.off=new Proxy(Z.off,{apply:(K,z,G)=>{let[,H]=G,V=Q.get(H);if(V){Q.delete(H);let F=G.slice();return F[1]=V,Reflect.apply(K,z,F)}return Reflect.apply(K,z,G)}}),Z.on("end",()=>{try{let K=Buffer.concat(Y).toString("utf-8");if(K){let G=Buffer.byteLength(K,"utf-8")>W?`${Buffer.from(K).subarray(0,W-3).toString("utf-8")}...`:K;J.setSDKProcessingMetadata({normalizedRequest:{data:G}})}}catch(K){if(_0)A.error(W7,"Error building captured request body",K)}})}catch(K){if(_0)A.error(W7,"Error patching request to capture body",K)}}var M6=k(f(),1),a5=k(H1(),1),A6=k(p0(),1);import{errorMonitor as YI0}from"events";var rd="Http.ServerSpans",QI0=(Z={})=>{let J=Z.ignoreStaticAssets??!0,X=Z.ignoreIncomingRequests,$=Z.ignoreStatusCodes??[[401,404],[301,303],[305,399]],{onSpanCreated:Y}=Z,{requestHook:Q,responseHook:W,applyCustomAttributesOnSpan:K}=Z.instrumentation??{};return{name:rd,setup(z){if(typeof __SENTRY_TRACING__<"u"&&!__SENTRY_TRACING__)return;z.on("httpServerRequest",(G,H,V)=>{let F=G,B=H;kg(F,(D)=>{if(zI0(F,{ignoreStaticAssets:J,ignoreIncomingRequests:X}))return _0&&A.log(rd,"Skipping span creation for incoming request",F.url),D();let _=V.url||F.url||"/",O=BY(_),w=F.headers,j=w["user-agent"],q=w["x-forwarded-for"],R=F.httpVersion,T=w.host,y=T?.replace(/^(.*)(:[0-9]{1,5})/,"$1")||"localhost",i=z.tracer,s=_.startsWith("https")?"https":"http",O0=V.method||F.method?.toUpperCase()||"GET",d0=O?O.pathname:p5(_),b0=`${O0} ${d0}`,G0=i.startSpan(b0,{kind:M6.SpanKind.SERVER,attributes:{[K0]:"http.server",[X0]:"auto.http.otel.http","sentry.http.prefetch":WI0(F)||void 0,"http.url":_,"http.method":V.method,"http.target":O?`${O.pathname}${O.search}`:d0,"http.host":T,"net.host.name":y,"http.client_ip":typeof q==="string"?q.split(",")[0]:void 0,"http.user_agent":j,"http.scheme":s,"http.flavor":R,"net.transport":R?.toUpperCase()==="QUIC"?"ip_udp":"ip_tcp",...GI0(F),...iJ(V.headers||{},z.getOptions().sendDefaultPii??!1)}});Q?.(G0,F),W?.(G0,B),K?.(G0,F,B),Y?.(G0,F,B);let E0={type:a5.RPCType.HTTP,span:G0};return M6.context.with(a5.setRPCMetadata(M6.trace.setSpan(M6.context.active(),G0),E0),()=>{M6.context.bind(M6.context.active(),F),M6.context.bind(M6.context.active(),B);let f0=!1;function k0(e0){if(f0)return;f0=!0;let y6=FI0(F,B);G0.setAttributes(y6),G0.setStatus(e0),G0.end();let i4=y6["http.route"];if(i4)R0().setTransactionName(`${F.method?.toUpperCase()||"GET"} ${i4}`)}return B.on("close",()=>{k0(d9(B.statusCode))}),B.on(YI0,()=>{let e0=d9(B.statusCode);k0(e0.code===A0?e0:{code:A0})}),D()})})})},processEvent(z){if(z.type==="transaction"){let G=z.contexts?.trace?.data?.["http.response.status_code"];if(typeof G==="number"){if(BI0(G,$))return _0&&A.log("Dropping transaction due to status code",G),null}}return z},afterAllSetup(z){if(!_0)return;if(z.getIntegrationByName("Http"))A.warn("It seems that you have manually added `httpServerSpansIntergation` while `httpIntegration` is also present. Make sure to remove `httpIntegration` when adding `httpServerSpansIntegration`.");if(!z.getIntegrationByName("Http.Server"))A.error("It seems that you have manually added `httpServerSpansIntergation` without adding `httpServerIntegration`. This is a requiement for spans to be created - please add the `httpServerIntegration` integration.")}}},WX=QI0;function WI0(Z){return Z.headers["next-router-prefetch"]==="1"}function KI0(Z){let J=p5(Z);if(J.match(/\.(ico|png|jpg|jpeg|gif|svg|css|js|woff|woff2|ttf|eot|webp|avif)$/))return!0;if(J.match(/^\/(robots\.txt|sitemap\.xml|manifest\.json|browserconfig\.xml)$/))return!0;return!1}function zI0(Z,{ignoreStaticAssets:J,ignoreIncomingRequests:X}){if(a5.isTracingSuppressed(M6.context.active()))return!0;let $=Z.url,Y=Z.method?.toUpperCase();if(Y==="OPTIONS"||Y==="HEAD"||!$)return!0;if(J&&Y==="GET"&&KI0($))return!0;if(X?.($,Z))return!0;return!1}function GI0(Z){let J=HI0(Z.headers);if(J==null)return{};if(VI0(Z.headers))return{["http.request_content_length"]:J};else return{["http.request_content_length_uncompressed"]:J}}function HI0(Z){let J=Z["content-length"];if(J===void 0)return null;let X=parseInt(J,10);if(isNaN(X))return null;return X}function VI0(Z){let J=Z["content-encoding"];return!!J&&J!=="identity"}function FI0(Z,J){let{socket:X}=Z,{statusCode:$,statusMessage:Y}=J,Q={[A6.ATTR_HTTP_RESPONSE_STATUS_CODE]:$,[A6.SEMATTRS_HTTP_STATUS_CODE]:$,"http.status_text":Y?.toUpperCase()},W=a5.getRPCMetadata(M6.context.active());if(X){let{localAddress:K,localPort:z,remoteAddress:G,remotePort:H}=X;Q[A6.SEMATTRS_NET_HOST_IP]=K,Q[A6.SEMATTRS_NET_HOST_PORT]=z,Q[A6.SEMATTRS_NET_PEER_IP]=G,Q["net.peer.port"]=H}if(Q[A6.SEMATTRS_HTTP_STATUS_CODE]=$,Q["http.status_text"]=(Y||"").toUpperCase(),W?.type===a5.RPCType.HTTP&&W.route!==void 0){let K=W.route;Q[A6.ATTR_HTTP_ROUTE]=K}return Q}function BI0(Z,J){return J.some((X)=>{if(typeof X==="number")return X===Z;let[$,Y]=X;return Z>=$&&Z<=Y})}var pu=k(f(),1),iu=k(H1(),1),gY=k(H0(),1);import{subscribe as AL,unsubscribe as TL}from"diagnostics_channel";function yY(Z){let J=Z.protocol||"",X=Z.hostname||Z.host||"",$=!Z.port||Z.port===80||Z.port===443||/^(.*):(\d+)$/.test(X)?"":`:${Z.port}`,Y=Z.path?Z.path:"/";return`${J}//${X}${$}${Y}`}var T0=k(p0(),1);var $6=k(f(),1),n=k(f(),1),k4=k(H1(),1);var Ku=k(H1(),1);var zX=k(f(),1),NK=k(H1(),1),P8=k(p0(),1);var UI0=typeof process==="object"&&typeof process.argv0==="string"&&process.argv0.length>0?`unknown_service:${process.argv0}`:"unknown_service";function sd(){return UI0}var KX=(Z)=>{return Z!==null&&typeof Z==="object"&&typeof Z.then==="function"};class RK{_rawAttributes;_asyncAttributesPending=!1;_schemaUrl;_memoizedAttributes;static FromAttributeList(Z,J){let X=new RK({},J);return X._rawAttributes=td(Z),X._asyncAttributesPending=Z.filter(([$,Y])=>KX(Y)).length>0,X}constructor(Z,J){let X=Z.attributes??{};this._rawAttributes=Object.entries(X).map(([$,Y])=>{if(KX(Y))this._asyncAttributesPending=!0;return[$,Y]}),this._rawAttributes=td(this._rawAttributes),this._schemaUrl=LI0(J?.schemaUrl)}get asyncAttributesPending(){return this._asyncAttributesPending}async waitForAsyncAttributes(){if(!this.asyncAttributesPending)return;for(let Z=0;Z<this._rawAttributes.length;Z++){let[J,X]=this._rawAttributes[Z];this._rawAttributes[Z]=[J,KX(X)?await X:X]}this._asyncAttributesPending=!1}get attributes(){if(this.asyncAttributesPending)zX.diag.error("Accessing resource attributes before async attributes settled");if(this._memoizedAttributes)return this._memoizedAttributes;let Z={};for(let[J,X]of this._rawAttributes){if(KX(X)){zX.diag.debug(`Unsettled resource attribute ${J} skipped`);continue}if(X!=null)Z[J]??=X}if(!this._asyncAttributesPending)this._memoizedAttributes=Z;return Z}getRawAttributes(){return this._rawAttributes}get schemaUrl(){return this._schemaUrl}merge(Z){if(Z==null)return this;let J=DI0(this,Z),X=J?{schemaUrl:J}:void 0;return RK.FromAttributeList([...Z.getRawAttributes(),...this.getRawAttributes()],X)}}function PK(Z,J){return RK.FromAttributeList(Object.entries(Z),J)}function SY(){return PK({[P8.ATTR_SERVICE_NAME]:sd(),[P8.ATTR_TELEMETRY_SDK_LANGUAGE]:NK.SDK_INFO[P8.ATTR_TELEMETRY_SDK_LANGUAGE],[P8.ATTR_TELEMETRY_SDK_NAME]:NK.SDK_INFO[P8.ATTR_TELEMETRY_SDK_NAME],[P8.ATTR_TELEMETRY_SDK_VERSION]:NK.SDK_INFO[P8.ATTR_TELEMETRY_SDK_VERSION]})}function td(Z){return Z.map(([J,X])=>{if(KX(X))return[J,X.catch(($)=>{zX.diag.debug("promise rejection for resource attribute: %s - %s",J,$);return})];return[J,X]})}function LI0(Z){if(typeof Z==="string"||Z===void 0)return Z;zX.diag.warn("Schema URL must be string or undefined, got %s. Schema URL will be ignored.",Z);return}function DI0(Z,J){let X=Z?.schemaUrl,$=J?.schemaUrl,Y=X===void 0||X==="",Q=$===void 0||$==="";if(Y)return $;if(Q)return X;if(X===$)return X;zX.diag.warn('Schema URL merge conflict: old resource has "%s", updating resource has "%s". Resulting resource will have undefined Schema URL.',X,$);return}var V1=k(f(),1),HX=k(H1(),1);var X6=k(f(),1),X1=k(H1(),1),J5=k(p0(),1);var ed="exception";class XL{_spanContext;kind;parentSpanContext;attributes={};links=[];events=[];startTime;resource;instrumentationScope;_droppedAttributesCount=0;_droppedEventsCount=0;_droppedLinksCount=0;name;status={code:X6.SpanStatusCode.UNSET};endTime=[0,0];_ended=!1;_duration=[-1,-1];_spanProcessor;_spanLimits;_attributeValueLengthLimit;_performanceStartTime;_performanceOffset;_startTimeProvided;constructor(Z){let J=Date.now();if(this._spanContext=Z.spanContext,this._performanceStartTime=X1.otperformance.now(),this._performanceOffset=J-(this._performanceStartTime+X1.otperformance.timeOrigin),this._startTimeProvided=Z.startTime!=null,this._spanLimits=Z.spanLimits,this._attributeValueLengthLimit=this._spanLimits.attributeValueLengthLimit||0,this._spanProcessor=Z.spanProcessor,this.name=Z.name,this.parentSpanContext=Z.parentSpanContext,this.kind=Z.kind,this.links=Z.links||[],this.startTime=this._getTime(Z.startTime??J),this.resource=Z.resource,this.instrumentationScope=Z.scope,Z.attributes!=null)this.setAttributes(Z.attributes);this._spanProcessor.onStart(this,Z.context)}spanContext(){return this._spanContext}setAttribute(Z,J){if(J==null||this._isSpanEnded())return this;if(Z.length===0)return X6.diag.warn(`Invalid attribute key: ${Z}`),this;if(!X1.isAttributeValue(J))return X6.diag.warn(`Invalid attribute value set for key: ${Z}`),this;let{attributeCountLimit:X}=this._spanLimits;if(X!==void 0&&Object.keys(this.attributes).length>=X&&!Object.prototype.hasOwnProperty.call(this.attributes,Z))return this._droppedAttributesCount++,this;return this.attributes[Z]=this._truncateToSize(J),this}setAttributes(Z){for(let[J,X]of Object.entries(Z))this.setAttribute(J,X);return this}addEvent(Z,J,X){if(this._isSpanEnded())return this;let{eventCountLimit:$}=this._spanLimits;if($===0)return X6.diag.warn("No events allowed."),this._droppedEventsCount++,this;if($!==void 0&&this.events.length>=$){if(this._droppedEventsCount===0)X6.diag.debug("Dropping extra events.");this.events.shift(),this._droppedEventsCount++}if(X1.isTimeInput(J)){if(!X1.isTimeInput(X))X=J;J=void 0}let Y=X1.sanitizeAttributes(J);return this.events.push({name:Z,attributes:Y,time:this._getTime(X),droppedAttributesCount:0}),this}addLink(Z){return this.links.push(Z),this}addLinks(Z){return this.links.push(...Z),this}setStatus(Z){if(this._isSpanEnded())return this;if(this.status={...Z},this.status.message!=null&&typeof Z.message!=="string")X6.diag.warn(`Dropping invalid status.message of type '${typeof Z.message}', expected 'string'`),delete this.status.message;return this}updateName(Z){if(this._isSpanEnded())return this;return this.name=Z,this}end(Z){if(this._isSpanEnded()){X6.diag.error(`${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`);return}if(this.endTime=this._getTime(Z),this._duration=X1.hrTimeDuration(this.startTime,this.endTime),this._duration[0]<0)X6.diag.warn("Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.",this.startTime,this.endTime),this.endTime=this.startTime.slice(),this._duration=[0,0];if(this._droppedEventsCount>0)X6.diag.warn(`Dropped ${this._droppedEventsCount} events because eventCountLimit reached`);if(this._spanProcessor.onEnding)this._spanProcessor.onEnding(this);this._ended=!0,this._spanProcessor.onEnd(this)}_getTime(Z){if(typeof Z==="number"&&Z<=X1.otperformance.now())return X1.hrTime(Z+this._performanceOffset);if(typeof Z==="number")return X1.millisToHrTime(Z);if(Z instanceof Date)return X1.millisToHrTime(Z.getTime());if(X1.isTimeInputHrTime(Z))return Z;if(this._startTimeProvided)return X1.millisToHrTime(Date.now());let J=X1.otperformance.now()-this._performanceStartTime;return X1.addHrTimes(this.startTime,X1.millisToHrTime(J))}isRecording(){return this._ended===!1}recordException(Z,J){let X={};if(typeof Z==="string")X[J5.ATTR_EXCEPTION_MESSAGE]=Z;else if(Z){if(Z.code)X[J5.ATTR_EXCEPTION_TYPE]=Z.code.toString();else if(Z.name)X[J5.ATTR_EXCEPTION_TYPE]=Z.name;if(Z.message)X[J5.ATTR_EXCEPTION_MESSAGE]=Z.message;if(Z.stack)X[J5.ATTR_EXCEPTION_STACKTRACE]=Z.stack}if(X[J5.ATTR_EXCEPTION_TYPE]||X[J5.ATTR_EXCEPTION_MESSAGE])this.addEvent(ed,X,J);else X6.diag.warn(`Failed to record an exception ${Z}`)}get duration(){return this._duration}get ended(){return this._ended}get droppedAttributesCount(){return this._droppedAttributesCount}get droppedEventsCount(){return this._droppedEventsCount}get droppedLinksCount(){return this._droppedLinksCount}_isSpanEnded(){if(this._ended){let Z=Error(`Operation attempted on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`);X6.diag.warn(`Cannot execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`,Z)}return this._ended}_truncateToLimitUtil(Z,J){if(Z.length<=J)return Z;return Z.substring(0,J)}_truncateToSize(Z){let J=this._attributeValueLengthLimit;if(J<=0)return X6.diag.warn(`Attribute value limit must be positive, got ${J}`),Z;if(typeof Z==="string")return this._truncateToLimitUtil(Z,J);if(Array.isArray(Z))return Z.map((X)=>typeof X==="string"?this._truncateToLimitUtil(X,J):X);return Z}}var yK=k(f(),1),u6=k(H1(),1);var e1;(function(Z){Z[Z.NOT_RECORD=0]="NOT_RECORD",Z[Z.RECORD=1]="RECORD",Z[Z.RECORD_AND_SAMPLED=2]="RECORD_AND_SAMPLED"})(e1||(e1={}));class RZ{shouldSample(){return{decision:e1.NOT_RECORD}}toString(){return"AlwaysOffSampler"}}class r5{shouldSample(){return{decision:e1.RECORD_AND_SAMPLED}}toString(){return"AlwaysOnSampler"}}var PZ=k(f(),1),Zu=k(H1(),1);class GX{_root;_remoteParentSampled;_remoteParentNotSampled;_localParentSampled;_localParentNotSampled;constructor(Z){if(this._root=Z.root,!this._root)Zu.globalErrorHandler(Error("ParentBasedSampler must have a root sampler configured")),this._root=new r5;this._remoteParentSampled=Z.remoteParentSampled??new r5,this._remoteParentNotSampled=Z.remoteParentNotSampled??new RZ,this._localParentSampled=Z.localParentSampled??new r5,this._localParentNotSampled=Z.localParentNotSampled??new RZ}shouldSample(Z,J,X,$,Y,Q){let W=PZ.trace.getSpanContext(Z);if(!W||!PZ.isSpanContextValid(W))return this._root.shouldSample(Z,J,X,$,Y,Q);if(W.isRemote){if(W.traceFlags&PZ.TraceFlags.SAMPLED)return this._remoteParentSampled.shouldSample(Z,J,X,$,Y,Q);return this._remoteParentNotSampled.shouldSample(Z,J,X,$,Y,Q)}if(W.traceFlags&PZ.TraceFlags.SAMPLED)return this._localParentSampled.shouldSample(Z,J,X,$,Y,Q);return this._localParentNotSampled.shouldSample(Z,J,X,$,Y,Q)}toString(){return`ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`}}var Ju=k(f(),1);class EK{_ratio;_upperBound;constructor(Z=0){this._ratio=this._normalize(Z),this._upperBound=Math.floor(this._ratio*4294967295)}shouldSample(Z,J){return{decision:Ju.isValidTraceId(J)&&this._accumulate(J)<this._upperBound?e1.RECORD_AND_SAMPLED:e1.NOT_RECORD}}toString(){return`TraceIdRatioBased{${this._ratio}}`}_normalize(Z){if(typeof Z!=="number"||isNaN(Z))return 0;return Z>=1?1:Z<=0?0:Z}_accumulate(Z){let J=0;for(let X=0;X<Z.length/8;X++){let $=X*8,Y=parseInt(Z.slice($,$+8),16);J=(J^Y)>>>0}return J}}var X5;(function(Z){Z.AlwaysOff="always_off",Z.AlwaysOn="always_on",Z.ParentBasedAlwaysOff="parentbased_always_off",Z.ParentBasedAlwaysOn="parentbased_always_on",Z.ParentBasedTraceIdRatio="parentbased_traceidratio",Z.TraceIdRatio="traceidratio"})(X5||(X5={}));var IK=1;function SK(){return{sampler:$L(),forceFlushTimeoutMillis:30000,generalLimits:{attributeValueLengthLimit:u6.getNumberFromEnv("OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT")??1/0,attributeCountLimit:u6.getNumberFromEnv("OTEL_ATTRIBUTE_COUNT_LIMIT")??128},spanLimits:{attributeValueLengthLimit:u6.getNumberFromEnv("OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT")??1/0,attributeCountLimit:u6.getNumberFromEnv("OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT")??128,linkCountLimit:u6.getNumberFromEnv("OTEL_SPAN_LINK_COUNT_LIMIT")??128,eventCountLimit:u6.getNumberFromEnv("OTEL_SPAN_EVENT_COUNT_LIMIT")??128,attributePerEventCountLimit:u6.getNumberFromEnv("OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT")??128,attributePerLinkCountLimit:u6.getNumberFromEnv("OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT")??128}}}function $L(){let Z=u6.getStringFromEnv("OTEL_TRACES_SAMPLER")??X5.ParentBasedAlwaysOn;switch(Z){case X5.AlwaysOn:return new r5;case X5.AlwaysOff:return new RZ;case X5.ParentBasedAlwaysOn:return new GX({root:new r5});case X5.ParentBasedAlwaysOff:return new GX({root:new RZ});case X5.TraceIdRatio:return new EK(Xu());case X5.ParentBasedTraceIdRatio:return new GX({root:new EK(Xu())});default:return yK.diag.error(`OTEL_TRACES_SAMPLER value "${Z}" invalid, defaulting to "${X5.ParentBasedAlwaysOn}".`),new GX({root:new r5})}}function Xu(){let Z=u6.getNumberFromEnv("OTEL_TRACES_SAMPLER_ARG");if(Z==null)return yK.diag.error(`OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${IK}.`),IK;if(Z<0||Z>1)return yK.diag.error(`OTEL_TRACES_SAMPLER_ARG=${Z} was given, but it is out of range ([0..1]), defaulting to ${IK}.`),IK;return Z}var kY=k(H1(),1),_I0=128,OI0=1/0;function $u(Z){let J={sampler:$L()},X=SK(),$=Object.assign({},X,J,Z);return $.generalLimits=Object.assign({},X.generalLimits,Z.generalLimits||{}),$.spanLimits=Object.assign({},X.spanLimits,Z.spanLimits||{}),$}function Yu(Z){let J=Object.assign({},Z.spanLimits);return J.attributeCountLimit=Z.spanLimits?.attributeCountLimit??Z.generalLimits?.attributeCountLimit??kY.getNumberFromEnv("OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT")??kY.getNumberFromEnv("OTEL_ATTRIBUTE_COUNT_LIMIT")??_I0,J.attributeValueLengthLimit=Z.spanLimits?.attributeValueLengthLimit??Z.generalLimits?.attributeValueLengthLimit??kY.getNumberFromEnv("OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT")??kY.getNumberFromEnv("OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT")??OI0,Object.assign({},Z,{spanLimits:J})}class xY{generateTraceId=Qu(16);generateSpanId=Qu(8)}var kK=Buffer.allocUnsafe(16);function Qu(Z){return function(){for(let X=0;X<Z/4;X++)kK.writeUInt32BE(Math.random()*4294967296>>>0,X*4);for(let X=0;X<Z;X++)if(kK[X]>0)break;else if(X===Z-1)kK[Z-1]=1;return kK.toString("hex",0,Z)}}class YL{_sampler;_generalLimits;_spanLimits;_idGenerator;instrumentationScope;_resource;_spanProcessor;constructor(Z,J,X,$){let Y=$u(J);this._sampler=Y.sampler,this._generalLimits=Y.generalLimits,this._spanLimits=Y.spanLimits,this._idGenerator=J.idGenerator||new xY,this._resource=X,this._spanProcessor=$,this.instrumentationScope=Z}startSpan(Z,J={},X=V1.context.active()){if(J.root)X=V1.trace.deleteSpan(X);let $=V1.trace.getSpan(X);if(HX.isTracingSuppressed(X))return V1.diag.debug("Instrumentation suppressed, returning Noop Span"),V1.trace.wrapSpanContext(V1.INVALID_SPAN_CONTEXT);let Y=$?.spanContext(),Q=this._idGenerator.generateSpanId(),W,K,z;if(!Y||!V1.trace.isSpanContextValid(Y))K=this._idGenerator.generateTraceId();else K=Y.traceId,z=Y.traceState,W=Y;let G=J.kind??V1.SpanKind.INTERNAL,H=(J.links??[]).map((O)=>{return{context:O.context,attributes:HX.sanitizeAttributes(O.attributes)}}),V=HX.sanitizeAttributes(J.attributes),F=this._sampler.shouldSample(X,K,Z,G,V,H);z=F.traceState??z;let B=F.decision===V1.SamplingDecision.RECORD_AND_SAMPLED?V1.TraceFlags.SAMPLED:V1.TraceFlags.NONE,U={traceId:K,spanId:Q,traceFlags:B,traceState:z};if(F.decision===V1.SamplingDecision.NOT_RECORD)return V1.diag.debug("Recording is off, propagating context in a non-recording span"),V1.trace.wrapSpanContext(U);let D=HX.sanitizeAttributes(Object.assign(V,F.attributes));return new XL({resource:this._resource,scope:this.instrumentationScope,context:X,spanContext:U,name:Z,kind:G,links:H,parentSpanContext:W,attributes:D,startTime:J.startTime,spanProcessor:this._spanProcessor,spanLimits:this._spanLimits})}startActiveSpan(Z,J,X,$){let Y,Q,W;if(arguments.length<2)return;else if(arguments.length===2)W=J;else if(arguments.length===3)Y=J,W=X;else Y=J,Q=X,W=$;let K=Q??V1.context.active(),z=this.startSpan(Z,Y,K),G=V1.trace.setSpan(K,z);return V1.context.with(G,W,void 0,z)}getGeneralLimits(){return this._generalLimits}getSpanLimits(){return this._spanLimits}}var Wu=k(H1(),1);class QL{_spanProcessors;constructor(Z){this._spanProcessors=Z}forceFlush(){let Z=[];for(let J of this._spanProcessors)Z.push(J.forceFlush());return new Promise((J)=>{Promise.all(Z).then(()=>{J()}).catch((X)=>{Wu.globalErrorHandler(X||Error("MultiSpanProcessor: forceFlush failed")),J()})})}onStart(Z,J){for(let X of this._spanProcessors)X.onStart(Z,J)}onEnding(Z){for(let J of this._spanProcessors)if(J.onEnding)J.onEnding(Z)}onEnd(Z){for(let J of this._spanProcessors)J.onEnd(Z)}shutdown(){let Z=[];for(let J of this._spanProcessors)Z.push(J.shutdown());return new Promise((J,X)=>{Promise.all(Z).then(()=>{J()},X)})}}var EZ;(function(Z){Z[Z.resolved=0]="resolved",Z[Z.timeout=1]="timeout",Z[Z.error=2]="error",Z[Z.unresolved=3]="unresolved"})(EZ||(EZ={}));class xK{_config;_tracers=new Map;_resource;_activeSpanProcessor;constructor(Z={}){let J=Ku.merge({},SK(),Yu(Z));this._resource=J.resource??SY(),this._config=Object.assign({},J,{resource:this._resource});let X=[];if(Z.spanProcessors?.length)X.push(...Z.spanProcessors);this._activeSpanProcessor=new QL(X)}getTracer(Z,J,X){let $=`${Z}@${J||""}:${X?.schemaUrl||""}`;if(!this._tracers.has($))this._tracers.set($,new YL({name:Z,version:J,schemaUrl:X?.schemaUrl},this._config,this._resource,this._activeSpanProcessor));return this._tracers.get($)}forceFlush(){let Z=this._config.forceFlushTimeoutMillis,J=this._activeSpanProcessor._spanProcessors.map((X)=>{return new Promise(($)=>{let Y,Q=setTimeout(()=>{$(Error(`Span processor did not completed within timeout period of ${Z} ms`)),Y=EZ.timeout},Z);X.forceFlush().then(()=>{if(clearTimeout(Q),Y!==EZ.timeout)Y=EZ.resolved,$(Y)}).catch((W)=>{clearTimeout(Q),Y=EZ.error,$(W)})})});return new Promise((X,$)=>{Promise.all(J).then((Y)=>{let Q=Y.filter((W)=>W!==EZ.resolved);if(Q.length>0)$(Q);else X()}).catch((Y)=>$([Y]))})}shutdown(){return this._activeSpanProcessor.shutdown()}}var BL="sentry.parentIsRemote",BX="sentry.graphql.operation";function UL(Z){if("parentSpanId"in Z)return Z.parentSpanId;else if("parentSpanContext"in Z)return Z.parentSpanContext?.spanId;return}function LL(Z){let J=Z;return!!J.attributes&&typeof J.attributes==="object"}function wI0(Z){return typeof Z.kind==="number"}function jI0(Z){return!!Z.status}function Fu(Z){return!!Z.name}function MI0(Z){if(!LL(Z))return{};let J=Z.attributes[T0.ATTR_URL_FULL]||Z.attributes[T0.SEMATTRS_HTTP_URL],X={url:J,"http.method":Z.attributes[T0.ATTR_HTTP_REQUEST_METHOD]||Z.attributes[T0.SEMATTRS_HTTP_METHOD]};if(!X["http.method"]&&X.url)X["http.method"]="GET";try{if(typeof J==="string"){let $=n9(J);if(X.url=o9($),$.search)X["http.query"]=$.search;if($.hash)X["http.fragment"]=$.hash}}catch{}return X}function AI0(Z){if(wI0(Z))return Z.kind;return n.SpanKind.INTERNAL}var WL="sentry-trace",KL="baggage",DL="sentry.dsc",_L="sentry.sampled_not_recording",Bu="sentry.url",TI0="sentry.sample_rand",qI0="sentry.sample_rate",OL=n.createContextKey("sentry_scopes"),zL=n.createContextKey("sentry_fork_isolation_scope"),GL=n.createContextKey("sentry_fork_set_scope"),HL=n.createContextKey("sentry_fork_set_isolation_scope"),Uu="_scopeContext";function UX(Z){return Z.getValue(OL)}function Lu(Z,J){return Z.setValue(OL,J)}function CI0(Z,J){f1(Z,Uu,J)}function hY(Z){return Z[Uu]}function FX(Z){let{traceFlags:J,traceState:X}=Z,$=X?X.get(_L)==="1":!1;if(J===n.TraceFlags.SAMPLED)return!0;if($)return!1;let Y=X?X.get(DL):void 0,Q=Y?T8(Y):void 0;if(Q?.sampled==="true")return!0;if(Q?.sampled==="false")return!1;return}function Du(Z,J,X){let $=J[T0.ATTR_HTTP_REQUEST_METHOD]||J[T0.SEMATTRS_HTTP_METHOD];if($)return RI0({attributes:J,name:Z,kind:X},$);let Y=J[T0.SEMATTRS_DB_SYSTEM],Q=typeof J[K0]==="string"&&J[K0].startsWith("cache.");if(Y&&!Q)return NI0({attributes:J,name:Z});let W=J[U1]==="custom"?"custom":"route";if(J[T0.SEMATTRS_RPC_SERVICE])return{...vY(Z,J,"route"),op:"rpc"};if(J[T0.SEMATTRS_MESSAGING_SYSTEM])return{...vY(Z,J,W),op:"message"};let G=J[T0.SEMATTRS_FAAS_TRIGGER];if(G)return{...vY(Z,J,W),op:G.toString()};return{op:void 0,description:Z,source:"custom"}}function _u(Z){let J=LL(Z)?Z.attributes:{},X=Fu(Z)?Z.name:"<unknown>",$=AI0(Z);return Du(X,J,$)}function NI0({attributes:Z,name:J}){let X=Z[s8];if(typeof X==="string")return{op:"db",description:X,source:Z[U1]||"custom"};if(Z[U1]==="custom")return{op:"db",description:J,source:"custom"};let $=Z[T0.SEMATTRS_DB_STATEMENT];return{op:"db",description:$?$.toString():J,source:"task"}}function RI0({name:Z,kind:J,attributes:X},$){let Y=["http"];switch(J){case n.SpanKind.CLIENT:Y.push("client");break;case n.SpanKind.SERVER:Y.push("server");break}if(X["sentry.http.prefetch"])Y.push("prefetch");let{urlPath:Q,url:W,query:K,fragment:z,hasRoute:G}=EI0(X,J);if(!Q)return{...vY(Z,X),op:Y.join(".")};let H=X[BX],V=`${$} ${Q}`,F=H?`${V} (${PI0(H)})`:V,B=G||Q==="/"?"route":"url",U={};if(W)U.url=W;if(K)U["http.query"]=K;if(z)U["http.fragment"]=z;let D=J===n.SpanKind.CLIENT||J===n.SpanKind.SERVER,O=!`${X[X0]||"manual"}`.startsWith("auto"),w=X[U1]==="custom",j=X[s8],q=!w&&j==null&&(D||!O),{description:R,source:T}=q?{description:F,source:B}:vY(Z,X);return{op:Y.join("."),description:R,source:T,data:U}}function PI0(Z){if(Array.isArray(Z)){let J=Z.slice().sort();if(J.length<=5)return J.join(", ");else return`${J.slice(0,5).join(", ")}, +${J.length-5}`}return`${Z}`}function EI0(Z,J){let X=Z[T0.SEMATTRS_HTTP_TARGET],$=Z[T0.SEMATTRS_HTTP_URL]||Z[T0.ATTR_URL_FULL],Y=Z[T0.ATTR_HTTP_ROUTE],Q=typeof $==="string"?n9($):void 0,W=Q?o9(Q):void 0,K=Q?.search||void 0,z=Q?.hash||void 0;if(typeof Y==="string")return{urlPath:Y,url:W,query:K,fragment:z,hasRoute:!0};if(J===n.SpanKind.SERVER&&typeof X==="string")return{urlPath:p5(X),url:W,query:K,fragment:z,hasRoute:!1};if(Q)return{urlPath:W,url:W,query:K,fragment:z,hasRoute:!1};if(typeof X==="string")return{urlPath:p5(X),url:W,query:K,fragment:z,hasRoute:!1};return{urlPath:void 0,url:W,query:K,fragment:z,hasRoute:!1}}function vY(Z,J,X="custom"){let $=J[U1]||X,Y=J[s8];if(Y&&typeof Y==="string")return{description:Y,source:$};return{description:Z,source:$}}function Ou(Z){Z.on("createDsc",(J,X)=>{if(!X)return;let Q=J0(X).data[U1],{description:W}=Fu(X)?_u(X):{description:void 0};if(Q!=="url"&&W)J.transaction=W;if(L1()){let K=FX(X.spanContext());J.sampled=K==null?void 0:String(K)}})}function wu(){return n.trace.getActiveSpan()}var $5=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;function ju({dsc:Z,sampled:J}){let X=Z?GZ(Z):void 0,$=new k4.TraceState,Y=X?$.set(DL,X):$;return J===!1?Y.set(_L,"1"):Y}var Mu=new Set;function Au(){return Array.from(Mu)}function vK(Z){Mu.add(Z)}class wL extends k4.W3CBaggagePropagator{constructor(){super();vK("SentryPropagator"),this._urlMatchesTargetsMap=new j6(100)}inject(Z,J,X){if(k4.isTracingSuppressed(Z)){$5&&A.log("[Tracing] Not injecting trace data for url because tracing is suppressed.");return}let $=n.trace.getSpan(Z),Y=$&&SI0($),{tracePropagationTargets:Q,propagateTraceparent:W}=u()?.getOptions()||{};if(!fY(Y,Q,this._urlMatchesTargetsMap)){$5&&A.log("[Tracing] Not injecting trace data for url because it does not match tracePropagationTargets:",Y);return}let K=yI0(J),z=n.propagation.getBaggage(Z)||n.propagation.createBaggage({}),{dynamicSamplingContext:G,traceId:H,spanId:V,sampled:F}=Tu(Z);if(K){let B=HZ(K);if(B)Object.entries(B).forEach(([U,D])=>{z=z.setEntry(U,{value:D})})}if(G)z=Object.entries(G).reduce((B,[U,D])=>{if(D)return B.setEntry(`${r$}${U}`,{value:D});return B},z);if(H&&H!==n.INVALID_TRACEID){if(X.set(J,WL,u9(H,V,F)),W)X.set(J,"traceparent",c9(H,V,F))}super.inject(n.propagation.setBaggage(Z,z),J,X)}extract(Z,J,X){let $=X.get(J,WL),Y=X.get(J,KL),Q=$?Array.isArray($)?$[0]:$:void 0;return Cu(qu(Z,{sentryTrace:Q,baggage:Y}))}fields(){return[WL,KL,"traceparent"]}}var zu="[Tracing] Not injecting trace data for url because it does not match tracePropagationTargets:";function fY(Z,J,X){if(typeof Z!=="string"||!J)return!0;let $=X?.get(Z);if($!==void 0)return $5&&!$&&A.log(zu,Z),$;let Y=h9(Z,J);return X?.set(Z,Y),$5&&!Y&&A.log(zu,Z),Y}function Tu(Z,J={}){let X=n.trace.getSpan(Z);if(X?.spanContext().isRemote){let K=X.spanContext();return{dynamicSamplingContext:S1(X),traceId:K.traceId,spanId:void 0,sampled:FX(K)}}if(X){let K=X.spanContext();return{dynamicSamplingContext:S1(X),traceId:K.traceId,spanId:K.spanId,sampled:FX(K)}}let $=J.scope||UX(Z)?.scope||u0(),Y=J.client||u(),Q=$.getPropagationContext();return{dynamicSamplingContext:Y?e8(Y,$):void 0,traceId:Q.traceId,spanId:Q.propagationSpanId,sampled:Q.sampled}}function qu(Z,{sentryTrace:J,baggage:X}){let $=VZ(J,X),{traceId:Y,parentSpanId:Q,sampled:W,dsc:K}=$,z=u(),G=T8(X);if(!Q||z&&!t$(z,G?.org_id))return Z;let H=kI0({traceId:Y,spanId:Q,sampled:W,dsc:K});return n.trace.setSpanContext(Z,H)}function II0(Z,J,X){let $=Cu(qu(Z,J));return n.context.with($,X)}function Cu(Z){let J=UX(Z),X={scope:J?J.scope:u0().clone(),isolationScope:J?J.isolationScope:R0()};return Lu(Z,X)}function yI0(Z){try{let J=Z[KL];return Array.isArray(J)?J.join(","):J}catch{return}}function SI0(Z){let J=J0(Z).data,X=J[T0.SEMATTRS_HTTP_URL]||J[T0.ATTR_URL_FULL];if(typeof X==="string")return X;let $=Z.spanContext().traceState?.get(Bu);if($)return $;return}function kI0({spanId:Z,traceId:J,sampled:X,dsc:$}){let Y=ju({dsc:$,sampled:X});return{traceId:J,spanId:Z,isRemote:!0,traceFlags:X?n.TraceFlags.SAMPLED:n.TraceFlags.NONE,traceState:Y}}function Nu(Z,J,X){let $=Pu(),{name:Y,parentSpan:Q}=Z;return Su(Q)(()=>{let K=Iu(Z.scope,Z.forceTransaction),G=Z.onlyIfParent&&!n.trace.getSpan(K)?k4.suppressTracing(K):K,H=Eu(Z);if(!L1()){let V=k4.isTracingSuppressed(G)?G:k4.suppressTracing(G);return n.context.with(V,()=>{return $.startActiveSpan(Y,H,V,(F)=>{return n.context.with(K,()=>{return D6(()=>J(F),()=>{if(J0(F).status===void 0)F.setStatus({code:n.SpanStatusCode.ERROR})},X?()=>F.end():void 0)})})})}return $.startActiveSpan(Y,H,G,(V)=>{return D6(()=>J(V),()=>{if(J0(V).status===void 0)V.setStatus({code:n.SpanStatusCode.ERROR})},X?()=>V.end():void 0)})})}function xI0(Z,J){return Nu(Z,J,!0)}function vI0(Z,J){return Nu(Z,(X)=>J(X,()=>X.end()),!1)}function hI0(Z){let J=Pu(),{name:X,parentSpan:$}=Z;return Su($)(()=>{let Q=Iu(Z.scope,Z.forceTransaction),K=Z.onlyIfParent&&!n.trace.getSpan(Q)?k4.suppressTracing(Q):Q,z=Eu(Z);if(!L1())K=k4.isTracingSuppressed(K)?K:k4.suppressTracing(K);return J.startSpan(X,z,K)})}function Ru(Z,J){let X=Z?n.trace.setSpan(n.context.active(),Z):n.trace.deleteSpan(n.context.active());return n.context.with(X,()=>J(u0()))}function Pu(){return u()?.tracer||n.trace.getTracer("@sentry/opentelemetry",N0)}function Eu(Z){let{startTime:J,attributes:X,kind:$,op:Y,links:Q}=Z,W=typeof J==="number"?fI0(J):J;return{attributes:Y?{[K0]:Y,...X}:X,kind:$,links:Q,startTime:W}}function fI0(Z){return Z<9999999999?Z*1000:Z}function Iu(Z,J){let X=bI0(Z),$=n.trace.getSpan(X);if(!$)return X;if(!J)return X;let Y=n.trace.deleteSpan(X),{spanId:Q,traceId:W}=$.spanContext(),K=FX($.spanContext()),z=q1($),G=S1(z),H=ju({dsc:G,sampled:K}),V={traceId:W,spanId:Q,isRemote:!0,traceFlags:K?n.TraceFlags.SAMPLED:n.TraceFlags.NONE,traceState:H};return n.trace.setSpanContext(Y,V)}function bI0(Z){if(Z){let J=hY(Z);if(J)return J}return n.context.active()}function gI0(Z,J){return II0(n.context.active(),Z,J)}function yu(Z,J){let X=hY(J),$=X&&n.trace.getSpan(X),Y=$?l9($):zZ(J);return[$?S1($):e8(Z,J),Y]}function Su(Z){return Z!==void 0?(J)=>{return Ru(Z,J)}:(J)=>J()}function mI0(Z){let J=k4.suppressTracing(n.context.active());return n.context.with(J,Z)}function ku(Z){Z.on("preprocessEvent",(J)=>{let X=wu();if(!X||J.type==="transaction")return;J.contexts={trace:l9(X),...J.contexts};let $=q1(X);return J.sdkProcessingMetadata={dynamicSamplingContext:S1($),...J.sdkProcessingMetadata},J})}function dI0({span:Z,scope:J,client:X,propagateTraceparent:$}={}){let Y=(J&&hY(J))??$6.context.active();if(Z){let{scope:H}=A8(Z);Y=H&&hY(H)||$6.trace.setSpan($6.context.active(),Z)}let{traceId:Q,spanId:W,sampled:K,dynamicSamplingContext:z}=Tu(Y,{scope:J,client:X}),G={"sentry-trace":u9(Q,W,K),baggage:GZ(z)};if($)G.traceparent=c9(Q,W,K);return G}function xu(){function Z(){let K=$6.context.active(),z=UX(K);if(z)return z;return{scope:vJ(),isolationScope:B6()}}function J(K){let z=$6.context.active();return $6.context.with(z,()=>{return K(Q())})}function X(K,z){let G=hY(K)||$6.context.active();return $6.context.with(G.setValue(GL,K),()=>{return z(K)})}function $(K){let z=$6.context.active();return $6.context.with(z.setValue(zL,!0),()=>{return K(W())})}function Y(K,z){let G=$6.context.active();return $6.context.with(G.setValue(HL,K),()=>{return z(W())})}function Q(){return Z().scope}function W(){return Z().isolationScope}PB({withScope:J,withSetScope:X,withSetIsolationScope:Y,withIsolationScope:$,getCurrentScope:Q,getIsolationScope:W,startSpan:xI0,startSpanManual:vI0,startInactiveSpan:hI0,getActiveSpan:wu,suppressTracing:mI0,getTraceData:dI0,continueTrace:gI0,withActiveSpan:Ru})}function vu(Z){class J extends Z{constructor(...X){super(...X);vK("SentryContextManager")}with(X,$,Y,...Q){let W=UX(X),K=W?.scope||u0(),z=W?.isolationScope||R0(),G=X.getValue(zL)===!0,H=X.getValue(GL),V=X.getValue(HL),F=H||K.clone(),B=V||(G?z.clone():z),_=Lu(X,{scope:F,isolationScope:B}).deleteValue(zL).deleteValue(GL).deleteValue(HL);return CI0(F,_),super.with(_,$,Y,...Q)}getAsyncLocalStorageLookup(){return{asyncLocalStorage:this._asyncLocalStorage,contextSymbol:OL}}}return J}function uI0(Z){let J=new Map;for(let X of Z)cI0(J,X);return Array.from(J,function([X,$]){return $})}function hu(Z){return Z.attributes[BL]!==!0?UL(Z):void 0}function cI0(Z,J){let X=J.spanContext().spanId,$=hu(J);if(!$){VL(Z,{id:X,span:J,children:[]});return}let Y=lI0(Z,$),Q=VL(Z,{id:X,span:J,parentNode:Y,children:[]});Y.children.push(Q)}function lI0(Z,J){let X=Z.get(J);if(X)return X;return VL(Z,{id:J,children:[]})}function VL(Z,J){let X=Z.get(J.id);if(X?.span)return X;if(X&&!X.span)return X.span=J.span,X.parentNode=J.parentNode,X;return Z.set(J.id,J),J}var fu={"1":"cancelled","2":"unknown_error","3":"invalid_argument","4":"deadline_exceeded","5":"not_found","6":"already_exists","7":"permission_denied","8":"resource_exhausted","9":"failed_precondition","10":"aborted","11":"out_of_range","12":"unimplemented","13":"internal_error","14":"unavailable","15":"data_loss","16":"unauthenticated"},pI0=(Z)=>{return Object.values(fu).includes(Z)};function bu(Z){let J=LL(Z)?Z.attributes:{},X=jI0(Z)?Z.status:void 0;if(X){if(X.code===n.SpanStatusCode.OK)return{code:gJ};else if(X.code===n.SpanStatusCode.ERROR){if(typeof X.message>"u"){let Y=Gu(J);if(Y)return Y}if(X.message&&pI0(X.message))return{code:A0,message:X.message};else return{code:A0,message:"internal_error"}}}let $=Gu(J);if($)return $;if(X?.code===n.SpanStatusCode.UNSET)return{code:gJ};else return{code:A0,message:"unknown_error"}}function Gu(Z){let J=Z[T0.ATTR_HTTP_RESPONSE_STATUS_CODE]||Z[T0.SEMATTRS_HTTP_STATUS_CODE],X=Z[T0.SEMATTRS_RPC_GRPC_STATUS_CODE],$=typeof J==="number"?J:typeof J==="string"?parseInt(J):void 0;if(typeof $==="number")return d9($);if(typeof X==="string")return{code:A0,message:fu[X]||"unknown_error"};return}var Hu=1000,Vu=300;class gu{constructor(Z){this._finishedSpanBucketSize=Z?.timeout||Vu,this._finishedSpanBuckets=Array(this._finishedSpanBucketSize).fill(void 0),this._lastCleanupTimestampInS=Math.floor(f6()/1000),this._spansToBucketEntry=new WeakMap,this._sentSpans=new Map,this._debouncedFlush=GU(this.flush.bind(this),1,{maxWait:100})}export(Z){let J=Math.floor(f6()/1000);if(this._lastCleanupTimestampInS!==J){let Q=0;if(this._finishedSpanBuckets.forEach((W,K)=>{if(W&&W.timestampInS<=J-this._finishedSpanBucketSize)Q+=W.spans.size,this._finishedSpanBuckets[K]=void 0}),Q>0)$5&&A.log(`SpanExporter dropped ${Q} spans because they were pending for more than ${this._finishedSpanBucketSize} seconds.`);this._lastCleanupTimestampInS=J}let X=J%this._finishedSpanBucketSize,$=this._finishedSpanBuckets[X]||{timestampInS:J,spans:new Set};this._finishedSpanBuckets[X]=$,$.spans.add(Z),this._spansToBucketEntry.set(Z,$);let Y=hu(Z);if(!Y||this._sentSpans.has(Y))this._debouncedFlush()}flush(){let Z=this._finishedSpanBuckets.flatMap((Q)=>Q?Array.from(Q.spans):[]);this._flushSentSpanCache();let J=this._maybeSend(Z),X=J.size,$=Z.length-X;$5&&A.log(`SpanExporter exported ${X} spans, ${$} spans are waiting for their parent spans to finish`);let Y=f6()+Vu*1000;for(let Q of J){this._sentSpans.set(Q.spanContext().spanId,Y);let W=this._spansToBucketEntry.get(Q);if(W)W.spans.delete(Q)}this._debouncedFlush.cancel()}clear(){this._finishedSpanBuckets=this._finishedSpanBuckets.fill(void 0),this._sentSpans.clear(),this._debouncedFlush.cancel()}_maybeSend(Z){let J=uI0(Z),X=new Set,$=this._getCompletedRootNodes(J);for(let Y of $){let Q=Y.span;X.add(Q);let W=nI0(Q);if(Y.parentNode&&this._sentSpans.has(Y.parentNode.id)){let G=W.contexts?.trace?.data;if(G)G["sentry.parent_span_already_sent"]=!0}let K=W.spans||[];for(let G of Y.children)FL(G,K,X);W.spans=K.length>Hu?K.sort((G,H)=>G.start_timestamp-H.start_timestamp).slice(0,Hu):K;let z=UZ(Q.events);if(z)W.measurements=z;pW(W)}return X}_flushSentSpanCache(){let Z=f6();for(let[J,X]of this._sentSpans.entries())if(X<=Z)this._sentSpans.delete(J)}_nodeIsCompletedRootNodeOrHasSentParent(Z){return!!Z.span&&(!Z.parentNode||this._sentSpans.has(Z.parentNode.id))}_getCompletedRootNodes(Z){return Z.filter((J)=>this._nodeIsCompletedRootNodeOrHasSentParent(J))}}function iI0(Z){let J=Z.attributes,X=J[X0],$=J[K0],Y=J[U1];return{origin:X,op:$,source:Y}}function nI0(Z){let{op:J,description:X,data:$,origin:Y="manual",source:Q}=mu(Z),W=A8(Z),K=Z.attributes[M8],z={[U1]:Q,[M8]:K,[K0]:J,[X0]:Y,...$,...du(Z.attributes)},{links:G}=Z,{traceId:H,spanId:V}=Z.spanContext(),F=UL(Z),B=bu(Z),U={parent_span_id:F,span_id:V,trace_id:H,data:z,origin:Y,op:J,status:BZ(B),links:FZ(G)},D=z[T0.ATTR_HTTP_RESPONSE_STATUS_CODE],_=typeof D==="number"?{response:{status_code:D}}:void 0;return{contexts:{trace:U,otel:{resource:Z.resource.attributes},..._},spans:[],start_timestamp:t4(Z.startTime),timestamp:t4(Z.endTime),transaction:X,type:"transaction",sdkProcessingMetadata:{capturedSpanScope:W.scope,capturedSpanIsolationScope:W.isolationScope,sampleRate:K,dynamicSamplingContext:S1(Z)},...Q&&{transaction_info:{source:Q}}}}function FL(Z,J,X){let $=Z.span;if($)X.add($);if(!$){Z.children.forEach((j)=>{FL(j,J,X)});return}let Q=$.spanContext().spanId,W=$.spanContext().traceId,K=UL($),{attributes:z,startTime:G,endTime:H,links:V}=$,{op:F,description:B,data:U,origin:D="manual"}=mu($),_={[X0]:D,[K0]:F,...du(z),...U},O=bu($),w={span_id:Q,trace_id:W,data:_,description:B,parent_span_id:K,start_timestamp:t4(G),timestamp:t4(H)||void 0,status:BZ(O),op:F,origin:D,measurements:UZ($.events),links:FZ(V)};J.push(w),Z.children.forEach((j)=>{FL(j,J,X)})}function mu(Z){let{op:J,source:X,origin:$}=iI0(Z),{op:Y,description:Q,source:W,data:K}=_u(Z),z=J||Y,G=X||W,H={...K,...oI0(Z)};return{op:z,description:Q,source:G,origin:$,data:H}}function du(Z){let J={...Z};return delete J[M8],delete J[BL],delete J[s8],J}function oI0(Z){let J=Z.attributes,X={};if(Z.kind!==n.SpanKind.INTERNAL)X["otel.kind"]=n.SpanKind[Z.kind];let $=J[T0.SEMATTRS_HTTP_STATUS_CODE];if($)X[T0.ATTR_HTTP_RESPONSE_STATUS_CODE]=$;let Y=MI0(Z);if(Y.url)X.url=Y.url;if(Y["http.query"])X["http.query"]=Y["http.query"].slice(1);if(Y["http.fragment"])X["http.fragment"]=Y["http.fragment"].slice(1);return X}function aI0(Z,J){let X=n.trace.getSpan(J),$=UX(J);if(X&&!X.spanContext().isRemote)mJ(X,Z);if(X?.spanContext().isRemote)Z.setAttribute(BL,!0);if(J===n.ROOT_CONTEXT)$={scope:vJ(),isolationScope:B6()};if($)a$(Z,$.scope,$.isolationScope);YY(Z),u()?.emit("spanStart",Z)}function rI0(Z){QY(Z),u()?.emit("spanEnd",Z)}class jL{constructor(Z){vK("SentrySpanProcessor"),this._exporter=new gu(Z)}async forceFlush(){this._exporter.flush()}async shutdown(){this._exporter.clear()}onStart(Z,J){aI0(Z,J)}onEnd(Z){rI0(Z),this._exporter.export(Z)}}class ML{constructor(Z){this._client=Z,vK("SentrySampler")}shouldSample(Z,J,X,$,Y,Q){let W=this._client.getOptions(),K=eI0(Z),z=K?.spanContext();if(!L1(W))return VX({decision:void 0,context:Z,spanAttributes:Y});let G=Y[T0.SEMATTRS_HTTP_METHOD]||Y[T0.ATTR_HTTP_REQUEST_METHOD];if($===n.SpanKind.CLIENT&&G&&(!K||z?.isRemote))return VX({decision:void 0,context:Z,spanAttributes:Y});let H=K?sI0(K,J,X):void 0;if(!(!K||z?.isRemote))return VX({decision:H?e1.RECORD_AND_SAMPLED:e1.NOT_RECORD,context:Z,spanAttributes:Y});let{description:F,data:B,op:U}=Du(X,Y,$),D={...B,...Y};if(U)D[K0]=U;let _={decision:!0};if(this._client.emit("beforeSampling",{spanAttributes:D,spanName:F,parentSampled:H,parentContext:z},_),!_.decision)return VX({decision:void 0,context:Z,spanAttributes:Y});let{isolationScope:O}=UX(Z)??{},w=z?.traceState?z.traceState.get(DL):void 0,j=w?T8(w):void 0,q=L6(j?.sample_rand)??K4(),[R,T,y]=KY(W,{name:F,attributes:D,normalizedRequest:O?.getScopeData().sdkProcessingMetadata.normalizedRequest,parentSampled:H,parentSampleRate:L6(j?.sample_rate)},q),i=`${G}`.toUpperCase();if(i==="OPTIONS"||i==="HEAD")return $5&&A.log(`[Tracing] Not sampling span because HTTP method is '${i}' for ${X}`),VX({decision:e1.NOT_RECORD,context:Z,spanAttributes:Y,sampleRand:q,downstreamTraceSampleRate:0});if(!R&&H===void 0)$5&&A.log("[Tracing] Discarding root span because its trace was not chosen to be sampled."),this._client.recordDroppedEvent("sample_rate","transaction");return{...VX({decision:R?e1.RECORD_AND_SAMPLED:e1.NOT_RECORD,context:Z,spanAttributes:Y,sampleRand:q,downstreamTraceSampleRate:y?T:void 0}),attributes:{[M8]:y?T:void 0}}}toString(){return"SentrySampler"}}function sI0(Z,J,X){let $=Z.spanContext();if(n.isSpanContextValid($)&&$.traceId===J){if($.isRemote){let Q=FX(Z.spanContext());return $5&&A.log(`[Tracing] Inheriting remote parent's sampled decision for ${X}: ${Q}`),Q}let Y=FX($);return $5&&A.log(`[Tracing] Inheriting parent's sampled decision for ${X}: ${Y}`),Y}return}function VX({decision:Z,context:J,spanAttributes:X,sampleRand:$,downstreamTraceSampleRate:Y}){let Q=tI0(J,X);if(Y!==void 0)Q=Q.set(qI0,`${Y}`);if($!==void 0)Q=Q.set(TI0,`${$}`);if(Z==null)return{decision:e1.NOT_RECORD,traceState:Q};if(Z===e1.NOT_RECORD)return{decision:Z,traceState:Q.set(_L,"1")};return{decision:Z,traceState:Q}}function tI0(Z,J){let Y=n.trace.getSpan(Z)?.spanContext()?.traceState||new k4.TraceState,Q=J[T0.SEMATTRS_HTTP_URL]||J[T0.ATTR_URL_FULL];if(Q&&typeof Q==="string")Y=Y.set(Bu,Q);return Y}function eI0(Z){let J=n.trace.getSpan(Z);return J&&n.isSpanContextValid(J.spanContext())?J:void 0}function bY(Z,J){if(!Z)return J;let X=HZ(Z),$=HZ(J);if(!$)return Z;let Y={...X};return Object.entries($).forEach(([Q,W])=>{if(!Y[Q])Y[Q]=W}),kW(Y)}function uu(Z,J){let X=Zy0(Z),$=J?.statusCode,Y=qY($);g6({category:"http",data:{status_code:$,...X},type:"http",level:Y},{event:"response",request:Z,response:J})}function cu(Z,J){let X=Jy0(Z),{tracePropagationTargets:$,propagateTraceparent:Y}=u()?.getOptions()||{},Q=fY(X,$,J)?pJ({propagateTraceparent:Y}):void 0;if(!Q)return;let{"sentry-trace":W,baggage:K,traceparent:z}=Q;if(W&&!Z.getHeader("sentry-trace"))try{Z.setHeader("sentry-trace",W),_0&&A.log(Z5,"Added sentry-trace header to outgoing request")}catch(G){_0&&A.error(Z5,"Failed to add sentry-trace header to outgoing request:",a8(G)?G.message:"Unknown error")}if(z&&!Z.getHeader("traceparent"))try{Z.setHeader("traceparent",z),_0&&A.log(Z5,"Added traceparent header to outgoing request")}catch(G){_0&&A.error(Z5,"Failed to add traceparent header to outgoing request:",a8(G)?G.message:"Unknown error")}if(K){let G=bY(Z.getHeader("baggage"),K);if(G)try{Z.setHeader("baggage",G),_0&&A.log(Z5,"Added baggage header to outgoing request")}catch(H){_0&&A.error(Z5,"Failed to add baggage header to outgoing request:",a8(H)?H.message:"Unknown error")}}}function Zy0(Z){try{let J=Z.getHeader("host")||Z.host,X=new URL(Z.path,`${Z.protocol}//${J}`),$=n9(X.toString()),Y={url:o9($),"http.method":Z.method||"GET"};if($.search)Y["http.query"]=$.search;if($.hash)Y["http.fragment"]=$.hash;return Y}catch{return{}}}function lu(Z){return{method:Z.method,protocol:Z.protocol,host:Z.host,hostname:Z.host,path:Z.path,headers:Z.getHeaders()}}function Jy0(Z){let J=Z.getHeader("host")||Z.host,X=Z.protocol,$=Z.path;return`${X}//${J}${$}`}class LX extends gY.InstrumentationBase{constructor(Z={}){super(Z5,N0,Z);this._propagationDecisionMap=new j6(100),this._ignoreOutgoingRequestsMap=new WeakMap}init(){let Z=!1,J=(W)=>{let K=W;this._onOutgoingRequestFinish(K.request,K.response)},X=(W)=>{let K=W;this._onOutgoingRequestFinish(K.request,void 0)},$=(W)=>{let K=W;this._onOutgoingRequestCreated(K.request)},Y=(W)=>{if(Z)return W;if(Z=!0,AL("http.client.response.finish",J),AL("http.client.request.error",X),this.getConfig().propagateTraceInOutgoingRequests)AL("http.client.request.created",$);return W},Q=()=>{TL("http.client.response.finish",J),TL("http.client.request.error",X),TL("http.client.request.created",$)};return[new gY.InstrumentationNodeModuleDefinition("http",["*"],Y,Q),new gY.InstrumentationNodeModuleDefinition("https",["*"],Y,Q)]}_onOutgoingRequestFinish(Z,J){_0&&A.log(Z5,"Handling finished outgoing request");let X=this.getConfig().breadcrumbs,$=typeof X>"u"?!0:X,Y=this._ignoreOutgoingRequestsMap.get(Z)??this._shouldIgnoreOutgoingRequest(Z);if(this._ignoreOutgoingRequestsMap.set(Z,Y),$&&!Y)uu(Z,J)}_onOutgoingRequestCreated(Z){let J=this._ignoreOutgoingRequestsMap.get(Z)??this._shouldIgnoreOutgoingRequest(Z);if(this._ignoreOutgoingRequestsMap.set(Z,J),J)return;cu(Z,this._propagationDecisionMap)}_shouldIgnoreOutgoingRequest(Z){if(iu.isTracingSuppressed(pu.context.active()))return!0;let J=this.getConfig().ignoreOutgoingRequests;if(!J)return!1;let X=lu(Z),$=yY(Z);return J($,X)}}var nu="Http",Xy0=a(`${nu}.sentry`,(Z)=>{return new LX(Z)}),ou=S((Z={})=>{let J={sessions:Z.trackIncomingRequestsAsSessions,sessionFlushingDelayMS:Z.sessionFlushingDelayMS,ignoreRequestBody:Z.ignoreIncomingRequestBody,maxRequestBodySize:Z.maxIncomingRequestBodySize},X={ignoreIncomingRequests:Z.ignoreIncomingRequests,ignoreStaticAssets:Z.ignoreStaticAssets,ignoreStatusCodes:Z.dropSpansForIncomingRequestStatusCodes},$={breadcrumbs:Z.breadcrumbs,propagateTraceInOutgoingRequests:!0,ignoreOutgoingRequests:Z.ignoreOutgoingRequests},Y=YX(J),Q=WX(X),W=Z.spans??!1,K=Z.disableIncomingRequestSpans??!1,z=W&&!K;return{name:nu,setup(G){if(z)Q.setup(G)},setupOnce(){Y.setupOnce(),Xy0($)},processEvent(G){return Q.processEvent(G)}}});var ru=k(f(),1),su=k(H1(),1),tu=k(H0(),1);import*as DX from"diagnostics_channel";var G7=NB(process.versions.node),s5=G7.major,mY=G7.minor;var hK="sentry-trace",qL="baggage",au=/baggage: (.*)\r\n/;class _X extends tu.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-node-fetch",N0,Z);this._channelSubs=[],this._propagationDecisionMap=new j6(100),this._ignoreOutgoingRequestsMap=new WeakMap}init(){return}disable(){super.disable(),this._channelSubs.forEach((Z)=>Z.unsubscribe()),this._channelSubs=[]}enable(){if(super.enable(),this._channelSubs=this._channelSubs||[],this._channelSubs.length>0)return;this._subscribeToChannel("undici:request:create",this._onRequestCreated.bind(this)),this._subscribeToChannel("undici:request:headers",this._onResponseHeaders.bind(this))}_onRequestCreated({request:Z}){if(this.getConfig().enabled===!1)return;let $=this._shouldIgnoreOutgoingRequest(Z);if(this._ignoreOutgoingRequestsMap.set(Z,$),$)return;let Y=CL(Z.origin,Z.path),{tracePropagationTargets:Q,propagateTraceparent:W}=u()?.getOptions()||{},K=fY(Y,Q,this._propagationDecisionMap)?pJ({propagateTraceparent:W}):void 0;if(!K)return;let{"sentry-trace":z,baggage:G,traceparent:H}=K;if(Array.isArray(Z.headers)){let V=Z.headers;if(z&&!V.includes(hK))V.push(hK,z);if(H&&!V.includes("traceparent"))V.push("traceparent",H);let F=V.findIndex((B)=>B===qL);if(G&&F===-1)V.push(qL,G);else if(G){let B=V[F+1],U=bY(B,G);if(U)V[F+1]=U}}else{let V=Z.headers;if(z&&!V.includes(`${hK}:`))Z.headers+=`${hK}: ${z}\r
40
+ Event: ${f9(Z)}`),!0}return!1}function oC0(Z,J){if(!J?.length)return!1;return rW(Z).some((X)=>h9(X,J))}function aC0(Z,J){if(!J?.length)return!1;let X=Z.transaction;return X?h9(X,J):!1}function rC0(Z,J){if(!J?.length)return!1;let X=eW(Z);return!X?!1:h9(X,J)}function sC0(Z,J){if(!J?.length)return!0;let X=eW(Z);return!X?!0:h9(X,J)}function tC0(Z=[]){for(let J=Z.length-1;J>=0;J--){let X=Z[J];if(X&&X.filename!=="<anonymous>"&&X.filename!=="[native code]")return X.filename||null}return null}function eW(Z){try{let X=[...Z.exception?.values??[]].reverse().find(($)=>$.mechanism?.parent_id===void 0&&$.stacktrace?.frames?.length)?.stacktrace?.frames;return X?tC0(X):null}catch{return l&&A.error(`Cannot extract url for event ${f9(Z)}`),null}}function eC0(Z){if(!Z.exception?.values?.length)return!1;return!Z.message&&!Z.exception.values.some((J)=>J.stacktrace||J.type&&J.type!=="Error"||J.value)}function nf(Z,J,X,$,Y,Q){if(!Y.exception?.values||!Q||!r8(Q.originalException,Error))return;let W=Y.exception.values.length>0?Y.exception.values[Y.exception.values.length-1]:void 0;if(W)Y.exception.values=FU(Z,J,$,Q.originalException,X,Y.exception.values,W,0)}function FU(Z,J,X,$,Y,Q,W,K){if(Q.length>=X+1)return Q;let z=[...Q];if(r8($[Y],Error)){lf(W,K);let G=Z(J,$[Y]),H=z.length;pf(G,Y,H,K),z=FU(Z,J,X,$[Y],Y,[G,...z],G,H)}if(Array.isArray($.errors))$.errors.forEach((G,H)=>{if(r8(G,Error)){lf(W,K);let V=Z(J,G),F=z.length;pf(V,`errors[${H}]`,F,K),z=FU(Z,J,X,G,Y,[V,...z],V,F)}});return z}function lf(Z,J){Z.mechanism={handled:!0,type:"auto.core.linked_errors",...Z.mechanism,...Z.type==="AggregateError"&&{is_exception_group:!0},exception_id:J}}function pf(Z,J,X,$){Z.mechanism={handled:!0,...Z.mechanism,type:"chained",source:J,exception_id:X,parent_id:$}}var ZN0="cause",JN0=5,XN0="LinkedErrors",$N0=(Z={})=>{let J=Z.limit||JN0,X=Z.key||ZN0;return{name:XN0,preprocessEvent($,Y,Q){let W=Q.getOptions();nf(YU,W.stackParser,X,J,$,Y)}}},aJ=S($N0);function of(Z){let J={},X=0;while(X<Z.length){let $=Z.indexOf("=",X);if($===-1)break;let Y=Z.indexOf(";",X);if(Y===-1)Y=Z.length;else if(Y<$){X=Z.lastIndexOf(";",$-1)+1;continue}let Q=Z.slice(X,$).trim();if(J[Q]===void 0){let W=Z.slice($+1,Y).trim();if(W.charCodeAt(0)===34)W=W.slice(1,-1);try{J[Q]=W.indexOf("%")!==-1?decodeURIComponent(W):W}catch{J[Q]=W}}X=Y+1}return J}var BU=["X-Client-IP","X-Forwarded-For","Fly-Client-IP","CF-Connecting-IP","Fastly-Client-Ip","True-Client-Ip","X-Real-IP","X-Cluster-Client-IP","X-Forwarded","Forwarded-For","Forwarded","X-Vercel-Forwarded-For"];function af(Z){return BU.map((Y)=>{let Q=Z[Y],W=Array.isArray(Q)?Q.join(";"):Q;if(Y==="Forwarded")return YN0(W);return W?.split(",").map((K)=>K.trim())}).reduce((Y,Q)=>{if(!Q)return Y;return Y.concat(Q)},[]).find((Y)=>Y!==null&&QN0(Y))||null}function YN0(Z){if(!Z)return null;for(let J of Z.split(";"))if(J.startsWith("for="))return J.slice(4);return null}function QN0(Z){return/(?:^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$)|(?:^(?:(?:[a-fA-F\d]{1,4}:){7}(?:[a-fA-F\d]{1,4}|:)|(?:[a-fA-F\d]{1,4}:){6}(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|:[a-fA-F\d]{1,4}|:)|(?:[a-fA-F\d]{1,4}:){5}(?::(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,2}|:)|(?:[a-fA-F\d]{1,4}:){4}(?:(?::[a-fA-F\d]{1,4}){0,1}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,3}|:)|(?:[a-fA-F\d]{1,4}:){3}(?:(?::[a-fA-F\d]{1,4}){0,2}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,4}|:)|(?:[a-fA-F\d]{1,4}:){2}(?:(?::[a-fA-F\d]{1,4}){0,3}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,5}|:)|(?:[a-fA-F\d]{1,4}:){1}(?:(?::[a-fA-F\d]{1,4}){0,4}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,6}|:)|(?::(?:(?::[a-fA-F\d]{1,4}){0,5}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,7}|:)))(?:%[0-9a-zA-Z]{1,})?$)/.test(Z)}var WN0={cookies:!0,data:!0,headers:!0,query_string:!0,url:!0},KN0="RequestData",zN0=(Z={})=>{let J={...WN0,...Z.include};return{name:KN0,processEvent(X,$,Y){let{sdkProcessingMetadata:Q={}}=X,{normalizedRequest:W,ipAddress:K}=Q,z={...J,ip:J.ip??Y.getOptions().sendDefaultPii};if(W)GN0(X,W,{ipAddress:K},z);return X}}},rJ=S(zN0);function GN0(Z,J,X,$){if(Z.request={...Z.request,...HN0(J,$)},$.ip){let Y=J.headers&&af(J.headers)||X.ipAddress;if(Y)Z.user={...Z.user,ip_address:Y}}}function HN0(Z,J){let X={},$={...Z.headers};if(J.headers){if(X.headers=$,!J.cookies)delete $.cookie;if(!J.ip)BU.forEach((Y)=>{delete $[Y]})}if(X.method=Z.method,J.url)X.url=Z.url;if(J.cookies){let Y=Z.cookies||($?.cookie?of($.cookie):void 0);X.cookies=Y||{}}if(J.query_string)X.query_string=Z.query_string;if(J.data)X.data=Z.data;return X}function rf(Z){EJ("console",Z),IJ("console",VN0)}function VN0(){if(!("console"in Q0))return;p$.forEach(function(Z){if(!(Z in Q0.console))return;OB(Q0.console,Z,function(J){return PJ[Z]=J,function(...X){yJ("console",{args:X,level:Z}),PJ[Z]?.apply(Q0.console,X)}})})}function sf(Z){return Z==="warn"?"warning":["fatal","error","warning","log","info","debug"].includes(Z)?Z:"log"}var FN0=/^(\S+:\\|\/?)([\s\S]*?)((?:\.{1,2}|[^/\\]+?|)(\.[^./\\]*|))(?:[/\\]*)$/;function BN0(Z){let J=Z.length>1024?`<truncated>${Z.slice(-1024)}`:Z,X=FN0.exec(J);return X?X.slice(1):[]}function UU(Z){let J=BN0(Z),X=J[0]||"",$=J[1];if(!X&&!$)return".";if($)$=$.slice(0,$.length-1);return X+$}var UN0="Console",sJ=S((Z={})=>{let J=new Set(Z.levels||p$);return{name:UN0,setup(X){rf(({args:$,level:Y})=>{if(u()!==X||!J.has(Y))return;LN0(Y,$)})}}});function LN0(Z,J){let X={category:"console",data:{arguments:J,logger:"console"},level:sf(Z),message:tf(J)};if(Z==="assert")if(J[0]===!1){let $=J.slice(1);X.message=$.length>0?`Assertion failed: ${tf($)}`:"Assertion failed",X.data.arguments=$}else return;g6(X,{input:J,level:Z})}function tf(Z){return"util"in Q0&&typeof Q0.util.format==="function"?Q0.util.format(...Z):AB(Z," ")}var ef="gen_ai.prompt",a9="gen_ai.system",C1="gen_ai.request.model",tJ="gen_ai.request.stream",r9="gen_ai.request.temperature",eJ="gen_ai.request.max_tokens",s9="gen_ai.request.frequency_penalty",ZX="gen_ai.request.presence_penalty",t9="gen_ai.request.top_p",ZK="gen_ai.request.top_k",Zb="gen_ai.request.encoding_format",Jb="gen_ai.request.dimensions",e4="gen_ai.response.finish_reasons",p1="gen_ai.response.model",m6="gen_ai.response.id",Xb="gen_ai.response.stop_reason",D1="gen_ai.usage.input_tokens",b1="gen_ai.usage.output_tokens",O6="gen_ai.usage.total_tokens",w4="gen_ai.operation.name",Z6="gen_ai.request.messages.original_length",G4="gen_ai.request.messages",g1="gen_ai.response.text",e9="gen_ai.request.available_tools",wZ="gen_ai.response.streaming",t1="gen_ai.response.tool_calls",LU="gen_ai.agent.name",$b="gen_ai.pipeline.name",LY="gen_ai.conversation.id",Yb="gen_ai.usage.cache_creation_input_tokens",Qb="gen_ai.usage.cache_read_input_tokens",DU="gen_ai.usage.input_tokens.cache_write",Z7="gen_ai.usage.input_tokens.cached",JK="gen_ai.invoke_agent",Wb="gen_ai.generate_text",Kb="gen_ai.stream_text",zb="gen_ai.generate_object",Gb="gen_ai.stream_object",Hb="gen_ai.embed",Vb="gen_ai.embed_many",Fb="gen_ai.execute_tool",_U="openai.response.id",OU="openai.response.model",wU="openai.response.timestamp",Bb="openai.usage.completion_tokens",Ub="openai.usage.prompt_tokens",DY={CHAT:"chat",RESPONSES:"responses",EMBEDDINGS:"embeddings",CONVERSATIONS:"conversations"},jU="anthropic.response.timestamp";var _Y=new Map;var $K=(Z)=>{return new TextEncoder().encode(Z).length},YK=(Z)=>{return $K(JSON.stringify(Z))};function AU(Z,J){if($K(Z)<=J)return Z;let X=0,$=Z.length,Y="";while(X<=$){let Q=Math.floor((X+$)/2),W=Z.slice(0,Q);if($K(W)<=J)Y=W,X=Q+1;else $=Q-1}return Y}function DN0(Z){if(typeof Z==="string")return Z;if("text"in Z)return Z.text;return""}function Lb(Z,J){if(typeof Z==="string")return J;return{...Z,text:J}}function _N0(Z){return Z!==null&&typeof Z==="object"&&"content"in Z&&typeof Z.content==="string"}function ON0(Z){return Z!==null&&typeof Z==="object"&&"content"in Z&&Array.isArray(Z.content)}function OY(Z){if(!Z||typeof Z!=="object")return!1;return wN0(Z)||_b(Z)||"media_type"in Z&&typeof Z.media_type==="string"&&"data"in Z||"image_url"in Z&&typeof Z.image_url==="string"&&Z.image_url.startsWith("data:")||"type"in Z&&(Z.type==="blob"||Z.type==="base64")||"b64_json"in Z||"type"in Z&&"result"in Z&&Z.type==="image_generation"||"uri"in Z&&typeof Z.uri==="string"&&Z.uri.startsWith("data:")}function wN0(Z){return"type"in Z&&typeof Z.type==="string"&&"source"in Z&&OY(Z.source)}function _b(Z){return"inlineData"in Z&&!!Z.inlineData&&typeof Z.inlineData==="object"&&"data"in Z.inlineData&&typeof Z.inlineData.data==="string"}function Ob(Z){return Z!==null&&typeof Z==="object"&&"parts"in Z&&Array.isArray(Z.parts)&&Z.parts.length>0}function jN0(Z,J){let X={...Z,content:""},$=YK(X),Y=J-$;if(Y<=0)return[];let Q=AU(Z.content,Y);return[{...Z,content:Q}]}function MN0(Z,J){let{parts:X}=Z,$=X.map((K)=>Lb(K,"")),Y=YK({...Z,parts:$}),Q=J-Y;if(Q<=0)return[];let W=[];for(let K of X){let z=DN0(K),G=$K(z);if(G<=Q)W.push(K),Q-=G;else if(W.length===0){let H=AU(z,Q);if(H)W.push(Lb(K,H));break}else break}if(W.length<=0)return[];else return[{...Z,parts:W}]}function AN0(Z,J){if(!Z||typeof Z!=="object")return[];if(_N0(Z))return jN0(Z,J);if(Ob(Z))return MN0(Z,J);return[]}var Db="[Filtered]",TN0=["image_url","data","content","b64_json","result","uri"];function XK(Z){let J={...Z};if(OY(J.source))J.source=XK(J.source);if(_b(Z))J.inlineData={...Z.inlineData,data:Db};for(let X of TN0)if(typeof J[X]==="string")J[X]=Db;return J}function MU(Z){return Z.map((X)=>{let $=void 0;if(!!X&&typeof X==="object"){if(ON0(X))$={...X,content:MU(X.content)};else if("content"in X&&OY(X.content))$={...X,content:XK(X.content)};if(Ob(X))$={...$??X,parts:MU(X.parts)};if(OY($))$=XK($);else if(OY(X))$=XK(X)}return $??X})}function qN0(Z,J){if(!Array.isArray(Z)||Z.length===0)return Z;let X=MU(Z);if(YK(X)<=J)return X;let Y=X.map(YK),Q=0,W=X.length;for(let K=X.length-1;K>=0;K--){let z=Y[K];if(z&&Q+z>J)break;if(z)Q+=z;W=K}if(W===X.length){let K=X[X.length-1];return AN0(K,J)}return X.slice(W)}function J7(Z){return qN0(Z,20000)}function wb(Z){return AU(Z,20000)}function jZ(Z){if(Z.includes("messages"))return"messages";if(Z.includes("completions"))return"completions";if(Z.includes("models"))return"models";if(Z.includes("chat"))return"chat";return Z.split(".").pop()||"unknown"}function JX(Z){return`gen_ai.${jZ(Z)}`}function QK(Z,J){return Z?`${Z}.${J}`:J}function wY(Z,J,X,$,Y){if(J!==void 0)Z.setAttributes({[D1]:J});if(X!==void 0)Z.setAttributes({[b1]:X});if(J!==void 0||X!==void 0||$!==void 0||Y!==void 0){let Q=(J??0)+(X??0)+($??0)+(Y??0);Z.setAttributes({[O6]:Q})}}function X7(Z){if(typeof Z==="string")return wb(Z);if(Array.isArray(Z)){let J=J7(Z);return JSON.stringify(J)}return JSON.stringify(Z)}var jb="operation.name",WK="ai.prompt",Mb="ai.schema",Ab="ai.response.object",Tb="ai.response.text",qb="ai.response.toolCalls",MZ="ai.prompt.messages",XX="ai.prompt.tools",jY="ai.model.id",Cb="ai.response.providerMetadata",Nb="ai.usage.cachedInputTokens",Rb="ai.telemetry.functionId",Pb="ai.usage.completionTokens",Eb="ai.usage.promptTokens",TU="ai.toolCall.name",qU="ai.toolCall.id",Ib="ai.toolCall.args",yb="ai.toolCall.result";function Sb(Z,J){let X=Z.parent_span_id;if(!X)return;let $=Z.data[D1],Y=Z.data[b1];if(typeof $==="number"||typeof Y==="number"){let Q=J.get(X)||{inputTokens:0,outputTokens:0};if(typeof $==="number")Q.inputTokens+=$;if(typeof Y==="number")Q.outputTokens+=Y;J.set(X,Q)}}function CU(Z,J){let X=J.get(Z.span_id);if(!X||!Z.data)return;if(X.inputTokens>0)Z.data[D1]=X.inputTokens;if(X.outputTokens>0)Z.data[b1]=X.outputTokens;if(X.inputTokens>0||X.outputTokens>0)Z.data["gen_ai.usage.total_tokens"]=X.inputTokens+X.outputTokens}function NU(Z){return _Y.get(Z)}function RU(Z){_Y.delete(Z)}function kb(Z){let J=Z.map((X)=>{if(typeof X==="string")try{return JSON.parse(X)}catch{return X}return X});return JSON.stringify(J)}function CN0(Z){try{let J=JSON.parse(Z);if(!!J&&typeof J==="object"){let{prompt:X,system:$}=J;if(typeof X==="string"||typeof $==="string"){let Y=[];if(typeof $==="string")Y.push({role:"system",content:$});if(typeof X==="string")Y.push({role:"user",content:X});return Y}}}catch{}return[]}function xb(Z,J){if(J[WK]){let $=X7(J[WK]);Z.setAttribute("gen_ai.prompt",$)}let X=J[WK];if(typeof X==="string"&&!J[G4]&&!J[MZ]){let $=CN0(X);if($.length)Z.setAttributes({[G4]:X7($),[Z6]:$.length})}else if(typeof J[MZ]==="string")try{let $=JSON.parse(J[MZ]);if(Array.isArray($))Z.setAttributes({[MZ]:void 0,[G4]:X7($),[Z6]:$.length})}catch{}}function vb(Z){switch(Z){case"ai.generateText":case"ai.streamText":case"ai.generateObject":case"ai.streamObject":case"ai.embed":case"ai.embedMany":return JK;case"ai.generateText.doGenerate":return Wb;case"ai.streamText.doStream":return Kb;case"ai.generateObject.doGenerate":return zb;case"ai.streamObject.doStream":return Gb;case"ai.embed.doEmbed":return Hb;case"ai.embedMany.doEmbed":return Vb;case"ai.toolCall":return Fb;default:if(Z.startsWith("ai.stream"))return"ai.run";return}}function hb(Z,J){Z.setAttribute(X0,J)}function NN0(Z){let{data:J,description:X}=J0(Z);if(!X)return;if(J[TU]&&J[qU]&&X==="ai.toolCall"){EN0(Z,J);return}if(!X.startsWith("ai."))return;IN0(Z,X,J)}function RN0(Z){if(Z.type==="transaction"&&Z.spans){let J=new Map;for(let $ of Z.spans)PN0($),Sb($,J);for(let $ of Z.spans){if($.op!=="gen_ai.invoke_agent")continue;CU($,J)}let X=Z.contexts?.trace;if(X&&X.op==="gen_ai.invoke_agent")CU(X,J)}return Z}function PN0(Z){let{data:J,origin:X}=Z;if(X!=="auto.vercelai.otel")return;if(j4(J,Pb,b1),j4(J,Eb,D1),j4(J,Nb,Z7),typeof J[D1]==="number"&&typeof J[Z7]==="number")J[D1]=J[D1]+J[Z7];if(typeof J[b1]==="number"&&typeof J[D1]==="number")J["gen_ai.usage.total_tokens"]=J[b1]+J[D1];if(J[XX]&&Array.isArray(J[XX]))J[XX]=kb(J[XX]);j4(J,jb,w4),j4(J,MZ,G4),j4(J,Tb,"gen_ai.response.text"),j4(J,qb,"gen_ai.response.tool_calls"),j4(J,Ab,"gen_ai.response.object"),j4(J,XX,"gen_ai.request.available_tools"),j4(J,Ib,"gen_ai.tool.input"),j4(J,yb,"gen_ai.tool.output"),j4(J,Mb,"gen_ai.request.schema"),j4(J,jY,C1),yN0(J);for(let $ of Object.keys(J))if($.startsWith("ai."))j4(J,$,`vercel.${$}`)}function j4(Z,J,X){if(Z[J]!=null)Z[X]=Z[J],delete Z[J]}function EN0(Z,J){hb(Z,"auto.vercelai.otel"),Z.setAttribute(K0,"gen_ai.execute_tool"),j4(J,TU,"gen_ai.tool.name"),j4(J,qU,"gen_ai.tool.call.id");let X=J["gen_ai.tool.call.id"];if(typeof X==="string")_Y.set(X,Z);if(!J["gen_ai.tool.type"])Z.setAttribute("gen_ai.tool.type","function");let $=J["gen_ai.tool.name"];if($)Z.updateName(`execute_tool ${$}`)}function IN0(Z,J,X){hb(Z,"auto.vercelai.otel");let $=J.replace("ai.","");Z.setAttribute("ai.pipeline.name",$),Z.updateName($);let Y=X[Rb];if(Y&&typeof Y==="string")Z.updateName(`${$} ${Y}`),Z.setAttribute("gen_ai.function_id",Y);if(xb(Z,X),X[jY]&&!X[p1])Z.setAttribute(p1,X[jY]);Z.setAttribute("ai.streaming",J.includes("stream"));let Q=vb(J);if(Q)Z.setAttribute(K0,Q);let W=X[jY];if(W)switch(J){case"ai.generateText.doGenerate":Z.updateName(`generate_text ${W}`);break;case"ai.streamText.doStream":Z.updateName(`stream_text ${W}`);break;case"ai.generateObject.doGenerate":Z.updateName(`generate_object ${W}`);break;case"ai.streamObject.doStream":Z.updateName(`stream_object ${W}`);break;case"ai.embed.doEmbed":Z.updateName(`embed ${W}`);break;case"ai.embedMany.doEmbed":Z.updateName(`embed_many ${W}`);break}}function KK(Z){Z.on("spanStart",NN0),Z.addEventProcessor(Object.assign(RN0,{id:"VercelAiEventProcessor"}))}function yN0(Z){let J=Z[Cb];if(J)try{let X=JSON.parse(J),$=X.openai??X.azure;if($)N8(Z,Z7,$.cachedPromptTokens),N8(Z,"gen_ai.usage.output_tokens.reasoning",$.reasoningTokens),N8(Z,"gen_ai.usage.output_tokens.prediction_accepted",$.acceptedPredictionTokens),N8(Z,"gen_ai.usage.output_tokens.prediction_rejected",$.rejectedPredictionTokens),N8(Z,"gen_ai.conversation.id",$.responseId);if(X.anthropic){let Y=X.anthropic.usage?.cache_read_input_tokens??X.anthropic.cacheReadInputTokens;N8(Z,Z7,Y);let Q=X.anthropic.usage?.cache_creation_input_tokens??X.anthropic.cacheCreationInputTokens;N8(Z,DU,Q)}if(X.bedrock?.usage)N8(Z,Z7,X.bedrock.usage.cacheReadInputTokens),N8(Z,DU,X.bedrock.usage.cacheWriteInputTokens);if(X.deepseek)N8(Z,Z7,X.deepseek.promptCacheHitTokens),N8(Z,"gen_ai.usage.input_tokens.cache_miss",X.deepseek.promptCacheMissTokens)}catch{}}function N8(Z,J,X){if(X!=null)Z[J]=X}var $7="OpenAI",fb=["responses.create","chat.completions.create","embeddings.create","conversations.create"],SN0=["response.output_item.added","response.function_call_arguments.delta","response.function_call_arguments.done","response.output_item.done"],bb=["response.created","response.in_progress","response.failed","response.completed","response.incomplete","response.queued","response.output_text.delta",...SN0];function zK(Z){if(Z.includes("chat.completions"))return DY.CHAT;if(Z.includes("responses"))return DY.RESPONSES;if(Z.includes("embeddings"))return DY.EMBEDDINGS;if(Z.includes("conversations"))return DY.CONVERSATIONS;return Z.split(".").pop()||"unknown"}function PU(Z){return`gen_ai.${zK(Z)}`}function gb(Z){return fb.includes(Z)}function mb(Z,J){return Z?`${Z}.${J}`:J}function db(Z){return Z!==null&&typeof Z==="object"&&"object"in Z&&Z.object==="chat.completion"}function ub(Z){return Z!==null&&typeof Z==="object"&&"object"in Z&&Z.object==="response"}function cb(Z){if(Z===null||typeof Z!=="object"||!("object"in Z))return!1;let J=Z;return J.object==="list"&&typeof J.model==="string"&&J.model.toLowerCase().includes("embedding")}function lb(Z){return Z!==null&&typeof Z==="object"&&"object"in Z&&Z.object==="conversation"}function pb(Z){return Z!==null&&typeof Z==="object"&&"type"in Z&&typeof Z.type==="string"&&Z.type.startsWith("response.")}function ib(Z){return Z!==null&&typeof Z==="object"&&"object"in Z&&Z.object==="chat.completion.chunk"}function nb(Z,J,X){if(GK(Z,J.id,J.model,J.created),J.usage)MY(Z,J.usage.prompt_tokens,J.usage.completion_tokens,J.usage.total_tokens);if(Array.isArray(J.choices)){let $=J.choices.map((Y)=>Y.finish_reason).filter((Y)=>Y!==null);if($.length>0)Z.setAttributes({[e4]:JSON.stringify($)});if(X){let Y=J.choices.map((Q)=>Q.message?.tool_calls).filter((Q)=>Array.isArray(Q)&&Q.length>0).flat();if(Y.length>0)Z.setAttributes({[t1]:JSON.stringify(Y)})}}}function ob(Z,J,X){if(GK(Z,J.id,J.model,J.created_at),J.status)Z.setAttributes({[e4]:JSON.stringify([J.status])});if(J.usage)MY(Z,J.usage.input_tokens,J.usage.output_tokens,J.usage.total_tokens);if(X){let $=J;if(Array.isArray($.output)&&$.output.length>0){let Y=$.output.filter((Q)=>typeof Q==="object"&&Q!==null&&Q.type==="function_call");if(Y.length>0)Z.setAttributes({[t1]:JSON.stringify(Y)})}}}function ab(Z,J){if(Z.setAttributes({[OU]:J.model,[p1]:J.model}),J.usage)MY(Z,J.usage.prompt_tokens,void 0,J.usage.total_tokens)}function rb(Z,J){let{id:X,created_at:$}=J;if(Z.setAttributes({[_U]:X,[m6]:X,[LY]:X}),$)Z.setAttributes({[wU]:new Date($*1000).toISOString()})}function MY(Z,J,X,$){if(J!==void 0)Z.setAttributes({[Ub]:J,[D1]:J});if(X!==void 0)Z.setAttributes({[Bb]:X,[b1]:X});if($!==void 0)Z.setAttributes({[O6]:$})}function GK(Z,J,X,$){Z.setAttributes({[_U]:J,[m6]:J}),Z.setAttributes({[OU]:X,[p1]:X}),Z.setAttributes({[wU]:new Date($*1000).toISOString()})}function kN0(Z){if("conversation"in Z&&typeof Z.conversation==="string")return Z.conversation;if("previous_response_id"in Z&&typeof Z.previous_response_id==="string")return Z.previous_response_id;return}function sb(Z){let J={[C1]:Z.model??"unknown"};if("temperature"in Z)J[r9]=Z.temperature;if("top_p"in Z)J[t9]=Z.top_p;if("frequency_penalty"in Z)J[s9]=Z.frequency_penalty;if("presence_penalty"in Z)J[ZX]=Z.presence_penalty;if("stream"in Z)J[tJ]=Z.stream;if("encoding_format"in Z)J[Zb]=Z.encoding_format;if("dimensions"in Z)J[Jb]=Z.dimensions;let X=kN0(Z);if(X)J[LY]=X;return J}function xN0(Z,J){for(let X of Z){let $=X.index;if($===void 0||!X.function)continue;if(!($ in J.chatCompletionToolCalls))J.chatCompletionToolCalls[$]={...X,function:{name:X.function.name,arguments:X.function.arguments||""}};else{let Y=J.chatCompletionToolCalls[$];if(X.function.arguments&&Y?.function)Y.function.arguments+=X.function.arguments}}}function vN0(Z,J,X){if(J.responseId=Z.id??J.responseId,J.responseModel=Z.model??J.responseModel,J.responseTimestamp=Z.created??J.responseTimestamp,Z.usage)J.promptTokens=Z.usage.prompt_tokens,J.completionTokens=Z.usage.completion_tokens,J.totalTokens=Z.usage.total_tokens;for(let $ of Z.choices??[]){if(X){if($.delta?.content)J.responseTexts.push($.delta.content);if($.delta?.tool_calls)xN0($.delta.tool_calls,J)}if($.finish_reason)J.finishReasons.push($.finish_reason)}}function hN0(Z,J,X,$){if(!(Z&&typeof Z==="object")){J.eventTypes.push("unknown:non-object");return}if(Z instanceof Error){$.setStatus({code:A0,message:"internal_error"}),V0(Z,{mechanism:{handled:!1,type:"auto.ai.openai.stream-response"}});return}if(!("type"in Z))return;let Y=Z;if(!bb.includes(Y.type)){J.eventTypes.push(Y.type);return}if(X){if(Y.type==="response.output_item.done"&&"item"in Y)J.responsesApiToolCalls.push(Y.item);if(Y.type==="response.output_text.delta"&&"delta"in Y&&Y.delta){J.responseTexts.push(Y.delta);return}}if("response"in Y){let{response:Q}=Y;if(J.responseId=Q.id??J.responseId,J.responseModel=Q.model??J.responseModel,J.responseTimestamp=Q.created_at??J.responseTimestamp,Q.usage)J.promptTokens=Q.usage.input_tokens,J.completionTokens=Q.usage.output_tokens,J.totalTokens=Q.usage.total_tokens;if(Q.status)J.finishReasons.push(Q.status);if(X&&Q.output_text)J.responseTexts.push(Q.output_text)}}async function*tb(Z,J,X){let $={eventTypes:[],responseTexts:[],finishReasons:[],responseId:"",responseModel:"",responseTimestamp:0,promptTokens:void 0,completionTokens:void 0,totalTokens:void 0,chatCompletionToolCalls:{},responsesApiToolCalls:[]};try{for await(let Y of Z){if(ib(Y))vN0(Y,$,X);else if(pb(Y))hN0(Y,$,X,J);yield Y}}finally{if(GK(J,$.responseId,$.responseModel,$.responseTimestamp),MY(J,$.promptTokens,$.completionTokens,$.totalTokens),J.setAttributes({[wZ]:!0}),$.finishReasons.length)J.setAttributes({[e4]:JSON.stringify($.finishReasons)});if(X&&$.responseTexts.length)J.setAttributes({[g1]:$.responseTexts.join("")});let Q=[...Object.values($.chatCompletionToolCalls),...$.responsesApiToolCalls];if(Q.length>0)J.setAttributes({[t1]:JSON.stringify(Q)});J.end()}}function fN0(Z){let J=Array.isArray(Z.tools)?Z.tools:[],$=Z.web_search_options&&typeof Z.web_search_options==="object"?[{type:"web_search_options",...Z.web_search_options}]:[],Y=[...J,...$];return Y.length>0?JSON.stringify(Y):void 0}function bN0(Z,J){let X={[a9]:"openai",[w4]:zK(J),[X0]:"auto.ai.openai"};if(Z.length>0&&typeof Z[0]==="object"&&Z[0]!==null){let $=Z[0],Y=fN0($);if(Y)X[e9]=Y;Object.assign(X,sb($))}else X[C1]="unknown";return X}function gN0(Z,J,X){if(!J||typeof J!=="object")return;let $=J;if(db($)){if(nb(Z,$,X),X&&$.choices?.length){let Y=$.choices.map((Q)=>Q.message?.content||"");Z.setAttributes({[g1]:JSON.stringify(Y)})}}else if(ub($)){if(ob(Z,$,X),X&&$.output_text)Z.setAttributes({[g1]:$.output_text})}else if(cb($))ab(Z,$);else if(lb($))rb(Z,$)}function eb(Z,J){let X="input"in J?J.input:("messages"in J)?J.messages:void 0,$=Array.isArray(X)?X.length:void 0;if(X&&$!==0){let Y=X7(X);if(Z.setAttribute(G4,Y),$)Z.setAttribute(Z6,$)}}function mN0(Z,J,X,$){return async function(...Q){let W=bN0(Q,J),K=W[C1]||"unknown",z=zK(J),G=Q[0];if(G&&typeof G==="object"&&G.stream===!0)return z4({name:`${z} ${K} stream-response`,op:PU(J),attributes:W},async(V)=>{try{if($.recordInputs&&G)eb(V,G);let F=await Z.apply(X,Q);return tb(F,V,$.recordOutputs??!1)}catch(F){throw V.setStatus({code:A0,message:"internal_error"}),V0(F,{mechanism:{handled:!1,type:"auto.ai.openai.stream",data:{function:J}}}),V.end(),F}});else return _6({name:`${z} ${K}`,op:PU(J),attributes:W},async(V)=>{try{if($.recordInputs&&G)eb(V,G);let F=await Z.apply(X,Q);return gN0(V,F,$.recordOutputs),F}catch(F){throw V0(F,{mechanism:{handled:!1,type:"auto.ai.openai",data:{function:J}}}),F}})}}function Zg(Z,J="",X){return new Proxy(Z,{get($,Y){let Q=$[Y],W=mb(J,String(Y));if(typeof Q==="function"&&gb(W))return mN0(Q,W,$,X);if(typeof Q==="function")return Q.bind($);if(Q&&typeof Q==="object")return Zg(Q,W,X);return Q}})}function HK(Z,J){let X=Boolean(u()?.getOptions().sendDefaultPii),$={recordInputs:X,recordOutputs:X,...J};return Zg(Z,"",$)}function dN0(Z,J){if("type"in Z&&typeof Z.type==="string"){if(Z.type==="error")return J.setStatus({code:A0,message:Z.error?.type??"internal_error"}),V0(Z.error,{mechanism:{handled:!1,type:"auto.ai.anthropic.anthropic_error"}}),!0}return!1}function uN0(Z,J){if(Z.type==="message_delta"&&Z.usage){if("output_tokens"in Z.usage&&typeof Z.usage.output_tokens==="number")J.completionTokens=Z.usage.output_tokens}if(Z.message){let X=Z.message;if(X.id)J.responseId=X.id;if(X.model)J.responseModel=X.model;if(X.stop_reason)J.finishReasons.push(X.stop_reason);if(X.usage){if(typeof X.usage.input_tokens==="number")J.promptTokens=X.usage.input_tokens;if(typeof X.usage.cache_creation_input_tokens==="number")J.cacheCreationInputTokens=X.usage.cache_creation_input_tokens;if(typeof X.usage.cache_read_input_tokens==="number")J.cacheReadInputTokens=X.usage.cache_read_input_tokens}}}function cN0(Z,J){if(Z.type!=="content_block_start"||typeof Z.index!=="number"||!Z.content_block)return;if(Z.content_block.type==="tool_use"||Z.content_block.type==="server_tool_use")J.activeToolBlocks[Z.index]={id:Z.content_block.id,name:Z.content_block.name,inputJsonParts:[]}}function lN0(Z,J,X){if(Z.type!=="content_block_delta"||!Z.delta)return;if(typeof Z.index==="number"&&"partial_json"in Z.delta&&typeof Z.delta.partial_json==="string"){let $=J.activeToolBlocks[Z.index];if($)$.inputJsonParts.push(Z.delta.partial_json)}if(X&&typeof Z.delta.text==="string")J.responseTexts.push(Z.delta.text)}function pN0(Z,J){if(Z.type!=="content_block_stop"||typeof Z.index!=="number")return;let X=J.activeToolBlocks[Z.index];if(!X)return;let $=X.inputJsonParts.join(""),Y;try{Y=$?JSON.parse($):{}}catch{Y={__unparsed:$}}J.toolCalls.push({type:"tool_use",id:X.id,name:X.name,input:Y}),delete J.activeToolBlocks[Z.index]}function Jg(Z,J,X,$){if(!(Z&&typeof Z==="object"))return;if(dN0(Z,$))return;uN0(Z,J),cN0(Z,J),lN0(Z,J,X),pN0(Z,J)}function iN0(Z,J,X){if(!J.isRecording())return;if(Z.responseId)J.setAttributes({[m6]:Z.responseId});if(Z.responseModel)J.setAttributes({[p1]:Z.responseModel});if(wY(J,Z.promptTokens,Z.completionTokens,Z.cacheCreationInputTokens,Z.cacheReadInputTokens),J.setAttributes({[wZ]:!0}),Z.finishReasons.length>0)J.setAttributes({[e4]:JSON.stringify(Z.finishReasons)});if(X&&Z.responseTexts.length>0)J.setAttributes({[g1]:Z.responseTexts.join("")});if(X&&Z.toolCalls.length>0)J.setAttributes({[t1]:JSON.stringify(Z.toolCalls)});J.end()}async function*Xg(Z,J,X){let $={responseTexts:[],finishReasons:[],responseId:"",responseModel:"",promptTokens:void 0,completionTokens:void 0,cacheCreationInputTokens:void 0,cacheReadInputTokens:void 0,toolCalls:[],activeToolBlocks:{}};try{for await(let Y of Z)Jg(Y,$,X,J),yield Y}finally{if($.responseId)J.setAttributes({[m6]:$.responseId});if($.responseModel)J.setAttributes({[p1]:$.responseModel});if(wY(J,$.promptTokens,$.completionTokens,$.cacheCreationInputTokens,$.cacheReadInputTokens),J.setAttributes({[wZ]:!0}),$.finishReasons.length>0)J.setAttributes({[e4]:JSON.stringify($.finishReasons)});if(X&&$.responseTexts.length>0)J.setAttributes({[g1]:$.responseTexts.join("")});if(X&&$.toolCalls.length>0)J.setAttributes({[t1]:JSON.stringify($.toolCalls)});J.end()}}function $g(Z,J,X){let $={responseTexts:[],finishReasons:[],responseId:"",responseModel:"",promptTokens:void 0,completionTokens:void 0,cacheCreationInputTokens:void 0,cacheReadInputTokens:void 0,toolCalls:[],activeToolBlocks:{}};return Z.on("streamEvent",(Y)=>{Jg(Y,$,X,J)}),Z.on("message",()=>{iN0($,J,X)}),Z.on("error",(Y)=>{if(V0(Y,{mechanism:{handled:!1,type:"auto.ai.anthropic.stream_error"}}),J.isRecording())J.setStatus({code:A0,message:"stream_error"}),J.end()}),Z}var Y7="Anthropic_AI",Yg=["messages.create","messages.stream","messages.countTokens","models.get","completions.create","models.retrieve","beta.messages.create"];function Qg(Z){return Yg.includes(Z)}function Wg(Z,J){let X=Array.isArray(J)?J.length:void 0;if(X!==0)Z.setAttributes({[G4]:X7(J),[Z6]:X})}function Kg(Z,J){if(J.error)Z.setStatus({code:A0,message:J.error.type||"internal_error"}),V0(J.error,{mechanism:{handled:!1,type:"auto.ai.anthropic.anthropic_error"}})}function zg(Z){let{system:J,messages:X,input:$}=Z,Y=typeof J==="string"?[{role:"system",content:Z.system}]:[],Q=Array.isArray($)?$:$!=null?[$]:void 0,W=Array.isArray(X)?X:X!=null?[X]:[],K=Q??W;return[...Y,...K]}function nN0(Z,J){let X={[a9]:"anthropic",[w4]:jZ(J),[X0]:"auto.ai.anthropic"};if(Z.length>0&&typeof Z[0]==="object"&&Z[0]!==null){let $=Z[0];if($.tools&&Array.isArray($.tools))X[e9]=JSON.stringify($.tools);if(X[C1]=$.model??"unknown","temperature"in $)X[r9]=$.temperature;if("top_p"in $)X[t9]=$.top_p;if("stream"in $)X[tJ]=$.stream;if("top_k"in $)X[ZK]=$.top_k;if("frequency_penalty"in $)X[s9]=$.frequency_penalty;if("max_tokens"in $)X[eJ]=$.max_tokens}else if(J==="models.retrieve"||J==="models.get")X[C1]=Z[0];else X[C1]="unknown";return X}function EU(Z,J){let X=zg(J);if(Wg(Z,X),"prompt"in J)Z.setAttributes({[ef]:JSON.stringify(J.prompt)})}function oN0(Z,J){if("content"in J){if(Array.isArray(J.content)){Z.setAttributes({[g1]:J.content.map(($)=>$.text).filter(($)=>!!$).join("")});let X=[];for(let $ of J.content)if($.type==="tool_use"||$.type==="server_tool_use")X.push($);if(X.length>0)Z.setAttributes({[t1]:JSON.stringify(X)})}}if("completion"in J)Z.setAttributes({[g1]:J.completion});if("input_tokens"in J)Z.setAttributes({[g1]:JSON.stringify(J.input_tokens)})}function aN0(Z,J){if("id"in J&&"model"in J){if(Z.setAttributes({[m6]:J.id,[p1]:J.model}),"created"in J&&typeof J.created==="number")Z.setAttributes({[jU]:new Date(J.created*1000).toISOString()});if("created_at"in J&&typeof J.created_at==="number")Z.setAttributes({[jU]:new Date(J.created_at*1000).toISOString()});if("usage"in J&&J.usage)wY(Z,J.usage.input_tokens,J.usage.output_tokens,J.usage.cache_creation_input_tokens,J.usage.cache_read_input_tokens)}}function rN0(Z,J,X){if(!J||typeof J!=="object")return;if("type"in J&&J.type==="error"){Kg(Z,J);return}if(X)oN0(Z,J);aN0(Z,J)}function Gg(Z,J,X){if(V0(Z,{mechanism:{handled:!1,type:"auto.ai.anthropic",data:{function:X}}}),J.isRecording())J.setStatus({code:A0,message:"internal_error"}),J.end();throw Z}function sN0(Z,J,X,$,Y,Q,W,K,z,G,H){let V=Y[C1]??"unknown",F={name:`${Q} ${V} stream-response`,op:JX(W),attributes:Y};if(G&&!H)return z4(F,async(B)=>{try{if(z.recordInputs&&K)EU(B,K);let U=await Z.apply(X,$);return Xg(U,B,z.recordOutputs??!1)}catch(U){return Gg(U,B,W)}});else return z4(F,(B)=>{try{if(z.recordInputs&&K)EU(B,K);let U=J.apply(X,$);return $g(U,B,z.recordOutputs??!1)}catch(U){return Gg(U,B,W)}})}function tN0(Z,J,X,$){return new Proxy(Z,{apply(Y,Q,W){let K=nN0(W,J),z=K[C1]??"unknown",G=jZ(J),H=typeof W[0]==="object"?W[0]:void 0,V=Boolean(H?.stream),F=J==="messages.stream";if(V||F)return sN0(Z,Y,X,W,K,G,J,H,$,V,F);return _6({name:`${G} ${z}`,op:JX(J),attributes:K},(B)=>{if($.recordInputs&&H)EU(B,H);return D6(()=>Y.apply(X,W),(U)=>{V0(U,{mechanism:{handled:!1,type:"auto.ai.anthropic",data:{function:J}}})},()=>{},(U)=>rN0(B,U,$.recordOutputs))})}})}function Hg(Z,J="",X){return new Proxy(Z,{get($,Y){let Q=$[Y],W=QK(J,String(Y));if(typeof Q==="function"&&Qg(W))return tN0(Q,W,$,X);if(typeof Q==="function")return Q.bind($);if(Q&&typeof Q==="object")return Hg(Q,W,X);return Q}})}function IU(Z,J){let X=Boolean(u()?.getOptions().sendDefaultPii),$={recordInputs:X,recordOutputs:X,...J};return Hg(Z,"",$)}var Q7="Google_GenAI",yU=["models.generateContent","models.generateContentStream","chats.create","sendMessage","sendMessageStream"],Vg="google_genai",SU="chats.create",Fg="chat";function eN0(Z,J){let X=Z?.promptFeedback;if(X?.blockReason){let $=X.blockReasonMessage??X.blockReason;return J.setStatus({code:A0,message:`Content blocked: ${$}`}),V0(`Content blocked: ${$}`,{mechanism:{handled:!1,type:"auto.ai.google_genai"}}),!0}return!1}function ZR0(Z,J){if(typeof Z.responseId==="string")J.responseId=Z.responseId;if(typeof Z.modelVersion==="string")J.responseModel=Z.modelVersion;let X=Z.usageMetadata;if(X){if(typeof X.promptTokenCount==="number")J.promptTokens=X.promptTokenCount;if(typeof X.candidatesTokenCount==="number")J.completionTokens=X.candidatesTokenCount;if(typeof X.totalTokenCount==="number")J.totalTokens=X.totalTokenCount}}function JR0(Z,J,X){if(Array.isArray(Z.functionCalls))J.toolCalls.push(...Z.functionCalls);for(let $ of Z.candidates??[]){if($?.finishReason&&!J.finishReasons.includes($.finishReason))J.finishReasons.push($.finishReason);for(let Y of $?.content?.parts??[]){if(X&&Y.text)J.responseTexts.push(Y.text);if(Y.functionCall)J.toolCalls.push({type:"function",id:Y.functionCall.id,name:Y.functionCall.name,arguments:Y.functionCall.args})}}}function XR0(Z,J,X,$){if(!Z||eN0(Z,$))return;ZR0(Z,J),JR0(Z,J,X)}async function*Bg(Z,J,X){let $={responseTexts:[],finishReasons:[],toolCalls:[]};try{for await(let Y of Z)XR0(Y,$,X,J),yield Y}finally{let Y={[wZ]:!0};if($.responseId)Y[m6]=$.responseId;if($.responseModel)Y[p1]=$.responseModel;if($.promptTokens!==void 0)Y[D1]=$.promptTokens;if($.completionTokens!==void 0)Y[b1]=$.completionTokens;if($.totalTokens!==void 0)Y[O6]=$.totalTokens;if($.finishReasons.length)Y[e4]=JSON.stringify($.finishReasons);if(X&&$.responseTexts.length)Y[g1]=$.responseTexts.join("");if(X&&$.toolCalls.length)Y[t1]=JSON.stringify($.toolCalls);J.setAttributes(Y),J.end()}}function Ug(Z){if(yU.includes(Z))return!0;let J=Z.split(".").pop();return yU.includes(J)}function Lg(Z){return Z.includes("Stream")}function $X(Z,J="user"){if(typeof Z==="string")return[{role:J,content:Z}];if(Array.isArray(Z))return Z.flatMap((X)=>$X(X,J));if(typeof Z!=="object"||!Z)return[];if("role"in Z&&typeof Z.role==="string")return[Z];if("parts"in Z)return[{...Z,role:J}];return[{role:J,content:Z}]}function Dg(Z,J){if("model"in Z&&typeof Z.model==="string")return Z.model;if(J&&typeof J==="object"){let X=J;if("model"in X&&typeof X.model==="string")return X.model;if("modelVersion"in X&&typeof X.modelVersion==="string")return X.modelVersion}return"unknown"}function $R0(Z){let J={};if("temperature"in Z&&typeof Z.temperature==="number")J[r9]=Z.temperature;if("topP"in Z&&typeof Z.topP==="number")J[t9]=Z.topP;if("topK"in Z&&typeof Z.topK==="number")J[ZK]=Z.topK;if("maxOutputTokens"in Z&&typeof Z.maxOutputTokens==="number")J[eJ]=Z.maxOutputTokens;if("frequencyPenalty"in Z&&typeof Z.frequencyPenalty==="number")J[s9]=Z.frequencyPenalty;if("presencePenalty"in Z&&typeof Z.presencePenalty==="number")J[ZX]=Z.presencePenalty;return J}function YR0(Z,J,X){let $={[a9]:Vg,[w4]:jZ(Z),[X0]:"auto.ai.google_genai"};if(J){if($[C1]=Dg(J,X),"config"in J&&typeof J.config==="object"&&J.config){let Y=J.config;if(Object.assign($,$R0(Y)),"tools"in Y&&Array.isArray(Y.tools)){let Q=Y.tools.flatMap((W)=>W.functionDeclarations);$[e9]=JSON.stringify(Q)}}}else $[C1]=Dg({},X);return $}function _g(Z,J){let X=[];if("config"in J&&J.config&&typeof J.config==="object"&&"systemInstruction"in J.config&&J.config.systemInstruction)X.push(...$X(J.config.systemInstruction,"system"));if("history"in J)X.push(...$X(J.history,"user"));if("contents"in J)X.push(...$X(J.contents,"user"));if("message"in J)X.push(...$X(J.message,"user"));if(Array.isArray(X)&&X.length)Z.setAttributes({[Z6]:X.length,[G4]:JSON.stringify(J7(X))})}function QR0(Z,J,X){if(!J||typeof J!=="object")return;if(J.modelVersion)Z.setAttribute(p1,J.modelVersion);if(J.usageMetadata&&typeof J.usageMetadata==="object"){let $=J.usageMetadata;if(typeof $.promptTokenCount==="number")Z.setAttributes({[D1]:$.promptTokenCount});if(typeof $.candidatesTokenCount==="number")Z.setAttributes({[b1]:$.candidatesTokenCount});if(typeof $.totalTokenCount==="number")Z.setAttributes({[O6]:$.totalTokenCount})}if(X&&Array.isArray(J.candidates)&&J.candidates.length>0){let $=J.candidates.map((Y)=>{if(Y.content?.parts&&Array.isArray(Y.content.parts))return Y.content.parts.map((Q)=>typeof Q.text==="string"?Q.text:"").filter((Q)=>Q.length>0).join("");return""}).filter((Y)=>Y.length>0);if($.length>0)Z.setAttributes({[g1]:$.join("")})}if(X&&J.functionCalls){let $=J.functionCalls;if(Array.isArray($)&&$.length>0)Z.setAttributes({[t1]:JSON.stringify($)})}}function Og(Z,J,X,$){let Y=J===SU;return new Proxy(Z,{apply(Q,W,K){let z=K[0],G=YR0(J,z,X),H=G[C1]??"unknown",V=jZ(J);if(Lg(J))return z4({name:`${V} ${H} stream-response`,op:JX(J),attributes:G},async(F)=>{try{if($.recordInputs&&z)_g(F,z);let B=await Q.apply(X,K);return Bg(B,F,Boolean($.recordOutputs))}catch(B){throw F.setStatus({code:A0,message:"internal_error"}),V0(B,{mechanism:{handled:!1,type:"auto.ai.google_genai",data:{function:J}}}),F.end(),B}});return _6({name:Y?`${V} ${H} create`:`${V} ${H}`,op:JX(J),attributes:G},(F)=>{if($.recordInputs&&z)_g(F,z);return D6(()=>Q.apply(X,K),(B)=>{V0(B,{mechanism:{handled:!1,type:"auto.ai.google_genai",data:{function:J}}})},()=>{},(B)=>{if(!Y)QR0(F,B,$.recordOutputs)})})}})}function kU(Z,J="",X){return new Proxy(Z,{get:($,Y,Q)=>{let W=Reflect.get($,Y,Q),K=QK(J,String(Y));if(typeof W==="function"&&Ug(K)){if(K===SU){let z=Og(W,K,$,X);return function(...H){let V=z(...H);if(V&&typeof V==="object")return kU(V,Fg,X);return V}}return Og(W,K,$,X)}if(typeof W==="function")return W.bind($);if(W&&typeof W==="object")return kU(W,K,X);return W}})}function xU(Z,J){let X=Boolean(u()?.getOptions().sendDefaultPii),$={recordInputs:X,recordOutputs:X,...J};return kU(Z,"",$)}var VK="LangChain",AZ="auto.ai.langchain",wg={human:"user",ai:"assistant",assistant:"assistant",system:"system",function:"function",tool:"tool"};var R8=(Z,J,X)=>{if(X!=null)Z[J]=X},w6=(Z,J,X)=>{let $=Number(X);if(!Number.isNaN($))Z[J]=$};function J6(Z){if(typeof Z==="string")return Z;try{return JSON.stringify(Z)}catch{return String(Z)}}function AY(Z){let J=Z.toLowerCase();return wg[J]??J}function jg(Z){if(Z.includes("System"))return"system";if(Z.includes("Human"))return"user";if(Z.includes("AI")||Z.includes("Assistant"))return"assistant";if(Z.includes("Function"))return"function";if(Z.includes("Tool"))return"tool";return"user"}function vU(Z){if(!Z||Array.isArray(Z))return;return Z.invocation_params}function TY(Z){return Z.map((J)=>{let X=J._getType;if(typeof X==="function"){let Y=X.call(J);return{role:AY(Y),content:J6(J.content)}}let $=J.constructor?.name;if($)return{role:AY(jg($)),content:J6(J.content)};if(J.type){let Y=String(J.type).toLowerCase();return{role:AY(Y),content:J6(J.content)}}if(J.role)return{role:AY(String(J.role)),content:J6(J.content)};if(J.lc===1&&J.kwargs){let Y=J.id,Q=Array.isArray(Y)&&Y.length>0?Y[Y.length-1]:"",W=typeof Q==="string"?jg(Q):"user";return{role:AY(W),content:J6(J.kwargs?.content)}}return{role:"user",content:J6(J.content)}})}function WR0(Z,J,X){let $={},Y="kwargs"in Z?Z.kwargs:void 0,Q=J?.temperature??X?.ls_temperature??Y?.temperature;w6($,r9,Q);let W=J?.max_tokens??X?.ls_max_tokens??Y?.max_tokens;w6($,eJ,W);let K=J?.top_p??Y?.top_p;w6($,t9,K);let z=J?.frequency_penalty;w6($,s9,z);let G=J?.presence_penalty;if(w6($,ZX,G),J&&"stream"in J)R8($,tJ,Boolean(J.stream));return $}function Mg(Z,J,X,$,Y,Q){return{[a9]:J6(Z??"langchain"),[w4]:X,[C1]:J6(J),[X0]:AZ,...WR0($,Y,Q)}}function Ag(Z,J,X,$,Y){let Q=Y?.ls_provider,W=$?.model??Y?.ls_model_name??"unknown",K=Mg(Q,W,"pipeline",Z,$,Y);if(X&&Array.isArray(J)&&J.length>0){R8(K,Z6,J.length);let z=J.map((G)=>({role:"user",content:G}));R8(K,G4,J6(z))}return K}function Tg(Z,J,X,$,Y){let Q=Y?.ls_provider??Z.id?.[2],W=$?.model??Y?.ls_model_name??"unknown",K=Mg(Q,W,"chat",Z,$,Y);if(X&&Array.isArray(J)&&J.length>0){let z=TY(J.flat());R8(K,Z6,z.length);let G=J7(z);R8(K,G4,J6(G))}return K}function KR0(Z,J){let X=[],$=Z.flat();for(let Y of $){let Q=Y.message?.content;if(Array.isArray(Q))for(let W of Q){let K=W;if(K.type==="tool_use")X.push(K)}}if(X.length>0)R8(J,t1,J6(X))}function zR0(Z,J){if(!Z)return;let{tokenUsage:X,usage:$}=Z;if(X)w6(J,D1,X.promptTokens),w6(J,b1,X.completionTokens),w6(J,O6,X.totalTokens);else if($){w6(J,D1,$.input_tokens),w6(J,b1,$.output_tokens);let Y=Number($.input_tokens),Q=Number($.output_tokens),W=(Number.isNaN(Y)?0:Y)+(Number.isNaN(Q)?0:Q);if(W>0)w6(J,O6,W);if($.cache_creation_input_tokens!==void 0)w6(J,Yb,$.cache_creation_input_tokens);if($.cache_read_input_tokens!==void 0)w6(J,Qb,$.cache_read_input_tokens)}}function qg(Z,J){if(!Z)return;let X={};if(Array.isArray(Z.generations)){let G=Z.generations.flat().map((H)=>{if(H.generationInfo?.finish_reason)return H.generationInfo.finish_reason;if(H.generation_info?.finish_reason)return H.generation_info.finish_reason;return null}).filter((H)=>typeof H==="string");if(G.length>0)R8(X,e4,J6(G));if(KR0(Z.generations,X),J){let H=Z.generations.flat().map((V)=>V.text??V.message?.content).filter((V)=>typeof V==="string");if(H.length>0)R8(X,g1,J6(H))}}zR0(Z.llmOutput,X);let $=Z.llmOutput,Q=Z.generations?.[0]?.[0]?.message,W=$?.model_name??$?.model??Q?.response_metadata?.model_name;if(W)R8(X,p1,W);let K=$?.id??Q?.id;if(K)R8(X,m6,K);let z=$?.stop_reason??Q?.response_metadata?.finish_reason;if(z)R8(X,Xb,J6(z));return X}function FK(Z={}){let J=Z.recordInputs??!1,X=Z.recordOutputs??!1,$=new Map,Y=(W)=>{let K=$.get(W);if(K?.isRecording())K.end(),$.delete(W)},Q={lc_serializable:!1,lc_namespace:["langchain_core","callbacks","sentry"],lc_secrets:void 0,lc_attributes:void 0,lc_aliases:void 0,lc_serializable_keys:void 0,lc_id:["langchain_core","callbacks","sentry"],lc_kwargs:{},name:"SentryCallbackHandler",ignoreLLM:!1,ignoreChain:!1,ignoreAgent:!1,ignoreRetriever:!1,ignoreCustomEvent:!1,raiseError:!1,awaitHandlers:!0,handleLLMStart(W,K,z,G,H,V,F,B){let U=vU(V),D=Ag(W,K,J,U,F),_=D[C1],O=D[w4];z4({name:`${O} ${_}`,op:"gen_ai.pipeline",attributes:{...D,[K0]:"gen_ai.pipeline"}},(w)=>{return $.set(z,w),w})},handleChatModelStart(W,K,z,G,H,V,F,B){let U=vU(V),D=Tg(W,K,J,U,F),_=D[C1],O=D[w4];z4({name:`${O} ${_}`,op:"gen_ai.chat",attributes:{...D,[K0]:"gen_ai.chat"}},(w)=>{return $.set(z,w),w})},handleLLMEnd(W,K,z,G,H){let V=$.get(K);if(V?.isRecording()){let F=qg(W,X);if(F)V.setAttributes(F);Y(K)}},handleLLMError(W,K){let z=$.get(K);if(z?.isRecording())z.setStatus({code:A0,message:"llm_error"}),Y(K);V0(W,{mechanism:{handled:!1,type:`${AZ}.llm_error_handler`}})},handleChainStart(W,K,z,G){let H=W.name||"unknown_chain",V={[X0]:"auto.ai.langchain","langchain.chain.name":H};if(J)V["langchain.chain.inputs"]=JSON.stringify(K);z4({name:`chain ${H}`,op:"gen_ai.invoke_agent",attributes:{...V,[K0]:"gen_ai.invoke_agent"}},(F)=>{return $.set(z,F),F})},handleChainEnd(W,K){let z=$.get(K);if(z?.isRecording()){if(X)z.setAttributes({"langchain.chain.outputs":JSON.stringify(W)});Y(K)}},handleChainError(W,K){let z=$.get(K);if(z?.isRecording())z.setStatus({code:A0,message:"chain_error"}),Y(K);V0(W,{mechanism:{handled:!1,type:`${AZ}.chain_error_handler`}})},handleToolStart(W,K,z,G){let H=W.name||"unknown_tool",V={[X0]:AZ,"gen_ai.tool.name":H};if(J)V["gen_ai.tool.input"]=K;z4({name:`execute_tool ${H}`,op:"gen_ai.execute_tool",attributes:{...V,[K0]:"gen_ai.execute_tool"}},(F)=>{return $.set(z,F),F})},handleToolEnd(W,K){let z=$.get(K);if(z?.isRecording()){if(X)z.setAttributes({"gen_ai.tool.output":JSON.stringify(W)});Y(K)}},handleToolError(W,K){let z=$.get(K);if(z?.isRecording())z.setStatus({code:A0,message:"tool_error"}),Y(K);V0(W,{mechanism:{handled:!1,type:`${AZ}.tool_error_handler`}})},copy(){return Q},toJSON(){return{lc:1,type:"not_implemented",id:Q.lc_id}},toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:Q.lc_id}}};return Q}var BK="LangGraph",hU="auto.ai.langgraph";function GR0(Z){if(!Z||Z.length===0)return null;let J=[];for(let X of Z)if(X&&typeof X==="object"){let $=X.tool_calls;if($&&Array.isArray($))J.push(...$)}return J.length>0?J:null}function HR0(Z){let J=Z,X=0,$=0,Y=0;if(J.usage_metadata&&typeof J.usage_metadata==="object"){let Q=J.usage_metadata;if(typeof Q.input_tokens==="number")X=Q.input_tokens;if(typeof Q.output_tokens==="number")$=Q.output_tokens;if(typeof Q.total_tokens==="number")Y=Q.total_tokens;return{inputTokens:X,outputTokens:$,totalTokens:Y}}if(J.response_metadata&&typeof J.response_metadata==="object"){let Q=J.response_metadata;if(Q.tokenUsage&&typeof Q.tokenUsage==="object"){let W=Q.tokenUsage;if(typeof W.promptTokens==="number")X=W.promptTokens;if(typeof W.completionTokens==="number")$=W.completionTokens;if(typeof W.totalTokens==="number")Y=W.totalTokens}}return{inputTokens:X,outputTokens:$,totalTokens:Y}}function VR0(Z,J){let X=J;if(X.response_metadata&&typeof X.response_metadata==="object"){let $=X.response_metadata;if($.model_name&&typeof $.model_name==="string")Z.setAttribute(p1,$.model_name);if($.finish_reason&&typeof $.finish_reason==="string")Z.setAttribute(e4,[$.finish_reason])}}function Cg(Z){if(!Z.builder?.nodes?.tools?.runnable?.tools)return null;let J=Z.builder?.nodes?.tools?.runnable?.tools;if(!J||!Array.isArray(J)||J.length===0)return null;return J.map((X)=>({name:X.lc_kwargs?.name,description:X.lc_kwargs?.description,schema:X.lc_kwargs?.schema}))}function Ng(Z,J,X){let Y=X?.messages;if(!Y||!Array.isArray(Y))return;let Q=J?.length??0,W=Y.length>Q?Y.slice(Q):[];if(W.length===0)return;let K=GR0(W);if(K)Z.setAttribute(t1,JSON.stringify(K));let z=TY(W);Z.setAttribute(g1,JSON.stringify(z));let G=0,H=0,V=0;for(let F of W){let B=HR0(F);G+=B.inputTokens,H+=B.outputTokens,V+=B.totalTokens,VR0(Z,F)}if(G>0)Z.setAttribute(D1,G);if(H>0)Z.setAttribute(b1,H);if(V>0)Z.setAttribute(O6,V)}function fU(Z,J){return new Proxy(Z,{apply(X,$,Y){return _6({op:"gen_ai.create_agent",name:"create_agent",attributes:{[X0]:hU,[K0]:"gen_ai.create_agent",[w4]:"create_agent"}},(Q)=>{try{let W=Reflect.apply(X,$,Y),K=Y.length>0?Y[0]:{};if(K?.name&&typeof K.name==="string")Q.setAttribute(LU,K.name),Q.updateName(`create_agent ${K.name}`);let z=W.invoke;if(z&&typeof z==="function")W.invoke=FR0(z.bind(W),W,K,J);return W}catch(W){throw Q.setStatus({code:A0,message:"internal_error"}),V0(W,{mechanism:{handled:!1,type:"auto.ai.langgraph.error"}}),W}})}})}function FR0(Z,J,X,$){return new Proxy(Z,{apply(Y,Q,W){return _6({op:"gen_ai.invoke_agent",name:"invoke_agent",attributes:{[X0]:hU,[K0]:JK,[w4]:"invoke_agent"}},async(K)=>{try{let z=X?.name;if(z&&typeof z==="string")K.setAttribute($b,z),K.setAttribute(LU,z),K.updateName(`invoke_agent ${z}`);let V=(W.length>1?W[1]:void 0)?.configurable?.thread_id;if(V&&typeof V==="string")K.setAttribute(LY,V);let F=Cg(J);if(F)K.setAttribute(e9,JSON.stringify(F));let{recordInputs:B,recordOutputs:U}=$,D=W.length>0?W[0].messages??[]:[];if(D&&B){let O=TY(D),w=J7(O);K.setAttributes({[G4]:JSON.stringify(w),[Z6]:O.length})}let _=await Reflect.apply(Y,Q,W);if(U)Ng(K,D??null,_);return _}catch(z){throw K.setStatus({code:A0,message:"internal_error"}),V0(z,{mechanism:{handled:!1,type:"auto.ai.langgraph.error"}}),z}})}})}function qY(Z){if(Z===void 0)return;else if(Z>=400&&Z<500)return"warning";else if(Z>=500)return"error";else return}function CY(Z,J,X){let $=Z[J];if(typeof $!=="function")return;try{Z[J]=X}catch(Y){Object.defineProperty(Z,J,{value:X,writable:!0,configurable:!0,enumerable:!0})}if(Z.default===$)try{Z.default=X}catch(Y){Object.defineProperty(Z,"default",{value:X,writable:!0,configurable:!0,enumerable:!0})}}function Pg(Z,J=!1){return!(J||Z&&!Z.startsWith("/")&&!Z.match(/^[A-Z]:/)&&!Z.startsWith(".")&&!Z.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&Z!==void 0&&!Z.includes("node_modules/")}function Eg(Z){let J=/^\s*[-]{4,}$/,X=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,$=/at (?:async )?(.+?) \(data:(.*?),/;return(Y)=>{let Q=Y.match($);if(Q)return{filename:`<data:${Q[2]}>`,function:Q[1]};let W=Y.match(X);if(W){let K,z,G,H,V;if(W[1]){G=W[1];let U=G.lastIndexOf(".");if(G[U-1]===".")U--;if(U>0){K=G.slice(0,U),z=G.slice(U+1);let D=K.indexOf(".Module");if(D>0)G=G.slice(D+1),K=K.slice(0,D)}H=void 0}if(z)H=K,V=z;if(z==="<anonymous>")V=void 0,G=void 0;if(G===void 0)V=V||GB,G=H?`${H}.${V}`:V;let F=W[2]?.startsWith("file://")?W[2].slice(7):W[2],B=W[5]==="native";if(F?.match(/\/[A-Z]:/))F=F.slice(1);if(!F&&W[5]&&!B)F=W[5];return{filename:F?decodeURI(F):void 0,module:Z?Z(F):void 0,function:G,lineno:Rg(W[3]),colno:Rg(W[4]),in_app:Pg(F||"",B)}}if(Y.match(J))return{filename:Y};return}}function bU(Z){return[90,Eg(Z)]}function Rg(Z){return parseInt(Z||"",10)||void 0}class j6{constructor(Z){this._maxSize=Z,this._cache=new Map}get size(){return this._cache.size}get(Z){let J=this._cache.get(Z);if(J===void 0)return;return this._cache.delete(Z),this._cache.set(Z,J),J}set(Z,J){if(this._cache.size>=this._maxSize){let X=this._cache.keys().next().value;this._cache.delete(X)}this._cache.set(Z,J)}remove(Z){let J=this._cache.get(Z);if(J)this._cache.delete(Z);return J}clear(){this._cache.clear()}keys(){return Array.from(this._cache.keys())}values(){let Z=[];return this._cache.forEach((J)=>Z.push(J)),Z}}var gU=k(H0(),1),NY={};function a(Z,J,X){if(X)return xR0(Z,J,X);return kR0(Z,J)}function kR0(Z,J){return Object.assign((X)=>{let $=NY[Z];if($){if(X)$.setConfig(X);return $}let Y=J(X);return NY[Z]=Y,gU.registerInstrumentations({instrumentations:[Y]}),Y},{id:Z})}function xR0(Z,J,X){return Object.assign(($)=>{let Y=X($),Q=NY[Z];if(Q)return Q.setConfig(Y),Q;let W=new J(Y);return NY[Z]=W,gU.registerInstrumentations({instrumentations:[W]}),W},{id:Z})}function RY(Z){let J=!1,X=[];if(!vR0(Z))J=!0;else{let Y=Z._wrap;Z._wrap=(...Q)=>{return J=!0,X.forEach((W)=>W()),X=[],Y(...Q)}}return(Y)=>{if(J)Y();else X.push(Y)}}function vR0(Z){return typeof Z._wrap==="function"}var K7=k(f(),1);import{subscribe as hR0}from"diagnostics_channel";var _0=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;var Z5="@sentry/instrumentation-http",Ig=1048576;var yg=K7.createContextKey("sentry_http_server_instrumented"),W7="Http.Server",mU=new Map,Sg=new WeakSet;function kg(Z,J){f1(Z,"_startSpanCallback",new WeakRef(J))}var fR0=(Z={})=>{let J={sessions:Z.sessions??!0,sessionFlushingDelayMS:Z.sessionFlushingDelayMS??60000,maxRequestBodySize:Z.maxRequestBodySize??"medium",ignoreRequestBody:Z.ignoreRequestBody};return{name:W7,setupOnce(){hR0("http.server.request.start",($)=>{bR0($.server,J)})},afterAllSetup(X){if(_0&&X.getIntegrationByName("Http"))A.warn("It seems that you have manually added `httpServerIntegration` while `httpIntegration` is also present. Make sure to remove `httpServerIntegration` when adding `httpIntegration`.")}}},YX=fR0;function bR0(Z,{ignoreRequestBody:J,maxRequestBodySize:X,sessions:$,sessionFlushingDelayMS:Y}){let Q=Z.emit;if(Sg.has(Q))return;let W=new Proxy(Q,{apply(K,z,G){if(G[0]!=="request")return K.apply(z,G);let H=u();if(K7.context.active().getValue(yg)||!H)return K.apply(z,G);_0&&A.log(W7,"Handling incoming request");let V=R0().clone(),F=G[1],B=G[2],U=UY(F),D=F.ip||F.socket?.remoteAddress,_=F.url||"/";if(X!=="none"&&!J?.(_,F))mR0(F,V,X);V.setSDKProcessingMetadata({normalizedRequest:U,ipAddress:D});let O=(F.method||"GET").toUpperCase(),w=p5(_),j=`${O} ${w}`;if(V.setTransactionName(j),$&&H)gR0(H,{requestIsolationScope:V,response:B,sessionFlushingDelayMS:Y??60000});return KZ(V,()=>{u0().getPropagationContext().propagationSpanId=r4();let q=K7.propagation.extract(K7.context.active(),U.headers).setValue(yg,!0);return K7.context.with(q,()=>{H.emit("httpServerRequest",F,B,U);let R=F._startSpanCallback?.deref();if(R)return R(()=>K.apply(z,G));return K.apply(z,G)})})}});Sg.add(W),Z.emit=W}function gR0(Z,{requestIsolationScope:J,response:X,sessionFlushingDelayMS:$}){J.setSDKProcessingMetadata({requestSession:{status:"ok"}}),X.once("close",()=>{let Y=J.getScopeData().sdkProcessingMetadata.requestSession;if(Z&&Y){_0&&A.log(`Recorded request session with status: ${Y.status}`);let Q=new Date;Q.setSeconds(0,0);let W=Q.toISOString(),K=mU.get(Z),z=K?.[W]||{exited:0,crashed:0,errored:0};if(z[{ok:"exited",crashed:"crashed",errored:"errored"}[Y.status]]++,K)K[W]=z;else{_0&&A.log("Opened new request session aggregate.");let G={[W]:z};mU.set(Z,G);let H=()=>{clearTimeout(F),V(),mU.delete(Z);let B=Object.entries(G).map(([U,D])=>({started:U,exited:D.exited,errored:D.errored,crashed:D.crashed}));Z.sendSession({aggregates:B})},V=Z.on("flush",()=>{_0&&A.log("Sending request session aggregate due to client flush"),H()}),F=setTimeout(()=>{_0&&A.log("Sending request session aggregate due to flushing schedule"),H()},$).unref()}}})}function mR0(Z,J,X){let $=0,Y=[];_0&&A.log(W7,"Patching request.on");let Q=new WeakMap,W=X==="small"?1000:X==="medium"?1e4:Ig;try{Z.on=new Proxy(Z.on,{apply:(K,z,G)=>{let[H,V,...F]=G;if(H==="data"){_0&&A.log(W7,`Handling request.on("data") with maximum body size of ${W}b`);let B=new Proxy(V,{apply:(U,D,_)=>{try{let O=_[0],w=Buffer.from(O);if($<W)Y.push(w),$+=w.byteLength;else if(_0)A.log(W7,`Dropping request body chunk because maximum body length of ${W}b is exceeded.`)}catch(O){_0&&A.error(W7,"Encountered error while storing body chunk.")}return Reflect.apply(U,D,_)}});return Q.set(V,B),Reflect.apply(K,z,[H,B,...F])}return Reflect.apply(K,z,G)}}),Z.off=new Proxy(Z.off,{apply:(K,z,G)=>{let[,H]=G,V=Q.get(H);if(V){Q.delete(H);let F=G.slice();return F[1]=V,Reflect.apply(K,z,F)}return Reflect.apply(K,z,G)}}),Z.on("end",()=>{try{let K=Buffer.concat(Y).toString("utf-8");if(K){let G=Buffer.byteLength(K,"utf-8")>W?`${Buffer.from(K).subarray(0,W-3).toString("utf-8")}...`:K;J.setSDKProcessingMetadata({normalizedRequest:{data:G}})}}catch(K){if(_0)A.error(W7,"Error building captured request body",K)}})}catch(K){if(_0)A.error(W7,"Error patching request to capture body",K)}}var M6=k(f(),1),a5=k(H1(),1),A6=k(p0(),1);import{errorMonitor as YI0}from"events";var rd="Http.ServerSpans",QI0=(Z={})=>{let J=Z.ignoreStaticAssets??!0,X=Z.ignoreIncomingRequests,$=Z.ignoreStatusCodes??[[401,404],[301,303],[305,399]],{onSpanCreated:Y}=Z,{requestHook:Q,responseHook:W,applyCustomAttributesOnSpan:K}=Z.instrumentation??{};return{name:rd,setup(z){if(typeof __SENTRY_TRACING__<"u"&&!__SENTRY_TRACING__)return;z.on("httpServerRequest",(G,H,V)=>{let F=G,B=H;kg(F,(D)=>{if(zI0(F,{ignoreStaticAssets:J,ignoreIncomingRequests:X}))return _0&&A.log(rd,"Skipping span creation for incoming request",F.url),D();let _=V.url||F.url||"/",O=BY(_),w=F.headers,j=w["user-agent"],q=w["x-forwarded-for"],R=F.httpVersion,T=w.host,y=T?.replace(/^(.*)(:[0-9]{1,5})/,"$1")||"localhost",i=z.tracer,s=_.startsWith("https")?"https":"http",O0=V.method||F.method?.toUpperCase()||"GET",d0=O?O.pathname:p5(_),b0=`${O0} ${d0}`,G0=i.startSpan(b0,{kind:M6.SpanKind.SERVER,attributes:{[K0]:"http.server",[X0]:"auto.http.otel.http","sentry.http.prefetch":WI0(F)||void 0,"http.url":_,"http.method":V.method,"http.target":O?`${O.pathname}${O.search}`:d0,"http.host":T,"net.host.name":y,"http.client_ip":typeof q==="string"?q.split(",")[0]:void 0,"http.user_agent":j,"http.scheme":s,"http.flavor":R,"net.transport":R?.toUpperCase()==="QUIC"?"ip_udp":"ip_tcp",...GI0(F),...iJ(V.headers||{},z.getOptions().sendDefaultPii??!1)}});Q?.(G0,F),W?.(G0,B),K?.(G0,F,B),Y?.(G0,F,B);let E0={type:a5.RPCType.HTTP,span:G0};return M6.context.with(a5.setRPCMetadata(M6.trace.setSpan(M6.context.active(),G0),E0),()=>{M6.context.bind(M6.context.active(),F),M6.context.bind(M6.context.active(),B);let f0=!1;function k0(e0){if(f0)return;f0=!0;let y6=FI0(F,B);G0.setAttributes(y6),G0.setStatus(e0),G0.end();let i4=y6["http.route"];if(i4)R0().setTransactionName(`${F.method?.toUpperCase()||"GET"} ${i4}`)}return B.on("close",()=>{k0(d9(B.statusCode))}),B.on(YI0,()=>{let e0=d9(B.statusCode);k0(e0.code===A0?e0:{code:A0})}),D()})})})},processEvent(z){if(z.type==="transaction"){let G=z.contexts?.trace?.data?.["http.response.status_code"];if(typeof G==="number"){if(BI0(G,$))return _0&&A.log("Dropping transaction due to status code",G),null}}return z},afterAllSetup(z){if(!_0)return;if(z.getIntegrationByName("Http"))A.warn("It seems that you have manually added `httpServerSpansIntergation` while `httpIntegration` is also present. Make sure to remove `httpIntegration` when adding `httpServerSpansIntegration`.");if(!z.getIntegrationByName("Http.Server"))A.error("It seems that you have manually added `httpServerSpansIntergation` without adding `httpServerIntegration`. This is a requiement for spans to be created - please add the `httpServerIntegration` integration.")}}},WX=QI0;function WI0(Z){return Z.headers["next-router-prefetch"]==="1"}function KI0(Z){let J=p5(Z);if(J.match(/\.(ico|png|jpg|jpeg|gif|svg|css|js|woff|woff2|ttf|eot|webp|avif)$/))return!0;if(J.match(/^\/(robots\.txt|sitemap\.xml|manifest\.json|browserconfig\.xml)$/))return!0;return!1}function zI0(Z,{ignoreStaticAssets:J,ignoreIncomingRequests:X}){if(a5.isTracingSuppressed(M6.context.active()))return!0;let $=Z.url,Y=Z.method?.toUpperCase();if(Y==="OPTIONS"||Y==="HEAD"||!$)return!0;if(J&&Y==="GET"&&KI0($))return!0;if(X?.($,Z))return!0;return!1}function GI0(Z){let J=HI0(Z.headers);if(J==null)return{};if(VI0(Z.headers))return{["http.request_content_length"]:J};else return{["http.request_content_length_uncompressed"]:J}}function HI0(Z){let J=Z["content-length"];if(J===void 0)return null;let X=parseInt(J,10);if(isNaN(X))return null;return X}function VI0(Z){let J=Z["content-encoding"];return!!J&&J!=="identity"}function FI0(Z,J){let{socket:X}=Z,{statusCode:$,statusMessage:Y}=J,Q={[A6.ATTR_HTTP_RESPONSE_STATUS_CODE]:$,[A6.SEMATTRS_HTTP_STATUS_CODE]:$,"http.status_text":Y?.toUpperCase()},W=a5.getRPCMetadata(M6.context.active());if(X){let{localAddress:K,localPort:z,remoteAddress:G,remotePort:H}=X;Q[A6.SEMATTRS_NET_HOST_IP]=K,Q[A6.SEMATTRS_NET_HOST_PORT]=z,Q[A6.SEMATTRS_NET_PEER_IP]=G,Q["net.peer.port"]=H}if(Q[A6.SEMATTRS_HTTP_STATUS_CODE]=$,Q["http.status_text"]=(Y||"").toUpperCase(),W?.type===a5.RPCType.HTTP&&W.route!==void 0){let K=W.route;Q[A6.ATTR_HTTP_ROUTE]=K}return Q}function BI0(Z,J){return J.some((X)=>{if(typeof X==="number")return X===Z;let[$,Y]=X;return Z>=$&&Z<=Y})}var pu=k(f(),1),iu=k(H1(),1),gY=k(H0(),1);import{subscribe as AL,unsubscribe as TL}from"diagnostics_channel";function yY(Z){let J=Z.protocol||"",X=Z.hostname||Z.host||"",$=!Z.port||Z.port===80||Z.port===443||/^(.*):(\d+)$/.test(X)?"":`:${Z.port}`,Y=Z.path?Z.path:"/";return`${J}//${X}${$}${Y}`}var T0=k(p0(),1);var $6=k(f(),1),n=k(f(),1),k4=k(H1(),1);var Ku=k(H1(),1);var zX=k(f(),1),NK=k(H1(),1),P8=k(p0(),1);var UI0=typeof process==="object"&&typeof process.argv0==="string"&&process.argv0.length>0?`unknown_service:${process.argv0}`:"unknown_service";function sd(){return UI0}var KX=(Z)=>{return Z!==null&&typeof Z==="object"&&typeof Z.then==="function"};class RK{_rawAttributes;_asyncAttributesPending=!1;_schemaUrl;_memoizedAttributes;static FromAttributeList(Z,J){let X=new RK({},J);return X._rawAttributes=td(Z),X._asyncAttributesPending=Z.filter(([$,Y])=>KX(Y)).length>0,X}constructor(Z,J){let X=Z.attributes??{};this._rawAttributes=Object.entries(X).map(([$,Y])=>{if(KX(Y))this._asyncAttributesPending=!0;return[$,Y]}),this._rawAttributes=td(this._rawAttributes),this._schemaUrl=LI0(J?.schemaUrl)}get asyncAttributesPending(){return this._asyncAttributesPending}async waitForAsyncAttributes(){if(!this.asyncAttributesPending)return;for(let Z=0;Z<this._rawAttributes.length;Z++){let[J,X]=this._rawAttributes[Z];this._rawAttributes[Z]=[J,KX(X)?await X:X]}this._asyncAttributesPending=!1}get attributes(){if(this.asyncAttributesPending)zX.diag.error("Accessing resource attributes before async attributes settled");if(this._memoizedAttributes)return this._memoizedAttributes;let Z={};for(let[J,X]of this._rawAttributes){if(KX(X)){zX.diag.debug(`Unsettled resource attribute ${J} skipped`);continue}if(X!=null)Z[J]??=X}if(!this._asyncAttributesPending)this._memoizedAttributes=Z;return Z}getRawAttributes(){return this._rawAttributes}get schemaUrl(){return this._schemaUrl}merge(Z){if(Z==null)return this;let J=DI0(this,Z),X=J?{schemaUrl:J}:void 0;return RK.FromAttributeList([...Z.getRawAttributes(),...this.getRawAttributes()],X)}}function PK(Z,J){return RK.FromAttributeList(Object.entries(Z),J)}function SY(){return PK({[P8.ATTR_SERVICE_NAME]:sd(),[P8.ATTR_TELEMETRY_SDK_LANGUAGE]:NK.SDK_INFO[P8.ATTR_TELEMETRY_SDK_LANGUAGE],[P8.ATTR_TELEMETRY_SDK_NAME]:NK.SDK_INFO[P8.ATTR_TELEMETRY_SDK_NAME],[P8.ATTR_TELEMETRY_SDK_VERSION]:NK.SDK_INFO[P8.ATTR_TELEMETRY_SDK_VERSION]})}function td(Z){return Z.map(([J,X])=>{if(KX(X))return[J,X.catch(($)=>{zX.diag.debug("promise rejection for resource attribute: %s - %s",J,$);return})];return[J,X]})}function LI0(Z){if(typeof Z==="string"||Z===void 0)return Z;zX.diag.warn("Schema URL must be string or undefined, got %s. Schema URL will be ignored.",Z);return}function DI0(Z,J){let X=Z?.schemaUrl,$=J?.schemaUrl,Y=X===void 0||X==="",Q=$===void 0||$==="";if(Y)return $;if(Q)return X;if(X===$)return X;zX.diag.warn('Schema URL merge conflict: old resource has "%s", updating resource has "%s". Resulting resource will have undefined Schema URL.',X,$);return}var V1=k(f(),1),HX=k(H1(),1);var X6=k(f(),1),X1=k(H1(),1),J5=k(p0(),1);var ed="exception";class XL{_spanContext;kind;parentSpanContext;attributes={};links=[];events=[];startTime;resource;instrumentationScope;_droppedAttributesCount=0;_droppedEventsCount=0;_droppedLinksCount=0;name;status={code:X6.SpanStatusCode.UNSET};endTime=[0,0];_ended=!1;_duration=[-1,-1];_spanProcessor;_spanLimits;_attributeValueLengthLimit;_performanceStartTime;_performanceOffset;_startTimeProvided;constructor(Z){let J=Date.now();if(this._spanContext=Z.spanContext,this._performanceStartTime=X1.otperformance.now(),this._performanceOffset=J-(this._performanceStartTime+X1.otperformance.timeOrigin),this._startTimeProvided=Z.startTime!=null,this._spanLimits=Z.spanLimits,this._attributeValueLengthLimit=this._spanLimits.attributeValueLengthLimit||0,this._spanProcessor=Z.spanProcessor,this.name=Z.name,this.parentSpanContext=Z.parentSpanContext,this.kind=Z.kind,this.links=Z.links||[],this.startTime=this._getTime(Z.startTime??J),this.resource=Z.resource,this.instrumentationScope=Z.scope,Z.attributes!=null)this.setAttributes(Z.attributes);this._spanProcessor.onStart(this,Z.context)}spanContext(){return this._spanContext}setAttribute(Z,J){if(J==null||this._isSpanEnded())return this;if(Z.length===0)return X6.diag.warn(`Invalid attribute key: ${Z}`),this;if(!X1.isAttributeValue(J))return X6.diag.warn(`Invalid attribute value set for key: ${Z}`),this;let{attributeCountLimit:X}=this._spanLimits;if(X!==void 0&&Object.keys(this.attributes).length>=X&&!Object.prototype.hasOwnProperty.call(this.attributes,Z))return this._droppedAttributesCount++,this;return this.attributes[Z]=this._truncateToSize(J),this}setAttributes(Z){for(let[J,X]of Object.entries(Z))this.setAttribute(J,X);return this}addEvent(Z,J,X){if(this._isSpanEnded())return this;let{eventCountLimit:$}=this._spanLimits;if($===0)return X6.diag.warn("No events allowed."),this._droppedEventsCount++,this;if($!==void 0&&this.events.length>=$){if(this._droppedEventsCount===0)X6.diag.debug("Dropping extra events.");this.events.shift(),this._droppedEventsCount++}if(X1.isTimeInput(J)){if(!X1.isTimeInput(X))X=J;J=void 0}let Y=X1.sanitizeAttributes(J);return this.events.push({name:Z,attributes:Y,time:this._getTime(X),droppedAttributesCount:0}),this}addLink(Z){return this.links.push(Z),this}addLinks(Z){return this.links.push(...Z),this}setStatus(Z){if(this._isSpanEnded())return this;if(this.status={...Z},this.status.message!=null&&typeof Z.message!=="string")X6.diag.warn(`Dropping invalid status.message of type '${typeof Z.message}', expected 'string'`),delete this.status.message;return this}updateName(Z){if(this._isSpanEnded())return this;return this.name=Z,this}end(Z){if(this._isSpanEnded()){X6.diag.error(`${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`);return}if(this.endTime=this._getTime(Z),this._duration=X1.hrTimeDuration(this.startTime,this.endTime),this._duration[0]<0)X6.diag.warn("Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.",this.startTime,this.endTime),this.endTime=this.startTime.slice(),this._duration=[0,0];if(this._droppedEventsCount>0)X6.diag.warn(`Dropped ${this._droppedEventsCount} events because eventCountLimit reached`);if(this._spanProcessor.onEnding)this._spanProcessor.onEnding(this);this._ended=!0,this._spanProcessor.onEnd(this)}_getTime(Z){if(typeof Z==="number"&&Z<=X1.otperformance.now())return X1.hrTime(Z+this._performanceOffset);if(typeof Z==="number")return X1.millisToHrTime(Z);if(Z instanceof Date)return X1.millisToHrTime(Z.getTime());if(X1.isTimeInputHrTime(Z))return Z;if(this._startTimeProvided)return X1.millisToHrTime(Date.now());let J=X1.otperformance.now()-this._performanceStartTime;return X1.addHrTimes(this.startTime,X1.millisToHrTime(J))}isRecording(){return this._ended===!1}recordException(Z,J){let X={};if(typeof Z==="string")X[J5.ATTR_EXCEPTION_MESSAGE]=Z;else if(Z){if(Z.code)X[J5.ATTR_EXCEPTION_TYPE]=Z.code.toString();else if(Z.name)X[J5.ATTR_EXCEPTION_TYPE]=Z.name;if(Z.message)X[J5.ATTR_EXCEPTION_MESSAGE]=Z.message;if(Z.stack)X[J5.ATTR_EXCEPTION_STACKTRACE]=Z.stack}if(X[J5.ATTR_EXCEPTION_TYPE]||X[J5.ATTR_EXCEPTION_MESSAGE])this.addEvent(ed,X,J);else X6.diag.warn(`Failed to record an exception ${Z}`)}get duration(){return this._duration}get ended(){return this._ended}get droppedAttributesCount(){return this._droppedAttributesCount}get droppedEventsCount(){return this._droppedEventsCount}get droppedLinksCount(){return this._droppedLinksCount}_isSpanEnded(){if(this._ended){let Z=Error(`Operation attempted on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`);X6.diag.warn(`Cannot execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`,Z)}return this._ended}_truncateToLimitUtil(Z,J){if(Z.length<=J)return Z;return Z.substring(0,J)}_truncateToSize(Z){let J=this._attributeValueLengthLimit;if(J<=0)return X6.diag.warn(`Attribute value limit must be positive, got ${J}`),Z;if(typeof Z==="string")return this._truncateToLimitUtil(Z,J);if(Array.isArray(Z))return Z.map((X)=>typeof X==="string"?this._truncateToLimitUtil(X,J):X);return Z}}var yK=k(f(),1),u6=k(H1(),1);var e1;(function(Z){Z[Z.NOT_RECORD=0]="NOT_RECORD",Z[Z.RECORD=1]="RECORD",Z[Z.RECORD_AND_SAMPLED=2]="RECORD_AND_SAMPLED"})(e1||(e1={}));class RZ{shouldSample(){return{decision:e1.NOT_RECORD}}toString(){return"AlwaysOffSampler"}}class r5{shouldSample(){return{decision:e1.RECORD_AND_SAMPLED}}toString(){return"AlwaysOnSampler"}}var PZ=k(f(),1),Zu=k(H1(),1);class GX{_root;_remoteParentSampled;_remoteParentNotSampled;_localParentSampled;_localParentNotSampled;constructor(Z){if(this._root=Z.root,!this._root)Zu.globalErrorHandler(Error("ParentBasedSampler must have a root sampler configured")),this._root=new r5;this._remoteParentSampled=Z.remoteParentSampled??new r5,this._remoteParentNotSampled=Z.remoteParentNotSampled??new RZ,this._localParentSampled=Z.localParentSampled??new r5,this._localParentNotSampled=Z.localParentNotSampled??new RZ}shouldSample(Z,J,X,$,Y,Q){let W=PZ.trace.getSpanContext(Z);if(!W||!PZ.isSpanContextValid(W))return this._root.shouldSample(Z,J,X,$,Y,Q);if(W.isRemote){if(W.traceFlags&PZ.TraceFlags.SAMPLED)return this._remoteParentSampled.shouldSample(Z,J,X,$,Y,Q);return this._remoteParentNotSampled.shouldSample(Z,J,X,$,Y,Q)}if(W.traceFlags&PZ.TraceFlags.SAMPLED)return this._localParentSampled.shouldSample(Z,J,X,$,Y,Q);return this._localParentNotSampled.shouldSample(Z,J,X,$,Y,Q)}toString(){return`ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`}}var Ju=k(f(),1);class EK{_ratio;_upperBound;constructor(Z=0){this._ratio=this._normalize(Z),this._upperBound=Math.floor(this._ratio*4294967295)}shouldSample(Z,J){return{decision:Ju.isValidTraceId(J)&&this._accumulate(J)<this._upperBound?e1.RECORD_AND_SAMPLED:e1.NOT_RECORD}}toString(){return`TraceIdRatioBased{${this._ratio}}`}_normalize(Z){if(typeof Z!=="number"||isNaN(Z))return 0;return Z>=1?1:Z<=0?0:Z}_accumulate(Z){let J=0;for(let X=0;X<Z.length/8;X++){let $=X*8,Y=parseInt(Z.slice($,$+8),16);J=(J^Y)>>>0}return J}}var X5;(function(Z){Z.AlwaysOff="always_off",Z.AlwaysOn="always_on",Z.ParentBasedAlwaysOff="parentbased_always_off",Z.ParentBasedAlwaysOn="parentbased_always_on",Z.ParentBasedTraceIdRatio="parentbased_traceidratio",Z.TraceIdRatio="traceidratio"})(X5||(X5={}));var IK=1;function SK(){return{sampler:$L(),forceFlushTimeoutMillis:30000,generalLimits:{attributeValueLengthLimit:u6.getNumberFromEnv("OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT")??1/0,attributeCountLimit:u6.getNumberFromEnv("OTEL_ATTRIBUTE_COUNT_LIMIT")??128},spanLimits:{attributeValueLengthLimit:u6.getNumberFromEnv("OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT")??1/0,attributeCountLimit:u6.getNumberFromEnv("OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT")??128,linkCountLimit:u6.getNumberFromEnv("OTEL_SPAN_LINK_COUNT_LIMIT")??128,eventCountLimit:u6.getNumberFromEnv("OTEL_SPAN_EVENT_COUNT_LIMIT")??128,attributePerEventCountLimit:u6.getNumberFromEnv("OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT")??128,attributePerLinkCountLimit:u6.getNumberFromEnv("OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT")??128}}}function $L(){let Z=u6.getStringFromEnv("OTEL_TRACES_SAMPLER")??X5.ParentBasedAlwaysOn;switch(Z){case X5.AlwaysOn:return new r5;case X5.AlwaysOff:return new RZ;case X5.ParentBasedAlwaysOn:return new GX({root:new r5});case X5.ParentBasedAlwaysOff:return new GX({root:new RZ});case X5.TraceIdRatio:return new EK(Xu());case X5.ParentBasedTraceIdRatio:return new GX({root:new EK(Xu())});default:return yK.diag.error(`OTEL_TRACES_SAMPLER value "${Z}" invalid, defaulting to "${X5.ParentBasedAlwaysOn}".`),new GX({root:new r5})}}function Xu(){let Z=u6.getNumberFromEnv("OTEL_TRACES_SAMPLER_ARG");if(Z==null)return yK.diag.error(`OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${IK}.`),IK;if(Z<0||Z>1)return yK.diag.error(`OTEL_TRACES_SAMPLER_ARG=${Z} was given, but it is out of range ([0..1]), defaulting to ${IK}.`),IK;return Z}var kY=k(H1(),1),_I0=128,OI0=1/0;function $u(Z){let J={sampler:$L()},X=SK(),$=Object.assign({},X,J,Z);return $.generalLimits=Object.assign({},X.generalLimits,Z.generalLimits||{}),$.spanLimits=Object.assign({},X.spanLimits,Z.spanLimits||{}),$}function Yu(Z){let J=Object.assign({},Z.spanLimits);return J.attributeCountLimit=Z.spanLimits?.attributeCountLimit??Z.generalLimits?.attributeCountLimit??kY.getNumberFromEnv("OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT")??kY.getNumberFromEnv("OTEL_ATTRIBUTE_COUNT_LIMIT")??_I0,J.attributeValueLengthLimit=Z.spanLimits?.attributeValueLengthLimit??Z.generalLimits?.attributeValueLengthLimit??kY.getNumberFromEnv("OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT")??kY.getNumberFromEnv("OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT")??OI0,Object.assign({},Z,{spanLimits:J})}class xY{generateTraceId=Qu(16);generateSpanId=Qu(8)}var kK=Buffer.allocUnsafe(16);function Qu(Z){return function(){for(let X=0;X<Z/4;X++)kK.writeUInt32BE(Math.random()*4294967296>>>0,X*4);for(let X=0;X<Z;X++)if(kK[X]>0)break;else if(X===Z-1)kK[Z-1]=1;return kK.toString("hex",0,Z)}}class YL{_sampler;_generalLimits;_spanLimits;_idGenerator;instrumentationScope;_resource;_spanProcessor;constructor(Z,J,X,$){let Y=$u(J);this._sampler=Y.sampler,this._generalLimits=Y.generalLimits,this._spanLimits=Y.spanLimits,this._idGenerator=J.idGenerator||new xY,this._resource=X,this._spanProcessor=$,this.instrumentationScope=Z}startSpan(Z,J={},X=V1.context.active()){if(J.root)X=V1.trace.deleteSpan(X);let $=V1.trace.getSpan(X);if(HX.isTracingSuppressed(X))return V1.diag.debug("Instrumentation suppressed, returning Noop Span"),V1.trace.wrapSpanContext(V1.INVALID_SPAN_CONTEXT);let Y=$?.spanContext(),Q=this._idGenerator.generateSpanId(),W,K,z;if(!Y||!V1.trace.isSpanContextValid(Y))K=this._idGenerator.generateTraceId();else K=Y.traceId,z=Y.traceState,W=Y;let G=J.kind??V1.SpanKind.INTERNAL,H=(J.links??[]).map((O)=>{return{context:O.context,attributes:HX.sanitizeAttributes(O.attributes)}}),V=HX.sanitizeAttributes(J.attributes),F=this._sampler.shouldSample(X,K,Z,G,V,H);z=F.traceState??z;let B=F.decision===V1.SamplingDecision.RECORD_AND_SAMPLED?V1.TraceFlags.SAMPLED:V1.TraceFlags.NONE,U={traceId:K,spanId:Q,traceFlags:B,traceState:z};if(F.decision===V1.SamplingDecision.NOT_RECORD)return V1.diag.debug("Recording is off, propagating context in a non-recording span"),V1.trace.wrapSpanContext(U);let D=HX.sanitizeAttributes(Object.assign(V,F.attributes));return new XL({resource:this._resource,scope:this.instrumentationScope,context:X,spanContext:U,name:Z,kind:G,links:H,parentSpanContext:W,attributes:D,startTime:J.startTime,spanProcessor:this._spanProcessor,spanLimits:this._spanLimits})}startActiveSpan(Z,J,X,$){let Y,Q,W;if(arguments.length<2)return;else if(arguments.length===2)W=J;else if(arguments.length===3)Y=J,W=X;else Y=J,Q=X,W=$;let K=Q??V1.context.active(),z=this.startSpan(Z,Y,K),G=V1.trace.setSpan(K,z);return V1.context.with(G,W,void 0,z)}getGeneralLimits(){return this._generalLimits}getSpanLimits(){return this._spanLimits}}var Wu=k(H1(),1);class QL{_spanProcessors;constructor(Z){this._spanProcessors=Z}forceFlush(){let Z=[];for(let J of this._spanProcessors)Z.push(J.forceFlush());return new Promise((J)=>{Promise.all(Z).then(()=>{J()}).catch((X)=>{Wu.globalErrorHandler(X||Error("MultiSpanProcessor: forceFlush failed")),J()})})}onStart(Z,J){for(let X of this._spanProcessors)X.onStart(Z,J)}onEnding(Z){for(let J of this._spanProcessors)if(J.onEnding)J.onEnding(Z)}onEnd(Z){for(let J of this._spanProcessors)J.onEnd(Z)}shutdown(){let Z=[];for(let J of this._spanProcessors)Z.push(J.shutdown());return new Promise((J,X)=>{Promise.all(Z).then(()=>{J()},X)})}}var EZ;(function(Z){Z[Z.resolved=0]="resolved",Z[Z.timeout=1]="timeout",Z[Z.error=2]="error",Z[Z.unresolved=3]="unresolved"})(EZ||(EZ={}));class xK{_config;_tracers=new Map;_resource;_activeSpanProcessor;constructor(Z={}){let J=Ku.merge({},SK(),Yu(Z));this._resource=J.resource??SY(),this._config=Object.assign({},J,{resource:this._resource});let X=[];if(Z.spanProcessors?.length)X.push(...Z.spanProcessors);this._activeSpanProcessor=new QL(X)}getTracer(Z,J,X){let $=`${Z}@${J||""}:${X?.schemaUrl||""}`;if(!this._tracers.has($))this._tracers.set($,new YL({name:Z,version:J,schemaUrl:X?.schemaUrl},this._config,this._resource,this._activeSpanProcessor));return this._tracers.get($)}forceFlush(){let Z=this._config.forceFlushTimeoutMillis,J=this._activeSpanProcessor._spanProcessors.map((X)=>{return new Promise(($)=>{let Y,Q=setTimeout(()=>{$(Error(`Span processor did not completed within timeout period of ${Z} ms`)),Y=EZ.timeout},Z);X.forceFlush().then(()=>{if(clearTimeout(Q),Y!==EZ.timeout)Y=EZ.resolved,$(Y)}).catch((W)=>{clearTimeout(Q),Y=EZ.error,$(W)})})});return new Promise((X,$)=>{Promise.all(J).then((Y)=>{let Q=Y.filter((W)=>W!==EZ.resolved);if(Q.length>0)$(Q);else X()}).catch((Y)=>$([Y]))})}shutdown(){return this._activeSpanProcessor.shutdown()}}var BL="sentry.parentIsRemote",BX="sentry.graphql.operation";function UL(Z){if("parentSpanId"in Z)return Z.parentSpanId;else if("parentSpanContext"in Z)return Z.parentSpanContext?.spanId;return}function LL(Z){let J=Z;return!!J.attributes&&typeof J.attributes==="object"}function wI0(Z){return typeof Z.kind==="number"}function jI0(Z){return!!Z.status}function Fu(Z){return!!Z.name}function MI0(Z){if(!LL(Z))return{};let J=Z.attributes[T0.ATTR_URL_FULL]||Z.attributes[T0.SEMATTRS_HTTP_URL],X={url:J,"http.method":Z.attributes[T0.ATTR_HTTP_REQUEST_METHOD]||Z.attributes[T0.SEMATTRS_HTTP_METHOD]};if(!X["http.method"]&&X.url)X["http.method"]="GET";try{if(typeof J==="string"){let $=n9(J);if(X.url=o9($),$.search)X["http.query"]=$.search;if($.hash)X["http.fragment"]=$.hash}}catch{}return X}function AI0(Z){if(wI0(Z))return Z.kind;return n.SpanKind.INTERNAL}var WL="sentry-trace",KL="baggage",DL="sentry.dsc",_L="sentry.sampled_not_recording",Bu="sentry.url",TI0="sentry.sample_rand",qI0="sentry.sample_rate",OL=n.createContextKey("sentry_scopes"),zL=n.createContextKey("sentry_fork_isolation_scope"),GL=n.createContextKey("sentry_fork_set_scope"),HL=n.createContextKey("sentry_fork_set_isolation_scope"),Uu="_scopeContext";function UX(Z){return Z.getValue(OL)}function Lu(Z,J){return Z.setValue(OL,J)}function CI0(Z,J){f1(Z,Uu,J)}function hY(Z){return Z[Uu]}function FX(Z){let{traceFlags:J,traceState:X}=Z,$=X?X.get(_L)==="1":!1;if(J===n.TraceFlags.SAMPLED)return!0;if($)return!1;let Y=X?X.get(DL):void 0,Q=Y?T8(Y):void 0;if(Q?.sampled==="true")return!0;if(Q?.sampled==="false")return!1;return}function Du(Z,J,X){let $=J[T0.ATTR_HTTP_REQUEST_METHOD]||J[T0.SEMATTRS_HTTP_METHOD];if($)return RI0({attributes:J,name:Z,kind:X},$);let Y=J[T0.SEMATTRS_DB_SYSTEM],Q=typeof J[K0]==="string"&&J[K0].startsWith("cache.");if(Y&&!Q)return NI0({attributes:J,name:Z});let W=J[U1]==="custom"?"custom":"route";if(J[T0.SEMATTRS_RPC_SERVICE])return{...vY(Z,J,"route"),op:"rpc"};if(J[T0.SEMATTRS_MESSAGING_SYSTEM])return{...vY(Z,J,W),op:"message"};let G=J[T0.SEMATTRS_FAAS_TRIGGER];if(G)return{...vY(Z,J,W),op:G.toString()};return{op:void 0,description:Z,source:"custom"}}function _u(Z){let J=LL(Z)?Z.attributes:{},X=Fu(Z)?Z.name:"<unknown>",$=AI0(Z);return Du(X,J,$)}function NI0({attributes:Z,name:J}){let X=Z[s8];if(typeof X==="string")return{op:"db",description:X,source:Z[U1]||"custom"};if(Z[U1]==="custom")return{op:"db",description:J,source:"custom"};let $=Z[T0.SEMATTRS_DB_STATEMENT];return{op:"db",description:$?$.toString():J,source:"task"}}function RI0({name:Z,kind:J,attributes:X},$){let Y=["http"];switch(J){case n.SpanKind.CLIENT:Y.push("client");break;case n.SpanKind.SERVER:Y.push("server");break}if(X["sentry.http.prefetch"])Y.push("prefetch");let{urlPath:Q,url:W,query:K,fragment:z,hasRoute:G}=EI0(X,J);if(!Q)return{...vY(Z,X),op:Y.join(".")};let H=X[BX],V=`${$} ${Q}`,F=H?`${V} (${PI0(H)})`:V,B=G||Q==="/"?"route":"url",U={};if(W)U.url=W;if(K)U["http.query"]=K;if(z)U["http.fragment"]=z;let D=J===n.SpanKind.CLIENT||J===n.SpanKind.SERVER,O=!`${X[X0]||"manual"}`.startsWith("auto"),w=X[U1]==="custom",j=X[s8],q=!w&&j==null&&(D||!O),{description:R,source:T}=q?{description:F,source:B}:vY(Z,X);return{op:Y.join("."),description:R,source:T,data:U}}function PI0(Z){if(Array.isArray(Z)){let J=Z.slice().sort();if(J.length<=5)return J.join(", ");else return`${J.slice(0,5).join(", ")}, +${J.length-5}`}return`${Z}`}function EI0(Z,J){let X=Z[T0.SEMATTRS_HTTP_TARGET],$=Z[T0.SEMATTRS_HTTP_URL]||Z[T0.ATTR_URL_FULL],Y=Z[T0.ATTR_HTTP_ROUTE],Q=typeof $==="string"?n9($):void 0,W=Q?o9(Q):void 0,K=Q?.search||void 0,z=Q?.hash||void 0;if(typeof Y==="string")return{urlPath:Y,url:W,query:K,fragment:z,hasRoute:!0};if(J===n.SpanKind.SERVER&&typeof X==="string")return{urlPath:p5(X),url:W,query:K,fragment:z,hasRoute:!1};if(Q)return{urlPath:W,url:W,query:K,fragment:z,hasRoute:!1};if(typeof X==="string")return{urlPath:p5(X),url:W,query:K,fragment:z,hasRoute:!1};return{urlPath:void 0,url:W,query:K,fragment:z,hasRoute:!1}}function vY(Z,J,X="custom"){let $=J[U1]||X,Y=J[s8];if(Y&&typeof Y==="string")return{description:Y,source:$};return{description:Z,source:$}}function Ou(Z){Z.on("createDsc",(J,X)=>{if(!X)return;let Q=J0(X).data[U1],{description:W}=Fu(X)?_u(X):{description:void 0};if(Q!=="url"&&W)J.transaction=W;if(L1()){let K=FX(X.spanContext());J.sampled=K==null?void 0:String(K)}})}function wu(){return n.trace.getActiveSpan()}var $5=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;function ju({dsc:Z,sampled:J}){let X=Z?GZ(Z):void 0,$=new k4.TraceState,Y=X?$.set(DL,X):$;return J===!1?Y.set(_L,"1"):Y}var Mu=new Set;function Au(){return Array.from(Mu)}function vK(Z){Mu.add(Z)}class wL extends k4.W3CBaggagePropagator{constructor(){super();vK("SentryPropagator"),this._urlMatchesTargetsMap=new j6(100)}inject(Z,J,X){if(k4.isTracingSuppressed(Z)){$5&&A.log("[Tracing] Not injecting trace data for url because tracing is suppressed.");return}let $=n.trace.getSpan(Z),Y=$&&SI0($),{tracePropagationTargets:Q,propagateTraceparent:W}=u()?.getOptions()||{};if(!fY(Y,Q,this._urlMatchesTargetsMap)){$5&&A.log("[Tracing] Not injecting trace data for url because it does not match tracePropagationTargets:",Y);return}let K=yI0(J),z=n.propagation.getBaggage(Z)||n.propagation.createBaggage({}),{dynamicSamplingContext:G,traceId:H,spanId:V,sampled:F}=Tu(Z);if(K){let B=HZ(K);if(B)Object.entries(B).forEach(([U,D])=>{z=z.setEntry(U,{value:D})})}if(G)z=Object.entries(G).reduce((B,[U,D])=>{if(D)return B.setEntry(`${r$}${U}`,{value:D});return B},z);if(H&&H!==n.INVALID_TRACEID){if(X.set(J,WL,u9(H,V,F)),W)X.set(J,"traceparent",c9(H,V,F))}super.inject(n.propagation.setBaggage(Z,z),J,X)}extract(Z,J,X){let $=X.get(J,WL),Y=X.get(J,KL),Q=$?Array.isArray($)?$[0]:$:void 0;return Cu(qu(Z,{sentryTrace:Q,baggage:Y}))}fields(){return[WL,KL,"traceparent"]}}var zu="[Tracing] Not injecting trace data for url because it does not match tracePropagationTargets:";function fY(Z,J,X){if(typeof Z!=="string"||!J)return!0;let $=X?.get(Z);if($!==void 0)return $5&&!$&&A.log(zu,Z),$;let Y=h9(Z,J);return X?.set(Z,Y),$5&&!Y&&A.log(zu,Z),Y}function Tu(Z,J={}){let X=n.trace.getSpan(Z);if(X?.spanContext().isRemote){let K=X.spanContext();return{dynamicSamplingContext:S1(X),traceId:K.traceId,spanId:void 0,sampled:FX(K)}}if(X){let K=X.spanContext();return{dynamicSamplingContext:S1(X),traceId:K.traceId,spanId:K.spanId,sampled:FX(K)}}let $=J.scope||UX(Z)?.scope||u0(),Y=J.client||u(),Q=$.getPropagationContext();return{dynamicSamplingContext:Y?e8(Y,$):void 0,traceId:Q.traceId,spanId:Q.propagationSpanId,sampled:Q.sampled}}function qu(Z,{sentryTrace:J,baggage:X}){let $=VZ(J,X),{traceId:Y,parentSpanId:Q,sampled:W,dsc:K}=$,z=u(),G=T8(X);if(!Q||z&&!t$(z,G?.org_id))return Z;let H=kI0({traceId:Y,spanId:Q,sampled:W,dsc:K});return n.trace.setSpanContext(Z,H)}function II0(Z,J,X){let $=Cu(qu(Z,J));return n.context.with($,X)}function Cu(Z){let J=UX(Z),X={scope:J?J.scope:u0().clone(),isolationScope:J?J.isolationScope:R0()};return Lu(Z,X)}function yI0(Z){try{let J=Z[KL];return Array.isArray(J)?J.join(","):J}catch{return}}function SI0(Z){let J=J0(Z).data,X=J[T0.SEMATTRS_HTTP_URL]||J[T0.ATTR_URL_FULL];if(typeof X==="string")return X;let $=Z.spanContext().traceState?.get(Bu);if($)return $;return}function kI0({spanId:Z,traceId:J,sampled:X,dsc:$}){let Y=ju({dsc:$,sampled:X});return{traceId:J,spanId:Z,isRemote:!0,traceFlags:X?n.TraceFlags.SAMPLED:n.TraceFlags.NONE,traceState:Y}}function Nu(Z,J,X){let $=Pu(),{name:Y,parentSpan:Q}=Z;return Su(Q)(()=>{let K=Iu(Z.scope,Z.forceTransaction),G=Z.onlyIfParent&&!n.trace.getSpan(K)?k4.suppressTracing(K):K,H=Eu(Z);if(!L1()){let V=k4.isTracingSuppressed(G)?G:k4.suppressTracing(G);return n.context.with(V,()=>{return $.startActiveSpan(Y,H,V,(F)=>{return n.context.with(K,()=>{return D6(()=>J(F),()=>{if(J0(F).status===void 0)F.setStatus({code:n.SpanStatusCode.ERROR})},X?()=>F.end():void 0)})})})}return $.startActiveSpan(Y,H,G,(V)=>{return D6(()=>J(V),()=>{if(J0(V).status===void 0)V.setStatus({code:n.SpanStatusCode.ERROR})},X?()=>V.end():void 0)})})}function xI0(Z,J){return Nu(Z,J,!0)}function vI0(Z,J){return Nu(Z,(X)=>J(X,()=>X.end()),!1)}function hI0(Z){let J=Pu(),{name:X,parentSpan:$}=Z;return Su($)(()=>{let Q=Iu(Z.scope,Z.forceTransaction),K=Z.onlyIfParent&&!n.trace.getSpan(Q)?k4.suppressTracing(Q):Q,z=Eu(Z);if(!L1())K=k4.isTracingSuppressed(K)?K:k4.suppressTracing(K);return J.startSpan(X,z,K)})}function Ru(Z,J){let X=Z?n.trace.setSpan(n.context.active(),Z):n.trace.deleteSpan(n.context.active());return n.context.with(X,()=>J(u0()))}function Pu(){return u()?.tracer||n.trace.getTracer("@sentry/opentelemetry",N0)}function Eu(Z){let{startTime:J,attributes:X,kind:$,op:Y,links:Q}=Z,W=typeof J==="number"?fI0(J):J;return{attributes:Y?{[K0]:Y,...X}:X,kind:$,links:Q,startTime:W}}function fI0(Z){return Z<9999999999?Z*1000:Z}function Iu(Z,J){let X=bI0(Z),$=n.trace.getSpan(X);if(!$)return X;if(!J)return X;let Y=n.trace.deleteSpan(X),{spanId:Q,traceId:W}=$.spanContext(),K=FX($.spanContext()),z=q1($),G=S1(z),H=ju({dsc:G,sampled:K}),V={traceId:W,spanId:Q,isRemote:!0,traceFlags:K?n.TraceFlags.SAMPLED:n.TraceFlags.NONE,traceState:H};return n.trace.setSpanContext(Y,V)}function bI0(Z){if(Z){let J=hY(Z);if(J)return J}return n.context.active()}function gI0(Z,J){return II0(n.context.active(),Z,J)}function yu(Z,J){let X=hY(J),$=X&&n.trace.getSpan(X),Y=$?l9($):zZ(J);return[$?S1($):e8(Z,J),Y]}function Su(Z){return Z!==void 0?(J)=>{return Ru(Z,J)}:(J)=>J()}function mI0(Z){let J=k4.suppressTracing(n.context.active());return n.context.with(J,Z)}function ku(Z){Z.on("preprocessEvent",(J)=>{let X=wu();if(!X||J.type==="transaction")return;J.contexts={trace:l9(X),...J.contexts};let $=q1(X);return J.sdkProcessingMetadata={dynamicSamplingContext:S1($),...J.sdkProcessingMetadata},J})}function dI0({span:Z,scope:J,client:X,propagateTraceparent:$}={}){let Y=(J&&hY(J))??$6.context.active();if(Z){let{scope:H}=A8(Z);Y=H&&hY(H)||$6.trace.setSpan($6.context.active(),Z)}let{traceId:Q,spanId:W,sampled:K,dynamicSamplingContext:z}=Tu(Y,{scope:J,client:X}),G={"sentry-trace":u9(Q,W,K),baggage:GZ(z)};if($)G.traceparent=c9(Q,W,K);return G}function xu(){function Z(){let K=$6.context.active(),z=UX(K);if(z)return z;return{scope:vJ(),isolationScope:B6()}}function J(K){let z=$6.context.active();return $6.context.with(z,()=>{return K(Q())})}function X(K,z){let G=hY(K)||$6.context.active();return $6.context.with(G.setValue(GL,K),()=>{return z(K)})}function $(K){let z=$6.context.active();return $6.context.with(z.setValue(zL,!0),()=>{return K(W())})}function Y(K,z){let G=$6.context.active();return $6.context.with(G.setValue(HL,K),()=>{return z(W())})}function Q(){return Z().scope}function W(){return Z().isolationScope}PB({withScope:J,withSetScope:X,withSetIsolationScope:Y,withIsolationScope:$,getCurrentScope:Q,getIsolationScope:W,startSpan:xI0,startSpanManual:vI0,startInactiveSpan:hI0,getActiveSpan:wu,suppressTracing:mI0,getTraceData:dI0,continueTrace:gI0,withActiveSpan:Ru})}function vu(Z){class J extends Z{constructor(...X){super(...X);vK("SentryContextManager")}with(X,$,Y,...Q){let W=UX(X),K=W?.scope||u0(),z=W?.isolationScope||R0(),G=X.getValue(zL)===!0,H=X.getValue(GL),V=X.getValue(HL),F=H||K.clone(),B=V||(G?z.clone():z),_=Lu(X,{scope:F,isolationScope:B}).deleteValue(zL).deleteValue(GL).deleteValue(HL);return CI0(F,_),super.with(_,$,Y,...Q)}getAsyncLocalStorageLookup(){return{asyncLocalStorage:this._asyncLocalStorage,contextSymbol:OL}}}return J}function uI0(Z){let J=new Map;for(let X of Z)cI0(J,X);return Array.from(J,function([X,$]){return $})}function hu(Z){return Z.attributes[BL]!==!0?UL(Z):void 0}function cI0(Z,J){let X=J.spanContext().spanId,$=hu(J);if(!$){VL(Z,{id:X,span:J,children:[]});return}let Y=lI0(Z,$),Q=VL(Z,{id:X,span:J,parentNode:Y,children:[]});Y.children.push(Q)}function lI0(Z,J){let X=Z.get(J);if(X)return X;return VL(Z,{id:J,children:[]})}function VL(Z,J){let X=Z.get(J.id);if(X?.span)return X;if(X&&!X.span)return X.span=J.span,X.parentNode=J.parentNode,X;return Z.set(J.id,J),J}var fu={"1":"cancelled","2":"unknown_error","3":"invalid_argument","4":"deadline_exceeded","5":"not_found","6":"already_exists","7":"permission_denied","8":"resource_exhausted","9":"failed_precondition","10":"aborted","11":"out_of_range","12":"unimplemented","13":"internal_error","14":"unavailable","15":"data_loss","16":"unauthenticated"},pI0=(Z)=>{return Object.values(fu).includes(Z)};function bu(Z){let J=LL(Z)?Z.attributes:{},X=jI0(Z)?Z.status:void 0;if(X){if(X.code===n.SpanStatusCode.OK)return{code:gJ};else if(X.code===n.SpanStatusCode.ERROR){if(typeof X.message>"u"){let Y=Gu(J);if(Y)return Y}if(X.message&&pI0(X.message))return{code:A0,message:X.message};else return{code:A0,message:"internal_error"}}}let $=Gu(J);if($)return $;if(X?.code===n.SpanStatusCode.UNSET)return{code:gJ};else return{code:A0,message:"unknown_error"}}function Gu(Z){let J=Z[T0.ATTR_HTTP_RESPONSE_STATUS_CODE]||Z[T0.SEMATTRS_HTTP_STATUS_CODE],X=Z[T0.SEMATTRS_RPC_GRPC_STATUS_CODE],$=typeof J==="number"?J:typeof J==="string"?parseInt(J):void 0;if(typeof $==="number")return d9($);if(typeof X==="string")return{code:A0,message:fu[X]||"unknown_error"};return}var Hu=1000,Vu=300;class gu{constructor(Z){this._finishedSpanBucketSize=Z?.timeout||Vu,this._finishedSpanBuckets=Array(this._finishedSpanBucketSize).fill(void 0),this._lastCleanupTimestampInS=Math.floor(f6()/1000),this._spansToBucketEntry=new WeakMap,this._sentSpans=new Map,this._debouncedFlush=GU(this.flush.bind(this),1,{maxWait:100})}export(Z){let J=Math.floor(f6()/1000);if(this._lastCleanupTimestampInS!==J){let Q=0;if(this._finishedSpanBuckets.forEach((W,K)=>{if(W&&W.timestampInS<=J-this._finishedSpanBucketSize)Q+=W.spans.size,this._finishedSpanBuckets[K]=void 0}),Q>0)$5&&A.log(`SpanExporter dropped ${Q} spans because they were pending for more than ${this._finishedSpanBucketSize} seconds.`);this._lastCleanupTimestampInS=J}let X=J%this._finishedSpanBucketSize,$=this._finishedSpanBuckets[X]||{timestampInS:J,spans:new Set};this._finishedSpanBuckets[X]=$,$.spans.add(Z),this._spansToBucketEntry.set(Z,$);let Y=hu(Z);if(!Y||this._sentSpans.has(Y))this._debouncedFlush()}flush(){let Z=this._finishedSpanBuckets.flatMap((Q)=>Q?Array.from(Q.spans):[]);this._flushSentSpanCache();let J=this._maybeSend(Z),X=J.size,$=Z.length-X;$5&&A.log(`SpanExporter exported ${X} spans, ${$} spans are waiting for their parent spans to finish`);let Y=f6()+Vu*1000;for(let Q of J){this._sentSpans.set(Q.spanContext().spanId,Y);let W=this._spansToBucketEntry.get(Q);if(W)W.spans.delete(Q)}this._debouncedFlush.cancel()}clear(){this._finishedSpanBuckets=this._finishedSpanBuckets.fill(void 0),this._sentSpans.clear(),this._debouncedFlush.cancel()}_maybeSend(Z){let J=uI0(Z),X=new Set,$=this._getCompletedRootNodes(J);for(let Y of $){let Q=Y.span;X.add(Q);let W=nI0(Q);if(Y.parentNode&&this._sentSpans.has(Y.parentNode.id)){let G=W.contexts?.trace?.data;if(G)G["sentry.parent_span_already_sent"]=!0}let K=W.spans||[];for(let G of Y.children)FL(G,K,X);W.spans=K.length>Hu?K.sort((G,H)=>G.start_timestamp-H.start_timestamp).slice(0,Hu):K;let z=UZ(Q.events);if(z)W.measurements=z;pW(W)}return X}_flushSentSpanCache(){let Z=f6();for(let[J,X]of this._sentSpans.entries())if(X<=Z)this._sentSpans.delete(J)}_nodeIsCompletedRootNodeOrHasSentParent(Z){return!!Z.span&&(!Z.parentNode||this._sentSpans.has(Z.parentNode.id))}_getCompletedRootNodes(Z){return Z.filter((J)=>this._nodeIsCompletedRootNodeOrHasSentParent(J))}}function iI0(Z){let J=Z.attributes,X=J[X0],$=J[K0],Y=J[U1];return{origin:X,op:$,source:Y}}function nI0(Z){let{op:J,description:X,data:$,origin:Y="manual",source:Q}=mu(Z),W=A8(Z),K=Z.attributes[M8],z={[U1]:Q,[M8]:K,[K0]:J,[X0]:Y,...$,...du(Z.attributes)},{links:G}=Z,{traceId:H,spanId:V}=Z.spanContext(),F=UL(Z),B=bu(Z),U={parent_span_id:F,span_id:V,trace_id:H,data:z,origin:Y,op:J,status:BZ(B),links:FZ(G)},D=z[T0.ATTR_HTTP_RESPONSE_STATUS_CODE],_=typeof D==="number"?{response:{status_code:D}}:void 0;return{contexts:{trace:U,otel:{resource:Z.resource.attributes},..._},spans:[],start_timestamp:t4(Z.startTime),timestamp:t4(Z.endTime),transaction:X,type:"transaction",sdkProcessingMetadata:{capturedSpanScope:W.scope,capturedSpanIsolationScope:W.isolationScope,sampleRate:K,dynamicSamplingContext:S1(Z)},...Q&&{transaction_info:{source:Q}}}}function FL(Z,J,X){let $=Z.span;if($)X.add($);if(!$){Z.children.forEach((j)=>{FL(j,J,X)});return}let Q=$.spanContext().spanId,W=$.spanContext().traceId,K=UL($),{attributes:z,startTime:G,endTime:H,links:V}=$,{op:F,description:B,data:U,origin:D="manual"}=mu($),_={[X0]:D,[K0]:F,...du(z),...U},O=bu($),w={span_id:Q,trace_id:W,data:_,description:B,parent_span_id:K,start_timestamp:t4(G),timestamp:t4(H)||void 0,status:BZ(O),op:F,origin:D,measurements:UZ($.events),links:FZ(V)};J.push(w),Z.children.forEach((j)=>{FL(j,J,X)})}function mu(Z){let{op:J,source:X,origin:$}=iI0(Z),{op:Y,description:Q,source:W,data:K}=_u(Z),z=J||Y,G=X||W,H={...K,...oI0(Z)};return{op:z,description:Q,source:G,origin:$,data:H}}function du(Z){let J={...Z};return delete J[M8],delete J[BL],delete J[s8],J}function oI0(Z){let J=Z.attributes,X={};if(Z.kind!==n.SpanKind.INTERNAL)X["otel.kind"]=n.SpanKind[Z.kind];let $=J[T0.SEMATTRS_HTTP_STATUS_CODE];if($)X[T0.ATTR_HTTP_RESPONSE_STATUS_CODE]=$;let Y=MI0(Z);if(Y.url)X.url=Y.url;if(Y["http.query"])X["http.query"]=Y["http.query"].slice(1);if(Y["http.fragment"])X["http.fragment"]=Y["http.fragment"].slice(1);return X}function aI0(Z,J){let X=n.trace.getSpan(J),$=UX(J);if(X&&!X.spanContext().isRemote)mJ(X,Z);if(X?.spanContext().isRemote)Z.setAttribute(BL,!0);if(J===n.ROOT_CONTEXT)$={scope:vJ(),isolationScope:B6()};if($)a$(Z,$.scope,$.isolationScope);YY(Z),u()?.emit("spanStart",Z)}function rI0(Z){QY(Z),u()?.emit("spanEnd",Z)}class jL{constructor(Z){vK("SentrySpanProcessor"),this._exporter=new gu(Z)}async forceFlush(){this._exporter.flush()}async shutdown(){this._exporter.clear()}onStart(Z,J){aI0(Z,J)}onEnd(Z){rI0(Z),this._exporter.export(Z)}}class ML{constructor(Z){this._client=Z,vK("SentrySampler")}shouldSample(Z,J,X,$,Y,Q){let W=this._client.getOptions(),K=eI0(Z),z=K?.spanContext();if(!L1(W))return VX({decision:void 0,context:Z,spanAttributes:Y});let G=Y[T0.SEMATTRS_HTTP_METHOD]||Y[T0.ATTR_HTTP_REQUEST_METHOD];if($===n.SpanKind.CLIENT&&G&&(!K||z?.isRemote))return VX({decision:void 0,context:Z,spanAttributes:Y});let H=K?sI0(K,J,X):void 0;if(!(!K||z?.isRemote))return VX({decision:H?e1.RECORD_AND_SAMPLED:e1.NOT_RECORD,context:Z,spanAttributes:Y});let{description:F,data:B,op:U}=Du(X,Y,$),D={...B,...Y};if(U)D[K0]=U;let _={decision:!0};if(this._client.emit("beforeSampling",{spanAttributes:D,spanName:F,parentSampled:H,parentContext:z},_),!_.decision)return VX({decision:void 0,context:Z,spanAttributes:Y});let{isolationScope:O}=UX(Z)??{},w=z?.traceState?z.traceState.get(DL):void 0,j=w?T8(w):void 0,q=L6(j?.sample_rand)??K4(),[R,T,y]=KY(W,{name:F,attributes:D,normalizedRequest:O?.getScopeData().sdkProcessingMetadata.normalizedRequest,parentSampled:H,parentSampleRate:L6(j?.sample_rate)},q),i=`${G}`.toUpperCase();if(i==="OPTIONS"||i==="HEAD")return $5&&A.log(`[Tracing] Not sampling span because HTTP method is '${i}' for ${X}`),VX({decision:e1.NOT_RECORD,context:Z,spanAttributes:Y,sampleRand:q,downstreamTraceSampleRate:0});if(!R&&H===void 0)$5&&A.log("[Tracing] Discarding root span because its trace was not chosen to be sampled."),this._client.recordDroppedEvent("sample_rate","transaction");return{...VX({decision:R?e1.RECORD_AND_SAMPLED:e1.NOT_RECORD,context:Z,spanAttributes:Y,sampleRand:q,downstreamTraceSampleRate:y?T:void 0}),attributes:{[M8]:y?T:void 0}}}toString(){return"SentrySampler"}}function sI0(Z,J,X){let $=Z.spanContext();if(n.isSpanContextValid($)&&$.traceId===J){if($.isRemote){let Q=FX(Z.spanContext());return $5&&A.log(`[Tracing] Inheriting remote parent's sampled decision for ${X}: ${Q}`),Q}let Y=FX($);return $5&&A.log(`[Tracing] Inheriting parent's sampled decision for ${X}: ${Y}`),Y}return}function VX({decision:Z,context:J,spanAttributes:X,sampleRand:$,downstreamTraceSampleRate:Y}){let Q=tI0(J,X);if(Y!==void 0)Q=Q.set(qI0,`${Y}`);if($!==void 0)Q=Q.set(TI0,`${$}`);if(Z==null)return{decision:e1.NOT_RECORD,traceState:Q};if(Z===e1.NOT_RECORD)return{decision:Z,traceState:Q.set(_L,"1")};return{decision:Z,traceState:Q}}function tI0(Z,J){let Y=n.trace.getSpan(Z)?.spanContext()?.traceState||new k4.TraceState,Q=J[T0.SEMATTRS_HTTP_URL]||J[T0.ATTR_URL_FULL];if(Q&&typeof Q==="string")Y=Y.set(Bu,Q);return Y}function eI0(Z){let J=n.trace.getSpan(Z);return J&&n.isSpanContextValid(J.spanContext())?J:void 0}function bY(Z,J){if(!Z)return J;let X=HZ(Z),$=HZ(J);if(!$)return Z;let Y={...X};return Object.entries($).forEach(([Q,W])=>{if(!Y[Q])Y[Q]=W}),kW(Y)}function uu(Z,J){let X=Zy0(Z),$=J?.statusCode,Y=qY($);g6({category:"http",data:{status_code:$,...X},type:"http",level:Y},{event:"response",request:Z,response:J})}function cu(Z,J){let X=Jy0(Z),{tracePropagationTargets:$,propagateTraceparent:Y}=u()?.getOptions()||{},Q=fY(X,$,J)?pJ({propagateTraceparent:Y}):void 0;if(!Q)return;let{"sentry-trace":W,baggage:K,traceparent:z}=Q;if(W&&!Z.getHeader("sentry-trace"))try{Z.setHeader("sentry-trace",W),_0&&A.log(Z5,"Added sentry-trace header to outgoing request")}catch(G){_0&&A.error(Z5,"Failed to add sentry-trace header to outgoing request:",a8(G)?G.message:"Unknown error")}if(z&&!Z.getHeader("traceparent"))try{Z.setHeader("traceparent",z),_0&&A.log(Z5,"Added traceparent header to outgoing request")}catch(G){_0&&A.error(Z5,"Failed to add traceparent header to outgoing request:",a8(G)?G.message:"Unknown error")}if(K){let G=bY(Z.getHeader("baggage"),K);if(G)try{Z.setHeader("baggage",G),_0&&A.log(Z5,"Added baggage header to outgoing request")}catch(H){_0&&A.error(Z5,"Failed to add baggage header to outgoing request:",a8(H)?H.message:"Unknown error")}}}function Zy0(Z){try{let J=Z.getHeader("host")||Z.host,X=new URL(Z.path,`${Z.protocol}//${J}`),$=n9(X.toString()),Y={url:o9($),"http.method":Z.method||"GET"};if($.search)Y["http.query"]=$.search;if($.hash)Y["http.fragment"]=$.hash;return Y}catch{return{}}}function lu(Z){return{method:Z.method,protocol:Z.protocol,host:Z.host,hostname:Z.host,path:Z.path,headers:Z.getHeaders()}}function Jy0(Z){let J=Z.getHeader("host")||Z.host,X=Z.protocol,$=Z.path;return`${X}//${J}${$}`}class LX extends gY.InstrumentationBase{constructor(Z={}){super(Z5,N0,Z);this._propagationDecisionMap=new j6(100),this._ignoreOutgoingRequestsMap=new WeakMap}init(){let Z=!1,J=(W)=>{let K=W;this._onOutgoingRequestFinish(K.request,K.response)},X=(W)=>{let K=W;this._onOutgoingRequestFinish(K.request,void 0)},$=(W)=>{let K=W;this._onOutgoingRequestCreated(K.request)},Y=(W)=>{if(Z)return W;if(Z=!0,AL("http.client.response.finish",J),AL("http.client.request.error",X),this.getConfig().propagateTraceInOutgoingRequests)AL("http.client.request.created",$);return W},Q=()=>{TL("http.client.response.finish",J),TL("http.client.request.error",X),TL("http.client.request.created",$)};return[new gY.InstrumentationNodeModuleDefinition("http",["*"],Y,Q),new gY.InstrumentationNodeModuleDefinition("https",["*"],Y,Q)]}_onOutgoingRequestFinish(Z,J){_0&&A.log(Z5,"Handling finished outgoing request");let X=this.getConfig().breadcrumbs,$=typeof X>"u"?!0:X,Y=this._ignoreOutgoingRequestsMap.get(Z)??this._shouldIgnoreOutgoingRequest(Z);if(this._ignoreOutgoingRequestsMap.set(Z,Y),$&&!Y)uu(Z,J)}_onOutgoingRequestCreated(Z){let J=this._ignoreOutgoingRequestsMap.get(Z)??this._shouldIgnoreOutgoingRequest(Z);if(this._ignoreOutgoingRequestsMap.set(Z,J),J)return;cu(Z,this._propagationDecisionMap)}_shouldIgnoreOutgoingRequest(Z){if(iu.isTracingSuppressed(pu.context.active()))return!0;let J=this.getConfig().ignoreOutgoingRequests;if(!J)return!1;let X=lu(Z),$=yY(Z);return J($,X)}}var nu="Http",Xy0=a(`${nu}.sentry`,(Z)=>{return new LX(Z)}),ou=S((Z={})=>{let J={sessions:Z.trackIncomingRequestsAsSessions,sessionFlushingDelayMS:Z.sessionFlushingDelayMS,ignoreRequestBody:Z.ignoreIncomingRequestBody,maxRequestBodySize:Z.maxIncomingRequestBodySize},X={ignoreIncomingRequests:Z.ignoreIncomingRequests,ignoreStaticAssets:Z.ignoreStaticAssets,ignoreStatusCodes:Z.dropSpansForIncomingRequestStatusCodes},$={breadcrumbs:Z.breadcrumbs,propagateTraceInOutgoingRequests:!0,ignoreOutgoingRequests:Z.ignoreOutgoingRequests},Y=YX(J),Q=WX(X),W=Z.spans??!1,K=Z.disableIncomingRequestSpans??!1,z=W&&!K;return{name:nu,setup(G){if(z)Q.setup(G)},setupOnce(){Y.setupOnce(),Xy0($)},processEvent(G){return Q.processEvent(G)}}});var ru=k(f(),1),su=k(H1(),1),tu=k(H0(),1);import*as DX from"diagnostics_channel";var G7=NB(process.versions.node),s5=G7.major,mY=G7.minor;var hK="sentry-trace",qL="baggage",au=/baggage: (.*)\r\n/;class _X extends tu.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-node-fetch",N0,Z);this._channelSubs=[],this._propagationDecisionMap=new j6(100),this._ignoreOutgoingRequestsMap=new WeakMap}init(){return}disable(){super.disable(),this._channelSubs.forEach((Z)=>Z.unsubscribe()),this._channelSubs=[]}enable(){if(super.enable(),this._channelSubs=this._channelSubs||[],this._channelSubs.length>0)return;this._subscribeToChannel("undici:request:create",this._onRequestCreated.bind(this)),this._subscribeToChannel("undici:request:headers",this._onResponseHeaders.bind(this))}_onRequestCreated({request:Z}){if(this.getConfig().enabled===!1)return;let $=this._shouldIgnoreOutgoingRequest(Z);if(this._ignoreOutgoingRequestsMap.set(Z,$),$)return;let Y=CL(Z.origin,Z.path),{tracePropagationTargets:Q,propagateTraceparent:W}=u()?.getOptions()||{},K=fY(Y,Q,this._propagationDecisionMap)?pJ({propagateTraceparent:W}):void 0;if(!K)return;let{"sentry-trace":z,baggage:G,traceparent:H}=K;if(Array.isArray(Z.headers)){let V=Z.headers;if(z&&!V.includes(hK))V.push(hK,z);if(H&&!V.includes("traceparent"))V.push("traceparent",H);let F=V.findIndex((B)=>B===qL);if(G&&F===-1)V.push(qL,G);else if(G){let B=V[F+1],U=bY(B,G);if(U)V[F+1]=U}}else{let V=Z.headers;if(z&&!V.includes(`${hK}:`))Z.headers+=`${hK}: ${z}\r
41
41
  `;if(H&&!V.includes("traceparent:"))Z.headers+=`traceparent: ${H}\r
42
42
  `;let F=Z.headers.match(au)?.[1];if(G&&!F)Z.headers+=`${qL}: ${G}\r
43
43
  `;else if(G){let B=bY(F,G);if(B)Z.headers=Z.headers.replace(au,`baggage: ${B}\r
@@ -50,7 +50,7 @@ Event: ${f9(Z)}`),!0}return!1}function oC0(Z,J){if(!J?.length)return!1;return rW
50
50
  `;let K=hc($);$.write(`${W}\r
51
51
  `);let{connect:z,buffered:G}=await K;if(Z.emit("proxyConnect",z),this.emit("proxyConnect",z,Z),z.statusCode===200){if(Z.once("socket",hS0),J.secureEndpoint){pY("Upgrading socket connection to TLS");let V=J.servername||J.host;return gL.connect({...fc(J,"host","path","port"),socket:$,servername:t5.isIP(V)?void 0:V})}return $}$.destroy();let H=new t5.Socket({writable:!1});return H.readable=!0,Z.once("socket",(V)=>{pY("Replaying proxy buffer for failed request"),V.push(G),V.push(null)}),H}}cK.__initStatic();function hS0(Z){Z.resume()}function fc(Z,...J){let X={},$;for($ in Z)if(!J.includes($))X[$]=Z[$];return X}var dS0=32768;function uS0(Z){return new gS0({read(){this.push(Z),this.push(null)}})}function mL(Z){let J;try{J=new URL(Z.url)}catch(z){return y1(()=>{console.warn("[@sentry/node]: Invalid dsn or tunnel option, will not send any events. The tunnel option must be a full URL when used.")}),_Z(Z,()=>Promise.resolve({}))}let X=J.protocol==="https:",$=cS0(J,Z.proxy||(X?process.env.https_proxy:void 0)||process.env.http_proxy),Y=X?bS0:fS0,Q=Z.keepAlive===void 0?!1:Z.keepAlive,W=$?new cK($):new Y.Agent({keepAlive:Q,maxSockets:30,timeout:2000}),K=lS0(Z,Z.httpModule??Y,W);return _Z(Z,K)}function cS0(Z,J){let{no_proxy:X}=process.env;if(X?.split(",").some((Y)=>Z.host.endsWith(Y)||Z.hostname.endsWith(Y)))return;else return J}function lS0(Z,J,X){let{hostname:$,pathname:Y,port:Q,protocol:W,search:K}=new URL(Z.url);return function(G){return new Promise((H,V)=>{p9(()=>{let F=uS0(G.body),B={...Z.headers};if(G.body.length>dS0)B["content-encoding"]="gzip",F=F.pipe(mS0());let U=$.startsWith("["),D=J.request({method:"POST",agent:X,headers:B,hostname:U?$.slice(1,-1):$,path:`${Y}${K}`,port:Q,protocol:W,ca:Z.caCerts},(_)=>{_.on("data",()=>{}),_.on("end",()=>{}),_.setEncoding("utf8");let O=_.headers["retry-after"]??null,w=_.headers["x-sentry-rate-limits"]??null;H({statusCode:_.statusCode,headers:{"retry-after":O,"x-sentry-rate-limits":Array.isArray(w)?w[0]||null:w}})});D.on("error",V),F.pipe(D)})})}}var pS0=new Set(["false","f","n","no","off","0"]),iS0=new Set(["true","t","y","yes","on","1"]);function lK(Z,J){let X=String(Z).toLowerCase();if(pS0.has(X))return!1;if(iS0.has(X))return!0;return J?.strict?null:Boolean(Z)}import{posix as nS0,sep as oS0}from"path";function bc(Z){return Z.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}function dL(Z=process.argv[1]?UU(process.argv[1]):process.cwd(),J=oS0==="\\"){let X=J?bc(Z):Z;return($)=>{if(!$)return;let Y=J?bc($):$,{dir:Q,base:W,ext:K}=nS0.parse(Y);if(K===".js"||K===".mjs"||K===".cjs")W=W.slice(0,K.length*-1);let z=decodeURIComponent(W);if(!Q)Q=".";let G=Q.lastIndexOf("/node_modules");if(G>-1)return`${Q.slice(G+14).replace(/\//g,".")}:${z}`;if(Q.startsWith(X)){let H=Q.slice(X.length+1).replace(/\//g,".");return H?`${H}:${z}`:z}return z}}function uL(Z){if(process.env.SENTRY_RELEASE)return process.env.SENTRY_RELEASE;if(Q0.SENTRY_RELEASE?.id)return Q0.SENTRY_RELEASE.id;let J=process.env.GITHUB_SHA||process.env.CI_MERGE_REQUEST_SOURCE_BRANCH_SHA||process.env.CI_BUILD_REF||process.env.CI_COMMIT_SHA||process.env.BITBUCKET_COMMIT,X=process.env.APPVEYOR_PULL_REQUEST_HEAD_COMMIT||process.env.APPVEYOR_REPO_COMMIT||process.env.CODEBUILD_RESOLVED_SOURCE_VERSION||process.env.AWS_COMMIT_ID||process.env.BUILD_SOURCEVERSION||process.env.GIT_CLONE_COMMIT_HASH||process.env.BUDDY_EXECUTION_REVISION||process.env.BUILDKITE_COMMIT||process.env.CIRCLE_SHA1||process.env.CIRRUS_CHANGE_IN_REPO||process.env.CF_REVISION||process.env.CM_COMMIT||process.env.CF_PAGES_COMMIT_SHA||process.env.DRONE_COMMIT_SHA||process.env.FC_GIT_COMMIT_SHA||process.env.HEROKU_TEST_RUN_COMMIT_VERSION||process.env.HEROKU_SLUG_COMMIT||process.env.RAILWAY_GIT_COMMIT_SHA||process.env.RENDER_GIT_COMMIT||process.env.SEMAPHORE_GIT_SHA||process.env.TRAVIS_PULL_REQUEST_SHA||process.env.VERCEL_GIT_COMMIT_SHA||process.env.VERCEL_GITHUB_COMMIT_SHA||process.env.VERCEL_GITLAB_COMMIT_SHA||process.env.VERCEL_BITBUCKET_COMMIT_SHA||process.env.ZEIT_GITHUB_COMMIT_SHA||process.env.ZEIT_GITLAB_COMMIT_SHA||process.env.ZEIT_BITBUCKET_COMMIT_SHA,$=process.env.CI_COMMIT_ID||process.env.SOURCE_COMMIT||process.env.SOURCE_VERSION||process.env.GIT_COMMIT||process.env.COMMIT_REF||process.env.BUILD_VCS_NUMBER||process.env.CI_COMMIT_SHA;return J||X||$||Z}var cL=CW(bU(dL()));var mc=k(f(),1),dc=k(H0(),1);import*as gc from"os";import{threadId as aS0,isMainThread as rS0}from"worker_threads";var sS0=60000;class pK extends tW{constructor(Z){let J=Z.includeServerName===!1?void 0:Z.serverName||global.process.env.SENTRY_NAME||gc.hostname(),X={...Z,platform:"node",runtime:{name:"node",version:global.process.version},serverName:J};if(Z.openTelemetryInstrumentations)dc.registerInstrumentations({instrumentations:Z.openTelemetryInstrumentations});i5(X,"node"),A.log(`Initializing Sentry: process: ${process.pid}, thread: ${rS0?"main":`worker-${aS0}`}.`);super(X);if(this.getOptions().enableLogs){if(this._logOnExitFlushListener=()=>{VY(this)},J)this.on("beforeCaptureLog",($)=>{$.attributes={...$.attributes,"server.address":J}});process.on("beforeExit",this._logOnExitFlushListener)}}get tracer(){if(this._tracer)return this._tracer;let Z="@sentry/node",J=N0,X=mc.trace.getTracer(Z,J);return this._tracer=X,X}async flush(Z){if(await this.traceProvider?.forceFlush(),this.getOptions().sendClientReports)this._flushOutcomes();return super.flush(Z)}async close(Z){if(this._clientReportInterval)clearInterval(this._clientReportInterval);if(this._clientReportOnExitFlushListener)process.off("beforeExit",this._clientReportOnExitFlushListener);if(this._logOnExitFlushListener)process.off("beforeExit",this._logOnExitFlushListener);let J=await super.close(Z);if(this.traceProvider)await this.traceProvider.shutdown();return J}startClientReportTracking(){let Z=this.getOptions();if(Z.sendClientReports)this._clientReportOnExitFlushListener=()=>{this._flushOutcomes()},this._clientReportInterval=setInterval(()=>{_0&&A.log("Flushing client reports based on interval."),this._flushOutcomes()},Z.clientReportFlushInterval??sS0).unref(),process.on("beforeExit",this._clientReportOnExitFlushListener)}_setupIntegrations(){KU(),super._setupIntegrations()}_getTraceInfoFromScope(Z){if(!Z)return[void 0,void 0];return yu(this,Z)}}var uc=k(nF(),1);import*as cc from"module";function lL(){if(!Dc())return;if(!Q0._sentryEsmLoaderHookRegistered){Q0._sentryEsmLoaderHookRegistered=!0;try{let{addHookMessagePort:Z}=uc.createAddHookMessageChannel();cc.register("import-in-the-middle/hook.mjs",import.meta.url,{data:{addHookMessagePort:Z,include:[]},transferList:[Z]})}catch(Z){A.warn("Failed to register 'import-in-the-middle' hook",Z)}}}function iK(){return[oJ(),nJ(),aJ(),rJ(),SL(),sJ(),ou(),eu(),MX(),AX(),wX(),PL(),OX(),xL(),vc(),jX()]}function pL(Z={}){return tS0(Z,iK)}function tS0(Z={},J){let X=eS0(Z,J);if(X.debug===!0)if(_0)A.enable();else y1(()=>{console.warn("[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.")});if(X.registerEsmLoaderHooks!==!1)lL();if(xu(),u0().update(X.initialScope),X.spotlight&&!X.integrations.some(({name:Q})=>Q===IL))X.integrations.push(yL({sidecarUrl:typeof X.spotlight==="string"?X.spotlight:void 0}));i5(X,"node-core");let Y=new pK(X);if(u0().setClient(Y),Y.init(),Q0._sentryInjectLoaderHookRegister?.(),A.log(`SDK initialized from ${uY()?"CommonJS":"ESM"}`),Y.startClientReportTracking(),Xk0(),Ou(Y),ku(Y),process.env.VERCEL)process.on("SIGTERM",async()=>{await Y.flush(200)});return Y}function nK(){if(!_0)return;let Z=Au(),J=["SentryContextManager","SentryPropagator"];if(L1())J.push("SentrySpanProcessor");for(let X of J)if(!Z.includes(X))A.error(`You have to set up the ${X}. Without this, the OpenTelemetry & Sentry integration will not work properly.`);if(!Z.includes("SentrySampler"))A.warn("You have to set up the SentrySampler. Without this, the OpenTelemetry & Sentry integration may still work, but sample rates set for the Sentry SDK will not be respected. If you use a custom sampler, make sure to use `wrapSamplingDecision`.")}function eS0(Z,J){let X=Zk0(Z.release),$;if(Z.spotlight===!1)$=!1;else if(typeof Z.spotlight==="string")$=Z.spotlight;else{let z=lK(process.env.SENTRY_SPOTLIGHT,{strict:!0}),G=z===null&&process.env.SENTRY_SPOTLIGHT?process.env.SENTRY_SPOTLIGHT:void 0;$=Z.spotlight===!0?G??!0:z??G}let Y=Jk0(Z.tracesSampleRate),Q={...Z,dsn:Z.dsn??process.env.SENTRY_DSN,environment:Z.environment??process.env.SENTRY_ENVIRONMENT,sendClientReports:Z.sendClientReports??!0,transport:Z.transport??mL,stackParser:HB(Z.stackParser||cL),release:X,tracesSampleRate:Y,spotlight:$,debug:lK(Z.debug??process.env.SENTRY_DEBUG)},W=Z.integrations,K=Z.defaultIntegrations??J(Q);return{...Q,integrations:sB({defaultIntegrations:K,integrations:W})}}function Zk0(Z){if(Z!==void 0)return Z;let J=uL();if(J!==void 0)return J;return}function Jk0(Z){if(Z!==void 0)return Z;let J=process.env.SENTRY_TRACES_SAMPLE_RATE;if(!J)return;let X=parseFloat(J);return isFinite(X)?X:void 0}function Xk0(){if(lK(process.env.SENTRY_USE_ENVIRONMENT)!==!1){let Z=process.env.SENTRY_TRACE,J=process.env.SENTRY_BAGGAGE,X=VZ(Z,J);u0().setPropagationContext(X)}}function i0(Z,J){Z.setAttribute(X0,J)}var iL="Http",lc="@opentelemetry_sentry-patched/instrumentation-http",$k0=a(`${iL}.sentry`,(Z)=>{return new LX(Z)}),Yk0=a(iL,(Z)=>{let J=new ic.HttpInstrumentation({...Z,disableIncomingRequestInstrumentation:!0});try{J._diag=pc.diag.createComponentLogger({namespace:lc}),J.instrumentationName=lc}catch{}return J});function Qk0(Z,J={}){if(typeof Z.spans==="boolean")return Z.spans;if(J.skipOpenTelemetrySetup)return!1;if(!L1(J)&&G7.major>=22)return!1;return!0}var iY=S((Z={})=>{let J=Z.spans??!0,X=Z.disableIncomingRequestSpans,$={sessions:Z.trackIncomingRequestsAsSessions,sessionFlushingDelayMS:Z.sessionFlushingDelayMS,ignoreRequestBody:Z.ignoreIncomingRequestBody,maxRequestBodySize:Z.maxIncomingRequestBodySize},Y={ignoreIncomingRequests:Z.ignoreIncomingRequests,ignoreStaticAssets:Z.ignoreStaticAssets,ignoreStatusCodes:Z.dropSpansForIncomingRequestStatusCodes,instrumentation:Z.instrumentation,onSpanCreated:Z.incomingRequestSpanHook},Q=YX($),W=WX(Y),K=J&&!X;return{name:iL,setup(z){let G=z.getOptions();if(K&&L1(G))W.setup(z)},setupOnce(){let z=u()?.getOptions()||{},G=Qk0(Z,z);Q.setupOnce();let H={breadcrumbs:Z.breadcrumbs,propagateTraceInOutgoingRequests:!G,ignoreOutgoingRequests:Z.ignoreOutgoingRequests};if($k0(H),G){let V=Wk0(Z);Yk0(V)}},processEvent(z){return W.processEvent(z)}}});function Wk0(Z={}){return{ignoreOutgoingRequestHook:(X)=>{let $=yY(X);if(!$)return!1;let Y=Z.ignoreOutgoingRequests;if(Y?.($,X))return!0;return!1},requireParentforOutgoingSpans:!1,requestHook:(X,$)=>{i0(X,"auto.http.otel.http"),Z.instrumentation?.requestHook?.(X,$)},responseHook:(X,$)=>{Z.instrumentation?.responseHook?.(X,$)},applyCustomAttributesOnSpan:(X,$,Y)=>{Z.instrumentation?.applyCustomAttributesOnSpan?.(X,$,Y)}}}var Xl=k(Jl(),1);var $l="NodeFetch",Vk0=a($l,Xl.UndiciInstrumentation,(Z)=>{return Dk0(Z)}),Fk0=a(`${$l}.sentry`,_X,(Z)=>{return Z}),Bk0=(Z={})=>{return{name:"NodeFetch",setupOnce(){if(Lk0(Z,u()?.getOptions()))Vk0(Z);Fk0(Z)}}},oY=S(Bk0);function Uk0(Z,J="/"){let X=`${Z}`;if(X.endsWith("/")&&J.startsWith("/"))return`${X}${J.slice(1)}`;if(!X.endsWith("/")&&!J.startsWith("/"))return`${X}/${J.slice(1)}`;return`${X}${J}`}function Lk0(Z,J={}){return typeof Z.spans==="boolean"?Z.spans:!J.skipOpenTelemetrySetup&&L1(J)}function Dk0(Z={}){return{requireParentforSpans:!1,ignoreRequestHook:(X)=>{let $=Uk0(X.origin,X.path),Y=Z.ignoreOutgoingRequests;return!!(Y&&$&&Y($))},startSpanHook:()=>{return{[X0]:"auto.http.otel.node_fetch"}},requestHook:Z.requestHook,responseHook:Z.responseHook}}var Cl=k(ql(),1);var N1=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;var Nl="Express";function dk0(Z){i0(Z,"auto.http.otel.express");let J=J0(Z).data,X=J["express.type"];if(X)Z.setAttribute(K0,`${X}.express`);let $=J["express.name"];if(typeof $==="string")Z.updateName($)}function uk0(Z,J){if(R0()===B6())return N1&&A.warn("Isolation scope is still default isolation scope - skipping setting transactionName"),J;if(Z.layerType==="request_handler"){let X=Z.request,$=X.method?X.method.toUpperCase():"GET";R0().setTransactionName(`${$} ${Z.route}`)}return J}var Rl=a(Nl,()=>new Cl.ExpressInstrumentation({requestHook:(Z)=>dk0(Z),spanNameHook:(Z,J)=>uk0(Z,J)})),ck0=()=>{return{name:Nl,setupOnce(){Rl()}}},Pl=S(ck0);import*as K2 from"diagnostics_channel";var k1=k(f(),1),Jz=k(H1(),1),Qp=k(H0(),1),d1=k(p0(),1);import Zp from"diagnostics_channel";var al=k(dl(),1);var sY=(Z)=>{if(typeof Z!=="string")throw TypeError("invalid pattern");if(Z.length>65536)throw TypeError("pattern is too long")};var sk0={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},tY=(Z)=>Z.replace(/[[\]\\-]/g,"\\$&"),tk0=(Z)=>Z.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),ul=(Z)=>Z.join(""),cl=(Z,J)=>{let X=J;if(Z.charAt(X)!=="[")throw Error("not in a brace expression");let $=[],Y=[],Q=X+1,W=!1,K=!1,z=!1,G=!1,H=X,V="";Z:while(Q<Z.length){let D=Z.charAt(Q);if((D==="!"||D==="^")&&Q===X+1){G=!0,Q++;continue}if(D==="]"&&W&&!z){H=Q+1;break}if(W=!0,D==="\\"){if(!z){z=!0,Q++;continue}}if(D==="["&&!z){for(let[_,[O,w,j]]of Object.entries(sk0))if(Z.startsWith(_,Q)){if(V)return["$.",!1,Z.length-X,!0];if(Q+=_.length,j)Y.push(O);else $.push(O);K=K||w;continue Z}}if(z=!1,V){if(D>V)$.push(tY(V)+"-"+tY(D));else if(D===V)$.push(tY(D));V="",Q++;continue}if(Z.startsWith("-]",Q+1)){$.push(tY(D+"-")),Q+=2;continue}if(Z.startsWith("-",Q+1)){V=D,Q+=2;continue}$.push(tY(D)),Q++}if(H<Q)return["",!1,0,!1];if(!$.length&&!Y.length)return["$.",!1,Z.length-X,!0];if(Y.length===0&&$.length===1&&/^\\?.$/.test($[0])&&!G){let D=$[0].length===2?$[0].slice(-1):$[0];return[tk0(D),!1,H-X,!1]}let F="["+(G?"^":"")+ul($)+"]",B="["+(G?"":"^")+ul(Y)+"]";return[$.length&&Y.length?"("+F+"|"+B+")":$.length?F:B,K,H-X,!0]};var H7=(Z,{windowsPathsNoEscape:J=!1}={})=>{return J?Z.replace(/\[([^\/\\])\]/g,"$1"):Z.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1")};var ek0=new Set(["!","?","+","*","@"]),ll=(Z)=>ek0.has(Z),Zx0="(?!(?:^|/)\\.\\.?(?:$|/))",eK="(?!\\.)",Jx0=new Set(["[","."]),Xx0=new Set(["..","."]),$x0=new Set("().*{}+?[]^$\\!"),Yx0=(Z)=>Z.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),X2="[^/]",pl=X2+"*?",il=X2+"+?";class H4{type;#J;#X;#G=!1;#$=[];#Y;#B;#Q;#H=!1;#K;#W;#Z=!1;constructor(Z,J,X={}){if(this.type=Z,Z)this.#X=!0;if(this.#Y=J,this.#J=this.#Y?this.#Y.#J:this,this.#K=this.#J===this?X:this.#J.#K,this.#Q=this.#J===this?[]:this.#J.#Q,Z==="!"&&!this.#J.#H)this.#Q.push(this);this.#B=this.#Y?this.#Y.#$.length:0}get hasMagic(){if(this.#X!==void 0)return this.#X;for(let Z of this.#$){if(typeof Z==="string")continue;if(Z.type||Z.hasMagic)return this.#X=!0}return this.#X}toString(){if(this.#W!==void 0)return this.#W;if(!this.type)return this.#W=this.#$.map((Z)=>String(Z)).join("");else return this.#W=this.type+"("+this.#$.map((Z)=>String(Z)).join("|")+")"}#L(){if(this!==this.#J)throw Error("should only call on root");if(this.#H)return this;this.toString(),this.#H=!0;let Z;while(Z=this.#Q.pop()){if(Z.type!=="!")continue;let J=Z,X=J.#Y;while(X){for(let $=J.#B+1;!X.type&&$<X.#$.length;$++)for(let Y of Z.#$){if(typeof Y==="string")throw Error("string part in extglob AST??");Y.copyIn(X.#$[$])}J=X,X=J.#Y}}return this}push(...Z){for(let J of Z){if(J==="")continue;if(typeof J!=="string"&&!(J instanceof H4&&J.#Y===this))throw Error("invalid part: "+J);this.#$.push(J)}}toJSON(){let Z=this.type===null?this.#$.slice().map((J)=>typeof J==="string"?J:J.toJSON()):[this.type,...this.#$.map((J)=>J.toJSON())];if(this.isStart()&&!this.type)Z.unshift([]);if(this.isEnd()&&(this===this.#J||this.#J.#H&&this.#Y?.type==="!"))Z.push({});return Z}isStart(){if(this.#J===this)return!0;if(!this.#Y?.isStart())return!1;if(this.#B===0)return!0;let Z=this.#Y;for(let J=0;J<this.#B;J++){let X=Z.#$[J];if(!(X instanceof H4&&X.type==="!"))return!1}return!0}isEnd(){if(this.#J===this)return!0;if(this.#Y?.type==="!")return!0;if(!this.#Y?.isEnd())return!1;if(!this.type)return this.#Y?.isEnd();let Z=this.#Y?this.#Y.#$.length:0;return this.#B===Z-1}copyIn(Z){if(typeof Z==="string")this.push(Z);else this.push(Z.clone(this))}clone(Z){let J=new H4(this.type,Z);for(let X of this.#$)J.copyIn(X);return J}static#D(Z,J,X,$){let Y=!1,Q=!1,W=-1,K=!1;if(J.type===null){let F=X,B="";while(F<Z.length){let U=Z.charAt(F++);if(Y||U==="\\"){Y=!Y,B+=U;continue}if(Q){if(F===W+1){if(U==="^"||U==="!")K=!0}else if(U==="]"&&!(F===W+2&&K))Q=!1;B+=U;continue}else if(U==="["){Q=!0,W=F,K=!1,B+=U;continue}if(!$.noext&&ll(U)&&Z.charAt(F)==="("){J.push(B),B="";let D=new H4(U,J);F=H4.#D(Z,D,F,$),J.push(D);continue}B+=U}return J.push(B),F}let z=X+1,G=new H4(null,J),H=[],V="";while(z<Z.length){let F=Z.charAt(z++);if(Y||F==="\\"){Y=!Y,V+=F;continue}if(Q){if(z===W+1){if(F==="^"||F==="!")K=!0}else if(F==="]"&&!(z===W+2&&K))Q=!1;V+=F;continue}else if(F==="["){Q=!0,W=z,K=!1,V+=F;continue}if(ll(F)&&Z.charAt(z)==="("){G.push(V),V="";let B=new H4(F,G);G.push(B),z=H4.#D(Z,B,z,$);continue}if(F==="|"){G.push(V),V="",H.push(G),G=new H4(null,J);continue}if(F===")"){if(V===""&&J.#$.length===0)J.#Z=!0;return G.push(V),V="",J.push(...H,G),z}V+=F}return J.type=null,J.#X=void 0,J.#$=[Z.substring(X-1)],z}static fromGlob(Z,J={}){let X=new H4(null,void 0,J);return H4.#D(Z,X,0,J),X}toMMPattern(){if(this!==this.#J)return this.#J.toMMPattern();let Z=this.toString(),[J,X,$,Y]=this.toRegExpSource();if(!($||this.#X||this.#K.nocase&&!this.#K.nocaseMagicOnly&&Z.toUpperCase()!==Z.toLowerCase()))return X;let W=(this.#K.nocase?"i":"")+(Y?"u":"");return Object.assign(new RegExp(`^${J}$`,W),{_src:J,_glob:Z})}get options(){return this.#K}toRegExpSource(Z){let J=Z??!!this.#K.dot;if(this.#J===this)this.#L();if(!this.type){let K=this.isStart()&&this.isEnd(),z=this.#$.map((F)=>{let[B,U,D,_]=typeof F==="string"?H4.#V(F,this.#X,K):F.toRegExpSource(Z);return this.#X=this.#X||D,this.#G=this.#G||_,B}).join(""),G="";if(this.isStart()){if(typeof this.#$[0]==="string"){if(!(this.#$.length===1&&Xx0.has(this.#$[0]))){let B=Jx0,U=J&&B.has(z.charAt(0))||z.startsWith("\\.")&&B.has(z.charAt(2))||z.startsWith("\\.\\.")&&B.has(z.charAt(4)),D=!J&&!Z&&B.has(z.charAt(0));G=U?Zx0:D?eK:""}}}let H="";if(this.isEnd()&&this.#J.#H&&this.#Y?.type==="!")H="(?:$|\\/)";return[G+z+H,H7(z),this.#X=!!this.#X,this.#G]}let X=this.type==="*"||this.type==="+",$=this.type==="!"?"(?:(?!(?:":"(?:",Y=this.#F(J);if(this.isStart()&&this.isEnd()&&!Y&&this.type!=="!"){let K=this.toString();return this.#$=[K],this.type=null,this.#X=void 0,[K,H7(this.toString()),!1,!1]}let Q=!X||Z||J||!eK?"":this.#F(!0);if(Q===Y)Q="";if(Q)Y=`(?:${Y})(?:${Q})*?`;let W="";if(this.type==="!"&&this.#Z)W=(this.isStart()&&!J?eK:"")+il;else{let K=this.type==="!"?"))"+(this.isStart()&&!J&&!Z?eK:"")+pl+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&Q?")":this.type==="*"&&Q?")?":`)${this.type}`;W=$+Y+K}return[W,H7(Y),this.#X=!!this.#X,this.#G]}#F(Z){return this.#$.map((J)=>{if(typeof J==="string")throw Error("string type in extglob ast??");let[X,$,Y,Q]=J.toRegExpSource(Z);return this.#G=this.#G||Q,X}).filter((J)=>!(this.isStart()&&this.isEnd())||!!J).join("|")}static#V(Z,J,X=!1){let $=!1,Y="",Q=!1;for(let W=0;W<Z.length;W++){let K=Z.charAt(W);if($){$=!1,Y+=($x0.has(K)?"\\":"")+K;continue}if(K==="\\"){if(W===Z.length-1)Y+="\\\\";else $=!0;continue}if(K==="["){let[z,G,H,V]=cl(Z,W);if(H){Y+=z,Q=Q||G,W+=H-1,J=J||V;continue}}if(K==="*"){if(X&&Z==="*")Y+=il;else Y+=pl;J=!0;continue}if(K==="?"){Y+=X2,J=!0;continue}Y+=Yx0(K)}return[Y,H7(Z),!!J,Q]}}var $2=(Z,{windowsPathsNoEscape:J=!1}={})=>{return J?Z.replace(/[?*()[\]]/g,"[$&]"):Z.replace(/[?*()[\]\\]/g,"\\$&")};var V4=(Z,J,X={})=>{if(sY(J),!X.nocomment&&J.charAt(0)==="#")return!1;return new eY(J,X).match(Z)},Qx0=/^\*+([^+@!?\*\[\(]*)$/,Wx0=(Z)=>(J)=>!J.startsWith(".")&&J.endsWith(Z),Kx0=(Z)=>(J)=>J.endsWith(Z),zx0=(Z)=>{return Z=Z.toLowerCase(),(J)=>!J.startsWith(".")&&J.toLowerCase().endsWith(Z)},Gx0=(Z)=>{return Z=Z.toLowerCase(),(J)=>J.toLowerCase().endsWith(Z)},Hx0=/^\*+\.\*+$/,Vx0=(Z)=>!Z.startsWith(".")&&Z.includes("."),Fx0=(Z)=>Z!=="."&&Z!==".."&&Z.includes("."),Bx0=/^\.\*+$/,Ux0=(Z)=>Z!=="."&&Z!==".."&&Z.startsWith("."),Lx0=/^\*+$/,Dx0=(Z)=>Z.length!==0&&!Z.startsWith("."),_x0=(Z)=>Z.length!==0&&Z!=="."&&Z!=="..",Ox0=/^\?+([^+@!?\*\[\(]*)?$/,wx0=([Z,J=""])=>{let X=rl([Z]);if(!J)return X;return J=J.toLowerCase(),($)=>X($)&&$.toLowerCase().endsWith(J)},jx0=([Z,J=""])=>{let X=sl([Z]);if(!J)return X;return J=J.toLowerCase(),($)=>X($)&&$.toLowerCase().endsWith(J)},Mx0=([Z,J=""])=>{let X=sl([Z]);return!J?X:($)=>X($)&&$.endsWith(J)},Ax0=([Z,J=""])=>{let X=rl([Z]);return!J?X:($)=>X($)&&$.endsWith(J)},rl=([Z])=>{let J=Z.length;return(X)=>X.length===J&&!X.startsWith(".")},sl=([Z])=>{let J=Z.length;return(X)=>X.length===J&&X!=="."&&X!==".."},tl=typeof process==="object"&&process?typeof process.env==="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",nl={win32:{sep:"\\"},posix:{sep:"/"}},Tx0=tl==="win32"?nl.win32.sep:nl.posix.sep;V4.sep=Tx0;var l6=Symbol("globstar **");V4.GLOBSTAR=l6;var qx0="[^/]",Cx0=qx0+"*?",Nx0="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",Rx0="(?:(?!(?:\\/|^)\\.).)*?",Px0=(Z,J={})=>(X)=>V4(X,Z,J);V4.filter=Px0;var c6=(Z,J={})=>Object.assign({},Z,J),Ex0=(Z)=>{if(!Z||typeof Z!=="object"||!Object.keys(Z).length)return V4;let J=V4;return Object.assign(($,Y,Q={})=>J($,Y,c6(Z,Q)),{Minimatch:class extends J.Minimatch{constructor(Y,Q={}){super(Y,c6(Z,Q))}static defaults(Y){return J.defaults(c6(Z,Y)).Minimatch}},AST:class extends J.AST{constructor(Y,Q,W={}){super(Y,Q,c6(Z,W))}static fromGlob(Y,Q={}){return J.AST.fromGlob(Y,c6(Z,Q))}},unescape:($,Y={})=>J.unescape($,c6(Z,Y)),escape:($,Y={})=>J.escape($,c6(Z,Y)),filter:($,Y={})=>J.filter($,c6(Z,Y)),defaults:($)=>J.defaults(c6(Z,$)),makeRe:($,Y={})=>J.makeRe($,c6(Z,Y)),braceExpand:($,Y={})=>J.braceExpand($,c6(Z,Y)),match:($,Y,Q={})=>J.match($,Y,c6(Z,Q)),sep:J.sep,GLOBSTAR:l6})};V4.defaults=Ex0;var el=(Z,J={})=>{if(sY(Z),J.nobrace||!/\{(?:(?!\{).)*\}/.test(Z))return[Z];return al.default(Z)};V4.braceExpand=el;var Ix0=(Z,J={})=>new eY(Z,J).makeRe();V4.makeRe=Ix0;var yx0=(Z,J,X={})=>{let $=new eY(J,X);if(Z=Z.filter((Y)=>$.match(Y)),$.options.nonull&&!Z.length)Z.push(J);return Z};V4.match=yx0;var ol=/[?*]|[+@!]\(.*?\)|\[|\]/,Sx0=(Z)=>Z.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");class eY{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(Z,J={}){if(sY(Z),J=J||{},this.options=J,this.pattern=Z,this.platform=J.platform||tl,this.isWindows=this.platform==="win32",this.windowsPathsNoEscape=!!J.windowsPathsNoEscape||J.allowWindowsEscape===!1,this.windowsPathsNoEscape)this.pattern=this.pattern.replace(/\\/g,"/");this.preserveMultipleSlashes=!!J.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!J.nonegate,this.comment=!1,this.empty=!1,this.partial=!!J.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=J.windowsNoMagicRoot!==void 0?J.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let Z of this.set)for(let J of Z)if(typeof J!=="string")return!0;return!1}debug(...Z){}make(){let Z=this.pattern,J=this.options;if(!J.nocomment&&Z.charAt(0)==="#"){this.comment=!0;return}if(!Z){this.empty=!0;return}if(this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],J.debug)this.debug=(...Y)=>console.error(...Y);this.debug(this.pattern,this.globSet);let X=this.globSet.map((Y)=>this.slashSplit(Y));this.globParts=this.preprocess(X),this.debug(this.pattern,this.globParts);let $=this.globParts.map((Y,Q,W)=>{if(this.isWindows&&this.windowsNoMagicRoot){let K=Y[0]===""&&Y[1]===""&&(Y[2]==="?"||!ol.test(Y[2]))&&!ol.test(Y[3]),z=/^[a-z]:/i.test(Y[0]);if(K)return[...Y.slice(0,4),...Y.slice(4).map((G)=>this.parse(G))];else if(z)return[Y[0],...Y.slice(1).map((G)=>this.parse(G))]}return Y.map((K)=>this.parse(K))});if(this.debug(this.pattern,$),this.set=$.filter((Y)=>Y.indexOf(!1)===-1),this.isWindows)for(let Y=0;Y<this.set.length;Y++){let Q=this.set[Y];if(Q[0]===""&&Q[1]===""&&this.globParts[Y][2]==="?"&&typeof Q[3]==="string"&&/^[a-z]:$/i.test(Q[3]))Q[2]="?"}this.debug(this.pattern,this.set)}preprocess(Z){if(this.options.noglobstar){for(let X=0;X<Z.length;X++)for(let $=0;$<Z[X].length;$++)if(Z[X][$]==="**")Z[X][$]="*"}let{optimizationLevel:J=1}=this.options;if(J>=2)Z=this.firstPhasePreProcess(Z),Z=this.secondPhasePreProcess(Z);else if(J>=1)Z=this.levelOneOptimize(Z);else Z=this.adjascentGlobstarOptimize(Z);return Z}adjascentGlobstarOptimize(Z){return Z.map((J)=>{let X=-1;while((X=J.indexOf("**",X+1))!==-1){let $=X;while(J[$+1]==="**")$++;if($!==X)J.splice(X,$-X)}return J})}levelOneOptimize(Z){return Z.map((J)=>{return J=J.reduce((X,$)=>{let Y=X[X.length-1];if($==="**"&&Y==="**")return X;if($===".."){if(Y&&Y!==".."&&Y!=="."&&Y!=="**")return X.pop(),X}return X.push($),X},[]),J.length===0?[""]:J})}levelTwoFileOptimize(Z){if(!Array.isArray(Z))Z=this.slashSplit(Z);let J=!1;do{if(J=!1,!this.preserveMultipleSlashes){for(let $=1;$<Z.length-1;$++){let Y=Z[$];if($===1&&Y===""&&Z[0]==="")continue;if(Y==="."||Y==="")J=!0,Z.splice($,1),$--}if(Z[0]==="."&&Z.length===2&&(Z[1]==="."||Z[1]===""))J=!0,Z.pop()}let X=0;while((X=Z.indexOf("..",X+1))!==-1){let $=Z[X-1];if($&&$!=="."&&$!==".."&&$!=="**")J=!0,Z.splice(X-1,2),X-=2}}while(J);return Z.length===0?[""]:Z}firstPhasePreProcess(Z){let J=!1;do{J=!1;for(let X of Z){let $=-1;while(($=X.indexOf("**",$+1))!==-1){let Q=$;while(X[Q+1]==="**")Q++;if(Q>$)X.splice($+1,Q-$);let W=X[$+1],K=X[$+2],z=X[$+3];if(W!=="..")continue;if(!K||K==="."||K===".."||!z||z==="."||z==="..")continue;J=!0,X.splice($,1);let G=X.slice(0);G[$]="**",Z.push(G),$--}if(!this.preserveMultipleSlashes){for(let Q=1;Q<X.length-1;Q++){let W=X[Q];if(Q===1&&W===""&&X[0]==="")continue;if(W==="."||W==="")J=!0,X.splice(Q,1),Q--}if(X[0]==="."&&X.length===2&&(X[1]==="."||X[1]===""))J=!0,X.pop()}let Y=0;while((Y=X.indexOf("..",Y+1))!==-1){let Q=X[Y-1];if(Q&&Q!=="."&&Q!==".."&&Q!=="**"){J=!0;let K=Y===1&&X[Y+1]==="**"?["."]:[];if(X.splice(Y-1,2,...K),X.length===0)X.push("");Y-=2}}}}while(J);return Z}secondPhasePreProcess(Z){for(let J=0;J<Z.length-1;J++)for(let X=J+1;X<Z.length;X++){let $=this.partsMatch(Z[J],Z[X],!this.preserveMultipleSlashes);if($){Z[J]=[],Z[X]=$;break}}return Z.filter((J)=>J.length)}partsMatch(Z,J,X=!1){let $=0,Y=0,Q=[],W="";while($<Z.length&&Y<J.length)if(Z[$]===J[Y])Q.push(W==="b"?J[Y]:Z[$]),$++,Y++;else if(X&&Z[$]==="**"&&J[Y]===Z[$+1])Q.push(Z[$]),$++;else if(X&&J[Y]==="**"&&Z[$]===J[Y+1])Q.push(J[Y]),Y++;else if(Z[$]==="*"&&J[Y]&&(this.options.dot||!J[Y].startsWith("."))&&J[Y]!=="**"){if(W==="b")return!1;W="a",Q.push(Z[$]),$++,Y++}else if(J[Y]==="*"&&Z[$]&&(this.options.dot||!Z[$].startsWith("."))&&Z[$]!=="**"){if(W==="a")return!1;W="b",Q.push(J[Y]),$++,Y++}else return!1;return Z.length===J.length&&Q}parseNegate(){if(this.nonegate)return;let Z=this.pattern,J=!1,X=0;for(let $=0;$<Z.length&&Z.charAt($)==="!";$++)J=!J,X++;if(X)this.pattern=Z.slice(X);this.negate=J}matchOne(Z,J,X=!1){let $=this.options;if(this.isWindows){let U=typeof Z[0]==="string"&&/^[a-z]:$/i.test(Z[0]),D=!U&&Z[0]===""&&Z[1]===""&&Z[2]==="?"&&/^[a-z]:$/i.test(Z[3]),_=typeof J[0]==="string"&&/^[a-z]:$/i.test(J[0]),O=!_&&J[0]===""&&J[1]===""&&J[2]==="?"&&typeof J[3]==="string"&&/^[a-z]:$/i.test(J[3]),w=D?3:U?0:void 0,j=O?3:_?0:void 0;if(typeof w==="number"&&typeof j==="number"){let[q,R]=[Z[w],J[j]];if(q.toLowerCase()===R.toLowerCase()){if(J[j]=q,j>w)J=J.slice(j);else if(w>j)Z=Z.slice(w)}}}let{optimizationLevel:Y=1}=this.options;if(Y>=2)Z=this.levelTwoFileOptimize(Z);this.debug("matchOne",this,{file:Z,pattern:J}),this.debug("matchOne",Z.length,J.length);for(var Q=0,W=0,K=Z.length,z=J.length;Q<K&&W<z;Q++,W++){this.debug("matchOne loop");var G=J[W],H=Z[Q];if(this.debug(J,G,H),G===!1)return!1;if(G===l6){this.debug("GLOBSTAR",[J,G,H]);var V=Q,F=W+1;if(F===z){this.debug("** at the end");for(;Q<K;Q++)if(Z[Q]==="."||Z[Q]===".."||!$.dot&&Z[Q].charAt(0)===".")return!1;return!0}while(V<K){var B=Z[V];if(this.debug(`
52
52
  globstar while`,Z,V,J,F,B),this.matchOne(Z.slice(V),J.slice(F),X))return this.debug("globstar found match!",V,K,B),!0;else{if(B==="."||B===".."||!$.dot&&B.charAt(0)==="."){this.debug("dot detected!",Z,V,J,F);break}this.debug("globstar swallow a segment, and continue"),V++}}if(X){if(this.debug(`
53
- >>> no match, partial?`,Z,V,J,F),V===K)return!0}return!1}let U;if(typeof G==="string")U=H===G,this.debug("string match",G,H,U);else U=G.test(H),this.debug("pattern match",G,H,U);if(!U)return!1}if(Q===K&&W===z)return!0;else if(Q===K)return X;else if(W===z)return Q===K-1&&Z[Q]==="";else throw Error("wtf?")}braceExpand(){return el(this.pattern,this.options)}parse(Z){sY(Z);let J=this.options;if(Z==="**")return l6;if(Z==="")return"";let X,$=null;if(X=Z.match(Lx0))$=J.dot?_x0:Dx0;else if(X=Z.match(Qx0))$=(J.nocase?J.dot?Gx0:zx0:J.dot?Kx0:Wx0)(X[1]);else if(X=Z.match(Ox0))$=(J.nocase?J.dot?jx0:wx0:J.dot?Mx0:Ax0)(X);else if(X=Z.match(Hx0))$=J.dot?Fx0:Vx0;else if(X=Z.match(Bx0))$=Ux0;let Y=H4.fromGlob(Z,this.options).toMMPattern();if($&&typeof Y==="object")Reflect.defineProperty(Y,"test",{value:$});return Y}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let Z=this.set;if(!Z.length)return this.regexp=!1,this.regexp;let J=this.options,X=J.noglobstar?Cx0:J.dot?Nx0:Rx0,$=new Set(J.nocase?["i"]:[]),Y=Z.map((K)=>{let z=K.map((G)=>{if(G instanceof RegExp)for(let H of G.flags.split(""))$.add(H);return typeof G==="string"?Sx0(G):G===l6?l6:G._src});return z.forEach((G,H)=>{let V=z[H+1],F=z[H-1];if(G!==l6||F===l6)return;if(F===void 0)if(V!==void 0&&V!==l6)z[H+1]="(?:\\/|"+X+"\\/)?"+V;else z[H]=X;else if(V===void 0)z[H-1]=F+"(?:\\/|"+X+")?";else if(V!==l6)z[H-1]=F+"(?:\\/|\\/"+X+"\\/)"+V,z[H+1]=l6}),z.filter((G)=>G!==l6).join("/")}).join("|"),[Q,W]=Z.length>1?["(?:",")"]:["",""];if(Y="^"+Q+Y+W+"$",this.negate)Y="^(?!"+Y+").+$";try{this.regexp=new RegExp(Y,[...$].join(""))}catch(K){this.regexp=!1}return this.regexp}slashSplit(Z){if(this.preserveMultipleSlashes)return Z.split("/");else if(this.isWindows&&/^\/\/[^\/]+/.test(Z))return["",...Z.split(/\/+/)];else return Z.split(/\/+/)}match(Z,J=this.partial){if(this.debug("match",Z,this.pattern),this.comment)return!1;if(this.empty)return Z==="";if(Z==="/"&&J)return!0;let X=this.options;if(this.isWindows)Z=Z.split("\\").join("/");let $=this.slashSplit(Z);this.debug(this.pattern,"split",$);let Y=this.set;this.debug(this.pattern,"set",Y);let Q=$[$.length-1];if(!Q)for(let W=$.length-2;!Q&&W>=0;W--)Q=$[W];for(let W=0;W<Y.length;W++){let K=Y[W],z=$;if(X.matchBase&&K.length===1)z=[Q];if(this.matchOne(z,K,J)){if(X.flipNegate)return!0;return!this.negate}}if(X.flipNegate)return!1;return this.negate}static defaults(Z){return V4.defaults(Z).Minimatch}}V4.AST=H4;V4.Minimatch=eY;V4.escape=$2;V4.unescape=H7;var Jp="@fastify/otel",xx0="0.8.0",vx0=">=4.0.0 <6",Xp=["onRequest","preParsing","preValidation","preHandler","preSerialization","onSend","onResponse","onError"],$1={HOOK_NAME:"hook.name",FASTIFY_TYPE:"fastify.type",HOOK_CALLBACK_NAME:"hook.callback.name",ROOT:"fastify.root"},V7={ROUTE:"route-hook",INSTANCE:"hook",HANDLER:"request-handler"},e5="anonymous",x4=Symbol("fastify otel instance"),F7=Symbol("fastify otel request spans"),Z3=Symbol("fastify otel request context"),$p=Symbol("fastify otel addhook original"),Yp=Symbol("fastify otel setnotfound original"),Zz=Symbol("fastify otel ignore path");class Y2 extends Qp.InstrumentationBase{constructor(Z){super(Jp,xx0,Z);if(this.servername=Z?.servername??process.env.OTEL_SERVICE_NAME??"fastify",this[Zz]=null,this._logger=k1.diag.createComponentLogger({namespace:Jp}),Z?.ignorePaths!=null||process.env.OTEL_FASTIFY_IGNORE_PATHS!=null){let J=Z?.ignorePaths??process.env.OTEL_FASTIFY_IGNORE_PATHS;if((typeof J!=="string"||J.length===0)&&typeof J!=="function")throw TypeError("ignorePaths must be a string or a function");let X=V4;this[Zz]=($)=>{if(typeof J==="function")return J($);else return X($.url,J)}}}enable(){if(this._handleInitialization===void 0&&this.getConfig().registerOnInitialization){let Z=this.plugin();this._handleInitialization=(J)=>{J.fastify.register(Z)},Zp.subscribe("fastify.initialization",this._handleInitialization)}return super.enable()}disable(){if(this._handleInitialization)Zp.unsubscribe("fastify.initialization",this._handleInitialization),this._handleInitialization=void 0;return super.disable()}init(){return[]}plugin(){let Z=this;return J[Symbol.for("skip-override")]=!0,J[Symbol.for("fastify.display-name")]="@fastify/otel",J[Symbol.for("plugin-meta")]={fastify:vx0,name:"@fastify/otel"},J;function J(X,$,Y){X.decorate(x4,Z),X.decorate($p,X.addHook),X.decorate(Yp,X.setNotFoundHandler),X.decorateRequest("opentelemetry",function(){let V=this[Z3];return{span:this[F7],tracer:Z.tracer,context:V,inject:(B,U)=>{return k1.propagation.inject(V,B,U)},extract:(B,U)=>{return k1.propagation.extract(V,B,U)}}}),X.decorateRequest(F7,null),X.decorateRequest(Z3,null),X.addHook("onRoute",function(H){if(Z[Zz]?.(H)===!0){Z._logger.debug(`Ignoring route instrumentation ${H.method} ${H.url} because it matches the ignore path`);return}for(let V of Xp)if(H[V]!=null){let F=H[V];if(typeof F==="function")H[V]=G(F,{[d1.ATTR_SERVICE_NAME]:X[x4].servername,[$1.HOOK_NAME]:`${this.pluginName} - route -> ${V}`,[$1.FASTIFY_TYPE]:V7.ROUTE,[d1.ATTR_HTTP_ROUTE]:H.url,[$1.HOOK_CALLBACK_NAME]:F.name?.length>0?F.name:e5});else if(Array.isArray(F)){let B=[];for(let U of F)B.push(G(U,{[d1.ATTR_SERVICE_NAME]:X[x4].servername,[$1.HOOK_NAME]:`${this.pluginName} - route -> ${V}`,[$1.FASTIFY_TYPE]:V7.ROUTE,[d1.ATTR_HTTP_ROUTE]:H.url,[$1.HOOK_CALLBACK_NAME]:U.name?.length>0?U.name:e5}));H[V]=B}}if(H.onSend!=null)H.onSend=Array.isArray(H.onSend)?[...H.onSend,Q]:[H.onSend,Q];else H.onSend=Q;if(H.onError!=null)H.onError=Array.isArray(H.onError)?[...H.onError,W]:[H.onError,W];else H.onError=W;H.handler=G(H.handler,{[d1.ATTR_SERVICE_NAME]:X[x4].servername,[$1.HOOK_NAME]:`${this.pluginName} - route-handler`,[$1.FASTIFY_TYPE]:V7.HANDLER,[d1.ATTR_HTTP_ROUTE]:H.url,[$1.HOOK_CALLBACK_NAME]:H.handler.name.length>0?H.handler.name:e5})}),X.addHook("onRequest",function(H,V,F){if(this[x4].isEnabled()===!1)return F();else if(this[x4][Zz]?.({url:H.url,method:H.method})===!0)return this[x4]._logger.debug(`Ignoring request ${H.method} ${H.url} because it matches the ignore path`),F();let B=k1.context.active();if(k1.trace.getSpan(B)==null)B=k1.propagation.extract(B,H.headers);let U=Jz.getRPCMetadata(B);if(H.routeOptions.url!=null&&U?.type===Jz.RPCType.HTTP)U.route=H.routeOptions.url;let D=this[x4].tracer.startSpan("request",{attributes:{[d1.ATTR_SERVICE_NAME]:X[x4].servername,[$1.ROOT]:"@fastify/otel",[d1.ATTR_HTTP_ROUTE]:H.url,[d1.ATTR_HTTP_REQUEST_METHOD]:H.method}},B);H[Z3]=k1.trace.setSpan(B,D),H[F7]=D,k1.context.with(H[Z3],()=>{F()})}),X.addHook("onResponse",function(H,V,F){let B=H[F7];if(B!=null)B.setStatus({code:k1.SpanStatusCode.OK,message:"OK"}),B.setAttributes({[d1.ATTR_HTTP_RESPONSE_STATUS_CODE]:404}),B.end();H[F7]=null,F()}),X.addHook=K,X.setNotFoundHandler=z,Y();function Q(H,V,F,B){let U=H[F7];if(U!=null){if(V.statusCode<500)U.setStatus({code:k1.SpanStatusCode.OK,message:"OK"});U.setAttributes({[d1.ATTR_HTTP_RESPONSE_STATUS_CODE]:V.statusCode}),U.end()}H[F7]=null,B(null,F)}function W(H,V,F,B){let U=H[F7];if(U!=null)U.setStatus({code:k1.SpanStatusCode.ERROR,message:F.message}),U.recordException(F);B()}function K(H,V){let F=this[$p];if(Xp.includes(H))return F.call(this,H,G(V,{[d1.ATTR_SERVICE_NAME]:X[x4].servername,[$1.HOOK_NAME]:`${this.pluginName} - ${H}`,[$1.FASTIFY_TYPE]:V7.INSTANCE,[$1.HOOK_CALLBACK_NAME]:V.name?.length>0?V.name:e5}));else return F.call(this,H,V)}function z(H,V){let F=this[Yp];if(typeof H==="function")V=G(H,{[d1.ATTR_SERVICE_NAME]:X[x4].servername,[$1.HOOK_NAME]:`${this.pluginName} - not-found-handler`,[$1.FASTIFY_TYPE]:V7.INSTANCE,[$1.HOOK_CALLBACK_NAME]:H.name?.length>0?H.name:e5}),F.call(this,V);else{if(H.preValidation!=null)H.preValidation=G(H.preValidation,{[d1.ATTR_SERVICE_NAME]:X[x4].servername,[$1.HOOK_NAME]:`${this.pluginName} - not-found-handler - preValidation`,[$1.FASTIFY_TYPE]:V7.INSTANCE,[$1.HOOK_CALLBACK_NAME]:H.preValidation.name?.length>0?H.preValidation.name:e5});if(H.preHandler!=null)H.preHandler=G(H.preHandler,{[d1.ATTR_SERVICE_NAME]:X[x4].servername,[$1.HOOK_NAME]:`${this.pluginName} - not-found-handler - preHandler`,[$1.FASTIFY_TYPE]:V7.INSTANCE,[$1.HOOK_CALLBACK_NAME]:H.preHandler.name?.length>0?H.preHandler.name:e5});V=G(V,{[d1.ATTR_SERVICE_NAME]:X[x4].servername,[$1.HOOK_NAME]:`${this.pluginName} - not-found-handler`,[$1.FASTIFY_TYPE]:V7.INSTANCE,[$1.HOOK_CALLBACK_NAME]:V.name?.length>0?V.name:e5}),F.call(this,H,V)}}function G(H,V={}){return function(...B){let U=this[x4],[D]=B;if(U.isEnabled()===!1)return H.call(this,...B);let _=D[Z3]??k1.context.active(),O=U.tracer.startSpan(`handler - ${H.name?.length>0?H.name:this.pluginName??e5}`,{attributes:V},_);return k1.context.with(k1.trace.setSpan(_,O),function(){try{let w=H.call(this,...B);if(typeof w?.then==="function")return w.then((j)=>{return O.end(),j},(j)=>{return O.setStatus({code:k1.SpanStatusCode.ERROR,message:j.message}),O.recordException(j),O.end(),Promise.reject(j)});return O.end(),w}catch(w){throw O.setStatus({code:k1.SpanStatusCode.ERROR,message:w.message}),O.recordException(w),O.end(),w}},this)}}}}}var I8=k(f(),1),$z=k(H1(),1),yZ=k(H0(),1),Hp=k(p0(),1);var Z9;(function(Z){Z.FASTIFY_NAME="fastify.name";let X="fastify.type";Z.FASTIFY_TYPE=X;let $="hook.name";Z.HOOK_NAME=$;let Y="plugin.name";Z.PLUGIN_NAME=Y})(Z9||(Z9={}));var J3;(function(Z){Z.MIDDLEWARE="middleware";let X="request_handler";Z.REQUEST_HANDLER=X})(J3||(J3={}));var X3;(function(Z){Z.MIDDLEWARE="middleware";let X="request handler";Z.REQUEST_HANDLER=X})(X3||(X3={}));var Kp=k(f(),1);var $3=Symbol("opentelemetry.instrumentation.fastify.request_active_span");function Q2(Z,J,X,$={}){let Y=J.startSpan(X,{attributes:$}),Q=Z[$3]||[];return Q.push(Y),Object.defineProperty(Z,$3,{enumerable:!1,configurable:!0,value:Q}),Y}function Xz(Z,J){let X=Z[$3]||[];if(!X.length)return;X.forEach(($)=>{if(J)$.setStatus({code:Kp.SpanStatusCode.ERROR,message:J.message}),$.recordException(J);$.end()}),delete Z[$3]}function zp(Z,J,X){let $,Y=void 0;try{if(Y=Z(),Wp(Y))Y.then((Q)=>J(void 0,Q),(Q)=>J(Q))}catch(Q){$=Q}finally{if(!Wp(Y)){if(J($,Y),$)throw $}return Y}}function Wp(Z){return typeof Z==="object"&&Z&&typeof Object.getOwnPropertyDescriptor(Z,"then")?.value==="function"||!1}var hx0="0.1.0",fx0="@sentry/instrumentation-fastify-v3",Gp="anonymous",bx0=new Set(["onTimeout","onRequest","preParsing","preValidation","preSerialization","preHandler","onSend","onResponse","onError"]);class W2 extends yZ.InstrumentationBase{constructor(Z={}){super(fx0,hx0,Z)}init(){return[new yZ.InstrumentationNodeModuleDefinition("fastify",[">=3.0.0 <4"],(Z)=>{return this._patchConstructor(Z)})]}_hookOnRequest(){let Z=this;return function(X,$,Y){if(!Z.isEnabled())return Y();Z._wrap($,"send",Z._patchSend());let Q=X,W=$z.getRPCMetadata(I8.context.active()),K=Q.routeOptions?Q.routeOptions.url:X.routerPath;if(K&&W?.type===$z.RPCType.HTTP)W.route=K;let z=X.method||"GET";R0().setTransactionName(`${z} ${K}`),Y()}}_wrapHandler(Z,J,X,$){let Y=this;return this._diag.debug("Patching fastify route.handler function"),function(...Q){if(!Y.isEnabled())return X.apply(this,Q);let W=X.name||Z||Gp,K=`${X3.MIDDLEWARE} - ${W}`,z=Q[1],G=Q2(z,Y.tracer,K,{[Z9.FASTIFY_TYPE]:J3.MIDDLEWARE,[Z9.PLUGIN_NAME]:Z,[Z9.HOOK_NAME]:J}),H=$&&Q[Q.length-1];if(H)Q[Q.length-1]=function(...V){Xz(z),H.apply(this,V)};return I8.context.with(I8.trace.setSpan(I8.context.active(),G),()=>{return zp(()=>{return X.apply(this,Q)},(V)=>{if(V instanceof Error)G.setStatus({code:I8.SpanStatusCode.ERROR,message:V.message}),G.recordException(V);if(!$)Xz(z)})})}}_wrapAddHook(){let Z=this;return this._diag.debug("Patching fastify server.addHook function"),function(J){return function(...$){let Y=$[0],Q=$[1],W=this.pluginName;if(!bx0.has(Y))return J.apply(this,$);let K=typeof $[$.length-1]==="function"&&Q.constructor.name!=="AsyncFunction";return J.apply(this,[Y,Z._wrapHandler(W,Y,Q,K)])}}}_patchConstructor(Z){let J=this;function X(...$){let Y=Z.fastify.apply(this,$);return Y.addHook("onRequest",J._hookOnRequest()),Y.addHook("preHandler",J._hookPreHandler()),gx0(),J._wrap(Y,"addHook",J._wrapAddHook()),Y}if(Z.errorCodes!==void 0)X.errorCodes=Z.errorCodes;return X.fastify=X,X.default=X,X}_patchSend(){let Z=this;return this._diag.debug("Patching fastify reply.send function"),function(X){return function(...Y){let Q=Y[0];if(!Z.isEnabled())return X.apply(this,Y);return yZ.safeExecuteInTheMiddle(()=>{return X.apply(this,Y)},(W)=>{if(!W&&Q instanceof Error)W=Q;Xz(this,W)})}}}_hookPreHandler(){let Z=this;return this._diag.debug("Patching fastify preHandler function"),function(X,$,Y){if(!Z.isEnabled())return Y();let Q=X,W=Q.routeOptions?.handler||Q.context?.handler,K=W?.name.startsWith("bound ")?W.name.substring(6):W?.name,z=`${X3.REQUEST_HANDLER} - ${K||this.pluginName||Gp}`,G={[Z9.PLUGIN_NAME]:this.pluginName,[Z9.FASTIFY_TYPE]:J3.REQUEST_HANDLER,[Hp.SEMATTRS_HTTP_ROUTE]:Q.routeOptions?Q.routeOptions.url:X.routerPath};if(K)G[Z9.FASTIFY_NAME]=K;let H=Q2($,Z.tracer,z,G);Vp(H);let{requestHook:V}=Z.getConfig();if(V)yZ.safeExecuteInTheMiddle(()=>V(H,{request:X}),(F)=>{if(F)Z._diag.error("request hook failed",F)},!0);return I8.context.with(I8.trace.setSpan(I8.context.active(),H),()=>{Y()})}}}function gx0(){let Z=u();if(Z)Z.on("spanStart",(J)=>{Vp(J)})}function Vp(Z){let J=J0(Z).data,X=J["fastify.type"];if(J[K0]||!X)return;Z.setAttributes({[X0]:"auto.http.otel.fastify",[K0]:`${X}.fastify`});let $=J["fastify.name"]||J["plugin.name"]||J["hook.name"];if(typeof $==="string"){let Y=$.replace(/^fastify -> /,"").replace(/^@fastify\/otel -> /,"");Z.updateName(Y)}}var Yz="Fastify",Bp=a(`${Yz}.v3`,()=>new W2);function mx0(){let Z=u();if(!Z)return;else return Z.getIntegrationByName(Yz)}function Fp(Z,J,X,$){let Y=mx0()?.getShouldHandleError()||Dp;if($==="diagnostics-channel")this.diagnosticsChannelExists=!0;if(this.diagnosticsChannelExists&&$==="onError-hook"){N1&&A.warn("Fastify error handler was already registered via diagnostics channel.","You can safely remove `setupFastifyErrorHandler` call and set `shouldHandleError` on the integration options.");return}if(Y(Z,J,X))V0(Z,{mechanism:{handled:!1,type:"auto.function.fastify"}})}var Up=a(`${Yz}.v5`,()=>{let Z=new Y2,J=Z.plugin();return K2.subscribe("fastify.initialization",(X)=>{let $=X.fastify;$?.register(J).after((Y)=>{if(Y)N1&&A.error("Failed to setup Fastify instrumentation",Y);else if(ux0(),$)cx0($)})}),K2.subscribe("tracing:fastify.request.handler:error",(X)=>{let{error:$,request:Y,reply:Q}=X;Fp.call(Fp,$,Y,Q,"diagnostics-channel")}),Z}),dx0=({shouldHandleError:Z})=>{let J;return{name:Yz,setupOnce(){J=Z||Dp,Bp(),Up()},getShouldHandleError(){return J},setShouldHandleError(X){J=X}}},Lp=S((Z={})=>dx0(Z));function Dp(Z,J,X){let $=X.statusCode;return $>=500||$<=299}function _p(Z){let J=J0(Z),X=J.description,$=J.data,Y=$["fastify.type"],Q=Y==="hook",W=Y===X?.startsWith("handler -"),K=X==="request"||Y==="request-handler";if($[K0]||!W&&!K&&!Q)return;let z=Q?"hook":W?"middleware":K?"request-handler":"<unknown>";Z.setAttributes({[X0]:"auto.http.otel.fastify",[K0]:`${z}.fastify`});let G=$["fastify.name"]||$["plugin.name"]||$["hook.name"];if(typeof G==="string"){let H=G.replace(/^fastify -> /,"").replace(/^@fastify\/otel -> /,"");Z.updateName(H)}}function ux0(){let Z=u();if(Z)Z.on("spanStart",(J)=>{_p(J)})}function cx0(Z){Z.addHook("onRequest",async(J,X)=>{if(J.opentelemetry){let{span:Q}=J.opentelemetry();if(Q)_p(Q)}let $=J.routeOptions?.url,Y=J.method||"GET";R0().setTransactionName(`${Y} ${$}`)})}var Zi=k(f(),1),Ji=k(ep(),1);var Xi="Graphql",$i=a(Xi,Ji.GraphQLInstrumentation,(Z)=>{let J=Qi(Z);return{...J,responseHook(X,$){if(i0(X,"auto.graphql.otel.graphql"),$.errors?.length&&!J0(X).status)X.setStatus({code:Zi.SpanStatusCode.ERROR});let Q=J0(X).data,W=Q["graphql.operation.type"],K=Q["graphql.operation.name"];if(J.useOperationNameForRootSpan&&W){let z=q1(X),H=J0(z).data[BX]||[],V=K?`${W} ${K}`:`${W}`;if(Array.isArray(H))H.push(V),z.setAttribute(BX,H);else if(typeof H==="string")z.setAttribute(BX,[H,V]);else z.setAttribute(BX,V);if(!J0(z).data["original-description"])z.setAttribute("original-description",J0(z).description);z.updateName(`${J0(z).data["original-description"]} (${wv0(H)})`)}}}}),Ov0=(Z={})=>{return{name:Xi,setupOnce(){$i(Qi(Z))}}},Yi=S(Ov0);function Qi(Z){return{ignoreResolveSpans:!0,ignoreTrivialResolveSpans:!0,useOperationNameForRootSpan:!0,...Z}}function wv0(Z){if(Array.isArray(Z)){let J=Z.slice().sort();if(J.length<=5)return J.join(", ");else return`${J.slice(0,5).join(", ")}, +${J.length-5}`}return`${Z}`}var Pi=k(Ri(),1);var Ei="Kafka",Ii=a(Ei,()=>new Pi.KafkaJsInstrumentation({consumerHook(Z){i0(Z,"auto.kafkajs.otel.consumer")},producerHook(Z){i0(Z,"auto.kafkajs.otel.producer")}})),gv0=()=>{return{name:Ei,setupOnce(){Ii()}}},yi=S(gv0);var ci=k(ui(),1);var li="LruMemoizer",pi=a(li,()=>new ci.LruMemoizerInstrumentation),cv0=()=>{return{name:li,setupOnce(){pi()}}},ii=S(cv0);var Gn=k(zn(),1);var Hn="Mongo",Vn=a(Hn,()=>new Gn.MongoDBInstrumentation({dbStatementSerializer:Qh0,responseHook(Z){i0(Z,"auto.db.otel.mongo")}}));function Qh0(Z){let J=j2(Z);return JSON.stringify(J)}function j2(Z){if(Array.isArray(Z))return Z.map((J)=>j2(J));if(Wh0(Z)){let J={};return Object.entries(Z).map(([X,$])=>[X,j2($)]).reduce((X,$)=>{if(zh0($))X[$[0]]=$[1];return X},J)}return"?"}function Wh0(Z){return typeof Z==="object"&&Z!==null&&!Kh0(Z)}function Kh0(Z){let J=!1;if(typeof Buffer<"u")J=Buffer.isBuffer(Z);return J}function zh0(Z){return Array.isArray(Z)}var Gh0=()=>{return{name:Hn,setupOnce(){Vn()}}},Fn=S(Gh0);var Sn=k(yn(),1);var kn="Mongoose",xn=a(kn,()=>new Sn.MongooseInstrumentation({responseHook(Z){i0(Z,"auto.db.otel.mongoose")}})),Ih0=()=>{return{name:kn,setupOnce(){xn()}}},vn=S(Ih0);var en=k(tn(),1);var Zo="Mysql",Jo=a(Zo,()=>new en.MySQLInstrumentation({})),Jf0=()=>{return{name:Zo,setupOnce(){Jo()}}},Xo=S(Jf0);var Mo=k(jo(),1);var Ao="Mysql2",To=a(Ao,()=>new Mo.MySQL2Instrumentation({responseHook(Z){i0(Z,"auto.db.otel.mysql2")}})),Ef0=()=>{return{name:Ao,setupOnce(){To()}}},qo=S(Ef0);var qa=k(lo(),1),Ca=k(wa(),1);var Vb0=["get","set","setex"],u2=["get","mget"],Fb0=["set","setex"];function B3(Z,J){return Z.includes(J.toLowerCase())}function c2(Z){if(B3(u2,Z))return"cache.get";else if(B3(Fb0,Z))return"cache.put";else return}function Bb0(Z,J){return J.some((X)=>Z.startsWith(X))}function Ma(Z,J){try{if(J.length===0)return;let X=(Y)=>{if(typeof Y==="string"||typeof Y==="number"||Buffer.isBuffer(Y))return[Y.toString()];else if(Array.isArray(Y))return ja(Y.map((Q)=>X(Q)));else return["<unknown>"]},$=J[0];if(B3(Vb0,Z)&&$!=null)return X($);return ja(J.map((Y)=>X(Y)))}catch{return}}function Aa(Z,J,X){if(!c2(Z))return!1;for(let $ of J)if(Bb0($,X))return!0;return!1}function Ta(Z){let J=(X)=>{try{if(Buffer.isBuffer(X))return X.byteLength;else if(typeof X==="string")return X.length;else if(typeof X==="number")return X.toString().length;else if(X===null||X===void 0)return 0;return JSON.stringify(X).length}catch{return}};return Array.isArray(Z)?Z.reduce((X,$)=>{let Y=J($);return typeof Y==="number"?X!==void 0?X+Y:Y:X},0):J(Z)}function ja(Z){let J=[],X=($)=>{$.forEach((Y)=>{if(Array.isArray(Y))X(Y);else J.push(Y)})};return X(Z),J}var wz="Redis",U3={},Na=(Z,J,X,$)=>{Z.setAttribute(X0,"auto.db.otel.redis");let Y=Ma(J,X),Q=c2(J);if(!Y||!Q||!U3.cachePrefixes||!Aa(J,Y,U3.cachePrefixes))return;let W=J0(Z).data["net.peer.name"],K=J0(Z).data["net.peer.port"];if(K&&W)Z.setAttributes({"network.peer.address":W,"network.peer.port":K});let z=Ta($);if(z)Z.setAttribute(xB,z);if(B3(u2,J)&&z!==void 0)Z.setAttribute(SB,z>0);Z.setAttributes({[K0]:Q,[kB]:Y});let G=Y.join(", ");Z.updateName(U3.maxCacheKeyLength?v9(G,U3.maxCacheKeyLength):G)},Ub0=a(`${wz}.IORedis`,()=>{return new qa.IORedisInstrumentation({responseHook:Na})}),Lb0=a(`${wz}.Redis`,()=>{return new Ca.RedisInstrumentation({responseHook:Na})}),Ra=Object.assign(()=>{Ub0(),Lb0()},{id:wz}),Db0=(Z={})=>{return{name:wz,setupOnce(){U3=Z,Ra()}}},Pa=S(Db0);var Yr=k($r(),1);var Qr="Postgres",Wr=a(Qr,()=>new Yr.PgInstrumentation({requireParentSpan:!0,requestHook(Z){i0(Z,"auto.db.otel.postgres")}})),zg0=()=>{return{name:Qr,setupOnce(){Wr()}}},Kr=S(zg0);var xX=k(f(),1),Y9=k(H0(),1),x1=k(p0(),1);var Nz="PostgresJs",zr=[">=3.0.0 <4"],Gg0=/^(SELECT|INSERT|UPDATE|DELETE|CREATE|DROP|ALTER)/i,Cz=Symbol("sentryPostgresConnectionContext"),r2=Symbol.for("sentry.instrumented.postgresjs"),Gr=Symbol.for("sentry.query.from.instrumented.sql"),Hr=a(Nz,(Z)=>new Vr({requireParentSpan:Z?.requireParentSpan??!0,requestHook:Z?.requestHook}));class Vr extends Y9.InstrumentationBase{constructor(Z){super("sentry-postgres-js",N0,Z)}init(){let Z=new Y9.InstrumentationNodeModuleDefinition("postgres",zr,(J)=>{try{return this._patchPostgres(J)}catch(X){return N1&&A.error("Failed to patch postgres module:",X),J}},(J)=>J);return["src","cf/src","cjs/src"].forEach((J)=>{Z.files.push(new Y9.InstrumentationNodeModuleFile(`postgres/${J}/query.js`,zr,this._patchQueryPrototype.bind(this),this._unpatchQueryPrototype.bind(this)))}),Z}_patchPostgres(Z){let J=typeof Z==="function",X=J?Z:Z.default;if(typeof X!=="function")return N1&&A.warn("postgres module does not export a function. Skipping instrumentation."),Z;let $=this,Y=function(...Q){let W=Reflect.construct(X,Q);if(!W||typeof W!=="function")return N1&&A.warn("postgres() did not return a valid instance"),W;return $._instrumentSqlInstance(W)};Object.setPrototypeOf(Y,X),Object.setPrototypeOf(Y.prototype,X.prototype);for(let Q of Object.getOwnPropertyNames(X))if(!["length","name","prototype"].includes(Q)){let W=Object.getOwnPropertyDescriptor(X,Q);if(W)Object.defineProperty(Y,Q,W)}if(J)return Y;else return CY(Z,"default",Y),Z}_wrapQueryMethod(Z,J,X){let $=this;return function(...Y){let Q=Reflect.apply(Z,J,Y);if(Q&&typeof Q==="object"&&"handle"in Q)$._wrapSingleQueryHandle(Q,X);return Q}}_wrapCallbackMethod(Z,J,X){let $=this;return function(...Y){let Q=X[Cz];if(typeof Y[Y.length-1]!=="function"){let H=Reflect.apply(Z,J,Y);if(H&&typeof H.then==="function")return H.then((V)=>{return $._instrumentSqlInstance(V,Q)});return H}let K=Y.length===1?Y[0]:Y[1],z=function(H){let V=$._instrumentSqlInstance(H,Q);return K(V)},G=Y.length===1?[z]:[Y[0],z];return Reflect.apply(Z,J,G)}}_setConnectionAttributes(Z,J){if(!J)return;if(J.ATTR_DB_NAMESPACE)Z.setAttribute(x1.ATTR_DB_NAMESPACE,J.ATTR_DB_NAMESPACE);if(J.ATTR_SERVER_ADDRESS)Z.setAttribute(x1.ATTR_SERVER_ADDRESS,J.ATTR_SERVER_ADDRESS);if(J.ATTR_SERVER_PORT!==void 0){let X=parseInt(J.ATTR_SERVER_PORT,10);if(!isNaN(X))Z.setAttribute(x1.ATTR_SERVER_PORT,X)}}_setOperationName(Z,J,X){if(X){Z.setAttribute(x1.ATTR_DB_OPERATION_NAME,X);return}let $=J?.match(Gg0);if($?.[1])Z.setAttribute(x1.ATTR_DB_OPERATION_NAME,$[1].toUpperCase())}_attachConnectionContext(Z,J){let X=Z;if(!X.options||typeof X.options!=="object")return;let $=X.options,Y=$.host?.[0]||"localhost",Q=$.port?.[0]||5432,W={ATTR_DB_NAMESPACE:typeof $.database==="string"&&$.database!==""?$.database:void 0,ATTR_SERVER_ADDRESS:Y,ATTR_SERVER_PORT:String(Q)};J[Cz]=W}_instrumentSqlInstance(Z,J){if(Z[r2])return Z;let X=this,$=new Proxy(Z,{apply(Y,Q,W){let K=Reflect.apply(Y,Q,W);if(K&&typeof K==="object"&&"handle"in K)X._wrapSingleQueryHandle(K,$);return K},get(Y,Q){let W=Y[Q];if(typeof Q!=="string"||typeof W!=="function")return W;if(Q==="unsafe"||Q==="file")return X._wrapQueryMethod(W,Y,$);if(Q==="begin"||Q==="reserve")return X._wrapCallbackMethod(W,Y,$);return W}});if(J)$[Cz]=J;else this._attachConnectionContext(Z,$);return Z[r2]=!0,$[r2]=!0,$}_wrapSingleQueryHandle(Z,J){if(Z.handle?.__sentryWrapped)return;Z[Gr]=!0;let X=Z.handle,$=this,Y=async function(...Q){if(!$._shouldCreateSpans())return X.apply(this,Q);let W=$._reconstructQuery(Z.strings),K=$._sanitizeSqlQuery(W);return z4({name:K||"postgresjs.query",op:"db"},(z)=>{i0(z,"auto.db.postgresjs"),z.setAttributes({[x1.ATTR_DB_SYSTEM_NAME]:"postgres",[x1.ATTR_DB_QUERY_TEXT]:K});let G=J?J[Cz]:void 0;$._setConnectionAttributes(z,G);let H=$.getConfig(),{requestHook:V}=H;if(V)Y9.safeExecuteInTheMiddle(()=>V(z,K,G),(B)=>{if(B)z.setAttribute("sentry.hook.error","requestHook failed"),N1&&A.error(`Error in requestHook for ${Nz} integration:`,B)},!0);let F=this;F.resolve=new Proxy(F.resolve,{apply:(B,U,D)=>{try{$._setOperationName(z,K,D?.[0]?.command),z.end()}catch(_){N1&&A.error("Error ending span in resolve callback:",_)}return Reflect.apply(B,U,D)}}),F.reject=new Proxy(F.reject,{apply:(B,U,D)=>{try{z.setStatus({code:A0,message:D?.[0]?.message||"unknown_error"}),z.setAttribute(x1.ATTR_DB_RESPONSE_STATUS_CODE,D?.[0]?.code||"unknown"),z.setAttribute(x1.ATTR_ERROR_TYPE,D?.[0]?.name||"unknown"),$._setOperationName(z,K),z.end()}catch(_){N1&&A.error("Error ending span in reject callback:",_)}return Reflect.apply(B,U,D)}});try{return X.apply(this,Q)}catch(B){throw z.setStatus({code:A0,message:B instanceof Error?B.message:"unknown_error"}),z.end(),B}})};Y.__sentryWrapped=!0,Z.handle=Y}_shouldCreateSpans(){let Z=this.getConfig();return xX.trace.getSpan(xX.context.active())!==void 0||!Z.requireParentSpan}_reconstructQuery(Z){if(!Z?.length)return;if(Z.length===1)return Z[0]||void 0;return Z.reduce((J,X,$)=>$===0?X:`${J}$${$}${X}`,"")}_sanitizeSqlQuery(Z){if(!Z)return"Unknown SQL Query";return Z.replace(/--.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/;\s*$/,"").replace(/\s+/g," ").trim().replace(/\bX'[0-9A-Fa-f]*'/gi,"?").replace(/\bB'[01]*'/gi,"?").replace(/'(?:[^']|'')*'/g,"?").replace(/\b0x[0-9A-Fa-f]+/gi,"?").replace(/\b(?:TRUE|FALSE)\b/gi,"?").replace(/-?\b\d+\.?\d*[eE][+-]?\d+\b/g,"?").replace(/-?\b\d+\.\d+\b/g,"?").replace(/-?\.\d+\b/g,"?").replace(/(?<!\$)-?\b\d+\b/g,"?").replace(/\bIN\b\s*\(\s*\?(?:\s*,\s*\?)*\s*\)/gi,"IN (?)").replace(/\bIN\b\s*\(\s*\$\d+(?:\s*,\s*\$\d+)*\s*\)/gi,"IN ($?)")}_patchQueryPrototype(Z){let J=this,X=Z.Query.prototype.handle;return Z.Query.prototype.handle=async function(...$){if(this[Gr])return X.apply(this,$);if(!J._shouldCreateSpans())return X.apply(this,$);let Y=J._reconstructQuery(this.strings),Q=J._sanitizeSqlQuery(Y);return z4({name:Q||"postgresjs.query",op:"db"},(W)=>{i0(W,"auto.db.postgresjs"),W.setAttributes({[x1.ATTR_DB_SYSTEM_NAME]:"postgres",[x1.ATTR_DB_QUERY_TEXT]:Q});let K=J.getConfig(),{requestHook:z}=K;if(z)Y9.safeExecuteInTheMiddle(()=>z(W,Q,void 0),(V)=>{if(V)W.setAttribute("sentry.hook.error","requestHook failed"),N1&&A.error(`Error in requestHook for ${Nz} integration:`,V)},!0);let G=this.resolve;this.resolve=new Proxy(G,{apply:(V,F,B)=>{try{J._setOperationName(W,Q,B?.[0]?.command),W.end()}catch(U){N1&&A.error("Error ending span in resolve callback:",U)}return Reflect.apply(V,F,B)}});let H=this.reject;this.reject=new Proxy(H,{apply:(V,F,B)=>{try{W.setStatus({code:A0,message:B?.[0]?.message||"unknown_error"}),W.setAttribute(x1.ATTR_DB_RESPONSE_STATUS_CODE,B?.[0]?.code||"unknown"),W.setAttribute(x1.ATTR_ERROR_TYPE,B?.[0]?.name||"unknown"),J._setOperationName(W,Q),W.end()}catch(U){N1&&A.error("Error ending span in reject callback:",U)}return Reflect.apply(V,F,B)}});try{return X.apply(this,$)}catch(V){throw W.setStatus({code:A0,message:V instanceof Error?V.message:"unknown_error"}),W.end(),V}})},Z.Query.prototype.handle.__sentry_original__=X,Z}_unpatchQueryPrototype(Z){if(Z.Query.prototype.handle.__sentry_original__)Z.Query.prototype.handle=Z.Query.prototype.handle.__sentry_original__;return Z}}var Hg0=(Z)=>{return{name:Nz,setupOnce(){Hr(Z)}}},Fr=S(Hg0);var r6=k(f(),1);var Lr=k(f(),1),Rz=k(H0(),1),_7=k(f(),1);var Vg0=process.env.PRISMA_SHOW_ALL_TRACES==="true",Fg0="00-10-10-00";function Bg0(Z){switch(Z){case"client":return _7.SpanKind.CLIENT;case"internal":default:return _7.SpanKind.INTERNAL}}var Ug0=class{tracerProvider;ignoreSpanTypes;constructor({tracerProvider:Z,ignoreSpanTypes:J}){this.tracerProvider=Z,this.ignoreSpanTypes=J}isEnabled(){return!0}getTraceParent(Z){let J=_7.trace.getSpanContext(Z??_7.context.active());if(J)return`00-${J.traceId}-${J.spanId}-0${J.traceFlags}`;return Fg0}dispatchEngineSpans(Z){let J=this.tracerProvider.getTracer("prisma"),X=new Map,$=Z.filter((Y)=>Y.parentId===null);for(let Y of $)Dr(J,Y,Z,X,this.ignoreSpanTypes)}getActiveContext(){return _7.context.active()}runInChildSpan(Z,J){if(typeof Z==="string")Z={name:Z};if(Z.internal&&!Vg0)return J();let X=this.tracerProvider.getTracer("prisma"),$=Z.context??this.getActiveContext(),Y=`prisma:client:${Z.name}`;if(_r(Y,this.ignoreSpanTypes))return J();if(Z.active===!1){let Q=X.startSpan(Y,Z,$);return Br(Q,J(Q,$))}return X.startActiveSpan(Y,Z,(Q)=>Br(Q,J(Q,$)))}};function Dr(Z,J,X,$,Y){if(_r(J.name,Y))return;let Q={attributes:J.attributes,kind:Bg0(J.kind),startTime:J.startTime};Z.startActiveSpan(J.name,Q,(W)=>{if($.set(J.id,W.spanContext().spanId),J.links)W.addLinks(J.links.flatMap((z)=>{let G=$.get(z);if(!G)return[];return{context:{spanId:G,traceId:W.spanContext().traceId,traceFlags:W.spanContext().traceFlags}}}));let K=X.filter((z)=>z.parentId===J.id);for(let z of K)Dr(Z,z,X,$,Y);W.end(J.endTime)})}function Br(Z,J){if(Lg0(J))return J.then((X)=>{return Z.end(),X},(X)=>{throw Z.end(),X});return Z.end(),J}function Lg0(Z){return Z!=null&&typeof Z.then==="function"}function _r(Z,J){return J.some((X)=>typeof X==="string"?X===Z:X.test(Z))}var Or={name:"@prisma/instrumentation",version:"6.19.0",description:"OpenTelemetry compliant instrumentation for Prisma Client",main:"dist/index.js",module:"dist/index.mjs",types:"dist/index.d.ts",exports:{".":{require:{types:"./dist/index.d.ts",default:"./dist/index.js"},import:{types:"./dist/index.d.ts",default:"./dist/index.mjs"}}},license:"Apache-2.0",homepage:"https://www.prisma.io",repository:{type:"git",url:"https://github.com/prisma/prisma.git",directory:"packages/instrumentation"},bugs:"https://github.com/prisma/prisma/issues",devDependencies:{"@prisma/internals":"workspace:*","@types/node":"18.19.76","@opentelemetry/api":"1.9.0",typescript:"5.4.5"},dependencies:{"@opentelemetry/instrumentation":">=0.52.0 <1"},peerDependencies:{"@opentelemetry/api":"^1.8"},files:["dist"],keywords:["prisma","instrumentation","opentelemetry","otel"],scripts:{dev:"DEV=true tsx helpers/build.ts",build:"tsx helpers/build.ts",prepublishOnly:"pnpm run build",test:"vitest run"},sideEffects:!1},t2=Or.version,Dg0=t2.split(".")[0],Ur="PRISMA_INSTRUMENTATION",s2=`V${Dg0}_PRISMA_INSTRUMENTATION`,_g0=Or.name,Og0="@prisma/client",wr=class extends Rz.InstrumentationBase{tracerProvider;constructor(Z={}){super(_g0,t2,Z)}setTracerProvider(Z){this.tracerProvider=Z}init(){return[new Rz.InstrumentationNodeModuleDefinition(Og0,[t2])]}enable(){let Z=this._config,J={helper:new Ug0({tracerProvider:this.tracerProvider??Lr.trace.getTracerProvider(),ignoreSpanTypes:Z.ignoreSpanTypes??[]})};global[Ur]=J,global[s2]=J}disable(){delete global[Ur],delete global[s2]}isEnabled(){return Boolean(global[s2])}};var jr="Prisma";function wg0(Z){return!!Z&&typeof Z==="object"&&"dispatchEngineSpans"in Z}function Mr(){let Z=globalThis.PRISMA_INSTRUMENTATION;return Z&&typeof Z==="object"&&"helper"in Z?Z.helper:void 0}class Ar extends wr{constructor(){super()}enable(){super.enable();let Z=Mr();if(wg0(Z))Z.createEngineSpan=(J)=>{let X=r6.trace.getTracer("prismaV5Compatibility"),$=X._idGenerator;if(!$){y1(()=>{console.warn("[Sentry] Could not find _idGenerator on tracer, skipping Prisma v5 compatibility - some Prisma spans may be missing!")});return}try{J.spans.forEach((Y)=>{let Q=jg0(Y.kind),W=Y.parent_span_id,K=Y.span_id,z=Y.trace_id,G=Y.links?.map((V)=>{return{context:{traceId:V.trace_id,spanId:V.span_id,traceFlags:r6.TraceFlags.SAMPLED}}}),H=r6.trace.setSpanContext(r6.context.active(),{traceId:z,spanId:W,traceFlags:r6.TraceFlags.SAMPLED});r6.context.with(H,()=>{let V={generateTraceId:()=>{return z},generateSpanId:()=>{return K}};X._idGenerator=V,X.startSpan(Y.name,{kind:Q,links:G,startTime:Y.start_time,attributes:Y.attributes}).end(Y.end_time),X._idGenerator=$})})}finally{X._idGenerator=$}}}}function jg0(Z){switch(Z){case"client":return r6.SpanKind.CLIENT;case"internal":default:return r6.SpanKind.INTERNAL}}var Mg0=a(jr,(Z)=>{return new Ar}),Tr=S((Z)=>{return{name:jr,setupOnce(){Mg0()},setup(J){if(!Mr())return;J.on("spanStart",(X)=>{let $=J0(X);if($.description?.startsWith("prisma:"))X.setAttribute(X0,"auto.db.otel.prisma");if($.description==="prisma:engine:db_query"&&$.data["db.query.text"])X.updateName($.data["db.query.text"]);if($.description==="prisma:engine:db_query"&&!$.data["db.system"])X.setAttribute("db.system","prisma")})}}});var pr=k(lr(),1);var ir="Hapi",nr=a(ir,()=>new pr.HapiInstrumentation),pg0=()=>{return{name:ir,setupOnce(){nr()}}},or=S(pg0);var Iz=k(p0(),1);var w7={HONO_TYPE:"hono.type",HONO_NAME:"hono.name"},w3={MIDDLEWARE:"middleware",REQUEST_HANDLER:"request_handler"};var xZ=k(f(),1),Ez=k(H0(),1);var ig0="@sentry/instrumentation-hono",ng0="0.0.1";class $D extends Ez.InstrumentationBase{constructor(Z={}){super(ig0,ng0,Z)}init(){return[new Ez.InstrumentationNodeModuleDefinition("hono",[">=4.0.0 <5"],(Z)=>this._patch(Z))]}_patch(Z){let J=this;class X extends Z.Hono{constructor(...$){super(...$);J._wrap(this,"get",J._patchHandler()),J._wrap(this,"post",J._patchHandler()),J._wrap(this,"put",J._patchHandler()),J._wrap(this,"delete",J._patchHandler()),J._wrap(this,"options",J._patchHandler()),J._wrap(this,"patch",J._patchHandler()),J._wrap(this,"all",J._patchHandler()),J._wrap(this,"on",J._patchOnHandler()),J._wrap(this,"use",J._patchMiddlewareHandler())}}try{Z.Hono=X}catch{return{...Z,Hono:X}}return Z}_patchHandler(){let Z=this;return function(J){return function(...$){if(typeof $[0]==="string"){let Y=$[0];if($.length===1)return J.apply(this,[Y]);let Q=$.slice(1);return J.apply(this,[Y,...Q.map((W)=>Z._wrapHandler(W))])}return J.apply(this,$.map((Y)=>Z._wrapHandler(Y)))}}}_patchOnHandler(){let Z=this;return function(J){return function(...$){let Y=$.slice(2);return J.apply(this,[...$.slice(0,2),...Y.map((Q)=>Z._wrapHandler(Q))])}}}_patchMiddlewareHandler(){let Z=this;return function(J){return function(...$){if(typeof $[0]==="string"){let Y=$[0];if($.length===1)return J.apply(this,[Y]);let Q=$.slice(1);return J.apply(this,[Y,...Q.map((W)=>Z._wrapHandler(W))])}return J.apply(this,$.map((Y)=>Z._wrapHandler(Y)))}}}_wrapHandler(Z){let J=this;return function(X,$){if(!J.isEnabled())return Z.apply(this,[X,$]);let Y=X.req.path,Q=J.tracer.startSpan(Y);return xZ.context.with(xZ.trace.setSpan(xZ.context.active(),Q),()=>{return J._safeExecute(()=>{let W=Z.apply(this,[X,$]);if(I4(W))return W.then((K)=>{let z=J._determineHandlerType(K);return Q.setAttributes({[w7.HONO_TYPE]:z,[w7.HONO_NAME]:z===w3.REQUEST_HANDLER?Y:Z.name||"anonymous"}),J.getConfig().responseHook?.(Q),K});else{let K=J._determineHandlerType(W);return Q.setAttributes({[w7.HONO_TYPE]:K,[w7.HONO_NAME]:K===w3.REQUEST_HANDLER?Y:Z.name||"anonymous"}),J.getConfig().responseHook?.(Q),W}},()=>Q.end(),(W)=>{J._handleError(Q,W),Q.end()})})}}_safeExecute(Z,J,X){try{let $=Z();if(I4($))$.then(()=>J(),(Y)=>X(Y));else J();return $}catch($){throw X($),$}}_determineHandlerType(Z){return Z===void 0?w3.MIDDLEWARE:w3.REQUEST_HANDLER}_handleError(Z,J){if(J instanceof Error)Z.setStatus({code:xZ.SpanStatusCode.ERROR,message:J.message}),Z.recordException(J)}}var ar="Hono";function og0(Z){let J=J0(Z).data,X=J[w7.HONO_TYPE];if(J[K0]||!X)return;Z.setAttributes({[X0]:"auto.http.otel.hono",[K0]:`${X}.hono`});let $=J[w7.HONO_NAME];if(typeof $==="string")Z.updateName($);if(R0()===B6()){N1&&A.warn("Isolation scope is default isolation scope - skipping setting transactionName");return}let Y=J[Iz.ATTR_HTTP_ROUTE],Q=J[Iz.ATTR_HTTP_REQUEST_METHOD];if(typeof Y==="string"&&typeof Q==="string")R0().setTransactionName(`${Q} ${Y}`)}var rr=a(ar,()=>new $D({responseHook:(Z)=>{og0(Z)}})),ag0=()=>{return{name:ar,setupOnce(){rr()}}},sr=S(ag0);var js=k(ws(),1),Ms=k(p0(),1);var As="Koa",Ts=a(As,js.KoaInstrumentation,(Z={})=>{return{ignoreLayersType:Z.ignoreLayersType,requestHook(J,X){i0(J,"auto.http.otel.koa");let $=J0(J).data,Y=$["koa.type"];if(Y)J.setAttribute(K0,`${Y}.koa`);let Q=$["koa.name"];if(typeof Q==="string")J.updateName(Q||"< unknown >");if(R0()===B6()){N1&&A.warn("Isolation scope is default isolation scope - skipping setting transactionName");return}let W=$[Ms.ATTR_HTTP_ROUTE],K=X.context?.request?.method?.toUpperCase()||"GET";if(W)R0().setTransactionName(`${K} ${W}`)}}}),Km0=(Z={})=>{return{name:As,setupOnce(){Ts(Z)}}},qs=S(Km0);var ps=k(ls(),1);var is="Connect",ns=a(is,()=>new ps.ConnectInstrumentation),Mm0=()=>{return{name:is,setupOnce(){ns()}}},os=S(Mm0);var Ft=k(Vt(),1);var hm0=new Set(["callProcedure","execSql","execSqlBatch","execBulkLoad","prepare","execute"]),Bt="Tedious",Ut=a(Bt,()=>new Ft.TediousInstrumentation({})),fm0=()=>{let Z;return{name:Bt,setupOnce(){let J=Ut();Z=RY(J)},setup(J){Z?.(()=>J.on("spanStart",(X)=>{let{description:$,data:Y}=J0(X);if(!$||Y["db.system"]!=="mssql")return;let Q=$.split(" ")[0]||"";if(hm0.has(Q))X.setAttribute(X0,"auto.db.otel.tedious")}))}}},Lt=S(fm0);var Ct=k(qt(),1);var Nt="GenericPool",Rt=a(Nt,()=>new Ct.GenericPoolInstrumentation({})),dm0=()=>{let Z;return{name:Nt,setupOnce(){let J=Rt();Z=RY(J)},setup(J){Z?.(()=>J.on("spanStart",(X)=>{let Y=J0(X).description;if(Y==="generic-pool.aquire"||Y==="generic-pool.acquire")X.setAttribute(X0,"auto.db.otel.generic_pool")}))}}},Pt=S(dm0);var tt=k(st(),1);var et="Amqplib",Md0={consumeEndHook:(Z)=>{i0(Z,"auto.amqplib.otel.consumer")},publishHook:(Z)=>{i0(Z,"auto.amqplib.otel.publisher")}},Ze=a(et,()=>new tt.AmqplibInstrumentation(Md0)),Ad0=()=>{return{name:et,setupOnce(){Ze()}}},Je=S(Ad0);var q3="VercelAI";var gz=k(H0(),1);var Td0=[">=3.0.0 <7"],Xe=["generateText","streamText","generateObject","streamObject","embed","embedMany"];function qd0(Z){if(typeof Z!=="object"||Z===null)return!1;let J=Z;return"type"in J&&"error"in J&&"toolName"in J&&"toolCallId"in J&&J.type==="tool-error"&&J.error instanceof Error}function Cd0(Z){if(typeof Z!=="object"||Z===null||!("content"in Z))return;let J=Z;if(!Array.isArray(J.content))return;for(let X of J.content)if(qd0(X)){let $=NU(X.toolCallId);if($){let Y=$.spanContext();s4((Q)=>{Q.setContext("trace",{trace_id:Y.traceId,span_id:Y.spanId}),Q.setTag("vercel.ai.tool.name",X.toolName),Q.setTag("vercel.ai.tool.callId",X.toolCallId),Q.setLevel("error"),V0(X.error,{mechanism:{type:"auto.vercelai.otel",handled:!1}})}),RU(X.toolCallId)}else s4((Y)=>{Y.setTag("vercel.ai.tool.name",X.toolName),Y.setTag("vercel.ai.tool.callId",X.toolCallId),Y.setLevel("error"),V0(X.error,{mechanism:{type:"auto.vercelai.otel",handled:!1}})})}}function Nd0(Z,J,X,$){let Y=Z?.recordInputs!==void 0?Z.recordInputs:J.recordInputs!==void 0?J.recordInputs:X===!0?!0:$,Q=Z?.recordOutputs!==void 0?Z.recordOutputs:J.recordOutputs!==void 0?J.recordOutputs:X===!0?!0:$;return{recordInputs:Y,recordOutputs:Q}}class C3 extends gz.InstrumentationBase{__init(){this._isPatched=!1}__init2(){this._callbacks=[]}constructor(Z={}){super("@sentry/instrumentation-vercel-ai",N0,Z);C3.prototype.__init.call(this),C3.prototype.__init2.call(this)}init(){return new gz.InstrumentationNodeModuleDefinition("ai",Td0,this._patch.bind(this))}callWhenPatched(Z){if(this._isPatched)Z();else this._callbacks.push(Z)}_patch(Z){this._isPatched=!0,this._callbacks.forEach((X)=>X()),this._callbacks=[];let J=(X)=>{return new Proxy(X,{apply:($,Y,Q)=>{let W=Q[0].experimental_telemetry||{},K=W.isEnabled,z=u(),G=z?.getIntegrationByName(q3),H=G?.options,V=G?Boolean(z?.getOptions().sendDefaultPii):!1,{recordInputs:F,recordOutputs:B}=Nd0(H,W,K,V);return Q[0].experimental_telemetry={...W,isEnabled:K!==void 0?K:!0,recordInputs:F,recordOutputs:B},D6(()=>Reflect.apply($,Y,Q),(U)=>{if(U&&typeof U==="object")f1(U,"_sentry_active_span",t8())},()=>{},(U)=>{Cd0(U)})}})};if(Object.prototype.toString.call(Z)==="[object Module]"){for(let X of Xe)Z[X]=J(Z[X]);return Z}else{let X=Xe.reduce(($,Y)=>{return $[Y]=J(Z[Y]),$},{});return{...Z,...X}}}}var $e=a(q3,()=>new C3({}));function Rd0(Z){return!!Z.getIntegrationByName("Modules")?.getModules?.()?.ai}var Pd0=(Z={})=>{let J;return{name:q3,options:Z,setupOnce(){J=$e()},afterAllSetup(X){if(Z.force??Rd0(X))KK(X);else J?.callWhenPatched(()=>KK(X))}}},Ye=S(Pd0);var mz=k(H0(),1);var Ed0=[">=4.0.0 <7"];class AD extends mz.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-openai",N0,Z)}init(){return new mz.InstrumentationNodeModuleDefinition("openai",Ed0,this._patch.bind(this))}_patch(Z){let J=Z;return J=this._patchClient(J,"OpenAI"),J=this._patchClient(J,"AzureOpenAI"),J}_patchClient(Z,J){let X=Z[J];if(!X)return Z;let $=this.getConfig(),Y=function(...Q){if(OZ($7))return Reflect.construct(X,Q);let W=Reflect.construct(X,Q),K=u(),z=Boolean(K?.getOptions().sendDefaultPii),G=$.recordInputs??z,H=$.recordOutputs??z;return HK(W,{recordInputs:G,recordOutputs:H})};Object.setPrototypeOf(Y,X),Object.setPrototypeOf(Y.prototype,X.prototype);for(let Q of Object.getOwnPropertyNames(X))if(!["length","name","prototype"].includes(Q)){let W=Object.getOwnPropertyDescriptor(X,Q);if(W)Object.defineProperty(Y,Q,W)}try{Z[J]=Y}catch(Q){Object.defineProperty(Z,J,{value:Y,writable:!0,configurable:!0,enumerable:!0})}if(Z.default===X)try{Z.default=Y}catch(Q){Object.defineProperty(Z,"default",{value:Y,writable:!0,configurable:!0,enumerable:!0})}return Z}}var Qe=a($7,(Z)=>new AD(Z)),Id0=(Z={})=>{return{name:$7,setupOnce(){Qe(Z)}}},We=S(Id0);var dz=k(H0(),1);var yd0=[">=0.19.2 <1.0.0"];class TD extends dz.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-anthropic-ai",N0,Z)}init(){return new dz.InstrumentationNodeModuleDefinition("@anthropic-ai/sdk",yd0,this._patch.bind(this))}_patch(Z){let J=Z.Anthropic,X=this.getConfig(),$=function(...Y){if(OZ(Y7))return Reflect.construct(J,Y);let Q=Reflect.construct(J,Y),W=u(),K=Boolean(W?.getOptions().sendDefaultPii),z=X.recordInputs??K,G=X.recordOutputs??K;return IU(Q,{recordInputs:z,recordOutputs:G})};Object.setPrototypeOf($,J),Object.setPrototypeOf($.prototype,J.prototype);for(let Y of Object.getOwnPropertyNames(J))if(!["length","name","prototype"].includes(Y)){let Q=Object.getOwnPropertyDescriptor(J,Y);if(Q)Object.defineProperty($,Y,Q)}try{Z.Anthropic=$}catch(Y){Object.defineProperty(Z,"Anthropic",{value:$,writable:!0,configurable:!0,enumerable:!0})}if(Z.default===J)try{Z.default=$}catch(Y){Object.defineProperty(Z,"default",{value:$,writable:!0,configurable:!0,enumerable:!0})}return Z}}var Ke=a(Y7,(Z)=>new TD(Z)),Sd0=(Z={})=>{return{name:Y7,options:Z,setupOnce(){Ke(Z)}}},ze=S(Sd0);var gX=k(H0(),1);var Ge=[">=0.10.0 <2"];class qD extends gX.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-google-genai",N0,Z)}init(){return new gX.InstrumentationNodeModuleDefinition("@google/genai",Ge,(J)=>this._patch(J),(J)=>J,[new gX.InstrumentationNodeModuleFile("@google/genai/dist/node/index.cjs",Ge,(J)=>this._patch(J),(J)=>J)])}_patch(Z){let J=Z.GoogleGenAI,X=this.getConfig();if(typeof J!=="function")return Z;let $=function(...Y){if(OZ(Q7))return Reflect.construct(J,Y);let Q=Reflect.construct(J,Y),W=u(),K=Boolean(W?.getOptions().sendDefaultPii),z=X,G=z?.recordInputs??K,H=z?.recordOutputs??K;return xU(Q,{recordInputs:G,recordOutputs:H})};Object.setPrototypeOf($,J),Object.setPrototypeOf($.prototype,J.prototype);for(let Y of Object.getOwnPropertyNames(J))if(!["length","name","prototype"].includes(Y)){let Q=Object.getOwnPropertyDescriptor(J,Y);if(Q)Object.defineProperty($,Y,Q)}return CY(Z,"GoogleGenAI",$),Z}}var He=a(Q7,(Z)=>new qD(Z)),kd0=(Z={})=>{return{name:Q7,setupOnce(){He(Z)}}},Ve=S(kd0);var A7=k(H0(),1);var uz=[">=0.1.0 <2.0.0"];function xd0(Z,J){if(!Z)return[J];if(Array.isArray(Z)){if(Z.includes(J))return Z;return[...Z,J]}if(typeof Z==="object")return[Z,J];return Z}function vd0(Z,J,X){return new Proxy(Z,{apply($,Y,Q){let K=Q[1];if(!K||typeof K!=="object"||Array.isArray(K))K={},Q[1]=K;let z=K.callbacks,G=xd0(z,J);return K.callbacks=G,Reflect.apply($,Y,Q)}})}class CD extends A7.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-langchain",N0,Z)}init(){let Z=[],J=["@langchain/anthropic","@langchain/openai","@langchain/google-genai","@langchain/mistralai","@langchain/google-vertexai","@langchain/groq"];for(let X of J)Z.push(new A7.InstrumentationNodeModuleDefinition(X,uz,this._patch.bind(this),($)=>$,[new A7.InstrumentationNodeModuleFile(`${X}/dist/index.cjs`,uz,this._patch.bind(this),($)=>$)]));return Z.push(new A7.InstrumentationNodeModuleDefinition("langchain",uz,this._patch.bind(this),(X)=>X,[new A7.InstrumentationNodeModuleFile("langchain/dist/chat_models/universal.cjs",uz,this._patch.bind(this),(X)=>X)])),Z}_patch(Z){WU([$7,Y7,Q7]);let J=u(),X=Boolean(J?.getOptions().sendDefaultPii),$=this.getConfig(),Y=$?.recordInputs??X,Q=$?.recordOutputs??X,W=FK({recordInputs:Y,recordOutputs:Q});return this._patchRunnableMethods(Z,W),Z}_patchRunnableMethods(Z,J){let X=["ChatAnthropic","ChatOpenAI","ChatGoogleGenerativeAI","ChatMistralAI","ChatVertexAI","ChatGroq","ConfigurableModel"],$=Z.universal_exports??Z,Y=Object.values($).find((K)=>{return typeof K==="function"&&X.includes(K.name)});if(!Y)return;let Q=Y.prototype,W=["invoke","stream","batch"];for(let K of W){let z=Q[K];if(typeof z==="function")Q[K]=vd0(z,J)}}}var Fe=a(VK,(Z)=>new CD(Z)),hd0=(Z={})=>{return{name:VK,setupOnce(){Fe(Z)}}},Be=S(hd0);var mX=k(H0(),1);var Ue=[">=0.0.0 <2.0.0"];class ND extends mX.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-langgraph",N0,Z)}init(){return new mX.InstrumentationNodeModuleDefinition("@langchain/langgraph",Ue,this._patch.bind(this),(J)=>J,[new mX.InstrumentationNodeModuleFile("@langchain/langgraph/dist/index.cjs",Ue,this._patch.bind(this),(J)=>J)])}_patch(Z){let J=u(),X=Boolean(J?.getOptions().sendDefaultPii),$=this.getConfig(),Y=$.recordInputs??X,Q=$.recordOutputs??X,W={recordInputs:Y,recordOutputs:Q};if(Z.StateGraph&&typeof Z.StateGraph==="function"){let K=Z.StateGraph;K.prototype.compile=fU(K.prototype.compile,W)}return Z}}var Le=a(BK,(Z)=>new ND(Z)),fd0=(Z={})=>{return{name:BK,setupOnce(){Le(Z)}}},De=S(fd0);var qe=k(H0(),1);var W9=k(f(),1),K9=k(H0(),1),s6=k(p0(),1);import*as Oe from"net";function we(Z,J,X,$,Y){let W=()=>{},K=Y.firestoreSpanCreationHook;if(typeof K==="function")W=(H)=>{K9.safeExecuteInTheMiddle(()=>K(H),(V)=>{if(!V)return;W9.diag.error(V?.message)},!0)};let z=new K9.InstrumentationNodeModuleDefinition("@firebase/firestore",J,(H)=>_e(H,X,$,Z,W)),G=["@firebase/firestore/dist/lite/index.node.cjs.js","@firebase/firestore/dist/lite/index.node.mjs.js","@firebase/firestore/dist/lite/index.rn.esm2017.js","@firebase/firestore/dist/lite/index.cjs.js"];for(let H of G)z.files.push(new K9.InstrumentationNodeModuleFile(H,J,(V)=>_e(V,X,$,Z,W),(V)=>je(V,$)));return z}function _e(Z,J,X,$,Y){return je(Z,X),J(Z,"addDoc",bd0($,Y)),J(Z,"getDocs",md0($,Y)),J(Z,"setDoc",dd0($,Y)),J(Z,"deleteDoc",gd0($,Y)),Z}function je(Z,J){for(let X of["addDoc","getDocs","setDoc","deleteDoc"])if(K9.isWrapped(Z[X]))J(Z,X);return Z}function bd0(Z,J){return function($){return function(Y,Q){let W=lz(Z,"addDoc",Y);return J(W),cz(W,()=>{return $(Y,Q)})}}}function gd0(Z,J){return function($){return function(Y){let Q=lz(Z,"deleteDoc",Y.parent||Y);return J(Q),cz(Q,()=>{return $(Y)})}}}function md0(Z,J){return function($){return function(Y){let Q=lz(Z,"getDocs",Y);return J(Q),cz(Q,()=>{return $(Y)})}}}function dd0(Z,J){return function($){return function(Y,Q,W){let K=lz(Z,"setDoc",Y.parent||Y);return J(K),cz(K,()=>{return typeof W<"u"?$(Y,Q,W):$(Y,Q)})}}}function cz(Z,J){return W9.context.with(W9.trace.setSpan(W9.context.active(),Z),()=>{return K9.safeExecuteInTheMiddle(()=>{return J()},(X)=>{if(X)Z.recordException(X);Z.end()},!0)})}function lz(Z,J,X){let $=Z.startSpan(`${J} ${X.path}`,{kind:W9.SpanKind.CLIENT});return cd0($,X),$.setAttribute(s6.ATTR_DB_OPERATION_NAME,J),$}function ud0(Z){let J,X;if(typeof Z.host==="string")if(Z.host.startsWith("[")){if(Z.host.endsWith("]"))J=Z.host.replace(/^\[|\]$/g,"");else if(Z.host.includes("]:")){let $=Z.host.lastIndexOf(":");if($!==-1)J=Z.host.slice(1,$).replace(/^\[|\]$/g,""),X=Z.host.slice($+1)}}else if(Oe.isIPv6(Z.host))J=Z.host;else{let $=Z.host.lastIndexOf(":");if($!==-1)J=Z.host.slice(0,$),X=Z.host.slice($+1);else J=Z.host}return{address:J,port:X?parseInt(X,10):void 0}}function cd0(Z,J){let X=J.firestore.app,$=X.options,Q=(J.firestore.toJSON()||{}).settings||{},W={[s6.ATTR_DB_COLLECTION_NAME]:J.path,[s6.ATTR_DB_NAMESPACE]:X.name,[s6.ATTR_DB_SYSTEM_NAME]:"firebase.firestore","firebase.firestore.type":J.type,"firebase.firestore.options.projectId":$.projectId,"firebase.firestore.options.appId":$.appId,"firebase.firestore.options.messagingSenderId":$.messagingSenderId,"firebase.firestore.options.storageBucket":$.storageBucket},{address:K,port:z}=ud0(Q);if(K)W[s6.ATTR_SERVER_ADDRESS]=K;if(z)W[s6.ATTR_SERVER_PORT]=z;Z.setAttributes(W)}var G5=k(f(),1),z9=k(H0(),1);function Me(Z,J,X,$,Y){let Q=()=>{},W=()=>{},K=Y.functions?.errorHook,z=Y.functions?.requestHook,G=Y.functions?.responseHook;if(typeof G==="function")W=(F,B)=>{z9.safeExecuteInTheMiddle(()=>G(F,B),(U)=>{if(!U)return;G5.diag.error(U?.message)},!0)};if(typeof z==="function")Q=(F)=>{z9.safeExecuteInTheMiddle(()=>z(F),(B)=>{if(!B)return;G5.diag.error(B?.message)},!0)};let H=new z9.InstrumentationNodeModuleDefinition("firebase-functions",J);return[{name:"firebase-functions/lib/v2/providers/https.js",triggerType:"function"},{name:"firebase-functions/lib/v2/providers/firestore.js",triggerType:"firestore"},{name:"firebase-functions/lib/v2/providers/scheduler.js",triggerType:"scheduler"},{name:"firebase-functions/lib/v2/storage.js",triggerType:"storage"}].forEach(({name:F,triggerType:B})=>{H.files.push(new z9.InstrumentationNodeModuleFile(F,J,(U)=>ld0(U,X,$,Z,{requestHook:Q,responseHook:W,errorHook:K},B),(U)=>Ae(U,$)))}),H}function f4(Z,J,X){return function(Y){return function(...Q){let W=typeof Q[0]==="function"?Q[0]:Q[1],K=typeof Q[0]==="function"?void 0:Q[0];if(!W)return Y.call(this,...Q);let z=async function(...G){let H=process.env.FUNCTION_TARGET||process.env.K_SERVICE||"unknown",V=Z.startSpan(`firebase.function.${X}`,{kind:G5.SpanKind.SERVER}),F={"faas.name":H,"faas.trigger":X,"faas.provider":"firebase"};if(process.env.GCLOUD_PROJECT)F["cloud.project_id"]=process.env.GCLOUD_PROJECT;if(process.env.EVENTARC_CLOUD_EVENT_SOURCE)F["cloud.event_source"]=process.env.EVENTARC_CLOUD_EVENT_SOURCE;return V.setAttributes(F),J?.requestHook?.(V),G5.context.with(G5.trace.setSpan(G5.context.active(),V),async()=>{let B,U;try{U=await W.apply(this,G)}catch(D){B=D}if(J?.responseHook?.(V,B),B)V.recordException(B);if(V.end(),B)throw await J?.errorHook?.(V,B),B;return U})};if(K)return Y.call(this,K,z);else return Y.call(this,z)}}}function ld0(Z,J,X,$,Y,Q){switch(Ae(Z,X),Q){case"function":J(Z,"onRequest",f4($,Y,"http.request")),J(Z,"onCall",f4($,Y,"http.call"));break;case"firestore":J(Z,"onDocumentCreated",f4($,Y,"firestore.document.created")),J(Z,"onDocumentUpdated",f4($,Y,"firestore.document.updated")),J(Z,"onDocumentDeleted",f4($,Y,"firestore.document.deleted")),J(Z,"onDocumentWritten",f4($,Y,"firestore.document.written")),J(Z,"onDocumentCreatedWithAuthContext",f4($,Y,"firestore.document.created")),J(Z,"onDocumentUpdatedWithAuthContext",f4($,Y,"firestore.document.updated")),J(Z,"onDocumentDeletedWithAuthContext",f4($,Y,"firestore.document.deleted")),J(Z,"onDocumentWrittenWithAuthContext",f4($,Y,"firestore.document.written"));break;case"scheduler":J(Z,"onSchedule",f4($,Y,"scheduler.scheduled"));break;case"storage":J(Z,"onObjectFinalized",f4($,Y,"storage.object.finalized")),J(Z,"onObjectArchived",f4($,Y,"storage.object.archived")),J(Z,"onObjectDeleted",f4($,Y,"storage.object.deleted")),J(Z,"onObjectMetadataUpdated",f4($,Y,"storage.object.metadataUpdated"));break}return Z}function Ae(Z,J){let X=["onSchedule","onRequest","onCall","onObjectFinalized","onObjectArchived","onObjectDeleted","onObjectMetadataUpdated","onDocumentCreated","onDocumentUpdated","onDocumentDeleted","onDocumentWritten","onDocumentCreatedWithAuthContext","onDocumentUpdatedWithAuthContext","onDocumentDeletedWithAuthContext","onDocumentWrittenWithAuthContext"];for(let $ of X)if(z9.isWrapped(Z[$]))J(Z,$);return Z}var Te={},pd0=[">=3.0.0 <5"],id0=[">=6.0.0 <7"];class RD extends qe.InstrumentationBase{constructor(Z=Te){super("@sentry/instrumentation-firebase",N0,Z)}setConfig(Z={}){super.setConfig({...Te,...Z})}init(){let Z=[];return Z.push(we(this.tracer,pd0,this._wrap,this._unwrap,this.getConfig())),Z.push(Me(this.tracer,id0,this._wrap,this._unwrap,this.getConfig())),Z}}var Ce="Firebase",nd0={firestoreSpanCreationHook:(Z)=>{i0(Z,"auto.firebase.otel.firestore"),Z.setAttribute(K0,"db.query")},functions:{requestHook:(Z)=>{i0(Z,"auto.firebase.otel.functions"),Z.setAttribute(K0,"http.request")},errorHook:async(Z,J)=>{if(J)V0(J,{mechanism:{type:"auto.firebase.otel.functions",handled:!1}}),await iW(2000)}}},Ne=a(Ce,()=>new RD(nd0)),od0=()=>{return{name:Ce,setupOnce(){Ne()}}},Re=S(od0);function N3(){return[Pl(),Lp(),Yi(),sr(),Fn(),vn(),Xo(),qo(),Pa(),Kr(),Tr(),or(),qs(),os(),Lt(),Pt(),yi(),Je(),ii(),Be(),De(),Ye(),We(),ze(),Ve(),Fr(),Re()]}var dX=k(f(),1);var uX=k(p0(),1);var PD=1e6;function Pe(Z,J={}){if(Z.getOptions().debug)hL();let[X,$]=ad0(Z,J);Z.traceProvider=X,Z.asyncLocalStorageLookup=$}function ad0(Z,J={}){let X=new xK({sampler:new ML(Z),resource:SY().merge(PK({[uX.ATTR_SERVICE_NAME]:"node",[uX.SEMRESATTRS_SERVICE_NAMESPACE]:"sentry",[uX.ATTR_SERVICE_VERSION]:N0})),forceFlushTimeoutMillis:500,spanProcessors:[new jL({timeout:rd0(Z.getOptions().maxSpanWaitDuration)}),...J.spanProcessors||[]]});dX.trace.setGlobalTracerProvider(X),dX.propagation.setGlobalPropagator(new wL);let $=new dK;return dX.context.setGlobalContextManager($),[X,$.getAsyncLocalStorageLookup()]}function rd0(Z){if(Z==null)return;if(Z>PD)return N1&&A.warn(`\`maxSpanWaitDuration\` is too high, using the maximum value of ${PD}`),PD;else if(Z<=0||Number.isNaN(Z)){N1&&A.warn("`maxSpanWaitDuration` must be a positive number, using default value instead.");return}return Z}function Ee(){return iK().filter((J)=>J.name!=="Http"&&J.name!=="NodeFetch").concat(iY(),oY())}function Ie(Z){return[...Ee(),...L1(Z)?N3():[]]}function ED(Z={}){return sd0(Z,Ie)}function sd0(Z={},J){i5(Z,"node");let X=pL({...Z,defaultIntegrations:Z.defaultIntegrations??J(Z)});if(X&&!Z.skipOpenTelemetrySetup)Pe(X,{spanProcessors:Z.openTelemetrySpanProcessors}),nK();return X}import*as ve from"os";var td0="BunServer",ed0=()=>{return{name:td0,setupOnce(){Zu0()}}},ke=S(ed0),ye=!1;function Zu0(){if(ye)return;Bun.serve=new Proxy(Bun.serve,{apply(Z,J,X){Se(X[0]);let $=Z.apply(J,X),Y=$.reload.bind($);return $.reload=(Q)=>{return Se(Q),Y(Q)},$}}),ye=!0}function Se(Z){Ju0(Z),Xu0(Z)}function Ju0(Z){if(typeof Z.fetch!=="function")return;Z.fetch=new Proxy(Z.fetch,{apply(J,X,$){return ID(J,X,$)}})}function Xu0(Z){if(!Z.routes)return;if(typeof Z.routes!=="object")return;Object.keys(Z.routes).forEach((J)=>{let X=Z.routes[J];if(typeof X==="function")Z.routes[J]=new Proxy(X,{apply:($,Y,Q)=>{return ID($,Y,Q,J)}});if(X instanceof Response)return;if(typeof X==="object")Object.entries(X).forEach(([$,Y])=>{if(typeof Y==="function")Z.routes[J][$]=new Proxy(Y,{apply:(Q,W,K)=>{return ID(Q,W,K,J)}})})})}function ID(Z,J,X,$){return KZ((Y)=>{let Q=X[0],W=Q.method.toUpperCase();if(W==="OPTIONS"||W==="HEAD")return Z.apply(J,X);let K=BY(Q.url),z=$u0(K,Q),G=K?.pathname||"/";if(Q.params){if(Object.keys(Q.params).forEach((H)=>{z[`url.path.parameter.${H}`]=Q.params[H]}),$)z[U1]="route",z["url.template"]=$,G=$}if($?.endsWith("/*"))z[U1]="route",z["url.template"]=$,G=$;return Object.assign(z,iJ(Q.headers.toJSON(),u()?.getOptions().sendDefaultPii??!1)),Y.setSDKProcessingMetadata({normalizedRequest:{url:Q.url,method:Q.method,headers:Q.headers.toJSON(),query_string:K?.search}}),cW({sentryTrace:Q.headers.get("sentry-trace")??"",baggage:Q.headers.get("baggage")},()=>_6({attributes:z,op:"http.server",name:`${Q.method} ${G}`},async(H)=>{try{let V=await Z.apply(J,X);if(V?.status)SW(H,V.status),Y.setContext("response",{headers:V.headers.toJSON(),status_code:V.status});return V}catch(V){throw V0(V,{mechanism:{type:"auto.http.bun.serve",handled:!1}}),V}}))})}function $u0(Z,J){let X={[X0]:"auto.http.bun.serve",[vB]:J.method||"GET",[U1]:"url"};if(Z){if(Z.search)X["url.query"]=Z.search;if(Z.hash)X["url.fragment"]=Z.hash;if(Z.pathname)X["url.path"]=Z.pathname;if(!zU(Z)){if(X["url.full"]=Z.href,Z.port)X["url.port"]=Z.port;if(Z.protocol)X["url.scheme"]=Z.protocol;if(Z.hostname)X["url.domain"]=Z.hostname}}return X}function xe(Z){function J(X){let $={body:X.body,method:"POST",headers:Z.headers};try{return p9(()=>{return fetch(Z.url,$).then((Y)=>{return{statusCode:Y.status,headers:{"x-sentry-rate-limits":Y.headers.get("X-Sentry-Rate-Limits"),"retry-after":Y.headers.get("Retry-After")}}})})}catch(Y){return Promise.reject(Y)}}return _Z(Z,J)}function he(Z){return[oJ(),nJ(),aJ(),rJ(),sJ(),iY(),oY(),MX(),AX(),wX(),OX(),jX(),ke(),...L1(Z)?N3():[]]}function yD(Z={}){i5(Z,"bun");let J={...Z,platform:"javascript",runtime:{name:"bun",version:Bun.version},serverName:Z.serverName||global.process.env.SENTRY_NAME||ve.hostname()};if(J.transport=J.transport||xe,J.defaultIntegrations===void 0)J.defaultIntegrations=he(J);return ED(J)}yD({dsn:"https://f0ba950f2a01c32d24ccd8711de778be@o4510345514123264.ingest.us.sentry.io/4510346875043848",tracesSampleRate:1,sendDefaultPii:!1});import{readFileSync as fe}from"fs";import{join as be}from"path";function Q6(){return"2.1.0-beta.1"}function SD(Z){let[J,X]=Z.split("-"),$=(J||"0.0.0").split(".").map(Number),Y=null,Q=0;if(X){let W=X.match(/^([a-z]+)\.?(\d+)?$/i);if(W)Y=W[1]||null,Q=parseInt(W[2]||"0",10);else Y=X}return{major:$[0]||0,minor:$[1]||0,patch:$[2]||0,preRelease:Y,preReleaseNum:Q}}function G9(Z){let J=SD(Z);if(!J.preRelease)return"stable";if(J.preRelease.startsWith("alpha"))return"alpha";return"beta"}function R3(Z,J){try{let X=SD(Z),$=SD(J);if(X.major>$.major)return!1;if(X.major<$.major)return!1;if($.preRelease&&!X.preRelease)return!1;if(!$.preRelease&&X.preRelease)return!1;if($.preRelease&&X.preRelease){if(X.minor<$.minor)return!1;if(X.minor>$.minor)return!0;if(X.patch>$.patch)return!0;if(X.patch<$.patch)return!1;return X.preReleaseNum>$.preReleaseNum}if(X.minor>$.minor)return!0;if(X.minor<$.minor)return!1;if(X.patch>$.patch)return!0;return!1}catch(X){return!1}}import{parseArgs as Qu0}from"util";var Wu0={debug:{type:"boolean",short:"d",default:!1,description:"Enable debug logging"},"mqtt-port":{type:"string",default:"8884",description:"MQTT broker port"},"terminal-port":{type:"string",default:"3001",description:"Terminal server port"},"router-port":{type:"string",default:"8883",description:"Router port"},username:{type:"string",short:"u",description:"MQTT broker username (required)"},password:{type:"string",short:"p",description:"MQTT broker password (required)"},"ngrok-token":{type:"string",description:"ngrok authentication token (optional)"},"ngrok-domain":{type:"string",description:"ngrok static domain (optional, paid plan)"},"no-auto-update":{type:"boolean",default:!1,description:"Disable auto-update checking"},"terminal-audit":{type:"boolean",default:!1,description:"Enable terminal input audit logging (logs commands, not output)"},"auto-update-check-interval":{type:"string",default:"60",description:"Auto-update check interval in minutes (default: 60)"},help:{type:"boolean",short:"h",default:!1,description:"Show help message"},version:{type:"boolean",short:"v",default:!1,description:"Show version"}};function ge(){let Z=Qu0({options:Wu0,allowPositionals:!1,strict:!0});if(Z.values.version)console.log(`ccc v${Q6()}`),process.exit(0);if(Z.values.help)Ku0(),process.exit(0);let J=process.env.CCC_USERNAME||Z.values.username,X=process.env.CCC_PASSWORD||Z.values.password,$=process.env.CCC_NGROK_TOKEN||Z.values["ngrok-token"],Y=process.env.CCC_NGROK_DOMAIN||Z.values["ngrok-domain"];if(!J||!X)console.error("\x1B[31mError: Authentication credentials are required.\x1B[0m"),console.error(""),console.error("These credentials secure the MQTT communication between the app and backend."),console.error(""),console.error("You can provide them via:"),console.error(""),console.error(" Environment variables (recommended for security):"),console.error(" export CCC_USERNAME=myuser"),console.error(" export CCC_PASSWORD=mypassword"),console.error(" export CCC_NGROK_TOKEN=your_token # optional"),console.error(" export CCC_NGROK_DOMAIN=your_domain # optional"),console.error(" ccc"),console.error(""),console.error(" Or CLI arguments:"),console.error(" ccc --username myuser --password mypassword"),console.error(" ccc -u myuser -p mypassword"),console.error(""),process.exit(1);return{debug:Z.values.debug,mqttPort:parseInt(Z.values["mqtt-port"],10),terminalPort:parseInt(Z.values["terminal-port"],10),routerPort:parseInt(Z.values["router-port"],10),username:J,password:X,ngrokToken:$,ngrokDomain:Y,autoUpdate:!Z.values["no-auto-update"],autoUpdateCheckInterval:parseInt(Z.values["auto-update-check-interval"],10),terminalAudit:Z.values["terminal-audit"]}}function Ku0(){console.log(`
53
+ >>> no match, partial?`,Z,V,J,F),V===K)return!0}return!1}let U;if(typeof G==="string")U=H===G,this.debug("string match",G,H,U);else U=G.test(H),this.debug("pattern match",G,H,U);if(!U)return!1}if(Q===K&&W===z)return!0;else if(Q===K)return X;else if(W===z)return Q===K-1&&Z[Q]==="";else throw Error("wtf?")}braceExpand(){return el(this.pattern,this.options)}parse(Z){sY(Z);let J=this.options;if(Z==="**")return l6;if(Z==="")return"";let X,$=null;if(X=Z.match(Lx0))$=J.dot?_x0:Dx0;else if(X=Z.match(Qx0))$=(J.nocase?J.dot?Gx0:zx0:J.dot?Kx0:Wx0)(X[1]);else if(X=Z.match(Ox0))$=(J.nocase?J.dot?jx0:wx0:J.dot?Mx0:Ax0)(X);else if(X=Z.match(Hx0))$=J.dot?Fx0:Vx0;else if(X=Z.match(Bx0))$=Ux0;let Y=H4.fromGlob(Z,this.options).toMMPattern();if($&&typeof Y==="object")Reflect.defineProperty(Y,"test",{value:$});return Y}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let Z=this.set;if(!Z.length)return this.regexp=!1,this.regexp;let J=this.options,X=J.noglobstar?Cx0:J.dot?Nx0:Rx0,$=new Set(J.nocase?["i"]:[]),Y=Z.map((K)=>{let z=K.map((G)=>{if(G instanceof RegExp)for(let H of G.flags.split(""))$.add(H);return typeof G==="string"?Sx0(G):G===l6?l6:G._src});return z.forEach((G,H)=>{let V=z[H+1],F=z[H-1];if(G!==l6||F===l6)return;if(F===void 0)if(V!==void 0&&V!==l6)z[H+1]="(?:\\/|"+X+"\\/)?"+V;else z[H]=X;else if(V===void 0)z[H-1]=F+"(?:\\/|"+X+")?";else if(V!==l6)z[H-1]=F+"(?:\\/|\\/"+X+"\\/)"+V,z[H+1]=l6}),z.filter((G)=>G!==l6).join("/")}).join("|"),[Q,W]=Z.length>1?["(?:",")"]:["",""];if(Y="^"+Q+Y+W+"$",this.negate)Y="^(?!"+Y+").+$";try{this.regexp=new RegExp(Y,[...$].join(""))}catch(K){this.regexp=!1}return this.regexp}slashSplit(Z){if(this.preserveMultipleSlashes)return Z.split("/");else if(this.isWindows&&/^\/\/[^\/]+/.test(Z))return["",...Z.split(/\/+/)];else return Z.split(/\/+/)}match(Z,J=this.partial){if(this.debug("match",Z,this.pattern),this.comment)return!1;if(this.empty)return Z==="";if(Z==="/"&&J)return!0;let X=this.options;if(this.isWindows)Z=Z.split("\\").join("/");let $=this.slashSplit(Z);this.debug(this.pattern,"split",$);let Y=this.set;this.debug(this.pattern,"set",Y);let Q=$[$.length-1];if(!Q)for(let W=$.length-2;!Q&&W>=0;W--)Q=$[W];for(let W=0;W<Y.length;W++){let K=Y[W],z=$;if(X.matchBase&&K.length===1)z=[Q];if(this.matchOne(z,K,J)){if(X.flipNegate)return!0;return!this.negate}}if(X.flipNegate)return!1;return this.negate}static defaults(Z){return V4.defaults(Z).Minimatch}}V4.AST=H4;V4.Minimatch=eY;V4.escape=$2;V4.unescape=H7;var Jp="@fastify/otel",xx0="0.8.0",vx0=">=4.0.0 <6",Xp=["onRequest","preParsing","preValidation","preHandler","preSerialization","onSend","onResponse","onError"],$1={HOOK_NAME:"hook.name",FASTIFY_TYPE:"fastify.type",HOOK_CALLBACK_NAME:"hook.callback.name",ROOT:"fastify.root"},V7={ROUTE:"route-hook",INSTANCE:"hook",HANDLER:"request-handler"},e5="anonymous",x4=Symbol("fastify otel instance"),F7=Symbol("fastify otel request spans"),Z3=Symbol("fastify otel request context"),$p=Symbol("fastify otel addhook original"),Yp=Symbol("fastify otel setnotfound original"),Zz=Symbol("fastify otel ignore path");class Y2 extends Qp.InstrumentationBase{constructor(Z){super(Jp,xx0,Z);if(this.servername=Z?.servername??process.env.OTEL_SERVICE_NAME??"fastify",this[Zz]=null,this._logger=k1.diag.createComponentLogger({namespace:Jp}),Z?.ignorePaths!=null||process.env.OTEL_FASTIFY_IGNORE_PATHS!=null){let J=Z?.ignorePaths??process.env.OTEL_FASTIFY_IGNORE_PATHS;if((typeof J!=="string"||J.length===0)&&typeof J!=="function")throw TypeError("ignorePaths must be a string or a function");let X=V4;this[Zz]=($)=>{if(typeof J==="function")return J($);else return X($.url,J)}}}enable(){if(this._handleInitialization===void 0&&this.getConfig().registerOnInitialization){let Z=this.plugin();this._handleInitialization=(J)=>{J.fastify.register(Z)},Zp.subscribe("fastify.initialization",this._handleInitialization)}return super.enable()}disable(){if(this._handleInitialization)Zp.unsubscribe("fastify.initialization",this._handleInitialization),this._handleInitialization=void 0;return super.disable()}init(){return[]}plugin(){let Z=this;return J[Symbol.for("skip-override")]=!0,J[Symbol.for("fastify.display-name")]="@fastify/otel",J[Symbol.for("plugin-meta")]={fastify:vx0,name:"@fastify/otel"},J;function J(X,$,Y){X.decorate(x4,Z),X.decorate($p,X.addHook),X.decorate(Yp,X.setNotFoundHandler),X.decorateRequest("opentelemetry",function(){let V=this[Z3];return{span:this[F7],tracer:Z.tracer,context:V,inject:(B,U)=>{return k1.propagation.inject(V,B,U)},extract:(B,U)=>{return k1.propagation.extract(V,B,U)}}}),X.decorateRequest(F7,null),X.decorateRequest(Z3,null),X.addHook("onRoute",function(H){if(Z[Zz]?.(H)===!0){Z._logger.debug(`Ignoring route instrumentation ${H.method} ${H.url} because it matches the ignore path`);return}for(let V of Xp)if(H[V]!=null){let F=H[V];if(typeof F==="function")H[V]=G(F,{[d1.ATTR_SERVICE_NAME]:X[x4].servername,[$1.HOOK_NAME]:`${this.pluginName} - route -> ${V}`,[$1.FASTIFY_TYPE]:V7.ROUTE,[d1.ATTR_HTTP_ROUTE]:H.url,[$1.HOOK_CALLBACK_NAME]:F.name?.length>0?F.name:e5});else if(Array.isArray(F)){let B=[];for(let U of F)B.push(G(U,{[d1.ATTR_SERVICE_NAME]:X[x4].servername,[$1.HOOK_NAME]:`${this.pluginName} - route -> ${V}`,[$1.FASTIFY_TYPE]:V7.ROUTE,[d1.ATTR_HTTP_ROUTE]:H.url,[$1.HOOK_CALLBACK_NAME]:U.name?.length>0?U.name:e5}));H[V]=B}}if(H.onSend!=null)H.onSend=Array.isArray(H.onSend)?[...H.onSend,Q]:[H.onSend,Q];else H.onSend=Q;if(H.onError!=null)H.onError=Array.isArray(H.onError)?[...H.onError,W]:[H.onError,W];else H.onError=W;H.handler=G(H.handler,{[d1.ATTR_SERVICE_NAME]:X[x4].servername,[$1.HOOK_NAME]:`${this.pluginName} - route-handler`,[$1.FASTIFY_TYPE]:V7.HANDLER,[d1.ATTR_HTTP_ROUTE]:H.url,[$1.HOOK_CALLBACK_NAME]:H.handler.name.length>0?H.handler.name:e5})}),X.addHook("onRequest",function(H,V,F){if(this[x4].isEnabled()===!1)return F();else if(this[x4][Zz]?.({url:H.url,method:H.method})===!0)return this[x4]._logger.debug(`Ignoring request ${H.method} ${H.url} because it matches the ignore path`),F();let B=k1.context.active();if(k1.trace.getSpan(B)==null)B=k1.propagation.extract(B,H.headers);let U=Jz.getRPCMetadata(B);if(H.routeOptions.url!=null&&U?.type===Jz.RPCType.HTTP)U.route=H.routeOptions.url;let D=this[x4].tracer.startSpan("request",{attributes:{[d1.ATTR_SERVICE_NAME]:X[x4].servername,[$1.ROOT]:"@fastify/otel",[d1.ATTR_HTTP_ROUTE]:H.url,[d1.ATTR_HTTP_REQUEST_METHOD]:H.method}},B);H[Z3]=k1.trace.setSpan(B,D),H[F7]=D,k1.context.with(H[Z3],()=>{F()})}),X.addHook("onResponse",function(H,V,F){let B=H[F7];if(B!=null)B.setStatus({code:k1.SpanStatusCode.OK,message:"OK"}),B.setAttributes({[d1.ATTR_HTTP_RESPONSE_STATUS_CODE]:404}),B.end();H[F7]=null,F()}),X.addHook=K,X.setNotFoundHandler=z,Y();function Q(H,V,F,B){let U=H[F7];if(U!=null){if(V.statusCode<500)U.setStatus({code:k1.SpanStatusCode.OK,message:"OK"});U.setAttributes({[d1.ATTR_HTTP_RESPONSE_STATUS_CODE]:V.statusCode}),U.end()}H[F7]=null,B(null,F)}function W(H,V,F,B){let U=H[F7];if(U!=null)U.setStatus({code:k1.SpanStatusCode.ERROR,message:F.message}),U.recordException(F);B()}function K(H,V){let F=this[$p];if(Xp.includes(H))return F.call(this,H,G(V,{[d1.ATTR_SERVICE_NAME]:X[x4].servername,[$1.HOOK_NAME]:`${this.pluginName} - ${H}`,[$1.FASTIFY_TYPE]:V7.INSTANCE,[$1.HOOK_CALLBACK_NAME]:V.name?.length>0?V.name:e5}));else return F.call(this,H,V)}function z(H,V){let F=this[Yp];if(typeof H==="function")V=G(H,{[d1.ATTR_SERVICE_NAME]:X[x4].servername,[$1.HOOK_NAME]:`${this.pluginName} - not-found-handler`,[$1.FASTIFY_TYPE]:V7.INSTANCE,[$1.HOOK_CALLBACK_NAME]:H.name?.length>0?H.name:e5}),F.call(this,V);else{if(H.preValidation!=null)H.preValidation=G(H.preValidation,{[d1.ATTR_SERVICE_NAME]:X[x4].servername,[$1.HOOK_NAME]:`${this.pluginName} - not-found-handler - preValidation`,[$1.FASTIFY_TYPE]:V7.INSTANCE,[$1.HOOK_CALLBACK_NAME]:H.preValidation.name?.length>0?H.preValidation.name:e5});if(H.preHandler!=null)H.preHandler=G(H.preHandler,{[d1.ATTR_SERVICE_NAME]:X[x4].servername,[$1.HOOK_NAME]:`${this.pluginName} - not-found-handler - preHandler`,[$1.FASTIFY_TYPE]:V7.INSTANCE,[$1.HOOK_CALLBACK_NAME]:H.preHandler.name?.length>0?H.preHandler.name:e5});V=G(V,{[d1.ATTR_SERVICE_NAME]:X[x4].servername,[$1.HOOK_NAME]:`${this.pluginName} - not-found-handler`,[$1.FASTIFY_TYPE]:V7.INSTANCE,[$1.HOOK_CALLBACK_NAME]:V.name?.length>0?V.name:e5}),F.call(this,H,V)}}function G(H,V={}){return function(...B){let U=this[x4],[D]=B;if(U.isEnabled()===!1)return H.call(this,...B);let _=D[Z3]??k1.context.active(),O=U.tracer.startSpan(`handler - ${H.name?.length>0?H.name:this.pluginName??e5}`,{attributes:V},_);return k1.context.with(k1.trace.setSpan(_,O),function(){try{let w=H.call(this,...B);if(typeof w?.then==="function")return w.then((j)=>{return O.end(),j},(j)=>{return O.setStatus({code:k1.SpanStatusCode.ERROR,message:j.message}),O.recordException(j),O.end(),Promise.reject(j)});return O.end(),w}catch(w){throw O.setStatus({code:k1.SpanStatusCode.ERROR,message:w.message}),O.recordException(w),O.end(),w}},this)}}}}}var I8=k(f(),1),$z=k(H1(),1),yZ=k(H0(),1),Hp=k(p0(),1);var Z9;(function(Z){Z.FASTIFY_NAME="fastify.name";let X="fastify.type";Z.FASTIFY_TYPE=X;let $="hook.name";Z.HOOK_NAME=$;let Y="plugin.name";Z.PLUGIN_NAME=Y})(Z9||(Z9={}));var J3;(function(Z){Z.MIDDLEWARE="middleware";let X="request_handler";Z.REQUEST_HANDLER=X})(J3||(J3={}));var X3;(function(Z){Z.MIDDLEWARE="middleware";let X="request handler";Z.REQUEST_HANDLER=X})(X3||(X3={}));var Kp=k(f(),1);var $3=Symbol("opentelemetry.instrumentation.fastify.request_active_span");function Q2(Z,J,X,$={}){let Y=J.startSpan(X,{attributes:$}),Q=Z[$3]||[];return Q.push(Y),Object.defineProperty(Z,$3,{enumerable:!1,configurable:!0,value:Q}),Y}function Xz(Z,J){let X=Z[$3]||[];if(!X.length)return;X.forEach(($)=>{if(J)$.setStatus({code:Kp.SpanStatusCode.ERROR,message:J.message}),$.recordException(J);$.end()}),delete Z[$3]}function zp(Z,J,X){let $,Y=void 0;try{if(Y=Z(),Wp(Y))Y.then((Q)=>J(void 0,Q),(Q)=>J(Q))}catch(Q){$=Q}finally{if(!Wp(Y)){if(J($,Y),$)throw $}return Y}}function Wp(Z){return typeof Z==="object"&&Z&&typeof Object.getOwnPropertyDescriptor(Z,"then")?.value==="function"||!1}var hx0="0.1.0",fx0="@sentry/instrumentation-fastify-v3",Gp="anonymous",bx0=new Set(["onTimeout","onRequest","preParsing","preValidation","preSerialization","preHandler","onSend","onResponse","onError"]);class W2 extends yZ.InstrumentationBase{constructor(Z={}){super(fx0,hx0,Z)}init(){return[new yZ.InstrumentationNodeModuleDefinition("fastify",[">=3.0.0 <4"],(Z)=>{return this._patchConstructor(Z)})]}_hookOnRequest(){let Z=this;return function(X,$,Y){if(!Z.isEnabled())return Y();Z._wrap($,"send",Z._patchSend());let Q=X,W=$z.getRPCMetadata(I8.context.active()),K=Q.routeOptions?Q.routeOptions.url:X.routerPath;if(K&&W?.type===$z.RPCType.HTTP)W.route=K;let z=X.method||"GET";R0().setTransactionName(`${z} ${K}`),Y()}}_wrapHandler(Z,J,X,$){let Y=this;return this._diag.debug("Patching fastify route.handler function"),function(...Q){if(!Y.isEnabled())return X.apply(this,Q);let W=X.name||Z||Gp,K=`${X3.MIDDLEWARE} - ${W}`,z=Q[1],G=Q2(z,Y.tracer,K,{[Z9.FASTIFY_TYPE]:J3.MIDDLEWARE,[Z9.PLUGIN_NAME]:Z,[Z9.HOOK_NAME]:J}),H=$&&Q[Q.length-1];if(H)Q[Q.length-1]=function(...V){Xz(z),H.apply(this,V)};return I8.context.with(I8.trace.setSpan(I8.context.active(),G),()=>{return zp(()=>{return X.apply(this,Q)},(V)=>{if(V instanceof Error)G.setStatus({code:I8.SpanStatusCode.ERROR,message:V.message}),G.recordException(V);if(!$)Xz(z)})})}}_wrapAddHook(){let Z=this;return this._diag.debug("Patching fastify server.addHook function"),function(J){return function(...$){let Y=$[0],Q=$[1],W=this.pluginName;if(!bx0.has(Y))return J.apply(this,$);let K=typeof $[$.length-1]==="function"&&Q.constructor.name!=="AsyncFunction";return J.apply(this,[Y,Z._wrapHandler(W,Y,Q,K)])}}}_patchConstructor(Z){let J=this;function X(...$){let Y=Z.fastify.apply(this,$);return Y.addHook("onRequest",J._hookOnRequest()),Y.addHook("preHandler",J._hookPreHandler()),gx0(),J._wrap(Y,"addHook",J._wrapAddHook()),Y}if(Z.errorCodes!==void 0)X.errorCodes=Z.errorCodes;return X.fastify=X,X.default=X,X}_patchSend(){let Z=this;return this._diag.debug("Patching fastify reply.send function"),function(X){return function(...Y){let Q=Y[0];if(!Z.isEnabled())return X.apply(this,Y);return yZ.safeExecuteInTheMiddle(()=>{return X.apply(this,Y)},(W)=>{if(!W&&Q instanceof Error)W=Q;Xz(this,W)})}}}_hookPreHandler(){let Z=this;return this._diag.debug("Patching fastify preHandler function"),function(X,$,Y){if(!Z.isEnabled())return Y();let Q=X,W=Q.routeOptions?.handler||Q.context?.handler,K=W?.name.startsWith("bound ")?W.name.substring(6):W?.name,z=`${X3.REQUEST_HANDLER} - ${K||this.pluginName||Gp}`,G={[Z9.PLUGIN_NAME]:this.pluginName,[Z9.FASTIFY_TYPE]:J3.REQUEST_HANDLER,[Hp.SEMATTRS_HTTP_ROUTE]:Q.routeOptions?Q.routeOptions.url:X.routerPath};if(K)G[Z9.FASTIFY_NAME]=K;let H=Q2($,Z.tracer,z,G);Vp(H);let{requestHook:V}=Z.getConfig();if(V)yZ.safeExecuteInTheMiddle(()=>V(H,{request:X}),(F)=>{if(F)Z._diag.error("request hook failed",F)},!0);return I8.context.with(I8.trace.setSpan(I8.context.active(),H),()=>{Y()})}}}function gx0(){let Z=u();if(Z)Z.on("spanStart",(J)=>{Vp(J)})}function Vp(Z){let J=J0(Z).data,X=J["fastify.type"];if(J[K0]||!X)return;Z.setAttributes({[X0]:"auto.http.otel.fastify",[K0]:`${X}.fastify`});let $=J["fastify.name"]||J["plugin.name"]||J["hook.name"];if(typeof $==="string"){let Y=$.replace(/^fastify -> /,"").replace(/^@fastify\/otel -> /,"");Z.updateName(Y)}}var Yz="Fastify",Bp=a(`${Yz}.v3`,()=>new W2);function mx0(){let Z=u();if(!Z)return;else return Z.getIntegrationByName(Yz)}function Fp(Z,J,X,$){let Y=mx0()?.getShouldHandleError()||Dp;if($==="diagnostics-channel")this.diagnosticsChannelExists=!0;if(this.diagnosticsChannelExists&&$==="onError-hook"){N1&&A.warn("Fastify error handler was already registered via diagnostics channel.","You can safely remove `setupFastifyErrorHandler` call and set `shouldHandleError` on the integration options.");return}if(Y(Z,J,X))V0(Z,{mechanism:{handled:!1,type:"auto.function.fastify"}})}var Up=a(`${Yz}.v5`,()=>{let Z=new Y2,J=Z.plugin();return K2.subscribe("fastify.initialization",(X)=>{let $=X.fastify;$?.register(J).after((Y)=>{if(Y)N1&&A.error("Failed to setup Fastify instrumentation",Y);else if(ux0(),$)cx0($)})}),K2.subscribe("tracing:fastify.request.handler:error",(X)=>{let{error:$,request:Y,reply:Q}=X;Fp.call(Fp,$,Y,Q,"diagnostics-channel")}),Z}),dx0=({shouldHandleError:Z})=>{let J;return{name:Yz,setupOnce(){J=Z||Dp,Bp(),Up()},getShouldHandleError(){return J},setShouldHandleError(X){J=X}}},Lp=S((Z={})=>dx0(Z));function Dp(Z,J,X){let $=X.statusCode;return $>=500||$<=299}function _p(Z){let J=J0(Z),X=J.description,$=J.data,Y=$["fastify.type"],Q=Y==="hook",W=Y===X?.startsWith("handler -"),K=X==="request"||Y==="request-handler";if($[K0]||!W&&!K&&!Q)return;let z=Q?"hook":W?"middleware":K?"request-handler":"<unknown>";Z.setAttributes({[X0]:"auto.http.otel.fastify",[K0]:`${z}.fastify`});let G=$["fastify.name"]||$["plugin.name"]||$["hook.name"];if(typeof G==="string"){let H=G.replace(/^fastify -> /,"").replace(/^@fastify\/otel -> /,"");Z.updateName(H)}}function ux0(){let Z=u();if(Z)Z.on("spanStart",(J)=>{_p(J)})}function cx0(Z){Z.addHook("onRequest",async(J,X)=>{if(J.opentelemetry){let{span:Q}=J.opentelemetry();if(Q)_p(Q)}let $=J.routeOptions?.url,Y=J.method||"GET";R0().setTransactionName(`${Y} ${$}`)})}var Zi=k(f(),1),Ji=k(ep(),1);var Xi="Graphql",$i=a(Xi,Ji.GraphQLInstrumentation,(Z)=>{let J=Qi(Z);return{...J,responseHook(X,$){if(i0(X,"auto.graphql.otel.graphql"),$.errors?.length&&!J0(X).status)X.setStatus({code:Zi.SpanStatusCode.ERROR});let Q=J0(X).data,W=Q["graphql.operation.type"],K=Q["graphql.operation.name"];if(J.useOperationNameForRootSpan&&W){let z=q1(X),H=J0(z).data[BX]||[],V=K?`${W} ${K}`:`${W}`;if(Array.isArray(H))H.push(V),z.setAttribute(BX,H);else if(typeof H==="string")z.setAttribute(BX,[H,V]);else z.setAttribute(BX,V);if(!J0(z).data["original-description"])z.setAttribute("original-description",J0(z).description);z.updateName(`${J0(z).data["original-description"]} (${wv0(H)})`)}}}}),Ov0=(Z={})=>{return{name:Xi,setupOnce(){$i(Qi(Z))}}},Yi=S(Ov0);function Qi(Z){return{ignoreResolveSpans:!0,ignoreTrivialResolveSpans:!0,useOperationNameForRootSpan:!0,...Z}}function wv0(Z){if(Array.isArray(Z)){let J=Z.slice().sort();if(J.length<=5)return J.join(", ");else return`${J.slice(0,5).join(", ")}, +${J.length-5}`}return`${Z}`}var Pi=k(Ri(),1);var Ei="Kafka",Ii=a(Ei,()=>new Pi.KafkaJsInstrumentation({consumerHook(Z){i0(Z,"auto.kafkajs.otel.consumer")},producerHook(Z){i0(Z,"auto.kafkajs.otel.producer")}})),gv0=()=>{return{name:Ei,setupOnce(){Ii()}}},yi=S(gv0);var ci=k(ui(),1);var li="LruMemoizer",pi=a(li,()=>new ci.LruMemoizerInstrumentation),cv0=()=>{return{name:li,setupOnce(){pi()}}},ii=S(cv0);var Gn=k(zn(),1);var Hn="Mongo",Vn=a(Hn,()=>new Gn.MongoDBInstrumentation({dbStatementSerializer:Qh0,responseHook(Z){i0(Z,"auto.db.otel.mongo")}}));function Qh0(Z){let J=j2(Z);return JSON.stringify(J)}function j2(Z){if(Array.isArray(Z))return Z.map((J)=>j2(J));if(Wh0(Z)){let J={};return Object.entries(Z).map(([X,$])=>[X,j2($)]).reduce((X,$)=>{if(zh0($))X[$[0]]=$[1];return X},J)}return"?"}function Wh0(Z){return typeof Z==="object"&&Z!==null&&!Kh0(Z)}function Kh0(Z){let J=!1;if(typeof Buffer<"u")J=Buffer.isBuffer(Z);return J}function zh0(Z){return Array.isArray(Z)}var Gh0=()=>{return{name:Hn,setupOnce(){Vn()}}},Fn=S(Gh0);var Sn=k(yn(),1);var kn="Mongoose",xn=a(kn,()=>new Sn.MongooseInstrumentation({responseHook(Z){i0(Z,"auto.db.otel.mongoose")}})),Ih0=()=>{return{name:kn,setupOnce(){xn()}}},vn=S(Ih0);var en=k(tn(),1);var Zo="Mysql",Jo=a(Zo,()=>new en.MySQLInstrumentation({})),Jf0=()=>{return{name:Zo,setupOnce(){Jo()}}},Xo=S(Jf0);var Mo=k(jo(),1);var Ao="Mysql2",To=a(Ao,()=>new Mo.MySQL2Instrumentation({responseHook(Z){i0(Z,"auto.db.otel.mysql2")}})),Ef0=()=>{return{name:Ao,setupOnce(){To()}}},qo=S(Ef0);var qa=k(lo(),1),Ca=k(wa(),1);var Vb0=["get","set","setex"],u2=["get","mget"],Fb0=["set","setex"];function B3(Z,J){return Z.includes(J.toLowerCase())}function c2(Z){if(B3(u2,Z))return"cache.get";else if(B3(Fb0,Z))return"cache.put";else return}function Bb0(Z,J){return J.some((X)=>Z.startsWith(X))}function Ma(Z,J){try{if(J.length===0)return;let X=(Y)=>{if(typeof Y==="string"||typeof Y==="number"||Buffer.isBuffer(Y))return[Y.toString()];else if(Array.isArray(Y))return ja(Y.map((Q)=>X(Q)));else return["<unknown>"]},$=J[0];if(B3(Vb0,Z)&&$!=null)return X($);return ja(J.map((Y)=>X(Y)))}catch{return}}function Aa(Z,J,X){if(!c2(Z))return!1;for(let $ of J)if(Bb0($,X))return!0;return!1}function Ta(Z){let J=(X)=>{try{if(Buffer.isBuffer(X))return X.byteLength;else if(typeof X==="string")return X.length;else if(typeof X==="number")return X.toString().length;else if(X===null||X===void 0)return 0;return JSON.stringify(X).length}catch{return}};return Array.isArray(Z)?Z.reduce((X,$)=>{let Y=J($);return typeof Y==="number"?X!==void 0?X+Y:Y:X},0):J(Z)}function ja(Z){let J=[],X=($)=>{$.forEach((Y)=>{if(Array.isArray(Y))X(Y);else J.push(Y)})};return X(Z),J}var wz="Redis",U3={},Na=(Z,J,X,$)=>{Z.setAttribute(X0,"auto.db.otel.redis");let Y=Ma(J,X),Q=c2(J);if(!Y||!Q||!U3.cachePrefixes||!Aa(J,Y,U3.cachePrefixes))return;let W=J0(Z).data["net.peer.name"],K=J0(Z).data["net.peer.port"];if(K&&W)Z.setAttributes({"network.peer.address":W,"network.peer.port":K});let z=Ta($);if(z)Z.setAttribute(xB,z);if(B3(u2,J)&&z!==void 0)Z.setAttribute(SB,z>0);Z.setAttributes({[K0]:Q,[kB]:Y});let G=Y.join(", ");Z.updateName(U3.maxCacheKeyLength?v9(G,U3.maxCacheKeyLength):G)},Ub0=a(`${wz}.IORedis`,()=>{return new qa.IORedisInstrumentation({responseHook:Na})}),Lb0=a(`${wz}.Redis`,()=>{return new Ca.RedisInstrumentation({responseHook:Na})}),Ra=Object.assign(()=>{Ub0(),Lb0()},{id:wz}),Db0=(Z={})=>{return{name:wz,setupOnce(){U3=Z,Ra()}}},Pa=S(Db0);var Yr=k($r(),1);var Qr="Postgres",Wr=a(Qr,()=>new Yr.PgInstrumentation({requireParentSpan:!0,requestHook(Z){i0(Z,"auto.db.otel.postgres")}})),zg0=()=>{return{name:Qr,setupOnce(){Wr()}}},Kr=S(zg0);var xX=k(f(),1),Y9=k(H0(),1),x1=k(p0(),1);var Nz="PostgresJs",zr=[">=3.0.0 <4"],Gg0=/^(SELECT|INSERT|UPDATE|DELETE|CREATE|DROP|ALTER)/i,Cz=Symbol("sentryPostgresConnectionContext"),r2=Symbol.for("sentry.instrumented.postgresjs"),Gr=Symbol.for("sentry.query.from.instrumented.sql"),Hr=a(Nz,(Z)=>new Vr({requireParentSpan:Z?.requireParentSpan??!0,requestHook:Z?.requestHook}));class Vr extends Y9.InstrumentationBase{constructor(Z){super("sentry-postgres-js",N0,Z)}init(){let Z=new Y9.InstrumentationNodeModuleDefinition("postgres",zr,(J)=>{try{return this._patchPostgres(J)}catch(X){return N1&&A.error("Failed to patch postgres module:",X),J}},(J)=>J);return["src","cf/src","cjs/src"].forEach((J)=>{Z.files.push(new Y9.InstrumentationNodeModuleFile(`postgres/${J}/query.js`,zr,this._patchQueryPrototype.bind(this),this._unpatchQueryPrototype.bind(this)))}),Z}_patchPostgres(Z){let J=typeof Z==="function",X=J?Z:Z.default;if(typeof X!=="function")return N1&&A.warn("postgres module does not export a function. Skipping instrumentation."),Z;let $=this,Y=function(...Q){let W=Reflect.construct(X,Q);if(!W||typeof W!=="function")return N1&&A.warn("postgres() did not return a valid instance"),W;return $._instrumentSqlInstance(W)};Object.setPrototypeOf(Y,X),Object.setPrototypeOf(Y.prototype,X.prototype);for(let Q of Object.getOwnPropertyNames(X))if(!["length","name","prototype"].includes(Q)){let W=Object.getOwnPropertyDescriptor(X,Q);if(W)Object.defineProperty(Y,Q,W)}if(J)return Y;else return CY(Z,"default",Y),Z}_wrapQueryMethod(Z,J,X){let $=this;return function(...Y){let Q=Reflect.apply(Z,J,Y);if(Q&&typeof Q==="object"&&"handle"in Q)$._wrapSingleQueryHandle(Q,X);return Q}}_wrapCallbackMethod(Z,J,X){let $=this;return function(...Y){let Q=X[Cz];if(typeof Y[Y.length-1]!=="function"){let H=Reflect.apply(Z,J,Y);if(H&&typeof H.then==="function")return H.then((V)=>{return $._instrumentSqlInstance(V,Q)});return H}let K=Y.length===1?Y[0]:Y[1],z=function(H){let V=$._instrumentSqlInstance(H,Q);return K(V)},G=Y.length===1?[z]:[Y[0],z];return Reflect.apply(Z,J,G)}}_setConnectionAttributes(Z,J){if(!J)return;if(J.ATTR_DB_NAMESPACE)Z.setAttribute(x1.ATTR_DB_NAMESPACE,J.ATTR_DB_NAMESPACE);if(J.ATTR_SERVER_ADDRESS)Z.setAttribute(x1.ATTR_SERVER_ADDRESS,J.ATTR_SERVER_ADDRESS);if(J.ATTR_SERVER_PORT!==void 0){let X=parseInt(J.ATTR_SERVER_PORT,10);if(!isNaN(X))Z.setAttribute(x1.ATTR_SERVER_PORT,X)}}_setOperationName(Z,J,X){if(X){Z.setAttribute(x1.ATTR_DB_OPERATION_NAME,X);return}let $=J?.match(Gg0);if($?.[1])Z.setAttribute(x1.ATTR_DB_OPERATION_NAME,$[1].toUpperCase())}_attachConnectionContext(Z,J){let X=Z;if(!X.options||typeof X.options!=="object")return;let $=X.options,Y=$.host?.[0]||"localhost",Q=$.port?.[0]||5432,W={ATTR_DB_NAMESPACE:typeof $.database==="string"&&$.database!==""?$.database:void 0,ATTR_SERVER_ADDRESS:Y,ATTR_SERVER_PORT:String(Q)};J[Cz]=W}_instrumentSqlInstance(Z,J){if(Z[r2])return Z;let X=this,$=new Proxy(Z,{apply(Y,Q,W){let K=Reflect.apply(Y,Q,W);if(K&&typeof K==="object"&&"handle"in K)X._wrapSingleQueryHandle(K,$);return K},get(Y,Q){let W=Y[Q];if(typeof Q!=="string"||typeof W!=="function")return W;if(Q==="unsafe"||Q==="file")return X._wrapQueryMethod(W,Y,$);if(Q==="begin"||Q==="reserve")return X._wrapCallbackMethod(W,Y,$);return W}});if(J)$[Cz]=J;else this._attachConnectionContext(Z,$);return Z[r2]=!0,$[r2]=!0,$}_wrapSingleQueryHandle(Z,J){if(Z.handle?.__sentryWrapped)return;Z[Gr]=!0;let X=Z.handle,$=this,Y=async function(...Q){if(!$._shouldCreateSpans())return X.apply(this,Q);let W=$._reconstructQuery(Z.strings),K=$._sanitizeSqlQuery(W);return z4({name:K||"postgresjs.query",op:"db"},(z)=>{i0(z,"auto.db.postgresjs"),z.setAttributes({[x1.ATTR_DB_SYSTEM_NAME]:"postgres",[x1.ATTR_DB_QUERY_TEXT]:K});let G=J?J[Cz]:void 0;$._setConnectionAttributes(z,G);let H=$.getConfig(),{requestHook:V}=H;if(V)Y9.safeExecuteInTheMiddle(()=>V(z,K,G),(B)=>{if(B)z.setAttribute("sentry.hook.error","requestHook failed"),N1&&A.error(`Error in requestHook for ${Nz} integration:`,B)},!0);let F=this;F.resolve=new Proxy(F.resolve,{apply:(B,U,D)=>{try{$._setOperationName(z,K,D?.[0]?.command),z.end()}catch(_){N1&&A.error("Error ending span in resolve callback:",_)}return Reflect.apply(B,U,D)}}),F.reject=new Proxy(F.reject,{apply:(B,U,D)=>{try{z.setStatus({code:A0,message:D?.[0]?.message||"unknown_error"}),z.setAttribute(x1.ATTR_DB_RESPONSE_STATUS_CODE,D?.[0]?.code||"unknown"),z.setAttribute(x1.ATTR_ERROR_TYPE,D?.[0]?.name||"unknown"),$._setOperationName(z,K),z.end()}catch(_){N1&&A.error("Error ending span in reject callback:",_)}return Reflect.apply(B,U,D)}});try{return X.apply(this,Q)}catch(B){throw z.setStatus({code:A0,message:B instanceof Error?B.message:"unknown_error"}),z.end(),B}})};Y.__sentryWrapped=!0,Z.handle=Y}_shouldCreateSpans(){let Z=this.getConfig();return xX.trace.getSpan(xX.context.active())!==void 0||!Z.requireParentSpan}_reconstructQuery(Z){if(!Z?.length)return;if(Z.length===1)return Z[0]||void 0;return Z.reduce((J,X,$)=>$===0?X:`${J}$${$}${X}`,"")}_sanitizeSqlQuery(Z){if(!Z)return"Unknown SQL Query";return Z.replace(/--.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/;\s*$/,"").replace(/\s+/g," ").trim().replace(/\bX'[0-9A-Fa-f]*'/gi,"?").replace(/\bB'[01]*'/gi,"?").replace(/'(?:[^']|'')*'/g,"?").replace(/\b0x[0-9A-Fa-f]+/gi,"?").replace(/\b(?:TRUE|FALSE)\b/gi,"?").replace(/-?\b\d+\.?\d*[eE][+-]?\d+\b/g,"?").replace(/-?\b\d+\.\d+\b/g,"?").replace(/-?\.\d+\b/g,"?").replace(/(?<!\$)-?\b\d+\b/g,"?").replace(/\bIN\b\s*\(\s*\?(?:\s*,\s*\?)*\s*\)/gi,"IN (?)").replace(/\bIN\b\s*\(\s*\$\d+(?:\s*,\s*\$\d+)*\s*\)/gi,"IN ($?)")}_patchQueryPrototype(Z){let J=this,X=Z.Query.prototype.handle;return Z.Query.prototype.handle=async function(...$){if(this[Gr])return X.apply(this,$);if(!J._shouldCreateSpans())return X.apply(this,$);let Y=J._reconstructQuery(this.strings),Q=J._sanitizeSqlQuery(Y);return z4({name:Q||"postgresjs.query",op:"db"},(W)=>{i0(W,"auto.db.postgresjs"),W.setAttributes({[x1.ATTR_DB_SYSTEM_NAME]:"postgres",[x1.ATTR_DB_QUERY_TEXT]:Q});let K=J.getConfig(),{requestHook:z}=K;if(z)Y9.safeExecuteInTheMiddle(()=>z(W,Q,void 0),(V)=>{if(V)W.setAttribute("sentry.hook.error","requestHook failed"),N1&&A.error(`Error in requestHook for ${Nz} integration:`,V)},!0);let G=this.resolve;this.resolve=new Proxy(G,{apply:(V,F,B)=>{try{J._setOperationName(W,Q,B?.[0]?.command),W.end()}catch(U){N1&&A.error("Error ending span in resolve callback:",U)}return Reflect.apply(V,F,B)}});let H=this.reject;this.reject=new Proxy(H,{apply:(V,F,B)=>{try{W.setStatus({code:A0,message:B?.[0]?.message||"unknown_error"}),W.setAttribute(x1.ATTR_DB_RESPONSE_STATUS_CODE,B?.[0]?.code||"unknown"),W.setAttribute(x1.ATTR_ERROR_TYPE,B?.[0]?.name||"unknown"),J._setOperationName(W,Q),W.end()}catch(U){N1&&A.error("Error ending span in reject callback:",U)}return Reflect.apply(V,F,B)}});try{return X.apply(this,$)}catch(V){throw W.setStatus({code:A0,message:V instanceof Error?V.message:"unknown_error"}),W.end(),V}})},Z.Query.prototype.handle.__sentry_original__=X,Z}_unpatchQueryPrototype(Z){if(Z.Query.prototype.handle.__sentry_original__)Z.Query.prototype.handle=Z.Query.prototype.handle.__sentry_original__;return Z}}var Hg0=(Z)=>{return{name:Nz,setupOnce(){Hr(Z)}}},Fr=S(Hg0);var r6=k(f(),1);var Lr=k(f(),1),Rz=k(H0(),1),_7=k(f(),1);var Vg0=process.env.PRISMA_SHOW_ALL_TRACES==="true",Fg0="00-10-10-00";function Bg0(Z){switch(Z){case"client":return _7.SpanKind.CLIENT;case"internal":default:return _7.SpanKind.INTERNAL}}var Ug0=class{tracerProvider;ignoreSpanTypes;constructor({tracerProvider:Z,ignoreSpanTypes:J}){this.tracerProvider=Z,this.ignoreSpanTypes=J}isEnabled(){return!0}getTraceParent(Z){let J=_7.trace.getSpanContext(Z??_7.context.active());if(J)return`00-${J.traceId}-${J.spanId}-0${J.traceFlags}`;return Fg0}dispatchEngineSpans(Z){let J=this.tracerProvider.getTracer("prisma"),X=new Map,$=Z.filter((Y)=>Y.parentId===null);for(let Y of $)Dr(J,Y,Z,X,this.ignoreSpanTypes)}getActiveContext(){return _7.context.active()}runInChildSpan(Z,J){if(typeof Z==="string")Z={name:Z};if(Z.internal&&!Vg0)return J();let X=this.tracerProvider.getTracer("prisma"),$=Z.context??this.getActiveContext(),Y=`prisma:client:${Z.name}`;if(_r(Y,this.ignoreSpanTypes))return J();if(Z.active===!1){let Q=X.startSpan(Y,Z,$);return Br(Q,J(Q,$))}return X.startActiveSpan(Y,Z,(Q)=>Br(Q,J(Q,$)))}};function Dr(Z,J,X,$,Y){if(_r(J.name,Y))return;let Q={attributes:J.attributes,kind:Bg0(J.kind),startTime:J.startTime};Z.startActiveSpan(J.name,Q,(W)=>{if($.set(J.id,W.spanContext().spanId),J.links)W.addLinks(J.links.flatMap((z)=>{let G=$.get(z);if(!G)return[];return{context:{spanId:G,traceId:W.spanContext().traceId,traceFlags:W.spanContext().traceFlags}}}));let K=X.filter((z)=>z.parentId===J.id);for(let z of K)Dr(Z,z,X,$,Y);W.end(J.endTime)})}function Br(Z,J){if(Lg0(J))return J.then((X)=>{return Z.end(),X},(X)=>{throw Z.end(),X});return Z.end(),J}function Lg0(Z){return Z!=null&&typeof Z.then==="function"}function _r(Z,J){return J.some((X)=>typeof X==="string"?X===Z:X.test(Z))}var Or={name:"@prisma/instrumentation",version:"6.19.0",description:"OpenTelemetry compliant instrumentation for Prisma Client",main:"dist/index.js",module:"dist/index.mjs",types:"dist/index.d.ts",exports:{".":{require:{types:"./dist/index.d.ts",default:"./dist/index.js"},import:{types:"./dist/index.d.ts",default:"./dist/index.mjs"}}},license:"Apache-2.0",homepage:"https://www.prisma.io",repository:{type:"git",url:"https://github.com/prisma/prisma.git",directory:"packages/instrumentation"},bugs:"https://github.com/prisma/prisma/issues",devDependencies:{"@prisma/internals":"workspace:*","@types/node":"18.19.76","@opentelemetry/api":"1.9.0",typescript:"5.4.5"},dependencies:{"@opentelemetry/instrumentation":">=0.52.0 <1"},peerDependencies:{"@opentelemetry/api":"^1.8"},files:["dist"],keywords:["prisma","instrumentation","opentelemetry","otel"],scripts:{dev:"DEV=true tsx helpers/build.ts",build:"tsx helpers/build.ts",prepublishOnly:"pnpm run build",test:"vitest run"},sideEffects:!1},t2=Or.version,Dg0=t2.split(".")[0],Ur="PRISMA_INSTRUMENTATION",s2=`V${Dg0}_PRISMA_INSTRUMENTATION`,_g0=Or.name,Og0="@prisma/client",wr=class extends Rz.InstrumentationBase{tracerProvider;constructor(Z={}){super(_g0,t2,Z)}setTracerProvider(Z){this.tracerProvider=Z}init(){return[new Rz.InstrumentationNodeModuleDefinition(Og0,[t2])]}enable(){let Z=this._config,J={helper:new Ug0({tracerProvider:this.tracerProvider??Lr.trace.getTracerProvider(),ignoreSpanTypes:Z.ignoreSpanTypes??[]})};global[Ur]=J,global[s2]=J}disable(){delete global[Ur],delete global[s2]}isEnabled(){return Boolean(global[s2])}};var jr="Prisma";function wg0(Z){return!!Z&&typeof Z==="object"&&"dispatchEngineSpans"in Z}function Mr(){let Z=globalThis.PRISMA_INSTRUMENTATION;return Z&&typeof Z==="object"&&"helper"in Z?Z.helper:void 0}class Ar extends wr{constructor(){super()}enable(){super.enable();let Z=Mr();if(wg0(Z))Z.createEngineSpan=(J)=>{let X=r6.trace.getTracer("prismaV5Compatibility"),$=X._idGenerator;if(!$){y1(()=>{console.warn("[Sentry] Could not find _idGenerator on tracer, skipping Prisma v5 compatibility - some Prisma spans may be missing!")});return}try{J.spans.forEach((Y)=>{let Q=jg0(Y.kind),W=Y.parent_span_id,K=Y.span_id,z=Y.trace_id,G=Y.links?.map((V)=>{return{context:{traceId:V.trace_id,spanId:V.span_id,traceFlags:r6.TraceFlags.SAMPLED}}}),H=r6.trace.setSpanContext(r6.context.active(),{traceId:z,spanId:W,traceFlags:r6.TraceFlags.SAMPLED});r6.context.with(H,()=>{let V={generateTraceId:()=>{return z},generateSpanId:()=>{return K}};X._idGenerator=V,X.startSpan(Y.name,{kind:Q,links:G,startTime:Y.start_time,attributes:Y.attributes}).end(Y.end_time),X._idGenerator=$})})}finally{X._idGenerator=$}}}}function jg0(Z){switch(Z){case"client":return r6.SpanKind.CLIENT;case"internal":default:return r6.SpanKind.INTERNAL}}var Mg0=a(jr,(Z)=>{return new Ar}),Tr=S((Z)=>{return{name:jr,setupOnce(){Mg0()},setup(J){if(!Mr())return;J.on("spanStart",(X)=>{let $=J0(X);if($.description?.startsWith("prisma:"))X.setAttribute(X0,"auto.db.otel.prisma");if($.description==="prisma:engine:db_query"&&$.data["db.query.text"])X.updateName($.data["db.query.text"]);if($.description==="prisma:engine:db_query"&&!$.data["db.system"])X.setAttribute("db.system","prisma")})}}});var pr=k(lr(),1);var ir="Hapi",nr=a(ir,()=>new pr.HapiInstrumentation),pg0=()=>{return{name:ir,setupOnce(){nr()}}},or=S(pg0);var Iz=k(p0(),1);var w7={HONO_TYPE:"hono.type",HONO_NAME:"hono.name"},w3={MIDDLEWARE:"middleware",REQUEST_HANDLER:"request_handler"};var xZ=k(f(),1),Ez=k(H0(),1);var ig0="@sentry/instrumentation-hono",ng0="0.0.1";class $D extends Ez.InstrumentationBase{constructor(Z={}){super(ig0,ng0,Z)}init(){return[new Ez.InstrumentationNodeModuleDefinition("hono",[">=4.0.0 <5"],(Z)=>this._patch(Z))]}_patch(Z){let J=this;class X extends Z.Hono{constructor(...$){super(...$);J._wrap(this,"get",J._patchHandler()),J._wrap(this,"post",J._patchHandler()),J._wrap(this,"put",J._patchHandler()),J._wrap(this,"delete",J._patchHandler()),J._wrap(this,"options",J._patchHandler()),J._wrap(this,"patch",J._patchHandler()),J._wrap(this,"all",J._patchHandler()),J._wrap(this,"on",J._patchOnHandler()),J._wrap(this,"use",J._patchMiddlewareHandler())}}try{Z.Hono=X}catch{return{...Z,Hono:X}}return Z}_patchHandler(){let Z=this;return function(J){return function(...$){if(typeof $[0]==="string"){let Y=$[0];if($.length===1)return J.apply(this,[Y]);let Q=$.slice(1);return J.apply(this,[Y,...Q.map((W)=>Z._wrapHandler(W))])}return J.apply(this,$.map((Y)=>Z._wrapHandler(Y)))}}}_patchOnHandler(){let Z=this;return function(J){return function(...$){let Y=$.slice(2);return J.apply(this,[...$.slice(0,2),...Y.map((Q)=>Z._wrapHandler(Q))])}}}_patchMiddlewareHandler(){let Z=this;return function(J){return function(...$){if(typeof $[0]==="string"){let Y=$[0];if($.length===1)return J.apply(this,[Y]);let Q=$.slice(1);return J.apply(this,[Y,...Q.map((W)=>Z._wrapHandler(W))])}return J.apply(this,$.map((Y)=>Z._wrapHandler(Y)))}}}_wrapHandler(Z){let J=this;return function(X,$){if(!J.isEnabled())return Z.apply(this,[X,$]);let Y=X.req.path,Q=J.tracer.startSpan(Y);return xZ.context.with(xZ.trace.setSpan(xZ.context.active(),Q),()=>{return J._safeExecute(()=>{let W=Z.apply(this,[X,$]);if(I4(W))return W.then((K)=>{let z=J._determineHandlerType(K);return Q.setAttributes({[w7.HONO_TYPE]:z,[w7.HONO_NAME]:z===w3.REQUEST_HANDLER?Y:Z.name||"anonymous"}),J.getConfig().responseHook?.(Q),K});else{let K=J._determineHandlerType(W);return Q.setAttributes({[w7.HONO_TYPE]:K,[w7.HONO_NAME]:K===w3.REQUEST_HANDLER?Y:Z.name||"anonymous"}),J.getConfig().responseHook?.(Q),W}},()=>Q.end(),(W)=>{J._handleError(Q,W),Q.end()})})}}_safeExecute(Z,J,X){try{let $=Z();if(I4($))$.then(()=>J(),(Y)=>X(Y));else J();return $}catch($){throw X($),$}}_determineHandlerType(Z){return Z===void 0?w3.MIDDLEWARE:w3.REQUEST_HANDLER}_handleError(Z,J){if(J instanceof Error)Z.setStatus({code:xZ.SpanStatusCode.ERROR,message:J.message}),Z.recordException(J)}}var ar="Hono";function og0(Z){let J=J0(Z).data,X=J[w7.HONO_TYPE];if(J[K0]||!X)return;Z.setAttributes({[X0]:"auto.http.otel.hono",[K0]:`${X}.hono`});let $=J[w7.HONO_NAME];if(typeof $==="string")Z.updateName($);if(R0()===B6()){N1&&A.warn("Isolation scope is default isolation scope - skipping setting transactionName");return}let Y=J[Iz.ATTR_HTTP_ROUTE],Q=J[Iz.ATTR_HTTP_REQUEST_METHOD];if(typeof Y==="string"&&typeof Q==="string")R0().setTransactionName(`${Q} ${Y}`)}var rr=a(ar,()=>new $D({responseHook:(Z)=>{og0(Z)}})),ag0=()=>{return{name:ar,setupOnce(){rr()}}},sr=S(ag0);var js=k(ws(),1),Ms=k(p0(),1);var As="Koa",Ts=a(As,js.KoaInstrumentation,(Z={})=>{return{ignoreLayersType:Z.ignoreLayersType,requestHook(J,X){i0(J,"auto.http.otel.koa");let $=J0(J).data,Y=$["koa.type"];if(Y)J.setAttribute(K0,`${Y}.koa`);let Q=$["koa.name"];if(typeof Q==="string")J.updateName(Q||"< unknown >");if(R0()===B6()){N1&&A.warn("Isolation scope is default isolation scope - skipping setting transactionName");return}let W=$[Ms.ATTR_HTTP_ROUTE],K=X.context?.request?.method?.toUpperCase()||"GET";if(W)R0().setTransactionName(`${K} ${W}`)}}}),Km0=(Z={})=>{return{name:As,setupOnce(){Ts(Z)}}},qs=S(Km0);var ps=k(ls(),1);var is="Connect",ns=a(is,()=>new ps.ConnectInstrumentation),Mm0=()=>{return{name:is,setupOnce(){ns()}}},os=S(Mm0);var Ft=k(Vt(),1);var hm0=new Set(["callProcedure","execSql","execSqlBatch","execBulkLoad","prepare","execute"]),Bt="Tedious",Ut=a(Bt,()=>new Ft.TediousInstrumentation({})),fm0=()=>{let Z;return{name:Bt,setupOnce(){let J=Ut();Z=RY(J)},setup(J){Z?.(()=>J.on("spanStart",(X)=>{let{description:$,data:Y}=J0(X);if(!$||Y["db.system"]!=="mssql")return;let Q=$.split(" ")[0]||"";if(hm0.has(Q))X.setAttribute(X0,"auto.db.otel.tedious")}))}}},Lt=S(fm0);var Ct=k(qt(),1);var Nt="GenericPool",Rt=a(Nt,()=>new Ct.GenericPoolInstrumentation({})),dm0=()=>{let Z;return{name:Nt,setupOnce(){let J=Rt();Z=RY(J)},setup(J){Z?.(()=>J.on("spanStart",(X)=>{let Y=J0(X).description;if(Y==="generic-pool.aquire"||Y==="generic-pool.acquire")X.setAttribute(X0,"auto.db.otel.generic_pool")}))}}},Pt=S(dm0);var tt=k(st(),1);var et="Amqplib",Md0={consumeEndHook:(Z)=>{i0(Z,"auto.amqplib.otel.consumer")},publishHook:(Z)=>{i0(Z,"auto.amqplib.otel.publisher")}},Ze=a(et,()=>new tt.AmqplibInstrumentation(Md0)),Ad0=()=>{return{name:et,setupOnce(){Ze()}}},Je=S(Ad0);var q3="VercelAI";var gz=k(H0(),1);var Td0=[">=3.0.0 <7"],Xe=["generateText","streamText","generateObject","streamObject","embed","embedMany"];function qd0(Z){if(typeof Z!=="object"||Z===null)return!1;let J=Z;return"type"in J&&"error"in J&&"toolName"in J&&"toolCallId"in J&&J.type==="tool-error"&&J.error instanceof Error}function Cd0(Z){if(typeof Z!=="object"||Z===null||!("content"in Z))return;let J=Z;if(!Array.isArray(J.content))return;for(let X of J.content)if(qd0(X)){let $=NU(X.toolCallId);if($){let Y=$.spanContext();s4((Q)=>{Q.setContext("trace",{trace_id:Y.traceId,span_id:Y.spanId}),Q.setTag("vercel.ai.tool.name",X.toolName),Q.setTag("vercel.ai.tool.callId",X.toolCallId),Q.setLevel("error"),V0(X.error,{mechanism:{type:"auto.vercelai.otel",handled:!1}})}),RU(X.toolCallId)}else s4((Y)=>{Y.setTag("vercel.ai.tool.name",X.toolName),Y.setTag("vercel.ai.tool.callId",X.toolCallId),Y.setLevel("error"),V0(X.error,{mechanism:{type:"auto.vercelai.otel",handled:!1}})})}}function Nd0(Z,J,X,$){let Y=Z?.recordInputs!==void 0?Z.recordInputs:J.recordInputs!==void 0?J.recordInputs:X===!0?!0:$,Q=Z?.recordOutputs!==void 0?Z.recordOutputs:J.recordOutputs!==void 0?J.recordOutputs:X===!0?!0:$;return{recordInputs:Y,recordOutputs:Q}}class C3 extends gz.InstrumentationBase{__init(){this._isPatched=!1}__init2(){this._callbacks=[]}constructor(Z={}){super("@sentry/instrumentation-vercel-ai",N0,Z);C3.prototype.__init.call(this),C3.prototype.__init2.call(this)}init(){return new gz.InstrumentationNodeModuleDefinition("ai",Td0,this._patch.bind(this))}callWhenPatched(Z){if(this._isPatched)Z();else this._callbacks.push(Z)}_patch(Z){this._isPatched=!0,this._callbacks.forEach((X)=>X()),this._callbacks=[];let J=(X)=>{return new Proxy(X,{apply:($,Y,Q)=>{let W=Q[0].experimental_telemetry||{},K=W.isEnabled,z=u(),G=z?.getIntegrationByName(q3),H=G?.options,V=G?Boolean(z?.getOptions().sendDefaultPii):!1,{recordInputs:F,recordOutputs:B}=Nd0(H,W,K,V);return Q[0].experimental_telemetry={...W,isEnabled:K!==void 0?K:!0,recordInputs:F,recordOutputs:B},D6(()=>Reflect.apply($,Y,Q),(U)=>{if(U&&typeof U==="object")f1(U,"_sentry_active_span",t8())},()=>{},(U)=>{Cd0(U)})}})};if(Object.prototype.toString.call(Z)==="[object Module]"){for(let X of Xe)Z[X]=J(Z[X]);return Z}else{let X=Xe.reduce(($,Y)=>{return $[Y]=J(Z[Y]),$},{});return{...Z,...X}}}}var $e=a(q3,()=>new C3({}));function Rd0(Z){return!!Z.getIntegrationByName("Modules")?.getModules?.()?.ai}var Pd0=(Z={})=>{let J;return{name:q3,options:Z,setupOnce(){J=$e()},afterAllSetup(X){if(Z.force??Rd0(X))KK(X);else J?.callWhenPatched(()=>KK(X))}}},Ye=S(Pd0);var mz=k(H0(),1);var Ed0=[">=4.0.0 <7"];class AD extends mz.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-openai",N0,Z)}init(){return new mz.InstrumentationNodeModuleDefinition("openai",Ed0,this._patch.bind(this))}_patch(Z){let J=Z;return J=this._patchClient(J,"OpenAI"),J=this._patchClient(J,"AzureOpenAI"),J}_patchClient(Z,J){let X=Z[J];if(!X)return Z;let $=this.getConfig(),Y=function(...Q){if(OZ($7))return Reflect.construct(X,Q);let W=Reflect.construct(X,Q),K=u(),z=Boolean(K?.getOptions().sendDefaultPii),G=$.recordInputs??z,H=$.recordOutputs??z;return HK(W,{recordInputs:G,recordOutputs:H})};Object.setPrototypeOf(Y,X),Object.setPrototypeOf(Y.prototype,X.prototype);for(let Q of Object.getOwnPropertyNames(X))if(!["length","name","prototype"].includes(Q)){let W=Object.getOwnPropertyDescriptor(X,Q);if(W)Object.defineProperty(Y,Q,W)}try{Z[J]=Y}catch(Q){Object.defineProperty(Z,J,{value:Y,writable:!0,configurable:!0,enumerable:!0})}if(Z.default===X)try{Z.default=Y}catch(Q){Object.defineProperty(Z,"default",{value:Y,writable:!0,configurable:!0,enumerable:!0})}return Z}}var Qe=a($7,(Z)=>new AD(Z)),Id0=(Z={})=>{return{name:$7,setupOnce(){Qe(Z)}}},We=S(Id0);var dz=k(H0(),1);var yd0=[">=0.19.2 <1.0.0"];class TD extends dz.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-anthropic-ai",N0,Z)}init(){return new dz.InstrumentationNodeModuleDefinition("@anthropic-ai/sdk",yd0,this._patch.bind(this))}_patch(Z){let J=Z.Anthropic,X=this.getConfig(),$=function(...Y){if(OZ(Y7))return Reflect.construct(J,Y);let Q=Reflect.construct(J,Y),W=u(),K=Boolean(W?.getOptions().sendDefaultPii),z=X.recordInputs??K,G=X.recordOutputs??K;return IU(Q,{recordInputs:z,recordOutputs:G})};Object.setPrototypeOf($,J),Object.setPrototypeOf($.prototype,J.prototype);for(let Y of Object.getOwnPropertyNames(J))if(!["length","name","prototype"].includes(Y)){let Q=Object.getOwnPropertyDescriptor(J,Y);if(Q)Object.defineProperty($,Y,Q)}try{Z.Anthropic=$}catch(Y){Object.defineProperty(Z,"Anthropic",{value:$,writable:!0,configurable:!0,enumerable:!0})}if(Z.default===J)try{Z.default=$}catch(Y){Object.defineProperty(Z,"default",{value:$,writable:!0,configurable:!0,enumerable:!0})}return Z}}var Ke=a(Y7,(Z)=>new TD(Z)),Sd0=(Z={})=>{return{name:Y7,options:Z,setupOnce(){Ke(Z)}}},ze=S(Sd0);var gX=k(H0(),1);var Ge=[">=0.10.0 <2"];class qD extends gX.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-google-genai",N0,Z)}init(){return new gX.InstrumentationNodeModuleDefinition("@google/genai",Ge,(J)=>this._patch(J),(J)=>J,[new gX.InstrumentationNodeModuleFile("@google/genai/dist/node/index.cjs",Ge,(J)=>this._patch(J),(J)=>J)])}_patch(Z){let J=Z.GoogleGenAI,X=this.getConfig();if(typeof J!=="function")return Z;let $=function(...Y){if(OZ(Q7))return Reflect.construct(J,Y);let Q=Reflect.construct(J,Y),W=u(),K=Boolean(W?.getOptions().sendDefaultPii),z=X,G=z?.recordInputs??K,H=z?.recordOutputs??K;return xU(Q,{recordInputs:G,recordOutputs:H})};Object.setPrototypeOf($,J),Object.setPrototypeOf($.prototype,J.prototype);for(let Y of Object.getOwnPropertyNames(J))if(!["length","name","prototype"].includes(Y)){let Q=Object.getOwnPropertyDescriptor(J,Y);if(Q)Object.defineProperty($,Y,Q)}return CY(Z,"GoogleGenAI",$),Z}}var He=a(Q7,(Z)=>new qD(Z)),kd0=(Z={})=>{return{name:Q7,setupOnce(){He(Z)}}},Ve=S(kd0);var A7=k(H0(),1);var uz=[">=0.1.0 <2.0.0"];function xd0(Z,J){if(!Z)return[J];if(Array.isArray(Z)){if(Z.includes(J))return Z;return[...Z,J]}if(typeof Z==="object")return[Z,J];return Z}function vd0(Z,J,X){return new Proxy(Z,{apply($,Y,Q){let K=Q[1];if(!K||typeof K!=="object"||Array.isArray(K))K={},Q[1]=K;let z=K.callbacks,G=xd0(z,J);return K.callbacks=G,Reflect.apply($,Y,Q)}})}class CD extends A7.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-langchain",N0,Z)}init(){let Z=[],J=["@langchain/anthropic","@langchain/openai","@langchain/google-genai","@langchain/mistralai","@langchain/google-vertexai","@langchain/groq"];for(let X of J)Z.push(new A7.InstrumentationNodeModuleDefinition(X,uz,this._patch.bind(this),($)=>$,[new A7.InstrumentationNodeModuleFile(`${X}/dist/index.cjs`,uz,this._patch.bind(this),($)=>$)]));return Z.push(new A7.InstrumentationNodeModuleDefinition("langchain",uz,this._patch.bind(this),(X)=>X,[new A7.InstrumentationNodeModuleFile("langchain/dist/chat_models/universal.cjs",uz,this._patch.bind(this),(X)=>X)])),Z}_patch(Z){WU([$7,Y7,Q7]);let J=u(),X=Boolean(J?.getOptions().sendDefaultPii),$=this.getConfig(),Y=$?.recordInputs??X,Q=$?.recordOutputs??X,W=FK({recordInputs:Y,recordOutputs:Q});return this._patchRunnableMethods(Z,W),Z}_patchRunnableMethods(Z,J){let X=["ChatAnthropic","ChatOpenAI","ChatGoogleGenerativeAI","ChatMistralAI","ChatVertexAI","ChatGroq","ConfigurableModel"],$=Z.universal_exports??Z,Y=Object.values($).find((K)=>{return typeof K==="function"&&X.includes(K.name)});if(!Y)return;let Q=Y.prototype,W=["invoke","stream","batch"];for(let K of W){let z=Q[K];if(typeof z==="function")Q[K]=vd0(z,J)}}}var Fe=a(VK,(Z)=>new CD(Z)),hd0=(Z={})=>{return{name:VK,setupOnce(){Fe(Z)}}},Be=S(hd0);var mX=k(H0(),1);var Ue=[">=0.0.0 <2.0.0"];class ND extends mX.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-langgraph",N0,Z)}init(){return new mX.InstrumentationNodeModuleDefinition("@langchain/langgraph",Ue,this._patch.bind(this),(J)=>J,[new mX.InstrumentationNodeModuleFile("@langchain/langgraph/dist/index.cjs",Ue,this._patch.bind(this),(J)=>J)])}_patch(Z){let J=u(),X=Boolean(J?.getOptions().sendDefaultPii),$=this.getConfig(),Y=$.recordInputs??X,Q=$.recordOutputs??X,W={recordInputs:Y,recordOutputs:Q};if(Z.StateGraph&&typeof Z.StateGraph==="function"){let K=Z.StateGraph;K.prototype.compile=fU(K.prototype.compile,W)}return Z}}var Le=a(BK,(Z)=>new ND(Z)),fd0=(Z={})=>{return{name:BK,setupOnce(){Le(Z)}}},De=S(fd0);var qe=k(H0(),1);var W9=k(f(),1),K9=k(H0(),1),s6=k(p0(),1);import*as Oe from"net";function we(Z,J,X,$,Y){let W=()=>{},K=Y.firestoreSpanCreationHook;if(typeof K==="function")W=(H)=>{K9.safeExecuteInTheMiddle(()=>K(H),(V)=>{if(!V)return;W9.diag.error(V?.message)},!0)};let z=new K9.InstrumentationNodeModuleDefinition("@firebase/firestore",J,(H)=>_e(H,X,$,Z,W)),G=["@firebase/firestore/dist/lite/index.node.cjs.js","@firebase/firestore/dist/lite/index.node.mjs.js","@firebase/firestore/dist/lite/index.rn.esm2017.js","@firebase/firestore/dist/lite/index.cjs.js"];for(let H of G)z.files.push(new K9.InstrumentationNodeModuleFile(H,J,(V)=>_e(V,X,$,Z,W),(V)=>je(V,$)));return z}function _e(Z,J,X,$,Y){return je(Z,X),J(Z,"addDoc",bd0($,Y)),J(Z,"getDocs",md0($,Y)),J(Z,"setDoc",dd0($,Y)),J(Z,"deleteDoc",gd0($,Y)),Z}function je(Z,J){for(let X of["addDoc","getDocs","setDoc","deleteDoc"])if(K9.isWrapped(Z[X]))J(Z,X);return Z}function bd0(Z,J){return function($){return function(Y,Q){let W=lz(Z,"addDoc",Y);return J(W),cz(W,()=>{return $(Y,Q)})}}}function gd0(Z,J){return function($){return function(Y){let Q=lz(Z,"deleteDoc",Y.parent||Y);return J(Q),cz(Q,()=>{return $(Y)})}}}function md0(Z,J){return function($){return function(Y){let Q=lz(Z,"getDocs",Y);return J(Q),cz(Q,()=>{return $(Y)})}}}function dd0(Z,J){return function($){return function(Y,Q,W){let K=lz(Z,"setDoc",Y.parent||Y);return J(K),cz(K,()=>{return typeof W<"u"?$(Y,Q,W):$(Y,Q)})}}}function cz(Z,J){return W9.context.with(W9.trace.setSpan(W9.context.active(),Z),()=>{return K9.safeExecuteInTheMiddle(()=>{return J()},(X)=>{if(X)Z.recordException(X);Z.end()},!0)})}function lz(Z,J,X){let $=Z.startSpan(`${J} ${X.path}`,{kind:W9.SpanKind.CLIENT});return cd0($,X),$.setAttribute(s6.ATTR_DB_OPERATION_NAME,J),$}function ud0(Z){let J,X;if(typeof Z.host==="string")if(Z.host.startsWith("[")){if(Z.host.endsWith("]"))J=Z.host.replace(/^\[|\]$/g,"");else if(Z.host.includes("]:")){let $=Z.host.lastIndexOf(":");if($!==-1)J=Z.host.slice(1,$).replace(/^\[|\]$/g,""),X=Z.host.slice($+1)}}else if(Oe.isIPv6(Z.host))J=Z.host;else{let $=Z.host.lastIndexOf(":");if($!==-1)J=Z.host.slice(0,$),X=Z.host.slice($+1);else J=Z.host}return{address:J,port:X?parseInt(X,10):void 0}}function cd0(Z,J){let X=J.firestore.app,$=X.options,Q=(J.firestore.toJSON()||{}).settings||{},W={[s6.ATTR_DB_COLLECTION_NAME]:J.path,[s6.ATTR_DB_NAMESPACE]:X.name,[s6.ATTR_DB_SYSTEM_NAME]:"firebase.firestore","firebase.firestore.type":J.type,"firebase.firestore.options.projectId":$.projectId,"firebase.firestore.options.appId":$.appId,"firebase.firestore.options.messagingSenderId":$.messagingSenderId,"firebase.firestore.options.storageBucket":$.storageBucket},{address:K,port:z}=ud0(Q);if(K)W[s6.ATTR_SERVER_ADDRESS]=K;if(z)W[s6.ATTR_SERVER_PORT]=z;Z.setAttributes(W)}var G5=k(f(),1),z9=k(H0(),1);function Me(Z,J,X,$,Y){let Q=()=>{},W=()=>{},K=Y.functions?.errorHook,z=Y.functions?.requestHook,G=Y.functions?.responseHook;if(typeof G==="function")W=(F,B)=>{z9.safeExecuteInTheMiddle(()=>G(F,B),(U)=>{if(!U)return;G5.diag.error(U?.message)},!0)};if(typeof z==="function")Q=(F)=>{z9.safeExecuteInTheMiddle(()=>z(F),(B)=>{if(!B)return;G5.diag.error(B?.message)},!0)};let H=new z9.InstrumentationNodeModuleDefinition("firebase-functions",J);return[{name:"firebase-functions/lib/v2/providers/https.js",triggerType:"function"},{name:"firebase-functions/lib/v2/providers/firestore.js",triggerType:"firestore"},{name:"firebase-functions/lib/v2/providers/scheduler.js",triggerType:"scheduler"},{name:"firebase-functions/lib/v2/storage.js",triggerType:"storage"}].forEach(({name:F,triggerType:B})=>{H.files.push(new z9.InstrumentationNodeModuleFile(F,J,(U)=>ld0(U,X,$,Z,{requestHook:Q,responseHook:W,errorHook:K},B),(U)=>Ae(U,$)))}),H}function f4(Z,J,X){return function(Y){return function(...Q){let W=typeof Q[0]==="function"?Q[0]:Q[1],K=typeof Q[0]==="function"?void 0:Q[0];if(!W)return Y.call(this,...Q);let z=async function(...G){let H=process.env.FUNCTION_TARGET||process.env.K_SERVICE||"unknown",V=Z.startSpan(`firebase.function.${X}`,{kind:G5.SpanKind.SERVER}),F={"faas.name":H,"faas.trigger":X,"faas.provider":"firebase"};if(process.env.GCLOUD_PROJECT)F["cloud.project_id"]=process.env.GCLOUD_PROJECT;if(process.env.EVENTARC_CLOUD_EVENT_SOURCE)F["cloud.event_source"]=process.env.EVENTARC_CLOUD_EVENT_SOURCE;return V.setAttributes(F),J?.requestHook?.(V),G5.context.with(G5.trace.setSpan(G5.context.active(),V),async()=>{let B,U;try{U=await W.apply(this,G)}catch(D){B=D}if(J?.responseHook?.(V,B),B)V.recordException(B);if(V.end(),B)throw await J?.errorHook?.(V,B),B;return U})};if(K)return Y.call(this,K,z);else return Y.call(this,z)}}}function ld0(Z,J,X,$,Y,Q){switch(Ae(Z,X),Q){case"function":J(Z,"onRequest",f4($,Y,"http.request")),J(Z,"onCall",f4($,Y,"http.call"));break;case"firestore":J(Z,"onDocumentCreated",f4($,Y,"firestore.document.created")),J(Z,"onDocumentUpdated",f4($,Y,"firestore.document.updated")),J(Z,"onDocumentDeleted",f4($,Y,"firestore.document.deleted")),J(Z,"onDocumentWritten",f4($,Y,"firestore.document.written")),J(Z,"onDocumentCreatedWithAuthContext",f4($,Y,"firestore.document.created")),J(Z,"onDocumentUpdatedWithAuthContext",f4($,Y,"firestore.document.updated")),J(Z,"onDocumentDeletedWithAuthContext",f4($,Y,"firestore.document.deleted")),J(Z,"onDocumentWrittenWithAuthContext",f4($,Y,"firestore.document.written"));break;case"scheduler":J(Z,"onSchedule",f4($,Y,"scheduler.scheduled"));break;case"storage":J(Z,"onObjectFinalized",f4($,Y,"storage.object.finalized")),J(Z,"onObjectArchived",f4($,Y,"storage.object.archived")),J(Z,"onObjectDeleted",f4($,Y,"storage.object.deleted")),J(Z,"onObjectMetadataUpdated",f4($,Y,"storage.object.metadataUpdated"));break}return Z}function Ae(Z,J){let X=["onSchedule","onRequest","onCall","onObjectFinalized","onObjectArchived","onObjectDeleted","onObjectMetadataUpdated","onDocumentCreated","onDocumentUpdated","onDocumentDeleted","onDocumentWritten","onDocumentCreatedWithAuthContext","onDocumentUpdatedWithAuthContext","onDocumentDeletedWithAuthContext","onDocumentWrittenWithAuthContext"];for(let $ of X)if(z9.isWrapped(Z[$]))J(Z,$);return Z}var Te={},pd0=[">=3.0.0 <5"],id0=[">=6.0.0 <7"];class RD extends qe.InstrumentationBase{constructor(Z=Te){super("@sentry/instrumentation-firebase",N0,Z)}setConfig(Z={}){super.setConfig({...Te,...Z})}init(){let Z=[];return Z.push(we(this.tracer,pd0,this._wrap,this._unwrap,this.getConfig())),Z.push(Me(this.tracer,id0,this._wrap,this._unwrap,this.getConfig())),Z}}var Ce="Firebase",nd0={firestoreSpanCreationHook:(Z)=>{i0(Z,"auto.firebase.otel.firestore"),Z.setAttribute(K0,"db.query")},functions:{requestHook:(Z)=>{i0(Z,"auto.firebase.otel.functions"),Z.setAttribute(K0,"http.request")},errorHook:async(Z,J)=>{if(J)V0(J,{mechanism:{type:"auto.firebase.otel.functions",handled:!1}}),await iW(2000)}}},Ne=a(Ce,()=>new RD(nd0)),od0=()=>{return{name:Ce,setupOnce(){Ne()}}},Re=S(od0);function N3(){return[Pl(),Lp(),Yi(),sr(),Fn(),vn(),Xo(),qo(),Pa(),Kr(),Tr(),or(),qs(),os(),Lt(),Pt(),yi(),Je(),ii(),Be(),De(),Ye(),We(),ze(),Ve(),Fr(),Re()]}var dX=k(f(),1);var uX=k(p0(),1);var PD=1e6;function Pe(Z,J={}){if(Z.getOptions().debug)hL();let[X,$]=ad0(Z,J);Z.traceProvider=X,Z.asyncLocalStorageLookup=$}function ad0(Z,J={}){let X=new xK({sampler:new ML(Z),resource:SY().merge(PK({[uX.ATTR_SERVICE_NAME]:"node",[uX.SEMRESATTRS_SERVICE_NAMESPACE]:"sentry",[uX.ATTR_SERVICE_VERSION]:N0})),forceFlushTimeoutMillis:500,spanProcessors:[new jL({timeout:rd0(Z.getOptions().maxSpanWaitDuration)}),...J.spanProcessors||[]]});dX.trace.setGlobalTracerProvider(X),dX.propagation.setGlobalPropagator(new wL);let $=new dK;return dX.context.setGlobalContextManager($),[X,$.getAsyncLocalStorageLookup()]}function rd0(Z){if(Z==null)return;if(Z>PD)return N1&&A.warn(`\`maxSpanWaitDuration\` is too high, using the maximum value of ${PD}`),PD;else if(Z<=0||Number.isNaN(Z)){N1&&A.warn("`maxSpanWaitDuration` must be a positive number, using default value instead.");return}return Z}function Ee(){return iK().filter((J)=>J.name!=="Http"&&J.name!=="NodeFetch").concat(iY(),oY())}function Ie(Z){return[...Ee(),...L1(Z)?N3():[]]}function ED(Z={}){return sd0(Z,Ie)}function sd0(Z={},J){i5(Z,"node");let X=pL({...Z,defaultIntegrations:Z.defaultIntegrations??J(Z)});if(X&&!Z.skipOpenTelemetrySetup)Pe(X,{spanProcessors:Z.openTelemetrySpanProcessors}),nK();return X}import*as ve from"os";var td0="BunServer",ed0=()=>{return{name:td0,setupOnce(){Zu0()}}},ke=S(ed0),ye=!1;function Zu0(){if(ye)return;Bun.serve=new Proxy(Bun.serve,{apply(Z,J,X){Se(X[0]);let $=Z.apply(J,X),Y=$.reload.bind($);return $.reload=(Q)=>{return Se(Q),Y(Q)},$}}),ye=!0}function Se(Z){Ju0(Z),Xu0(Z)}function Ju0(Z){if(typeof Z.fetch!=="function")return;Z.fetch=new Proxy(Z.fetch,{apply(J,X,$){return ID(J,X,$)}})}function Xu0(Z){if(!Z.routes)return;if(typeof Z.routes!=="object")return;Object.keys(Z.routes).forEach((J)=>{let X=Z.routes[J];if(typeof X==="function")Z.routes[J]=new Proxy(X,{apply:($,Y,Q)=>{return ID($,Y,Q,J)}});if(X instanceof Response)return;if(typeof X==="object")Object.entries(X).forEach(([$,Y])=>{if(typeof Y==="function")Z.routes[J][$]=new Proxy(Y,{apply:(Q,W,K)=>{return ID(Q,W,K,J)}})})})}function ID(Z,J,X,$){return KZ((Y)=>{let Q=X[0],W=Q.method.toUpperCase();if(W==="OPTIONS"||W==="HEAD")return Z.apply(J,X);let K=BY(Q.url),z=$u0(K,Q),G=K?.pathname||"/";if(Q.params){if(Object.keys(Q.params).forEach((H)=>{z[`url.path.parameter.${H}`]=Q.params[H]}),$)z[U1]="route",z["url.template"]=$,G=$}if($?.endsWith("/*"))z[U1]="route",z["url.template"]=$,G=$;return Object.assign(z,iJ(Q.headers.toJSON(),u()?.getOptions().sendDefaultPii??!1)),Y.setSDKProcessingMetadata({normalizedRequest:{url:Q.url,method:Q.method,headers:Q.headers.toJSON(),query_string:K?.search}}),cW({sentryTrace:Q.headers.get("sentry-trace")??"",baggage:Q.headers.get("baggage")},()=>_6({attributes:z,op:"http.server",name:`${Q.method} ${G}`},async(H)=>{try{let V=await Z.apply(J,X);if(V?.status)SW(H,V.status),Y.setContext("response",{headers:V.headers.toJSON(),status_code:V.status});return V}catch(V){throw V0(V,{mechanism:{type:"auto.http.bun.serve",handled:!1}}),V}}))})}function $u0(Z,J){let X={[X0]:"auto.http.bun.serve",[vB]:J.method||"GET",[U1]:"url"};if(Z){if(Z.search)X["url.query"]=Z.search;if(Z.hash)X["url.fragment"]=Z.hash;if(Z.pathname)X["url.path"]=Z.pathname;if(!zU(Z)){if(X["url.full"]=Z.href,Z.port)X["url.port"]=Z.port;if(Z.protocol)X["url.scheme"]=Z.protocol;if(Z.hostname)X["url.domain"]=Z.hostname}}return X}function xe(Z){function J(X){let $={body:X.body,method:"POST",headers:Z.headers};try{return p9(()=>{return fetch(Z.url,$).then((Y)=>{return{statusCode:Y.status,headers:{"x-sentry-rate-limits":Y.headers.get("X-Sentry-Rate-Limits"),"retry-after":Y.headers.get("Retry-After")}}})})}catch(Y){return Promise.reject(Y)}}return _Z(Z,J)}function he(Z){return[oJ(),nJ(),aJ(),rJ(),sJ(),iY(),oY(),MX(),AX(),wX(),OX(),jX(),ke(),...L1(Z)?N3():[]]}function yD(Z={}){i5(Z,"bun");let J={...Z,platform:"javascript",runtime:{name:"bun",version:Bun.version},serverName:Z.serverName||global.process.env.SENTRY_NAME||ve.hostname()};if(J.transport=J.transport||xe,J.defaultIntegrations===void 0)J.defaultIntegrations=he(J);return ED(J)}yD({dsn:"https://f0ba950f2a01c32d24ccd8711de778be@o4510345514123264.ingest.us.sentry.io/4510346875043848",tracesSampleRate:1,sendDefaultPii:!1});import{readFileSync as fe}from"fs";import{join as be}from"path";function Q6(){return"2.1.0-beta.2"}function SD(Z){let[J,X]=Z.split("-"),$=(J||"0.0.0").split(".").map(Number),Y=null,Q=0;if(X){let W=X.match(/^([a-z]+)\.?(\d+)?$/i);if(W)Y=W[1]||null,Q=parseInt(W[2]||"0",10);else Y=X}return{major:$[0]||0,minor:$[1]||0,patch:$[2]||0,preRelease:Y,preReleaseNum:Q}}function G9(Z){let J=SD(Z);if(!J.preRelease)return"stable";if(J.preRelease.startsWith("alpha"))return"alpha";return"beta"}function R3(Z,J){try{let X=SD(Z),$=SD(J);if(X.major>$.major)return!1;if(X.major<$.major)return!1;if($.preRelease&&!X.preRelease)return!1;if(!$.preRelease&&X.preRelease)return!1;if($.preRelease&&X.preRelease){if(X.minor<$.minor)return!1;if(X.minor>$.minor)return!0;if(X.patch>$.patch)return!0;if(X.patch<$.patch)return!1;return X.preReleaseNum>$.preReleaseNum}if(X.minor>$.minor)return!0;if(X.minor<$.minor)return!1;if(X.patch>$.patch)return!0;return!1}catch(X){return!1}}import{parseArgs as Qu0}from"util";var Wu0={debug:{type:"boolean",short:"d",default:!1,description:"Enable debug logging"},"mqtt-port":{type:"string",default:"8884",description:"MQTT broker port"},"terminal-port":{type:"string",default:"3001",description:"Terminal server port"},"router-port":{type:"string",default:"8883",description:"Router port"},username:{type:"string",short:"u",description:"MQTT broker username (required)"},password:{type:"string",short:"p",description:"MQTT broker password (required)"},"ngrok-token":{type:"string",description:"ngrok authentication token (optional)"},"ngrok-domain":{type:"string",description:"ngrok static domain (optional, paid plan)"},"no-auto-update":{type:"boolean",default:!1,description:"Disable auto-update checking"},"terminal-audit":{type:"boolean",default:!1,description:"Enable terminal input audit logging (logs commands, not output)"},"auto-update-check-interval":{type:"string",default:"60",description:"Auto-update check interval in minutes (default: 60)"},help:{type:"boolean",short:"h",default:!1,description:"Show help message"},version:{type:"boolean",short:"v",default:!1,description:"Show version"}};function ge(){let Z=Qu0({options:Wu0,allowPositionals:!1,strict:!0});if(Z.values.version)console.log(`ccc v${Q6()}`),process.exit(0);if(Z.values.help)Ku0(),process.exit(0);let J=process.env.CCC_USERNAME||Z.values.username,X=process.env.CCC_PASSWORD||Z.values.password,$=process.env.CCC_NGROK_TOKEN||Z.values["ngrok-token"],Y=process.env.CCC_NGROK_DOMAIN||Z.values["ngrok-domain"];if(!J||!X)console.error("\x1B[31mError: Authentication credentials are required.\x1B[0m"),console.error(""),console.error("These credentials secure the MQTT communication between the app and backend."),console.error(""),console.error("You can provide them via:"),console.error(""),console.error(" Environment variables (recommended for security):"),console.error(" export CCC_USERNAME=myuser"),console.error(" export CCC_PASSWORD=mypassword"),console.error(" export CCC_NGROK_TOKEN=your_token # optional"),console.error(" export CCC_NGROK_DOMAIN=your_domain # optional"),console.error(" ccc"),console.error(""),console.error(" Or CLI arguments:"),console.error(" ccc --username myuser --password mypassword"),console.error(" ccc -u myuser -p mypassword"),console.error(""),process.exit(1);return{debug:Z.values.debug,mqttPort:parseInt(Z.values["mqtt-port"],10),terminalPort:parseInt(Z.values["terminal-port"],10),routerPort:parseInt(Z.values["router-port"],10),username:J,password:X,ngrokToken:$,ngrokDomain:Y,autoUpdate:!Z.values["no-auto-update"],autoUpdateCheckInterval:parseInt(Z.values["auto-update-check-interval"],10),terminalAudit:Z.values["terminal-audit"]}}function Ku0(){console.log(`
54
54
  Backend v2 - Clean modular architecture
55
55
 
56
56
  Usage:
@@ -87,7 +87,7 @@ Environment Variables:
87
87
  `).replace(/\r/g,`
88
88
  `);let C=new ue,h=E.split(`
89
89
  `),d=h.shift();if(!d)throw Error("Invalid font file: missing header");let p=d.split(" "),c={hardBlank:p[0].substring(5,6),height:parseInt(p[1],10),baseline:parseInt(p[2],10),maxLength:parseInt(p[3],10),oldLayout:parseInt(p[4],10),numCommentLines:parseInt(p[5],10),printDirection:p[6]?parseInt(p[6],10):0,fullLayout:p[7]?parseInt(p[7],10):null,codeTagCount:p[8]?parseInt(p[8],10):null};if((c.hardBlank||"").length!==1||[c.height,c.baseline,c.maxLength,c.oldLayout,c.numCommentLines].some((w0)=>w0===null||w0===void 0||isNaN(w0)))throw Error("FIGlet header contains invalid values.");if(c.height==null||c.numCommentLines==null)throw Error("FIGlet header contains invalid values.");c.fittingRules=K(c.oldLayout,c.fullLayout),C.options=c;let $0=[];for(let w0=32;w0<=126;w0++)$0.push(w0);if($0.push(196,214,220,228,246,252,223),h.length<c.numCommentLines+c.height*$0.length)throw Error(`FIGlet file is missing data. Line length: ${h.length}. Comment lines: ${c.numCommentLines}. Height: ${c.height}. Num chars: ${$0.length}.`);C.comment=h.splice(0,c.numCommentLines).join(`
90
- `),C.numChars=0;while(h.length>0&&C.numChars<$0.length){let w0=$0[C.numChars];C[w0]=h.splice(0,c.height);for(let D0=0;D0<c.height;D0++)if(typeof C[w0][D0]>"u")C[w0][D0]="";else C[w0][D0]=W(C[w0][D0],D0,c.height);C.numChars++}while(h.length>0){let w0=h.shift();if(!w0||w0.trim()==="")break;let D0=w0.split(" ")[0],j0;if(/^-?0[xX][0-9a-fA-F]+$/.test(D0))j0=parseInt(D0,16);else if(/^-?0[0-7]+$/.test(D0))j0=parseInt(D0,8);else if(/^-?[0-9]+$/.test(D0))j0=parseInt(D0,10);else throw Error(`Error parsing data. Invalid data: ${D0}`);if(j0===-1||j0<-2147483648||j0>2147483647){let I0=j0===-1?"The char code -1 is not permitted.":`The char code cannot be ${j0<-2147483648?"less than -2147483648":"greater than 2147483647"}.`;throw Error(`Error parsing data. ${I0}`)}C[j0]=h.splice(0,c.height);for(let I0=0;I0<c.height;I0++)if(typeof C[j0][I0]>"u")C[j0][I0]="";else C[j0][I0]=W(C[j0][I0],I0,c.height);C.numChars++}return Y[P]=C,c},h1.loadedFonts=()=>{return Object.keys(Y)},h1.clearLoadedFonts=()=>{Object.keys(Y).forEach((P)=>{delete Y[P]})},h1.loadFont=async function(P,E){if(Y[P]){let M=Y[P].options;if(E)E(null,M);return Promise.resolve(M)}try{if(!Q.fetchFontIfMissing)throw Error(`Font is not loaded: ${P}`);let M=await fetch(`${Q.fontPath}/${P}.flf`);if(!M.ok)throw Error(`Network response was not ok: ${M.status}`);let C=await M.text(),h=h1.parseFont(P,C);if(E)E(null,h);return h}catch(M){let C=M instanceof Error?M:Error(String(M));if(E)return E(C),null;throw C}},h1.loadFontSync=function(P){if(Y[P])return Y[P].options;throw Error("Synchronous font loading is not implemented for the browser, it will only work for fonts already loaded.")},h1.preloadFonts=async function(P,E){try{for(let M of P){let C=await fetch(`${Q.fontPath}/${M}.flf`);if(!C.ok)throw Error(`Failed to preload fonts. Error fetching font: ${M}, status code: ${C.statusText}`);let h=await C.text();h1.parseFont(M,h)}if(E)E()}catch(M){let C=M instanceof Error?M:Error(String(M));if(E){E(C);return}throw M}},h1.fonts=function(P){return new Promise(function(E,M){if(E(vD),P)P(null,vD)})},h1.fontsSync=function(){return vD},h1.figFonts=Y,h1})();import{fileURLToPath as Bu0}from"url";var Uu0=Bu0(import.meta.url),Lu0=cX.dirname(Uu0),Du0=cX.join(Lu0,"/../fonts/"),p1=ce;p1.defaults({fontPath:Du0});p1.loadFont=function(Z,J){return new Promise((X,$)=>{if(p1.figFonts[Z]){if(J)J(null,p1.figFonts[Z].options);X(p1.figFonts[Z].options);return}T7.readFile(cX.join(p1.defaults().fontPath,Z+".flf"),{encoding:"utf-8"},(Y,Q)=>{if(Y){if(J)J(Y);$(Y);return}Q=Q+"";try{let W=p1.parseFont(Z,Q);if(J)J(null,W);X(W)}catch(W){let K=W instanceof Error?W:Error(String(W));if(J)J(K);$(K)}})})};p1.loadFontSync=function(Z){if(p1.figFonts[Z])return p1.figFonts[Z].options;let J=T7.readFileSync(cX.join(p1.defaults().fontPath,Z+".flf"),{encoding:"utf-8"})+"";return p1.parseFont(Z,J)};p1.fonts=function(Z){return new Promise((J,X)=>{let $=[];T7.readdir(p1.defaults().fontPath,(Y,Q)=>{if(Y){Z&&Z(Y),X(Y);return}Q.forEach((W)=>{if(/\.flf$/.test(W))$.push(W.replace(/\.flf$/,""))}),Z&&Z(null,$),J($)})})};p1.fontsSync=function(){let Z=[];return T7.readdirSync(p1.defaults().fontPath).forEach((J)=>{if(/\.flf$/.test(J))Z.push(J.replace(/\.flf$/,""))}),Z};var le=`flf2a$ 6 5 16 15 13 0 24463 229
90
+ `),C.numChars=0;while(h.length>0&&C.numChars<$0.length){let w0=$0[C.numChars];C[w0]=h.splice(0,c.height);for(let D0=0;D0<c.height;D0++)if(typeof C[w0][D0]>"u")C[w0][D0]="";else C[w0][D0]=W(C[w0][D0],D0,c.height);C.numChars++}while(h.length>0){let w0=h.shift();if(!w0||w0.trim()==="")break;let D0=w0.split(" ")[0],j0;if(/^-?0[xX][0-9a-fA-F]+$/.test(D0))j0=parseInt(D0,16);else if(/^-?0[0-7]+$/.test(D0))j0=parseInt(D0,8);else if(/^-?[0-9]+$/.test(D0))j0=parseInt(D0,10);else throw Error(`Error parsing data. Invalid data: ${D0}`);if(j0===-1||j0<-2147483648||j0>2147483647){let I0=j0===-1?"The char code -1 is not permitted.":`The char code cannot be ${j0<-2147483648?"less than -2147483648":"greater than 2147483647"}.`;throw Error(`Error parsing data. ${I0}`)}C[j0]=h.splice(0,c.height);for(let I0=0;I0<c.height;I0++)if(typeof C[j0][I0]>"u")C[j0][I0]="";else C[j0][I0]=W(C[j0][I0],I0,c.height);C.numChars++}return Y[P]=C,c},h1.loadedFonts=()=>{return Object.keys(Y)},h1.clearLoadedFonts=()=>{Object.keys(Y).forEach((P)=>{delete Y[P]})},h1.loadFont=async function(P,E){if(Y[P]){let M=Y[P].options;if(E)E(null,M);return Promise.resolve(M)}try{if(!Q.fetchFontIfMissing)throw Error(`Font is not loaded: ${P}`);let M=await fetch(`${Q.fontPath}/${P}.flf`);if(!M.ok)throw Error(`Network response was not ok: ${M.status}`);let C=await M.text(),h=h1.parseFont(P,C);if(E)E(null,h);return h}catch(M){let C=M instanceof Error?M:Error(String(M));if(E)return E(C),null;throw C}},h1.loadFontSync=function(P){if(Y[P])return Y[P].options;throw Error("Synchronous font loading is not implemented for the browser, it will only work for fonts already loaded.")},h1.preloadFonts=async function(P,E){try{for(let M of P){let C=await fetch(`${Q.fontPath}/${M}.flf`);if(!C.ok)throw Error(`Failed to preload fonts. Error fetching font: ${M}, status code: ${C.statusText}`);let h=await C.text();h1.parseFont(M,h)}if(E)E()}catch(M){let C=M instanceof Error?M:Error(String(M));if(E){E(C);return}throw M}},h1.fonts=function(P){return new Promise(function(E,M){if(E(vD),P)P(null,vD)})},h1.fontsSync=function(){return vD},h1.figFonts=Y,h1})();import{fileURLToPath as Bu0}from"url";var Uu0=Bu0(import.meta.url),Lu0=cX.dirname(Uu0),Du0=cX.join(Lu0,"/../fonts/"),i1=ce;i1.defaults({fontPath:Du0});i1.loadFont=function(Z,J){return new Promise((X,$)=>{if(i1.figFonts[Z]){if(J)J(null,i1.figFonts[Z].options);X(i1.figFonts[Z].options);return}T7.readFile(cX.join(i1.defaults().fontPath,Z+".flf"),{encoding:"utf-8"},(Y,Q)=>{if(Y){if(J)J(Y);$(Y);return}Q=Q+"";try{let W=i1.parseFont(Z,Q);if(J)J(null,W);X(W)}catch(W){let K=W instanceof Error?W:Error(String(W));if(J)J(K);$(K)}})})};i1.loadFontSync=function(Z){if(i1.figFonts[Z])return i1.figFonts[Z].options;let J=T7.readFileSync(cX.join(i1.defaults().fontPath,Z+".flf"),{encoding:"utf-8"})+"";return i1.parseFont(Z,J)};i1.fonts=function(Z){return new Promise((J,X)=>{let $=[];T7.readdir(i1.defaults().fontPath,(Y,Q)=>{if(Y){Z&&Z(Y),X(Y);return}Q.forEach((W)=>{if(/\.flf$/.test(W))$.push(W.replace(/\.flf$/,""))}),Z&&Z(null,$),J($)})})};i1.fontsSync=function(){let Z=[];return T7.readdirSync(i1.defaults().fontPath).forEach((J)=>{if(/\.flf$/.test(J))Z.push(J.replace(/\.flf$/,""))}),Z};var le=`flf2a$ 6 5 16 15 13 0 24463 229
91
91
  Standard by Glenn Chappell & Ian Chai 3/93 -- based on Frank's .sig
92
92
  Includes ISO Latin-1
93
93
  figlet release 2.1 -- 12 Aug 1994
@@ -2323,7 +2323,7 @@ Font modified May 20, 2012 by patorjk to add the 0xCA0 character
2323
2323
  | (_) | @
2324
2324
  $\\___/$ @
2325
2325
  @@
2326
- `;p1.parseFont("Standard",le);function pe(){let Z=p1.textSync("ccc",{font:"Standard",horizontalLayout:"default",verticalLayout:"default"});console.log(`
2326
+ `;i1.parseFont("Standard",le);function pe(){let Z=i1.textSync("ccc",{font:"Standard",horizontalLayout:"default",verticalLayout:"default"});console.log(`
2327
2327
  `),console.log(Z),console.log("Code Chat Connect - v2.0.0"),console.log("Mobile IDE to code on the go!"),console.log(`
2328
2328
  `)}var A70=k(j70(),1);import{Duplex as W11}from"stream";async function M70(Z,J,X){let $=null,Y=await import("net"),Q=new Set;return $=Y.createServer((W)=>{X.debug("[MQTT TCP] Client socket connected"),Q.add(W);let K=new W11({read(){},write(z,G,H){W.write(z,G,H)}});W.on("data",(z)=>{K.push(z)}),W.on("end",()=>{K.push(null),Q.delete(W)}),W.on("error",(z)=>{X.debug("[MQTT TCP] Socket error",{error:z.message}),K.destroy(z),Q.delete(W)}),W.on("close",()=>{Q.delete(W)}),K.on("error",(z)=>{X.debug("[MQTT TCP] Stream error",{error:z.message}),W.destroy()});try{Z.handle(K)}catch(z){X.error("[MQTT TCP] Error handling connection",{error:z}),W.destroy()}}),{server:null,tcpServer:$,listen:async(W,K)=>{return new Promise((z,G)=>{let H=(F)=>{X.error("[MQTT TCP] Server error",{error:F.message,code:F.code,port:W,hostname:K}),G(F)},V=()=>{X.debug("[MQTT TCP] Server listening",{port:W,hostname:K}),$.removeListener("error",H),z()};$.once("error",H),$.once("listening",V),$.listen(W,K)})},close:async()=>{return new Promise((W)=>{if($){for(let z of Q)try{z.destroy()}catch(G){X.debug("[MQTT TCP] Error destroying socket",{error:G})}Q.clear();let K=setTimeout(()=>{X.warn("[MQTT TCP] Server close timeout, forcing shutdown"),W()},500);$.close(()=>{clearTimeout(K),X.debug("[MQTT] TCP server closed"),W()})}else W()})}}}class nG{servers=null;broker=null;running=!1;startedAt;config;name="CCC MQTT Broker";constructor(Z){this.config=Z,this.createBrokerInstance()}createBrokerInstance(){this.broker=A70.default({id:"ccc-mqtt-broker",heartbeatInterval:this.config.heartbeatInterval||30000,connectTimeout:this.config.connectTimeout||30000,authenticate:this.authenticate.bind(this)}),this.setupBrokerEvents()}setupBrokerEvents(){let Z=x();this.broker.on("client",(J)=>{Z.debug("MQTT client connected",{clientId:J.id,clean:J.clean})}),this.broker.on("clientDisconnect",(J)=>{Z.debug("MQTT client disconnected",{clientId:J.id})}),this.broker.on("subscribe",(J,X)=>{Z.debug("MQTT client subscribed",{clientId:X?.id,topics:J.map(($)=>$.topic)})}),this.broker.on("unsubscribe",(J,X)=>{Z.debug("MQTT client unsubscribed",{clientId:X?.id,topics:J})}),this.broker.on("publish",(J,X)=>{if(X)Z.debug("MQTT message published",{clientId:X.id,topic:J.topic,qos:J.qos,size:J.payload?.length||0})}),this.broker.on("clientError",(J,X)=>{Z.error("MQTT client error",{clientId:J?.id,error:X.message})}),this.broker.on("connectionError",(J,X)=>{Z.error("MQTT connection error",{clientId:J?.id,error:X.message})})}async start(){try{let Z=x();this.servers=await M70(this.broker,{port:this.config.port,hostname:"localhost"},Z),await this.servers.listen(this.config.port,"localhost"),this.running=!0,this.startedAt=new Date,Z.debug("MQTT Broker started (TCP only)",{tcpPort:this.config.port,protocols:["mqtt/tcp"]})}catch(Z){throw new pz(`Failed to start MQTT broker: ${Z instanceof Error?Z.message:String(Z)}`)}}async stop(){try{let Z=x();if(!this.running)return;if(Z.debug("Stopping MQTT Broker"),this.broker?.clients)for(let J of Object.keys(this.broker.clients)){let X=this.broker.clients[J];try{X.close()}catch($){Z.debug("Error closing MQTT client",{clientId:J,error:$})}}if(this.servers)try{await this.servers.close()}catch(J){Z.error("Error closing servers",{error:J})}try{await new Promise((J)=>{let X=setTimeout(()=>{Z.debug("MQTT broker close timeout, forcing shutdown"),J()},1000);if(this.broker)this.broker.close(()=>{clearTimeout(X),Z.debug("MQTT broker closed"),J()});else clearTimeout(X),J()})}catch(J){Z.error("Error closing MQTT broker",{error:J})}this.running=!1,Z.info("\u2713 MQTT Broker stopped")}catch(Z){throw this.running=!1,new pz(`Failed to stop MQTT broker: ${Z instanceof Error?Z.message:String(Z)}`)}}getStatus(){return{name:"MQTT Broker",running:this.running,port:this.config.port,startedAt:this.startedAt,clientCount:this.broker?.clients?Object.keys(this.broker.clients).length:0}}authenticate(Z,J,X,$){let Y=x();if(!this.config.auth){Y.error("MQTT authentication not configured - rejecting connection",{clientId:Z.id}),$(Error("Server misconfiguration: authentication required"),!1);return}let Q=X?.toString();if(J===this.config.auth.username&&Q===this.config.auth.password)Y.debug("MQTT client authenticated successfully",{clientId:Z.id,username:J}),$(null,!0);else Y.warn("MQTT client authentication failed",{clientId:Z.id,username:J}),$(Error("Invalid credentials"),!1)}}var QY0=k(YY0(),1),I6=x();class _H{name="Backend MQTT Client";client=null;running=!1;connected=!1;shuttingDown=!1;startedAt;config;subscriptions=new Map;constructor(Z){this.config=Z}async start(){return new Promise((Z,J)=>{try{let X=`mqtt://${this.config.host}:${this.config.port}`;this.client=QY0.default.connect(X,{clientId:"backend-client",clean:!0,connectTimeout:5000,username:this.config.username,password:this.config.password}),this.client.on("connect",()=>{this.connected=!0,this.running=!0,this.startedAt=new Date,I6.info("[BackendClient] Connected to MQTT broker"),Z()}),this.client.on("error",($)=>{if(!this.shuttingDown)I6.error("[BackendClient] MQTT error",{error:$.message});if(!this.connected)J($)}),this.client.on("close",()=>{this.connected=!1,I6.debug("[BackendClient] Disconnected from MQTT broker")}),this.client.on("message",($,Y)=>{this.handleMessage($,Y)})}catch(X){I6.error("[BackendClient] Failed to start",X),J(X)}})}async stop(){return new Promise((Z)=>{if(!this.client){this.running=!1,Z();return}this.shuttingDown=!0,this.connected=!1,this.running=!1,this.subscriptions.clear();let J=setTimeout(()=>{I6.debug("[BackendClient] Stop timeout, forcing close"),Z()},2000);this.client.end(!0,{},()=>{clearTimeout(J),I6.info("[BackendClient] Stopped"),Z()})})}subscribe(Z,J){if(!this.client)throw Error("MQTT client not initialized");if(!this.subscriptions.has(Z))this.subscriptions.set(Z,new Set),this.client.subscribe(Z,{qos:1},(X)=>{if(X)I6.error(`[BackendClient] Failed to subscribe to ${Z}`,{error:X.message});else I6.debug(`[BackendClient] Subscribed to ${Z}`)});this.subscriptions.get(Z).add(J)}unsubscribe(Z,J){if(!this.client)return;let X=this.subscriptions.get(Z);if(!X)return;if(X.delete(J),X.size===0){if(this.subscriptions.delete(Z),this.connected)this.client.unsubscribe(Z,($)=>{if($)I6.debug(`[BackendClient] Failed to unsubscribe from ${Z}`,{error:$.message});else I6.debug(`[BackendClient] Unsubscribed from ${Z}`)})}}publish(Z,J,X){return new Promise(($,Y)=>{if(!this.client){Y(Error("MQTT client not initialized"));return}this.client.publish(Z,J,{qos:X?.qos||1},(Q)=>{if(Q)I6.error(`[BackendClient] Failed to publish to ${Z}`,{error:Q.message}),Y(Q);else I6.debug(`[BackendClient] Published to ${Z}`),$()})})}topicToRegex(Z){let J=Z.replace(/[.\\^${}|[\]()]/g,"\\$&").replace(/\+/g,"[^/]+").replace(/#/g,".*");return new RegExp(`^${J}$`)}handleMessage(Z,J){this.subscriptions.forEach((X,$)=>{if(this.topicToRegex($).test(Z))X.forEach((Q)=>{try{Q(Z,J)}catch(W){I6.error(`[BackendClient] Error in message handler for ${Z}`,{error:W instanceof Error?W.message:"Unknown error"})}})})}markShuttingDown(){this.shuttingDown=!0}isShuttingDown(){return this.shuttingDown}getStatus(){return{name:this.name,running:this.running,connected:this.connected,startedAt:this.startedAt}}}var WY0=5,L71=900000;class cw{credentials;failedAttempts=new Map;blockedIPs=new Map;logger=x();constructor(){this.credentials=this.generateCredentials(),this.logger.debug("Terminal credentials generated")}getCredentials(){return this.credentials}authenticate(Z,J,X){let $=this.blockedIPs.get(X);if($&&$>Date.now())throw new iz("IP temporarily blocked due to too many failed attempts");if(Z===this.credentials.username&&J===this.credentials.password)return this.failedAttempts.delete(X),this.blockedIPs.delete(X),!0;let Y=(this.failedAttempts.get(X)||0)+1;if(this.failedAttempts.set(X,Y),Y>=WY0)this.blockedIPs.set(X,Date.now()+L71),this.failedAttempts.delete(X),this.logger.warn(`IP blocked after ${WY0} failed attempts`,{ip:X});throw new iz("Invalid credentials")}generateCredentials(){let Z=this.generateRandomString(32),J=this.generateRandomString(480);return{username:Z,password:J}}generateRandomString(Z){let X="",$=new Uint8Array(Z);crypto.getRandomValues($);for(let Y=0;Y<Z;Y++){let Q=$[Y]??0;X+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+-=[]{}|;,.<>?"[Q%87]}return X}}var OH=null;async function D71(){if(!OH)try{OH=await import("../../lib/bun-pty-loader.generated")}catch{try{OH=await import("bun-pty")}catch{throw Error(`PTY support unavailable. Native library not found.
2329
2329
  This may happen if running a compiled binary without the native library.
@@ -2375,14 +2375,14 @@ Please ensure librust_pty.so is available or use the install script.`)}}return O
2375
2375
  `)[0]?.slice(0,100),V=B?.["argument-hint"]}$.push({name:G,filename:W.name,description:H,argumentHint:V,scope:J,subdirectory:X||void 0,modified:z.mtime.toISOString()})}}catch(Q){if(Q.code!=="ENOENT")d7.warn("[SlashCommands] Error scanning directory",{dir:Y,error:Q})}return $}async handleListCommandsRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("commands/list",J.clientId,J.requestId);try{let $=this.getCommandsDir(J.scope,J.projectPath),Y=await this.scanCommandsDir($,J.scope),Q={scope:J.scope,commands:Y,timestamp:Date.now()};await this.publishResponse(X,Q)}catch($){let Y={scope:J.scope,commands:[],timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){d7.error("[SlashCommands] Error handling list commands request",{error:this.formatError(J)})}}async handleReadCommandRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("commands/read",J.clientId);try{let $=this.getCommandsDir(J.scope,J.projectPath),Y=Y4.join($,`${J.commandName}.md`),Q=Y4.resolve(Y).toLowerCase().replace(/\\/g,"/"),W=Y4.resolve($).toLowerCase().replace(/\\/g,"/");if(!Q.startsWith(W))throw Error("Invalid command path");let K=await W1(Y);if(K===null)throw Error("Command file not found or unreadable");let z=await R9(Y);if(!z)throw Error("Could not get file stats");let{frontmatter:G,body:H}=this.parseFrontmatter(K),V=J.commandName.split("/"),F=V[V.length-1]||J.commandName,B=V.length>1?V.slice(0,-1).join("/"):void 0,D={command:{name:F,filename:`${F}.md`,description:G?.description||H.split(`
2376
2376
  `)[0]?.slice(0,100),scope:J.scope,subdirectory:B,modified:z.mtime.toISOString(),content:H,frontmatter:G,rawContent:K},timestamp:Date.now()};await this.publishResponse(X,D)}catch($){let Y={timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){d7.error("[SlashCommands] Error handling read command request",{error:this.formatError(J)})}}async handleWriteCommandRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("commands/write",J.clientId);try{let $=this.getCommandsDir(J.scope,J.projectPath);if(!/^[a-z][a-z0-9-]*$/i.test(J.commandName.split("/").pop()||""))throw Error("Invalid command name");let Y=Y4.join($,`${J.commandName}.md`),Q=Y4.resolve(Y),W=Y4.resolve($);if(!Q.startsWith(W))throw Error("Invalid command path");await u7.mkdir(Y4.dirname(Y),{recursive:!0});let K="";if(J.frontmatter&&Object.keys(J.frontmatter).length>0)K=this.generateFrontmatter(J.frontmatter)+`
2377
2377
 
2378
- `;K+=J.content,await u7.writeFile(Y,K,"utf-8");let z={success:!0,commandName:J.commandName,scope:J.scope,timestamp:Date.now()};await this.publishResponse(X,z)}catch($){let Y={success:!1,commandName:J.commandName,scope:J.scope,timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){d7.error("[SlashCommands] Error handling write command request",{error:this.formatError(J)})}}async handleDeleteCommandRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("commands/delete",J.clientId);try{let $=this.getCommandsDir(J.scope,J.projectPath),Y=Y4.join($,`${J.commandName}.md`),Q=Y4.resolve(Y),W=Y4.resolve($);if(!Q.startsWith(W))throw Error("Invalid command path");await u7.unlink(Y);let K={success:!0,commandName:J.commandName,scope:J.scope,timestamp:Date.now()};await this.publishResponse(X,K)}catch($){let Y={success:!1,commandName:J.commandName,scope:J.scope,timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){d7.error("[SlashCommands] Error handling delete command request",{error:this.formatError(J)})}}}import*as Bj from"path";import*as XQ0 from"os";import*as c7 from"fs/promises";import*as aH from"path";var s30=x(),jZ1={logWarnings:!0,ensureDirectory:!0,prettyFormat:!0};class Vj{options;constructor(Z={}){this.options={...jZ1,...Z}}async readConfig(Z){try{let J=await W1(Z,{logWarnings:this.options.logWarnings});if(J===null)return null;return JSON.parse(J)}catch(J){return s30.debug("[ConfigManager] Error parsing config file",{filePath:Z,error:J}),null}}async readConfigOrEmpty(Z){return await this.readConfig(Z)??{}}async writeConfig(Z,J){if(this.options.ensureDirectory){let $=aH.dirname(Z);await c7.mkdir($,{recursive:!0})}let X=this.options.prettyFormat?JSON.stringify(J,null,2):JSON.stringify(J);await c7.writeFile(Z,X,"utf-8"),s30.debug("[ConfigManager] Config file written",{filePath:Z})}async updateConfig(Z,J){let $={...await this.readConfigOrEmpty(Z),...J};await this.writeConfig(Z,$)}async deleteConfigKeys(Z,J){let X=await this.readConfigOrEmpty(Z);for(let $ of J)delete X[$];await this.writeConfig(Z,X)}async configExists(Z){try{return await c7.access(Z,c7.constants.R_OK),!0}catch{return!1}}async getConfigValue(Z,J,X){return(await this.readConfigOrEmpty(Z))[J]??X}async setConfigValue(Z,J,X){await this.updateConfig(Z,{[J]:X})}forDirectory(Z){return new t30(Z,this.options)}}class t30 extends Vj{baseDir;constructor(Z,J={}){super(J);this.baseDir=Z}resolvePath(Z){return aH.resolve(this.baseDir,Z)}async readConfig(Z){return super.readConfig(this.resolvePath(Z))}async readConfigOrEmpty(Z){return super.readConfigOrEmpty(this.resolvePath(Z))}async writeConfig(Z,J){return super.writeConfig(this.resolvePath(Z),J)}async updateConfig(Z,J){return super.updateConfig(this.resolvePath(Z),J)}async deleteConfigKeys(Z,J){return super.deleteConfigKeys(this.resolvePath(Z),J)}async configExists(Z){return super.configExists(this.resolvePath(Z))}async getConfigValue(Z,J,X){return super.getConfigValue(this.resolvePath(Z),J,X)}async setConfigValue(Z,J,X){return super.setConfigValue(this.resolvePath(Z),J,X)}}var E9=new Vj;import*as F8 from"path";import*as e30 from"os";class Fj{getBaseDir(Z,J){switch(Z){case"user":return F8.join(e30.homedir(),".claude");case"local":return F8.join(process.cwd(),".claude");case"project":if(!J)throw Error("Project path is required for project scope");return F8.join(J,".claude");default:throw Error(`Unknown scope: ${Z}`)}}getConfigDir(Z,J,X){let $=this.getBaseDir(J,X);switch(Z){case"plugins":return F8.join($,"plugins");case"hooks":return $;case"skills":return F8.join($,"skills");case"mcp":return $;case"claude":return $;case"settings":return $;default:throw Error(`Unknown config type: ${Z}`)}}getConfigPath(Z,J,X,$){let Y=this.getConfigDir(Z,J,X),Q=$??this.getDefaultFileName(Z);return F8.join(Y,Q)}getDefaultFileName(Z){switch(Z){case"plugins":return"settings.json";case"hooks":return"hooks.json";case"skills":return"skills.json";case"mcp":return"mcp.json";case"claude":return"claude_desktop_config.json";case"settings":return"settings.json";default:throw Error(`Unknown config type: ${Z}`)}}getUserConfigPath(Z,J){return this.getConfigPath(Z,"user",void 0,J)}getProjectConfigPath(Z,J,X){return this.getConfigPath(Z,"project",J,X)}getLocalConfigPath(Z,J){return this.getConfigPath(Z,"local",void 0,J)}validateProjectPath(Z){if(!Z||typeof Z!=="string")return!1;if(!F8.isAbsolute(Z))return!1;if(F8.normalize(Z).includes(".."))return!1;return!0}getAllConfigPaths(Z,J,X){let $={user:this.getUserConfigPath(Z,X),local:this.getLocalConfigPath(Z,X)};if(J&&this.validateProjectPath(J))$.project=this.getProjectConfigPath(Z,J,X);return $}resolveConfigPaths(Z,J,X){let $=this.getAllConfigPaths(Z,J,X),Y=[];if($.project)Y.push($.project);return Y.push($.local),Y.push($.user),Y}getPluginsDir(Z,J){return this.getConfigDir("plugins",Z,J)}getSkillsDir(Z,J){return this.getConfigDir("skills",Z,J)}getMarketplaceCacheDir(){return F8.join(this.getBaseDir("user"),"plugins","marketplace-cache")}forProject(Z){if(!this.validateProjectPath(Z))throw Error(`Invalid project path: ${Z}`);return new ZQ0(Z)}}class ZQ0{projectPath;pathResolver=new Fj;constructor(Z){this.projectPath=Z}getUserConfigPath(Z,J){return this.pathResolver.getUserConfigPath(Z,J)}getProjectConfigPath(Z,J){return this.pathResolver.getProjectConfigPath(Z,this.projectPath,J)}getLocalConfigPath(Z,J){return this.pathResolver.getLocalConfigPath(Z,J)}getAllConfigPaths(Z,J){return this.pathResolver.getAllConfigPaths(Z,this.projectPath,J)}resolveConfigPaths(Z,J){return this.pathResolver.resolveConfigPaths(Z,this.projectPath,J)}getPluginsDir(Z){return this.pathResolver.getPluginsDir(Z,this.projectPath)}getSkillsDir(Z){return this.pathResolver.getSkillsDir(Z,this.projectPath)}}var I9=new Fj;function JQ0(Z){if(!Z||typeof Z!=="string")return!1;return/^[a-zA-Z][a-zA-Z0-9-]*$/.test(Z)}var dQ=x();class rH extends p4{name="MCP Servers Service";get logPrefix(){return"[MCPServers]"}getStatus(){return{...super.getStatus()}}registerMQTTHandlers(){this.registerHandler("mcp/list/request",(Z,J)=>{this.handleListServersRequest(J)}),this.registerHandler("mcp/read/request",(Z,J)=>{this.handleReadServerRequest(J)}),this.registerHandler("mcp/write/request",(Z,J)=>{this.handleWriteServerRequest(J)}),this.registerHandler("mcp/delete/request",(Z,J)=>{this.handleDeleteServerRequest(J)}),dQ.info("[MCPServers] MQTT handlers registered")}getUserConfigPath(){return Bj.join(XQ0.homedir(),".claude.json")}getProjectConfigPath(Z){return Bj.join(Z,".mcp.json")}isValidServerName(Z){return JQ0(Z)}isValidProjectPath(Z){return I9.validateProjectPath(Z)}async readConfigFile(Z){return await E9.readConfig(Z)}async writeConfigFile(Z,J){await E9.writeConfig(Z,J)}async getServersFromUserConfig(Z,J){let X=this.getUserConfigPath(),$=await this.readConfigFile(X);if(!$?.mcpServers)return[];let Y=[];for(let[Q,W]of Object.entries($.mcpServers)){let K=W._projectPath;if(Z==="user"){if(!K)Y.push({name:Q,type:W.type,url:W.url,command:W.command,scope:"user"})}else if(Z==="local"&&J){if(K===J)Y.push({name:Q,type:W.type,url:W.url,command:W.command,scope:"local",projectPath:K})}}return Y}async getServersFromProjectConfig(Z){let J=this.getProjectConfigPath(Z),X=await this.readConfigFile(J);if(!X?.mcpServers)return[];let $=[];for(let[Y,Q]of Object.entries(X.mcpServers))$.push({name:Y,type:Q.type,url:Q.url,command:Q.command,scope:"project",projectPath:Z});return $}async getServerDetailFromUserConfig(Z,J,X){let $=this.getUserConfigPath(),Y=await this.readConfigFile($);if(!Y?.mcpServers?.[Z])return null;let Q=Y.mcpServers[Z],W=Q._projectPath;if(J==="user"&&W)return null;if(J==="local"&&W!==X)return null;let{_projectPath:K,...z}=Q;return{name:Z,type:z.type,url:z.url,command:z.command,args:z.args,env:z.env,headers:z.headers,scope:J,projectPath:K}}async getServerDetailFromProjectConfig(Z,J){let X=this.getProjectConfigPath(J),$=await this.readConfigFile(X);if(!$?.mcpServers?.[Z])return null;let Y=$.mcpServers[Z];return{name:Z,type:Y.type,url:Y.url,command:Y.command,args:Y.args,env:Y.env,headers:Y.headers,scope:"project",projectPath:J}}async writeServerToUserConfig(Z,J,X,$){let Y=this.getUserConfigPath(),Q=await this.readConfigFile(Y);if(!Q)Q={};if(!Q.mcpServers)Q.mcpServers={};let W={...J};if(X==="local"&&$)W._projectPath=$;Q.mcpServers[Z]=W,await this.writeConfigFile(Y,Q)}async writeServerToProjectConfig(Z,J,X){let $=this.getProjectConfigPath(X),Y=await this.readConfigFile($);if(!Y)Y={};if(!Y.mcpServers)Y.mcpServers={};Y.mcpServers[Z]=J,await this.writeConfigFile($,Y)}async deleteServerFromUserConfig(Z,J,X){let $=this.getUserConfigPath(),Y=await this.readConfigFile($);if(!Y?.mcpServers?.[Z])return!1;let W=Y.mcpServers[Z]._projectPath;if(J==="user"&&W)return!1;if(J==="local"&&W!==X)return!1;if(delete Y.mcpServers[Z],Object.keys(Y.mcpServers).length===0)delete Y.mcpServers;return await this.writeConfigFile($,Y),!0}async deleteServerFromProjectConfig(Z,J){let X=this.getProjectConfigPath(J),$=await this.readConfigFile(X);if(!$?.mcpServers?.[Z])return!1;if(delete $.mcpServers[Z],Object.keys($.mcpServers).length===0)delete $.mcpServers;return await this.writeConfigFile(X,$),!0}async handleListServersRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("mcp/list",J.clientId,J.requestId);try{let $=[];if(J.scope==="user")$=await this.getServersFromUserConfig("user");else if(J.scope==="local"){if(!J.projectPath)throw Error("Project path is required for local scope");if(!this.isValidProjectPath(J.projectPath))throw Error("Invalid project path");$=await this.getServersFromUserConfig("local",J.projectPath)}else if(J.scope==="project"){if(!J.projectPath)throw Error("Project path is required for project scope");if(!this.isValidProjectPath(J.projectPath))throw Error("Invalid project path");$=await this.getServersFromProjectConfig(J.projectPath)}let Y={scope:J.scope,servers:$,timestamp:Date.now()};await this.publishResponse(X,Y)}catch($){let Y={scope:J.scope,servers:[],timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){dQ.error("[MCPServers] Error handling list servers request",{error:this.formatError(J)})}}async handleReadServerRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("mcp/read",J.clientId,J.requestId);try{if(!this.isValidServerName(J.serverName))throw Error("Invalid server name");let $=null;if(J.scope==="user")$=await this.getServerDetailFromUserConfig(J.serverName,"user");else if(J.scope==="local"){if(!J.projectPath)throw Error("Project path is required for local scope");if(!this.isValidProjectPath(J.projectPath))throw Error("Invalid project path");$=await this.getServerDetailFromUserConfig(J.serverName,"local",J.projectPath)}else if(J.scope==="project"){if(!J.projectPath)throw Error("Project path is required for project scope");if(!this.isValidProjectPath(J.projectPath))throw Error("Invalid project path");$=await this.getServerDetailFromProjectConfig(J.serverName,J.projectPath)}let Y={server:$||void 0,timestamp:Date.now()};await this.publishResponse(X,Y)}catch($){let Y={timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){dQ.error("[MCPServers] Error handling read server request",{error:this.formatError(J)})}}async handleWriteServerRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("mcp/write",J.clientId);try{if(!this.isValidServerName(J.serverName))throw Error("Invalid server name");if(!J.config.type)throw Error("Server type is required");if((J.config.type==="http"||J.config.type==="sse")&&!J.config.url)throw Error("URL is required for HTTP/SSE servers");if(J.config.type==="stdio"&&!J.config.command)throw Error("Command is required for stdio servers");if(J.scope==="user")await this.writeServerToUserConfig(J.serverName,J.config,"user");else if(J.scope==="local"){if(!J.projectPath)throw Error("Project path is required for local scope");if(!this.isValidProjectPath(J.projectPath))throw Error("Invalid project path");await this.writeServerToUserConfig(J.serverName,J.config,"local",J.projectPath)}else if(J.scope==="project"){if(!J.projectPath)throw Error("Project path is required for project scope");if(!this.isValidProjectPath(J.projectPath))throw Error("Invalid project path");await this.writeServerToProjectConfig(J.serverName,J.config,J.projectPath)}let $={success:!0,serverName:J.serverName,scope:J.scope,timestamp:Date.now()};await this.publishResponse(X,$)}catch($){let Y={success:!1,serverName:J.serverName,scope:J.scope,timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){dQ.error("[MCPServers] Error handling write server request",{error:this.formatError(J)})}}async handleDeleteServerRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("mcp/delete",J.clientId);try{if(!this.isValidServerName(J.serverName))throw Error("Invalid server name");let $=!1;if(J.scope==="user")$=await this.deleteServerFromUserConfig(J.serverName,"user");else if(J.scope==="local"){if(!J.projectPath)throw Error("Project path is required for local scope");if(!this.isValidProjectPath(J.projectPath))throw Error("Invalid project path");$=await this.deleteServerFromUserConfig(J.serverName,"local",J.projectPath)}else if(J.scope==="project"){if(!J.projectPath)throw Error("Project path is required for project scope");if(!this.isValidProjectPath(J.projectPath))throw Error("Invalid project path");$=await this.deleteServerFromProjectConfig(J.serverName,J.projectPath)}if(!$)throw Error("Server not found or scope mismatch");let Y={success:!0,serverName:J.serverName,scope:J.scope,timestamp:Date.now()};await this.publishResponse(X,Y)}catch($){let Y={success:!1,serverName:J.serverName,scope:J.scope,timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){dQ.error("[MCPServers] Error handling delete server request",{error:this.formatError(J)})}}}import*as DJ from"fs/promises";import*as n8 from"path";import*as $Q0 from"os";var uQ=x();class sH extends p4{name="Claude Memory Service";get logPrefix(){return"[ClaudeMemory]"}getStatus(){return{...super.getStatus()}}async onStart(){await this.ensureClaudeDirectory()}registerMQTTHandlers(){this.registerHandler("memory/read/request",(Z,J)=>{this.handleReadMemoryRequest(J)}),this.registerHandler("memory/write/request",(Z,J)=>{this.handleWriteMemoryRequest(J)}),this.registerHandler("memory/delete/request",(Z,J)=>{this.handleDeleteMemoryRequest(J)}),this.registerHandler("memory/check/request",(Z,J)=>{this.handleCheckMemoryRequest(J)}),uQ.info("[ClaudeMemory] MQTT handlers registered")}getClaudeDir(){return n8.join($Q0.homedir(),".claude")}async ensureClaudeDirectory(){let Z=this.getClaudeDir();await DJ.mkdir(Z,{recursive:!0})}getUserMemoryPath(){return n8.join(this.getClaudeDir(),"CLAUDE.md")}getLocalMemoryPath(Z){return n8.join(Z,"CLAUDE.local.md")}getProjectMemoryPath(Z){return n8.join(Z,"CLAUDE.md")}isValidProjectPath(Z){if(!n8.isAbsolute(Z))return!1;return!n8.normalize(Z).includes("..")}async readMemoryFile(Z){try{let J=await W1(Z,{logWarnings:!1});if(J===null)return null;let X=await R9(Z);if(!X)return null;return{content:J,lastModified:X.mtime.toISOString()}}catch(J){if(J.code==="ENOENT")return null;throw J}}async writeMemoryFile(Z,J){let X=n8.dirname(Z);await DJ.mkdir(X,{recursive:!0}),await DJ.writeFile(Z,J,"utf-8")}async deleteMemoryFile(Z){try{return await DJ.unlink(Z),!0}catch(J){if(J.code==="ENOENT")return!1;throw J}}async checkMemoryExists(Z){try{let J=await R9(Z);if(!J||!J.isFile())return{exists:!1};let X=await W1(Z,{logWarnings:!1});if(X===null)return{exists:!1};return{exists:!0,lastModified:J.mtime.toISOString(),preview:X.substring(0,100)}}catch(J){if(J.code==="ENOENT")return{exists:!1};throw J}}async handleReadMemoryRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("memory/read",J.clientId,J.requestId);try{let $;if(J.scope==="user")$=this.getUserMemoryPath();else if(J.scope==="local"){if(!J.projectPath)throw Error("Project path is required for local scope");if(!this.isValidProjectPath(J.projectPath))throw Error("Invalid project path");$=this.getLocalMemoryPath(J.projectPath)}else if(J.scope==="project"){if(!J.projectPath)throw Error("Project path is required for project scope");if(!this.isValidProjectPath(J.projectPath))throw Error("Invalid project path");$=this.getProjectMemoryPath(J.projectPath)}else throw Error("Invalid scope");let Y=await this.readMemoryFile($),Q={memory:Y?{scope:J.scope,projectPath:J.projectPath,content:Y.content,lastModified:Y.lastModified}:void 0,timestamp:Date.now()};await this.publishResponse(X,Q)}catch($){let Y={timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){uQ.error("[ClaudeMemory] Error handling read memory request",{error:this.formatError(J)})}}async handleWriteMemoryRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("memory/write",J.clientId);try{let $;if(J.scope==="user")$=this.getUserMemoryPath();else if(J.scope==="local"){if(!J.projectPath)throw Error("Project path is required for local scope");if(!this.isValidProjectPath(J.projectPath))throw Error("Invalid project path");$=this.getLocalMemoryPath(J.projectPath)}else if(J.scope==="project"){if(!J.projectPath)throw Error("Project path is required for project scope");if(!this.isValidProjectPath(J.projectPath))throw Error("Invalid project path");$=this.getProjectMemoryPath(J.projectPath)}else throw Error("Invalid scope");await this.writeMemoryFile($,J.content);let Y={success:!0,scope:J.scope,timestamp:Date.now()};await this.publishResponse(X,Y)}catch($){let Y={success:!1,scope:J.scope,timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){uQ.error("[ClaudeMemory] Error handling write memory request",{error:this.formatError(J)})}}async handleDeleteMemoryRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("memory/delete",J.clientId);try{let $;if(J.scope==="user")$=this.getUserMemoryPath();else if(J.scope==="local"){if(!J.projectPath)throw Error("Project path is required for local scope");if(!this.isValidProjectPath(J.projectPath))throw Error("Invalid project path");$=this.getLocalMemoryPath(J.projectPath)}else if(J.scope==="project"){if(!J.projectPath)throw Error("Project path is required for project scope");if(!this.isValidProjectPath(J.projectPath))throw Error("Invalid project path");$=this.getProjectMemoryPath(J.projectPath)}else throw Error("Invalid scope");if(!await this.deleteMemoryFile($))throw Error("Memory file not found");let Q={success:!0,scope:J.scope,timestamp:Date.now()};await this.publishResponse(X,Q)}catch($){let Y={success:!1,scope:J.scope,timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){uQ.error("[ClaudeMemory] Error handling delete memory request",{error:this.formatError(J)})}}async handleCheckMemoryRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("memory/check",J.clientId,J.requestId);try{let $;if(J.scope==="user")$=this.getUserMemoryPath();else if(J.scope==="local"){if(!J.projectPath)throw Error("Project path is required for local scope");if(!this.isValidProjectPath(J.projectPath))throw Error("Invalid project path");$=this.getLocalMemoryPath(J.projectPath)}else if(J.scope==="project"){if(!J.projectPath)throw Error("Project path is required for project scope");if(!this.isValidProjectPath(J.projectPath))throw Error("Invalid project path");$=this.getProjectMemoryPath(J.projectPath)}else throw Error("Invalid scope");let Y=await this.checkMemoryExists($),Q={entry:{scope:J.scope,projectPath:J.projectPath,exists:Y.exists,lastModified:Y.lastModified,preview:Y.preview},timestamp:Date.now()};await this.publishResponse(X,Q)}catch($){let Y={entry:{scope:J.scope,projectPath:J.projectPath,exists:!1},timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){uQ.error("[ClaudeMemory] Error handling check memory request",{error:this.formatError(J)})}}}import*as a1 from"fs/promises";import*as B1 from"path";import*as cQ from"os";var{YAML:MZ1}=globalThis.Bun;var h5=x();class tH extends p4{name="Skills Service";get logPrefix(){return"[Skills]"}getStatus(){return{...super.getStatus()}}registerMQTTHandlers(){this.registerHandler("skills/list/request",(Z,J)=>{this.handleListSkillsRequest(J)}),this.registerHandler("skills/read/request",(Z,J)=>{this.handleReadSkillRequest(J)}),this.registerHandler("skills/write/request",(Z,J)=>{this.handleWriteSkillRequest(J)}),this.registerHandler("skills/delete/request",(Z,J)=>{this.handleDeleteSkillRequest(J)}),this.registerHandler("skills/install/request",(Z,J)=>{this.handleInstallSkillRequest(J)}),h5.info("[Skills] MQTT handlers registered")}getSkillsDir(Z,J){if(Z==="user")return B1.join(cQ.homedir(),".claude","skills");else{if(!J)throw Error("Project path is required for project-scoped skills");return B1.join(J,".claude","skills")}}parseFrontmatter(Z){let J=/^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/,X=Z.match(J);if(!X)return{body:Z};let $=X[1]||"",Y=X[2]||"";try{let Q=MZ1.parse($);if(!Q||typeof Q!=="object")return{body:Y};let W={};if(Q.name)W.name=String(Q.name);if(Q.description)W.description=String(Q.description);if(Q.license)W.license=String(Q.license);if(Array.isArray(Q.compatibility))W.compatibility=Q.compatibility.map(String);if(Q.metadata&&typeof Q.metadata==="object"){if(W.metadata={},Q.metadata.author)W.metadata.author=String(Q.metadata.author);if(Q.metadata.version)W.metadata.version=String(Q.metadata.version);if(Q.metadata.repository)W.metadata.repository=String(Q.metadata.repository);if(Array.isArray(Q.metadata.tags))W.metadata.tags=Q.metadata.tags.map(String)}if(Q["allowed-tools"]){if(typeof Q["allowed-tools"]==="string")W.allowedTools=Q["allowed-tools"].split(",").map((K)=>K.trim()).filter(Boolean);else if(Array.isArray(Q["allowed-tools"]))W.allowedTools=Q["allowed-tools"].map(String)}if(Q["user-invocable"]!==void 0){if(typeof Q["user-invocable"]==="boolean")W.userInvocable=Q["user-invocable"];else if(typeof Q["user-invocable"]==="object")W.userInvocable=!0}if(Q["argument-hint"])W.argumentHint=String(Q["argument-hint"]);if(Q["disable-model-invocation"]===!0)W.disableModelInvocation=!0;if(Q.model)W.model=String(Q.model);if(Q.context==="fork")W.context="fork";if(Q.agent)W.agent=String(Q.agent);if(Q.hooks&&typeof Q.hooks==="object"&&!Array.isArray(Q.hooks)){let K={};if(Array.isArray(Q.hooks.PreToolUse))K.PreToolUse=this.parseHookMatchers(Q.hooks.PreToolUse);if(Array.isArray(Q.hooks.PostToolUse))K.PostToolUse=this.parseHookMatchers(Q.hooks.PostToolUse);if(Array.isArray(Q.hooks.Stop))K.Stop=Q.hooks.Stop.filter((z)=>z&&typeof z.command==="string").map((z)=>({command:String(z.command)}));if(Object.keys(K).length>0)W.hooks=K}return{frontmatter:Object.keys(W).length>0?W:void 0,body:Y}}catch(Q){return h5.warn("[Skills] Failed to parse frontmatter",{error:Q}),{body:Z}}}parseHookMatchers(Z){return Z.filter((J)=>J&&typeof J.matcher==="string"&&Array.isArray(J.hooks)).map((J)=>({matcher:String(J.matcher),hooks:J.hooks.filter((X)=>X&&typeof X.command==="string").map((X)=>({command:String(X.command)}))})).filter((J)=>J.hooks.length>0)}generateFrontmatter(Z){let J=["---"];if(J.push(`name: ${Z.name}`),J.push(`description: "${Z.description.replace(/"/g,"\\\"")}"`),Z.license)J.push(`license: ${Z.license}`);if(Z.compatibility&&Z.compatibility.length>0){J.push("compatibility:");for(let X of Z.compatibility)J.push(` - ${X}`)}if(Z.metadata&&Object.keys(Z.metadata).length>0){if(J.push("metadata:"),Z.metadata.author)J.push(` author: ${Z.metadata.author}`);if(Z.metadata.version)J.push(` version: ${Z.metadata.version}`);if(Z.metadata.repository)J.push(` repository: ${Z.metadata.repository}`);if(Z.metadata.tags&&Z.metadata.tags.length>0){J.push(" tags:");for(let X of Z.metadata.tags)J.push(` - ${X}`)}}if(Z.allowedTools&&Z.allowedTools.length>0){J.push("allowed-tools:");for(let X of Z.allowedTools)J.push(` - ${X}`)}if(Z.userInvocable!==void 0)J.push(`user-invocable: ${Z.userInvocable}`);if(Z.argumentHint)J.push(`argument-hint: "${Z.argumentHint.replace(/"/g,"\\\"")}"`);if(Z.disableModelInvocation)J.push("disable-model-invocation: true");if(Z.model)J.push(`model: ${Z.model}`);if(Z.context==="fork")J.push("context: fork");if(Z.agent)J.push(`agent: ${Z.agent}`);if(Z.hooks&&Object.keys(Z.hooks).length>0){if(J.push("hooks:"),Z.hooks.PreToolUse&&Z.hooks.PreToolUse.length>0){J.push(" PreToolUse:");for(let X of Z.hooks.PreToolUse){J.push(` - matcher: ${X.matcher}`),J.push(" hooks:");for(let $ of X.hooks)J.push(` - command: "${$.command.replace(/"/g,"\\\"")}"`)}}if(Z.hooks.PostToolUse&&Z.hooks.PostToolUse.length>0){J.push(" PostToolUse:");for(let X of Z.hooks.PostToolUse){J.push(` - matcher: ${X.matcher}`),J.push(" hooks:");for(let $ of X.hooks)J.push(` - command: "${$.command.replace(/"/g,"\\\"")}"`)}}if(Z.hooks.Stop&&Z.hooks.Stop.length>0){J.push(" Stop:");for(let X of Z.hooks.Stop)J.push(` - command: "${X.command.replace(/"/g,"\\\"")}"`)}}return J.push("---"),J.join(`
2379
- `)}async checkSubfolders(Z){let J={hasScripts:!1,hasReferences:!1,hasAssets:!1};try{let X=B1.join(Z,"scripts"),$=B1.join(Z,"references"),Y=B1.join(Z,"assets"),[Q,W,K]=await Promise.all([a1.stat(X).then((z)=>z.isDirectory()).catch(()=>!1),a1.stat($).then((z)=>z.isDirectory()).catch(()=>!1),a1.stat(Y).then((z)=>z.isDirectory()).catch(()=>!1)]);J.hasScripts=Q,J.hasReferences=W,J.hasAssets=K}catch{}return J}async scanSkillsDir(Z,J,X){let $=[];try{if(!await c4(Z))return $;let Q=await a1.readdir(Z,{withFileTypes:!0});for(let W of Q)if(W.isDirectory()){let K=B1.join(Z,W.name),z=B1.join(K,"SKILL.md");try{let G=await W1(z);if(G===null)continue;let{frontmatter:H}=this.parseFrontmatter(G),V=await this.checkSubfolders(K);$.push({name:H?.name||W.name,description:H?.description||"",scope:J,projectPath:J==="project"?X:void 0,path:K,...V})}catch(G){h5.debug("[Skills] Error processing skill folder",{skillDir:K,error:G})}}}catch(Y){if(Y.code!=="ENOENT")h5.warn("[Skills] Error scanning directory",{dir:Z,error:Y})}return $}async handleListSkillsRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("skills/list",J.clientId,J.requestId);try{let $=this.getSkillsDir(J.scope,J.projectPath),Y=await this.scanSkillsDir($,J.scope,J.projectPath),Q={scope:J.scope,skills:Y,timestamp:Date.now()};await this.publishResponse(X,Q)}catch($){let Y={scope:J.scope,skills:[],timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){h5.error("[Skills] Error handling list skills request",{error:this.formatError(J)})}}async handleReadSkillRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("skills/read",J.clientId);try{let $=this.getSkillsDir(J.scope,J.projectPath),Y=B1.join(J.skillPath,"SKILL.md"),Q=B1.resolve(Y).toLowerCase().replace(/\\/g,"/"),W=B1.resolve($).toLowerCase().replace(/\\/g,"/");if(!Q.startsWith(W))throw h5.warn("[Skills] Path security check failed",{resolvedPath:Q,resolvedBase:W,skillPath:J.skillPath,scope:J.scope}),Error("Invalid skill path");let K=await W1(Y);if(K===null)throw Error("Skill file not found or unreadable");let z=await a1.stat(Y),{frontmatter:G,body:H}=this.parseFrontmatter(K),V=await this.checkSubfolders(J.skillPath),F=B1.basename(J.skillPath),U={skill:{name:G?.name||F,description:G?.description||"",scope:J.scope,projectPath:J.projectPath,path:J.skillPath,...V,license:G?.license,compatibility:G?.compatibility,metadata:G?.metadata,allowedTools:G?.allowedTools,userInvocable:G?.userInvocable,argumentHint:G?.argumentHint,disableModelInvocation:G?.disableModelInvocation,model:G?.model,context:G?.context,agent:G?.agent,hooks:G?.hooks,content:H,rawContent:K,lastModified:z.mtime.toISOString()},timestamp:Date.now()};await this.publishResponse(X,U)}catch($){let Y={timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){h5.error("[Skills] Error handling read skill request",{error:this.formatError(J)})}}async handleWriteSkillRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("skills/write",J.clientId);try{let $=this.getSkillsDir(J.scope,J.projectPath);if(!/^[a-z][a-z0-9-]*$/i.test(J.skillName))throw Error("Invalid skill name");let Y=B1.join($,J.skillName),Q=B1.join(Y,"SKILL.md"),W=B1.resolve(Q),K=B1.resolve($);if(!W.startsWith(K))throw Error("Invalid skill path");await a1.mkdir(Y,{recursive:!0});let G=this.generateFrontmatter({name:J.skillName,description:J.description,license:J.license,compatibility:J.compatibility,metadata:J.metadata,allowedTools:J.allowedTools,userInvocable:J.userInvocable,argumentHint:J.argumentHint,disableModelInvocation:J.disableModelInvocation,model:J.model,context:J.context,agent:J.agent,hooks:J.hooks})+`
2378
+ `;K+=J.content,await u7.writeFile(Y,K,"utf-8");let z={success:!0,commandName:J.commandName,scope:J.scope,timestamp:Date.now()};await this.publishResponse(X,z)}catch($){let Y={success:!1,commandName:J.commandName,scope:J.scope,timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){d7.error("[SlashCommands] Error handling write command request",{error:this.formatError(J)})}}async handleDeleteCommandRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("commands/delete",J.clientId);try{let $=this.getCommandsDir(J.scope,J.projectPath),Y=Y4.join($,`${J.commandName}.md`),Q=Y4.resolve(Y),W=Y4.resolve($);if(!Q.startsWith(W))throw Error("Invalid command path");await u7.unlink(Y);let K={success:!0,commandName:J.commandName,scope:J.scope,timestamp:Date.now()};await this.publishResponse(X,K)}catch($){let Y={success:!1,commandName:J.commandName,scope:J.scope,timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){d7.error("[SlashCommands] Error handling delete command request",{error:this.formatError(J)})}}}import*as Bj from"path";import*as XQ0 from"os";import*as c7 from"fs/promises";import*as aH from"path";var s30=x(),jZ1={logWarnings:!0,ensureDirectory:!0,prettyFormat:!0};class Vj{options;constructor(Z={}){this.options={...jZ1,...Z}}async readConfig(Z){try{let J=await W1(Z,{logWarnings:this.options.logWarnings});if(J===null)return null;return JSON.parse(J)}catch(J){return s30.debug("[ConfigManager] Error parsing config file",{filePath:Z,error:J}),null}}async readConfigOrEmpty(Z){return await this.readConfig(Z)??{}}async writeConfig(Z,J){if(this.options.ensureDirectory){let $=aH.dirname(Z);await c7.mkdir($,{recursive:!0})}let X=this.options.prettyFormat?JSON.stringify(J,null,2):JSON.stringify(J);await c7.writeFile(Z,X,"utf-8"),s30.debug("[ConfigManager] Config file written",{filePath:Z})}async updateConfig(Z,J){let $={...await this.readConfigOrEmpty(Z),...J};await this.writeConfig(Z,$)}async deleteConfigKeys(Z,J){let X=await this.readConfigOrEmpty(Z);for(let $ of J)delete X[$];await this.writeConfig(Z,X)}async configExists(Z){try{return await c7.access(Z,c7.constants.R_OK),!0}catch{return!1}}async getConfigValue(Z,J,X){return(await this.readConfigOrEmpty(Z))[J]??X}async setConfigValue(Z,J,X){await this.updateConfig(Z,{[J]:X})}forDirectory(Z){return new t30(Z,this.options)}}class t30 extends Vj{baseDir;constructor(Z,J={}){super(J);this.baseDir=Z}resolvePath(Z){return aH.resolve(this.baseDir,Z)}async readConfig(Z){return super.readConfig(this.resolvePath(Z))}async readConfigOrEmpty(Z){return super.readConfigOrEmpty(this.resolvePath(Z))}async writeConfig(Z,J){return super.writeConfig(this.resolvePath(Z),J)}async updateConfig(Z,J){return super.updateConfig(this.resolvePath(Z),J)}async deleteConfigKeys(Z,J){return super.deleteConfigKeys(this.resolvePath(Z),J)}async configExists(Z){return super.configExists(this.resolvePath(Z))}async getConfigValue(Z,J,X){return super.getConfigValue(this.resolvePath(Z),J,X)}async setConfigValue(Z,J,X){return super.setConfigValue(this.resolvePath(Z),J,X)}}var E9=new Vj;import*as F8 from"path";import*as e30 from"os";class Fj{getBaseDir(Z,J){switch(Z){case"user":return F8.join(e30.homedir(),".claude");case"local":return F8.join(process.cwd(),".claude");case"project":if(!J)throw Error("Project path is required for project scope");return F8.join(J,".claude");default:throw Error(`Unknown scope: ${Z}`)}}getConfigDir(Z,J,X){let $=this.getBaseDir(J,X);switch(Z){case"plugins":return F8.join($,"plugins");case"hooks":return $;case"skills":return F8.join($,"skills");case"mcp":return $;case"claude":return $;case"settings":return $;default:throw Error(`Unknown config type: ${Z}`)}}getConfigPath(Z,J,X,$){let Y=this.getConfigDir(Z,J,X),Q=$??this.getDefaultFileName(Z);return F8.join(Y,Q)}getDefaultFileName(Z){switch(Z){case"plugins":return"settings.json";case"hooks":return"hooks.json";case"skills":return"skills.json";case"mcp":return"mcp.json";case"claude":return"claude_desktop_config.json";case"settings":return"settings.json";default:throw Error(`Unknown config type: ${Z}`)}}getUserConfigPath(Z,J){return this.getConfigPath(Z,"user",void 0,J)}getProjectConfigPath(Z,J,X){return this.getConfigPath(Z,"project",J,X)}getLocalConfigPath(Z,J){return this.getConfigPath(Z,"local",void 0,J)}validateProjectPath(Z){if(!Z||typeof Z!=="string")return!1;if(!F8.isAbsolute(Z))return!1;if(F8.normalize(Z).includes(".."))return!1;return!0}getAllConfigPaths(Z,J,X){let $={user:this.getUserConfigPath(Z,X),local:this.getLocalConfigPath(Z,X)};if(J&&this.validateProjectPath(J))$.project=this.getProjectConfigPath(Z,J,X);return $}resolveConfigPaths(Z,J,X){let $=this.getAllConfigPaths(Z,J,X),Y=[];if($.project)Y.push($.project);return Y.push($.local),Y.push($.user),Y}getPluginsDir(Z,J){return this.getConfigDir("plugins",Z,J)}getSkillsDir(Z,J){return this.getConfigDir("skills",Z,J)}getMarketplaceCacheDir(){return F8.join(this.getBaseDir("user"),"plugins","marketplace-cache")}forProject(Z){if(!this.validateProjectPath(Z))throw Error(`Invalid project path: ${Z}`);return new ZQ0(Z)}}class ZQ0{projectPath;pathResolver=new Fj;constructor(Z){this.projectPath=Z}getUserConfigPath(Z,J){return this.pathResolver.getUserConfigPath(Z,J)}getProjectConfigPath(Z,J){return this.pathResolver.getProjectConfigPath(Z,this.projectPath,J)}getLocalConfigPath(Z,J){return this.pathResolver.getLocalConfigPath(Z,J)}getAllConfigPaths(Z,J){return this.pathResolver.getAllConfigPaths(Z,this.projectPath,J)}resolveConfigPaths(Z,J){return this.pathResolver.resolveConfigPaths(Z,this.projectPath,J)}getPluginsDir(Z){return this.pathResolver.getPluginsDir(Z,this.projectPath)}getSkillsDir(Z){return this.pathResolver.getSkillsDir(Z,this.projectPath)}}var I9=new Fj;function JQ0(Z){if(!Z||typeof Z!=="string")return!1;return/^[a-zA-Z][a-zA-Z0-9-]*$/.test(Z)}var dQ=x();class rH extends p4{name="MCP Servers Service";get logPrefix(){return"[MCPServers]"}getStatus(){return{...super.getStatus()}}registerMQTTHandlers(){this.registerHandler("mcp/list/request",(Z,J)=>{this.handleListServersRequest(J)}),this.registerHandler("mcp/read/request",(Z,J)=>{this.handleReadServerRequest(J)}),this.registerHandler("mcp/write/request",(Z,J)=>{this.handleWriteServerRequest(J)}),this.registerHandler("mcp/delete/request",(Z,J)=>{this.handleDeleteServerRequest(J)}),dQ.info("[MCPServers] MQTT handlers registered")}getUserConfigPath(){return Bj.join(XQ0.homedir(),".claude.json")}getProjectConfigPath(Z){return Bj.join(Z,".mcp.json")}isValidServerName(Z){return JQ0(Z)}isValidProjectPath(Z){return I9.validateProjectPath(Z)}async readConfigFile(Z){return await E9.readConfig(Z)}async writeConfigFile(Z,J){await E9.writeConfig(Z,J)}async getServersFromUserConfig(Z,J){let X=this.getUserConfigPath(),$=await this.readConfigFile(X);if(!$?.mcpServers)return[];let Y=[];for(let[Q,W]of Object.entries($.mcpServers)){let K=W._projectPath;if(Z==="user"){if(!K)Y.push({name:Q,type:W.type,url:W.url,command:W.command,scope:"user"})}else if(Z==="local"&&J){if(K===J)Y.push({name:Q,type:W.type,url:W.url,command:W.command,scope:"local",projectPath:K})}}return Y}async getServersFromProjectConfig(Z){let J=this.getProjectConfigPath(Z),X=await this.readConfigFile(J);if(!X?.mcpServers)return[];let $=[];for(let[Y,Q]of Object.entries(X.mcpServers))$.push({name:Y,type:Q.type,url:Q.url,command:Q.command,scope:"project",projectPath:Z});return $}async getServerDetailFromUserConfig(Z,J,X){let $=this.getUserConfigPath(),Y=await this.readConfigFile($);if(!Y?.mcpServers?.[Z])return null;let Q=Y.mcpServers[Z],W=Q._projectPath;if(J==="user"&&W)return null;if(J==="local"&&W!==X)return null;let{_projectPath:K,...z}=Q;return{name:Z,type:z.type,url:z.url,command:z.command,args:z.args,env:z.env,headers:z.headers,scope:J,projectPath:K}}async getServerDetailFromProjectConfig(Z,J){let X=this.getProjectConfigPath(J),$=await this.readConfigFile(X);if(!$?.mcpServers?.[Z])return null;let Y=$.mcpServers[Z];return{name:Z,type:Y.type,url:Y.url,command:Y.command,args:Y.args,env:Y.env,headers:Y.headers,scope:"project",projectPath:J}}async writeServerToUserConfig(Z,J,X,$){let Y=this.getUserConfigPath(),Q=await this.readConfigFile(Y);if(!Q)Q={};if(!Q.mcpServers)Q.mcpServers={};let W={...J};if(X==="local"&&$)W._projectPath=$;Q.mcpServers[Z]=W,await this.writeConfigFile(Y,Q)}async writeServerToProjectConfig(Z,J,X){let $=this.getProjectConfigPath(X),Y=await this.readConfigFile($);if(!Y)Y={};if(!Y.mcpServers)Y.mcpServers={};Y.mcpServers[Z]=J,await this.writeConfigFile($,Y)}async deleteServerFromUserConfig(Z,J,X){let $=this.getUserConfigPath(),Y=await this.readConfigFile($);if(!Y?.mcpServers?.[Z])return!1;let W=Y.mcpServers[Z]._projectPath;if(J==="user"&&W)return!1;if(J==="local"&&W!==X)return!1;if(delete Y.mcpServers[Z],Object.keys(Y.mcpServers).length===0)delete Y.mcpServers;return await this.writeConfigFile($,Y),!0}async deleteServerFromProjectConfig(Z,J){let X=this.getProjectConfigPath(J),$=await this.readConfigFile(X);if(!$?.mcpServers?.[Z])return!1;if(delete $.mcpServers[Z],Object.keys($.mcpServers).length===0)delete $.mcpServers;return await this.writeConfigFile(X,$),!0}async handleListServersRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("mcp/list",J.clientId,J.requestId);try{let $=[];if(J.scope==="user")$=await this.getServersFromUserConfig("user");else if(J.scope==="local"){if(!J.projectPath)throw Error("Project path is required for local scope");if(!this.isValidProjectPath(J.projectPath))throw Error("Invalid project path");$=await this.getServersFromUserConfig("local",J.projectPath)}else if(J.scope==="project"){if(!J.projectPath)throw Error("Project path is required for project scope");if(!this.isValidProjectPath(J.projectPath))throw Error("Invalid project path");$=await this.getServersFromProjectConfig(J.projectPath)}let Y={scope:J.scope,servers:$,timestamp:Date.now()};await this.publishResponse(X,Y)}catch($){let Y={scope:J.scope,servers:[],timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){dQ.error("[MCPServers] Error handling list servers request",{error:this.formatError(J)})}}async handleReadServerRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("mcp/read",J.clientId,J.requestId);try{if(!this.isValidServerName(J.serverName))throw Error("Invalid server name");let $=null;if(J.scope==="user")$=await this.getServerDetailFromUserConfig(J.serverName,"user");else if(J.scope==="local"){if(!J.projectPath)throw Error("Project path is required for local scope");if(!this.isValidProjectPath(J.projectPath))throw Error("Invalid project path");$=await this.getServerDetailFromUserConfig(J.serverName,"local",J.projectPath)}else if(J.scope==="project"){if(!J.projectPath)throw Error("Project path is required for project scope");if(!this.isValidProjectPath(J.projectPath))throw Error("Invalid project path");$=await this.getServerDetailFromProjectConfig(J.serverName,J.projectPath)}let Y={server:$||void 0,timestamp:Date.now()};await this.publishResponse(X,Y)}catch($){let Y={timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){dQ.error("[MCPServers] Error handling read server request",{error:this.formatError(J)})}}async handleWriteServerRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("mcp/write",J.clientId);try{if(!this.isValidServerName(J.serverName))throw Error("Invalid server name");if(!J.config.type)throw Error("Server type is required");if((J.config.type==="http"||J.config.type==="sse")&&!J.config.url)throw Error("URL is required for HTTP/SSE servers");if(J.config.type==="stdio"&&!J.config.command)throw Error("Command is required for stdio servers");if(J.scope==="user")await this.writeServerToUserConfig(J.serverName,J.config,"user");else if(J.scope==="local"){if(!J.projectPath)throw Error("Project path is required for local scope");if(!this.isValidProjectPath(J.projectPath))throw Error("Invalid project path");await this.writeServerToUserConfig(J.serverName,J.config,"local",J.projectPath)}else if(J.scope==="project"){if(!J.projectPath)throw Error("Project path is required for project scope");if(!this.isValidProjectPath(J.projectPath))throw Error("Invalid project path");await this.writeServerToProjectConfig(J.serverName,J.config,J.projectPath)}let $={success:!0,serverName:J.serverName,scope:J.scope,timestamp:Date.now()};await this.publishResponse(X,$)}catch($){let Y={success:!1,serverName:J.serverName,scope:J.scope,timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){dQ.error("[MCPServers] Error handling write server request",{error:this.formatError(J)})}}async handleDeleteServerRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("mcp/delete",J.clientId);try{if(!this.isValidServerName(J.serverName))throw Error("Invalid server name");let $=!1;if(J.scope==="user")$=await this.deleteServerFromUserConfig(J.serverName,"user");else if(J.scope==="local"){if(!J.projectPath)throw Error("Project path is required for local scope");if(!this.isValidProjectPath(J.projectPath))throw Error("Invalid project path");$=await this.deleteServerFromUserConfig(J.serverName,"local",J.projectPath)}else if(J.scope==="project"){if(!J.projectPath)throw Error("Project path is required for project scope");if(!this.isValidProjectPath(J.projectPath))throw Error("Invalid project path");$=await this.deleteServerFromProjectConfig(J.serverName,J.projectPath)}if(!$)throw Error("Server not found or scope mismatch");let Y={success:!0,serverName:J.serverName,scope:J.scope,timestamp:Date.now()};await this.publishResponse(X,Y)}catch($){let Y={success:!1,serverName:J.serverName,scope:J.scope,timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){dQ.error("[MCPServers] Error handling delete server request",{error:this.formatError(J)})}}}import*as DJ from"fs/promises";import*as n8 from"path";import*as $Q0 from"os";var uQ=x();class sH extends p4{name="Claude Memory Service";get logPrefix(){return"[ClaudeMemory]"}getStatus(){return{...super.getStatus()}}async onStart(){await this.ensureClaudeDirectory()}registerMQTTHandlers(){this.registerHandler("memory/read/request",(Z,J)=>{this.handleReadMemoryRequest(J)}),this.registerHandler("memory/write/request",(Z,J)=>{this.handleWriteMemoryRequest(J)}),this.registerHandler("memory/delete/request",(Z,J)=>{this.handleDeleteMemoryRequest(J)}),this.registerHandler("memory/check/request",(Z,J)=>{this.handleCheckMemoryRequest(J)}),uQ.info("[ClaudeMemory] MQTT handlers registered")}getClaudeDir(){return n8.join($Q0.homedir(),".claude")}async ensureClaudeDirectory(){let Z=this.getClaudeDir();await DJ.mkdir(Z,{recursive:!0})}getUserMemoryPath(){return n8.join(this.getClaudeDir(),"CLAUDE.md")}getLocalMemoryPath(Z){return n8.join(Z,"CLAUDE.local.md")}getProjectMemoryPath(Z){return n8.join(Z,"CLAUDE.md")}isValidProjectPath(Z){if(!n8.isAbsolute(Z))return!1;return!n8.normalize(Z).includes("..")}async readMemoryFile(Z){try{let J=await W1(Z,{logWarnings:!1});if(J===null)return null;let X=await R9(Z);if(!X)return null;return{content:J,lastModified:X.mtime.toISOString()}}catch(J){if(J.code==="ENOENT")return null;throw J}}async writeMemoryFile(Z,J){let X=n8.dirname(Z);await DJ.mkdir(X,{recursive:!0}),await DJ.writeFile(Z,J,"utf-8")}async deleteMemoryFile(Z){try{return await DJ.unlink(Z),!0}catch(J){if(J.code==="ENOENT")return!1;throw J}}async checkMemoryExists(Z){try{let J=await R9(Z);if(!J||!J.isFile())return{exists:!1};let X=await W1(Z,{logWarnings:!1});if(X===null)return{exists:!1};return{exists:!0,lastModified:J.mtime.toISOString(),preview:X.substring(0,100)}}catch(J){if(J.code==="ENOENT")return{exists:!1};throw J}}async handleReadMemoryRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("memory/read",J.clientId,J.requestId);try{let $;if(J.scope==="user")$=this.getUserMemoryPath();else if(J.scope==="local"){if(!J.projectPath)throw Error("Project path is required for local scope");if(!this.isValidProjectPath(J.projectPath))throw Error("Invalid project path");$=this.getLocalMemoryPath(J.projectPath)}else if(J.scope==="project"){if(!J.projectPath)throw Error("Project path is required for project scope");if(!this.isValidProjectPath(J.projectPath))throw Error("Invalid project path");$=this.getProjectMemoryPath(J.projectPath)}else throw Error("Invalid scope");let Y=await this.readMemoryFile($),Q={memory:Y?{scope:J.scope,projectPath:J.projectPath,content:Y.content,lastModified:Y.lastModified}:void 0,timestamp:Date.now()};await this.publishResponse(X,Q)}catch($){let Y={timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){uQ.error("[ClaudeMemory] Error handling read memory request",{error:this.formatError(J)})}}async handleWriteMemoryRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("memory/write",J.clientId);try{let $;if(J.scope==="user")$=this.getUserMemoryPath();else if(J.scope==="local"){if(!J.projectPath)throw Error("Project path is required for local scope");if(!this.isValidProjectPath(J.projectPath))throw Error("Invalid project path");$=this.getLocalMemoryPath(J.projectPath)}else if(J.scope==="project"){if(!J.projectPath)throw Error("Project path is required for project scope");if(!this.isValidProjectPath(J.projectPath))throw Error("Invalid project path");$=this.getProjectMemoryPath(J.projectPath)}else throw Error("Invalid scope");await this.writeMemoryFile($,J.content);let Y={success:!0,scope:J.scope,timestamp:Date.now()};await this.publishResponse(X,Y)}catch($){let Y={success:!1,scope:J.scope,timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){uQ.error("[ClaudeMemory] Error handling write memory request",{error:this.formatError(J)})}}async handleDeleteMemoryRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("memory/delete",J.clientId);try{let $;if(J.scope==="user")$=this.getUserMemoryPath();else if(J.scope==="local"){if(!J.projectPath)throw Error("Project path is required for local scope");if(!this.isValidProjectPath(J.projectPath))throw Error("Invalid project path");$=this.getLocalMemoryPath(J.projectPath)}else if(J.scope==="project"){if(!J.projectPath)throw Error("Project path is required for project scope");if(!this.isValidProjectPath(J.projectPath))throw Error("Invalid project path");$=this.getProjectMemoryPath(J.projectPath)}else throw Error("Invalid scope");if(!await this.deleteMemoryFile($))throw Error("Memory file not found");let Q={success:!0,scope:J.scope,timestamp:Date.now()};await this.publishResponse(X,Q)}catch($){let Y={success:!1,scope:J.scope,timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){uQ.error("[ClaudeMemory] Error handling delete memory request",{error:this.formatError(J)})}}async handleCheckMemoryRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("memory/check",J.clientId,J.requestId);try{let $;if(J.scope==="user")$=this.getUserMemoryPath();else if(J.scope==="local"){if(!J.projectPath)throw Error("Project path is required for local scope");if(!this.isValidProjectPath(J.projectPath))throw Error("Invalid project path");$=this.getLocalMemoryPath(J.projectPath)}else if(J.scope==="project"){if(!J.projectPath)throw Error("Project path is required for project scope");if(!this.isValidProjectPath(J.projectPath))throw Error("Invalid project path");$=this.getProjectMemoryPath(J.projectPath)}else throw Error("Invalid scope");let Y=await this.checkMemoryExists($),Q={entry:{scope:J.scope,projectPath:J.projectPath,exists:Y.exists,lastModified:Y.lastModified,preview:Y.preview},timestamp:Date.now()};await this.publishResponse(X,Q)}catch($){let Y={entry:{scope:J.scope,projectPath:J.projectPath,exists:!1},timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){uQ.error("[ClaudeMemory] Error handling check memory request",{error:this.formatError(J)})}}}import*as r1 from"fs/promises";import*as B1 from"path";import*as cQ from"os";var{YAML:MZ1}=globalThis.Bun;var h5=x();class tH extends p4{name="Skills Service";get logPrefix(){return"[Skills]"}getStatus(){return{...super.getStatus()}}registerMQTTHandlers(){this.registerHandler("skills/list/request",(Z,J)=>{this.handleListSkillsRequest(J)}),this.registerHandler("skills/read/request",(Z,J)=>{this.handleReadSkillRequest(J)}),this.registerHandler("skills/write/request",(Z,J)=>{this.handleWriteSkillRequest(J)}),this.registerHandler("skills/delete/request",(Z,J)=>{this.handleDeleteSkillRequest(J)}),this.registerHandler("skills/install/request",(Z,J)=>{this.handleInstallSkillRequest(J)}),h5.info("[Skills] MQTT handlers registered")}getSkillsDir(Z,J){if(Z==="user")return B1.join(cQ.homedir(),".claude","skills");else{if(!J)throw Error("Project path is required for project-scoped skills");return B1.join(J,".claude","skills")}}parseFrontmatter(Z){let J=/^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/,X=Z.match(J);if(!X)return{body:Z};let $=X[1]||"",Y=X[2]||"";try{let Q=MZ1.parse($);if(!Q||typeof Q!=="object")return{body:Y};let W={};if(Q.name)W.name=String(Q.name);if(Q.description)W.description=String(Q.description);if(Q.license)W.license=String(Q.license);if(Array.isArray(Q.compatibility))W.compatibility=Q.compatibility.map(String);if(Q.metadata&&typeof Q.metadata==="object"){if(W.metadata={},Q.metadata.author)W.metadata.author=String(Q.metadata.author);if(Q.metadata.version)W.metadata.version=String(Q.metadata.version);if(Q.metadata.repository)W.metadata.repository=String(Q.metadata.repository);if(Array.isArray(Q.metadata.tags))W.metadata.tags=Q.metadata.tags.map(String)}if(Q["allowed-tools"]){if(typeof Q["allowed-tools"]==="string")W.allowedTools=Q["allowed-tools"].split(",").map((K)=>K.trim()).filter(Boolean);else if(Array.isArray(Q["allowed-tools"]))W.allowedTools=Q["allowed-tools"].map(String)}if(Q["user-invocable"]!==void 0){if(typeof Q["user-invocable"]==="boolean")W.userInvocable=Q["user-invocable"];else if(typeof Q["user-invocable"]==="object")W.userInvocable=!0}if(Q["argument-hint"])W.argumentHint=String(Q["argument-hint"]);if(Q["disable-model-invocation"]===!0)W.disableModelInvocation=!0;if(Q.model)W.model=String(Q.model);if(Q.context==="fork")W.context="fork";if(Q.agent)W.agent=String(Q.agent);if(Q.hooks&&typeof Q.hooks==="object"&&!Array.isArray(Q.hooks)){let K={};if(Array.isArray(Q.hooks.PreToolUse))K.PreToolUse=this.parseHookMatchers(Q.hooks.PreToolUse);if(Array.isArray(Q.hooks.PostToolUse))K.PostToolUse=this.parseHookMatchers(Q.hooks.PostToolUse);if(Array.isArray(Q.hooks.Stop))K.Stop=Q.hooks.Stop.filter((z)=>z&&typeof z.command==="string").map((z)=>({command:String(z.command)}));if(Object.keys(K).length>0)W.hooks=K}return{frontmatter:Object.keys(W).length>0?W:void 0,body:Y}}catch(Q){return h5.warn("[Skills] Failed to parse frontmatter",{error:Q}),{body:Z}}}parseHookMatchers(Z){return Z.filter((J)=>J&&typeof J.matcher==="string"&&Array.isArray(J.hooks)).map((J)=>({matcher:String(J.matcher),hooks:J.hooks.filter((X)=>X&&typeof X.command==="string").map((X)=>({command:String(X.command)}))})).filter((J)=>J.hooks.length>0)}generateFrontmatter(Z){let J=["---"];if(J.push(`name: ${Z.name}`),J.push(`description: "${Z.description.replace(/"/g,"\\\"")}"`),Z.license)J.push(`license: ${Z.license}`);if(Z.compatibility&&Z.compatibility.length>0){J.push("compatibility:");for(let X of Z.compatibility)J.push(` - ${X}`)}if(Z.metadata&&Object.keys(Z.metadata).length>0){if(J.push("metadata:"),Z.metadata.author)J.push(` author: ${Z.metadata.author}`);if(Z.metadata.version)J.push(` version: ${Z.metadata.version}`);if(Z.metadata.repository)J.push(` repository: ${Z.metadata.repository}`);if(Z.metadata.tags&&Z.metadata.tags.length>0){J.push(" tags:");for(let X of Z.metadata.tags)J.push(` - ${X}`)}}if(Z.allowedTools&&Z.allowedTools.length>0){J.push("allowed-tools:");for(let X of Z.allowedTools)J.push(` - ${X}`)}if(Z.userInvocable!==void 0)J.push(`user-invocable: ${Z.userInvocable}`);if(Z.argumentHint)J.push(`argument-hint: "${Z.argumentHint.replace(/"/g,"\\\"")}"`);if(Z.disableModelInvocation)J.push("disable-model-invocation: true");if(Z.model)J.push(`model: ${Z.model}`);if(Z.context==="fork")J.push("context: fork");if(Z.agent)J.push(`agent: ${Z.agent}`);if(Z.hooks&&Object.keys(Z.hooks).length>0){if(J.push("hooks:"),Z.hooks.PreToolUse&&Z.hooks.PreToolUse.length>0){J.push(" PreToolUse:");for(let X of Z.hooks.PreToolUse){J.push(` - matcher: ${X.matcher}`),J.push(" hooks:");for(let $ of X.hooks)J.push(` - command: "${$.command.replace(/"/g,"\\\"")}"`)}}if(Z.hooks.PostToolUse&&Z.hooks.PostToolUse.length>0){J.push(" PostToolUse:");for(let X of Z.hooks.PostToolUse){J.push(` - matcher: ${X.matcher}`),J.push(" hooks:");for(let $ of X.hooks)J.push(` - command: "${$.command.replace(/"/g,"\\\"")}"`)}}if(Z.hooks.Stop&&Z.hooks.Stop.length>0){J.push(" Stop:");for(let X of Z.hooks.Stop)J.push(` - command: "${X.command.replace(/"/g,"\\\"")}"`)}}return J.push("---"),J.join(`
2379
+ `)}async checkSubfolders(Z){let J={hasScripts:!1,hasReferences:!1,hasAssets:!1};try{let X=B1.join(Z,"scripts"),$=B1.join(Z,"references"),Y=B1.join(Z,"assets"),[Q,W,K]=await Promise.all([r1.stat(X).then((z)=>z.isDirectory()).catch(()=>!1),r1.stat($).then((z)=>z.isDirectory()).catch(()=>!1),r1.stat(Y).then((z)=>z.isDirectory()).catch(()=>!1)]);J.hasScripts=Q,J.hasReferences=W,J.hasAssets=K}catch{}return J}async scanSkillsDir(Z,J,X){let $=[];try{if(!await c4(Z))return $;let Q=await r1.readdir(Z,{withFileTypes:!0});for(let W of Q)if(W.isDirectory()){let K=B1.join(Z,W.name),z=B1.join(K,"SKILL.md");try{let G=await W1(z);if(G===null)continue;let{frontmatter:H}=this.parseFrontmatter(G),V=await this.checkSubfolders(K);$.push({name:H?.name||W.name,description:H?.description||"",scope:J,projectPath:J==="project"?X:void 0,path:K,...V})}catch(G){h5.debug("[Skills] Error processing skill folder",{skillDir:K,error:G})}}}catch(Y){if(Y.code!=="ENOENT")h5.warn("[Skills] Error scanning directory",{dir:Z,error:Y})}return $}async handleListSkillsRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("skills/list",J.clientId,J.requestId);try{let $=this.getSkillsDir(J.scope,J.projectPath),Y=await this.scanSkillsDir($,J.scope,J.projectPath),Q={scope:J.scope,skills:Y,timestamp:Date.now()};await this.publishResponse(X,Q)}catch($){let Y={scope:J.scope,skills:[],timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){h5.error("[Skills] Error handling list skills request",{error:this.formatError(J)})}}async handleReadSkillRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("skills/read",J.clientId);try{let $=this.getSkillsDir(J.scope,J.projectPath),Y=B1.join(J.skillPath,"SKILL.md"),Q=B1.resolve(Y).toLowerCase().replace(/\\/g,"/"),W=B1.resolve($).toLowerCase().replace(/\\/g,"/");if(!Q.startsWith(W))throw h5.warn("[Skills] Path security check failed",{resolvedPath:Q,resolvedBase:W,skillPath:J.skillPath,scope:J.scope}),Error("Invalid skill path");let K=await W1(Y);if(K===null)throw Error("Skill file not found or unreadable");let z=await r1.stat(Y),{frontmatter:G,body:H}=this.parseFrontmatter(K),V=await this.checkSubfolders(J.skillPath),F=B1.basename(J.skillPath),U={skill:{name:G?.name||F,description:G?.description||"",scope:J.scope,projectPath:J.projectPath,path:J.skillPath,...V,license:G?.license,compatibility:G?.compatibility,metadata:G?.metadata,allowedTools:G?.allowedTools,userInvocable:G?.userInvocable,argumentHint:G?.argumentHint,disableModelInvocation:G?.disableModelInvocation,model:G?.model,context:G?.context,agent:G?.agent,hooks:G?.hooks,content:H,rawContent:K,lastModified:z.mtime.toISOString()},timestamp:Date.now()};await this.publishResponse(X,U)}catch($){let Y={timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){h5.error("[Skills] Error handling read skill request",{error:this.formatError(J)})}}async handleWriteSkillRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("skills/write",J.clientId);try{let $=this.getSkillsDir(J.scope,J.projectPath);if(!/^[a-z][a-z0-9-]*$/i.test(J.skillName))throw Error("Invalid skill name");let Y=B1.join($,J.skillName),Q=B1.join(Y,"SKILL.md"),W=B1.resolve(Q),K=B1.resolve($);if(!W.startsWith(K))throw Error("Invalid skill path");await r1.mkdir(Y,{recursive:!0});let G=this.generateFrontmatter({name:J.skillName,description:J.description,license:J.license,compatibility:J.compatibility,metadata:J.metadata,allowedTools:J.allowedTools,userInvocable:J.userInvocable,argumentHint:J.argumentHint,disableModelInvocation:J.disableModelInvocation,model:J.model,context:J.context,agent:J.agent,hooks:J.hooks})+`
2380
2380
 
2381
- `+J.content;await a1.writeFile(Q,G,"utf-8");let H={success:!0,skillName:J.skillName,skillPath:Y,scope:J.scope,timestamp:Date.now()};await this.publishResponse(X,H)}catch($){let Y={success:!1,skillName:J.skillName,scope:J.scope,timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){h5.error("[Skills] Error handling write skill request",{error:this.formatError(J)})}}async handleDeleteSkillRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("skills/delete",J.clientId);try{let $=this.getSkillsDir(J.scope,J.projectPath),Y=B1.resolve(J.skillPath),Q=B1.resolve($);if(!Y.startsWith(Q))throw Error("Invalid skill path");await a1.rm(J.skillPath,{recursive:!0,force:!0});let W={success:!0,skillPath:J.skillPath,scope:J.scope,timestamp:Date.now()};await this.publishResponse(X,W)}catch($){let Y={success:!1,skillPath:J.skillPath,scope:J.scope,timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){h5.error("[Skills] Error handling delete skill request",{error:this.formatError(J)})}}async handleInstallSkillRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("skills/install",J.clientId);try{let $=this.getSkillsDir(J.scope,J.projectPath);if(await a1.mkdir($,{recursive:!0}),J.method==="url"){if(!J.url)throw Error("URL is required for URL installation method");let Y=Bun.spawn(["npx","add-skill",J.url],{cwd:J.scope==="project"?J.projectPath:cQ.homedir(),stdout:"pipe",stderr:"pipe"}),Q=await Y.exited,W=await new Response(Y.stdout).text(),K=await new Response(Y.stderr).text();if(Q!==0)throw Error(`Installation failed: ${K||W||"Unknown error"}`);let H={success:!0,skillName:(W.match(/installed\s+(\S+)/i)||W.match(/(\S+)\s+skill/i))?.[1]||void 0,scope:J.scope,timestamp:Date.now()};await this.publishResponse(X,H)}else if(J.method==="zip"){if(!J.zipData)throw Error("ZIP data is required for ZIP installation method");let Y=Buffer.from(J.zipData,"base64"),Q=B1.join(cQ.tmpdir(),`skill-${Date.now()}.zip`);await a1.writeFile(Q,Y);try{let W=process.platform==="win32",K;if(W){let H=Bun.spawn(["powershell","-Command",`Expand-Archive -Path "${Q}" -DestinationPath "${$}" -Force`],{stdout:"pipe",stderr:"pipe"});if(await H.exited!==0){let D=await new Response(H.stderr).text();throw Error(`ZIP extraction failed: ${D||"Unknown error"}`)}let B=(await a1.readdir($,{withFileTypes:!0})).filter((D)=>D.isDirectory()),U=B[B.length-1];if(U)K=B1.join($,U.name)}else{let H=Bun.spawn(["unzip","-o",Q,"-d",$],{stdout:"pipe",stderr:"pipe"});if(await H.exited!==0){let D=await new Response(H.stderr).text();throw Error(`ZIP extraction failed: ${D||"Unknown error"}`)}let B=(await a1.readdir($,{withFileTypes:!0})).filter((D)=>D.isDirectory()),U=B[B.length-1];if(U)K=B1.join($,U.name)}let G={success:!0,skillName:K?B1.basename(K):void 0,skillPath:K,scope:J.scope,timestamp:Date.now()};await this.publishResponse(X,G)}finally{await a1.unlink(Q).catch(()=>{})}}else throw Error(`Unknown installation method: ${J.method}`)}catch($){let Y={success:!1,scope:J.scope,timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){h5.error("[Skills] Error handling install skill request",{error:this.formatError(J)})}}}var lQ=x();class eH extends p4{name="Hooks Service";get logPrefix(){return"[Hooks]"}getStatus(){return{...super.getStatus()}}registerMQTTHandlers(){this.registerHandler("hooks/list/request",(Z,J)=>{this.handleListHooksRequest(J)}),this.registerHandler("hooks/read/request",(Z,J)=>{this.handleReadHooksConfigRequest(J)}),this.registerHandler("hooks/write/request",(Z,J)=>{this.handleWriteHookRequest(J)}),this.registerHandler("hooks/delete/request",(Z,J)=>{this.handleDeleteHookRequest(J)}),lQ.info("[Hooks] MQTT handlers registered")}getSettingsPath(Z,J){if(Z==="user")return I9.getUserConfigPath("settings");else{if(!J)throw Error("Project path is required for project-scoped hooks");return I9.getProjectConfigPath("settings",J,"settings.local.json")}}async readSettingsFile(Z){return await E9.readConfigOrEmpty(Z)}async writeSettingsFile(Z,J){await E9.writeConfig(Z,J)}async readHooksConfig(Z,J){let X=this.getSettingsPath(Z,J);return(await this.readSettingsFile(X)).hooks||{}}async writeHooksConfig(Z,J,X){let $=this.getSettingsPath(Z,X),Y=await this.readSettingsFile($);if(Y.hooks=J,Object.keys(J).length===0)delete Y.hooks;await this.writeSettingsFile($,Y)}configToEntries(Z,J,X){let $=[];for(let Y of Object.keys(Z)){let Q=Z[Y];if(!Array.isArray(Q))continue;for(let W of Q){let K=[];if(Array.isArray(W.hooks)){for(let z of W.hooks)if(z.type&&!K.includes(z.type))K.push(z.type)}$.push({event:Y,matcher:W.matcher||"",hookCount:Array.isArray(W.hooks)?W.hooks.length:0,hookTypes:K,scope:J,projectPath:J==="project"?X:void 0})}}return $}async handleListHooksRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("hooks/list",J.clientId);try{let $=await this.readHooksConfig(J.scope,J.projectPath),Y=this.configToEntries($,J.scope,J.projectPath),Q={scope:J.scope,hooks:Y,timestamp:Date.now()};await this.publishResponse(X,Q)}catch($){let Y={scope:J.scope,hooks:[],timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){lQ.error("[Hooks] Error handling list hooks request",{error:this.formatError(J)})}}async handleReadHooksConfigRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("hooks/read",J.clientId);try{let Y={config:await this.readHooksConfig(J.scope,J.projectPath),scope:J.scope,timestamp:Date.now()};await this.publishResponse(X,Y)}catch($){let Y={config:{},scope:J.scope,timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){lQ.error("[Hooks] Error handling read hooks config request",{error:this.formatError(J)})}}async handleWriteHookRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("hooks/write",J.clientId);try{let $=await this.readHooksConfig(J.scope,J.projectPath);if(!$[J.event])$[J.event]=[];let Y=$[J.event],Q=Y.findIndex((z)=>z.matcher===J.matcher),W={matcher:J.matcher,hooks:J.hooks};if(Q>=0)Y[Q]=W;else Y.push(W);if(Y.length===0)delete $[J.event];await this.writeHooksConfig(J.scope,$,J.projectPath);let K={success:!0,event:J.event,scope:J.scope,timestamp:Date.now()};await this.publishResponse(X,K)}catch($){let Y={success:!1,event:J.event,scope:J.scope,timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){lQ.error("[Hooks] Error handling write hook request",{error:this.formatError(J)})}}async handleDeleteHookRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("hooks/delete",J.clientId);try{let $=await this.readHooksConfig(J.scope,J.projectPath),Y=$[J.event];if(Y){let Q=Y.length;$[J.event]=Y.filter((H)=>H.matcher!==J.matcher);let W=$[J.event];if(!W||W.length===0)delete $[J.event];await this.writeHooksConfig(J.scope,$,J.projectPath);let K=$[J.event],z=!K||K.length<Q,G={success:z,event:J.event,scope:J.scope,timestamp:Date.now(),error:z?void 0:"Hook matcher not found"};await this.publishResponse(X,G)}else{let Q={success:!1,event:J.event,scope:J.scope,timestamp:Date.now(),error:"Event not found in hooks configuration"};await this.publishResponse(X,Q)}}catch($){let Y={success:!1,event:J.event,scope:J.scope,timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){lQ.error("[Hooks] Error handling delete hook request",{error:this.formatError(J)})}}}import*as U8 from"fs/promises";import*as Q4 from"path";import*as Uj from"os";var{YAML:AZ1}=globalThis.Bun;var ZV=[{name:"default",displayName:"Default",description:"Standard efficient software engineering mode"},{name:"explanatory",displayName:"Explanatory",description:'Provides educational "Insights" while coding'},{name:"learning",displayName:"Learning",description:"Collaborative learn-by-doing with TODO(human) markers"}];var B8=x();class JV extends p4{name="Output Styles Service";get logPrefix(){return"[OutputStyles]"}getStatus(){return{...super.getStatus()}}registerMQTTHandlers(){this.registerHandler("output-styles/list/request",(Z,J)=>{this.handleListStylesRequest(J)}),this.registerHandler("output-styles/read/request",(Z,J)=>{this.handleReadStyleRequest(J)}),this.registerHandler("output-styles/write/request",(Z,J)=>{this.handleWriteStyleRequest(J)}),this.registerHandler("output-styles/delete/request",(Z,J)=>{this.handleDeleteStyleRequest(J)}),this.registerHandler("output-styles/set-active/request",(Z,J)=>{this.handleSetActiveStyleRequest(J)}),B8.info("[OutputStyles] MQTT handlers registered")}getOutputStylesDir(Z,J){if(Z==="user")return Q4.join(Uj.homedir(),".claude","output-styles");else{if(!J)throw Error("Project path is required for project-scoped output styles");return Q4.join(J,".claude","output-styles")}}getSettingsPath(Z,J){if(Z==="user")return Q4.join(Uj.homedir(),".claude","settings.json");else{if(!J)throw Error("Project path is required for project-scoped settings");return Q4.join(J,".claude","settings.local.json")}}parseFrontmatter(Z){let J=/^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/,X=Z.match(J);if(!X)return{body:Z};let $=X[1]||"",Y=X[2]||"";try{let Q=AZ1.parse($);if(!Q||typeof Q!=="object")return{body:Y};let W={};if(Q.name)W.name=String(Q.name);if(Q.description)W.description=String(Q.description);if(Q["keep-coding-instructions"]!==void 0)W.keepCodingInstructions=Boolean(Q["keep-coding-instructions"]);return{frontmatter:Object.keys(W).length>0?W:void 0,body:Y}}catch(Q){return B8.warn("[OutputStyles] Failed to parse frontmatter",{error:Q}),{body:Z}}}generateFrontmatter(Z){let J=["---"];if(J.push(`name: "${Z.name.replace(/"/g,"\\\"")}"`),J.push(`description: "${Z.description.replace(/"/g,"\\\"")}"`),Z.keepCodingInstructions!==void 0)J.push(`keep-coding-instructions: ${Z.keepCodingInstructions}`);return J.push("---"),J.join(`
2381
+ `+J.content;await r1.writeFile(Q,G,"utf-8");let H={success:!0,skillName:J.skillName,skillPath:Y,scope:J.scope,timestamp:Date.now()};await this.publishResponse(X,H)}catch($){let Y={success:!1,skillName:J.skillName,scope:J.scope,timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){h5.error("[Skills] Error handling write skill request",{error:this.formatError(J)})}}async handleDeleteSkillRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("skills/delete",J.clientId);try{let $=this.getSkillsDir(J.scope,J.projectPath),Y=B1.resolve(J.skillPath),Q=B1.resolve($);if(!Y.startsWith(Q))throw Error("Invalid skill path");await r1.rm(J.skillPath,{recursive:!0,force:!0});let W={success:!0,skillPath:J.skillPath,scope:J.scope,timestamp:Date.now()};await this.publishResponse(X,W)}catch($){let Y={success:!1,skillPath:J.skillPath,scope:J.scope,timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){h5.error("[Skills] Error handling delete skill request",{error:this.formatError(J)})}}async handleInstallSkillRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("skills/install",J.clientId);try{let $=this.getSkillsDir(J.scope,J.projectPath);if(await r1.mkdir($,{recursive:!0}),J.method==="url"){if(!J.url)throw Error("URL is required for URL installation method");let Y=Bun.spawn(["npx","add-skill",J.url],{cwd:J.scope==="project"?J.projectPath:cQ.homedir(),stdout:"pipe",stderr:"pipe"}),Q=await Y.exited,W=await new Response(Y.stdout).text(),K=await new Response(Y.stderr).text();if(Q!==0)throw Error(`Installation failed: ${K||W||"Unknown error"}`);let H={success:!0,skillName:(W.match(/installed\s+(\S+)/i)||W.match(/(\S+)\s+skill/i))?.[1]||void 0,scope:J.scope,timestamp:Date.now()};await this.publishResponse(X,H)}else if(J.method==="zip"){if(!J.zipData)throw Error("ZIP data is required for ZIP installation method");let Y=Buffer.from(J.zipData,"base64"),Q=B1.join(cQ.tmpdir(),`skill-${Date.now()}.zip`);await r1.writeFile(Q,Y);try{let W=process.platform==="win32",K;if(W){let H=Bun.spawn(["powershell","-Command",`Expand-Archive -Path "${Q}" -DestinationPath "${$}" -Force`],{stdout:"pipe",stderr:"pipe"});if(await H.exited!==0){let D=await new Response(H.stderr).text();throw Error(`ZIP extraction failed: ${D||"Unknown error"}`)}let B=(await r1.readdir($,{withFileTypes:!0})).filter((D)=>D.isDirectory()),U=B[B.length-1];if(U)K=B1.join($,U.name)}else{let H=Bun.spawn(["unzip","-o",Q,"-d",$],{stdout:"pipe",stderr:"pipe"});if(await H.exited!==0){let D=await new Response(H.stderr).text();throw Error(`ZIP extraction failed: ${D||"Unknown error"}`)}let B=(await r1.readdir($,{withFileTypes:!0})).filter((D)=>D.isDirectory()),U=B[B.length-1];if(U)K=B1.join($,U.name)}let G={success:!0,skillName:K?B1.basename(K):void 0,skillPath:K,scope:J.scope,timestamp:Date.now()};await this.publishResponse(X,G)}finally{await r1.unlink(Q).catch(()=>{})}}else throw Error(`Unknown installation method: ${J.method}`)}catch($){let Y={success:!1,scope:J.scope,timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){h5.error("[Skills] Error handling install skill request",{error:this.formatError(J)})}}}var lQ=x();class eH extends p4{name="Hooks Service";get logPrefix(){return"[Hooks]"}getStatus(){return{...super.getStatus()}}registerMQTTHandlers(){this.registerHandler("hooks/list/request",(Z,J)=>{this.handleListHooksRequest(J)}),this.registerHandler("hooks/read/request",(Z,J)=>{this.handleReadHooksConfigRequest(J)}),this.registerHandler("hooks/write/request",(Z,J)=>{this.handleWriteHookRequest(J)}),this.registerHandler("hooks/delete/request",(Z,J)=>{this.handleDeleteHookRequest(J)}),lQ.info("[Hooks] MQTT handlers registered")}getSettingsPath(Z,J){if(Z==="user")return I9.getUserConfigPath("settings");else{if(!J)throw Error("Project path is required for project-scoped hooks");return I9.getProjectConfigPath("settings",J,"settings.local.json")}}async readSettingsFile(Z){return await E9.readConfigOrEmpty(Z)}async writeSettingsFile(Z,J){await E9.writeConfig(Z,J)}async readHooksConfig(Z,J){let X=this.getSettingsPath(Z,J);return(await this.readSettingsFile(X)).hooks||{}}async writeHooksConfig(Z,J,X){let $=this.getSettingsPath(Z,X),Y=await this.readSettingsFile($);if(Y.hooks=J,Object.keys(J).length===0)delete Y.hooks;await this.writeSettingsFile($,Y)}configToEntries(Z,J,X){let $=[];for(let Y of Object.keys(Z)){let Q=Z[Y];if(!Array.isArray(Q))continue;for(let W of Q){let K=[];if(Array.isArray(W.hooks)){for(let z of W.hooks)if(z.type&&!K.includes(z.type))K.push(z.type)}$.push({event:Y,matcher:W.matcher||"",hookCount:Array.isArray(W.hooks)?W.hooks.length:0,hookTypes:K,scope:J,projectPath:J==="project"?X:void 0})}}return $}async handleListHooksRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("hooks/list",J.clientId);try{let $=await this.readHooksConfig(J.scope,J.projectPath),Y=this.configToEntries($,J.scope,J.projectPath),Q={scope:J.scope,hooks:Y,timestamp:Date.now()};await this.publishResponse(X,Q)}catch($){let Y={scope:J.scope,hooks:[],timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){lQ.error("[Hooks] Error handling list hooks request",{error:this.formatError(J)})}}async handleReadHooksConfigRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("hooks/read",J.clientId);try{let Y={config:await this.readHooksConfig(J.scope,J.projectPath),scope:J.scope,timestamp:Date.now()};await this.publishResponse(X,Y)}catch($){let Y={config:{},scope:J.scope,timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){lQ.error("[Hooks] Error handling read hooks config request",{error:this.formatError(J)})}}async handleWriteHookRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("hooks/write",J.clientId);try{let $=await this.readHooksConfig(J.scope,J.projectPath);if(!$[J.event])$[J.event]=[];let Y=$[J.event],Q=Y.findIndex((z)=>z.matcher===J.matcher),W={matcher:J.matcher,hooks:J.hooks};if(Q>=0)Y[Q]=W;else Y.push(W);if(Y.length===0)delete $[J.event];await this.writeHooksConfig(J.scope,$,J.projectPath);let K={success:!0,event:J.event,scope:J.scope,timestamp:Date.now()};await this.publishResponse(X,K)}catch($){let Y={success:!1,event:J.event,scope:J.scope,timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){lQ.error("[Hooks] Error handling write hook request",{error:this.formatError(J)})}}async handleDeleteHookRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("hooks/delete",J.clientId);try{let $=await this.readHooksConfig(J.scope,J.projectPath),Y=$[J.event];if(Y){let Q=Y.length;$[J.event]=Y.filter((H)=>H.matcher!==J.matcher);let W=$[J.event];if(!W||W.length===0)delete $[J.event];await this.writeHooksConfig(J.scope,$,J.projectPath);let K=$[J.event],z=!K||K.length<Q,G={success:z,event:J.event,scope:J.scope,timestamp:Date.now(),error:z?void 0:"Hook matcher not found"};await this.publishResponse(X,G)}else{let Q={success:!1,event:J.event,scope:J.scope,timestamp:Date.now(),error:"Event not found in hooks configuration"};await this.publishResponse(X,Q)}}catch($){let Y={success:!1,event:J.event,scope:J.scope,timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){lQ.error("[Hooks] Error handling delete hook request",{error:this.formatError(J)})}}}import*as U8 from"fs/promises";import*as Q4 from"path";import*as Uj from"os";var{YAML:AZ1}=globalThis.Bun;var ZV=[{name:"default",displayName:"Default",description:"Standard efficient software engineering mode"},{name:"explanatory",displayName:"Explanatory",description:'Provides educational "Insights" while coding'},{name:"learning",displayName:"Learning",description:"Collaborative learn-by-doing with TODO(human) markers"}];var B8=x();class JV extends p4{name="Output Styles Service";get logPrefix(){return"[OutputStyles]"}getStatus(){return{...super.getStatus()}}registerMQTTHandlers(){this.registerHandler("output-styles/list/request",(Z,J)=>{this.handleListStylesRequest(J)}),this.registerHandler("output-styles/read/request",(Z,J)=>{this.handleReadStyleRequest(J)}),this.registerHandler("output-styles/write/request",(Z,J)=>{this.handleWriteStyleRequest(J)}),this.registerHandler("output-styles/delete/request",(Z,J)=>{this.handleDeleteStyleRequest(J)}),this.registerHandler("output-styles/set-active/request",(Z,J)=>{this.handleSetActiveStyleRequest(J)}),B8.info("[OutputStyles] MQTT handlers registered")}getOutputStylesDir(Z,J){if(Z==="user")return Q4.join(Uj.homedir(),".claude","output-styles");else{if(!J)throw Error("Project path is required for project-scoped output styles");return Q4.join(J,".claude","output-styles")}}getSettingsPath(Z,J){if(Z==="user")return Q4.join(Uj.homedir(),".claude","settings.json");else{if(!J)throw Error("Project path is required for project-scoped settings");return Q4.join(J,".claude","settings.local.json")}}parseFrontmatter(Z){let J=/^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/,X=Z.match(J);if(!X)return{body:Z};let $=X[1]||"",Y=X[2]||"";try{let Q=AZ1.parse($);if(!Q||typeof Q!=="object")return{body:Y};let W={};if(Q.name)W.name=String(Q.name);if(Q.description)W.description=String(Q.description);if(Q["keep-coding-instructions"]!==void 0)W.keepCodingInstructions=Boolean(Q["keep-coding-instructions"]);return{frontmatter:Object.keys(W).length>0?W:void 0,body:Y}}catch(Q){return B8.warn("[OutputStyles] Failed to parse frontmatter",{error:Q}),{body:Z}}}generateFrontmatter(Z){let J=["---"];if(J.push(`name: "${Z.name.replace(/"/g,"\\\"")}"`),J.push(`description: "${Z.description.replace(/"/g,"\\\"")}"`),Z.keepCodingInstructions!==void 0)J.push(`keep-coding-instructions: ${Z.keepCodingInstructions}`);return J.push("---"),J.join(`
2382
2382
  `)}async readActiveStyle(Z,J){try{let X=this.getSettingsPath(Z,J),$=await W1(X);if(!$)return;return JSON.parse($).outputStyle||void 0}catch(X){B8.debug("[OutputStyles] Failed to read active style",{error:X});return}}async setActiveStyle(Z,J,X){let $=this.getSettingsPath(Z,X);try{let Y={},Q=await W1($);if(Q)try{Y=JSON.parse(Q)}catch{Y={}}if(J==="default"||J==="")delete Y.outputStyle;else Y.outputStyle=J;let W=Q4.dirname($);await U8.mkdir(W,{recursive:!0}),await U8.writeFile($,JSON.stringify(Y,null,2),"utf-8")}catch(Y){throw B8.error("[OutputStyles] Failed to set active style",{error:Y}),Y}}async scanOutputStylesDir(Z,J,X,$){let Y=[];try{if(!await c4(Z))return Y;let W=await U8.readdir(Z,{withFileTypes:!0});for(let K of W)if(K.isFile()&&K.name.endsWith(".md")){let z=Q4.join(Z,K.name),G=K.name.replace(/\.md$/,"");try{let H=await W1(z);if(H===null)continue;let{frontmatter:V}=this.parseFrontmatter(H);Y.push({name:G,displayName:V?.name||G,description:V?.description||"",scope:J,projectPath:J==="project"?$:void 0,isActive:X===G})}catch(H){B8.debug("[OutputStyles] Error processing style file",{stylePath:z,error:H})}}}catch(Q){if(Q.code!=="ENOENT")B8.warn("[OutputStyles] Error scanning directory",{dir:Z,error:Q})}return Y}getBuiltinStyleEntries(Z){return ZV.map((J)=>({name:J.name,displayName:J.displayName,description:J.description,scope:"builtin",isActive:Z===J.name||J.name==="default"&&!Z}))}async handleListStylesRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("output-styles/list",J.clientId,J.requestId);try{let $=this.getOutputStylesDir(J.scope,J.projectPath),Y=await this.readActiveStyle(J.scope,J.projectPath),Q=await this.scanOutputStylesDir($,J.scope,Y,J.projectPath),W=this.getBuiltinStyleEntries(Y),K={scope:J.scope,styles:Q,builtinStyles:W,activeStyle:Y,timestamp:Date.now()};await this.publishResponse(X,K)}catch($){let Y={scope:J.scope,styles:[],builtinStyles:this.getBuiltinStyleEntries(void 0),timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){B8.error("[OutputStyles] Error handling list styles request",{error:this.formatError(J)})}}async handleReadStyleRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("output-styles/read",J.clientId);try{if(J.scope==="builtin"){let U=ZV.find((w)=>w.name===J.styleName);if(!U)throw Error("Built-in style not found");let D=await this.readActiveStyle("user"),O={style:{name:U.name,displayName:U.displayName,description:U.description,scope:"builtin",isActive:D===U.name||U.name==="default"&&!D,content:`# ${U.displayName}
2383
2383
 
2384
2384
  ${U.description}
2385
2385
 
2386
2386
  This is a built-in style. Built-in styles cannot be edited.`,rawContent:"",keepCodingInstructions:!1,lastModified:new Date().toISOString()},timestamp:Date.now()};await this.publishResponse(X,O),this.requestsHandled++;return}let $=this.getOutputStylesDir(J.scope,J.projectPath),Y=Q4.join($,`${J.styleName}.md`),Q=Q4.resolve(Y).toLowerCase().replace(/\\/g,"/"),W=Q4.resolve($).toLowerCase().replace(/\\/g,"/");if(!Q.startsWith(W))throw B8.warn("[OutputStyles] Path security check failed",{resolvedPath:Q,resolvedBase:W,styleName:J.styleName,scope:J.scope}),Error("Invalid style path");let K=await W1(Y);if(K===null)throw Error("Style file not found or unreadable");let z=await U8.stat(Y),{frontmatter:G,body:H}=this.parseFrontmatter(K),V=await this.readActiveStyle(J.scope,J.projectPath),B={style:{name:J.styleName,displayName:G?.name||J.styleName,description:G?.description||"",scope:J.scope,projectPath:J.projectPath,isActive:V===J.styleName,content:H,rawContent:K,keepCodingInstructions:G?.keepCodingInstructions??!1,lastModified:z.mtime.toISOString()},timestamp:Date.now()};await this.publishResponse(X,B)}catch($){let Y={timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){B8.error("[OutputStyles] Error handling read style request",{error:this.formatError(J)})}}async handleWriteStyleRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("output-styles/write",J.clientId);try{let $=this.getOutputStylesDir(J.scope,J.projectPath);if(!/^[a-z][a-z0-9_-]*$/i.test(J.styleName))throw Error("Invalid style name. Use only letters, numbers, hyphens, and underscores.");let Y=Q4.join($,`${J.styleName}.md`),Q=Q4.resolve(Y),W=Q4.resolve($);if(!Q.startsWith(W))throw Error("Invalid style path");await U8.mkdir($,{recursive:!0});let z=this.generateFrontmatter({name:J.displayName,description:J.description,keepCodingInstructions:J.keepCodingInstructions})+`
2387
2387
 
2388
- `+J.content;await U8.writeFile(Y,z,"utf-8");let G={success:!0,styleName:J.styleName,scope:J.scope,timestamp:Date.now()};await this.publishResponse(X,G)}catch($){let Y={success:!1,styleName:J.styleName,scope:J.scope,timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){B8.error("[OutputStyles] Error handling write style request",{error:this.formatError(J)})}}async handleDeleteStyleRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("output-styles/delete",J.clientId);try{let $=this.getOutputStylesDir(J.scope,J.projectPath),Y=Q4.join($,`${J.styleName}.md`),Q=Q4.resolve(Y),W=Q4.resolve($);if(!Q.startsWith(W))throw Error("Invalid style path");if(await U8.unlink(Y),await this.readActiveStyle(J.scope,J.projectPath)===J.styleName)await this.setActiveStyle(J.scope,"default",J.projectPath);let z={success:!0,styleName:J.styleName,scope:J.scope,timestamp:Date.now()};await this.publishResponse(X,z)}catch($){let Y={success:!1,styleName:J.styleName,scope:J.scope,timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){B8.error("[OutputStyles] Error handling delete style request",{error:this.formatError(J)})}}async handleSetActiveStyleRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("output-styles/set-active",J.clientId);try{await this.setActiveStyle(J.scope,J.styleName,J.projectPath);let $={success:!0,styleName:J.styleName,scope:J.scope,timestamp:Date.now()};await this.publishResponse(X,$)}catch($){let Y={success:!1,styleName:J.styleName,scope:J.scope,timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){B8.error("[OutputStyles] Error handling set active style request",{error:this.formatError(J)})}}}import*as W4 from"fs/promises";import*as v1 from"path";var r1=x(),pQ={name:"claude-plugins-official",source:{source:"github",repo:"anthropics/claude-plugins-official"}};class XV extends p4{name="Plugins Service";get logPrefix(){return"[Plugins]"}getStatus(){return{...super.getStatus()}}async onStart(){await this.ensureDirectories()}registerMQTTHandlers(){this.registerHandler("plugins/marketplaces/list/request",(Z,J)=>{this.handleListMarketplacesRequest(J)}),this.registerHandler("plugins/list/request",(Z,J)=>{this.handleListPluginsRequest(J)}),this.registerHandler("plugins/read/request",(Z,J)=>{this.handleReadPluginRequest(J)}),this.registerHandler("plugins/install/request",(Z,J)=>{this.handleInstallPluginRequest(J)}),this.registerHandler("plugins/uninstall/request",(Z,J)=>{this.handleUninstallPluginRequest(J)}),this.registerHandler("plugins/toggle/request",(Z,J)=>{this.handleTogglePluginRequest(J)}),this.registerHandler("plugins/marketplace/add/request",(Z,J)=>{this.handleAddMarketplaceRequest(J)}),this.registerHandler("plugins/marketplace/remove/request",(Z,J)=>{this.handleRemoveMarketplaceRequest(J)}),this.registerHandler("plugins/marketplace/refresh/request",(Z,J)=>{this.handleRefreshMarketplaceRequest(J)}),r1.info("[Plugins] MQTT handlers registered")}getPluginsDir(){return I9.getPluginsDir("user")}getMarketplaceCacheDir(){return I9.getMarketplaceCacheDir()}getSettingsPath(){return I9.getUserConfigPath("settings")}getInstalledPluginsJsonPath(){return v1.join(this.getPluginsDir(),"installed_plugins.json")}getPluginCacheDir(){return v1.join(this.getPluginsDir(),"cache")}async ensureDirectories(){let Z=[this.getPluginsDir(),this.getPluginCacheDir(),this.getMarketplaceCacheDir()];for(let J of Z)await W4.mkdir(J,{recursive:!0})}async readSettings(){return await E9.readConfigOrEmpty(this.getSettingsPath())}async writeSettings(Z){await E9.writeConfig(this.getSettingsPath(),Z)}async getEnabledPlugins(){return(await this.readSettings()).enabledPlugins||{}}async setPluginEnabled(Z,J){let X=await this.readSettings();if(!X.enabledPlugins)X.enabledPlugins={};X.enabledPlugins[Z]=J,await this.writeSettings(X)}async getKnownMarketplaces(){return(await this.readSettings()).extraKnownMarketplaces||{}}async addKnownMarketplace(Z,J){let X=await this.readSettings();if(!X.extraKnownMarketplaces)X.extraKnownMarketplaces={};X.extraKnownMarketplaces[Z]=J,await this.writeSettings(X)}async removeKnownMarketplace(Z){let J=await this.readSettings();if(J.extraKnownMarketplaces)delete J.extraKnownMarketplaces[Z],await this.writeSettings(J)}async readInstalledPluginsJson(){let Z=this.getInstalledPluginsJsonPath(),J=await W1(Z);if(!J)return{version:2,plugins:{}};try{let X=JSON.parse(J);return{version:X.version||2,plugins:X.plugins||{}}}catch(X){return r1.warn("[Plugins] Failed to parse installed_plugins.json, returning empty",X),{version:2,plugins:{}}}}async writeInstalledPluginsJson(Z){let J=this.getInstalledPluginsJsonPath();await W4.writeFile(J,JSON.stringify(Z,null,2),"utf-8")}async addInstalledPluginRecord(Z,J){let X=await this.readInstalledPluginsJson();if(!X.plugins[Z])X.plugins[Z]=[];let $=X.plugins[Z].findIndex((Y)=>Y.scope===J.scope);if($>=0)X.plugins[Z][$]=J;else X.plugins[Z].push(J);await this.writeInstalledPluginsJson(X)}async removeInstalledPluginRecord(Z,J){let X=await this.readInstalledPluginsJson();if(!X.plugins[Z])return;if(J){if(X.plugins[Z]=X.plugins[Z].filter(($)=>$.scope!==J),X.plugins[Z].length===0)delete X.plugins[Z]}else delete X.plugins[Z];await this.writeInstalledPluginsJson(X)}async getInstalledPluginRecord(Z){let X=(await this.readInstalledPluginsJson()).plugins[Z];if(!X||X.length===0)return null;return X[0]??null}getMarketplaceCachePath(Z){return v1.join(this.getMarketplaceCacheDir(),Z)}async fetchMarketplace(Z,J){let X=this.getMarketplaceCachePath(Z);try{if(typeof J==="object"&&J.source==="github"){let Q=`https://github.com/${J.repo}.git`,W=J.ref||"main";if(await c4(X)){let{$:K}=awaitPromise.resolve(globalThis.Bun);await K`git -C ${X} fetch origin ${W}`.quiet(),await K`git -C ${X} reset --hard origin/${W}`.quiet()}else{let{$:K}=awaitPromise.resolve(globalThis.Bun);await K`git clone --depth 1 --branch ${W} ${Q} ${X}`.quiet()}}else if(typeof J==="object"&&J.source==="url"){let Q=J.url,W=J.ref||"main";if(await c4(X)){let{$:K}=awaitPromise.resolve(globalThis.Bun);await K`git -C ${X} fetch origin ${W}`.quiet(),await K`git -C ${X} reset --hard origin/${W}`.quiet()}else{let{$:K}=awaitPromise.resolve(globalThis.Bun);await K`git clone --depth 1 --branch ${W} ${Q} ${X}`.quiet()}}else if(typeof J==="string")return r1.warn("[Plugins] Relative path source not supported for marketplaces"),null;let $=v1.join(X,".claude-plugin","marketplace.json"),Y=await W1($);if(!Y){let Q=v1.join(X,"marketplace.json"),W=await W1(Q);if(W)return JSON.parse(W);return r1.warn(`[Plugins] No marketplace.json found for ${Z}`),null}return JSON.parse(Y)}catch($){return r1.error(`[Plugins] Failed to fetch marketplace ${Z}`,$),null}}async parseMarketplace(Z){let J=this.getMarketplaceCachePath(Z),X=v1.join(J,".claude-plugin","marketplace.json"),$=await W1(X);if(!$)X=v1.join(J,"marketplace.json"),$=await W1(X);if(!$)return null;try{return JSON.parse($)}catch(Y){return r1.error(`[Plugins] Failed to parse marketplace.json for ${Z}`,Y),null}}async marketplacePluginToEntry(Z,J,X,$){let Y=`${Z.name}@${J}`;return{name:Z.name,displayName:Z.name,description:Z.description||"",version:Z.version,author:Z.author?.name,category:Z.category,tags:Z.tags,marketplaceName:J,isInstalled:$.has(Y),isEnabled:X[Y]??!1,source:Z.source}}async getAllMarketplaces(){let Z=await this.getKnownMarketplaces(),J=[{name:pQ.name,source:pQ.source,isOfficial:!0}];for(let[X,$]of Object.entries(Z))J.push({name:X,source:$,isOfficial:!1});return J}async getInstalledPlugins(){let Z=new Set,J=await this.readInstalledPluginsJson();for(let[X,$]of Object.entries(J.plugins)){if(!$||$.length===0)continue;for(let Y of $)if(Y.installPath){if(await c4(Y.installPath)){Z.add(X);break}}}return Z}getPluginInstallPath(Z,J,X="1.0.0"){return v1.join(this.getPluginCacheDir(),J,Z,X)}async getPluginInstallPathFromRecord(Z,J){let X=`${Z}@${J}`;return(await this.getInstalledPluginRecord(X))?.installPath||null}async getGitCommitSha(Z){try{let{$:J}=awaitPromise.resolve(globalThis.Bun);return(await J`git -C ${Z} rev-parse HEAD`.quiet()).stdout.toString().trim()||void 0}catch{return}}async installPluginFromMarketplace(Z,J,X="user"){try{let $=await this.parseMarketplace(J);if(!$)return{success:!1,error:"Marketplace not found or not cached"};let Y=$.plugins.find((F)=>F.name===Z);if(!Y)return{success:!1,error:"Plugin not found in marketplace"};let Q=Y.version||"1.0.0",W=this.getPluginInstallPath(Z,J,Q),K=this.getMarketplaceCachePath(J),z=`${Z}@${J}`;await W4.mkdir(v1.dirname(W),{recursive:!0});let G;if(typeof Y.source==="string"){let F=v1.join(K,Y.source);await W4.rm(W,{recursive:!0,force:!0}),await W4.cp(F,W,{recursive:!0}),G=await this.getGitCommitSha(K)}else if(Y.source.source==="github"){let F=`https://github.com/${Y.source.repo}.git`,B=Y.source.ref||"main",{$:U}=awaitPromise.resolve(globalThis.Bun);await W4.rm(W,{recursive:!0,force:!0}),await U`git clone --depth 1 --branch ${B} ${F} ${W}`.quiet(),G=await this.getGitCommitSha(W)}else if(Y.source.source==="url"){let F=Y.source.url,B=Y.source.ref||"main",{$:U}=awaitPromise.resolve(globalThis.Bun);await W4.rm(W,{recursive:!0,force:!0}),await U`git clone --depth 1 --branch ${B} ${F} ${W}`.quiet(),G=await this.getGitCommitSha(W)}else return{success:!1,error:"Unknown plugin source type"};let H=new Date().toISOString(),V={scope:X,installPath:W,version:Q,installedAt:H,lastUpdated:H,gitCommitSha:G};return await this.addInstalledPluginRecord(z,V),await this.setPluginEnabled(z,!0),r1.info(`[Plugins] Installed ${z} to ${W}`),{success:!0}}catch($){return r1.error(`[Plugins] Failed to install plugin ${Z}@${J}`,$),{success:!1,error:$ instanceof Error?$.message:"Unknown error"}}}async uninstallPlugin(Z,J,X){try{let $=`${Z}@${J}`,Y=await this.getInstalledPluginRecord($);if(!Y)return{success:!1,error:"Plugin not installed"};if(Y.installPath&&await c4(Y.installPath))await W4.rm(Y.installPath,{recursive:!0,force:!0});await this.removeInstalledPluginRecord($,X);let Q=await this.readSettings();if(Q.enabledPlugins&&Q.enabledPlugins[$]!==void 0)delete Q.enabledPlugins[$],await this.writeSettings(Q);return r1.info(`[Plugins] Uninstalled ${$}`),{success:!0}}catch($){return r1.error(`[Plugins] Failed to uninstall plugin ${Z}@${J}`,$),{success:!1,error:$ instanceof Error?$.message:"Unknown error"}}}async readPluginManifest(Z){let J=v1.join(Z,".claude-plugin","plugin.json"),X=await W1(J);if(!X)return null;try{return JSON.parse(X)}catch($){return null}}async getPluginDetail(Z,J){let X=await this.getEnabledPlugins(),$=await this.getInstalledPlugins(),Y=`${Z}@${J}`,W=(await this.parseMarketplace(J))?.plugins.find((O)=>O.name===Z),K=$.has(Y),G=(K?await this.getInstalledPluginRecord(Y):null)?.installPath,H=K&&G?await this.readPluginManifest(G):null,V=!1,F=!1,B=!1,U=!1,D=!1,_=!1;if(K&&G)V=await c4(v1.join(G,"commands")),F=await c4(v1.join(G,"skills")),B=await c4(v1.join(G,"agents")),U=await c4(v1.join(G,"hooks")),D=await c4(v1.join(G,".mcp.json"))||await W4.access(v1.join(G,".mcp.json")).then(()=>!0).catch(()=>!1),_=await c4(v1.join(G,".lsp.json"))||await W4.access(v1.join(G,".lsp.json")).then(()=>!0).catch(()=>!1);return{name:Z,displayName:H?.name||W?.name||Z,description:H?.description||W?.description||"",version:H?.version||W?.version,author:H?.author?.name||W?.author?.name,category:W?.category,tags:W?.tags,marketplaceName:J,isInstalled:K,isEnabled:X[Y]??!1,source:W?.source||Z,homepage:H?.homepage,repository:H?.repository,license:H?.license,hasCommands:V,hasSkills:F,hasAgents:B,hasHooks:U,hasMcpServers:D,hasLspServers:_,installPath:K?G:void 0}}async handleListMarketplacesRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("plugins/marketplaces/list",J.clientId);try{let $=await this.getAllMarketplaces(),Y=[];for(let{name:W,source:K,isOfficial:z}of $){let G=await this.parseMarketplace(W),H=0,V,F="Unknown";if(G)H=G.plugins.length,V=G.description,F=G.owner.name;Y.push({name:W,description:V,owner:F,source:K,pluginCount:H,isOfficial:z})}let Q={marketplaces:Y,timestamp:Date.now()};await this.publishResponse(X,Q)}catch($){let Y={marketplaces:[],timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){r1.error("[Plugins] Error handling list marketplaces request",{error:this.formatError(J)})}}async handleListPluginsRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("plugins/list",J.clientId);try{let $=await this.getEnabledPlugins(),Y=await this.getInstalledPlugins(),Q=[];if(J.scope==="installed")for(let K of Y){let z=K.split("@"),G=z[0],H=z[1];if(!G||!H)continue;let V=await this.getPluginDetail(G,H);if(V)Q.push({name:V.name,displayName:V.displayName,description:V.description,version:V.version,author:V.author,category:V.category,tags:V.tags,marketplaceName:H,isInstalled:!0,isEnabled:V.isEnabled,source:V.source})}else if(J.scope==="marketplace"){let K=await this.getAllMarketplaces(),z=J.marketplaceName?K.filter((G)=>G.name===J.marketplaceName):K;for(let{name:G}of z){let H=await this.parseMarketplace(G);if(!H)continue;for(let V of H.plugins){let F=await this.marketplacePluginToEntry(V,G,$,Y);Q.push(F)}}}let W={plugins:Q,marketplaceName:J.marketplaceName,timestamp:Date.now()};await this.publishResponse(X,W)}catch($){let Y={plugins:[],timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){r1.error("[Plugins] Error handling list plugins request",{error:this.formatError(J)})}}async handleReadPluginRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("plugins/read",J.clientId);try{let Y={plugin:await this.getPluginDetail(J.pluginName,J.marketplaceName)||void 0,timestamp:Date.now()};await this.publishResponse(X,Y)}catch($){let Y={timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){r1.error("[Plugins] Error handling read plugin request",{error:this.formatError(J)})}}async handleInstallPluginRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("plugins/install",J.clientId);try{let $=await this.installPluginFromMarketplace(J.pluginName,J.marketplaceName),Y={success:$.success,pluginName:J.pluginName,marketplaceName:J.marketplaceName,timestamp:Date.now(),error:$.error};await this.publishResponse(X,Y)}catch($){let Y={success:!1,pluginName:J.pluginName,marketplaceName:J.marketplaceName,timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){r1.error("[Plugins] Error handling install plugin request",{error:this.formatError(J)})}}async handleUninstallPluginRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("plugins/uninstall",J.clientId);try{let $=await this.uninstallPlugin(J.pluginName,J.marketplaceName),Y={success:$.success,pluginName:J.pluginName,marketplaceName:J.marketplaceName,timestamp:Date.now(),error:$.error};await this.publishResponse(X,Y)}catch($){let Y={success:!1,pluginName:J.pluginName,marketplaceName:J.marketplaceName,timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){r1.error("[Plugins] Error handling uninstall plugin request",{error:this.formatError(J)})}}async handleTogglePluginRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("plugins/toggle",J.clientId);try{let $=`${J.pluginName}@${J.marketplaceName}`;await this.setPluginEnabled($,J.enabled);let Y={success:!0,pluginName:J.pluginName,marketplaceName:J.marketplaceName,enabled:J.enabled,timestamp:Date.now()};await this.publishResponse(X,Y)}catch($){let Y={success:!1,pluginName:J.pluginName,marketplaceName:J.marketplaceName,enabled:J.enabled,timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){r1.error("[Plugins] Error handling toggle plugin request",{error:this.formatError(J)})}}async handleAddMarketplaceRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("plugins/marketplace/add",J.clientId);try{let $="temp_"+Date.now();if(typeof J.source==="object"&&J.source.source==="github")$=J.source.repo.split("/").pop()||$;let Y=await this.fetchMarketplace($,J.source);if(!Y){let z={success:!1,timestamp:Date.now(),error:"Failed to fetch or parse marketplace"};await this.publishResponse(X,z);return}let Q=Y.name;if($!==Q){let z=this.getMarketplaceCachePath($),G=this.getMarketplaceCachePath(Q);await W4.rm(G,{recursive:!0,force:!0}),await W4.rename(z,G)}await this.addKnownMarketplace(Q,J.source);let K={success:!0,marketplace:{name:Q,description:Y.description,owner:Y.owner.name,source:J.source,pluginCount:Y.plugins.length,isOfficial:!1},timestamp:Date.now()};await this.publishResponse(X,K)}catch($){let Y={success:!1,timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){r1.error("[Plugins] Error handling add marketplace request",{error:this.formatError(J)})}}async handleRemoveMarketplaceRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("plugins/marketplace/remove",J.clientId);try{if(J.marketplaceName===pQ.name){let Y={success:!1,marketplaceName:J.marketplaceName,timestamp:Date.now(),error:"Cannot remove official marketplace"};await this.publishResponse(X,Y);return}await this.removeKnownMarketplace(J.marketplaceName);let $={success:!0,marketplaceName:J.marketplaceName,timestamp:Date.now()};await this.publishResponse(X,$)}catch($){let Y={success:!1,marketplaceName:J.marketplaceName,timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){r1.error("[Plugins] Error handling remove marketplace request",{error:this.formatError(J)})}}async handleRefreshMarketplaceRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("plugins/marketplace/refresh",J.clientId);try{let $=null;if(J.marketplaceName===pQ.name)$=pQ.source;else $=(await this.getKnownMarketplaces())[J.marketplaceName]||null;if(!$){let W={success:!1,marketplaceName:J.marketplaceName,pluginCount:0,timestamp:Date.now(),error:"Marketplace not found"};await this.publishResponse(X,W);return}let Y=await this.fetchMarketplace(J.marketplaceName,$);if(!Y){let W={success:!1,marketplaceName:J.marketplaceName,pluginCount:0,timestamp:Date.now(),error:"Failed to fetch marketplace"};await this.publishResponse(X,W);return}let Q={success:!0,marketplaceName:J.marketplaceName,pluginCount:Y.plugins.length,timestamp:Date.now()};await this.publishResponse(X,Q)}catch($){let Y={success:!1,marketplaceName:J.marketplaceName,pluginCount:0,timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){r1.error("[Plugins] Error handling refresh marketplace request",{error:this.formatError(J)})}}}class Lj{services=[];startedServices=[];logger=x();addService(Z){this.services.push(Z)}addOptionalService(Z,J){if(J)this.services.push(Z)}getServiceByName(Z){return this.services.find((J)=>J.name===Z)}async startAll(){for(let Z of this.services)try{this.logger.debug(`Starting ${Z.name}...`),await Z.start(),this.startedServices.push(Z)}catch(J){throw this.logger.error(`Failed to start ${Z.name}`,J),await this.stopAll(),J}this.logger.info("All services started successfully")}async stopAll(){for(let Z=this.startedServices.length-1;Z>=0;Z--){let J=this.startedServices[Z];try{this.logger.debug(`Stopping ${J?.name}...`),await J?.stop()}catch(X){this.logger.error(`Failed to stop ${J?.name}`,X)}}this.startedServices=[],this.logger.info("All services stopped")}getStatus(){return this.services.map((Z)=>Z.getStatus())}printStatus(){let Z=this.getStatus();this.logger.info("=== Backend Status ===");for(let J of Z){let X=J.running?"\u2713":"\u2717";if(this.logger.info(`${X} ${J.name}`),"port"in J&&J.port)this.logger.info(` Port: ${J.port}`);if("routes"in J&&J.routes)this.logger.info(` Routes: ${J.routes.map(($)=>`${$.path}->${$.target}`).join(", ")}`);if(J.startedAt)this.logger.info(` Started: ${J.startedAt.toISOString()}`);if(J.error)this.logger.info(` Error: ${J.error}`)}this.logger.info("=====================")}}import YQ0 from"os";function QQ0(){let Z=YQ0.networkInterfaces(),J=/^(wlan|wlp|wifi|wi-fi|en0)/i,X=/^(eth|enp|en1|ethernet)/i;for(let[$,Y]of Object.entries(Z))if(J.test($)&&Y){let Q=Y.find((W)=>W.family==="IPv4"&&!W.internal);if(Q)return Q.address}for(let[$,Y]of Object.entries(Z))if(X.test($)&&Y){let Q=Y.find((W)=>W.family==="IPv4"&&!W.internal);if(Q)return Q.address}for(let $ of Object.values(Z))if($){let Y=$.find((Q)=>Q.family==="IPv4"&&!Q.internal);if(Y)return Y.address}return null}function WQ0(){let Z=YQ0.hostname().toLowerCase();if(Z.endsWith(".local"))Z=Z.slice(0,-6);return Z=Z.replace(/\./g,"-"),Z||"ccc-server"}var KQ0=process.argv.slice(2);if(KQ0.includes("--version")||KQ0.includes("-v"))console.log(`ccc v${Q6()}`),process.exit(0);function TZ1(Z){let J=x();try{if(process.stdin.isTTY)process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",(X)=>{let $=X.toString().toLowerCase();if($==="q")Z.display();if($==="\x03")process.emit("SIGINT")}),J.debug('Keypress listener enabled (press "q" to redisplay QR codes)')}catch(X){J.warn("Could not setup keypress listener",X)}}async function qZ1(){try{pe();let Z=ge();de(Z.debug);let J=x();J.info("Backend v2 starting...");let X=me(Z);if(Z.debug){let k0={...X,mqtt:{...X.mqtt,auth:X.mqtt.auth?{username:X.mqtt.auth.username?"[REDACTED]":void 0,password:X.mqtt.auth.password?"[REDACTED]":void 0}:void 0},ngrok:X.ngrok?{...X.ngrok,authToken:X.ngrok.authToken?"[REDACTED]":void 0}:void 0,qrcode:{...X.qrcode,username:X.qrcode.username?"[REDACTED]":void 0,password:X.qrcode.password?"[REDACTED]":void 0}};J.debug("Configuration",k0)}let $=new nG(X.mqtt),Y=new _H({host:"localhost",port:X.mqtt.port,username:X.mqtt.auth?.username,password:X.mqtt.auth?.password}),Q=new wH(X.terminal),W=new MH(X.router),K=new EH(X.autoUpdate),z=new yH,G=new SH,H=new kH(Q),V=new mH(X.claudeAgent),F=new uH,B=new cH,U=new iH,D=new oH,_=new rH,O=new sH,w=new tH,j=new eH,q=new JV,R=new XV,T=new Lj;if(T.addService($),T.addService(Y),T.addService(Q),T.addService(W),T.addService(K),T.addService(z),T.addService(G),T.addService(H),T.addService(V),T.addService(F),T.addService(B),T.addService(U),T.addService(D),T.addService(_),T.addService(O),T.addService(w),T.addService(j),T.addService(q),T.addService(R),X.ngrok){let k0=new AH(X.ngrok);T.addOptionalService(k0,!0)}z.setMQTTClient(Y),z.setClaudeAgentService(V),G.setMQTTClient(Y),H.setMQTTClient(Y),V.setMQTTClient(Y),V.setSessionsService(z),F.setMQTTClient(Y),B.setMQTTClient(Y),U.setMQTTClient(Y),U.setClaudeAgentService(V),D.setMQTTClient(Y),_.setMQTTClient(Y),O.setMQTTClient(Y),w.setMQTTClient(Y),j.setMQTTClient(Y),q.setMQTTClient(Y),R.setMQTTClient(Y),await T.startAll();let y=T.getServiceByName("CCC Ngrok Service"),i,s=QQ0(),O0=s?`${s}:${X.router.port}`:void 0;if(y&&y.getStatus().active)i=y.getUrl()||void 0;let d0=WQ0(),b0={...X.qrcode,profileName:d0,ipBasedUrl:O0,ngrokUrl:i},G0=new NH(b0);if(T.addService(G0),await G0.start(),T.printStatus(),O0&&!i)console.log(""),console.log("\x1B[33m"+"=".repeat(60)+"\x1B[0m"),console.log("\x1B[33m SECURITY NOTICE: HTTP Connection (Unencrypted)\x1B[0m"),console.log("\x1B[33m"+"=".repeat(60)+"\x1B[0m"),console.log(""),console.log("\x1B[32m SAFE if you are on:\x1B[0m"),console.log(" - Your home/private network"),console.log(" - A trusted VPN connection"),console.log(" - localhost only"),console.log(""),console.log("\x1B[31m NOT SAFE if:\x1B[0m"),console.log(" - You are on public WiFi (coffee shop, airport, etc.)"),console.log(" - The network has untrusted users"),console.log(""),console.log(" For secure public access:"),console.log(" - Use built-in ngrok (\x1B[36m--ngrok-token\x1B[0m) for automatic HTTPS"),console.log(" - Or use Cloudflare Tunnels, Tailscale, or similar solutions"),console.log(" - Enable \x1B[36mUse SSL\x1B[0m in the mobile app with a domain-based URL"),console.log("\x1B[33m"+"=".repeat(60)+"\x1B[0m"),console.log("");else if(i)console.log(""),console.log("\x1B[32m Secure HTTPS connection via ngrok is active.\x1B[0m"),console.log("\x1B[32m Your traffic is encrypted end-to-end.\x1B[0m"),console.log("");J.info("Backend v2 is ready"),TZ1(G0);let E0=!1,f0=async(k0)=>{if(E0){J.warn("Shutdown already in progress, ignoring signal");return}E0=!0,J.info(`Received ${k0}, shutting down...`),Y.markShuttingDown();try{await T.stopAll(),process.exit(0)}catch(e0){J.error("Error during shutdown",e0),process.exit(1)}};process.once("SIGINT",()=>f0("SIGINT")),process.once("SIGTERM",()=>f0("SIGTERM")),process.on("uncaughtException",(k0)=>{if(k0&&k0.code==="ERR_SOCKET_CLOSED"){J.debug("Ignoring socket closed error (expected during PTY cleanup)");return}J.error("Uncaught exception",k0)}),process.on("unhandledRejection",(k0)=>{J.error("Unhandled rejection",k0)})}catch(Z){x().error("Fatal error",Z),process.exit(1)}}qZ1();
2388
+ `+J.content;await U8.writeFile(Y,z,"utf-8");let G={success:!0,styleName:J.styleName,scope:J.scope,timestamp:Date.now()};await this.publishResponse(X,G)}catch($){let Y={success:!1,styleName:J.styleName,scope:J.scope,timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){B8.error("[OutputStyles] Error handling write style request",{error:this.formatError(J)})}}async handleDeleteStyleRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("output-styles/delete",J.clientId);try{let $=this.getOutputStylesDir(J.scope,J.projectPath),Y=Q4.join($,`${J.styleName}.md`),Q=Q4.resolve(Y),W=Q4.resolve($);if(!Q.startsWith(W))throw Error("Invalid style path");if(await U8.unlink(Y),await this.readActiveStyle(J.scope,J.projectPath)===J.styleName)await this.setActiveStyle(J.scope,"default",J.projectPath);let z={success:!0,styleName:J.styleName,scope:J.scope,timestamp:Date.now()};await this.publishResponse(X,z)}catch($){let Y={success:!1,styleName:J.styleName,scope:J.scope,timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){B8.error("[OutputStyles] Error handling delete style request",{error:this.formatError(J)})}}async handleSetActiveStyleRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("output-styles/set-active",J.clientId);try{await this.setActiveStyle(J.scope,J.styleName,J.projectPath);let $={success:!0,styleName:J.styleName,scope:J.scope,timestamp:Date.now()};await this.publishResponse(X,$)}catch($){let Y={success:!1,styleName:J.styleName,scope:J.scope,timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){B8.error("[OutputStyles] Error handling set active style request",{error:this.formatError(J)})}}}import*as W4 from"fs/promises";import*as v1 from"path";var c1=x(),pQ={name:"claude-plugins-official",source:{source:"github",repo:"anthropics/claude-plugins-official"}};class XV extends p4{name="Plugins Service";get logPrefix(){return"[Plugins]"}getStatus(){return{...super.getStatus()}}async onStart(){await this.ensureDirectories()}registerMQTTHandlers(){this.registerHandler("plugins/marketplaces/list/request",(Z,J)=>{this.handleListMarketplacesRequest(J)}),this.registerHandler("plugins/list/request",(Z,J)=>{this.handleListPluginsRequest(J)}),this.registerHandler("plugins/read/request",(Z,J)=>{this.handleReadPluginRequest(J)}),this.registerHandler("plugins/install/request",(Z,J)=>{this.handleInstallPluginRequest(J)}),this.registerHandler("plugins/uninstall/request",(Z,J)=>{this.handleUninstallPluginRequest(J)}),this.registerHandler("plugins/toggle/request",(Z,J)=>{this.handleTogglePluginRequest(J)}),this.registerHandler("plugins/marketplace/add/request",(Z,J)=>{this.handleAddMarketplaceRequest(J)}),this.registerHandler("plugins/marketplace/remove/request",(Z,J)=>{this.handleRemoveMarketplaceRequest(J)}),this.registerHandler("plugins/marketplace/refresh/request",(Z,J)=>{this.handleRefreshMarketplaceRequest(J)}),c1.info("[Plugins] MQTT handlers registered")}getPluginsDir(){return I9.getPluginsDir("user")}getMarketplaceCacheDir(){return I9.getMarketplaceCacheDir()}getSettingsPath(){return I9.getUserConfigPath("settings")}getInstalledPluginsJsonPath(){return v1.join(this.getPluginsDir(),"installed_plugins.json")}getPluginCacheDir(){return v1.join(this.getPluginsDir(),"cache")}async ensureDirectories(){let Z=[this.getPluginsDir(),this.getPluginCacheDir(),this.getMarketplaceCacheDir()];for(let J of Z)await W4.mkdir(J,{recursive:!0})}async readSettings(){return await E9.readConfigOrEmpty(this.getSettingsPath())}async writeSettings(Z){await E9.writeConfig(this.getSettingsPath(),Z)}async getEnabledPlugins(){return(await this.readSettings()).enabledPlugins||{}}async setPluginEnabled(Z,J){let X=await this.readSettings();if(!X.enabledPlugins)X.enabledPlugins={};X.enabledPlugins[Z]=J,await this.writeSettings(X)}async getKnownMarketplaces(){let J=(await this.readSettings()).extraKnownMarketplaces||{},X={};for(let[$,Y]of Object.entries(J))if(typeof Y==="object"&&Y!==null&&"source"in Y)X[$]=Y.source;else X[$]=Y;return X}async addKnownMarketplace(Z,J){let X=await this.readSettings();if(!X.extraKnownMarketplaces)X.extraKnownMarketplaces={};X.extraKnownMarketplaces[Z]={source:J},await this.writeSettings(X)}async removeKnownMarketplace(Z){let J=await this.readSettings();if(J.extraKnownMarketplaces)delete J.extraKnownMarketplaces[Z],await this.writeSettings(J)}async readInstalledPluginsJson(){let Z=this.getInstalledPluginsJsonPath(),J=await W1(Z);if(!J)return{version:2,plugins:{}};try{let X=JSON.parse(J);return{version:X.version||2,plugins:X.plugins||{}}}catch(X){return c1.warn("[Plugins] Failed to parse installed_plugins.json, returning empty",X),{version:2,plugins:{}}}}async writeInstalledPluginsJson(Z){let J=this.getInstalledPluginsJsonPath();await W4.writeFile(J,JSON.stringify(Z,null,2),"utf-8")}async addInstalledPluginRecord(Z,J){let X=await this.readInstalledPluginsJson();if(!X.plugins[Z])X.plugins[Z]=[];let $=X.plugins[Z].findIndex((Y)=>Y.scope===J.scope);if($>=0)X.plugins[Z][$]=J;else X.plugins[Z].push(J);await this.writeInstalledPluginsJson(X)}async removeInstalledPluginRecord(Z,J){let X=await this.readInstalledPluginsJson();if(!X.plugins[Z])return;if(J){if(X.plugins[Z]=X.plugins[Z].filter(($)=>$.scope!==J),X.plugins[Z].length===0)delete X.plugins[Z]}else delete X.plugins[Z];await this.writeInstalledPluginsJson(X)}async getInstalledPluginRecord(Z){let X=(await this.readInstalledPluginsJson()).plugins[Z];if(!X||X.length===0)return null;return X[0]??null}getMarketplaceCachePath(Z){return v1.join(this.getMarketplaceCacheDir(),Z)}async fetchMarketplace(Z,J){let X=this.getMarketplaceCachePath(Z);try{if(typeof J==="object"&&J.source==="github"){let Q=`https://github.com/${J.repo}.git`,W=J.ref||"main";if(await c4(X)){let{$:K}=awaitPromise.resolve(globalThis.Bun);await K`git -C ${X} fetch origin ${W}`.quiet(),await K`git -C ${X} reset --hard origin/${W}`.quiet()}else{let{$:K}=awaitPromise.resolve(globalThis.Bun);await K`git clone --depth 1 --branch ${W} ${Q} ${X}`.quiet()}}else if(typeof J==="object"&&J.source==="url"){let Q=J.url,W=J.ref||"main";if(await c4(X)){let{$:K}=awaitPromise.resolve(globalThis.Bun);await K`git -C ${X} fetch origin ${W}`.quiet(),await K`git -C ${X} reset --hard origin/${W}`.quiet()}else{let{$:K}=awaitPromise.resolve(globalThis.Bun);await K`git clone --depth 1 --branch ${W} ${Q} ${X}`.quiet()}}else if(typeof J==="string")return c1.warn("[Plugins] Relative path source not supported for marketplaces"),null;let $=v1.join(X,".claude-plugin","marketplace.json"),Y=await W1($);if(!Y){let Q=v1.join(X,"marketplace.json"),W=await W1(Q);if(W)return JSON.parse(W);return c1.warn(`[Plugins] No marketplace.json found for ${Z}`),null}return JSON.parse(Y)}catch($){return c1.error(`[Plugins] Failed to fetch marketplace ${Z}`,$),null}}async parseMarketplace(Z){let J=this.getMarketplaceCachePath(Z),X=v1.join(J,".claude-plugin","marketplace.json"),$=await W1(X);if(!$)X=v1.join(J,"marketplace.json"),$=await W1(X);if(!$)return null;try{return JSON.parse($)}catch(Y){return c1.error(`[Plugins] Failed to parse marketplace.json for ${Z}`,Y),null}}async marketplacePluginToEntry(Z,J,X,$){let Y=`${Z.name}@${J}`;return{name:Z.name,displayName:Z.name,description:Z.description||"",version:Z.version,author:Z.author?.name,category:Z.category,tags:Z.tags,marketplaceName:J,isInstalled:$.has(Y),isEnabled:X[Y]??!1,source:Z.source}}async getAllMarketplaces(){let Z=await this.getKnownMarketplaces(),J=[{name:pQ.name,source:pQ.source,isOfficial:!0}];for(let[X,$]of Object.entries(Z))J.push({name:X,source:$,isOfficial:!1});return J}async getInstalledPlugins(){let Z=new Set,J=await this.readInstalledPluginsJson();for(let[X,$]of Object.entries(J.plugins)){if(!$||$.length===0)continue;for(let Y of $)if(Y.installPath){if(await c4(Y.installPath)){Z.add(X);break}}}return Z}getPluginInstallPath(Z,J,X="1.0.0"){return v1.join(this.getPluginCacheDir(),J,Z,X)}async getPluginInstallPathFromRecord(Z,J){let X=`${Z}@${J}`;return(await this.getInstalledPluginRecord(X))?.installPath||null}async getGitCommitSha(Z){try{let{$:J}=awaitPromise.resolve(globalThis.Bun);return(await J`git -C ${Z} rev-parse HEAD`.quiet()).stdout.toString().trim()||void 0}catch{return}}async installPluginFromMarketplace(Z,J,X="user"){try{let $=await this.parseMarketplace(J);if(!$)return{success:!1,error:"Marketplace not found or not cached"};let Y=$.plugins.find((F)=>F.name===Z);if(!Y)return{success:!1,error:"Plugin not found in marketplace"};let Q=Y.version||"1.0.0",W=this.getPluginInstallPath(Z,J,Q),K=this.getMarketplaceCachePath(J),z=`${Z}@${J}`;await W4.mkdir(v1.dirname(W),{recursive:!0});let G;if(typeof Y.source==="string"){let F=v1.join(K,Y.source);await W4.rm(W,{recursive:!0,force:!0}),await W4.cp(F,W,{recursive:!0}),G=await this.getGitCommitSha(K)}else if(Y.source.source==="github"){let F=`https://github.com/${Y.source.repo}.git`,B=Y.source.ref||"main",{$:U}=awaitPromise.resolve(globalThis.Bun);await W4.rm(W,{recursive:!0,force:!0}),await U`git clone --depth 1 --branch ${B} ${F} ${W}`.quiet(),G=await this.getGitCommitSha(W)}else if(Y.source.source==="url"){let F=Y.source.url,B=Y.source.ref||"main",{$:U}=awaitPromise.resolve(globalThis.Bun);await W4.rm(W,{recursive:!0,force:!0}),await U`git clone --depth 1 --branch ${B} ${F} ${W}`.quiet(),G=await this.getGitCommitSha(W)}else return{success:!1,error:"Unknown plugin source type"};let H=new Date().toISOString(),V={scope:X,installPath:W,version:Q,installedAt:H,lastUpdated:H,gitCommitSha:G};return await this.addInstalledPluginRecord(z,V),await this.setPluginEnabled(z,!0),c1.info(`[Plugins] Installed ${z} to ${W}`),{success:!0}}catch($){return c1.error(`[Plugins] Failed to install plugin ${Z}@${J}`,$),{success:!1,error:$ instanceof Error?$.message:"Unknown error"}}}async uninstallPlugin(Z,J,X){try{let $=`${Z}@${J}`,Y=await this.getInstalledPluginRecord($);if(!Y)return{success:!1,error:"Plugin not installed"};if(Y.installPath&&await c4(Y.installPath))await W4.rm(Y.installPath,{recursive:!0,force:!0});await this.removeInstalledPluginRecord($,X);let Q=await this.readSettings();if(Q.enabledPlugins&&Q.enabledPlugins[$]!==void 0)delete Q.enabledPlugins[$],await this.writeSettings(Q);return c1.info(`[Plugins] Uninstalled ${$}`),{success:!0}}catch($){return c1.error(`[Plugins] Failed to uninstall plugin ${Z}@${J}`,$),{success:!1,error:$ instanceof Error?$.message:"Unknown error"}}}async readPluginManifest(Z){let J=v1.join(Z,".claude-plugin","plugin.json"),X=await W1(J);if(!X)return null;try{return JSON.parse(X)}catch($){return null}}async getPluginDetail(Z,J){let X=await this.getEnabledPlugins(),$=await this.getInstalledPlugins(),Y=`${Z}@${J}`,W=(await this.parseMarketplace(J))?.plugins.find((O)=>O.name===Z),K=$.has(Y),G=(K?await this.getInstalledPluginRecord(Y):null)?.installPath,H=K&&G?await this.readPluginManifest(G):null,V=!1,F=!1,B=!1,U=!1,D=!1,_=!1;if(K&&G)V=await c4(v1.join(G,"commands")),F=await c4(v1.join(G,"skills")),B=await c4(v1.join(G,"agents")),U=await c4(v1.join(G,"hooks")),D=await c4(v1.join(G,".mcp.json"))||await W4.access(v1.join(G,".mcp.json")).then(()=>!0).catch(()=>!1),_=await c4(v1.join(G,".lsp.json"))||await W4.access(v1.join(G,".lsp.json")).then(()=>!0).catch(()=>!1);return{name:Z,displayName:H?.name||W?.name||Z,description:H?.description||W?.description||"",version:H?.version||W?.version,author:H?.author?.name||W?.author?.name,category:W?.category,tags:W?.tags,marketplaceName:J,isInstalled:K,isEnabled:X[Y]??!1,source:W?.source||Z,homepage:H?.homepage,repository:H?.repository,license:H?.license,hasCommands:V,hasSkills:F,hasAgents:B,hasHooks:U,hasMcpServers:D,hasLspServers:_,installPath:K?G:void 0}}async handleListMarketplacesRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("plugins/marketplaces/list",J.clientId);try{let $=await this.getAllMarketplaces(),Y=[];for(let{name:W,source:K,isOfficial:z}of $){let G=await this.parseMarketplace(W),H=0,V,F="Unknown";if(G)H=G.plugins.length,V=G.description,F=G.owner.name;Y.push({name:W,description:V,owner:F,source:K,pluginCount:H,isOfficial:z})}let Q={marketplaces:Y,timestamp:Date.now()};await this.publishResponse(X,Q)}catch($){let Y={marketplaces:[],timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){c1.error("[Plugins] Error handling list marketplaces request",{error:this.formatError(J)})}}async handleListPluginsRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("plugins/list",J.clientId);try{let $=await this.getEnabledPlugins(),Y=await this.getInstalledPlugins(),Q=[];if(J.scope==="installed")for(let K of Y){let z=K.split("@"),G=z[0],H=z[1];if(!G||!H)continue;let V=await this.getPluginDetail(G,H);if(V)Q.push({name:V.name,displayName:V.displayName,description:V.description,version:V.version,author:V.author,category:V.category,tags:V.tags,marketplaceName:H,isInstalled:!0,isEnabled:V.isEnabled,source:V.source})}else if(J.scope==="marketplace"){let K=await this.getAllMarketplaces(),z=J.marketplaceName?K.filter((G)=>G.name===J.marketplaceName):K;for(let{name:G,source:H}of z){let V=await this.parseMarketplace(G);if(!V&&H)c1.info(`[Plugins] Marketplace cache not found for ${G}, fetching...`),V=await this.fetchMarketplace(G,H);if(!V)continue;for(let F of V.plugins){let B=await this.marketplacePluginToEntry(F,G,$,Y);Q.push(B)}}}let W={plugins:Q,marketplaceName:J.marketplaceName,timestamp:Date.now()};await this.publishResponse(X,W)}catch($){let Y={plugins:[],timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){c1.error("[Plugins] Error handling list plugins request",{error:this.formatError(J)})}}async handleReadPluginRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("plugins/read",J.clientId);try{let Y={plugin:await this.getPluginDetail(J.pluginName,J.marketplaceName)||void 0,timestamp:Date.now()};await this.publishResponse(X,Y)}catch($){let Y={timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){c1.error("[Plugins] Error handling read plugin request",{error:this.formatError(J)})}}async handleInstallPluginRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("plugins/install",J.clientId);try{let $=await this.installPluginFromMarketplace(J.pluginName,J.marketplaceName),Y={success:$.success,pluginName:J.pluginName,marketplaceName:J.marketplaceName,timestamp:Date.now(),error:$.error};await this.publishResponse(X,Y)}catch($){let Y={success:!1,pluginName:J.pluginName,marketplaceName:J.marketplaceName,timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){c1.error("[Plugins] Error handling install plugin request",{error:this.formatError(J)})}}async handleUninstallPluginRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("plugins/uninstall",J.clientId);try{let $=await this.uninstallPlugin(J.pluginName,J.marketplaceName),Y={success:$.success,pluginName:J.pluginName,marketplaceName:J.marketplaceName,timestamp:Date.now(),error:$.error};await this.publishResponse(X,Y)}catch($){let Y={success:!1,pluginName:J.pluginName,marketplaceName:J.marketplaceName,timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){c1.error("[Plugins] Error handling uninstall plugin request",{error:this.formatError(J)})}}async handleTogglePluginRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("plugins/toggle",J.clientId);try{let $=`${J.pluginName}@${J.marketplaceName}`;await this.setPluginEnabled($,J.enabled);let Y={success:!0,pluginName:J.pluginName,marketplaceName:J.marketplaceName,enabled:J.enabled,timestamp:Date.now()};await this.publishResponse(X,Y)}catch($){let Y={success:!1,pluginName:J.pluginName,marketplaceName:J.marketplaceName,enabled:J.enabled,timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){c1.error("[Plugins] Error handling toggle plugin request",{error:this.formatError(J)})}}async handleAddMarketplaceRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("plugins/marketplace/add",J.clientId);try{let $="temp_"+Date.now();if(typeof J.source==="object"&&J.source.source==="github")$=J.source.repo.split("/").pop()||$;let Y=await this.fetchMarketplace($,J.source);if(!Y){let z={success:!1,timestamp:Date.now(),error:"Failed to fetch or parse marketplace"};await this.publishResponse(X,z);return}let Q=Y.name;if($!==Q){let z=this.getMarketplaceCachePath($),G=this.getMarketplaceCachePath(Q);await W4.rm(G,{recursive:!0,force:!0}),await W4.rename(z,G)}await this.addKnownMarketplace(Q,J.source);let K={success:!0,marketplace:{name:Q,description:Y.description,owner:Y.owner.name,source:J.source,pluginCount:Y.plugins.length,isOfficial:!1},timestamp:Date.now()};await this.publishResponse(X,K)}catch($){let Y={success:!1,timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){c1.error("[Plugins] Error handling add marketplace request",{error:this.formatError(J)})}}async handleRemoveMarketplaceRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("plugins/marketplace/remove",J.clientId);try{if(J.marketplaceName===pQ.name){let Y={success:!1,marketplaceName:J.marketplaceName,timestamp:Date.now(),error:"Cannot remove official marketplace"};await this.publishResponse(X,Y);return}await this.removeKnownMarketplace(J.marketplaceName);let $={success:!0,marketplaceName:J.marketplaceName,timestamp:Date.now()};await this.publishResponse(X,$)}catch($){let Y={success:!1,marketplaceName:J.marketplaceName,timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){c1.error("[Plugins] Error handling remove marketplace request",{error:this.formatError(J)})}}async handleRefreshMarketplaceRequest(Z){try{let J=this.parseMessage(Z);if(!J)return;let X=this.buildResponseTopic("plugins/marketplace/refresh",J.clientId);try{let $=null;if(J.marketplaceName===pQ.name)$=pQ.source;else $=(await this.getKnownMarketplaces())[J.marketplaceName]||null;if(!$){let W={success:!1,marketplaceName:J.marketplaceName,pluginCount:0,timestamp:Date.now(),error:"Marketplace not found"};await this.publishResponse(X,W);return}let Y=await this.fetchMarketplace(J.marketplaceName,$);if(!Y){let W={success:!1,marketplaceName:J.marketplaceName,pluginCount:0,timestamp:Date.now(),error:"Failed to fetch marketplace"};await this.publishResponse(X,W);return}let Q={success:!0,marketplaceName:J.marketplaceName,pluginCount:Y.plugins.length,timestamp:Date.now()};await this.publishResponse(X,Q)}catch($){let Y={success:!1,marketplaceName:J.marketplaceName,pluginCount:0,timestamp:Date.now(),error:this.formatError($)};await this.publishResponse(X,Y)}this.incrementRequestCount()}catch(J){c1.error("[Plugins] Error handling refresh marketplace request",{error:this.formatError(J)})}}}class Lj{services=[];startedServices=[];logger=x();addService(Z){this.services.push(Z)}addOptionalService(Z,J){if(J)this.services.push(Z)}getServiceByName(Z){return this.services.find((J)=>J.name===Z)}async startAll(){for(let Z of this.services)try{this.logger.debug(`Starting ${Z.name}...`),await Z.start(),this.startedServices.push(Z)}catch(J){throw this.logger.error(`Failed to start ${Z.name}`,J),await this.stopAll(),J}this.logger.info("All services started successfully")}async stopAll(){for(let Z=this.startedServices.length-1;Z>=0;Z--){let J=this.startedServices[Z];try{this.logger.debug(`Stopping ${J?.name}...`),await J?.stop()}catch(X){this.logger.error(`Failed to stop ${J?.name}`,X)}}this.startedServices=[],this.logger.info("All services stopped")}getStatus(){return this.services.map((Z)=>Z.getStatus())}printStatus(){let Z=this.getStatus();this.logger.info("=== Backend Status ===");for(let J of Z){let X=J.running?"\u2713":"\u2717";if(this.logger.info(`${X} ${J.name}`),"port"in J&&J.port)this.logger.info(` Port: ${J.port}`);if("routes"in J&&J.routes)this.logger.info(` Routes: ${J.routes.map(($)=>`${$.path}->${$.target}`).join(", ")}`);if(J.startedAt)this.logger.info(` Started: ${J.startedAt.toISOString()}`);if(J.error)this.logger.info(` Error: ${J.error}`)}this.logger.info("=====================")}}import YQ0 from"os";function QQ0(){let Z=YQ0.networkInterfaces(),J=/^(wlan|wlp|wifi|wi-fi|en0)/i,X=/^(eth|enp|en1|ethernet)/i;for(let[$,Y]of Object.entries(Z))if(J.test($)&&Y){let Q=Y.find((W)=>W.family==="IPv4"&&!W.internal);if(Q)return Q.address}for(let[$,Y]of Object.entries(Z))if(X.test($)&&Y){let Q=Y.find((W)=>W.family==="IPv4"&&!W.internal);if(Q)return Q.address}for(let $ of Object.values(Z))if($){let Y=$.find((Q)=>Q.family==="IPv4"&&!Q.internal);if(Y)return Y.address}return null}function WQ0(){let Z=YQ0.hostname().toLowerCase();if(Z.endsWith(".local"))Z=Z.slice(0,-6);return Z=Z.replace(/\./g,"-"),Z||"ccc-server"}var KQ0=process.argv.slice(2);if(KQ0.includes("--version")||KQ0.includes("-v"))console.log(`ccc v${Q6()}`),process.exit(0);function TZ1(Z){let J=x();try{if(process.stdin.isTTY)process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",(X)=>{let $=X.toString().toLowerCase();if($==="q")Z.display();if($==="\x03")process.emit("SIGINT")}),J.debug('Keypress listener enabled (press "q" to redisplay QR codes)')}catch(X){J.warn("Could not setup keypress listener",X)}}async function qZ1(){try{pe();let Z=ge();de(Z.debug);let J=x();J.info("Backend v2 starting...");let X=me(Z);if(Z.debug){let k0={...X,mqtt:{...X.mqtt,auth:X.mqtt.auth?{username:X.mqtt.auth.username?"[REDACTED]":void 0,password:X.mqtt.auth.password?"[REDACTED]":void 0}:void 0},ngrok:X.ngrok?{...X.ngrok,authToken:X.ngrok.authToken?"[REDACTED]":void 0}:void 0,qrcode:{...X.qrcode,username:X.qrcode.username?"[REDACTED]":void 0,password:X.qrcode.password?"[REDACTED]":void 0}};J.debug("Configuration",k0)}let $=new nG(X.mqtt),Y=new _H({host:"localhost",port:X.mqtt.port,username:X.mqtt.auth?.username,password:X.mqtt.auth?.password}),Q=new wH(X.terminal),W=new MH(X.router),K=new EH(X.autoUpdate),z=new yH,G=new SH,H=new kH(Q),V=new mH(X.claudeAgent),F=new uH,B=new cH,U=new iH,D=new oH,_=new rH,O=new sH,w=new tH,j=new eH,q=new JV,R=new XV,T=new Lj;if(T.addService($),T.addService(Y),T.addService(Q),T.addService(W),T.addService(K),T.addService(z),T.addService(G),T.addService(H),T.addService(V),T.addService(F),T.addService(B),T.addService(U),T.addService(D),T.addService(_),T.addService(O),T.addService(w),T.addService(j),T.addService(q),T.addService(R),X.ngrok){let k0=new AH(X.ngrok);T.addOptionalService(k0,!0)}z.setMQTTClient(Y),z.setClaudeAgentService(V),G.setMQTTClient(Y),H.setMQTTClient(Y),V.setMQTTClient(Y),V.setSessionsService(z),F.setMQTTClient(Y),B.setMQTTClient(Y),U.setMQTTClient(Y),U.setClaudeAgentService(V),D.setMQTTClient(Y),_.setMQTTClient(Y),O.setMQTTClient(Y),w.setMQTTClient(Y),j.setMQTTClient(Y),q.setMQTTClient(Y),R.setMQTTClient(Y),await T.startAll();let y=T.getServiceByName("CCC Ngrok Service"),i,s=QQ0(),O0=s?`${s}:${X.router.port}`:void 0;if(y&&y.getStatus().active)i=y.getUrl()||void 0;let d0=WQ0(),b0={...X.qrcode,profileName:d0,ipBasedUrl:O0,ngrokUrl:i},G0=new NH(b0);if(T.addService(G0),await G0.start(),T.printStatus(),O0&&!i)console.log(""),console.log("\x1B[33m"+"=".repeat(60)+"\x1B[0m"),console.log("\x1B[33m SECURITY NOTICE: HTTP Connection (Unencrypted)\x1B[0m"),console.log("\x1B[33m"+"=".repeat(60)+"\x1B[0m"),console.log(""),console.log("\x1B[32m SAFE if you are on:\x1B[0m"),console.log(" - Your home/private network"),console.log(" - A trusted VPN connection"),console.log(" - localhost only"),console.log(""),console.log("\x1B[31m NOT SAFE if:\x1B[0m"),console.log(" - You are on public WiFi (coffee shop, airport, etc.)"),console.log(" - The network has untrusted users"),console.log(""),console.log(" For secure public access:"),console.log(" - Use built-in ngrok (\x1B[36m--ngrok-token\x1B[0m) for automatic HTTPS"),console.log(" - Or use Cloudflare Tunnels, Tailscale, or similar solutions"),console.log(" - Enable \x1B[36mUse SSL\x1B[0m in the mobile app with a domain-based URL"),console.log("\x1B[33m"+"=".repeat(60)+"\x1B[0m"),console.log("");else if(i)console.log(""),console.log("\x1B[32m Secure HTTPS connection via ngrok is active.\x1B[0m"),console.log("\x1B[32m Your traffic is encrypted end-to-end.\x1B[0m"),console.log("");J.info("Backend v2 is ready"),TZ1(G0);let E0=!1,f0=async(k0)=>{if(E0){J.warn("Shutdown already in progress, ignoring signal");return}E0=!0,J.info(`Received ${k0}, shutting down...`),Y.markShuttingDown();try{await T.stopAll(),process.exit(0)}catch(e0){J.error("Error during shutdown",e0),process.exit(1)}};process.once("SIGINT",()=>f0("SIGINT")),process.once("SIGTERM",()=>f0("SIGTERM")),process.on("uncaughtException",(k0)=>{if(k0&&k0.code==="ERR_SOCKET_CLOSED"){J.debug("Ignoring socket closed error (expected during PTY cleanup)");return}J.error("Uncaught exception",k0)}),process.on("unhandledRejection",(k0)=>{J.error("Unhandled rejection",k0)})}catch(Z){x().error("Fatal error",Z),process.exit(1)}}qZ1();