@naarang/ccc 3.3.0-beta.1 → 3.3.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.
- package/dist/index.js +2 -2
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -51,7 +51,7 @@ Event: ${N7(Z)}`),!0}return!1}function yP1(Z,J){if(!J?.length)return!1;return Vz
|
|
|
51
51
|
`;let K=$i(X);X.write(`${W}\r
|
|
52
52
|
`);let{connect:z,buffered:G}=await K;if(Z.emit("proxyConnect",z),this.emit("proxyConnect",z,Z),z.statusCode===200){if(Z.once("socket",Ah1),J.secureEndpoint){n3("Upgrading socket connection to TLS");let V=J.servername||J.host;return RD.connect({...Xi(J,"host","path","port"),socket:X,servername:N9.isIP(V)?void 0:V})}return X}X.destroy();let H=new N9.Socket({writable:!1});return H.readable=!0,Z.once("socket",(V)=>{n3("Replaying proxy buffer for failed request"),V.push(G),V.push(null)}),H}}QG.__initStatic();function Ah1(Z){Z.resume()}function Xi(Z,...J){let $={},X;for(X in Z)if(!J.includes(X))$[X]=Z[X];return $}var Rh1=32768;function Ch1(Z){return new jh1({read(){this.push(Z),this.push(null)}})}function CD(Z){let J;try{J=new URL(Z.url)}catch(z){return o0(()=>{console.warn("[@sentry/node]: Invalid dsn or tunnel option, will not send any events. The tunnel option must be a full URL when used.")}),WJ(Z,()=>Promise.resolve({}))}let $=J.protocol==="https:",X=qh1(J,Z.proxy||($?process.env.https_proxy:void 0)||process.env.http_proxy),Y=$?Mh1:Th1,Q=Z.keepAlive===void 0?!1:Z.keepAlive,W=X?new QG(X):new Y.Agent({keepAlive:Q,maxSockets:30,timeout:2000}),K=Eh1(Z,Z.httpModule??Y,W);return WJ(Z,K)}function qh1(Z,J){let{no_proxy:$}=process.env;if($?.split(",").some((Y)=>Z.host.endsWith(Y)||Z.hostname.endsWith(Y)))return;else return J}function Eh1(Z,J,$){let{hostname:X,pathname:Y,port:Q,protocol:W,search:K}=new URL(Z.url);return function(G){return new Promise((H,V)=>{S7(()=>{let F=Ch1(G.body),B={...Z.headers};if(G.body.length>Rh1)B["content-encoding"]="gzip",F=F.pipe(Nh1());let U=X.startsWith("["),L=J.request({method:"POST",agent:$,headers:B,hostname:U?X.slice(1,-1):X,path:`${Y}${K}`,port:Q,protocol:W,ca:Z.caCerts},(O)=>{O.on("data",()=>{}),O.on("end",()=>{}),O.setEncoding("utf8");let _=O.headers["retry-after"]??null,w=O.headers["x-sentry-rate-limits"]??null;H({statusCode:O.statusCode,headers:{"retry-after":_,"x-sentry-rate-limits":Array.isArray(w)?w[0]||null:w}})});L.on("error",V),F.pipe(L)})})}}var Ph1=new Set(["false","f","n","no","off","0"]),Ih1=new Set(["true","t","y","yes","on","1"]);function WG(Z,J){let $=String(Z).toLowerCase();if(Ph1.has($))return!1;if(Ih1.has($))return!0;return J?.strict?null:Boolean(Z)}import{posix as Sh1,sep as yh1}from"path";function Yi(Z){return Z.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}function qD(Z=process.argv[1]?Z2(process.argv[1]):process.cwd(),J=yh1==="\\"){let $=J?Yi(Z):Z;return(X)=>{if(!X)return;let Y=J?Yi(X):X,{dir:Q,base:W,ext:K}=Sh1.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($)){let H=Q.slice($.length+1).replace(/\//g,".");return H?`${H}:${z}`:z}return z}}function ED(Z){if(process.env.SENTRY_RELEASE)return process.env.SENTRY_RELEASE;if(G1.SENTRY_RELEASE?.id)return G1.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,$=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,X=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 PD=lK(N2(qD()));var Wi=v(u(),1),Ki=v(D1(),1);import*as Qi from"os";import{threadId as kh1,isMainThread as xh1}from"worker_threads";var vh1=60000;class KG extends Uz{constructor(Z){let J=Z.includeServerName===!1?void 0:Z.serverName||global.process.env.SENTRY_NAME||Qi.hostname(),$={...Z,platform:"node",runtime:{name:"node",version:global.process.version},serverName:J};if(Z.openTelemetryInstrumentations)Ki.registerInstrumentations({instrumentations:Z.openTelemetryInstrumentations});_9($,"node"),R.log(`Initializing Sentry: process: ${process.pid}, thread: ${xh1?"main":`worker-${kh1}`}.`);super($);if(this.getOptions().enableLogs){if(this._logOnExitFlushListener=()=>{B3(this)},J)this.on("beforeCaptureLog",(X)=>{X.attributes={...X.attributes,"server.address":J}});process.on("beforeExit",this._logOnExitFlushListener)}}get tracer(){if(this._tracer)return this._tracer;let Z="@sentry/node",J=u1,$=Wi.trace.getTracer(Z,J);return this._tracer=$,$}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(()=>{E1&&R.log("Flushing client reports based on interval."),this._flushOutcomes()},Z.clientReportFlushInterval??vh1).unref(),process.on("beforeExit",this._clientReportOnExitFlushListener)}_setupIntegrations(){nL(),super._setupIntegrations()}_getTraceInfoFromScope(Z){if(!Z)return[void 0,void 0];return sl(this,Z)}}var zi=v(kU(),1);import*as Gi from"module";function ID(){if(!kp())return;if(!G1._sentryEsmLoaderHookRegistered){G1._sentryEsmLoaderHookRegistered=!0;try{let{addHookMessagePort:Z}=zi.createAddHookMessageChannel();Gi.register("import-in-the-middle/hook.mjs",import.meta.url,{data:{addHookMessagePort:Z,include:[]},transferList:[Z]})}catch(Z){R.warn("Failed to register 'import-in-the-middle' hook",Z)}}}function zG(){return[f$(),h$(),b$(),g$(),OD(),m$(),ep(),Zi(),HX(),VX(),zX(),BD(),KX(),wD(),Ji(),GX()]}function SD(Z={}){return hh1(Z,zG)}function hh1(Z={},J){let $=fh1(Z,J);if($.debug===!0)if(E1)R.enable();else o0(()=>{console.warn("[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.")});if($.registerEsmLoaderHooks!==!1)ID();if(Zp(),e1().update($.initialScope),$.spotlight&&!$.integrations.some(({name:Q})=>Q===LD))$.integrations.push(DD({sidecarUrl:typeof $.spotlight==="string"?$.spotlight:void 0}));_9($,"node-core");let Y=new KG($);if(e1().setClient(Y),Y.init(),G1._sentryInjectLoaderHookRegister?.(),R.log(`SDK initialized from ${d3()?"CommonJS":"ESM"}`),Y.startClientReportTracking(),mh1(),bl(Y),el(Y),process.env.VERCEL)process.on("SIGTERM",async()=>{await Y.flush(200)});return Y}function GG(){if(!E1)return;let Z=dl(),J=["SentryContextManager","SentryPropagator"];if(P0())J.push("SentrySpanProcessor");for(let $ of J)if(!Z.includes($))R.error(`You have to set up the ${$}. Without this, the OpenTelemetry & Sentry integration will not work properly.`);if(!Z.includes("SentrySampler"))R.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 fh1(Z,J){let $=bh1(Z.release),X;if(Z.spotlight===!1)X=!1;else if(typeof Z.spotlight==="string")X=Z.spotlight;else{let z=WG(process.env.SENTRY_SPOTLIGHT,{strict:!0}),G=z===null&&process.env.SENTRY_SPOTLIGHT?process.env.SENTRY_SPOTLIGHT:void 0;X=Z.spotlight===!0?G??!0:z??G}let Y=gh1(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??CD,stackParser:QL(Z.stackParser||PD),release:$,tracesSampleRate:Y,spotlight:X,debug:WG(Z.debug??process.env.SENTRY_DEBUG)},W=Z.integrations,K=Z.defaultIntegrations??J(Q);return{...Q,integrations:vL({defaultIntegrations:K,integrations:W})}}function bh1(Z){if(Z!==void 0)return Z;let J=ED();if(J!==void 0)return J;return}function gh1(Z){if(Z!==void 0)return Z;let J=process.env.SENTRY_TRACES_SAMPLE_RATE;if(!J)return;let $=parseFloat(J);return isFinite($)?$:void 0}function mh1(){if(WG(process.env.SENTRY_USE_ENVIRONMENT)!==!1){let Z=process.env.SENTRY_TRACE,J=process.env.SENTRY_BAGGAGE,$=ZJ(Z,J);e1().setPropagationContext($)}}function Y0(Z,J){Z.setAttribute(W1,J)}var yD="Http",Hi="@opentelemetry_sentry-patched/instrumentation-http",uh1=s(`${yD}.sentry`,(Z)=>{return new YX(Z)}),dh1=s(yD,(Z)=>{let J=new Fi.HttpInstrumentation({...Z,disableIncomingRequestInstrumentation:!0});try{J._diag=Vi.diag.createComponentLogger({namespace:Hi}),J.instrumentationName=Hi}catch{}return J});function ch1(Z,J={}){if(typeof Z.spans==="boolean")return Z.spans;if(J.skipOpenTelemetrySetup)return!1;if(!P0(J)&&o7.major>=22)return!1;return!0}var a3=k((Z={})=>{let J=Z.spans??!0,$=Z.disableIncomingRequestSpans,X={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=a$(X),W=o$(Y),K=J&&!$;return{name:yD,setup(z){let G=z.getOptions();if(K&&P0(G))W.setup(z)},setupOnce(){let z=p()?.getOptions()||{},G=ch1(Z,z);Q.setupOnce();let H={breadcrumbs:Z.breadcrumbs,propagateTraceInOutgoingRequests:!G,ignoreOutgoingRequests:Z.ignoreOutgoingRequests};if(uh1(H),G){let V=lh1(Z);dh1(V)}},processEvent(z){return W.processEvent(z)}}});function lh1(Z={}){return{ignoreOutgoingRequestHook:($)=>{let X=S3($);if(!X)return!1;let Y=Z.ignoreOutgoingRequests;if(Y?.(X,$))return!0;return!1},requireParentforOutgoingSpans:!1,requestHook:($,X)=>{Y0($,"auto.http.otel.http"),Z.instrumentation?.requestHook?.($,X)},responseHook:($,X)=>{Z.instrumentation?.responseHook?.($,X)},applyCustomAttributesOnSpan:($,X,Y)=>{Z.instrumentation?.applyCustomAttributesOnSpan?.($,X,Y)}}}var Mi=v(Ti(),1);var ji="NodeFetch",oh1=s(ji,Mi.UndiciInstrumentation,(Z)=>{return Zf1(Z)}),rh1=s(`${ji}.sentry`,WX,(Z)=>{return Z}),sh1=(Z={})=>{return{name:"NodeFetch",setupOnce(){if(eh1(Z,p()?.getOptions()))oh1(Z);rh1(Z)}}},r3=k(sh1);function th1(Z,J="/"){let $=`${Z}`;if($.endsWith("/")&&J.startsWith("/"))return`${$}${J.slice(1)}`;if(!$.endsWith("/")&&!J.startsWith("/"))return`${$}/${J.slice(1)}`;return`${$}${J}`}function eh1(Z,J={}){return typeof Z.spans==="boolean"?Z.spans:!J.skipOpenTelemetrySetup&&P0(J)}function Zf1(Z={}){return{requireParentforSpans:!1,ignoreRequestHook:($)=>{let X=th1($.origin,$.path),Y=Z.ignoreOutgoingRequests;return!!(Y&&X&&Y(X))},startSpanHook:()=>{return{[W1]:"auto.http.otel.node_fetch"}},requestHook:Z.requestHook,responseHook:Z.responseHook}}var pi=v(li(),1);var u0=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;var ii="Express";function Rf1(Z){Y0(Z,"auto.http.otel.express");let J=X1(Z).data,$=J["express.type"];if($)Z.setAttribute(U1,`${$}.express`);let X=J["express.name"];if(typeof X==="string")Z.updateName(X)}function Cf1(Z,J){if(d1()===y6())return u0&&R.warn("Isolation scope is still default isolation scope - skipping setting transactionName"),J;if(Z.layerType==="request_handler"){let $=Z.request,X=$.method?$.method.toUpperCase():"GET";d1().setTransactionName(`${X} ${Z.route}`)}return J}var ni=s(ii,()=>new pi.ExpressInstrumentation({requestHook:(Z)=>Rf1(Z),spanNameHook:(Z,J)=>Cf1(Z,J)})),qf1=()=>{return{name:ii,setupOnce(){ni()}}},ai=k(qf1);import*as nD from"diagnostics_channel";var s0=v(u(),1),OG=v(N0(),1),Rn=v(D1(),1),Y4=v(X0(),1);import An from"diagnostics_channel";var Ln=v(Kn(),1);var e3=(Z)=>{if(typeof Z!=="string")throw TypeError("invalid pattern");if(Z.length>65536)throw TypeError("pattern is too long")};var vf1={"[: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]},ZQ=(Z)=>Z.replace(/[[\]\\-]/g,"\\$&"),hf1=(Z)=>Z.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),zn=(Z)=>Z.join(""),Gn=(Z,J)=>{let $=J;if(Z.charAt($)!=="[")throw Error("not in a brace expression");let X=[],Y=[],Q=$+1,W=!1,K=!1,z=!1,G=!1,H=$,V="";Z:while(Q<Z.length){let L=Z.charAt(Q);if((L==="!"||L==="^")&&Q===$+1){G=!0,Q++;continue}if(L==="]"&&W&&!z){H=Q+1;break}if(W=!0,L==="\\"){if(!z){z=!0,Q++;continue}}if(L==="["&&!z){for(let[O,[_,w,A]]of Object.entries(vf1))if(Z.startsWith(O,Q)){if(V)return["$.",!1,Z.length-$,!0];if(Q+=O.length,A)Y.push(_);else X.push(_);K=K||w;continue Z}}if(z=!1,V){if(L>V)X.push(ZQ(V)+"-"+ZQ(L));else if(L===V)X.push(ZQ(L));V="",Q++;continue}if(Z.startsWith("-]",Q+1)){X.push(ZQ(L+"-")),Q+=2;continue}if(Z.startsWith("-",Q+1)){V=L,Q+=2;continue}X.push(ZQ(L)),Q++}if(H<Q)return["",!1,0,!1];if(!X.length&&!Y.length)return["$.",!1,Z.length-$,!0];if(Y.length===0&&X.length===1&&/^\\?.$/.test(X[0])&&!G){let L=X[0].length===2?X[0].slice(-1):X[0];return[hf1(L),!1,H-$,!1]}let F="["+(G?"^":"")+zn(X)+"]",B="["+(G?"":"^")+zn(Y)+"]";return[X.length&&Y.length?"("+F+"|"+B+")":X.length?F:B,K,H-$,!0]};var r7=(Z,{windowsPathsNoEscape:J=!1}={})=>{return J?Z.replace(/\[([^\/\\])\]/g,"$1"):Z.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1")};var ff1=new Set(["!","?","+","*","@"]),Hn=(Z)=>ff1.has(Z),bf1="(?!(?:^|/)\\.\\.?(?:$|/))",LG="(?!\\.)",gf1=new Set(["[","."]),mf1=new Set(["..","."]),uf1=new Set("().*{}+?[]^$\\!"),df1=(Z)=>Z.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),dD="[^/]",Vn=dD+"*?",Fn=dD+"+?";class S4{type;#Z;#J;#Y=!1;#X=[];#Q;#B;#W;#H=!1;#z;#K;#$=!1;constructor(Z,J,$={}){if(this.type=Z,Z)this.#J=!0;if(this.#Q=J,this.#Z=this.#Q?this.#Q.#Z:this,this.#z=this.#Z===this?$:this.#Z.#z,this.#W=this.#Z===this?[]:this.#Z.#W,Z==="!"&&!this.#Z.#H)this.#W.push(this);this.#B=this.#Q?this.#Q.#X.length:0}get hasMagic(){if(this.#J!==void 0)return this.#J;for(let Z of this.#X){if(typeof Z==="string")continue;if(Z.type||Z.hasMagic)return this.#J=!0}return this.#J}toString(){if(this.#K!==void 0)return this.#K;if(!this.type)return this.#K=this.#X.map((Z)=>String(Z)).join("");else return this.#K=this.type+"("+this.#X.map((Z)=>String(Z)).join("|")+")"}#L(){if(this!==this.#Z)throw Error("should only call on root");if(this.#H)return this;this.toString(),this.#H=!0;let Z;while(Z=this.#W.pop()){if(Z.type!=="!")continue;let J=Z,$=J.#Q;while($){for(let X=J.#B+1;!$.type&&X<$.#X.length;X++)for(let Y of Z.#X){if(typeof Y==="string")throw Error("string part in extglob AST??");Y.copyIn($.#X[X])}J=$,$=J.#Q}}return this}push(...Z){for(let J of Z){if(J==="")continue;if(typeof J!=="string"&&!(J instanceof S4&&J.#Q===this))throw Error("invalid part: "+J);this.#X.push(J)}}toJSON(){let Z=this.type===null?this.#X.slice().map((J)=>typeof J==="string"?J:J.toJSON()):[this.type,...this.#X.map((J)=>J.toJSON())];if(this.isStart()&&!this.type)Z.unshift([]);if(this.isEnd()&&(this===this.#Z||this.#Z.#H&&this.#Q?.type==="!"))Z.push({});return Z}isStart(){if(this.#Z===this)return!0;if(!this.#Q?.isStart())return!1;if(this.#B===0)return!0;let Z=this.#Q;for(let J=0;J<this.#B;J++){let $=Z.#X[J];if(!($ instanceof S4&&$.type==="!"))return!1}return!0}isEnd(){if(this.#Z===this)return!0;if(this.#Q?.type==="!")return!0;if(!this.#Q?.isEnd())return!1;if(!this.type)return this.#Q?.isEnd();let Z=this.#Q?this.#Q.#X.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 S4(this.type,Z);for(let $ of this.#X)J.copyIn($);return J}static#D(Z,J,$,X){let Y=!1,Q=!1,W=-1,K=!1;if(J.type===null){let F=$,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(!X.noext&&Hn(U)&&Z.charAt(F)==="("){J.push(B),B="";let L=new S4(U,J);F=S4.#D(Z,L,F,X),J.push(L);continue}B+=U}return J.push(B),F}let z=$+1,G=new S4(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(Hn(F)&&Z.charAt(z)==="("){G.push(V),V="";let B=new S4(F,G);G.push(B),z=S4.#D(Z,B,z,X);continue}if(F==="|"){G.push(V),V="",H.push(G),G=new S4(null,J);continue}if(F===")"){if(V===""&&J.#X.length===0)J.#$=!0;return G.push(V),V="",J.push(...H,G),z}V+=F}return J.type=null,J.#J=void 0,J.#X=[Z.substring($-1)],z}static fromGlob(Z,J={}){let $=new S4(null,void 0,J);return S4.#D(Z,$,0,J),$}toMMPattern(){if(this!==this.#Z)return this.#Z.toMMPattern();let Z=this.toString(),[J,$,X,Y]=this.toRegExpSource();if(!(X||this.#J||this.#z.nocase&&!this.#z.nocaseMagicOnly&&Z.toUpperCase()!==Z.toLowerCase()))return $;let W=(this.#z.nocase?"i":"")+(Y?"u":"");return Object.assign(new RegExp(`^${J}$`,W),{_src:J,_glob:Z})}get options(){return this.#z}toRegExpSource(Z){let J=Z??!!this.#z.dot;if(this.#Z===this)this.#L();if(!this.type){let K=this.isStart()&&this.isEnd(),z=this.#X.map((F)=>{let[B,U,L,O]=typeof F==="string"?S4.#V(F,this.#J,K):F.toRegExpSource(Z);return this.#J=this.#J||L,this.#Y=this.#Y||O,B}).join(""),G="";if(this.isStart()){if(typeof this.#X[0]==="string"){if(!(this.#X.length===1&&mf1.has(this.#X[0]))){let B=gf1,U=J&&B.has(z.charAt(0))||z.startsWith("\\.")&&B.has(z.charAt(2))||z.startsWith("\\.\\.")&&B.has(z.charAt(4)),L=!J&&!Z&&B.has(z.charAt(0));G=U?bf1:L?LG:""}}}let H="";if(this.isEnd()&&this.#Z.#H&&this.#Q?.type==="!")H="(?:$|\\/)";return[G+z+H,r7(z),this.#J=!!this.#J,this.#Y]}let $=this.type==="*"||this.type==="+",X=this.type==="!"?"(?:(?!(?:":"(?:",Y=this.#F(J);if(this.isStart()&&this.isEnd()&&!Y&&this.type!=="!"){let K=this.toString();return this.#X=[K],this.type=null,this.#J=void 0,[K,r7(this.toString()),!1,!1]}let Q=!$||Z||J||!LG?"":this.#F(!0);if(Q===Y)Q="";if(Q)Y=`(?:${Y})(?:${Q})*?`;let W="";if(this.type==="!"&&this.#$)W=(this.isStart()&&!J?LG:"")+Fn;else{let K=this.type==="!"?"))"+(this.isStart()&&!J&&!Z?LG:"")+Vn+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&Q?")":this.type==="*"&&Q?")?":`)${this.type}`;W=X+Y+K}return[W,r7(Y),this.#J=!!this.#J,this.#Y]}#F(Z){return this.#X.map((J)=>{if(typeof J==="string")throw Error("string type in extglob ast??");let[$,X,Y,Q]=J.toRegExpSource(Z);return this.#Y=this.#Y||Q,$}).filter((J)=>!(this.isStart()&&this.isEnd())||!!J).join("|")}static#V(Z,J,$=!1){let X=!1,Y="",Q=!1;for(let W=0;W<Z.length;W++){let K=Z.charAt(W);if(X){X=!1,Y+=(uf1.has(K)?"\\":"")+K;continue}if(K==="\\"){if(W===Z.length-1)Y+="\\\\";else X=!0;continue}if(K==="["){let[z,G,H,V]=Gn(Z,W);if(H){Y+=z,Q=Q||G,W+=H-1,J=J||V;continue}}if(K==="*"){if($&&Z==="*")Y+=Fn;else Y+=Vn;J=!0;continue}if(K==="?"){Y+=dD,J=!0;continue}Y+=df1(K)}return[Y,r7(Z),!!J,Q]}}var cD=(Z,{windowsPathsNoEscape:J=!1}={})=>{return J?Z.replace(/[?*()[\]]/g,"[$&]"):Z.replace(/[?*()[\]\\]/g,"\\$&")};var y4=(Z,J,$={})=>{if(e3(J),!$.nocomment&&J.charAt(0)==="#")return!1;return new JQ(J,$).match(Z)},cf1=/^\*+([^+@!?\*\[\(]*)$/,lf1=(Z)=>(J)=>!J.startsWith(".")&&J.endsWith(Z),pf1=(Z)=>(J)=>J.endsWith(Z),if1=(Z)=>{return Z=Z.toLowerCase(),(J)=>!J.startsWith(".")&&J.toLowerCase().endsWith(Z)},nf1=(Z)=>{return Z=Z.toLowerCase(),(J)=>J.toLowerCase().endsWith(Z)},af1=/^\*+\.\*+$/,of1=(Z)=>!Z.startsWith(".")&&Z.includes("."),rf1=(Z)=>Z!=="."&&Z!==".."&&Z.includes("."),sf1=/^\.\*+$/,tf1=(Z)=>Z!=="."&&Z!==".."&&Z.startsWith("."),ef1=/^\*+$/,Zb1=(Z)=>Z.length!==0&&!Z.startsWith("."),Jb1=(Z)=>Z.length!==0&&Z!=="."&&Z!=="..",$b1=/^\?+([^+@!?\*\[\(]*)?$/,Xb1=([Z,J=""])=>{let $=Dn([Z]);if(!J)return $;return J=J.toLowerCase(),(X)=>$(X)&&X.toLowerCase().endsWith(J)},Yb1=([Z,J=""])=>{let $=On([Z]);if(!J)return $;return J=J.toLowerCase(),(X)=>$(X)&&X.toLowerCase().endsWith(J)},Qb1=([Z,J=""])=>{let $=On([Z]);return!J?$:(X)=>$(X)&&X.endsWith(J)},Wb1=([Z,J=""])=>{let $=Dn([Z]);return!J?$:(X)=>$(X)&&X.endsWith(J)},Dn=([Z])=>{let J=Z.length;return($)=>$.length===J&&!$.startsWith(".")},On=([Z])=>{let J=Z.length;return($)=>$.length===J&&$!=="."&&$!==".."},_n=typeof process==="object"&&process?typeof process.env==="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",Bn={win32:{sep:"\\"},posix:{sep:"/"}},Kb1=_n==="win32"?Bn.win32.sep:Bn.posix.sep;y4.sep=Kb1;var V8=Symbol("globstar **");y4.GLOBSTAR=V8;var zb1="[^/]",Gb1=zb1+"*?",Hb1="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",Vb1="(?:(?!(?:\\/|^)\\.).)*?",Fb1=(Z,J={})=>($)=>y4($,Z,J);y4.filter=Fb1;var H8=(Z,J={})=>Object.assign({},Z,J),Bb1=(Z)=>{if(!Z||typeof Z!=="object"||!Object.keys(Z).length)return y4;let J=y4;return Object.assign((X,Y,Q={})=>J(X,Y,H8(Z,Q)),{Minimatch:class extends J.Minimatch{constructor(Y,Q={}){super(Y,H8(Z,Q))}static defaults(Y){return J.defaults(H8(Z,Y)).Minimatch}},AST:class extends J.AST{constructor(Y,Q,W={}){super(Y,Q,H8(Z,W))}static fromGlob(Y,Q={}){return J.AST.fromGlob(Y,H8(Z,Q))}},unescape:(X,Y={})=>J.unescape(X,H8(Z,Y)),escape:(X,Y={})=>J.escape(X,H8(Z,Y)),filter:(X,Y={})=>J.filter(X,H8(Z,Y)),defaults:(X)=>J.defaults(H8(Z,X)),makeRe:(X,Y={})=>J.makeRe(X,H8(Z,Y)),braceExpand:(X,Y={})=>J.braceExpand(X,H8(Z,Y)),match:(X,Y,Q={})=>J.match(X,Y,H8(Z,Q)),sep:J.sep,GLOBSTAR:V8})};y4.defaults=Bb1;var wn=(Z,J={})=>{if(e3(Z),J.nobrace||!/\{(?:(?!\{).)*\}/.test(Z))return[Z];return Ln.default(Z)};y4.braceExpand=wn;var Ub1=(Z,J={})=>new JQ(Z,J).makeRe();y4.makeRe=Ub1;var Lb1=(Z,J,$={})=>{let X=new JQ(J,$);if(Z=Z.filter((Y)=>X.match(Y)),X.options.nonull&&!Z.length)Z.push(J);return Z};y4.match=Lb1;var Un=/[?*]|[+@!]\(.*?\)|\[|\]/,Db1=(Z)=>Z.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");class JQ{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(Z,J={}){if(e3(Z),J=J||{},this.options=J,this.pattern=Z,this.platform=J.platform||_n,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 $=this.globSet.map((Y)=>this.slashSplit(Y));this.globParts=this.preprocess($),this.debug(this.pattern,this.globParts);let X=this.globParts.map((Y,Q,W)=>{if(this.isWindows&&this.windowsNoMagicRoot){let K=Y[0]===""&&Y[1]===""&&(Y[2]==="?"||!Un.test(Y[2]))&&!Un.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,X),this.set=X.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 $=0;$<Z.length;$++)for(let X=0;X<Z[$].length;X++)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 $=-1;while(($=J.indexOf("**",$+1))!==-1){let X=$;while(J[X+1]==="**")X++;if(X!==$)J.splice($,X-$)}return J})}levelOneOptimize(Z){return Z.map((J)=>{return J=J.reduce(($,X)=>{let Y=$[$.length-1];if(X==="**"&&Y==="**")return $;if(X===".."){if(Y&&Y!==".."&&Y!=="."&&Y!=="**")return $.pop(),$}return $.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 X=1;X<Z.length-1;X++){let Y=Z[X];if(X===1&&Y===""&&Z[0]==="")continue;if(Y==="."||Y==="")J=!0,Z.splice(X,1),X--}if(Z[0]==="."&&Z.length===2&&(Z[1]==="."||Z[1]===""))J=!0,Z.pop()}let $=0;while(($=Z.indexOf("..",$+1))!==-1){let X=Z[$-1];if(X&&X!=="."&&X!==".."&&X!=="**")J=!0,Z.splice($-1,2),$-=2}}while(J);return Z.length===0?[""]:Z}firstPhasePreProcess(Z){let J=!1;do{J=!1;for(let $ of Z){let X=-1;while((X=$.indexOf("**",X+1))!==-1){let Q=X;while($[Q+1]==="**")Q++;if(Q>X)$.splice(X+1,Q-X);let W=$[X+1],K=$[X+2],z=$[X+3];if(W!=="..")continue;if(!K||K==="."||K===".."||!z||z==="."||z==="..")continue;J=!0,$.splice(X,1);let G=$.slice(0);G[X]="**",Z.push(G),X--}if(!this.preserveMultipleSlashes){for(let Q=1;Q<$.length-1;Q++){let W=$[Q];if(Q===1&&W===""&&$[0]==="")continue;if(W==="."||W==="")J=!0,$.splice(Q,1),Q--}if($[0]==="."&&$.length===2&&($[1]==="."||$[1]===""))J=!0,$.pop()}let Y=0;while((Y=$.indexOf("..",Y+1))!==-1){let Q=$[Y-1];if(Q&&Q!=="."&&Q!==".."&&Q!=="**"){J=!0;let K=Y===1&&$[Y+1]==="**"?["."]:[];if($.splice(Y-1,2,...K),$.length===0)$.push("");Y-=2}}}}while(J);return Z}secondPhasePreProcess(Z){for(let J=0;J<Z.length-1;J++)for(let $=J+1;$<Z.length;$++){let X=this.partsMatch(Z[J],Z[$],!this.preserveMultipleSlashes);if(X){Z[J]=[],Z[$]=X;break}}return Z.filter((J)=>J.length)}partsMatch(Z,J,$=!1){let X=0,Y=0,Q=[],W="";while(X<Z.length&&Y<J.length)if(Z[X]===J[Y])Q.push(W==="b"?J[Y]:Z[X]),X++,Y++;else if($&&Z[X]==="**"&&J[Y]===Z[X+1])Q.push(Z[X]),X++;else if($&&J[Y]==="**"&&Z[X]===J[Y+1])Q.push(J[Y]),Y++;else if(Z[X]==="*"&&J[Y]&&(this.options.dot||!J[Y].startsWith("."))&&J[Y]!=="**"){if(W==="b")return!1;W="a",Q.push(Z[X]),X++,Y++}else if(J[Y]==="*"&&Z[X]&&(this.options.dot||!Z[X].startsWith("."))&&Z[X]!=="**"){if(W==="a")return!1;W="b",Q.push(J[Y]),X++,Y++}else return!1;return Z.length===J.length&&Q}parseNegate(){if(this.nonegate)return;let Z=this.pattern,J=!1,$=0;for(let X=0;X<Z.length&&Z.charAt(X)==="!";X++)J=!J,$++;if($)this.pattern=Z.slice($);this.negate=J}matchOne(Z,J,$=!1){let X=this.options;if(this.isWindows){let U=typeof Z[0]==="string"&&/^[a-z]:$/i.test(Z[0]),L=!U&&Z[0]===""&&Z[1]===""&&Z[2]==="?"&&/^[a-z]:$/i.test(Z[3]),O=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=L?3:U?0:void 0,A=_?3:O?0:void 0;if(typeof w==="number"&&typeof A==="number"){let[j,T]=[Z[w],J[A]];if(j.toLowerCase()===T.toLowerCase()){if(J[A]=j,A>w)J=J.slice(A);else if(w>A)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===V8){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]===".."||!X.dot&&Z[Q].charAt(0)===".")return!1;return!0}while(V<K){var B=Z[V];if(this.debug(`
|
|
53
53
|
globstar while`,Z,V,J,F,B),this.matchOne(Z.slice(V),J.slice(F),$))return this.debug("globstar found match!",V,K,B),!0;else{if(B==="."||B===".."||!X.dot&&B.charAt(0)==="."){this.debug("dot detected!",Z,V,J,F);break}this.debug("globstar swallow a segment, and continue"),V++}}if($){if(this.debug(`
|
|
54
|
-
>>> 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 $;else if(W===z)return Q===K-1&&Z[Q]==="";else throw Error("wtf?")}braceExpand(){return wn(this.pattern,this.options)}parse(Z){e3(Z);let J=this.options;if(Z==="**")return V8;if(Z==="")return"";let $,X=null;if($=Z.match(ef1))X=J.dot?Jb1:Zb1;else if($=Z.match(cf1))X=(J.nocase?J.dot?nf1:if1:J.dot?pf1:lf1)($[1]);else if($=Z.match($b1))X=(J.nocase?J.dot?Yb1:Xb1:J.dot?Qb1:Wb1)($);else if($=Z.match(af1))X=J.dot?rf1:of1;else if($=Z.match(sf1))X=tf1;let Y=S4.fromGlob(Z,this.options).toMMPattern();if(X&&typeof Y==="object")Reflect.defineProperty(Y,"test",{value:X});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,$=J.noglobstar?Gb1:J.dot?Hb1:Vb1,X=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(""))X.add(H);return typeof G==="string"?Db1(G):G===V8?V8:G._src});return z.forEach((G,H)=>{let V=z[H+1],F=z[H-1];if(G!==V8||F===V8)return;if(F===void 0)if(V!==void 0&&V!==V8)z[H+1]="(?:\\/|"+$+"\\/)?"+V;else z[H]=$;else if(V===void 0)z[H-1]=F+"(?:\\/|"+$+")?";else if(V!==V8)z[H-1]=F+"(?:\\/|\\/"+$+"\\/)"+V,z[H+1]=V8}),z.filter((G)=>G!==V8).join("/")}).join("|"),[Q,W]=Z.length>1?["(?:",")"]:["",""];if(Y="^"+Q+Y+W+"$",this.negate)Y="^(?!"+Y+").+$";try{this.regexp=new RegExp(Y,[...X].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 $=this.options;if(this.isWindows)Z=Z.split("\\").join("/");let X=this.slashSplit(Z);this.debug(this.pattern,"split",X);let Y=this.set;this.debug(this.pattern,"set",Y);let Q=X[X.length-1];if(!Q)for(let W=X.length-2;!Q&&W>=0;W--)Q=X[W];for(let W=0;W<Y.length;W++){let K=Y[W],z=X;if($.matchBase&&K.length===1)z=[Q];if(this.matchOne(z,K,J)){if($.flipNegate)return!0;return!this.negate}}if($.flipNegate)return!1;return this.negate}static defaults(Z){return y4.defaults(Z).Minimatch}}y4.AST=S4;y4.Minimatch=JQ;y4.escape=cD;y4.unescape=r7;var Tn="@fastify/otel",_b1="0.8.0",wb1=">=4.0.0 <6",Mn=["onRequest","preParsing","preValidation","preHandler","preSerialization","onSend","onResponse","onError"],L0={HOOK_NAME:"hook.name",FASTIFY_TYPE:"fastify.type",HOOK_CALLBACK_NAME:"hook.callback.name",ROOT:"fastify.root"},s7={ROUTE:"route-hook",INSTANCE:"hook",HANDLER:"request-handler"},R9="anonymous",$6=Symbol("fastify otel instance"),t7=Symbol("fastify otel request spans"),$Q=Symbol("fastify otel request context"),jn=Symbol("fastify otel addhook original"),Nn=Symbol("fastify otel setnotfound original"),DG=Symbol("fastify otel ignore path");class lD extends Rn.InstrumentationBase{constructor(Z){super(Tn,_b1,Z);if(this.servername=Z?.servername??process.env.OTEL_SERVICE_NAME??"fastify",this[DG]=null,this._logger=s0.diag.createComponentLogger({namespace:Tn}),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 $=y4;this[DG]=(X)=>{if(typeof J==="function")return J(X);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)},An.subscribe("fastify.initialization",this._handleInitialization)}return super.enable()}disable(){if(this._handleInitialization)An.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:wb1,name:"@fastify/otel"},J;function J($,X,Y){$.decorate($6,Z),$.decorate(jn,$.addHook),$.decorate(Nn,$.setNotFoundHandler),$.decorateRequest("opentelemetry",function(){let V=this[$Q];return{span:this[t7],tracer:Z.tracer,context:V,inject:(B,U)=>{return s0.propagation.inject(V,B,U)},extract:(B,U)=>{return s0.propagation.extract(V,B,U)}}}),$.decorateRequest(t7,null),$.decorateRequest($Q,null),$.addHook("onRoute",function(H){if(Z[DG]?.(H)===!0){Z._logger.debug(`Ignoring route instrumentation ${H.method} ${H.url} because it matches the ignore path`);return}for(let V of Mn)if(H[V]!=null){let F=H[V];if(typeof F==="function")H[V]=G(F,{[Y4.ATTR_SERVICE_NAME]:$[$6].servername,[L0.HOOK_NAME]:`${this.pluginName} - route -> ${V}`,[L0.FASTIFY_TYPE]:s7.ROUTE,[Y4.ATTR_HTTP_ROUTE]:H.url,[L0.HOOK_CALLBACK_NAME]:F.name?.length>0?F.name:R9});else if(Array.isArray(F)){let B=[];for(let U of F)B.push(G(U,{[Y4.ATTR_SERVICE_NAME]:$[$6].servername,[L0.HOOK_NAME]:`${this.pluginName} - route -> ${V}`,[L0.FASTIFY_TYPE]:s7.ROUTE,[Y4.ATTR_HTTP_ROUTE]:H.url,[L0.HOOK_CALLBACK_NAME]:U.name?.length>0?U.name:R9}));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,{[Y4.ATTR_SERVICE_NAME]:$[$6].servername,[L0.HOOK_NAME]:`${this.pluginName} - route-handler`,[L0.FASTIFY_TYPE]:s7.HANDLER,[Y4.ATTR_HTTP_ROUTE]:H.url,[L0.HOOK_CALLBACK_NAME]:H.handler.name.length>0?H.handler.name:R9})}),$.addHook("onRequest",function(H,V,F){if(this[$6].isEnabled()===!1)return F();else if(this[$6][DG]?.({url:H.url,method:H.method})===!0)return this[$6]._logger.debug(`Ignoring request ${H.method} ${H.url} because it matches the ignore path`),F();let B=s0.context.active();if(s0.trace.getSpan(B)==null)B=s0.propagation.extract(B,H.headers);let U=OG.getRPCMetadata(B);if(H.routeOptions.url!=null&&U?.type===OG.RPCType.HTTP)U.route=H.routeOptions.url;let L=this[$6].tracer.startSpan("request",{attributes:{[Y4.ATTR_SERVICE_NAME]:$[$6].servername,[L0.ROOT]:"@fastify/otel",[Y4.ATTR_HTTP_ROUTE]:H.url,[Y4.ATTR_HTTP_REQUEST_METHOD]:H.method}},B);H[$Q]=s0.trace.setSpan(B,L),H[t7]=L,s0.context.with(H[$Q],()=>{F()})}),$.addHook("onResponse",function(H,V,F){let B=H[t7];if(B!=null)B.setStatus({code:s0.SpanStatusCode.OK,message:"OK"}),B.setAttributes({[Y4.ATTR_HTTP_RESPONSE_STATUS_CODE]:404}),B.end();H[t7]=null,F()}),$.addHook=K,$.setNotFoundHandler=z,Y();function Q(H,V,F,B){let U=H[t7];if(U!=null){if(V.statusCode<500)U.setStatus({code:s0.SpanStatusCode.OK,message:"OK"});U.setAttributes({[Y4.ATTR_HTTP_RESPONSE_STATUS_CODE]:V.statusCode}),U.end()}H[t7]=null,B(null,F)}function W(H,V,F,B){let U=H[t7];if(U!=null)U.setStatus({code:s0.SpanStatusCode.ERROR,message:F.message}),U.recordException(F);B()}function K(H,V){let F=this[jn];if(Mn.includes(H))return F.call(this,H,G(V,{[Y4.ATTR_SERVICE_NAME]:$[$6].servername,[L0.HOOK_NAME]:`${this.pluginName} - ${H}`,[L0.FASTIFY_TYPE]:s7.INSTANCE,[L0.HOOK_CALLBACK_NAME]:V.name?.length>0?V.name:R9}));else return F.call(this,H,V)}function z(H,V){let F=this[Nn];if(typeof H==="function")V=G(H,{[Y4.ATTR_SERVICE_NAME]:$[$6].servername,[L0.HOOK_NAME]:`${this.pluginName} - not-found-handler`,[L0.FASTIFY_TYPE]:s7.INSTANCE,[L0.HOOK_CALLBACK_NAME]:H.name?.length>0?H.name:R9}),F.call(this,V);else{if(H.preValidation!=null)H.preValidation=G(H.preValidation,{[Y4.ATTR_SERVICE_NAME]:$[$6].servername,[L0.HOOK_NAME]:`${this.pluginName} - not-found-handler - preValidation`,[L0.FASTIFY_TYPE]:s7.INSTANCE,[L0.HOOK_CALLBACK_NAME]:H.preValidation.name?.length>0?H.preValidation.name:R9});if(H.preHandler!=null)H.preHandler=G(H.preHandler,{[Y4.ATTR_SERVICE_NAME]:$[$6].servername,[L0.HOOK_NAME]:`${this.pluginName} - not-found-handler - preHandler`,[L0.FASTIFY_TYPE]:s7.INSTANCE,[L0.HOOK_CALLBACK_NAME]:H.preHandler.name?.length>0?H.preHandler.name:R9});V=G(V,{[Y4.ATTR_SERVICE_NAME]:$[$6].servername,[L0.HOOK_NAME]:`${this.pluginName} - not-found-handler`,[L0.FASTIFY_TYPE]:s7.INSTANCE,[L0.HOOK_CALLBACK_NAME]:V.name?.length>0?V.name:R9}),F.call(this,H,V)}}function G(H,V={}){return function(...B){let U=this[$6],[L]=B;if(U.isEnabled()===!1)return H.call(this,...B);let O=L[$Q]??s0.context.active(),_=U.tracer.startSpan(`handler - ${H.name?.length>0?H.name:this.pluginName??R9}`,{attributes:V},O);return s0.context.with(s0.trace.setSpan(O,_),function(){try{let w=H.call(this,...B);if(typeof w?.then==="function")return w.then((A)=>{return _.end(),A},(A)=>{return _.setStatus({code:s0.SpanStatusCode.ERROR,message:A.message}),_.recordException(A),_.end(),Promise.reject(A)});return _.end(),w}catch(w){throw _.setStatus({code:s0.SpanStatusCode.ERROR,message:w.message}),_.recordException(w),_.end(),w}},this)}}}}}var Z5=v(u(),1),wG=v(N0(),1),AJ=v(D1(),1),In=v(X0(),1);var C9;(function(Z){Z.FASTIFY_NAME="fastify.name";let $="fastify.type";Z.FASTIFY_TYPE=$;let X="hook.name";Z.HOOK_NAME=X;let Y="plugin.name";Z.PLUGIN_NAME=Y})(C9||(C9={}));var XQ;(function(Z){Z.MIDDLEWARE="middleware";let $="request_handler";Z.REQUEST_HANDLER=$})(XQ||(XQ={}));var YQ;(function(Z){Z.MIDDLEWARE="middleware";let $="request handler";Z.REQUEST_HANDLER=$})(YQ||(YQ={}));var qn=v(u(),1);var QQ=Symbol("opentelemetry.instrumentation.fastify.request_active_span");function pD(Z,J,$,X={}){let Y=J.startSpan($,{attributes:X}),Q=Z[QQ]||[];return Q.push(Y),Object.defineProperty(Z,QQ,{enumerable:!1,configurable:!0,value:Q}),Y}function _G(Z,J){let $=Z[QQ]||[];if(!$.length)return;$.forEach((X)=>{if(J)X.setStatus({code:qn.SpanStatusCode.ERROR,message:J.message}),X.recordException(J);X.end()}),delete Z[QQ]}function En(Z,J,$){let X,Y=void 0;try{if(Y=Z(),Cn(Y))Y.then((Q)=>J(void 0,Q),(Q)=>J(Q))}catch(Q){X=Q}finally{if(!Cn(Y)){if(J(X,Y),X)throw X}return Y}}function Cn(Z){return typeof Z==="object"&&Z&&typeof Object.getOwnPropertyDescriptor(Z,"then")?.value==="function"||!1}var Ab1="0.1.0",Tb1="@sentry/instrumentation-fastify-v3",Pn="anonymous",Mb1=new Set(["onTimeout","onRequest","preParsing","preValidation","preSerialization","preHandler","onSend","onResponse","onError"]);class iD extends AJ.InstrumentationBase{constructor(Z={}){super(Tb1,Ab1,Z)}init(){return[new AJ.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(X,"send",Z._patchSend());let Q=$,W=wG.getRPCMetadata(Z5.context.active()),K=Q.routeOptions?Q.routeOptions.url:$.routerPath;if(K&&W?.type===wG.RPCType.HTTP)W.route=K;let z=$.method||"GET";d1().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 $.apply(this,Q);let W=$.name||Z||Pn,K=`${YQ.MIDDLEWARE} - ${W}`,z=Q[1],G=pD(z,Y.tracer,K,{[C9.FASTIFY_TYPE]:XQ.MIDDLEWARE,[C9.PLUGIN_NAME]:Z,[C9.HOOK_NAME]:J}),H=X&&Q[Q.length-1];if(H)Q[Q.length-1]=function(...V){_G(z),H.apply(this,V)};return Z5.context.with(Z5.trace.setSpan(Z5.context.active(),G),()=>{return En(()=>{return $.apply(this,Q)},(V)=>{if(V instanceof Error)G.setStatus({code:Z5.SpanStatusCode.ERROR,message:V.message}),G.recordException(V);if(!X)_G(z)})})}}_wrapAddHook(){let Z=this;return this._diag.debug("Patching fastify server.addHook function"),function(J){return function(...X){let Y=X[0],Q=X[1],W=this.pluginName;if(!Mb1.has(Y))return J.apply(this,X);let K=typeof X[X.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,X);return Y.addHook("onRequest",J._hookOnRequest()),Y.addHook("preHandler",J._hookPreHandler()),jb1(),J._wrap(Y,"addHook",J._wrapAddHook()),Y}if(Z.errorCodes!==void 0)$.errorCodes=Z.errorCodes;return $.fastify=$,$.default=$,$}_patchSend(){let Z=this;return this._diag.debug("Patching fastify reply.send function"),function($){return function(...Y){let Q=Y[0];if(!Z.isEnabled())return $.apply(this,Y);return AJ.safeExecuteInTheMiddle(()=>{return $.apply(this,Y)},(W)=>{if(!W&&Q instanceof Error)W=Q;_G(this,W)})}}}_hookPreHandler(){let Z=this;return this._diag.debug("Patching fastify preHandler function"),function($,X,Y){if(!Z.isEnabled())return Y();let Q=$,W=Q.routeOptions?.handler||Q.context?.handler,K=W?.name.startsWith("bound ")?W.name.substring(6):W?.name,z=`${YQ.REQUEST_HANDLER} - ${K||this.pluginName||Pn}`,G={[C9.PLUGIN_NAME]:this.pluginName,[C9.FASTIFY_TYPE]:XQ.REQUEST_HANDLER,[In.SEMATTRS_HTTP_ROUTE]:Q.routeOptions?Q.routeOptions.url:$.routerPath};if(K)G[C9.FASTIFY_NAME]=K;let H=pD(X,Z.tracer,z,G);Sn(H);let{requestHook:V}=Z.getConfig();if(V)AJ.safeExecuteInTheMiddle(()=>V(H,{request:$}),(F)=>{if(F)Z._diag.error("request hook failed",F)},!0);return Z5.context.with(Z5.trace.setSpan(Z5.context.active(),H),()=>{Y()})}}}function jb1(){let Z=p();if(Z)Z.on("spanStart",(J)=>{Sn(J)})}function Sn(Z){let J=X1(Z).data,$=J["fastify.type"];if(J[U1]||!$)return;Z.setAttributes({[W1]:"auto.http.otel.fastify",[U1]:`${$}.fastify`});let X=J["fastify.name"]||J["plugin.name"]||J["hook.name"];if(typeof X==="string"){let Y=X.replace(/^fastify -> /,"").replace(/^@fastify\/otel -> /,"");Z.updateName(Y)}}var AG="Fastify",kn=s(`${AG}.v3`,()=>new iD);function Nb1(){let Z=p();if(!Z)return;else return Z.getIntegrationByName(AG)}function yn(Z,J,$,X){let Y=Nb1()?.getShouldHandleError()||hn;if(X==="diagnostics-channel")this.diagnosticsChannelExists=!0;if(this.diagnosticsChannelExists&&X==="onError-hook"){u0&&R.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,$))O1(Z,{mechanism:{handled:!1,type:"auto.function.fastify"}})}var xn=s(`${AG}.v5`,()=>{let Z=new lD,J=Z.plugin();return nD.subscribe("fastify.initialization",($)=>{let X=$.fastify;X?.register(J).after((Y)=>{if(Y)u0&&R.error("Failed to setup Fastify instrumentation",Y);else if(Cb1(),X)qb1(X)})}),nD.subscribe("tracing:fastify.request.handler:error",($)=>{let{error:X,request:Y,reply:Q}=$;yn.call(yn,X,Y,Q,"diagnostics-channel")}),Z}),Rb1=({shouldHandleError:Z})=>{let J;return{name:AG,setupOnce(){J=Z||hn,kn(),xn()},getShouldHandleError(){return J},setShouldHandleError($){J=$}}},vn=k((Z={})=>Rb1(Z));function hn(Z,J,$){let X=$.statusCode;return X>=500||X<=299}function fn(Z){let J=X1(Z),$=J.description,X=J.data,Y=X["fastify.type"],Q=Y==="hook",W=Y===$?.startsWith("handler -"),K=$==="request"||Y==="request-handler";if(X[U1]||!W&&!K&&!Q)return;let z=Q?"hook":W?"middleware":K?"request-handler":"<unknown>";Z.setAttributes({[W1]:"auto.http.otel.fastify",[U1]:`${z}.fastify`});let G=X["fastify.name"]||X["plugin.name"]||X["hook.name"];if(typeof G==="string"){let H=G.replace(/^fastify -> /,"").replace(/^@fastify\/otel -> /,"");Z.updateName(H)}}function Cb1(){let Z=p();if(Z)Z.on("spanStart",(J)=>{fn(J)})}function qb1(Z){Z.addHook("onRequest",async(J,$)=>{if(J.opentelemetry){let{span:Q}=J.opentelemetry();if(Q)fn(Q)}let X=J.routeOptions?.url,Y=J.method||"GET";d1().setTransactionName(`${Y} ${X}`)})}var Ta=v(u(),1),Ma=v(Aa(),1);var ja="Graphql",Na=s(ja,Ma.GraphQLInstrumentation,(Z)=>{let J=Ca(Z);return{...J,responseHook($,X){if(Y0($,"auto.graphql.otel.graphql"),X.errors?.length&&!X1($).status)$.setStatus({code:Ta.SpanStatusCode.ERROR});let Q=X1($).data,W=Q["graphql.operation.type"],K=Q["graphql.operation.name"];if(J.useOperationNameForRootSpan&&W){let z=g0($),H=X1(z).data[$X]||[],V=K?`${W} ${K}`:`${W}`;if(Array.isArray(H))H.push(V),z.setAttribute($X,H);else if(typeof H==="string")z.setAttribute($X,[H,V]);else z.setAttribute($X,V);if(!X1(z).data["original-description"])z.setAttribute("original-description",X1(z).description);z.updateName(`${X1(z).data["original-description"]} (${Xg1(H)})`)}}}}),$g1=(Z={})=>{return{name:ja,setupOnce(){Na(Ca(Z))}}},Ra=k($g1);function Ca(Z){return{ignoreResolveSpans:!0,ignoreTrivialResolveSpans:!0,useOperationNameForRootSpan:!0,...Z}}function Xg1(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 oa=v(aa(),1);var ra="Kafka",sa=s(ra,()=>new oa.KafkaJsInstrumentation({consumerHook(Z){Y0(Z,"auto.kafkajs.otel.consumer")},producerHook(Z){Y0(Z,"auto.kafkajs.otel.producer")}})),jg1=()=>{return{name:ra,setupOnce(){sa()}}},ta=k(jg1);var Ho=v(Go(),1);var Vo="LruMemoizer",Fo=s(Vo,()=>new Ho.LruMemoizerInstrumentation),qg1=()=>{return{name:Vo,setupOnce(){Fo()}}},Bo=k(qg1);var Io=v(Po(),1);var So="Mongo",yo=s(So,()=>new Io.MongoDBInstrumentation({dbStatementSerializer:cg1,responseHook(Z){Y0(Z,"auto.db.otel.mongo")}}));function cg1(Z){let J=WO(Z);return JSON.stringify(J)}function WO(Z){if(Array.isArray(Z))return Z.map((J)=>WO(J));if(lg1(Z)){let J={};return Object.entries(Z).map(([$,X])=>[$,WO(X)]).reduce(($,X)=>{if(ig1(X))$[X[0]]=X[1];return $},J)}return"?"}function lg1(Z){return typeof Z==="object"&&Z!==null&&!pg1(Z)}function pg1(Z){let J=!1;if(typeof Buffer<"u")J=Buffer.isBuffer(Z);return J}function ig1(Z){return Array.isArray(Z)}var ng1=()=>{return{name:So,setupOnce(){yo()}}},ko=k(ng1);var Zr=v(eo(),1);var Jr="Mongoose",$r=s(Jr,()=>new Zr.MongooseInstrumentation({responseHook(Z){Y0(Z,"auto.db.otel.mongoose")}})),Um1=()=>{return{name:Jr,setupOnce(){$r()}}},Xr=k(Um1);var Ar=v(wr(),1);var Tr="Mysql",Mr=s(Tr,()=>new Ar.MySQLInstrumentation({})),gm1=()=>{return{name:Tr,setupOnce(){Mr()}}},jr=k(gm1);var dr=v(ur(),1);var cr="Mysql2",lr=s(cr,()=>new dr.MySQL2Instrumentation({responseHook(Z){Y0(Z,"auto.db.otel.mysql2")}})),Bu1=()=>{return{name:cr,setupOnce(){lr()}}},pr=k(Bu1);var ls=v(Hs(),1),ps=v(gs(),1);var ou1=["get","set","setex"],EO=["get","mget"],ru1=["set","setex"];function LQ(Z,J){return Z.includes(J.toLowerCase())}function PO(Z){if(LQ(EO,Z))return"cache.get";else if(LQ(ru1,Z))return"cache.put";else return}function su1(Z,J){return J.some(($)=>Z.startsWith($))}function us(Z,J){try{if(J.length===0)return;let $=(Y)=>{if(typeof Y==="string"||typeof Y==="number"||Buffer.isBuffer(Y))return[Y.toString()];else if(Array.isArray(Y))return ms(Y.map((Q)=>$(Q)));else return["<unknown>"]},X=J[0];if(LQ(ou1,Z)&&X!=null)return $(X);return ms(J.map((Y)=>$(Y)))}catch{return}}function ds(Z,J,$){if(!PO(Z))return!1;for(let X of J)if(su1(X,$))return!0;return!1}function cs(Z){let J=($)=>{try{if(Buffer.isBuffer($))return $.byteLength;else if(typeof $==="string")return $.length;else if(typeof $==="number")return $.toString().length;else if($===null||$===void 0)return 0;return JSON.stringify($).length}catch{return}};return Array.isArray(Z)?Z.reduce(($,X)=>{let Y=J(X);return typeof Y==="number"?$!==void 0?$+Y:Y:$},0):J(Z)}function ms(Z){let J=[],$=(X)=>{X.forEach((Y)=>{if(Array.isArray(Y))$(Y);else J.push(Y)})};return $(Z),J}var vG="Redis",DQ={},is=(Z,J,$,X)=>{Z.setAttribute(W1,"auto.db.otel.redis");let Y=us(J,$),Q=PO(J);if(!Y||!Q||!DQ.cachePrefixes||!ds(J,Y,DQ.cachePrefixes))return;let W=X1(Z).data["net.peer.name"],K=X1(Z).data["net.peer.port"];if(K&&W)Z.setAttributes({"network.peer.address":W,"network.peer.port":K});let z=cs(X);if(z)Z.setAttribute(wL,z);if(LQ(EO,J)&&z!==void 0)Z.setAttribute(OL,z>0);Z.setAttributes({[U1]:Q,[_L]:Y});let G=Y.join(", ");Z.updateName(DQ.maxCacheKeyLength?M7(G,DQ.maxCacheKeyLength):G)},tu1=s(`${vG}.IORedis`,()=>{return new ls.IORedisInstrumentation({responseHook:is})}),eu1=s(`${vG}.Redis`,()=>{return new ps.RedisInstrumentation({responseHook:is})}),ns=Object.assign(()=>{tu1(),eu1()},{id:vG}),Zd1=(Z={})=>{return{name:vG,setupOnce(){DQ=Z,ns()}}},as=k(Zd1);var Nt=v(jt(),1);var Rt="Postgres",Ct=s(Rt,()=>new Nt.PgInstrumentation({requireParentSpan:!0,requestHook(Z){Y0(Z,"auto.db.otel.postgres")}})),id1=()=>{return{name:Rt,setupOnce(){Ct()}}},qt=k(id1);var jX=v(u(),1),I9=v(D1(),1),t0=v(X0(),1);var dG="PostgresJs",Et=[">=3.0.0 <4"],nd1=/^(SELECT|INSERT|UPDATE|DELETE|CREATE|DROP|ALTER)/i,uG=Symbol("sentryPostgresConnectionContext"),hO=Symbol.for("sentry.instrumented.postgresjs"),Pt=Symbol.for("sentry.query.from.instrumented.sql"),It=s(dG,(Z)=>new St({requireParentSpan:Z?.requireParentSpan??!0,requestHook:Z?.requestHook}));class St extends I9.InstrumentationBase{constructor(Z){super("sentry-postgres-js",u1,Z)}init(){let Z=new I9.InstrumentationNodeModuleDefinition("postgres",Et,(J)=>{try{return this._patchPostgres(J)}catch($){return u0&&R.error("Failed to patch postgres module:",$),J}},(J)=>J);return["src","cf/src","cjs/src"].forEach((J)=>{Z.files.push(new I9.InstrumentationNodeModuleFile(`postgres/${J}/query.js`,Et,this._patchQueryPrototype.bind(this),this._unpatchQueryPrototype.bind(this)))}),Z}_patchPostgres(Z){let J=typeof Z==="function",$=J?Z:Z.default;if(typeof $!=="function")return u0&&R.warn("postgres module does not export a function. Skipping instrumentation."),Z;let X=this,Y=function(...Q){let W=Reflect.construct($,Q);if(!W||typeof W!=="function")return u0&&R.warn("postgres() did not return a valid instance"),W;return X._instrumentSqlInstance(W)};Object.setPrototypeOf(Y,$),Object.setPrototypeOf(Y.prototype,$.prototype);for(let Q of Object.getOwnPropertyNames($))if(!["length","name","prototype"].includes(Q)){let W=Object.getOwnPropertyDescriptor($,Q);if(W)Object.defineProperty(Y,Q,W)}if(J)return Y;else return q3(Z,"default",Y),Z}_wrapQueryMethod(Z,J,$){let X=this;return function(...Y){let Q=Reflect.apply(Z,J,Y);if(Q&&typeof Q==="object"&&"handle"in Q)X._wrapSingleQueryHandle(Q,$);return Q}}_wrapCallbackMethod(Z,J,$){let X=this;return function(...Y){let Q=$[uG];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 X._instrumentSqlInstance(V,Q)});return H}let K=Y.length===1?Y[0]:Y[1],z=function(H){let V=X._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(t0.ATTR_DB_NAMESPACE,J.ATTR_DB_NAMESPACE);if(J.ATTR_SERVER_ADDRESS)Z.setAttribute(t0.ATTR_SERVER_ADDRESS,J.ATTR_SERVER_ADDRESS);if(J.ATTR_SERVER_PORT!==void 0){let $=parseInt(J.ATTR_SERVER_PORT,10);if(!isNaN($))Z.setAttribute(t0.ATTR_SERVER_PORT,$)}}_setOperationName(Z,J,$){if($){Z.setAttribute(t0.ATTR_DB_OPERATION_NAME,$);return}let X=J?.match(nd1);if(X?.[1])Z.setAttribute(t0.ATTR_DB_OPERATION_NAME,X[1].toUpperCase())}_attachConnectionContext(Z,J){let $=Z;if(!$.options||typeof $.options!=="object")return;let X=$.options,Y=X.host?.[0]||"localhost",Q=X.port?.[0]||5432,W={ATTR_DB_NAMESPACE:typeof X.database==="string"&&X.database!==""?X.database:void 0,ATTR_SERVER_ADDRESS:Y,ATTR_SERVER_PORT:String(Q)};J[uG]=W}_instrumentSqlInstance(Z,J){if(Z[hO])return Z;let $=this,X=new Proxy(Z,{apply(Y,Q,W){let K=Reflect.apply(Y,Q,W);if(K&&typeof K==="object"&&"handle"in K)$._wrapSingleQueryHandle(K,X);return K},get(Y,Q){let W=Y[Q];if(typeof Q!=="string"||typeof W!=="function")return W;if(Q==="unsafe"||Q==="file")return $._wrapQueryMethod(W,Y,X);if(Q==="begin"||Q==="reserve")return $._wrapCallbackMethod(W,Y,X);return W}});if(J)X[uG]=J;else this._attachConnectionContext(Z,X);return Z[hO]=!0,X[hO]=!0,X}_wrapSingleQueryHandle(Z,J){if(Z.handle?.__sentryWrapped)return;Z[Pt]=!0;let $=Z.handle,X=this,Y=async function(...Q){if(!X._shouldCreateSpans())return $.apply(this,Q);let W=X._reconstructQuery(Z.strings),K=X._sanitizeSqlQuery(W);return P4({name:K||"postgresjs.query",op:"db"},(z)=>{Y0(z,"auto.db.postgresjs"),z.setAttributes({[t0.ATTR_DB_SYSTEM_NAME]:"postgres",[t0.ATTR_DB_QUERY_TEXT]:K});let G=J?J[uG]:void 0;X._setConnectionAttributes(z,G);let H=X.getConfig(),{requestHook:V}=H;if(V)I9.safeExecuteInTheMiddle(()=>V(z,K,G),(B)=>{if(B)z.setAttribute("sentry.hook.error","requestHook failed"),u0&&R.error(`Error in requestHook for ${dG} integration:`,B)},!0);let F=this;F.resolve=new Proxy(F.resolve,{apply:(B,U,L)=>{try{X._setOperationName(z,K,L?.[0]?.command),z.end()}catch(O){u0&&R.error("Error ending span in resolve callback:",O)}return Reflect.apply(B,U,L)}}),F.reject=new Proxy(F.reject,{apply:(B,U,L)=>{try{z.setStatus({code:v1,message:L?.[0]?.message||"unknown_error"}),z.setAttribute(t0.ATTR_DB_RESPONSE_STATUS_CODE,L?.[0]?.code||"unknown"),z.setAttribute(t0.ATTR_ERROR_TYPE,L?.[0]?.name||"unknown"),X._setOperationName(z,K),z.end()}catch(O){u0&&R.error("Error ending span in reject callback:",O)}return Reflect.apply(B,U,L)}});try{return $.apply(this,Q)}catch(B){throw z.setStatus({code:v1,message:B instanceof Error?B.message:"unknown_error"}),z.end(),B}})};Y.__sentryWrapped=!0,Z.handle=Y}_shouldCreateSpans(){let Z=this.getConfig();return jX.trace.getSpan(jX.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)=>X===0?$:`${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,$=Z.Query.prototype.handle;return Z.Query.prototype.handle=async function(...X){if(this[Pt])return $.apply(this,X);if(!J._shouldCreateSpans())return $.apply(this,X);let Y=J._reconstructQuery(this.strings),Q=J._sanitizeSqlQuery(Y);return P4({name:Q||"postgresjs.query",op:"db"},(W)=>{Y0(W,"auto.db.postgresjs"),W.setAttributes({[t0.ATTR_DB_SYSTEM_NAME]:"postgres",[t0.ATTR_DB_QUERY_TEXT]:Q});let K=J.getConfig(),{requestHook:z}=K;if(z)I9.safeExecuteInTheMiddle(()=>z(W,Q,void 0),(V)=>{if(V)W.setAttribute("sentry.hook.error","requestHook failed"),u0&&R.error(`Error in requestHook for ${dG} 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){u0&&R.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:v1,message:B?.[0]?.message||"unknown_error"}),W.setAttribute(t0.ATTR_DB_RESPONSE_STATUS_CODE,B?.[0]?.code||"unknown"),W.setAttribute(t0.ATTR_ERROR_TYPE,B?.[0]?.name||"unknown"),J._setOperationName(W,Q),W.end()}catch(U){u0&&R.error("Error ending span in reject callback:",U)}return Reflect.apply(V,F,B)}});try{return $.apply(this,X)}catch(V){throw W.setStatus({code:v1,message:V instanceof Error?V.message:"unknown_error"}),W.end(),V}})},Z.Query.prototype.handle.__sentry_original__=$,Z}_unpatchQueryPrototype(Z){if(Z.Query.prototype.handle.__sentry_original__)Z.Query.prototype.handle=Z.Query.prototype.handle.__sentry_original__;return Z}}var ad1=(Z)=>{return{name:dG,setupOnce(){It(Z)}}},yt=k(ad1);var O8=v(u(),1);var vt=v(u(),1),cG=v(D1(),1),XZ=v(u(),1);var od1=process.env.PRISMA_SHOW_ALL_TRACES==="true",rd1="00-10-10-00";function sd1(Z){switch(Z){case"client":return XZ.SpanKind.CLIENT;case"internal":default:return XZ.SpanKind.INTERNAL}}var td1=class{tracerProvider;ignoreSpanTypes;constructor({tracerProvider:Z,ignoreSpanTypes:J}){this.tracerProvider=Z,this.ignoreSpanTypes=J}isEnabled(){return!0}getTraceParent(Z){let J=XZ.trace.getSpanContext(Z??XZ.context.active());if(J)return`00-${J.traceId}-${J.spanId}-0${J.traceFlags}`;return rd1}dispatchEngineSpans(Z){let J=this.tracerProvider.getTracer("prisma"),$=new Map,X=Z.filter((Y)=>Y.parentId===null);for(let Y of X)ht(J,Y,Z,$,this.ignoreSpanTypes)}getActiveContext(){return XZ.context.active()}runInChildSpan(Z,J){if(typeof Z==="string")Z={name:Z};if(Z.internal&&!od1)return J();let $=this.tracerProvider.getTracer("prisma"),X=Z.context??this.getActiveContext(),Y=`prisma:client:${Z.name}`;if(ft(Y,this.ignoreSpanTypes))return J();if(Z.active===!1){let Q=$.startSpan(Y,Z,X);return kt(Q,J(Q,X))}return $.startActiveSpan(Y,Z,(Q)=>kt(Q,J(Q,X)))}};function ht(Z,J,$,X,Y){if(ft(J.name,Y))return;let Q={attributes:J.attributes,kind:sd1(J.kind),startTime:J.startTime};Z.startActiveSpan(J.name,Q,(W)=>{if(X.set(J.id,W.spanContext().spanId),J.links)W.addLinks(J.links.flatMap((z)=>{let G=X.get(z);if(!G)return[];return{context:{spanId:G,traceId:W.spanContext().traceId,traceFlags:W.spanContext().traceFlags}}}));let K=$.filter((z)=>z.parentId===J.id);for(let z of K)ht(Z,z,$,X,Y);W.end(J.endTime)})}function kt(Z,J){if(ed1(J))return J.then(($)=>{return Z.end(),$},($)=>{throw Z.end(),$});return Z.end(),J}function ed1(Z){return Z!=null&&typeof Z.then==="function"}function ft(Z,J){return J.some(($)=>typeof $==="string"?$===Z:$.test(Z))}var bt={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},bO=bt.version,Zc1=bO.split(".")[0],xt="PRISMA_INSTRUMENTATION",fO=`V${Zc1}_PRISMA_INSTRUMENTATION`,Jc1=bt.name,$c1="@prisma/client",gt=class extends cG.InstrumentationBase{tracerProvider;constructor(Z={}){super(Jc1,bO,Z)}setTracerProvider(Z){this.tracerProvider=Z}init(){return[new cG.InstrumentationNodeModuleDefinition($c1,[bO])]}enable(){let Z=this._config,J={helper:new td1({tracerProvider:this.tracerProvider??vt.trace.getTracerProvider(),ignoreSpanTypes:Z.ignoreSpanTypes??[]})};global[xt]=J,global[fO]=J}disable(){delete global[xt],delete global[fO]}isEnabled(){return Boolean(global[fO])}};var mt="Prisma";function Xc1(Z){return!!Z&&typeof Z==="object"&&"dispatchEngineSpans"in Z}function ut(){let Z=globalThis.PRISMA_INSTRUMENTATION;return Z&&typeof Z==="object"&&"helper"in Z?Z.helper:void 0}class dt extends gt{constructor(){super()}enable(){super.enable();let Z=ut();if(Xc1(Z))Z.createEngineSpan=(J)=>{let $=O8.trace.getTracer("prismaV5Compatibility"),X=$._idGenerator;if(!X){o0(()=>{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=Yc1(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:O8.TraceFlags.SAMPLED}}}),H=O8.trace.setSpanContext(O8.context.active(),{traceId:z,spanId:W,traceFlags:O8.TraceFlags.SAMPLED});O8.context.with(H,()=>{let V={generateTraceId:()=>{return z},generateSpanId:()=>{return K}};$._idGenerator=V,$.startSpan(Y.name,{kind:Q,links:G,startTime:Y.start_time,attributes:Y.attributes}).end(Y.end_time),$._idGenerator=X})})}finally{$._idGenerator=X}}}}function Yc1(Z){switch(Z){case"client":return O8.SpanKind.CLIENT;case"internal":default:return O8.SpanKind.INTERNAL}}var Qc1=s(mt,(Z)=>{return new dt}),ct=k((Z)=>{return{name:mt,setupOnce(){Qc1()},setup(J){if(!ut())return;J.on("spanStart",($)=>{let X=X1($);if(X.description?.startsWith("prisma:"))$.setAttribute(W1,"auto.db.otel.prisma");if(X.description==="prisma:engine:db_query"&&X.data["db.query.text"])$.updateName(X.data["db.query.text"]);if(X.description==="prisma:engine:db_query"&&!X.data["db.system"])$.setAttribute("db.system","prisma")})}}});var Ve=v(He(),1);var Fe="Hapi",Be=s(Fe,()=>new Ve.HapiInstrumentation),Pc1=()=>{return{name:Fe,setupOnce(){Be()}}},Ue=k(Pc1);var iG=v(X0(),1);var QZ={HONO_TYPE:"hono.type",HONO_NAME:"hono.name"},TQ={MIDDLEWARE:"middleware",REQUEST_HANDLER:"request_handler"};var jJ=v(u(),1),pG=v(D1(),1);var Ic1="@sentry/instrumentation-hono",Sc1="0.0.1";class cO extends pG.InstrumentationBase{constructor(Z={}){super(Ic1,Sc1,Z)}init(){return[new pG.InstrumentationNodeModuleDefinition("hono",[">=4.0.0 <5"],(Z)=>this._patch(Z))]}_patch(Z){let J=this;class $ extends Z.Hono{constructor(...X){super(...X);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=$}catch{return{...Z,Hono:$}}return Z}_patchHandler(){let Z=this;return function(J){return function(...X){if(typeof X[0]==="string"){let Y=X[0];if(X.length===1)return J.apply(this,[Y]);let Q=X.slice(1);return J.apply(this,[Y,...Q.map((W)=>Z._wrapHandler(W))])}return J.apply(this,X.map((Y)=>Z._wrapHandler(Y)))}}}_patchOnHandler(){let Z=this;return function(J){return function(...X){let Y=X.slice(2);return J.apply(this,[...X.slice(0,2),...Y.map((Q)=>Z._wrapHandler(Q))])}}}_patchMiddlewareHandler(){let Z=this;return function(J){return function(...X){if(typeof X[0]==="string"){let Y=X[0];if(X.length===1)return J.apply(this,[Y]);let Q=X.slice(1);return J.apply(this,[Y,...Q.map((W)=>Z._wrapHandler(W))])}return J.apply(this,X.map((Y)=>Z._wrapHandler(Y)))}}}_wrapHandler(Z){let J=this;return function($,X){if(!J.isEnabled())return Z.apply(this,[$,X]);let Y=$.req.path,Q=J.tracer.startSpan(Y);return jJ.context.with(jJ.trace.setSpan(jJ.context.active(),Q),()=>{return J._safeExecute(()=>{let W=Z.apply(this,[$,X]);if(t4(W))return W.then((K)=>{let z=J._determineHandlerType(K);return Q.setAttributes({[QZ.HONO_TYPE]:z,[QZ.HONO_NAME]:z===TQ.REQUEST_HANDLER?Y:Z.name||"anonymous"}),J.getConfig().responseHook?.(Q),K});else{let K=J._determineHandlerType(W);return Q.setAttributes({[QZ.HONO_TYPE]:K,[QZ.HONO_NAME]:K===TQ.REQUEST_HANDLER?Y:Z.name||"anonymous"}),J.getConfig().responseHook?.(Q),W}},()=>Q.end(),(W)=>{J._handleError(Q,W),Q.end()})})}}_safeExecute(Z,J,$){try{let X=Z();if(t4(X))X.then(()=>J(),(Y)=>$(Y));else J();return X}catch(X){throw $(X),X}}_determineHandlerType(Z){return Z===void 0?TQ.MIDDLEWARE:TQ.REQUEST_HANDLER}_handleError(Z,J){if(J instanceof Error)Z.setStatus({code:jJ.SpanStatusCode.ERROR,message:J.message}),Z.recordException(J)}}var Le="Hono";function yc1(Z){let J=X1(Z).data,$=J[QZ.HONO_TYPE];if(J[U1]||!$)return;Z.setAttributes({[W1]:"auto.http.otel.hono",[U1]:`${$}.hono`});let X=J[QZ.HONO_NAME];if(typeof X==="string")Z.updateName(X);if(d1()===y6()){u0&&R.warn("Isolation scope is default isolation scope - skipping setting transactionName");return}let Y=J[iG.ATTR_HTTP_ROUTE],Q=J[iG.ATTR_HTTP_REQUEST_METHOD];if(typeof Y==="string"&&typeof Q==="string")d1().setTransactionName(`${Q} ${Y}`)}var De=s(Le,()=>new cO({responseHook:(Z)=>{yc1(Z)}})),kc1=()=>{return{name:Le,setupOnce(){De()}}},Oe=k(kc1);var me=v(ge(),1),ue=v(X0(),1);var de="Koa",ce=s(de,me.KoaInstrumentation,(Z={})=>{return{ignoreLayersType:Z.ignoreLayersType,requestHook(J,$){Y0(J,"auto.http.otel.koa");let X=X1(J).data,Y=X["koa.type"];if(Y)J.setAttribute(U1,`${Y}.koa`);let Q=X["koa.name"];if(typeof Q==="string")J.updateName(Q||"< unknown >");if(d1()===y6()){u0&&R.warn("Isolation scope is default isolation scope - skipping setting transactionName");return}let W=X[ue.ATTR_HTTP_ROUTE],K=$.context?.request?.method?.toUpperCase()||"GET";if(W)d1().setTransactionName(`${K} ${W}`)}}}),pc1=(Z={})=>{return{name:de,setupOnce(){ce(Z)}}},le=k(pc1);var V11=v(H11(),1);var F11="Connect",B11=s(F11,()=>new V11.ConnectInstrumentation),Ql1=()=>{return{name:F11,setupOnce(){B11()}}},U11=k(Ql1);var y11=v(S11(),1);var Al1=new Set(["callProcedure","execSql","execSqlBatch","execBulkLoad","prepare","execute"]),k11="Tedious",x11=s(k11,()=>new y11.TediousInstrumentation({})),Tl1=()=>{let Z;return{name:k11,setupOnce(){let J=x11();Z=i3(J)},setup(J){Z?.(()=>J.on("spanStart",($)=>{let{description:X,data:Y}=X1($);if(!X||Y["db.system"]!=="mssql")return;let Q=X.split(" ")[0]||"";if(Al1.has(Q))$.setAttribute(W1,"auto.db.otel.tedious")}))}}},v11=k(Tl1);var p11=v(l11(),1);var i11="GenericPool",n11=s(i11,()=>new p11.GenericPoolInstrumentation({})),Rl1=()=>{let Z;return{name:i11,setupOnce(){let J=n11();Z=i3(J)},setup(J){Z?.(()=>J.on("spanStart",($)=>{let Y=X1($).description;if(Y==="generic-pool.aquire"||Y==="generic-pool.acquire")$.setAttribute(W1,"auto.db.otel.generic_pool")}))}}},a11=k(Rl1);var _01=v(O01(),1);var w01="Amqplib",Qp1={consumeEndHook:(Z)=>{Y0(Z,"auto.amqplib.otel.consumer")},publishHook:(Z)=>{Y0(Z,"auto.amqplib.otel.publisher")}},A01=s(w01,()=>new _01.AmqplibInstrumentation(Qp1)),Wp1=()=>{return{name:w01,setupOnce(){A01()}}},T01=k(Wp1);var CQ="VercelAI";var JH=v(D1(),1);var Kp1=[">=3.0.0 <7"],M01=["generateText","streamText","generateObject","streamObject","embed","embedMany"];function zp1(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 Gp1(Z){if(typeof Z!=="object"||Z===null||!("content"in Z))return;let J=Z;if(!Array.isArray(J.content))return;for(let $ of J.content)if(zp1($)){let X=F2($.toolCallId);if(X){let Y=X.spanContext();D6((Q)=>{Q.setContext("trace",{trace_id:Y.traceId,span_id:Y.spanId}),Q.setTag("vercel.ai.tool.name",$.toolName),Q.setTag("vercel.ai.tool.callId",$.toolCallId),Q.setLevel("error"),O1($.error,{mechanism:{type:"auto.vercelai.otel",handled:!1}})}),B2($.toolCallId)}else D6((Y)=>{Y.setTag("vercel.ai.tool.name",$.toolName),Y.setTag("vercel.ai.tool.callId",$.toolCallId),Y.setLevel("error"),O1($.error,{mechanism:{type:"auto.vercelai.otel",handled:!1}})})}}function Hp1(Z,J,$,X){let Y=Z?.recordInputs!==void 0?Z.recordInputs:J.recordInputs!==void 0?J.recordInputs:$===!0?!0:X,Q=Z?.recordOutputs!==void 0?Z.recordOutputs:J.recordOutputs!==void 0?J.recordOutputs:$===!0?!0:X;return{recordInputs:Y,recordOutputs:Q}}class qQ extends JH.InstrumentationBase{__init(){this._isPatched=!1}__init2(){this._callbacks=[]}constructor(Z={}){super("@sentry/instrumentation-vercel-ai",u1,Z);qQ.prototype.__init.call(this),qQ.prototype.__init2.call(this)}init(){return new JH.InstrumentationNodeModuleDefinition("ai",Kp1,this._patch.bind(this))}callWhenPatched(Z){if(this._isPatched)Z();else this._callbacks.push(Z)}_patch(Z){this._isPatched=!0,this._callbacks.forEach(($)=>$()),this._callbacks=[];let J=($)=>{return new Proxy($,{apply:(X,Y,Q)=>{let W=Q[0].experimental_telemetry||{},K=W.isEnabled,z=p(),G=z?.getIntegrationByName(CQ),H=G?.options,V=G?Boolean(z?.getOptions().sendDefaultPii):!1,{recordInputs:F,recordOutputs:B}=Hp1(H,W,K,V);return Q[0].experimental_telemetry={...W,isEnabled:K!==void 0?K:!0,recordInputs:F,recordOutputs:B},k6(()=>Reflect.apply(X,Y,Q),(U)=>{if(U&&typeof U==="object")Z4(U,"_sentry_active_span",M5())},()=>{},(U)=>{Gp1(U)})}})};if(Object.prototype.toString.call(Z)==="[object Module]"){for(let $ of M01)Z[$]=J(Z[$]);return Z}else{let $=M01.reduce((X,Y)=>{return X[Y]=J(Z[Y]),X},{});return{...Z,...$}}}}var j01=s(CQ,()=>new qQ({}));function Vp1(Z){return!!Z.getIntegrationByName("Modules")?.getModules?.()?.ai}var Fp1=(Z={})=>{let J;return{name:CQ,options:Z,setupOnce(){J=j01()},afterAllSetup($){if(Z.force??Vp1($))jz($);else J?.callWhenPatched(()=>jz($))}}},N01=k(Fp1);var $H=v(D1(),1);var Bp1=[">=4.0.0 <7"];class z_ extends $H.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-openai",u1,Z)}init(){return new $H.InstrumentationNodeModuleDefinition("openai",Bp1,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 $=Z[J];if(!$)return Z;let X=this.getConfig(),Y=function(...Q){if(KJ(c7))return Reflect.construct($,Q);let W=Reflect.construct($,Q),K=p(),z=Boolean(K?.getOptions().sendDefaultPii),G=X.recordInputs??z,H=X.recordOutputs??z;return Cz(W,{recordInputs:G,recordOutputs:H})};Object.setPrototypeOf(Y,$),Object.setPrototypeOf(Y.prototype,$.prototype);for(let Q of Object.getOwnPropertyNames($))if(!["length","name","prototype"].includes(Q)){let W=Object.getOwnPropertyDescriptor($,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===$)try{Z.default=Y}catch(Q){Object.defineProperty(Z,"default",{value:Y,writable:!0,configurable:!0,enumerable:!0})}return Z}}var R01=s(c7,(Z)=>new z_(Z)),Up1=(Z={})=>{return{name:c7,setupOnce(){R01(Z)}}},C01=k(Up1);var XH=v(D1(),1);var Lp1=[">=0.19.2 <1.0.0"];class G_ extends XH.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-anthropic-ai",u1,Z)}init(){return new XH.InstrumentationNodeModuleDefinition("@anthropic-ai/sdk",Lp1,this._patch.bind(this))}_patch(Z){let J=Z.Anthropic,$=this.getConfig(),X=function(...Y){if(KJ(l7))return Reflect.construct(J,Y);let Q=Reflect.construct(J,Y),W=p(),K=Boolean(W?.getOptions().sendDefaultPii),z=$.recordInputs??K,G=$.recordOutputs??K;return D2(Q,{recordInputs:z,recordOutputs:G})};Object.setPrototypeOf(X,J),Object.setPrototypeOf(X.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(X,Y,Q)}try{Z.Anthropic=X}catch(Y){Object.defineProperty(Z,"Anthropic",{value:X,writable:!0,configurable:!0,enumerable:!0})}if(Z.default===J)try{Z.default=X}catch(Y){Object.defineProperty(Z,"default",{value:X,writable:!0,configurable:!0,enumerable:!0})}return Z}}var q01=s(l7,(Z)=>new G_(Z)),Dp1=(Z={})=>{return{name:l7,options:Z,setupOnce(){q01(Z)}}},E01=k(Dp1);var EX=v(D1(),1);var P01=[">=0.10.0 <2"];class H_ extends EX.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-google-genai",u1,Z)}init(){return new EX.InstrumentationNodeModuleDefinition("@google/genai",P01,(J)=>this._patch(J),(J)=>J,[new EX.InstrumentationNodeModuleFile("@google/genai/dist/node/index.cjs",P01,(J)=>this._patch(J),(J)=>J)])}_patch(Z){let J=Z.GoogleGenAI,$=this.getConfig();if(typeof J!=="function")return Z;let X=function(...Y){if(KJ(p7))return Reflect.construct(J,Y);let Q=Reflect.construct(J,Y),W=p(),K=Boolean(W?.getOptions().sendDefaultPii),z=$,G=z?.recordInputs??K,H=z?.recordOutputs??K;return A2(Q,{recordInputs:G,recordOutputs:H})};Object.setPrototypeOf(X,J),Object.setPrototypeOf(X.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(X,Y,Q)}return q3(Z,"GoogleGenAI",X),Z}}var I01=s(p7,(Z)=>new H_(Z)),Op1=(Z={})=>{return{name:p7,setupOnce(){I01(Z)}}},S01=k(Op1);var zZ=v(D1(),1);var YH=[">=0.1.0 <2.0.0"];function _p1(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 wp1(Z,J,$){return new Proxy(Z,{apply(X,Y,Q){let K=Q[1];if(!K||typeof K!=="object"||Array.isArray(K))K={},Q[1]=K;let z=K.callbacks,G=_p1(z,J);return K.callbacks=G,Reflect.apply(X,Y,Q)}})}class V_ extends zZ.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-langchain",u1,Z)}init(){let Z=[],J=["@langchain/anthropic","@langchain/openai","@langchain/google-genai","@langchain/mistralai","@langchain/google-vertexai","@langchain/groq"];for(let $ of J)Z.push(new zZ.InstrumentationNodeModuleDefinition($,YH,this._patch.bind(this),(X)=>X,[new zZ.InstrumentationNodeModuleFile(`${$}/dist/index.cjs`,YH,this._patch.bind(this),(X)=>X)]));return Z.push(new zZ.InstrumentationNodeModuleDefinition("langchain",YH,this._patch.bind(this),($)=>$,[new zZ.InstrumentationNodeModuleFile("langchain/dist/chat_models/universal.cjs",YH,this._patch.bind(this),($)=>$)])),Z}_patch(Z){iL([c7,l7,p7]);let J=p(),$=Boolean(J?.getOptions().sendDefaultPii),X=this.getConfig(),Y=X?.recordInputs??$,Q=X?.recordOutputs??$,W=Ez({recordInputs:Y,recordOutputs:Q});return this._patchRunnableMethods(Z,W),Z}_patchRunnableMethods(Z,J){let $=["ChatAnthropic","ChatOpenAI","ChatGoogleGenerativeAI","ChatMistralAI","ChatVertexAI","ChatGroq","ConfigurableModel"],X=Z.universal_exports??Z,Y=Object.values(X).find((K)=>{return typeof K==="function"&&$.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]=wp1(z,J)}}}var y01=s(qz,(Z)=>new V_(Z)),Ap1=(Z={})=>{return{name:qz,setupOnce(){y01(Z)}}},k01=k(Ap1);var PX=v(D1(),1);var x01=[">=0.0.0 <2.0.0"];class F_ extends PX.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-langgraph",u1,Z)}init(){return new PX.InstrumentationNodeModuleDefinition("@langchain/langgraph",x01,this._patch.bind(this),(J)=>J,[new PX.InstrumentationNodeModuleFile("@langchain/langgraph/dist/index.cjs",x01,this._patch.bind(this),(J)=>J)])}_patch(Z){let J=p(),$=Boolean(J?.getOptions().sendDefaultPii),X=this.getConfig(),Y=X.recordInputs??$,Q=X.recordOutputs??$,W={recordInputs:Y,recordOutputs:Q};if(Z.StateGraph&&typeof Z.StateGraph==="function"){let K=Z.StateGraph;K.prototype.compile=j2(K.prototype.compile,W)}return Z}}var v01=s(Pz,(Z)=>new F_(Z)),Tp1=(Z={})=>{return{name:Pz,setupOnce(){v01(Z)}}},h01=k(Tp1);var l01=v(D1(),1);var y9=v(u(),1),k9=v(D1(),1),_8=v(X0(),1);import*as b01 from"net";function g01(Z,J,$,X,Y){let W=()=>{},K=Y.firestoreSpanCreationHook;if(typeof K==="function")W=(H)=>{k9.safeExecuteInTheMiddle(()=>K(H),(V)=>{if(!V)return;y9.diag.error(V?.message)},!0)};let z=new k9.InstrumentationNodeModuleDefinition("@firebase/firestore",J,(H)=>f01(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)=>f01(V,$,X,Z,W),(V)=>m01(V,X)));return z}function f01(Z,J,$,X,Y){return m01(Z,$),J(Z,"addDoc",Mp1(X,Y)),J(Z,"getDocs",Np1(X,Y)),J(Z,"setDoc",Rp1(X,Y)),J(Z,"deleteDoc",jp1(X,Y)),Z}function m01(Z,J){for(let $ of["addDoc","getDocs","setDoc","deleteDoc"])if(k9.isWrapped(Z[$]))J(Z,$);return Z}function Mp1(Z,J){return function(X){return function(Y,Q){let W=WH(Z,"addDoc",Y);return J(W),QH(W,()=>{return X(Y,Q)})}}}function jp1(Z,J){return function(X){return function(Y){let Q=WH(Z,"deleteDoc",Y.parent||Y);return J(Q),QH(Q,()=>{return X(Y)})}}}function Np1(Z,J){return function(X){return function(Y){let Q=WH(Z,"getDocs",Y);return J(Q),QH(Q,()=>{return X(Y)})}}}function Rp1(Z,J){return function(X){return function(Y,Q,W){let K=WH(Z,"setDoc",Y.parent||Y);return J(K),QH(K,()=>{return typeof W<"u"?X(Y,Q,W):X(Y,Q)})}}}function QH(Z,J){return y9.context.with(y9.trace.setSpan(y9.context.active(),Z),()=>{return k9.safeExecuteInTheMiddle(()=>{return J()},($)=>{if($)Z.recordException($);Z.end()},!0)})}function WH(Z,J,$){let X=Z.startSpan(`${J} ${$.path}`,{kind:y9.SpanKind.CLIENT});return qp1(X,$),X.setAttribute(_8.ATTR_DB_OPERATION_NAME,J),X}function Cp1(Z){let J,$;if(typeof Z.host==="string")if(Z.host.startsWith("[")){if(Z.host.endsWith("]"))J=Z.host.replace(/^\[|\]$/g,"");else if(Z.host.includes("]:")){let X=Z.host.lastIndexOf(":");if(X!==-1)J=Z.host.slice(1,X).replace(/^\[|\]$/g,""),$=Z.host.slice(X+1)}}else if(b01.isIPv6(Z.host))J=Z.host;else{let X=Z.host.lastIndexOf(":");if(X!==-1)J=Z.host.slice(0,X),$=Z.host.slice(X+1);else J=Z.host}return{address:J,port:$?parseInt($,10):void 0}}function qp1(Z,J){let $=J.firestore.app,X=$.options,Q=(J.firestore.toJSON()||{}).settings||{},W={[_8.ATTR_DB_COLLECTION_NAME]:J.path,[_8.ATTR_DB_NAMESPACE]:$.name,[_8.ATTR_DB_SYSTEM_NAME]:"firebase.firestore","firebase.firestore.type":J.type,"firebase.firestore.options.projectId":X.projectId,"firebase.firestore.options.appId":X.appId,"firebase.firestore.options.messagingSenderId":X.messagingSenderId,"firebase.firestore.options.storageBucket":X.storageBucket},{address:K,port:z}=Cp1(Q);if(K)W[_8.ATTR_SERVER_ADDRESS]=K;if(z)W[_8.ATTR_SERVER_PORT]=z;Z.setAttributes(W)}var k5=v(u(),1),x9=v(D1(),1);function u01(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)=>{x9.safeExecuteInTheMiddle(()=>G(F,B),(U)=>{if(!U)return;k5.diag.error(U?.message)},!0)};if(typeof z==="function")Q=(F)=>{x9.safeExecuteInTheMiddle(()=>z(F),(B)=>{if(!B)return;k5.diag.error(B?.message)},!0)};let H=new x9.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 x9.InstrumentationNodeModuleFile(F,J,(U)=>Ep1(U,$,X,Z,{requestHook:Q,responseHook:W,errorHook:K},B),(U)=>d01(U,X)))}),H}function Q6(Z,J,$){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.${$}`,{kind:k5.SpanKind.SERVER}),F={"faas.name":H,"faas.trigger":$,"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),k5.context.with(k5.trace.setSpan(k5.context.active(),V),async()=>{let B,U;try{U=await W.apply(this,G)}catch(L){B=L}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 Ep1(Z,J,$,X,Y,Q){switch(d01(Z,$),Q){case"function":J(Z,"onRequest",Q6(X,Y,"http.request")),J(Z,"onCall",Q6(X,Y,"http.call"));break;case"firestore":J(Z,"onDocumentCreated",Q6(X,Y,"firestore.document.created")),J(Z,"onDocumentUpdated",Q6(X,Y,"firestore.document.updated")),J(Z,"onDocumentDeleted",Q6(X,Y,"firestore.document.deleted")),J(Z,"onDocumentWritten",Q6(X,Y,"firestore.document.written")),J(Z,"onDocumentCreatedWithAuthContext",Q6(X,Y,"firestore.document.created")),J(Z,"onDocumentUpdatedWithAuthContext",Q6(X,Y,"firestore.document.updated")),J(Z,"onDocumentDeletedWithAuthContext",Q6(X,Y,"firestore.document.deleted")),J(Z,"onDocumentWrittenWithAuthContext",Q6(X,Y,"firestore.document.written"));break;case"scheduler":J(Z,"onSchedule",Q6(X,Y,"scheduler.scheduled"));break;case"storage":J(Z,"onObjectFinalized",Q6(X,Y,"storage.object.finalized")),J(Z,"onObjectArchived",Q6(X,Y,"storage.object.archived")),J(Z,"onObjectDeleted",Q6(X,Y,"storage.object.deleted")),J(Z,"onObjectMetadataUpdated",Q6(X,Y,"storage.object.metadataUpdated"));break}return Z}function d01(Z,J){let $=["onSchedule","onRequest","onCall","onObjectFinalized","onObjectArchived","onObjectDeleted","onObjectMetadataUpdated","onDocumentCreated","onDocumentUpdated","onDocumentDeleted","onDocumentWritten","onDocumentCreatedWithAuthContext","onDocumentUpdatedWithAuthContext","onDocumentDeletedWithAuthContext","onDocumentWrittenWithAuthContext"];for(let X of $)if(x9.isWrapped(Z[X]))J(Z,X);return Z}var c01={},Pp1=[">=3.0.0 <5"],Ip1=[">=6.0.0 <7"];class B_ extends l01.InstrumentationBase{constructor(Z=c01){super("@sentry/instrumentation-firebase",u1,Z)}setConfig(Z={}){super.setConfig({...c01,...Z})}init(){let Z=[];return Z.push(g01(this.tracer,Pp1,this._wrap,this._unwrap,this.getConfig())),Z.push(u01(this.tracer,Ip1,this._wrap,this._unwrap,this.getConfig())),Z}}var p01="Firebase",Sp1={firestoreSpanCreationHook:(Z)=>{Y0(Z,"auto.firebase.otel.firestore"),Z.setAttribute(U1,"db.query")},functions:{requestHook:(Z)=>{Y0(Z,"auto.firebase.otel.functions"),Z.setAttribute(U1,"http.request")},errorHook:async(Z,J)=>{if(J)O1(J,{mechanism:{type:"auto.firebase.otel.functions",handled:!1}}),await Kz(2000)}}},i01=s(p01,()=>new B_(Sp1)),yp1=()=>{return{name:p01,setupOnce(){i01()}}},n01=k(yp1);function EQ(){return[ai(),vn(),Ra(),Oe(),ko(),Xr(),jr(),pr(),as(),qt(),ct(),Ue(),le(),U11(),v11(),a11(),ta(),T01(),Bo(),k01(),h01(),N01(),C01(),E01(),S01(),yt(),n01()]}var IX=v(u(),1);var SX=v(X0(),1);var U_=1e6;function a01(Z,J={}){if(Z.getOptions().debug)TD();let[$,X]=kp1(Z,J);Z.traceProvider=$,Z.asyncLocalStorageLookup=X}function kp1(Z,J={}){let $=new rz({sampler:new WD(Z),resource:y3().merge(lz({[SX.ATTR_SERVICE_NAME]:"node",[SX.SEMRESATTRS_SERVICE_NAMESPACE]:"sentry",[SX.ATTR_SERVICE_VERSION]:u1})),forceFlushTimeoutMillis:500,spanProcessors:[new QD({timeout:xp1(Z.getOptions().maxSpanWaitDuration)}),...J.spanProcessors||[]]});IX.trace.setGlobalTracerProvider($),IX.propagation.setGlobalPropagator(new YD);let X=new XG;return IX.context.setGlobalContextManager(X),[$,X.getAsyncLocalStorageLookup()]}function xp1(Z){if(Z==null)return;if(Z>U_)return u0&&R.warn(`\`maxSpanWaitDuration\` is too high, using the maximum value of ${U_}`),U_;else if(Z<=0||Number.isNaN(Z)){u0&&R.warn("`maxSpanWaitDuration` must be a positive number, using default value instead.");return}return Z}function o01(){return zG().filter((J)=>J.name!=="Http"&&J.name!=="NodeFetch").concat(a3(),r3())}function r01(Z){return[...o01(),...P0(Z)?EQ():[]]}function L_(Z={}){return vp1(Z,r01)}function vp1(Z={},J){_9(Z,"node");let $=SD({...Z,defaultIntegrations:Z.defaultIntegrations??J(Z)});if($&&!Z.skipOpenTelemetrySetup)a01($,{spanProcessors:Z.openTelemetrySpanProcessors}),GG();return $}import*as J41 from"os";var hp1="BunServer",fp1=()=>{return{name:hp1,setupOnce(){bp1()}}},e01=k(fp1),s01=!1;function bp1(){if(s01)return;Bun.serve=new Proxy(Bun.serve,{apply(Z,J,$){t01($[0]);let X=Z.apply(J,$),Y=X.reload.bind(X);return X.reload=(Q)=>{return t01(Q),Y(Q)},X}}),s01=!0}function t01(Z){gp1(Z),mp1(Z)}function gp1(Z){if(typeof Z.fetch!=="function")return;Z.fetch=new Proxy(Z.fetch,{apply(J,$,X){return D_(J,$,X)}})}function mp1(Z){if(!Z.routes)return;if(typeof Z.routes!=="object")return;Object.keys(Z.routes).forEach((J)=>{let $=Z.routes[J];if(typeof $==="function")Z.routes[J]=new Proxy($,{apply:(X,Y,Q)=>{return D_(X,Y,Q,J)}});if($ instanceof Response)return;if(typeof $==="object")Object.entries($).forEach(([X,Y])=>{if(typeof Y==="function")Z.routes[J][X]=new Proxy(Y,{apply:(Q,W,K)=>{return D_(Q,W,K,J)}})})})}function D_(Z,J,$,X){return rZ((Y)=>{let Q=$[0],W=Q.method.toUpperCase();if(W==="OPTIONS"||W==="HEAD")return Z.apply(J,$);let K=L3(Q.url),z=up1(K,Q),G=K?.pathname||"/";if(Q.params){if(Object.keys(Q.params).forEach((H)=>{z[`url.path.parameter.${H}`]=Q.params[H]}),X)z[E0]="route",z["url.template"]=X,G=X}if(X?.endsWith("/*"))z[E0]="route",z["url.template"]=X,G=X;return Object.assign(z,v$(Q.headers.toJSON(),p()?.getOptions().sendDefaultPii??!1)),Y.setSDKProcessingMetadata({normalizedRequest:{url:Q.url,method:Q.method,headers:Q.headers.toJSON(),query_string:K?.search}}),Yz({sentryTrace:Q.headers.get("sentry-trace")??"",baggage:Q.headers.get("baggage")},()=>h6({attributes:z,op:"http.server",name:`${Q.method} ${G}`},async(H)=>{try{let V=await Z.apply(J,$);if(V?.status)dK(H,V.status),Y.setContext("response",{headers:V.headers.toJSON(),status_code:V.status});return V}catch(V){throw O1(V,{mechanism:{type:"auto.http.bun.serve",handled:!1}}),V}}))})}function up1(Z,J){let $={[W1]:"auto.http.bun.serve",[AL]:J.method||"GET",[E0]:"url"};if(Z){if(Z.search)$["url.query"]=Z.search;if(Z.hash)$["url.fragment"]=Z.hash;if(Z.pathname)$["url.path"]=Z.pathname;if(!aL(Z)){if($["url.full"]=Z.href,Z.port)$["url.port"]=Z.port;if(Z.protocol)$["url.scheme"]=Z.protocol;if(Z.hostname)$["url.domain"]=Z.hostname}}return $}function Z41(Z){function J($){let X={body:$.body,method:"POST",headers:Z.headers};try{return S7(()=>{return fetch(Z.url,X).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 WJ(Z,J)}function $41(Z){return[f$(),h$(),b$(),g$(),m$(),a3(),r3(),HX(),VX(),zX(),KX(),GX(),e01(),...P0(Z)?EQ():[]]}function O_(Z={}){_9(Z,"bun");let J={...Z,platform:"javascript",runtime:{name:"bun",version:Bun.version},serverName:Z.serverName||global.process.env.SENTRY_NAME||J41.hostname()};if(J.transport=J.transport||Z41,J.defaultIntegrations===void 0)J.defaultIntegrations=$41(J);return L_(J)}O_({dsn:"https://f0ba950f2a01c32d24ccd8711de778be@o4510345514123264.ingest.us.sentry.io/4510346875043848",tracesSampleRate:1,sendDefaultPii:!1});import{readFileSync as X41}from"fs";import{join as Y41}from"path";function O0(){return"3.3.0-beta.1"}function __(Z){let[J,$]=Z.split("-"),X=(J||"0.0.0").split(".").map(Number),Y=null,Q=0;if($){let W=$.match(/^([a-z]+)\.?(\d+)?$/i);if(W)Y=W[1]||null,Q=parseInt(W[2]||"0",10);else Y=$}return{major:X[0]||0,minor:X[1]||0,patch:X[2]||0,preRelease:Y,preReleaseNum:Q}}function v9(Z){let J=__(Z);if(!J.preRelease)return"stable";if(J.preRelease.startsWith("alpha"))return"alpha";return"beta"}function PQ(Z,J){try{let $=__(Z),X=__(J);if($.major>X.major)return!1;if($.major<X.major)return!1;if(X.preRelease&&!$.preRelease)return!1;if(!X.preRelease&&$.preRelease)return!1;if(X.preRelease&&$.preRelease){if($.minor<X.minor)return!1;if($.minor>X.minor)return!0;if($.patch>X.patch)return!0;if($.patch<X.patch)return!1;return $.preReleaseNum>X.preReleaseNum}if($.minor>X.minor)return!0;if($.minor<X.minor)return!1;if($.patch>X.patch)return!0;return!1}catch($){return!1}}import{parseArgs as cp1}from"util";var lp1={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 Q41(){let Z=cp1({options:lp1,allowPositionals:!1,strict:!0});if(Z.values.version)console.log(`ccc v${O0()}`),process.exit(0);if(Z.values.help)pp1(),process.exit(0);let J=process.env.CCC_USERNAME||Z.values.username,$=process.env.CCC_PASSWORD||Z.values.password,X=process.env.CCC_NGROK_TOKEN||Z.values["ngrok-token"],Y=process.env.CCC_NGROK_DOMAIN||Z.values["ngrok-domain"];if(!J||!$)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:$,ngrokToken:X,ngrokDomain:Y,autoUpdate:!Z.values["no-auto-update"],autoUpdateCheckInterval:parseInt(Z.values["auto-update-check-interval"],10),terminalAudit:Z.values["terminal-audit"]}}function pp1(){console.log(`
|
|
54
|
+
>>> 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 $;else if(W===z)return Q===K-1&&Z[Q]==="";else throw Error("wtf?")}braceExpand(){return wn(this.pattern,this.options)}parse(Z){e3(Z);let J=this.options;if(Z==="**")return V8;if(Z==="")return"";let $,X=null;if($=Z.match(ef1))X=J.dot?Jb1:Zb1;else if($=Z.match(cf1))X=(J.nocase?J.dot?nf1:if1:J.dot?pf1:lf1)($[1]);else if($=Z.match($b1))X=(J.nocase?J.dot?Yb1:Xb1:J.dot?Qb1:Wb1)($);else if($=Z.match(af1))X=J.dot?rf1:of1;else if($=Z.match(sf1))X=tf1;let Y=S4.fromGlob(Z,this.options).toMMPattern();if(X&&typeof Y==="object")Reflect.defineProperty(Y,"test",{value:X});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,$=J.noglobstar?Gb1:J.dot?Hb1:Vb1,X=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(""))X.add(H);return typeof G==="string"?Db1(G):G===V8?V8:G._src});return z.forEach((G,H)=>{let V=z[H+1],F=z[H-1];if(G!==V8||F===V8)return;if(F===void 0)if(V!==void 0&&V!==V8)z[H+1]="(?:\\/|"+$+"\\/)?"+V;else z[H]=$;else if(V===void 0)z[H-1]=F+"(?:\\/|"+$+")?";else if(V!==V8)z[H-1]=F+"(?:\\/|\\/"+$+"\\/)"+V,z[H+1]=V8}),z.filter((G)=>G!==V8).join("/")}).join("|"),[Q,W]=Z.length>1?["(?:",")"]:["",""];if(Y="^"+Q+Y+W+"$",this.negate)Y="^(?!"+Y+").+$";try{this.regexp=new RegExp(Y,[...X].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 $=this.options;if(this.isWindows)Z=Z.split("\\").join("/");let X=this.slashSplit(Z);this.debug(this.pattern,"split",X);let Y=this.set;this.debug(this.pattern,"set",Y);let Q=X[X.length-1];if(!Q)for(let W=X.length-2;!Q&&W>=0;W--)Q=X[W];for(let W=0;W<Y.length;W++){let K=Y[W],z=X;if($.matchBase&&K.length===1)z=[Q];if(this.matchOne(z,K,J)){if($.flipNegate)return!0;return!this.negate}}if($.flipNegate)return!1;return this.negate}static defaults(Z){return y4.defaults(Z).Minimatch}}y4.AST=S4;y4.Minimatch=JQ;y4.escape=cD;y4.unescape=r7;var Tn="@fastify/otel",_b1="0.8.0",wb1=">=4.0.0 <6",Mn=["onRequest","preParsing","preValidation","preHandler","preSerialization","onSend","onResponse","onError"],L0={HOOK_NAME:"hook.name",FASTIFY_TYPE:"fastify.type",HOOK_CALLBACK_NAME:"hook.callback.name",ROOT:"fastify.root"},s7={ROUTE:"route-hook",INSTANCE:"hook",HANDLER:"request-handler"},R9="anonymous",$6=Symbol("fastify otel instance"),t7=Symbol("fastify otel request spans"),$Q=Symbol("fastify otel request context"),jn=Symbol("fastify otel addhook original"),Nn=Symbol("fastify otel setnotfound original"),DG=Symbol("fastify otel ignore path");class lD extends Rn.InstrumentationBase{constructor(Z){super(Tn,_b1,Z);if(this.servername=Z?.servername??process.env.OTEL_SERVICE_NAME??"fastify",this[DG]=null,this._logger=s0.diag.createComponentLogger({namespace:Tn}),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 $=y4;this[DG]=(X)=>{if(typeof J==="function")return J(X);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)},An.subscribe("fastify.initialization",this._handleInitialization)}return super.enable()}disable(){if(this._handleInitialization)An.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:wb1,name:"@fastify/otel"},J;function J($,X,Y){$.decorate($6,Z),$.decorate(jn,$.addHook),$.decorate(Nn,$.setNotFoundHandler),$.decorateRequest("opentelemetry",function(){let V=this[$Q];return{span:this[t7],tracer:Z.tracer,context:V,inject:(B,U)=>{return s0.propagation.inject(V,B,U)},extract:(B,U)=>{return s0.propagation.extract(V,B,U)}}}),$.decorateRequest(t7,null),$.decorateRequest($Q,null),$.addHook("onRoute",function(H){if(Z[DG]?.(H)===!0){Z._logger.debug(`Ignoring route instrumentation ${H.method} ${H.url} because it matches the ignore path`);return}for(let V of Mn)if(H[V]!=null){let F=H[V];if(typeof F==="function")H[V]=G(F,{[Y4.ATTR_SERVICE_NAME]:$[$6].servername,[L0.HOOK_NAME]:`${this.pluginName} - route -> ${V}`,[L0.FASTIFY_TYPE]:s7.ROUTE,[Y4.ATTR_HTTP_ROUTE]:H.url,[L0.HOOK_CALLBACK_NAME]:F.name?.length>0?F.name:R9});else if(Array.isArray(F)){let B=[];for(let U of F)B.push(G(U,{[Y4.ATTR_SERVICE_NAME]:$[$6].servername,[L0.HOOK_NAME]:`${this.pluginName} - route -> ${V}`,[L0.FASTIFY_TYPE]:s7.ROUTE,[Y4.ATTR_HTTP_ROUTE]:H.url,[L0.HOOK_CALLBACK_NAME]:U.name?.length>0?U.name:R9}));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,{[Y4.ATTR_SERVICE_NAME]:$[$6].servername,[L0.HOOK_NAME]:`${this.pluginName} - route-handler`,[L0.FASTIFY_TYPE]:s7.HANDLER,[Y4.ATTR_HTTP_ROUTE]:H.url,[L0.HOOK_CALLBACK_NAME]:H.handler.name.length>0?H.handler.name:R9})}),$.addHook("onRequest",function(H,V,F){if(this[$6].isEnabled()===!1)return F();else if(this[$6][DG]?.({url:H.url,method:H.method})===!0)return this[$6]._logger.debug(`Ignoring request ${H.method} ${H.url} because it matches the ignore path`),F();let B=s0.context.active();if(s0.trace.getSpan(B)==null)B=s0.propagation.extract(B,H.headers);let U=OG.getRPCMetadata(B);if(H.routeOptions.url!=null&&U?.type===OG.RPCType.HTTP)U.route=H.routeOptions.url;let L=this[$6].tracer.startSpan("request",{attributes:{[Y4.ATTR_SERVICE_NAME]:$[$6].servername,[L0.ROOT]:"@fastify/otel",[Y4.ATTR_HTTP_ROUTE]:H.url,[Y4.ATTR_HTTP_REQUEST_METHOD]:H.method}},B);H[$Q]=s0.trace.setSpan(B,L),H[t7]=L,s0.context.with(H[$Q],()=>{F()})}),$.addHook("onResponse",function(H,V,F){let B=H[t7];if(B!=null)B.setStatus({code:s0.SpanStatusCode.OK,message:"OK"}),B.setAttributes({[Y4.ATTR_HTTP_RESPONSE_STATUS_CODE]:404}),B.end();H[t7]=null,F()}),$.addHook=K,$.setNotFoundHandler=z,Y();function Q(H,V,F,B){let U=H[t7];if(U!=null){if(V.statusCode<500)U.setStatus({code:s0.SpanStatusCode.OK,message:"OK"});U.setAttributes({[Y4.ATTR_HTTP_RESPONSE_STATUS_CODE]:V.statusCode}),U.end()}H[t7]=null,B(null,F)}function W(H,V,F,B){let U=H[t7];if(U!=null)U.setStatus({code:s0.SpanStatusCode.ERROR,message:F.message}),U.recordException(F);B()}function K(H,V){let F=this[jn];if(Mn.includes(H))return F.call(this,H,G(V,{[Y4.ATTR_SERVICE_NAME]:$[$6].servername,[L0.HOOK_NAME]:`${this.pluginName} - ${H}`,[L0.FASTIFY_TYPE]:s7.INSTANCE,[L0.HOOK_CALLBACK_NAME]:V.name?.length>0?V.name:R9}));else return F.call(this,H,V)}function z(H,V){let F=this[Nn];if(typeof H==="function")V=G(H,{[Y4.ATTR_SERVICE_NAME]:$[$6].servername,[L0.HOOK_NAME]:`${this.pluginName} - not-found-handler`,[L0.FASTIFY_TYPE]:s7.INSTANCE,[L0.HOOK_CALLBACK_NAME]:H.name?.length>0?H.name:R9}),F.call(this,V);else{if(H.preValidation!=null)H.preValidation=G(H.preValidation,{[Y4.ATTR_SERVICE_NAME]:$[$6].servername,[L0.HOOK_NAME]:`${this.pluginName} - not-found-handler - preValidation`,[L0.FASTIFY_TYPE]:s7.INSTANCE,[L0.HOOK_CALLBACK_NAME]:H.preValidation.name?.length>0?H.preValidation.name:R9});if(H.preHandler!=null)H.preHandler=G(H.preHandler,{[Y4.ATTR_SERVICE_NAME]:$[$6].servername,[L0.HOOK_NAME]:`${this.pluginName} - not-found-handler - preHandler`,[L0.FASTIFY_TYPE]:s7.INSTANCE,[L0.HOOK_CALLBACK_NAME]:H.preHandler.name?.length>0?H.preHandler.name:R9});V=G(V,{[Y4.ATTR_SERVICE_NAME]:$[$6].servername,[L0.HOOK_NAME]:`${this.pluginName} - not-found-handler`,[L0.FASTIFY_TYPE]:s7.INSTANCE,[L0.HOOK_CALLBACK_NAME]:V.name?.length>0?V.name:R9}),F.call(this,H,V)}}function G(H,V={}){return function(...B){let U=this[$6],[L]=B;if(U.isEnabled()===!1)return H.call(this,...B);let O=L[$Q]??s0.context.active(),_=U.tracer.startSpan(`handler - ${H.name?.length>0?H.name:this.pluginName??R9}`,{attributes:V},O);return s0.context.with(s0.trace.setSpan(O,_),function(){try{let w=H.call(this,...B);if(typeof w?.then==="function")return w.then((A)=>{return _.end(),A},(A)=>{return _.setStatus({code:s0.SpanStatusCode.ERROR,message:A.message}),_.recordException(A),_.end(),Promise.reject(A)});return _.end(),w}catch(w){throw _.setStatus({code:s0.SpanStatusCode.ERROR,message:w.message}),_.recordException(w),_.end(),w}},this)}}}}}var Z5=v(u(),1),wG=v(N0(),1),AJ=v(D1(),1),In=v(X0(),1);var C9;(function(Z){Z.FASTIFY_NAME="fastify.name";let $="fastify.type";Z.FASTIFY_TYPE=$;let X="hook.name";Z.HOOK_NAME=X;let Y="plugin.name";Z.PLUGIN_NAME=Y})(C9||(C9={}));var XQ;(function(Z){Z.MIDDLEWARE="middleware";let $="request_handler";Z.REQUEST_HANDLER=$})(XQ||(XQ={}));var YQ;(function(Z){Z.MIDDLEWARE="middleware";let $="request handler";Z.REQUEST_HANDLER=$})(YQ||(YQ={}));var qn=v(u(),1);var QQ=Symbol("opentelemetry.instrumentation.fastify.request_active_span");function pD(Z,J,$,X={}){let Y=J.startSpan($,{attributes:X}),Q=Z[QQ]||[];return Q.push(Y),Object.defineProperty(Z,QQ,{enumerable:!1,configurable:!0,value:Q}),Y}function _G(Z,J){let $=Z[QQ]||[];if(!$.length)return;$.forEach((X)=>{if(J)X.setStatus({code:qn.SpanStatusCode.ERROR,message:J.message}),X.recordException(J);X.end()}),delete Z[QQ]}function En(Z,J,$){let X,Y=void 0;try{if(Y=Z(),Cn(Y))Y.then((Q)=>J(void 0,Q),(Q)=>J(Q))}catch(Q){X=Q}finally{if(!Cn(Y)){if(J(X,Y),X)throw X}return Y}}function Cn(Z){return typeof Z==="object"&&Z&&typeof Object.getOwnPropertyDescriptor(Z,"then")?.value==="function"||!1}var Ab1="0.1.0",Tb1="@sentry/instrumentation-fastify-v3",Pn="anonymous",Mb1=new Set(["onTimeout","onRequest","preParsing","preValidation","preSerialization","preHandler","onSend","onResponse","onError"]);class iD extends AJ.InstrumentationBase{constructor(Z={}){super(Tb1,Ab1,Z)}init(){return[new AJ.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(X,"send",Z._patchSend());let Q=$,W=wG.getRPCMetadata(Z5.context.active()),K=Q.routeOptions?Q.routeOptions.url:$.routerPath;if(K&&W?.type===wG.RPCType.HTTP)W.route=K;let z=$.method||"GET";d1().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 $.apply(this,Q);let W=$.name||Z||Pn,K=`${YQ.MIDDLEWARE} - ${W}`,z=Q[1],G=pD(z,Y.tracer,K,{[C9.FASTIFY_TYPE]:XQ.MIDDLEWARE,[C9.PLUGIN_NAME]:Z,[C9.HOOK_NAME]:J}),H=X&&Q[Q.length-1];if(H)Q[Q.length-1]=function(...V){_G(z),H.apply(this,V)};return Z5.context.with(Z5.trace.setSpan(Z5.context.active(),G),()=>{return En(()=>{return $.apply(this,Q)},(V)=>{if(V instanceof Error)G.setStatus({code:Z5.SpanStatusCode.ERROR,message:V.message}),G.recordException(V);if(!X)_G(z)})})}}_wrapAddHook(){let Z=this;return this._diag.debug("Patching fastify server.addHook function"),function(J){return function(...X){let Y=X[0],Q=X[1],W=this.pluginName;if(!Mb1.has(Y))return J.apply(this,X);let K=typeof X[X.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,X);return Y.addHook("onRequest",J._hookOnRequest()),Y.addHook("preHandler",J._hookPreHandler()),jb1(),J._wrap(Y,"addHook",J._wrapAddHook()),Y}if(Z.errorCodes!==void 0)$.errorCodes=Z.errorCodes;return $.fastify=$,$.default=$,$}_patchSend(){let Z=this;return this._diag.debug("Patching fastify reply.send function"),function($){return function(...Y){let Q=Y[0];if(!Z.isEnabled())return $.apply(this,Y);return AJ.safeExecuteInTheMiddle(()=>{return $.apply(this,Y)},(W)=>{if(!W&&Q instanceof Error)W=Q;_G(this,W)})}}}_hookPreHandler(){let Z=this;return this._diag.debug("Patching fastify preHandler function"),function($,X,Y){if(!Z.isEnabled())return Y();let Q=$,W=Q.routeOptions?.handler||Q.context?.handler,K=W?.name.startsWith("bound ")?W.name.substring(6):W?.name,z=`${YQ.REQUEST_HANDLER} - ${K||this.pluginName||Pn}`,G={[C9.PLUGIN_NAME]:this.pluginName,[C9.FASTIFY_TYPE]:XQ.REQUEST_HANDLER,[In.SEMATTRS_HTTP_ROUTE]:Q.routeOptions?Q.routeOptions.url:$.routerPath};if(K)G[C9.FASTIFY_NAME]=K;let H=pD(X,Z.tracer,z,G);Sn(H);let{requestHook:V}=Z.getConfig();if(V)AJ.safeExecuteInTheMiddle(()=>V(H,{request:$}),(F)=>{if(F)Z._diag.error("request hook failed",F)},!0);return Z5.context.with(Z5.trace.setSpan(Z5.context.active(),H),()=>{Y()})}}}function jb1(){let Z=p();if(Z)Z.on("spanStart",(J)=>{Sn(J)})}function Sn(Z){let J=X1(Z).data,$=J["fastify.type"];if(J[U1]||!$)return;Z.setAttributes({[W1]:"auto.http.otel.fastify",[U1]:`${$}.fastify`});let X=J["fastify.name"]||J["plugin.name"]||J["hook.name"];if(typeof X==="string"){let Y=X.replace(/^fastify -> /,"").replace(/^@fastify\/otel -> /,"");Z.updateName(Y)}}var AG="Fastify",kn=s(`${AG}.v3`,()=>new iD);function Nb1(){let Z=p();if(!Z)return;else return Z.getIntegrationByName(AG)}function yn(Z,J,$,X){let Y=Nb1()?.getShouldHandleError()||hn;if(X==="diagnostics-channel")this.diagnosticsChannelExists=!0;if(this.diagnosticsChannelExists&&X==="onError-hook"){u0&&R.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,$))O1(Z,{mechanism:{handled:!1,type:"auto.function.fastify"}})}var xn=s(`${AG}.v5`,()=>{let Z=new lD,J=Z.plugin();return nD.subscribe("fastify.initialization",($)=>{let X=$.fastify;X?.register(J).after((Y)=>{if(Y)u0&&R.error("Failed to setup Fastify instrumentation",Y);else if(Cb1(),X)qb1(X)})}),nD.subscribe("tracing:fastify.request.handler:error",($)=>{let{error:X,request:Y,reply:Q}=$;yn.call(yn,X,Y,Q,"diagnostics-channel")}),Z}),Rb1=({shouldHandleError:Z})=>{let J;return{name:AG,setupOnce(){J=Z||hn,kn(),xn()},getShouldHandleError(){return J},setShouldHandleError($){J=$}}},vn=k((Z={})=>Rb1(Z));function hn(Z,J,$){let X=$.statusCode;return X>=500||X<=299}function fn(Z){let J=X1(Z),$=J.description,X=J.data,Y=X["fastify.type"],Q=Y==="hook",W=Y===$?.startsWith("handler -"),K=$==="request"||Y==="request-handler";if(X[U1]||!W&&!K&&!Q)return;let z=Q?"hook":W?"middleware":K?"request-handler":"<unknown>";Z.setAttributes({[W1]:"auto.http.otel.fastify",[U1]:`${z}.fastify`});let G=X["fastify.name"]||X["plugin.name"]||X["hook.name"];if(typeof G==="string"){let H=G.replace(/^fastify -> /,"").replace(/^@fastify\/otel -> /,"");Z.updateName(H)}}function Cb1(){let Z=p();if(Z)Z.on("spanStart",(J)=>{fn(J)})}function qb1(Z){Z.addHook("onRequest",async(J,$)=>{if(J.opentelemetry){let{span:Q}=J.opentelemetry();if(Q)fn(Q)}let X=J.routeOptions?.url,Y=J.method||"GET";d1().setTransactionName(`${Y} ${X}`)})}var Ta=v(u(),1),Ma=v(Aa(),1);var ja="Graphql",Na=s(ja,Ma.GraphQLInstrumentation,(Z)=>{let J=Ca(Z);return{...J,responseHook($,X){if(Y0($,"auto.graphql.otel.graphql"),X.errors?.length&&!X1($).status)$.setStatus({code:Ta.SpanStatusCode.ERROR});let Q=X1($).data,W=Q["graphql.operation.type"],K=Q["graphql.operation.name"];if(J.useOperationNameForRootSpan&&W){let z=g0($),H=X1(z).data[$X]||[],V=K?`${W} ${K}`:`${W}`;if(Array.isArray(H))H.push(V),z.setAttribute($X,H);else if(typeof H==="string")z.setAttribute($X,[H,V]);else z.setAttribute($X,V);if(!X1(z).data["original-description"])z.setAttribute("original-description",X1(z).description);z.updateName(`${X1(z).data["original-description"]} (${Xg1(H)})`)}}}}),$g1=(Z={})=>{return{name:ja,setupOnce(){Na(Ca(Z))}}},Ra=k($g1);function Ca(Z){return{ignoreResolveSpans:!0,ignoreTrivialResolveSpans:!0,useOperationNameForRootSpan:!0,...Z}}function Xg1(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 oa=v(aa(),1);var ra="Kafka",sa=s(ra,()=>new oa.KafkaJsInstrumentation({consumerHook(Z){Y0(Z,"auto.kafkajs.otel.consumer")},producerHook(Z){Y0(Z,"auto.kafkajs.otel.producer")}})),jg1=()=>{return{name:ra,setupOnce(){sa()}}},ta=k(jg1);var Ho=v(Go(),1);var Vo="LruMemoizer",Fo=s(Vo,()=>new Ho.LruMemoizerInstrumentation),qg1=()=>{return{name:Vo,setupOnce(){Fo()}}},Bo=k(qg1);var Io=v(Po(),1);var So="Mongo",yo=s(So,()=>new Io.MongoDBInstrumentation({dbStatementSerializer:cg1,responseHook(Z){Y0(Z,"auto.db.otel.mongo")}}));function cg1(Z){let J=WO(Z);return JSON.stringify(J)}function WO(Z){if(Array.isArray(Z))return Z.map((J)=>WO(J));if(lg1(Z)){let J={};return Object.entries(Z).map(([$,X])=>[$,WO(X)]).reduce(($,X)=>{if(ig1(X))$[X[0]]=X[1];return $},J)}return"?"}function lg1(Z){return typeof Z==="object"&&Z!==null&&!pg1(Z)}function pg1(Z){let J=!1;if(typeof Buffer<"u")J=Buffer.isBuffer(Z);return J}function ig1(Z){return Array.isArray(Z)}var ng1=()=>{return{name:So,setupOnce(){yo()}}},ko=k(ng1);var Zr=v(eo(),1);var Jr="Mongoose",$r=s(Jr,()=>new Zr.MongooseInstrumentation({responseHook(Z){Y0(Z,"auto.db.otel.mongoose")}})),Um1=()=>{return{name:Jr,setupOnce(){$r()}}},Xr=k(Um1);var Ar=v(wr(),1);var Tr="Mysql",Mr=s(Tr,()=>new Ar.MySQLInstrumentation({})),gm1=()=>{return{name:Tr,setupOnce(){Mr()}}},jr=k(gm1);var dr=v(ur(),1);var cr="Mysql2",lr=s(cr,()=>new dr.MySQL2Instrumentation({responseHook(Z){Y0(Z,"auto.db.otel.mysql2")}})),Bu1=()=>{return{name:cr,setupOnce(){lr()}}},pr=k(Bu1);var ls=v(Hs(),1),ps=v(gs(),1);var ou1=["get","set","setex"],EO=["get","mget"],ru1=["set","setex"];function LQ(Z,J){return Z.includes(J.toLowerCase())}function PO(Z){if(LQ(EO,Z))return"cache.get";else if(LQ(ru1,Z))return"cache.put";else return}function su1(Z,J){return J.some(($)=>Z.startsWith($))}function us(Z,J){try{if(J.length===0)return;let $=(Y)=>{if(typeof Y==="string"||typeof Y==="number"||Buffer.isBuffer(Y))return[Y.toString()];else if(Array.isArray(Y))return ms(Y.map((Q)=>$(Q)));else return["<unknown>"]},X=J[0];if(LQ(ou1,Z)&&X!=null)return $(X);return ms(J.map((Y)=>$(Y)))}catch{return}}function ds(Z,J,$){if(!PO(Z))return!1;for(let X of J)if(su1(X,$))return!0;return!1}function cs(Z){let J=($)=>{try{if(Buffer.isBuffer($))return $.byteLength;else if(typeof $==="string")return $.length;else if(typeof $==="number")return $.toString().length;else if($===null||$===void 0)return 0;return JSON.stringify($).length}catch{return}};return Array.isArray(Z)?Z.reduce(($,X)=>{let Y=J(X);return typeof Y==="number"?$!==void 0?$+Y:Y:$},0):J(Z)}function ms(Z){let J=[],$=(X)=>{X.forEach((Y)=>{if(Array.isArray(Y))$(Y);else J.push(Y)})};return $(Z),J}var vG="Redis",DQ={},is=(Z,J,$,X)=>{Z.setAttribute(W1,"auto.db.otel.redis");let Y=us(J,$),Q=PO(J);if(!Y||!Q||!DQ.cachePrefixes||!ds(J,Y,DQ.cachePrefixes))return;let W=X1(Z).data["net.peer.name"],K=X1(Z).data["net.peer.port"];if(K&&W)Z.setAttributes({"network.peer.address":W,"network.peer.port":K});let z=cs(X);if(z)Z.setAttribute(wL,z);if(LQ(EO,J)&&z!==void 0)Z.setAttribute(OL,z>0);Z.setAttributes({[U1]:Q,[_L]:Y});let G=Y.join(", ");Z.updateName(DQ.maxCacheKeyLength?M7(G,DQ.maxCacheKeyLength):G)},tu1=s(`${vG}.IORedis`,()=>{return new ls.IORedisInstrumentation({responseHook:is})}),eu1=s(`${vG}.Redis`,()=>{return new ps.RedisInstrumentation({responseHook:is})}),ns=Object.assign(()=>{tu1(),eu1()},{id:vG}),Zd1=(Z={})=>{return{name:vG,setupOnce(){DQ=Z,ns()}}},as=k(Zd1);var Nt=v(jt(),1);var Rt="Postgres",Ct=s(Rt,()=>new Nt.PgInstrumentation({requireParentSpan:!0,requestHook(Z){Y0(Z,"auto.db.otel.postgres")}})),id1=()=>{return{name:Rt,setupOnce(){Ct()}}},qt=k(id1);var jX=v(u(),1),I9=v(D1(),1),t0=v(X0(),1);var dG="PostgresJs",Et=[">=3.0.0 <4"],nd1=/^(SELECT|INSERT|UPDATE|DELETE|CREATE|DROP|ALTER)/i,uG=Symbol("sentryPostgresConnectionContext"),hO=Symbol.for("sentry.instrumented.postgresjs"),Pt=Symbol.for("sentry.query.from.instrumented.sql"),It=s(dG,(Z)=>new St({requireParentSpan:Z?.requireParentSpan??!0,requestHook:Z?.requestHook}));class St extends I9.InstrumentationBase{constructor(Z){super("sentry-postgres-js",u1,Z)}init(){let Z=new I9.InstrumentationNodeModuleDefinition("postgres",Et,(J)=>{try{return this._patchPostgres(J)}catch($){return u0&&R.error("Failed to patch postgres module:",$),J}},(J)=>J);return["src","cf/src","cjs/src"].forEach((J)=>{Z.files.push(new I9.InstrumentationNodeModuleFile(`postgres/${J}/query.js`,Et,this._patchQueryPrototype.bind(this),this._unpatchQueryPrototype.bind(this)))}),Z}_patchPostgres(Z){let J=typeof Z==="function",$=J?Z:Z.default;if(typeof $!=="function")return u0&&R.warn("postgres module does not export a function. Skipping instrumentation."),Z;let X=this,Y=function(...Q){let W=Reflect.construct($,Q);if(!W||typeof W!=="function")return u0&&R.warn("postgres() did not return a valid instance"),W;return X._instrumentSqlInstance(W)};Object.setPrototypeOf(Y,$),Object.setPrototypeOf(Y.prototype,$.prototype);for(let Q of Object.getOwnPropertyNames($))if(!["length","name","prototype"].includes(Q)){let W=Object.getOwnPropertyDescriptor($,Q);if(W)Object.defineProperty(Y,Q,W)}if(J)return Y;else return q3(Z,"default",Y),Z}_wrapQueryMethod(Z,J,$){let X=this;return function(...Y){let Q=Reflect.apply(Z,J,Y);if(Q&&typeof Q==="object"&&"handle"in Q)X._wrapSingleQueryHandle(Q,$);return Q}}_wrapCallbackMethod(Z,J,$){let X=this;return function(...Y){let Q=$[uG];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 X._instrumentSqlInstance(V,Q)});return H}let K=Y.length===1?Y[0]:Y[1],z=function(H){let V=X._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(t0.ATTR_DB_NAMESPACE,J.ATTR_DB_NAMESPACE);if(J.ATTR_SERVER_ADDRESS)Z.setAttribute(t0.ATTR_SERVER_ADDRESS,J.ATTR_SERVER_ADDRESS);if(J.ATTR_SERVER_PORT!==void 0){let $=parseInt(J.ATTR_SERVER_PORT,10);if(!isNaN($))Z.setAttribute(t0.ATTR_SERVER_PORT,$)}}_setOperationName(Z,J,$){if($){Z.setAttribute(t0.ATTR_DB_OPERATION_NAME,$);return}let X=J?.match(nd1);if(X?.[1])Z.setAttribute(t0.ATTR_DB_OPERATION_NAME,X[1].toUpperCase())}_attachConnectionContext(Z,J){let $=Z;if(!$.options||typeof $.options!=="object")return;let X=$.options,Y=X.host?.[0]||"localhost",Q=X.port?.[0]||5432,W={ATTR_DB_NAMESPACE:typeof X.database==="string"&&X.database!==""?X.database:void 0,ATTR_SERVER_ADDRESS:Y,ATTR_SERVER_PORT:String(Q)};J[uG]=W}_instrumentSqlInstance(Z,J){if(Z[hO])return Z;let $=this,X=new Proxy(Z,{apply(Y,Q,W){let K=Reflect.apply(Y,Q,W);if(K&&typeof K==="object"&&"handle"in K)$._wrapSingleQueryHandle(K,X);return K},get(Y,Q){let W=Y[Q];if(typeof Q!=="string"||typeof W!=="function")return W;if(Q==="unsafe"||Q==="file")return $._wrapQueryMethod(W,Y,X);if(Q==="begin"||Q==="reserve")return $._wrapCallbackMethod(W,Y,X);return W}});if(J)X[uG]=J;else this._attachConnectionContext(Z,X);return Z[hO]=!0,X[hO]=!0,X}_wrapSingleQueryHandle(Z,J){if(Z.handle?.__sentryWrapped)return;Z[Pt]=!0;let $=Z.handle,X=this,Y=async function(...Q){if(!X._shouldCreateSpans())return $.apply(this,Q);let W=X._reconstructQuery(Z.strings),K=X._sanitizeSqlQuery(W);return P4({name:K||"postgresjs.query",op:"db"},(z)=>{Y0(z,"auto.db.postgresjs"),z.setAttributes({[t0.ATTR_DB_SYSTEM_NAME]:"postgres",[t0.ATTR_DB_QUERY_TEXT]:K});let G=J?J[uG]:void 0;X._setConnectionAttributes(z,G);let H=X.getConfig(),{requestHook:V}=H;if(V)I9.safeExecuteInTheMiddle(()=>V(z,K,G),(B)=>{if(B)z.setAttribute("sentry.hook.error","requestHook failed"),u0&&R.error(`Error in requestHook for ${dG} integration:`,B)},!0);let F=this;F.resolve=new Proxy(F.resolve,{apply:(B,U,L)=>{try{X._setOperationName(z,K,L?.[0]?.command),z.end()}catch(O){u0&&R.error("Error ending span in resolve callback:",O)}return Reflect.apply(B,U,L)}}),F.reject=new Proxy(F.reject,{apply:(B,U,L)=>{try{z.setStatus({code:v1,message:L?.[0]?.message||"unknown_error"}),z.setAttribute(t0.ATTR_DB_RESPONSE_STATUS_CODE,L?.[0]?.code||"unknown"),z.setAttribute(t0.ATTR_ERROR_TYPE,L?.[0]?.name||"unknown"),X._setOperationName(z,K),z.end()}catch(O){u0&&R.error("Error ending span in reject callback:",O)}return Reflect.apply(B,U,L)}});try{return $.apply(this,Q)}catch(B){throw z.setStatus({code:v1,message:B instanceof Error?B.message:"unknown_error"}),z.end(),B}})};Y.__sentryWrapped=!0,Z.handle=Y}_shouldCreateSpans(){let Z=this.getConfig();return jX.trace.getSpan(jX.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)=>X===0?$:`${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,$=Z.Query.prototype.handle;return Z.Query.prototype.handle=async function(...X){if(this[Pt])return $.apply(this,X);if(!J._shouldCreateSpans())return $.apply(this,X);let Y=J._reconstructQuery(this.strings),Q=J._sanitizeSqlQuery(Y);return P4({name:Q||"postgresjs.query",op:"db"},(W)=>{Y0(W,"auto.db.postgresjs"),W.setAttributes({[t0.ATTR_DB_SYSTEM_NAME]:"postgres",[t0.ATTR_DB_QUERY_TEXT]:Q});let K=J.getConfig(),{requestHook:z}=K;if(z)I9.safeExecuteInTheMiddle(()=>z(W,Q,void 0),(V)=>{if(V)W.setAttribute("sentry.hook.error","requestHook failed"),u0&&R.error(`Error in requestHook for ${dG} 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){u0&&R.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:v1,message:B?.[0]?.message||"unknown_error"}),W.setAttribute(t0.ATTR_DB_RESPONSE_STATUS_CODE,B?.[0]?.code||"unknown"),W.setAttribute(t0.ATTR_ERROR_TYPE,B?.[0]?.name||"unknown"),J._setOperationName(W,Q),W.end()}catch(U){u0&&R.error("Error ending span in reject callback:",U)}return Reflect.apply(V,F,B)}});try{return $.apply(this,X)}catch(V){throw W.setStatus({code:v1,message:V instanceof Error?V.message:"unknown_error"}),W.end(),V}})},Z.Query.prototype.handle.__sentry_original__=$,Z}_unpatchQueryPrototype(Z){if(Z.Query.prototype.handle.__sentry_original__)Z.Query.prototype.handle=Z.Query.prototype.handle.__sentry_original__;return Z}}var ad1=(Z)=>{return{name:dG,setupOnce(){It(Z)}}},yt=k(ad1);var O8=v(u(),1);var vt=v(u(),1),cG=v(D1(),1),XZ=v(u(),1);var od1=process.env.PRISMA_SHOW_ALL_TRACES==="true",rd1="00-10-10-00";function sd1(Z){switch(Z){case"client":return XZ.SpanKind.CLIENT;case"internal":default:return XZ.SpanKind.INTERNAL}}var td1=class{tracerProvider;ignoreSpanTypes;constructor({tracerProvider:Z,ignoreSpanTypes:J}){this.tracerProvider=Z,this.ignoreSpanTypes=J}isEnabled(){return!0}getTraceParent(Z){let J=XZ.trace.getSpanContext(Z??XZ.context.active());if(J)return`00-${J.traceId}-${J.spanId}-0${J.traceFlags}`;return rd1}dispatchEngineSpans(Z){let J=this.tracerProvider.getTracer("prisma"),$=new Map,X=Z.filter((Y)=>Y.parentId===null);for(let Y of X)ht(J,Y,Z,$,this.ignoreSpanTypes)}getActiveContext(){return XZ.context.active()}runInChildSpan(Z,J){if(typeof Z==="string")Z={name:Z};if(Z.internal&&!od1)return J();let $=this.tracerProvider.getTracer("prisma"),X=Z.context??this.getActiveContext(),Y=`prisma:client:${Z.name}`;if(ft(Y,this.ignoreSpanTypes))return J();if(Z.active===!1){let Q=$.startSpan(Y,Z,X);return kt(Q,J(Q,X))}return $.startActiveSpan(Y,Z,(Q)=>kt(Q,J(Q,X)))}};function ht(Z,J,$,X,Y){if(ft(J.name,Y))return;let Q={attributes:J.attributes,kind:sd1(J.kind),startTime:J.startTime};Z.startActiveSpan(J.name,Q,(W)=>{if(X.set(J.id,W.spanContext().spanId),J.links)W.addLinks(J.links.flatMap((z)=>{let G=X.get(z);if(!G)return[];return{context:{spanId:G,traceId:W.spanContext().traceId,traceFlags:W.spanContext().traceFlags}}}));let K=$.filter((z)=>z.parentId===J.id);for(let z of K)ht(Z,z,$,X,Y);W.end(J.endTime)})}function kt(Z,J){if(ed1(J))return J.then(($)=>{return Z.end(),$},($)=>{throw Z.end(),$});return Z.end(),J}function ed1(Z){return Z!=null&&typeof Z.then==="function"}function ft(Z,J){return J.some(($)=>typeof $==="string"?$===Z:$.test(Z))}var bt={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},bO=bt.version,Zc1=bO.split(".")[0],xt="PRISMA_INSTRUMENTATION",fO=`V${Zc1}_PRISMA_INSTRUMENTATION`,Jc1=bt.name,$c1="@prisma/client",gt=class extends cG.InstrumentationBase{tracerProvider;constructor(Z={}){super(Jc1,bO,Z)}setTracerProvider(Z){this.tracerProvider=Z}init(){return[new cG.InstrumentationNodeModuleDefinition($c1,[bO])]}enable(){let Z=this._config,J={helper:new td1({tracerProvider:this.tracerProvider??vt.trace.getTracerProvider(),ignoreSpanTypes:Z.ignoreSpanTypes??[]})};global[xt]=J,global[fO]=J}disable(){delete global[xt],delete global[fO]}isEnabled(){return Boolean(global[fO])}};var mt="Prisma";function Xc1(Z){return!!Z&&typeof Z==="object"&&"dispatchEngineSpans"in Z}function ut(){let Z=globalThis.PRISMA_INSTRUMENTATION;return Z&&typeof Z==="object"&&"helper"in Z?Z.helper:void 0}class dt extends gt{constructor(){super()}enable(){super.enable();let Z=ut();if(Xc1(Z))Z.createEngineSpan=(J)=>{let $=O8.trace.getTracer("prismaV5Compatibility"),X=$._idGenerator;if(!X){o0(()=>{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=Yc1(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:O8.TraceFlags.SAMPLED}}}),H=O8.trace.setSpanContext(O8.context.active(),{traceId:z,spanId:W,traceFlags:O8.TraceFlags.SAMPLED});O8.context.with(H,()=>{let V={generateTraceId:()=>{return z},generateSpanId:()=>{return K}};$._idGenerator=V,$.startSpan(Y.name,{kind:Q,links:G,startTime:Y.start_time,attributes:Y.attributes}).end(Y.end_time),$._idGenerator=X})})}finally{$._idGenerator=X}}}}function Yc1(Z){switch(Z){case"client":return O8.SpanKind.CLIENT;case"internal":default:return O8.SpanKind.INTERNAL}}var Qc1=s(mt,(Z)=>{return new dt}),ct=k((Z)=>{return{name:mt,setupOnce(){Qc1()},setup(J){if(!ut())return;J.on("spanStart",($)=>{let X=X1($);if(X.description?.startsWith("prisma:"))$.setAttribute(W1,"auto.db.otel.prisma");if(X.description==="prisma:engine:db_query"&&X.data["db.query.text"])$.updateName(X.data["db.query.text"]);if(X.description==="prisma:engine:db_query"&&!X.data["db.system"])$.setAttribute("db.system","prisma")})}}});var Ve=v(He(),1);var Fe="Hapi",Be=s(Fe,()=>new Ve.HapiInstrumentation),Pc1=()=>{return{name:Fe,setupOnce(){Be()}}},Ue=k(Pc1);var iG=v(X0(),1);var QZ={HONO_TYPE:"hono.type",HONO_NAME:"hono.name"},TQ={MIDDLEWARE:"middleware",REQUEST_HANDLER:"request_handler"};var jJ=v(u(),1),pG=v(D1(),1);var Ic1="@sentry/instrumentation-hono",Sc1="0.0.1";class cO extends pG.InstrumentationBase{constructor(Z={}){super(Ic1,Sc1,Z)}init(){return[new pG.InstrumentationNodeModuleDefinition("hono",[">=4.0.0 <5"],(Z)=>this._patch(Z))]}_patch(Z){let J=this;class $ extends Z.Hono{constructor(...X){super(...X);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=$}catch{return{...Z,Hono:$}}return Z}_patchHandler(){let Z=this;return function(J){return function(...X){if(typeof X[0]==="string"){let Y=X[0];if(X.length===1)return J.apply(this,[Y]);let Q=X.slice(1);return J.apply(this,[Y,...Q.map((W)=>Z._wrapHandler(W))])}return J.apply(this,X.map((Y)=>Z._wrapHandler(Y)))}}}_patchOnHandler(){let Z=this;return function(J){return function(...X){let Y=X.slice(2);return J.apply(this,[...X.slice(0,2),...Y.map((Q)=>Z._wrapHandler(Q))])}}}_patchMiddlewareHandler(){let Z=this;return function(J){return function(...X){if(typeof X[0]==="string"){let Y=X[0];if(X.length===1)return J.apply(this,[Y]);let Q=X.slice(1);return J.apply(this,[Y,...Q.map((W)=>Z._wrapHandler(W))])}return J.apply(this,X.map((Y)=>Z._wrapHandler(Y)))}}}_wrapHandler(Z){let J=this;return function($,X){if(!J.isEnabled())return Z.apply(this,[$,X]);let Y=$.req.path,Q=J.tracer.startSpan(Y);return jJ.context.with(jJ.trace.setSpan(jJ.context.active(),Q),()=>{return J._safeExecute(()=>{let W=Z.apply(this,[$,X]);if(t4(W))return W.then((K)=>{let z=J._determineHandlerType(K);return Q.setAttributes({[QZ.HONO_TYPE]:z,[QZ.HONO_NAME]:z===TQ.REQUEST_HANDLER?Y:Z.name||"anonymous"}),J.getConfig().responseHook?.(Q),K});else{let K=J._determineHandlerType(W);return Q.setAttributes({[QZ.HONO_TYPE]:K,[QZ.HONO_NAME]:K===TQ.REQUEST_HANDLER?Y:Z.name||"anonymous"}),J.getConfig().responseHook?.(Q),W}},()=>Q.end(),(W)=>{J._handleError(Q,W),Q.end()})})}}_safeExecute(Z,J,$){try{let X=Z();if(t4(X))X.then(()=>J(),(Y)=>$(Y));else J();return X}catch(X){throw $(X),X}}_determineHandlerType(Z){return Z===void 0?TQ.MIDDLEWARE:TQ.REQUEST_HANDLER}_handleError(Z,J){if(J instanceof Error)Z.setStatus({code:jJ.SpanStatusCode.ERROR,message:J.message}),Z.recordException(J)}}var Le="Hono";function yc1(Z){let J=X1(Z).data,$=J[QZ.HONO_TYPE];if(J[U1]||!$)return;Z.setAttributes({[W1]:"auto.http.otel.hono",[U1]:`${$}.hono`});let X=J[QZ.HONO_NAME];if(typeof X==="string")Z.updateName(X);if(d1()===y6()){u0&&R.warn("Isolation scope is default isolation scope - skipping setting transactionName");return}let Y=J[iG.ATTR_HTTP_ROUTE],Q=J[iG.ATTR_HTTP_REQUEST_METHOD];if(typeof Y==="string"&&typeof Q==="string")d1().setTransactionName(`${Q} ${Y}`)}var De=s(Le,()=>new cO({responseHook:(Z)=>{yc1(Z)}})),kc1=()=>{return{name:Le,setupOnce(){De()}}},Oe=k(kc1);var me=v(ge(),1),ue=v(X0(),1);var de="Koa",ce=s(de,me.KoaInstrumentation,(Z={})=>{return{ignoreLayersType:Z.ignoreLayersType,requestHook(J,$){Y0(J,"auto.http.otel.koa");let X=X1(J).data,Y=X["koa.type"];if(Y)J.setAttribute(U1,`${Y}.koa`);let Q=X["koa.name"];if(typeof Q==="string")J.updateName(Q||"< unknown >");if(d1()===y6()){u0&&R.warn("Isolation scope is default isolation scope - skipping setting transactionName");return}let W=X[ue.ATTR_HTTP_ROUTE],K=$.context?.request?.method?.toUpperCase()||"GET";if(W)d1().setTransactionName(`${K} ${W}`)}}}),pc1=(Z={})=>{return{name:de,setupOnce(){ce(Z)}}},le=k(pc1);var V11=v(H11(),1);var F11="Connect",B11=s(F11,()=>new V11.ConnectInstrumentation),Ql1=()=>{return{name:F11,setupOnce(){B11()}}},U11=k(Ql1);var y11=v(S11(),1);var Al1=new Set(["callProcedure","execSql","execSqlBatch","execBulkLoad","prepare","execute"]),k11="Tedious",x11=s(k11,()=>new y11.TediousInstrumentation({})),Tl1=()=>{let Z;return{name:k11,setupOnce(){let J=x11();Z=i3(J)},setup(J){Z?.(()=>J.on("spanStart",($)=>{let{description:X,data:Y}=X1($);if(!X||Y["db.system"]!=="mssql")return;let Q=X.split(" ")[0]||"";if(Al1.has(Q))$.setAttribute(W1,"auto.db.otel.tedious")}))}}},v11=k(Tl1);var p11=v(l11(),1);var i11="GenericPool",n11=s(i11,()=>new p11.GenericPoolInstrumentation({})),Rl1=()=>{let Z;return{name:i11,setupOnce(){let J=n11();Z=i3(J)},setup(J){Z?.(()=>J.on("spanStart",($)=>{let Y=X1($).description;if(Y==="generic-pool.aquire"||Y==="generic-pool.acquire")$.setAttribute(W1,"auto.db.otel.generic_pool")}))}}},a11=k(Rl1);var _01=v(O01(),1);var w01="Amqplib",Qp1={consumeEndHook:(Z)=>{Y0(Z,"auto.amqplib.otel.consumer")},publishHook:(Z)=>{Y0(Z,"auto.amqplib.otel.publisher")}},A01=s(w01,()=>new _01.AmqplibInstrumentation(Qp1)),Wp1=()=>{return{name:w01,setupOnce(){A01()}}},T01=k(Wp1);var CQ="VercelAI";var JH=v(D1(),1);var Kp1=[">=3.0.0 <7"],M01=["generateText","streamText","generateObject","streamObject","embed","embedMany"];function zp1(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 Gp1(Z){if(typeof Z!=="object"||Z===null||!("content"in Z))return;let J=Z;if(!Array.isArray(J.content))return;for(let $ of J.content)if(zp1($)){let X=F2($.toolCallId);if(X){let Y=X.spanContext();D6((Q)=>{Q.setContext("trace",{trace_id:Y.traceId,span_id:Y.spanId}),Q.setTag("vercel.ai.tool.name",$.toolName),Q.setTag("vercel.ai.tool.callId",$.toolCallId),Q.setLevel("error"),O1($.error,{mechanism:{type:"auto.vercelai.otel",handled:!1}})}),B2($.toolCallId)}else D6((Y)=>{Y.setTag("vercel.ai.tool.name",$.toolName),Y.setTag("vercel.ai.tool.callId",$.toolCallId),Y.setLevel("error"),O1($.error,{mechanism:{type:"auto.vercelai.otel",handled:!1}})})}}function Hp1(Z,J,$,X){let Y=Z?.recordInputs!==void 0?Z.recordInputs:J.recordInputs!==void 0?J.recordInputs:$===!0?!0:X,Q=Z?.recordOutputs!==void 0?Z.recordOutputs:J.recordOutputs!==void 0?J.recordOutputs:$===!0?!0:X;return{recordInputs:Y,recordOutputs:Q}}class qQ extends JH.InstrumentationBase{__init(){this._isPatched=!1}__init2(){this._callbacks=[]}constructor(Z={}){super("@sentry/instrumentation-vercel-ai",u1,Z);qQ.prototype.__init.call(this),qQ.prototype.__init2.call(this)}init(){return new JH.InstrumentationNodeModuleDefinition("ai",Kp1,this._patch.bind(this))}callWhenPatched(Z){if(this._isPatched)Z();else this._callbacks.push(Z)}_patch(Z){this._isPatched=!0,this._callbacks.forEach(($)=>$()),this._callbacks=[];let J=($)=>{return new Proxy($,{apply:(X,Y,Q)=>{let W=Q[0].experimental_telemetry||{},K=W.isEnabled,z=p(),G=z?.getIntegrationByName(CQ),H=G?.options,V=G?Boolean(z?.getOptions().sendDefaultPii):!1,{recordInputs:F,recordOutputs:B}=Hp1(H,W,K,V);return Q[0].experimental_telemetry={...W,isEnabled:K!==void 0?K:!0,recordInputs:F,recordOutputs:B},k6(()=>Reflect.apply(X,Y,Q),(U)=>{if(U&&typeof U==="object")Z4(U,"_sentry_active_span",M5())},()=>{},(U)=>{Gp1(U)})}})};if(Object.prototype.toString.call(Z)==="[object Module]"){for(let $ of M01)Z[$]=J(Z[$]);return Z}else{let $=M01.reduce((X,Y)=>{return X[Y]=J(Z[Y]),X},{});return{...Z,...$}}}}var j01=s(CQ,()=>new qQ({}));function Vp1(Z){return!!Z.getIntegrationByName("Modules")?.getModules?.()?.ai}var Fp1=(Z={})=>{let J;return{name:CQ,options:Z,setupOnce(){J=j01()},afterAllSetup($){if(Z.force??Vp1($))jz($);else J?.callWhenPatched(()=>jz($))}}},N01=k(Fp1);var $H=v(D1(),1);var Bp1=[">=4.0.0 <7"];class z_ extends $H.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-openai",u1,Z)}init(){return new $H.InstrumentationNodeModuleDefinition("openai",Bp1,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 $=Z[J];if(!$)return Z;let X=this.getConfig(),Y=function(...Q){if(KJ(c7))return Reflect.construct($,Q);let W=Reflect.construct($,Q),K=p(),z=Boolean(K?.getOptions().sendDefaultPii),G=X.recordInputs??z,H=X.recordOutputs??z;return Cz(W,{recordInputs:G,recordOutputs:H})};Object.setPrototypeOf(Y,$),Object.setPrototypeOf(Y.prototype,$.prototype);for(let Q of Object.getOwnPropertyNames($))if(!["length","name","prototype"].includes(Q)){let W=Object.getOwnPropertyDescriptor($,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===$)try{Z.default=Y}catch(Q){Object.defineProperty(Z,"default",{value:Y,writable:!0,configurable:!0,enumerable:!0})}return Z}}var R01=s(c7,(Z)=>new z_(Z)),Up1=(Z={})=>{return{name:c7,setupOnce(){R01(Z)}}},C01=k(Up1);var XH=v(D1(),1);var Lp1=[">=0.19.2 <1.0.0"];class G_ extends XH.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-anthropic-ai",u1,Z)}init(){return new XH.InstrumentationNodeModuleDefinition("@anthropic-ai/sdk",Lp1,this._patch.bind(this))}_patch(Z){let J=Z.Anthropic,$=this.getConfig(),X=function(...Y){if(KJ(l7))return Reflect.construct(J,Y);let Q=Reflect.construct(J,Y),W=p(),K=Boolean(W?.getOptions().sendDefaultPii),z=$.recordInputs??K,G=$.recordOutputs??K;return D2(Q,{recordInputs:z,recordOutputs:G})};Object.setPrototypeOf(X,J),Object.setPrototypeOf(X.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(X,Y,Q)}try{Z.Anthropic=X}catch(Y){Object.defineProperty(Z,"Anthropic",{value:X,writable:!0,configurable:!0,enumerable:!0})}if(Z.default===J)try{Z.default=X}catch(Y){Object.defineProperty(Z,"default",{value:X,writable:!0,configurable:!0,enumerable:!0})}return Z}}var q01=s(l7,(Z)=>new G_(Z)),Dp1=(Z={})=>{return{name:l7,options:Z,setupOnce(){q01(Z)}}},E01=k(Dp1);var EX=v(D1(),1);var P01=[">=0.10.0 <2"];class H_ extends EX.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-google-genai",u1,Z)}init(){return new EX.InstrumentationNodeModuleDefinition("@google/genai",P01,(J)=>this._patch(J),(J)=>J,[new EX.InstrumentationNodeModuleFile("@google/genai/dist/node/index.cjs",P01,(J)=>this._patch(J),(J)=>J)])}_patch(Z){let J=Z.GoogleGenAI,$=this.getConfig();if(typeof J!=="function")return Z;let X=function(...Y){if(KJ(p7))return Reflect.construct(J,Y);let Q=Reflect.construct(J,Y),W=p(),K=Boolean(W?.getOptions().sendDefaultPii),z=$,G=z?.recordInputs??K,H=z?.recordOutputs??K;return A2(Q,{recordInputs:G,recordOutputs:H})};Object.setPrototypeOf(X,J),Object.setPrototypeOf(X.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(X,Y,Q)}return q3(Z,"GoogleGenAI",X),Z}}var I01=s(p7,(Z)=>new H_(Z)),Op1=(Z={})=>{return{name:p7,setupOnce(){I01(Z)}}},S01=k(Op1);var zZ=v(D1(),1);var YH=[">=0.1.0 <2.0.0"];function _p1(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 wp1(Z,J,$){return new Proxy(Z,{apply(X,Y,Q){let K=Q[1];if(!K||typeof K!=="object"||Array.isArray(K))K={},Q[1]=K;let z=K.callbacks,G=_p1(z,J);return K.callbacks=G,Reflect.apply(X,Y,Q)}})}class V_ extends zZ.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-langchain",u1,Z)}init(){let Z=[],J=["@langchain/anthropic","@langchain/openai","@langchain/google-genai","@langchain/mistralai","@langchain/google-vertexai","@langchain/groq"];for(let $ of J)Z.push(new zZ.InstrumentationNodeModuleDefinition($,YH,this._patch.bind(this),(X)=>X,[new zZ.InstrumentationNodeModuleFile(`${$}/dist/index.cjs`,YH,this._patch.bind(this),(X)=>X)]));return Z.push(new zZ.InstrumentationNodeModuleDefinition("langchain",YH,this._patch.bind(this),($)=>$,[new zZ.InstrumentationNodeModuleFile("langchain/dist/chat_models/universal.cjs",YH,this._patch.bind(this),($)=>$)])),Z}_patch(Z){iL([c7,l7,p7]);let J=p(),$=Boolean(J?.getOptions().sendDefaultPii),X=this.getConfig(),Y=X?.recordInputs??$,Q=X?.recordOutputs??$,W=Ez({recordInputs:Y,recordOutputs:Q});return this._patchRunnableMethods(Z,W),Z}_patchRunnableMethods(Z,J){let $=["ChatAnthropic","ChatOpenAI","ChatGoogleGenerativeAI","ChatMistralAI","ChatVertexAI","ChatGroq","ConfigurableModel"],X=Z.universal_exports??Z,Y=Object.values(X).find((K)=>{return typeof K==="function"&&$.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]=wp1(z,J)}}}var y01=s(qz,(Z)=>new V_(Z)),Ap1=(Z={})=>{return{name:qz,setupOnce(){y01(Z)}}},k01=k(Ap1);var PX=v(D1(),1);var x01=[">=0.0.0 <2.0.0"];class F_ extends PX.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-langgraph",u1,Z)}init(){return new PX.InstrumentationNodeModuleDefinition("@langchain/langgraph",x01,this._patch.bind(this),(J)=>J,[new PX.InstrumentationNodeModuleFile("@langchain/langgraph/dist/index.cjs",x01,this._patch.bind(this),(J)=>J)])}_patch(Z){let J=p(),$=Boolean(J?.getOptions().sendDefaultPii),X=this.getConfig(),Y=X.recordInputs??$,Q=X.recordOutputs??$,W={recordInputs:Y,recordOutputs:Q};if(Z.StateGraph&&typeof Z.StateGraph==="function"){let K=Z.StateGraph;K.prototype.compile=j2(K.prototype.compile,W)}return Z}}var v01=s(Pz,(Z)=>new F_(Z)),Tp1=(Z={})=>{return{name:Pz,setupOnce(){v01(Z)}}},h01=k(Tp1);var l01=v(D1(),1);var y9=v(u(),1),k9=v(D1(),1),_8=v(X0(),1);import*as b01 from"net";function g01(Z,J,$,X,Y){let W=()=>{},K=Y.firestoreSpanCreationHook;if(typeof K==="function")W=(H)=>{k9.safeExecuteInTheMiddle(()=>K(H),(V)=>{if(!V)return;y9.diag.error(V?.message)},!0)};let z=new k9.InstrumentationNodeModuleDefinition("@firebase/firestore",J,(H)=>f01(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)=>f01(V,$,X,Z,W),(V)=>m01(V,X)));return z}function f01(Z,J,$,X,Y){return m01(Z,$),J(Z,"addDoc",Mp1(X,Y)),J(Z,"getDocs",Np1(X,Y)),J(Z,"setDoc",Rp1(X,Y)),J(Z,"deleteDoc",jp1(X,Y)),Z}function m01(Z,J){for(let $ of["addDoc","getDocs","setDoc","deleteDoc"])if(k9.isWrapped(Z[$]))J(Z,$);return Z}function Mp1(Z,J){return function(X){return function(Y,Q){let W=WH(Z,"addDoc",Y);return J(W),QH(W,()=>{return X(Y,Q)})}}}function jp1(Z,J){return function(X){return function(Y){let Q=WH(Z,"deleteDoc",Y.parent||Y);return J(Q),QH(Q,()=>{return X(Y)})}}}function Np1(Z,J){return function(X){return function(Y){let Q=WH(Z,"getDocs",Y);return J(Q),QH(Q,()=>{return X(Y)})}}}function Rp1(Z,J){return function(X){return function(Y,Q,W){let K=WH(Z,"setDoc",Y.parent||Y);return J(K),QH(K,()=>{return typeof W<"u"?X(Y,Q,W):X(Y,Q)})}}}function QH(Z,J){return y9.context.with(y9.trace.setSpan(y9.context.active(),Z),()=>{return k9.safeExecuteInTheMiddle(()=>{return J()},($)=>{if($)Z.recordException($);Z.end()},!0)})}function WH(Z,J,$){let X=Z.startSpan(`${J} ${$.path}`,{kind:y9.SpanKind.CLIENT});return qp1(X,$),X.setAttribute(_8.ATTR_DB_OPERATION_NAME,J),X}function Cp1(Z){let J,$;if(typeof Z.host==="string")if(Z.host.startsWith("[")){if(Z.host.endsWith("]"))J=Z.host.replace(/^\[|\]$/g,"");else if(Z.host.includes("]:")){let X=Z.host.lastIndexOf(":");if(X!==-1)J=Z.host.slice(1,X).replace(/^\[|\]$/g,""),$=Z.host.slice(X+1)}}else if(b01.isIPv6(Z.host))J=Z.host;else{let X=Z.host.lastIndexOf(":");if(X!==-1)J=Z.host.slice(0,X),$=Z.host.slice(X+1);else J=Z.host}return{address:J,port:$?parseInt($,10):void 0}}function qp1(Z,J){let $=J.firestore.app,X=$.options,Q=(J.firestore.toJSON()||{}).settings||{},W={[_8.ATTR_DB_COLLECTION_NAME]:J.path,[_8.ATTR_DB_NAMESPACE]:$.name,[_8.ATTR_DB_SYSTEM_NAME]:"firebase.firestore","firebase.firestore.type":J.type,"firebase.firestore.options.projectId":X.projectId,"firebase.firestore.options.appId":X.appId,"firebase.firestore.options.messagingSenderId":X.messagingSenderId,"firebase.firestore.options.storageBucket":X.storageBucket},{address:K,port:z}=Cp1(Q);if(K)W[_8.ATTR_SERVER_ADDRESS]=K;if(z)W[_8.ATTR_SERVER_PORT]=z;Z.setAttributes(W)}var k5=v(u(),1),x9=v(D1(),1);function u01(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)=>{x9.safeExecuteInTheMiddle(()=>G(F,B),(U)=>{if(!U)return;k5.diag.error(U?.message)},!0)};if(typeof z==="function")Q=(F)=>{x9.safeExecuteInTheMiddle(()=>z(F),(B)=>{if(!B)return;k5.diag.error(B?.message)},!0)};let H=new x9.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 x9.InstrumentationNodeModuleFile(F,J,(U)=>Ep1(U,$,X,Z,{requestHook:Q,responseHook:W,errorHook:K},B),(U)=>d01(U,X)))}),H}function Q6(Z,J,$){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.${$}`,{kind:k5.SpanKind.SERVER}),F={"faas.name":H,"faas.trigger":$,"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),k5.context.with(k5.trace.setSpan(k5.context.active(),V),async()=>{let B,U;try{U=await W.apply(this,G)}catch(L){B=L}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 Ep1(Z,J,$,X,Y,Q){switch(d01(Z,$),Q){case"function":J(Z,"onRequest",Q6(X,Y,"http.request")),J(Z,"onCall",Q6(X,Y,"http.call"));break;case"firestore":J(Z,"onDocumentCreated",Q6(X,Y,"firestore.document.created")),J(Z,"onDocumentUpdated",Q6(X,Y,"firestore.document.updated")),J(Z,"onDocumentDeleted",Q6(X,Y,"firestore.document.deleted")),J(Z,"onDocumentWritten",Q6(X,Y,"firestore.document.written")),J(Z,"onDocumentCreatedWithAuthContext",Q6(X,Y,"firestore.document.created")),J(Z,"onDocumentUpdatedWithAuthContext",Q6(X,Y,"firestore.document.updated")),J(Z,"onDocumentDeletedWithAuthContext",Q6(X,Y,"firestore.document.deleted")),J(Z,"onDocumentWrittenWithAuthContext",Q6(X,Y,"firestore.document.written"));break;case"scheduler":J(Z,"onSchedule",Q6(X,Y,"scheduler.scheduled"));break;case"storage":J(Z,"onObjectFinalized",Q6(X,Y,"storage.object.finalized")),J(Z,"onObjectArchived",Q6(X,Y,"storage.object.archived")),J(Z,"onObjectDeleted",Q6(X,Y,"storage.object.deleted")),J(Z,"onObjectMetadataUpdated",Q6(X,Y,"storage.object.metadataUpdated"));break}return Z}function d01(Z,J){let $=["onSchedule","onRequest","onCall","onObjectFinalized","onObjectArchived","onObjectDeleted","onObjectMetadataUpdated","onDocumentCreated","onDocumentUpdated","onDocumentDeleted","onDocumentWritten","onDocumentCreatedWithAuthContext","onDocumentUpdatedWithAuthContext","onDocumentDeletedWithAuthContext","onDocumentWrittenWithAuthContext"];for(let X of $)if(x9.isWrapped(Z[X]))J(Z,X);return Z}var c01={},Pp1=[">=3.0.0 <5"],Ip1=[">=6.0.0 <7"];class B_ extends l01.InstrumentationBase{constructor(Z=c01){super("@sentry/instrumentation-firebase",u1,Z)}setConfig(Z={}){super.setConfig({...c01,...Z})}init(){let Z=[];return Z.push(g01(this.tracer,Pp1,this._wrap,this._unwrap,this.getConfig())),Z.push(u01(this.tracer,Ip1,this._wrap,this._unwrap,this.getConfig())),Z}}var p01="Firebase",Sp1={firestoreSpanCreationHook:(Z)=>{Y0(Z,"auto.firebase.otel.firestore"),Z.setAttribute(U1,"db.query")},functions:{requestHook:(Z)=>{Y0(Z,"auto.firebase.otel.functions"),Z.setAttribute(U1,"http.request")},errorHook:async(Z,J)=>{if(J)O1(J,{mechanism:{type:"auto.firebase.otel.functions",handled:!1}}),await Kz(2000)}}},i01=s(p01,()=>new B_(Sp1)),yp1=()=>{return{name:p01,setupOnce(){i01()}}},n01=k(yp1);function EQ(){return[ai(),vn(),Ra(),Oe(),ko(),Xr(),jr(),pr(),as(),qt(),ct(),Ue(),le(),U11(),v11(),a11(),ta(),T01(),Bo(),k01(),h01(),N01(),C01(),E01(),S01(),yt(),n01()]}var IX=v(u(),1);var SX=v(X0(),1);var U_=1e6;function a01(Z,J={}){if(Z.getOptions().debug)TD();let[$,X]=kp1(Z,J);Z.traceProvider=$,Z.asyncLocalStorageLookup=X}function kp1(Z,J={}){let $=new rz({sampler:new WD(Z),resource:y3().merge(lz({[SX.ATTR_SERVICE_NAME]:"node",[SX.SEMRESATTRS_SERVICE_NAMESPACE]:"sentry",[SX.ATTR_SERVICE_VERSION]:u1})),forceFlushTimeoutMillis:500,spanProcessors:[new QD({timeout:xp1(Z.getOptions().maxSpanWaitDuration)}),...J.spanProcessors||[]]});IX.trace.setGlobalTracerProvider($),IX.propagation.setGlobalPropagator(new YD);let X=new XG;return IX.context.setGlobalContextManager(X),[$,X.getAsyncLocalStorageLookup()]}function xp1(Z){if(Z==null)return;if(Z>U_)return u0&&R.warn(`\`maxSpanWaitDuration\` is too high, using the maximum value of ${U_}`),U_;else if(Z<=0||Number.isNaN(Z)){u0&&R.warn("`maxSpanWaitDuration` must be a positive number, using default value instead.");return}return Z}function o01(){return zG().filter((J)=>J.name!=="Http"&&J.name!=="NodeFetch").concat(a3(),r3())}function r01(Z){return[...o01(),...P0(Z)?EQ():[]]}function L_(Z={}){return vp1(Z,r01)}function vp1(Z={},J){_9(Z,"node");let $=SD({...Z,defaultIntegrations:Z.defaultIntegrations??J(Z)});if($&&!Z.skipOpenTelemetrySetup)a01($,{spanProcessors:Z.openTelemetrySpanProcessors}),GG();return $}import*as J41 from"os";var hp1="BunServer",fp1=()=>{return{name:hp1,setupOnce(){bp1()}}},e01=k(fp1),s01=!1;function bp1(){if(s01)return;Bun.serve=new Proxy(Bun.serve,{apply(Z,J,$){t01($[0]);let X=Z.apply(J,$),Y=X.reload.bind(X);return X.reload=(Q)=>{return t01(Q),Y(Q)},X}}),s01=!0}function t01(Z){gp1(Z),mp1(Z)}function gp1(Z){if(typeof Z.fetch!=="function")return;Z.fetch=new Proxy(Z.fetch,{apply(J,$,X){return D_(J,$,X)}})}function mp1(Z){if(!Z.routes)return;if(typeof Z.routes!=="object")return;Object.keys(Z.routes).forEach((J)=>{let $=Z.routes[J];if(typeof $==="function")Z.routes[J]=new Proxy($,{apply:(X,Y,Q)=>{return D_(X,Y,Q,J)}});if($ instanceof Response)return;if(typeof $==="object")Object.entries($).forEach(([X,Y])=>{if(typeof Y==="function")Z.routes[J][X]=new Proxy(Y,{apply:(Q,W,K)=>{return D_(Q,W,K,J)}})})})}function D_(Z,J,$,X){return rZ((Y)=>{let Q=$[0],W=Q.method.toUpperCase();if(W==="OPTIONS"||W==="HEAD")return Z.apply(J,$);let K=L3(Q.url),z=up1(K,Q),G=K?.pathname||"/";if(Q.params){if(Object.keys(Q.params).forEach((H)=>{z[`url.path.parameter.${H}`]=Q.params[H]}),X)z[E0]="route",z["url.template"]=X,G=X}if(X?.endsWith("/*"))z[E0]="route",z["url.template"]=X,G=X;return Object.assign(z,v$(Q.headers.toJSON(),p()?.getOptions().sendDefaultPii??!1)),Y.setSDKProcessingMetadata({normalizedRequest:{url:Q.url,method:Q.method,headers:Q.headers.toJSON(),query_string:K?.search}}),Yz({sentryTrace:Q.headers.get("sentry-trace")??"",baggage:Q.headers.get("baggage")},()=>h6({attributes:z,op:"http.server",name:`${Q.method} ${G}`},async(H)=>{try{let V=await Z.apply(J,$);if(V?.status)dK(H,V.status),Y.setContext("response",{headers:V.headers.toJSON(),status_code:V.status});return V}catch(V){throw O1(V,{mechanism:{type:"auto.http.bun.serve",handled:!1}}),V}}))})}function up1(Z,J){let $={[W1]:"auto.http.bun.serve",[AL]:J.method||"GET",[E0]:"url"};if(Z){if(Z.search)$["url.query"]=Z.search;if(Z.hash)$["url.fragment"]=Z.hash;if(Z.pathname)$["url.path"]=Z.pathname;if(!aL(Z)){if($["url.full"]=Z.href,Z.port)$["url.port"]=Z.port;if(Z.protocol)$["url.scheme"]=Z.protocol;if(Z.hostname)$["url.domain"]=Z.hostname}}return $}function Z41(Z){function J($){let X={body:$.body,method:"POST",headers:Z.headers};try{return S7(()=>{return fetch(Z.url,X).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 WJ(Z,J)}function $41(Z){return[f$(),h$(),b$(),g$(),m$(),a3(),r3(),HX(),VX(),zX(),KX(),GX(),e01(),...P0(Z)?EQ():[]]}function O_(Z={}){_9(Z,"bun");let J={...Z,platform:"javascript",runtime:{name:"bun",version:Bun.version},serverName:Z.serverName||global.process.env.SENTRY_NAME||J41.hostname()};if(J.transport=J.transport||Z41,J.defaultIntegrations===void 0)J.defaultIntegrations=$41(J);return L_(J)}O_({dsn:"https://f0ba950f2a01c32d24ccd8711de778be@o4510345514123264.ingest.us.sentry.io/4510346875043848",tracesSampleRate:1,sendDefaultPii:!1});import{readFileSync as X41}from"fs";import{join as Y41}from"path";function O0(){return"3.3.0-beta.2"}function __(Z){let[J,$]=Z.split("-"),X=(J||"0.0.0").split(".").map(Number),Y=null,Q=0;if($){let W=$.match(/^([a-z]+)\.?(\d+)?$/i);if(W)Y=W[1]||null,Q=parseInt(W[2]||"0",10);else Y=$}return{major:X[0]||0,minor:X[1]||0,patch:X[2]||0,preRelease:Y,preReleaseNum:Q}}function v9(Z){let J=__(Z);if(!J.preRelease)return"stable";if(J.preRelease.startsWith("alpha"))return"alpha";return"beta"}function PQ(Z,J){try{let $=__(Z),X=__(J);if($.major>X.major)return!1;if($.major<X.major)return!1;if(X.preRelease&&!$.preRelease)return!1;if(!X.preRelease&&$.preRelease)return!1;if(X.preRelease&&$.preRelease){if($.minor<X.minor)return!1;if($.minor>X.minor)return!0;if($.patch>X.patch)return!0;if($.patch<X.patch)return!1;return $.preReleaseNum>X.preReleaseNum}if($.minor>X.minor)return!0;if($.minor<X.minor)return!1;if($.patch>X.patch)return!0;return!1}catch($){return!1}}import{parseArgs as cp1}from"util";var lp1={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 Q41(){let Z=cp1({options:lp1,allowPositionals:!1,strict:!0});if(Z.values.version)console.log(`ccc v${O0()}`),process.exit(0);if(Z.values.help)pp1(),process.exit(0);let J=process.env.CCC_USERNAME||Z.values.username,$=process.env.CCC_PASSWORD||Z.values.password,X=process.env.CCC_NGROK_TOKEN||Z.values["ngrok-token"],Y=process.env.CCC_NGROK_DOMAIN||Z.values["ngrok-domain"];if(!J||!$)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:$,ngrokToken:X,ngrokDomain:Y,autoUpdate:!Z.values["no-auto-update"],autoUpdateCheckInterval:parseInt(Z.values["auto-update-check-interval"],10),terminalAudit:Z.values["terminal-audit"]}}function pp1(){console.log(`
|
|
55
55
|
Backend v2 - Clean modular architecture
|
|
56
56
|
|
|
57
57
|
Usage:
|
|
@@ -2406,7 +2406,7 @@ $ ${z}
|
|
|
2406
2406
|
${H}${H.endsWith(`
|
|
2407
2407
|
`)?"":`
|
|
2408
2408
|
`}\`\`\`${V!==0?`
|
|
2409
|
-
Exit code: ${V}`:""}`}]}};this.publishOutput($,W.sessionId,F)}catch(G){let H={type:"error",error:{message:`Bash: ${G instanceof Error?G.message:"failed"}`,type:"bash_error"}};this.publishOutput($,W.sessionId,H)}finally{this.publishStatus($,W.sessionId,{type:"session_idle",sessionId:W.sessionId,timestamp:Date.now()})}this.totalMessagesProcessed++;return}}await this.sessionManager.sendMessage(Y.sessionId,Y.message||"",Y.attachments),this.totalMessagesProcessed++}catch(X){V1.error("[PiAgent] Error handling user input:",{profileId:$,sessionId:Z,error:X instanceof Error?X.message:"Unknown error"})}}async handlePermissionResponseFromMobile(Z,J){let $,X,Y="";try{let Q=await this.parseMessage(J);if(!Q)return;if($=Q.data,X=$.requestId,Y=Q.profileId,!this.sessionManager.getSession(Z)){V1.warn(`[PiAgent] Session ${Z} not found for permission response`),this.publishStatus(Y,Z,{type:"session_stopped",reason:"session_lost",message:"Session is no longer active.",timestamp:Date.now()});return}if(this.sessionManager.sendApprovalResponse(X,$.approved),!$.approved&&$.hardDeny){let K=Y;setTimeout(()=>{this.sessionManager.stopSession(Z).catch(()=>{}),this.publishStatus(K,Z,{type:"session_stopped",reason:"permission_denied",message:$.denyMessage||"Permission denied by user",timestamp:Date.now()})},100)}if(X)this.pendingPermissions.delete(X),B0.removePermission(X).catch(()=>{})}catch(Q){if(V1.error("[PiAgent] Error handling permission response:",{profileId:Y,sessionId:Z,error:Q instanceof Error?Q.message:"Unknown error"}),Y)this.publishStatus(Y,Z,{type:"session_stopped",reason:"session_lost",message:"Session is no longer active. The permission request could not be delivered.",timestamp:Date.now()});if(X)this.pendingPermissions.delete(X),B0.removePermission(X).catch(()=>{})}}async handleSessionStop(Z,J){let X=(await this.parseMessage(J))?.profileId||"";V1.debug("[PiAgent] Session stop request:",{profileId:X,sessionId:Z});try{await this.sessionManager.stopSession(Z)}catch(Y){V1.error("[PiAgent] Failed to stop session",{sessionId:Z,error:Y})}}async handleTogglePi(Z){let J="";try{let $=await this.parseMessage(Z);if(!$)return;J=$.profileId;let{enabled:X}=$.data;if(X)V1.info("[PiAgent] Enabling Pi..."),W7("pi_enabled",!0);else V1.info("[PiAgent] Disabling Pi, stopping all sessions..."),W7("pi_enabled",!1),await this.sessionManager.stopAll();this.publishToggleResponse(J,{enabled:!!X})}catch($){if(V1.error("[PiAgent] Error toggling Pi:",{profileId:J,error:$ instanceof Error?$.message:"Unknown error"}),J)this.publishToggleResponse(J,{enabled:!1,error:$ instanceof Error?$.message:"Failed to toggle Pi"})}}async handleGetEnabled(Z){let J=await this.parseMessage(Z);if(!J)return;let $=J.profileId,X=D5("pi_enabled")||!1;this.publishToggleResponse($,{enabled:X})}async handleSetModel(Z,J){let $="";try{let X=await this.parseMessage(J);if(!X)return;$=X.profileId;let{model:Y}=X.data;await this.sessionManager.setModel(Z,Y)}catch(X){V1.error("[PiAgent] Error setting model:",{profileId:$,sessionId:Z,error:X instanceof Error?X.message:"Unknown error"})}}async handleSetThinkingLevel(Z,J){let $="";try{let X=await this.parseMessage(J);if(!X)return;$=X.profileId;let{level:Y}=X.data;this.sessionManager.setThinkingLevel(Z,Y),this.publishStatus($,Z,{type:"thinking_level_changed",thinkingLevel:Y,timestamp:Date.now()})}catch(X){V1.error("[PiAgent] Error setting thinking level:",{profileId:$,sessionId:Z,error:X instanceof Error?X.message:"Unknown error"})}}async handleCompact(Z,J){let $="";try{let X=await this.parseMessage(J);if(!X)return;$=X.profileId,await this.sessionManager.compactSession(Z);let Y=`pi/${$}/compact/response/${Z}`;await this.publishEncrypted(Y,{type:"compact_started",sessionId:Z},$)}catch(X){if(V1.error("[PiAgent] Error handling compact:",{profileId:$,sessionId:Z,error:X instanceof Error?X.message:"Unknown error"}),$){let Y=`pi/${$}/compact/response/${Z}`;await this.publishEncrypted(Y,{type:"compact_error",sessionId:Z,error:X instanceof Error?X.message:"Compact failed"},$)}}}async handleSteer(Z,J){let $="";try{let X=await this.parseMessage(J);if(!X)return;$=X.profileId;let{message:Y}=X.data;await this.sessionManager.steerSession(Z,Y)}catch(X){V1.error("[PiAgent] Error handling steer:",{profileId:$,sessionId:Z,error:X instanceof Error?X.message:"Unknown error"})}}serializeTreeNode(Z){let J=Z.entry,$={id:J.id,parentId:J.parentId,type:J.type,timestamp:J.timestamp,label:Z.label,children:Array.isArray(Z.children)?Z.children.map((X)=>this.serializeTreeNode(X)):[]};if(J.type==="message"){let X=J.message;$.role=X?.role;let Y=X?.content,Q="";if(typeof Y==="string")Q=Y;else if(Array.isArray(Y))Q=Y.filter((W)=>W.type==="text"&&typeof W.text==="string").map((W)=>W.text).join(" ");$.preview=Q.substring(0,200)}else if(J.type==="compaction")$.summary=J.summary,$.tokensBefore=J.tokensBefore;else if(J.type==="branch_summary")$.summary=J.summary;else if(J.type==="model_change")$.modelId=J.modelId;else if(J.type==="thinking_level_change")$.thinkingLevel=J.thinkingLevel;else if(J.type==="label")$.label=J.label;else if(J.type==="session_info")$.name=J.name;else if(J.type==="custom"||J.type==="custom_message")$.customType=J.customType;return $}hasMultipleBranches(Z){for(let J of Z){if((J.children?.length||0)>1)return!0;if(J.children&&this.hasMultipleBranches(J.children))return!0}return!1}async handleTreeList(Z,J){let $="";try{let X=await this.parseMessage(J);if(!X)return;$=X.profileId;let{directoryPath:Y}=X.data||{},Q=`pi/${$}/tree/response/${Z}`,W=this.sessionManager.getSessionTree(Z);if(!W){if(!Y)throw Error("directoryPath required to read session from disk");let{piSdk:z}=await W9(),H=(await z.SessionManager.list(Y)).find((F)=>F.id===Z);if(!H)throw Error(`Pi session ${Z} not found on disk`);let V=z.SessionManager.open(H.path);W={nodes:V.getTree(),leafId:V.getLeafId()}}let K=W.nodes.map((z)=>this.serializeTreeNode(z));await this.publishEncrypted(Q,{sessionId:Z,nodes:K,leafId:W.leafId,hasMultipleBranches:this.hasMultipleBranches(K)},$)}catch(X){if(V1.error("[PiAgent] Error handling tree list:",{profileId:$,sessionId:Z,error:X instanceof Error?X.message:"Unknown error"}),$){let Y=`pi/${$}/tree/response/${Z}`;await this.publishEncrypted(Y,{sessionId:Z,nodes:[],leafId:null,hasMultipleBranches:!1,error:X instanceof Error?X.message:"Failed to load tree"},$)}}}async handleRewind(Z,J){let $="";try{let X=await this.parseMessage(J);if(!X)return;$=X.profileId;let{targetId:Y,summarize:Q=!1,directoryPath:W,checkpointUuid:K}=X.data||{},z=Y||K,G=`pi/${$}/rewind/response/${Z}`;if(!z){await this.publishEncrypted(G,{type:"rewind_failed",sessionId:Z,error:"targetId is required"},$);return}if(this.sessionManager.isSessionStreaming(Z)){await this.publishEncrypted(G,{type:"rewind_failed",sessionId:Z,checkpointUuid:z,error:"Cannot navigate while agent is streaming. Stop the session first."},$);return}let H=this.sessionManager.getSession(Z);if(!H?.piSession){if(!W)throw Error("directoryPath required to resume session for navigation");H=await this.sessionManager.resumeSession(Z,$,"",W)}if(!H?.piSession)throw Error("Could not activate Pi session for tree navigation");let V=await this.sessionManager.navigateTree(Z,z,!!Q);if(V.cancelled||V.aborted){await this.publishEncrypted(G,{type:"rewind_failed",sessionId:Z,checkpointUuid:z,error:V.aborted?"Navigation aborted":"Navigation cancelled"},$);return}await this.publishEncrypted(G,{type:"rewind_complete",sessionId:Z,checkpointUuid:z,mode:Q?"branch_with_summary":"conversation_only",restoredMessage:V.editorText},$),this.publishStatus($,Z,{type:"session_idle",sessionId:Z,timestamp:Date.now()})}catch(X){if(V1.error("[PiAgent] Error handling rewind:",{profileId:$,sessionId:Z,error:X instanceof Error?X.message:"Unknown error"}),$){let Y=`pi/${$}/rewind/response/${Z}`;await this.publishEncrypted(Y,{type:"rewind_failed",sessionId:Z,error:X instanceof Error?X.message:"Navigation failed"},$)}}}async handleSetLabel(Z,J){let $="";try{let X=await this.parseMessage(J);if(!X)return;$=X.profileId;let{targetId:Y,label:Q,directoryPath:W}=X.data||{},K=`pi/${$}/label/response/${Z}`;if(!Y){await this.publishEncrypted(K,{type:"label_failed",sessionId:Z,error:"targetId is required"},$);return}let z=this.sessionManager.getSession(Z);if(!z?.piSession){if(!W)throw Error("directoryPath required to resume session for labeling");z=await this.sessionManager.resumeSession(Z,$,"",W)}if(!z?.piSession)throw Error("Could not activate Pi session for labeling");let G=Q?String(Q).trim():void 0,H=this.sessionManager.setLabel(Z,Y,G);await this.publishEncrypted(K,{type:"label_set",sessionId:Z,targetId:Y,label:G,entryId:H},$)}catch(X){if(V1.error("[PiAgent] Error handling set label:",{profileId:$,sessionId:Z,error:X instanceof Error?X.message:"Unknown error"}),$){let Y=`pi/${$}/label/response/${Z}`;await this.publishEncrypted(Y,{type:"label_failed",sessionId:Z,error:X instanceof Error?X.message:"Label update failed"},$)}}}async handleRename(Z,J){let $="";try{let X=await this.parseMessage(J);if(!X)return;$=X.profileId;let{name:Y,directoryPath:Q}=X.data||{},W=`pi/${$}/rename/response/${Z}`;if(!Y||typeof Y!=="string"||!Y.trim()){await this.publishEncrypted(W,{success:!1,sessionId:Z,error:"name is required"},$);return}let K=Y.trim(),{wasInMemory:z,session:G}=await this.sessionManager.renameSession(Z,K,Q);if(!z){if(this.publishStatus($,Z,{type:"title_generated",title:K,timestamp:Date.now()}),this.sessionsService&&Q)this.sessionsService.notifyProviderSessionUpdate(Q,{sessionId:Z,title:K,status:"idle",provider:"pi"})}else if(G)this.handleTitleGenerated(G,K);await this.publishEncrypted(W,{success:!0,sessionId:Z,name:K},$)}catch(X){if(V1.error("[PiAgent] Error handling rename:",{profileId:$,sessionId:Z,error:X instanceof Error?X.message:"Unknown error"}),$){let Y=`pi/${$}/rename/response/${Z}`;await this.publishEncrypted(Y,{success:!1,sessionId:Z,error:X instanceof Error?X.message:"Rename failed"},$)}}}async getSettingsManager(){if(this.settingsManager)return this.settingsManager;let{piSdk:Z}=await W9();return this.settingsManager=Z.SettingsManager.create(process.cwd()),this.settingsManager}async readMobileSettings(){let Z=await this.getSettingsManager(),J=Z.getCompactionSettings(),$=Z.getRetrySettings(),X=Z.getBranchSummarySettings();return{compactionEnabled:J.enabled,compactionReserveTokens:J.reserveTokens,compactionKeepRecentTokens:J.keepRecentTokens,retryEnabled:$.enabled,retryMaxRetries:$.maxRetries,retryBaseDelayMs:$.baseDelayMs,retryMaxDelayMs:$.maxDelayMs,steeringMode:Z.getSteeringMode(),followUpMode:Z.getFollowUpMode(),defaultThinkingLevel:Z.getDefaultThinkingLevel()??null,branchSummarySkipPrompt:X.skipPrompt}}async applyMobileSettings(Z){let J=await this.getSettingsManager();if(Z.compactionEnabled!==void 0)J.setCompactionEnabled(Z.compactionEnabled);if(Z.retryEnabled!==void 0)J.setRetryEnabled(Z.retryEnabled);if(Z.steeringMode!==void 0)J.setSteeringMode(Z.steeringMode);if(Z.followUpMode!==void 0)J.setFollowUpMode(Z.followUpMode);if(Z.defaultThinkingLevel!==void 0)if(Z.defaultThinkingLevel!==null)J.setDefaultThinkingLevel(Z.defaultThinkingLevel);else J.applyOverrides({defaultThinkingLevel:void 0});let $={};if(Z.compactionReserveTokens!==void 0||Z.compactionKeepRecentTokens!==void 0)$.compaction={...Z.compactionReserveTokens!==void 0&&{reserveTokens:Z.compactionReserveTokens},...Z.compactionKeepRecentTokens!==void 0&&{keepRecentTokens:Z.compactionKeepRecentTokens}};if(Z.retryMaxRetries!==void 0||Z.retryBaseDelayMs!==void 0||Z.retryMaxDelayMs!==void 0)$.retry={...Z.retryMaxRetries!==void 0&&{maxRetries:Z.retryMaxRetries},...Z.retryBaseDelayMs!==void 0&&{baseDelayMs:Z.retryBaseDelayMs},...Z.retryMaxDelayMs!==void 0&&{maxDelayMs:Z.retryMaxDelayMs}};if(Z.branchSummarySkipPrompt!==void 0)$.branchSummary={skipPrompt:Z.branchSummarySkipPrompt};if(Object.keys($).length>0)J.applyOverrides($);await J.flush()}async handleSettingsGet(Z){let J="";try{let $=await this.parseMessage(Z);if(!$)return;J=$.profileId;let X=await this.readMobileSettings(),Y=`pi/${J}/settings/response`;await this.publishEncrypted(Y,{success:!0,settings:X},J)}catch($){if(V1.error("[PiAgent] Error reading settings:",{profileId:J,error:$ instanceof Error?$.message:"Unknown error"}),J)await this.publishEncrypted(`pi/${J}/settings/response`,{success:!1,error:$ instanceof Error?$.message:"Failed to read settings"},J)}}async handleSettingsSet(Z){let J="";try{let $=await this.parseMessage(Z);if(!$)return;J=$.profileId;let X=$.data?.patch;if(!X||typeof X!=="object"){await this.publishEncrypted(`pi/${J}/settings/response`,{success:!1,error:"patch is required"},J);return}await this.applyMobileSettings(X);let Y=await this.readMobileSettings();await this.publishEncrypted(`pi/${J}/settings/response`,{success:!0,settings:Y},J)}catch($){if(V1.error("[PiAgent] Error writing settings:",{profileId:J,error:$ instanceof Error?$.message:"Unknown error"}),J)await this.publishEncrypted(`pi/${J}/settings/response`,{success:!1,error:$ instanceof Error?$.message:"Failed to write settings"},J)}}async handleProvidersList(Z){let J="";try{let $=await this.parseMessage(Z);if(!$)return;J=$.profileId;let X=[];try{let{piAi:W}=await W9(),K=await import("fs"),z=await import("path"),G=await import("os"),H=z.join(G.homedir(),".pi","agent","auth.json"),V=[];try{let U=K.readFileSync(H,"utf-8");V=Object.keys(JSON.parse(U))}catch{V=["anthropic"]}let F="";try{let U=z.join(G.homedir(),".pi","agent","settings.json");F=JSON.parse(K.readFileSync(U,"utf-8")).defaultModel||""}catch{}let B=/^claude-.*-\d{8}$/;for(let U of V)try{let L=W.getModels(U);for(let O of L){if(B.test(O.id))continue;if(O.id.startsWith("claude-3-"))continue;X.push({id:O.id,displayName:O.name||O.id,provider:O.provider,isDefault:O.id===F,reasoning_variants:O.reasoning?["minimal","low","medium","high","xhigh"]:void 0})}}catch{V1.debug(`[PiAgent] No built-in models for provider: ${U}`)}}catch(W){V1.debug("[PiAgent] Failed to read Pi model catalog:",W)}if(X.length===0)X=[{id:"claude-sonnet-4-5",displayName:"Claude Sonnet 4.5",provider:"anthropic",isDefault:!0},{id:"claude-opus-4-5",displayName:"Claude Opus 4.5",provider:"anthropic"},{id:"claude-haiku-4-5",displayName:"Claude Haiku 4.5",provider:"anthropic"}];let Y={};for(let W of X){let K=W.provider||"unknown";if(!Y[K])Y[K]=[];Y[K].push(W)}let Q=Object.entries(Y).map(([W,K])=>({id:W,name:W.charAt(0).toUpperCase()+W.slice(1),models:Object.fromEntries(K.map((z)=>[z.id,{name:z.displayName||z.id,family:W,capabilities:{reasoning:!!z.reasoning_variants,attachment:!0,toolcall:!0},reasoning_variants:z.reasoning_variants}]))}));this.publishProviderResponse(J,{providers:Q,connected:Object.keys(Y)})}catch($){if(V1.error("[PiAgent] Error listing providers:",{profileId:J,error:$ instanceof Error?$.message:"Unknown error"}),J)this.publishProviderResponse(J,{error:$ instanceof Error?$.message:"Failed to list providers"})}}handleSessionInitialized(Z){if(Z.worktreePath&&Z.tempId&&Z.sessionId)this.worktreeManager.updateSessionId(Z.worktreePath,Z.tempId,Z.sessionId);if(this.publishStatus(Z.userId,Z.sessionId,{type:"session_started",sessionId:Z.sessionId,tempId:Z.tempId,model:Z.model,thinkingLevel:Z.thinkingLevel,worktreePath:Z.worktreePath,worktreeBranch:Z.worktreeBranch,slashCommands:[],agents:[],skills:[],timestamp:Date.now()}),this.sessionsService)this.sessionsService.notifyProviderSessionUpdate(Z.directoryPath,{sessionId:Z.sessionId,title:Z.title||"Pi Session",status:Z.status,provider:"pi"})}handleTitleGenerated(Z,J){if(this.publishStatus(Z.userId,Z.sessionId,{type:"title_generated",title:J,timestamp:Date.now()}),this.sessionsService&&Z.sessionId)this.sessionsService.notifyProviderSessionUpdate(Z.directoryPath,{sessionId:Z.sessionId,title:J,status:Z.status,provider:"pi"})}handleAssistantMessage(Z,J){if(Z.sessionId)this.publishOutput(Z.userId,Z.sessionId,J)}handlePermissionRequest(Z,J){if(!Z.sessionId)return;this.pendingPermissions.set(J.request_id,{requestId:J.request_id,action:J.action,params:J.params,createdAt:Date.now()}),B0.addPermission({requestId:J.request_id,sessionId:Z.sessionId,projectPath:Z.directoryPath,action:J.action,params:J.params,createdAt:new Date().toISOString()}).catch(()=>{});let $=`pi/${Z.userId}/permission/request/${Z.sessionId}`;this.publishEncrypted($,J,Z.userId).catch((X)=>{V1.error("[PiAgent] Failed to publish permission request",{error:X instanceof Error?X.message:"Unknown error"})})}handleSessionError(Z,J){this.publishStatus(Z.userId,Z.sessionId||Z.tempId,{type:"error",error:J,timestamp:Date.now()})}handleSessionStopped(Z,J){if(this.publishStatus(Z.userId,Z.sessionId||Z.tempId,{type:"session_stopped",reason:J,timestamp:Date.now()}),this.sessionsService){if(this.sessionsService.notifySessionStopped(),Z.sessionId)this.sessionsService.notifyProviderSessionUpdate(Z.directoryPath,{sessionId:Z.sessionId,title:Z.title||"Pi Session",status:"stopped",provider:"pi"})}}handleProcessingStarted(Z){if(Z.sessionId)this.publishStatus(Z.userId,Z.sessionId,{type:"session_processing",sessionId:Z.sessionId,timestamp:Date.now()})}handleProcessingComplete(Z){if(!Z.sessionId)return;if(this.publishStatus(Z.userId,Z.sessionId,{type:"session_idle",sessionId:Z.sessionId,timestamp:Date.now()}),Z.tempId&&Z.tempId!==Z.sessionId)this.publishStatus(Z.userId,Z.tempId,{type:"session_idle",sessionId:Z.sessionId,timestamp:Date.now()});if(this.sessionsService)this.sessionsService.notifyProviderSessionUpdate(Z.directoryPath,{sessionId:Z.sessionId,title:Z.title||"Pi Session",status:"idle",messageCount:Z.messageCount,provider:"pi"})}handleContextUpdate(Z,J){if(Z.sessionId)this.publishContextUpdate(Z.userId,Z.sessionId,J)}handleExtensionUiRequest(Z,J){let $=Z.sessionId||Z.tempId;if(!$)return;let X=`pi/${Z.userId}/extension/ui/request/${$}`;this.publishEncrypted(X,J,Z.userId).catch((Y)=>{V1.error("[PiAgent] Failed to publish extension UI request",{method:J.method,error:Y instanceof Error?Y.message:"Unknown error"})})}async handleExtensionUiResponse(Z){try{let J=await this.parseMessage(Z);if(!J)return;this.sessionManager.resolveUiResponse(J.data)}catch(J){V1.error("[PiAgent] Error handling extension UI response:",{error:J instanceof Error?J.message:"Unknown error"})}}publishStatus(Z,J,$){if(!this.mqttClient)return;let X=`pi/${Z}/status/${J}`;this.publishEncrypted(X,$,Z).catch((Y)=>{V1.error("[PiAgent] Failed to publish status",{error:Y instanceof Error?Y.message:"Unknown error"})})}publishOutput(Z,J,$){if(!this.mqttClient)return;let X=`pi/${Z}/output/${J}`;this.publishEncrypted(X,$,Z).catch((Y)=>{V1.error("[PiAgent] Failed to publish output",{error:Y instanceof Error?Y.message:"Unknown error"})})}publishContextUpdate(Z,J,$){if(!this.mqttClient)return;let X=`pi/${Z}/context/${J}`;this.publishEncrypted(X,$,Z).catch((Y)=>{V1.error("[PiAgent] Failed to publish context",{error:Y instanceof Error?Y.message:"Unknown error"})})}publishToggleResponse(Z,J){if(!this.mqttClient)return;let $=`pi/${Z}/toggle/response`;this.publishEncrypted($,J,Z).catch((X)=>{V1.error("[PiAgent] Failed to publish toggle response",{error:X instanceof Error?X.message:"Unknown error"})})}publishProviderResponse(Z,J){if(!this.mqttClient)return;let $=`pi/${Z}/providers/response`;this.publishEncrypted($,J,Z).catch((X)=>{V1.error("[PiAgent] Failed to publish provider response",{error:X instanceof Error?X.message:"Unknown error"})})}async parseMessage(Z){try{let J=JSON.parse(Z.toString());if(M1.isEncryptedEnvelope(J)){let $=J.c;if(!$)return null;let X=M1.getClientKeyOrRekey($);if(!X)return null;let Y=await M1.decrypt(X,J);return{data:JSON.parse(Y),profileId:$}}return V1.warn("[PiAgent] Received unencrypted message \u2014 dropping"),null}catch(J){return V1.warn("[PiAgent] Failed to parse message",{error:J}),null}}async publishEncrypted(Z,J,$){if(!this.mqttClient)return;if(!$)return;let X=M1.getClientKeyOrRekey($);if(!X){V1.warn(`[PiAgent] No encryption key for profile ${$} \u2014 dropping message on ${Z} (rekey requested)`);return}let Y=await M1.encrypt(X,JSON.stringify(J));Y.c=$,await this.mqttClient.publish(Z,JSON.stringify(Y),{qos:1})}cleanupStalePendingPermissions(){let Z=Date.now();for(let[J,$]of this.pendingPermissions)if(Z-$.createdAt>tW.PENDING_PERMISSION_TTL_MS)this.pendingPermissions.delete(J),B0.removePermission(J).catch(()=>{})}getStatus(){return{name:this.name,running:this.running,startedAt:this.startedAt,activeSessions:this.sessionManager.getSessionCount(),totalSessionsCreated:this.totalSessionsCreated,totalMessagesProcessed:this.totalMessagesProcessed}}getActiveSessionCount(){return this.sessionManager.getSessionCount()}getActiveSessions(){return this.sessionManager.getActiveSessions()}async getSessionMessages(Z,J){let $=this.sessionManager.getSessionEntries(Z);if((!$||$.length===0)&&J)try{let{piSdk:K}=await W9(),G=(await K.SessionManager.list(J)).find((H)=>H.id===Z);if(G)$=K.SessionManager.open(G.path).getEntries()}catch(K){V1.warn("[PiAgent] Failed to read session messages from disk",{sessionId:Z,error:K instanceof Error?K.message:"Unknown error"})}let X=jY0($||[]),Y=this.sessionManager.getSession(Z),Q=Y?.contextUsage,W=Y?.title;return{messages:X,title:W,context:Q}}}function jY0(Z){let J=[],$=null;for(let X of Z){if(!X||X.type!=="message")continue;let Y=X.message;if(!Y)continue;let Q=X.id,W=X.timestamp||new Date().toISOString(),K=Y.role;if(K==="user"){let z;if(typeof Y.content==="string")z=Y.content;else if(Array.isArray(Y.content))z=Y.content.map((G)=>{if(G.type==="text")return{type:"text",text:G.text};if(G.type==="image"&&G.source)return{type:"image",source:{type:"base64",media_type:G.source.mediaType??G.source.media_type,data:G.source.data}};return null}).filter(Boolean);else z="";J.push({uuid:Q,parentUuid:$,timestamp:W,type:"user",role:"user",content:z}),$=Q}else if(K==="assistant"){let z=[],G=Array.isArray(Y.content)?Y.content:[];for(let H of G)if(H.type==="text"&&H.text)z.push({type:"text",text:H.text});else if(H.type==="thinking"&&H.thinking)z.push({type:"thinking",thinking:H.thinking});else if(H.type==="toolCall")z.push({type:"tool_use",id:H.id||H.toolCallId,name:H.name,input:H.arguments??H.input??{}});if(z.length===0)continue;J.push({uuid:Q,parentUuid:$,timestamp:W,type:"assistant",role:"assistant",content:z}),$=Q}else if(K==="toolResult"){let z=Y.toolCallId,G="";if(typeof Y.content==="string")G=Y.content;else if(Array.isArray(Y.content))G=Y.content.filter((H)=>H.type==="text").map((H)=>H.text).join(`
|
|
2409
|
+
Exit code: ${V}`:""}`}]}};this.publishOutput($,W.sessionId,F)}catch(G){let H={type:"error",error:{message:`Bash: ${G instanceof Error?G.message:"failed"}`,type:"bash_error"}};this.publishOutput($,W.sessionId,H)}finally{this.publishStatus($,W.sessionId,{type:"session_idle",sessionId:W.sessionId,timestamp:Date.now()})}this.totalMessagesProcessed++;return}}await this.sessionManager.sendMessage(Y.sessionId,Y.message||"",Y.attachments),this.totalMessagesProcessed++}catch(X){V1.error("[PiAgent] Error handling user input:",{profileId:$,sessionId:Z,error:X instanceof Error?X.message:"Unknown error"})}}async handlePermissionResponseFromMobile(Z,J){let $,X,Y="";try{let Q=await this.parseMessage(J);if(!Q)return;if($=Q.data,X=$.requestId,Y=Q.profileId,!this.sessionManager.getSession(Z)){V1.warn(`[PiAgent] Session ${Z} not found for permission response`),this.publishStatus(Y,Z,{type:"session_stopped",reason:"session_lost",message:"Session is no longer active.",timestamp:Date.now()});return}if(this.sessionManager.sendApprovalResponse(X,$.approved),!$.approved&&$.hardDeny){let K=Y;setTimeout(()=>{this.sessionManager.stopSession(Z).catch(()=>{}),this.publishStatus(K,Z,{type:"session_stopped",reason:"permission_denied",message:$.denyMessage||"Permission denied by user",timestamp:Date.now()})},100)}if(X)this.pendingPermissions.delete(X),B0.removePermission(X).catch(()=>{})}catch(Q){if(V1.error("[PiAgent] Error handling permission response:",{profileId:Y,sessionId:Z,error:Q instanceof Error?Q.message:"Unknown error"}),Y)this.publishStatus(Y,Z,{type:"session_stopped",reason:"session_lost",message:"Session is no longer active. The permission request could not be delivered.",timestamp:Date.now()});if(X)this.pendingPermissions.delete(X),B0.removePermission(X).catch(()=>{})}}async handleSessionStop(Z,J){let X=(await this.parseMessage(J))?.profileId||"";V1.debug("[PiAgent] Session stop request:",{profileId:X,sessionId:Z});try{await this.sessionManager.stopSession(Z)}catch(Y){V1.error("[PiAgent] Failed to stop session",{sessionId:Z,error:Y})}}async handleTogglePi(Z){let J="";try{let $=await this.parseMessage(Z);if(!$)return;J=$.profileId;let{enabled:X}=$.data;if(X)V1.info("[PiAgent] Enabling Pi..."),W7("pi_enabled",!0);else V1.info("[PiAgent] Disabling Pi, stopping all sessions..."),W7("pi_enabled",!1),await this.sessionManager.stopAll();this.publishToggleResponse(J,{enabled:!!X})}catch($){if(V1.error("[PiAgent] Error toggling Pi:",{profileId:J,error:$ instanceof Error?$.message:"Unknown error"}),J)this.publishToggleResponse(J,{enabled:!1,error:$ instanceof Error?$.message:"Failed to toggle Pi"})}}async handleGetEnabled(Z){let J=await this.parseMessage(Z);if(!J)return;let $=J.profileId,X=D5("pi_enabled")||!1;this.publishToggleResponse($,{enabled:X})}async handleSetModel(Z,J){let $="";try{let X=await this.parseMessage(J);if(!X)return;$=X.profileId;let{model:Y}=X.data;await this.sessionManager.setModel(Z,Y)}catch(X){V1.error("[PiAgent] Error setting model:",{profileId:$,sessionId:Z,error:X instanceof Error?X.message:"Unknown error"})}}async handleSetThinkingLevel(Z,J){let $="";try{let X=await this.parseMessage(J);if(!X)return;$=X.profileId;let{level:Y}=X.data;this.sessionManager.setThinkingLevel(Z,Y),this.publishStatus($,Z,{type:"thinking_level_changed",thinkingLevel:Y,timestamp:Date.now()})}catch(X){V1.error("[PiAgent] Error setting thinking level:",{profileId:$,sessionId:Z,error:X instanceof Error?X.message:"Unknown error"})}}async handleCompact(Z,J){let $="";try{let X=await this.parseMessage(J);if(!X)return;$=X.profileId,await this.sessionManager.compactSession(Z);let Y=`pi/${$}/compact/response/${Z}`;await this.publishEncrypted(Y,{type:"compact_started",sessionId:Z},$)}catch(X){if(V1.error("[PiAgent] Error handling compact:",{profileId:$,sessionId:Z,error:X instanceof Error?X.message:"Unknown error"}),$){let Y=`pi/${$}/compact/response/${Z}`;await this.publishEncrypted(Y,{type:"compact_error",sessionId:Z,error:X instanceof Error?X.message:"Compact failed"},$)}}}async handleSteer(Z,J){let $="";try{let X=await this.parseMessage(J);if(!X)return;$=X.profileId;let{message:Y}=X.data;await this.sessionManager.steerSession(Z,Y)}catch(X){V1.error("[PiAgent] Error handling steer:",{profileId:$,sessionId:Z,error:X instanceof Error?X.message:"Unknown error"})}}serializeTreeNode(Z){let J=Z.entry,$={id:J.id,parentId:J.parentId,type:J.type,timestamp:J.timestamp,label:Z.label,children:Array.isArray(Z.children)?Z.children.map((X)=>this.serializeTreeNode(X)):[]};if(J.type==="message"){let X=J.message;$.role=X?.role;let Y=X?.content,Q="";if(typeof Y==="string")Q=Y;else if(Array.isArray(Y))Q=Y.filter((W)=>W.type==="text"&&typeof W.text==="string").map((W)=>W.text).join(" ");$.preview=Q.substring(0,200)}else if(J.type==="compaction")$.summary=J.summary,$.tokensBefore=J.tokensBefore;else if(J.type==="branch_summary")$.summary=J.summary;else if(J.type==="model_change")$.modelId=J.modelId;else if(J.type==="thinking_level_change")$.thinkingLevel=J.thinkingLevel;else if(J.type==="label")$.label=J.label;else if(J.type==="session_info")$.name=J.name;else if(J.type==="custom"||J.type==="custom_message")$.customType=J.customType;return $}hasMultipleBranches(Z){for(let J of Z){if((J.children?.length||0)>1)return!0;if(J.children&&this.hasMultipleBranches(J.children))return!0}return!1}async handleTreeList(Z,J){let $="";try{let X=await this.parseMessage(J);if(!X)return;$=X.profileId;let{directoryPath:Y}=X.data||{},Q=`pi/${$}/tree/response/${Z}`,W=this.sessionManager.getSessionTree(Z);if(!W){if(!Y)throw Error("directoryPath required to read session from disk");let{piSdk:z}=await W9(),H=(await z.SessionManager.list(Y)).find((F)=>F.id===Z);if(!H)throw Error(`Pi session ${Z} not found on disk`);let V=z.SessionManager.open(H.path);W={nodes:V.getTree(),leafId:V.getLeafId()}}let K=W.nodes.map((z)=>this.serializeTreeNode(z));await this.publishEncrypted(Q,{sessionId:Z,nodes:K,leafId:W.leafId,hasMultipleBranches:this.hasMultipleBranches(K)},$)}catch(X){if(V1.error("[PiAgent] Error handling tree list:",{profileId:$,sessionId:Z,error:X instanceof Error?X.message:"Unknown error"}),$){let Y=`pi/${$}/tree/response/${Z}`;await this.publishEncrypted(Y,{sessionId:Z,nodes:[],leafId:null,hasMultipleBranches:!1,error:X instanceof Error?X.message:"Failed to load tree"},$)}}}async handleRewind(Z,J){let $="";try{let X=await this.parseMessage(J);if(!X)return;$=X.profileId;let{targetId:Y,summarize:Q=!1,directoryPath:W,checkpointUuid:K}=X.data||{},z=Y||K,G=`pi/${$}/rewind/response/${Z}`;if(!z){await this.publishEncrypted(G,{type:"rewind_failed",sessionId:Z,error:"targetId is required"},$);return}if(this.sessionManager.isSessionStreaming(Z)){await this.publishEncrypted(G,{type:"rewind_failed",sessionId:Z,checkpointUuid:z,error:"Cannot navigate while agent is streaming. Stop the session first."},$);return}let H=this.sessionManager.getSession(Z);if(!H?.piSession){if(!W)throw Error("directoryPath required to resume session for navigation");H=await this.sessionManager.resumeSession(Z,$,"",W)}if(!H?.piSession)throw Error("Could not activate Pi session for tree navigation");let V=await this.sessionManager.navigateTree(Z,z,!!Q);if(V.cancelled||V.aborted){await this.publishEncrypted(G,{type:"rewind_failed",sessionId:Z,checkpointUuid:z,error:V.aborted?"Navigation aborted":"Navigation cancelled"},$);return}await this.publishEncrypted(G,{type:"rewind_complete",sessionId:Z,checkpointUuid:z,mode:Q?"branch_with_summary":"conversation_only",restoredMessage:V.editorText},$),this.publishStatus($,Z,{type:"session_idle",sessionId:Z,timestamp:Date.now()})}catch(X){if(V1.error("[PiAgent] Error handling rewind:",{profileId:$,sessionId:Z,error:X instanceof Error?X.message:"Unknown error"}),$){let Y=`pi/${$}/rewind/response/${Z}`;await this.publishEncrypted(Y,{type:"rewind_failed",sessionId:Z,error:X instanceof Error?X.message:"Navigation failed"},$)}}}async handleSetLabel(Z,J){let $="";try{let X=await this.parseMessage(J);if(!X)return;$=X.profileId;let{targetId:Y,label:Q,directoryPath:W}=X.data||{},K=`pi/${$}/label/response/${Z}`;if(!Y){await this.publishEncrypted(K,{type:"label_failed",sessionId:Z,error:"targetId is required"},$);return}let z=this.sessionManager.getSession(Z);if(!z?.piSession){if(!W)throw Error("directoryPath required to resume session for labeling");z=await this.sessionManager.resumeSession(Z,$,"",W)}if(!z?.piSession)throw Error("Could not activate Pi session for labeling");let G=Q?String(Q).trim():void 0,H=this.sessionManager.setLabel(Z,Y,G);await this.publishEncrypted(K,{type:"label_set",sessionId:Z,targetId:Y,label:G,entryId:H},$)}catch(X){if(V1.error("[PiAgent] Error handling set label:",{profileId:$,sessionId:Z,error:X instanceof Error?X.message:"Unknown error"}),$){let Y=`pi/${$}/label/response/${Z}`;await this.publishEncrypted(Y,{type:"label_failed",sessionId:Z,error:X instanceof Error?X.message:"Label update failed"},$)}}}async handleRename(Z,J){let $="";try{let X=await this.parseMessage(J);if(!X)return;$=X.profileId;let{name:Y,directoryPath:Q}=X.data||{},W=`pi/${$}/rename/response/${Z}`;if(!Y||typeof Y!=="string"||!Y.trim()){await this.publishEncrypted(W,{success:!1,sessionId:Z,error:"name is required"},$);return}let K=Y.trim(),{wasInMemory:z,session:G}=await this.sessionManager.renameSession(Z,K,Q);if(!z){if(this.publishStatus($,Z,{type:"title_generated",title:K,timestamp:Date.now()}),this.sessionsService&&Q)this.sessionsService.notifyProviderSessionUpdate(Q,{sessionId:Z,title:K,status:"idle",provider:"pi"})}else if(G)this.handleTitleGenerated(G,K);await this.publishEncrypted(W,{success:!0,sessionId:Z,name:K},$)}catch(X){if(V1.error("[PiAgent] Error handling rename:",{profileId:$,sessionId:Z,error:X instanceof Error?X.message:"Unknown error"}),$){let Y=`pi/${$}/rename/response/${Z}`;await this.publishEncrypted(Y,{success:!1,sessionId:Z,error:X instanceof Error?X.message:"Rename failed"},$)}}}async getSettingsManager(){if(this.settingsManager)return this.settingsManager;let{piSdk:Z}=await W9();return this.settingsManager=Z.SettingsManager.create(process.cwd()),this.settingsManager}async readMobileSettings(){let Z=await this.getSettingsManager(),J=Z.getCompactionSettings(),$=Z.getRetrySettings(),X=Z.getBranchSummarySettings();return{compactionEnabled:J.enabled,compactionReserveTokens:J.reserveTokens,compactionKeepRecentTokens:J.keepRecentTokens,retryEnabled:$.enabled,retryMaxRetries:$.maxRetries,retryBaseDelayMs:$.baseDelayMs,retryMaxDelayMs:$.maxDelayMs,steeringMode:Z.getSteeringMode(),followUpMode:Z.getFollowUpMode(),defaultThinkingLevel:Z.getDefaultThinkingLevel()??null,branchSummarySkipPrompt:X.skipPrompt}}async applyMobileSettings(Z){let J=await this.getSettingsManager();if(Z.compactionEnabled!==void 0)J.setCompactionEnabled(Z.compactionEnabled);if(Z.retryEnabled!==void 0)J.setRetryEnabled(Z.retryEnabled);if(Z.steeringMode!==void 0)J.setSteeringMode(Z.steeringMode);if(Z.followUpMode!==void 0)J.setFollowUpMode(Z.followUpMode);if(Z.defaultThinkingLevel!==void 0)if(Z.defaultThinkingLevel!==null)J.setDefaultThinkingLevel(Z.defaultThinkingLevel);else J.applyOverrides({defaultThinkingLevel:void 0});let $={};if(Z.compactionReserveTokens!==void 0||Z.compactionKeepRecentTokens!==void 0)$.compaction={...Z.compactionReserveTokens!==void 0&&{reserveTokens:Z.compactionReserveTokens},...Z.compactionKeepRecentTokens!==void 0&&{keepRecentTokens:Z.compactionKeepRecentTokens}};if(Z.retryMaxRetries!==void 0||Z.retryBaseDelayMs!==void 0||Z.retryMaxDelayMs!==void 0)$.retry={...Z.retryMaxRetries!==void 0&&{maxRetries:Z.retryMaxRetries},...Z.retryBaseDelayMs!==void 0&&{baseDelayMs:Z.retryBaseDelayMs},...Z.retryMaxDelayMs!==void 0&&{maxDelayMs:Z.retryMaxDelayMs}};if(Z.branchSummarySkipPrompt!==void 0)$.branchSummary={skipPrompt:Z.branchSummarySkipPrompt};if(Object.keys($).length>0)J.applyOverrides($);await J.flush()}async handleSettingsGet(Z){let J="";try{let $=await this.parseMessage(Z);if(!$)return;J=$.profileId;let X=await this.readMobileSettings(),Y=`pi/${J}/settings/response`;await this.publishEncrypted(Y,{success:!0,settings:X},J)}catch($){if(V1.error("[PiAgent] Error reading settings:",{profileId:J,error:$ instanceof Error?$.message:"Unknown error"}),J)await this.publishEncrypted(`pi/${J}/settings/response`,{success:!1,error:$ instanceof Error?$.message:"Failed to read settings"},J)}}async handleSettingsSet(Z){let J="";try{let $=await this.parseMessage(Z);if(!$)return;J=$.profileId;let X=$.data?.patch;if(!X||typeof X!=="object"){await this.publishEncrypted(`pi/${J}/settings/response`,{success:!1,error:"patch is required"},J);return}await this.applyMobileSettings(X);let Y=await this.readMobileSettings();await this.publishEncrypted(`pi/${J}/settings/response`,{success:!0,settings:Y},J)}catch($){if(V1.error("[PiAgent] Error writing settings:",{profileId:J,error:$ instanceof Error?$.message:"Unknown error"}),J)await this.publishEncrypted(`pi/${J}/settings/response`,{success:!1,error:$ instanceof Error?$.message:"Failed to write settings"},J)}}async handleProvidersList(Z){let J="";try{let $=await this.parseMessage(Z);if(!$)return;J=$.profileId;let X=[],Y={};try{let{piSdk:K}=await W9(),z=await import("fs"),G=await import("path"),H=await import("os"),V=K.AuthStorage.create(),F=K.ModelRegistry.create(V),B=F.getError?.();if(B)V1.debug("[PiAgent] ModelRegistry parse warning:",B);let U="";try{let _=G.join(H.homedir(),".pi","agent","settings.json");U=JSON.parse(z.readFileSync(_,"utf-8")).defaultModel||""}catch{}let L=/^claude-.*-\d{8}$/,O=F.getAvailable();for(let _ of O){if(L.test(_.id))continue;if(_.id.startsWith("claude-3-"))continue;if(X.push({id:_.id,displayName:_.name||_.id,provider:_.provider,isDefault:_.id===U,reasoning_variants:_.reasoning?["minimal","low","medium","high","xhigh"]:void 0,oauth:F.isUsingOAuth(_)}),!Y[_.provider])try{Y[_.provider]=F.getProviderDisplayName(_.provider)}catch{Y[_.provider]=_.provider}}}catch(K){V1.debug("[PiAgent] Failed to load Pi ModelRegistry:",K)}if(X.length===0)X=[{id:"claude-sonnet-4-5",displayName:"Claude Sonnet 4.5",provider:"anthropic",isDefault:!0,oauth:!1},{id:"claude-opus-4-5",displayName:"Claude Opus 4.5",provider:"anthropic",isDefault:!1,oauth:!1},{id:"claude-haiku-4-5",displayName:"Claude Haiku 4.5",provider:"anthropic",isDefault:!1,oauth:!1}];let Q={};for(let K of X){let z=K.provider||"unknown";if(!Q[z])Q[z]=[];Q[z].push(K)}let W=Object.entries(Q).map(([K,z])=>({id:K,name:Y[K]??K.charAt(0).toUpperCase()+K.slice(1),models:Object.fromEntries(z.map((G)=>[G.id,{name:G.displayName||G.id,family:K,capabilities:{reasoning:!!G.reasoning_variants,attachment:!0,toolcall:!0,oauth:G.oauth},reasoning_variants:G.reasoning_variants}]))}));this.publishProviderResponse(J,{providers:W,connected:Object.keys(Q)})}catch($){if(V1.error("[PiAgent] Error listing providers:",{profileId:J,error:$ instanceof Error?$.message:"Unknown error"}),J)this.publishProviderResponse(J,{error:$ instanceof Error?$.message:"Failed to list providers"})}}handleSessionInitialized(Z){if(Z.worktreePath&&Z.tempId&&Z.sessionId)this.worktreeManager.updateSessionId(Z.worktreePath,Z.tempId,Z.sessionId);if(this.publishStatus(Z.userId,Z.sessionId,{type:"session_started",sessionId:Z.sessionId,tempId:Z.tempId,model:Z.model,thinkingLevel:Z.thinkingLevel,worktreePath:Z.worktreePath,worktreeBranch:Z.worktreeBranch,slashCommands:[],agents:[],skills:[],timestamp:Date.now()}),this.sessionsService)this.sessionsService.notifyProviderSessionUpdate(Z.directoryPath,{sessionId:Z.sessionId,title:Z.title||"Pi Session",status:Z.status,provider:"pi"})}handleTitleGenerated(Z,J){if(this.publishStatus(Z.userId,Z.sessionId,{type:"title_generated",title:J,timestamp:Date.now()}),this.sessionsService&&Z.sessionId)this.sessionsService.notifyProviderSessionUpdate(Z.directoryPath,{sessionId:Z.sessionId,title:J,status:Z.status,provider:"pi"})}handleAssistantMessage(Z,J){if(Z.sessionId)this.publishOutput(Z.userId,Z.sessionId,J)}handlePermissionRequest(Z,J){if(!Z.sessionId)return;this.pendingPermissions.set(J.request_id,{requestId:J.request_id,action:J.action,params:J.params,createdAt:Date.now()}),B0.addPermission({requestId:J.request_id,sessionId:Z.sessionId,projectPath:Z.directoryPath,action:J.action,params:J.params,createdAt:new Date().toISOString()}).catch(()=>{});let $=`pi/${Z.userId}/permission/request/${Z.sessionId}`;this.publishEncrypted($,J,Z.userId).catch((X)=>{V1.error("[PiAgent] Failed to publish permission request",{error:X instanceof Error?X.message:"Unknown error"})})}handleSessionError(Z,J){this.publishStatus(Z.userId,Z.sessionId||Z.tempId,{type:"error",error:J,timestamp:Date.now()})}handleSessionStopped(Z,J){if(this.publishStatus(Z.userId,Z.sessionId||Z.tempId,{type:"session_stopped",reason:J,timestamp:Date.now()}),this.sessionsService){if(this.sessionsService.notifySessionStopped(),Z.sessionId)this.sessionsService.notifyProviderSessionUpdate(Z.directoryPath,{sessionId:Z.sessionId,title:Z.title||"Pi Session",status:"stopped",provider:"pi"})}}handleProcessingStarted(Z){if(Z.sessionId)this.publishStatus(Z.userId,Z.sessionId,{type:"session_processing",sessionId:Z.sessionId,timestamp:Date.now()})}handleProcessingComplete(Z){if(!Z.sessionId)return;if(this.publishStatus(Z.userId,Z.sessionId,{type:"session_idle",sessionId:Z.sessionId,timestamp:Date.now()}),Z.tempId&&Z.tempId!==Z.sessionId)this.publishStatus(Z.userId,Z.tempId,{type:"session_idle",sessionId:Z.sessionId,timestamp:Date.now()});if(this.sessionsService)this.sessionsService.notifyProviderSessionUpdate(Z.directoryPath,{sessionId:Z.sessionId,title:Z.title||"Pi Session",status:"idle",messageCount:Z.messageCount,provider:"pi"})}handleContextUpdate(Z,J){if(Z.sessionId)this.publishContextUpdate(Z.userId,Z.sessionId,J)}handleExtensionUiRequest(Z,J){let $=Z.sessionId||Z.tempId;if(!$)return;let X=`pi/${Z.userId}/extension/ui/request/${$}`;this.publishEncrypted(X,J,Z.userId).catch((Y)=>{V1.error("[PiAgent] Failed to publish extension UI request",{method:J.method,error:Y instanceof Error?Y.message:"Unknown error"})})}async handleExtensionUiResponse(Z){try{let J=await this.parseMessage(Z);if(!J)return;this.sessionManager.resolveUiResponse(J.data)}catch(J){V1.error("[PiAgent] Error handling extension UI response:",{error:J instanceof Error?J.message:"Unknown error"})}}publishStatus(Z,J,$){if(!this.mqttClient)return;let X=`pi/${Z}/status/${J}`;this.publishEncrypted(X,$,Z).catch((Y)=>{V1.error("[PiAgent] Failed to publish status",{error:Y instanceof Error?Y.message:"Unknown error"})})}publishOutput(Z,J,$){if(!this.mqttClient)return;let X=`pi/${Z}/output/${J}`;this.publishEncrypted(X,$,Z).catch((Y)=>{V1.error("[PiAgent] Failed to publish output",{error:Y instanceof Error?Y.message:"Unknown error"})})}publishContextUpdate(Z,J,$){if(!this.mqttClient)return;let X=`pi/${Z}/context/${J}`;this.publishEncrypted(X,$,Z).catch((Y)=>{V1.error("[PiAgent] Failed to publish context",{error:Y instanceof Error?Y.message:"Unknown error"})})}publishToggleResponse(Z,J){if(!this.mqttClient)return;let $=`pi/${Z}/toggle/response`;this.publishEncrypted($,J,Z).catch((X)=>{V1.error("[PiAgent] Failed to publish toggle response",{error:X instanceof Error?X.message:"Unknown error"})})}publishProviderResponse(Z,J){if(!this.mqttClient)return;let $=`pi/${Z}/providers/response`;this.publishEncrypted($,J,Z).catch((X)=>{V1.error("[PiAgent] Failed to publish provider response",{error:X instanceof Error?X.message:"Unknown error"})})}async parseMessage(Z){try{let J=JSON.parse(Z.toString());if(M1.isEncryptedEnvelope(J)){let $=J.c;if(!$)return null;let X=M1.getClientKeyOrRekey($);if(!X)return null;let Y=await M1.decrypt(X,J);return{data:JSON.parse(Y),profileId:$}}return V1.warn("[PiAgent] Received unencrypted message \u2014 dropping"),null}catch(J){return V1.warn("[PiAgent] Failed to parse message",{error:J}),null}}async publishEncrypted(Z,J,$){if(!this.mqttClient)return;if(!$)return;let X=M1.getClientKeyOrRekey($);if(!X){V1.warn(`[PiAgent] No encryption key for profile ${$} \u2014 dropping message on ${Z} (rekey requested)`);return}let Y=await M1.encrypt(X,JSON.stringify(J));Y.c=$,await this.mqttClient.publish(Z,JSON.stringify(Y),{qos:1})}cleanupStalePendingPermissions(){let Z=Date.now();for(let[J,$]of this.pendingPermissions)if(Z-$.createdAt>tW.PENDING_PERMISSION_TTL_MS)this.pendingPermissions.delete(J),B0.removePermission(J).catch(()=>{})}getStatus(){return{name:this.name,running:this.running,startedAt:this.startedAt,activeSessions:this.sessionManager.getSessionCount(),totalSessionsCreated:this.totalSessionsCreated,totalMessagesProcessed:this.totalMessagesProcessed}}getActiveSessionCount(){return this.sessionManager.getSessionCount()}getActiveSessions(){return this.sessionManager.getActiveSessions()}async getSessionMessages(Z,J){let $=this.sessionManager.getSessionEntries(Z);if((!$||$.length===0)&&J)try{let{piSdk:K}=await W9(),G=(await K.SessionManager.list(J)).find((H)=>H.id===Z);if(G)$=K.SessionManager.open(G.path).getEntries()}catch(K){V1.warn("[PiAgent] Failed to read session messages from disk",{sessionId:Z,error:K instanceof Error?K.message:"Unknown error"})}let X=jY0($||[]),Y=this.sessionManager.getSession(Z),Q=Y?.contextUsage,W=Y?.title;return{messages:X,title:W,context:Q}}}function jY0(Z){let J=[],$=null;for(let X of Z){if(!X||X.type!=="message")continue;let Y=X.message;if(!Y)continue;let Q=X.id,W=X.timestamp||new Date().toISOString(),K=Y.role;if(K==="user"){let z;if(typeof Y.content==="string")z=Y.content;else if(Array.isArray(Y.content))z=Y.content.map((G)=>{if(G.type==="text")return{type:"text",text:G.text};if(G.type==="image"&&G.source)return{type:"image",source:{type:"base64",media_type:G.source.mediaType??G.source.media_type,data:G.source.data}};return null}).filter(Boolean);else z="";J.push({uuid:Q,parentUuid:$,timestamp:W,type:"user",role:"user",content:z}),$=Q}else if(K==="assistant"){let z=[],G=Array.isArray(Y.content)?Y.content:[];for(let H of G)if(H.type==="text"&&H.text)z.push({type:"text",text:H.text});else if(H.type==="thinking"&&H.thinking)z.push({type:"thinking",thinking:H.thinking});else if(H.type==="toolCall")z.push({type:"tool_use",id:H.id||H.toolCallId,name:H.name,input:H.arguments??H.input??{}});if(z.length===0)continue;J.push({uuid:Q,parentUuid:$,timestamp:W,type:"assistant",role:"assistant",content:z}),$=Q}else if(K==="toolResult"){let z=Y.toolCallId,G="";if(typeof Y.content==="string")G=Y.content;else if(Array.isArray(Y.content))G=Y.content.filter((H)=>H.type==="text").map((H)=>H.text).join(`
|
|
2410
2410
|
`);J.push({uuid:Q,parentUuid:$,timestamp:W,type:"tool",toolName:Y.toolName,toolUseId:z,isError:!!Y.isError,content:[{type:"tool_result",tool_use_id:z,content:G,is_error:!!Y.isError}]}),$=Q}}return J}import*as T0 from"fs/promises";import*as LM from"fs";import*as W4 from"path";import*as qZ from"fs/promises";var OY=S(),Gz1=10485760;async function A0(Z,J={}){let{maxSize:$=Gz1,encoding:X="utf-8",logWarnings:Y=!0}=J;try{let Q=await qZ.stat(Z);if(!Q.isFile()){if(Y)OY.debug("[SafeFS] Path is not a file",{filePath:Z});return null}if(Q.size>$){if(Y)OY.warn("[SafeFS] File too large, skipping",{filePath:Z,size:Q.size,maxSize:$});return null}return await qZ.readFile(Z,X)}catch(Q){if(Q.code!=="ENOENT"&&Y)OY.debug("[SafeFS] Error reading file",{filePath:Z,error:Q});return null}}async function Hz1(Z,J={}){let{maxSize:$=Gz1,logWarnings:X=!0}=J;try{let Y=await qZ.stat(Z);if(!Y.isFile()){if(X)OY.debug("[SafeFS] Path is not a file",{filePath:Z});return null}if(Y.size>$){if(X)OY.warn("[SafeFS] File too large, skipping",{filePath:Z,size:Y.size,maxSize:$});return null}return await qZ.readFile(Z)}catch(Y){if(Y.code!=="ENOENT"&&X)OY.debug("[SafeFS] Error reading file",{filePath:Z,error:Y});return null}}async function H6(Z){try{return(await qZ.stat(Z)).isDirectory()}catch{return!1}}async function z7(Z){try{return await qZ.stat(Z)}catch{return null}}var G7=S();class DF{validatePath(Z,J){try{let $=W4.resolve(Z),X=W4.resolve($,J);if(!(X===$||X.startsWith($+W4.sep)))return{valid:!1,fullPath:"",error:"Path traversal detected: path escapes project directory"};try{let Q=LM.realpathSync(X),W=LM.realpathSync($);if(!(Q===W||Q.startsWith(W+W4.sep)))return{valid:!1,fullPath:"",error:"Symlink escape detected: symlink points outside project directory"}}catch{}return{valid:!0,fullPath:X}}catch($){return{valid:!1,fullPath:"",error:`Path validation error: ${$ instanceof Error?$.message:"Unknown error"}`}}}async listDirectory(Z,J){let $=this.validatePath(Z,J);if(!$.valid)return{entries:[],error:$.error};try{if(!(await T0.stat($.fullPath)).isDirectory())return{entries:[],error:"Path is not a directory"};let Y=await T0.readdir($.fullPath,{withFileTypes:!0}),Q=await Promise.all(Y.map(async(W)=>{let K=W4.join($.fullPath,W.name);try{let z=await T0.stat(K);return{name:W.name,type:W.isDirectory()?"directory":"file",size:W.isFile()?z.size:void 0,modified:z.mtime.toISOString()}}catch{return{name:W.name,type:W.isDirectory()?"directory":"file"}}}));return Q.sort((W,K)=>{if(W.type!==K.type)return W.type==="directory"?-1:1;return W.name.localeCompare(K.name,void 0,{sensitivity:"base"})}),{entries:Q}}catch(X){let Y=X instanceof Error?X.message:"Unknown error";return G7.error("[FileManager] listDirectory error",{error:Y,path:$.fullPath}),{entries:[],error:`Failed to list directory: ${Y}`}}}async readFile(Z,J){let $=this.validatePath(Z,J);if(!$.valid)return{content:"",size:0,error:$.error};try{let X=await z7($.fullPath);if(!X||!X.isFile())return{content:"",size:0,error:"Path is not a file"};let Y=await A0($.fullPath);if(Y===null)return{content:"",size:0,error:"Failed to read file"};return{content:Y,size:Number(X.size)}}catch(X){let Y=X instanceof Error?X.message:"Unknown error";return G7.error("[FileManager] readFile error",{error:Y,path:$.fullPath}),{content:"",size:0,error:`Failed to read file: ${Y}`}}}async writeFile(Z,J,$){let X=this.validatePath(Z,J);if(!X.valid)return{success:!1,error:X.error};try{let Y=W4.dirname(X.fullPath);return await T0.mkdir(Y,{recursive:!0}),await T0.writeFile(X.fullPath,$,"utf-8"),{success:!0}}catch(Y){let Q=Y instanceof Error?Y.message:"Unknown error";return G7.error("[FileManager] writeFile error",{error:Q,path:X.fullPath}),{success:!1,error:`Failed to write file: ${Q}`}}}async createFile(Z,J){let $=this.validatePath(Z,J);if(!$.valid)return{success:!1,error:$.error};try{try{return await T0.access($.fullPath),{success:!1,error:"File already exists"}}catch{}let X=W4.basename(J);if(!this.isValidFilename(X))return{success:!1,error:"Invalid filename"};let Y=W4.dirname($.fullPath);return await T0.mkdir(Y,{recursive:!0}),await T0.writeFile($.fullPath,"","utf-8"),{success:!0}}catch(X){let Y=X instanceof Error?X.message:"Unknown error";return G7.error("[FileManager] createFile error",{error:Y,path:$.fullPath}),{success:!1,error:`Failed to create file: ${Y}`}}}async createDirectory(Z,J){let $=this.validatePath(Z,J);if(!$.valid)return{success:!1,error:$.error};try{let X=W4.basename(J);if(!this.isValidFilename(X))return{success:!1,error:"Invalid directory name"};try{if((await T0.stat($.fullPath)).isDirectory())return{success:!1,error:"Directory already exists"};return{success:!1,error:"A file with this name already exists"}}catch{}return await T0.mkdir($.fullPath,{recursive:!0}),{success:!0}}catch(X){let Y=X instanceof Error?X.message:"Unknown error";return G7.error("[FileManager] createDirectory error",{error:Y,path:$.fullPath}),{success:!1,error:`Failed to create directory: ${Y}`}}}async deleteFile(Z,J){let $=this.validatePath(Z,J);if(!$.valid)return{success:!1,error:$.error};try{if(!(await T0.stat($.fullPath)).isFile())return{success:!1,error:"Path is not a file"};return await T0.unlink($.fullPath),{success:!0}}catch(X){let Y=X instanceof Error?X.message:"Unknown error";return G7.error("[FileManager] deleteFile error",{error:Y,path:$.fullPath}),{success:!1,error:`Failed to delete file: ${Y}`}}}async deleteDirectory(Z,J){let $=this.validatePath(Z,J);if(!$.valid)return{success:!1,error:$.error};if($.fullPath===W4.resolve(Z))return{success:!1,error:"Cannot delete project root directory"};try{if(!(await T0.stat($.fullPath)).isDirectory())return{success:!1,error:"Path is not a directory"};return await T0.rm($.fullPath,{recursive:!0,force:!0}),{success:!0}}catch(X){let Y=X instanceof Error?X.message:"Unknown error";return G7.error("[FileManager] deleteDirectory error",{error:Y,path:$.fullPath}),{success:!1,error:`Failed to delete directory: ${Y}`}}}async pathExists(Z,J){let $=this.validatePath(Z,J);if(!$.valid)return!1;try{return await T0.access($.fullPath),!0}catch{return!1}}async getStats(Z,J){let $=this.validatePath(Z,J);if(!$.valid)return null;try{let X=await T0.stat($.fullPath);return{isFile:X.isFile(),isDirectory:X.isDirectory(),size:X.size,modified:X.mtime.toISOString()}}catch{return null}}async readFileBinary(Z,J){let $=this.validatePath(Z,J);if(!$.valid)return{content:Buffer.alloc(0),size:0,mimeType:"",error:$.error};try{let X=await z7($.fullPath);if(!X||!X.isFile())return{content:Buffer.alloc(0),size:0,mimeType:"",error:"Path is not a file"};let Y=52428800;if(X.size>Y)return{content:Buffer.alloc(0),size:0,mimeType:"",error:"File exceeds maximum size of 50MB"};let Q=await Hz1($.fullPath,{maxSize:Y});if(Q===null)return{content:Buffer.alloc(0),size:0,mimeType:"",error:"Failed to read file"};let W=this.getMimeType(W4.basename(J));return{content:Q,size:Number(X.size),mimeType:W}}catch(X){let Y=X instanceof Error?X.message:"Unknown error";return G7.error("[FileManager] readFileBinary error",{error:Y,path:$.fullPath}),{content:Buffer.alloc(0),size:0,mimeType:"",error:`Failed to read file: ${Y}`}}}async writeFileBinary(Z,J,$){let X=this.validatePath(Z,J);if(!X.valid)return{success:!1,error:X.error};try{let Y=W4.basename(J);if(!this.isValidFilename(Y))return{success:!1,error:"Invalid filename"};let Q=W4.dirname(X.fullPath);return await T0.mkdir(Q,{recursive:!0}),await T0.writeFile(X.fullPath,$),{success:!0}}catch(Y){let Q=Y instanceof Error?Y.message:"Unknown error";return G7.error("[FileManager] writeFileBinary error",{error:Q,path:X.fullPath}),{success:!1,error:`Failed to write file: ${Q}`}}}getMimeType(Z){let J=W4.extname(Z).toLowerCase();return{".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".ico":"image/x-icon",".bmp":"image/bmp",".tiff":"image/tiff",".heic":"image/heic",".heif":"image/heif",".pdf":"application/pdf",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".odt":"application/vnd.oasis.opendocument.text",".ods":"application/vnd.oasis.opendocument.spreadsheet",".txt":"text/plain",".json":"application/json",".xml":"application/xml",".html":"text/html",".htm":"text/html",".css":"text/css",".js":"application/javascript",".ts":"application/typescript",".tsx":"application/typescript",".jsx":"application/javascript",".md":"text/markdown",".yaml":"text/yaml",".yml":"text/yaml",".csv":"text/csv",".log":"text/plain",".zip":"application/zip",".tar":"application/x-tar",".gz":"application/gzip",".rar":"application/vnd.rar",".7z":"application/x-7z-compressed",".mp3":"audio/mpeg",".wav":"audio/wav",".ogg":"audio/ogg",".m4a":"audio/mp4",".flac":"audio/flac",".aac":"audio/aac",".mp4":"video/mp4",".mov":"video/quicktime",".avi":"video/x-msvideo",".mkv":"video/x-matroska",".webm":"video/webm",".wmv":"video/x-ms-wmv",".ttf":"font/ttf",".otf":"font/otf",".woff":"font/woff",".woff2":"font/woff2",".apk":"application/vnd.android.package-archive",".ipa":"application/octet-stream",".exe":"application/x-msdownload",".dmg":"application/x-apple-diskimage",".deb":"application/x-deb",".rpm":"application/x-rpm"}[J]||"application/octet-stream"}isValidFilename(Z){if(!Z||Z.length===0)return!1;if(Z.includes("/")||Z.includes("\\"))return!1;let J=["CON","PRN","AUX","NUL","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9"],$=(Z.split(".")[0]||"").toUpperCase();if(J.includes($))return!1;if(/[<>:"|?*\x00-\x1f]/.test(Z))return!1;if(Z==="."||Z==="..")return!1;return!0}}import*as DM from"path";var V6=S(),_Y=51200,Vz1=50,NY0=60000,Fz1=300000;class OF extends Q0{name="File Browser Service";get logPrefix(){return"[FileBrowser]"}fileManager;fileSaveOperations=new Map;binaryUploadOperations=new Map;staleOpCleanupInterval=null;constructor(){super();this.fileManager=new DF}async onStart(){this.staleOpCleanupInterval=setInterval(()=>{this.cleanupStaleOperations()},NY0)}async onStop(){if(this.staleOpCleanupInterval)clearInterval(this.staleOpCleanupInterval),this.staleOpCleanupInterval=null;this.fileSaveOperations.clear(),this.binaryUploadOperations.clear()}registerMQTTHandlers(){if(!this.mqttClient)return;this.registerHandler("files/list/request",(Z,J)=>{this.handleDirectoryListRequest(J)}),this.registerHandler("files/content/request",(Z,J)=>{this.handleFileContentRequest(J)}),this.registerHandler("files/save/request",(Z,J)=>{this.handleFileSaveRequest(J)}),this.registerHandler("files/create/request",(Z,J)=>{this.handleFileCreateRequest(J)}),this.registerHandler("files/delete/request",(Z,J)=>{this.handleFileDeleteRequest(J)}),this.registerHandler("files/upload/request",(Z,J)=>{this.handleBinaryUploadRequest(J)}),this.registerHandler("files/download/request",(Z,J)=>{this.handleBinaryDownloadRequest(J)}),V6.debug("[FileBrowser] MQTT handlers registered")}async handleDirectoryListRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J,Y=await this.fileManager.listDirectory($.projectPath,$.relativePath),Q={path:$.relativePath,entries:Y.entries,timestamp:Date.now(),error:Y.error};await this.publishResponse(this.buildResponseTopic("files/list",$.clientId,$.requestId),Q,X),this.requestsHandled++}catch(J){V6.error("[FileBrowser] Error handling directory list request",{error:J instanceof Error?J.message:"Unknown error"})}}async handleFileContentRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J,Y=await this.fileManager.readFile($.projectPath,$.relativePath),Q=this.buildResponseTopic("files/content",$.clientId,$.requestId);if(Y.error){let K={path:$.relativePath,chunk:{chunkIndex:0,totalChunks:1,content:""},totalSize:0,timestamp:Date.now(),error:Y.error};await this.publishResponse(Q,K,X);return}let W=Math.max(1,Math.ceil(Y.content.length/_Y));for(let K=0;K<W;K++){let z=K*_Y,G=Math.min(z+_Y,Y.content.length),H=Y.content.slice(z,G),V={path:$.relativePath,chunk:{chunkIndex:K,totalChunks:W,content:H},totalSize:Y.size,timestamp:Date.now()};if(await this.publishResponse(Q,V,X),K<W-1)await this.delay(Vz1)}this.requestsHandled++}catch(J){V6.error("[FileBrowser] Error handling file content request",{error:J instanceof Error?J.message:"Unknown error"})}}async handleFileSaveRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J,Y=`${$.clientId}:${$.relativePath}`;if($.chunk.chunkIndex===0)this.fileSaveOperations.set(Y,{chunks:new Map,totalChunks:$.chunk.totalChunks,totalSize:$.totalSize,startedAt:Date.now()});let Q=this.fileSaveOperations.get(Y);if(!Q){await this.sendSaveResponse($,X,!1,"Save operation not initialized");return}if(Q.chunks.set($.chunk.chunkIndex,$.chunk.content),await this.sendSaveResponse($,X,!0),Q.chunks.size===Q.totalChunks){let W=[];for(let G=0;G<Q.totalChunks;G++){let H=Q.chunks.get(G);if(H===void 0){V6.error(`[FileBrowser] Missing chunk ${G} of ${Q.totalChunks} for ${Y}`),this.fileSaveOperations.delete(Y),await this.sendSaveResponse($,X,!1,`Missing chunk ${G} \u2014 file save aborted`);return}W.push(H)}let K=W.join(""),z=await this.fileManager.writeFile($.projectPath,$.relativePath,K);if(this.fileSaveOperations.delete(Y),!z.error)this.requestsHandled++}}catch(J){V6.error("[FileBrowser] Error handling file save request",{error:J instanceof Error?J.message:"Unknown error"})}}async handleFileCreateRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J,Y;if($.type==="directory")Y=await this.fileManager.createDirectory($.projectPath,$.relativePath);else Y=await this.fileManager.createFile($.projectPath,$.relativePath);let Q={path:$.relativePath,success:Y.success,type:$.type,timestamp:Date.now(),error:Y.error};if(await this.publishResponse(this.buildResponseTopic("files/create",$.clientId,$.requestId),Q,X),Y.success)this.requestsHandled++}catch(J){V6.error("[FileBrowser] Error handling file create request",{error:J instanceof Error?J.message:"Unknown error"})}}async handleFileDeleteRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J,Y=await this.fileManager.getStats($.projectPath,$.relativePath),Q;if(!Y)Q={success:!1,error:"Path does not exist"};else if(Y.isDirectory)Q=await this.fileManager.deleteDirectory($.projectPath,$.relativePath);else Q=await this.fileManager.deleteFile($.projectPath,$.relativePath);let W={path:$.relativePath,success:Q.success,timestamp:Date.now(),error:Q.error};if(await this.publishResponse(this.buildResponseTopic("files/delete",$.clientId,$.requestId),W,X),Q.success)this.requestsHandled++}catch(J){V6.error("[FileBrowser] Error handling file delete request",{error:J instanceof Error?J.message:"Unknown error"})}}async sendSaveResponse(Z,J,$,X){let Y={path:Z.relativePath,success:$,chunkIndex:Z.chunk.chunkIndex,totalChunks:Z.chunk.totalChunks,timestamp:Date.now(),error:X};await this.publishResponse(this.buildResponseTopic("files/save",Z.clientId,Z.requestId),Y,J)}delay(Z){return new Promise((J)=>setTimeout(J,Z))}async handleBinaryUploadRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J,Y=`${$.clientId}:${$.relativePath}`;if($.chunk.chunkIndex===0){if($.totalSize>52428800){await this.sendBinaryUploadResponse($,X,!1,"File exceeds 50MB limit",0);return}this.binaryUploadOperations.set(Y,{chunks:new Map,totalChunks:$.chunk.totalChunks,totalSize:$.totalSize,filename:$.filename,mimeType:$.mimeType,receivedBytes:0,startedAt:Date.now()})}let Q=this.binaryUploadOperations.get(Y);if(!Q){await this.sendBinaryUploadResponse($,X,!1,"Upload operation not initialized",0);return}let W=Buffer.from($.chunk.data,"base64");if(Q.chunks.set($.chunk.chunkIndex,W),Q.receivedBytes+=W.length,await this.sendBinaryUploadResponse($,X,!0,void 0,Q.receivedBytes),Q.chunks.size===Q.totalChunks){let K=[];for(let H=0;H<Q.totalChunks;H++){let V=Q.chunks.get(H);if(!V){V6.error(`[FileBrowser] Missing binary chunk ${H} of ${Q.totalChunks} for ${Y}`),this.binaryUploadOperations.delete(Y),await this.sendBinaryUploadResponse($,X,!1,`Missing chunk ${H} \u2014 upload aborted`);return}K.push(V)}let z=Buffer.concat(K),G=await this.fileManager.writeFileBinary($.projectPath,$.relativePath,z);if(this.binaryUploadOperations.delete(Y),G.error)V6.error("[FileBrowser] Binary upload write failed",{error:G.error});else this.requestsHandled++,V6.debug("[FileBrowser] Binary upload completed",{path:$.relativePath,size:z.length})}}catch(J){V6.error("[FileBrowser] Error handling binary upload",{error:J instanceof Error?J.message:"Unknown error"})}}async sendBinaryUploadResponse(Z,J,$,X,Y){let Q={path:Z.relativePath,success:$,chunkIndex:Z.chunk.chunkIndex,totalChunks:Z.chunk.totalChunks,bytesReceived:Y||0,timestamp:Date.now(),error:X};await this.publishResponse(this.buildResponseTopic("files/upload",Z.clientId,Z.requestId),Q,J)}async handleBinaryDownloadRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J,Y=this.buildResponseTopic("files/download",$.clientId,$.requestId),Q=await this.fileManager.readFileBinary($.projectPath,$.relativePath);if(Q.error){let G={path:$.relativePath,filename:DM.basename($.relativePath),mimeType:"",chunk:{chunkIndex:0,totalChunks:1,data:""},totalSize:0,timestamp:Date.now(),error:Q.error};await this.publishResponse(Y,G,X);return}let W=Q.content.toString("base64"),K=Math.max(1,Math.ceil(W.length/_Y)),z=DM.basename($.relativePath);for(let G=0;G<K;G++){let H=G*_Y,V=Math.min(H+_Y,W.length),F=W.slice(H,V),B={path:$.relativePath,filename:z,mimeType:Q.mimeType,chunk:{chunkIndex:G,totalChunks:K,data:F},totalSize:Q.size,timestamp:Date.now()};if(await this.publishResponse(Y,B,X),G<K-1)await this.delay(Vz1)}this.requestsHandled++,V6.debug("[FileBrowser] Binary download completed",{path:$.relativePath,size:Q.size,chunks:K})}catch(J){V6.error("[FileBrowser] Error handling binary download",{error:J instanceof Error?J.message:"Unknown error"})}}cleanupStaleOperations(){let Z=Date.now();for(let[J,$]of this.fileSaveOperations)if(Z-$.startedAt>Fz1)V6.warn(`[FileBrowser] Cleaning up stale file save operation: ${J} (age: ${Math.round((Z-$.startedAt)/1000)}s)`),this.fileSaveOperations.delete(J);for(let[J,$]of this.binaryUploadOperations)if(Z-$.startedAt>Fz1)V6.warn(`[FileBrowser] Cleaning up stale binary upload operation: ${J} (age: ${Math.round((Z-$.startedAt)/1000)}s)`),this.binaryUploadOperations.delete(J)}getStatus(){return{name:this.name,running:this.running,startedAt:this.startedAt,requestsHandled:this.requestsHandled,pendingSaveOperations:this.fileSaveOperations.size}}}var Z1=S();class _F extends Q0{name="Git Service";get logPrefix(){return"[GitService]"}worktreeManager;ghAuthResult={authenticated:!1,installed:!1,inPath:!1};constructor(){super();this.worktreeManager=new k8}async onStart(){if(this.ghAuthResult=await EW1(),!this.ghAuthResult.authenticated)Z1.warn("[GitService] GitHub CLI issue detected",{installed:this.ghAuthResult.installed,inPath:this.ghAuthResult.inPath,ghPath:this.ghAuthResult.ghPath,error:this.ghAuthResult.error});else{Z1.info("[GitService] GitHub CLI authenticated",{username:this.ghAuthResult.username,gitProtocol:this.ghAuthResult.gitProtocol});let Z=await IW1();if(!Z.success)Z1.warn("[GitService] Could not sync gh config git_protocol",{error:Z.error});let J=await SW1();if(!J.success)Z1.warn("[GitService] Could not setup git credential helper",{error:J.error})}}async onStop(){this.worktreeManager.clearCache()}registerMQTTHandlers(){if(!this.mqttClient)return;this.registerHandler("git/orgs/request",(Z,J)=>{this.handleOrgsRequest(J)}),this.registerHandler("git/repos/request",(Z,J)=>{this.handleReposRequest(J)}),this.registerHandler("git/repos/search/request",(Z,J)=>{this.handleSearchReposRequest(J)}),this.registerHandler("git/branches/request",(Z,J)=>{this.handleBranchesRequest(J)}),this.registerHandler("git/clone/request",(Z,J)=>{this.handleCloneRequest(J)}),this.registerHandler("git/is-repo/request",(Z,J)=>{this.handleIsRepoRequest(J)}),this.registerHandler("git/worktree/get-or-create/request",(Z,J)=>{this.handleWorktreeGetOrCreateRequest(J)}),this.registerHandler("git/worktree/get/request",(Z,J)=>{this.handleWorktreeGetRequest(J)}),this.registerHandler("git/worktree/list/request",(Z,J)=>{this.handleWorktreeListRequest(J)}),this.registerHandler("git/status/request",(Z,J)=>{this.handleStatusRequest(J)}),this.registerHandler("git/diff/request",(Z,J)=>{this.handleDiffRequest(J)}),this.registerHandler("git/changes/all/request",(Z,J)=>{this.handleChangesAllRequest(J)}),this.registerHandler("git/stage/request",(Z,J)=>{this.handleStageRequest(J)}),this.registerHandler("git/unstage/request",(Z,J)=>{this.handleUnstageRequest(J)}),this.registerHandler("git/commit/request",(Z,J)=>{this.handleCommitRequest(J)}),this.registerHandler("git/unpushed/request",(Z,J)=>{this.handleUnpushedCommitsRequest(J)}),this.registerHandler("git/push/request",(Z,J)=>{this.handlePushRequest(J)}),this.registerHandler("git/history/request",(Z,J)=>{this.handleHistoryRequest(J)}),this.registerHandler("git/commit-details/request",(Z,J)=>{this.handleCommitDetailsRequest(J)}),this.registerHandler("git/commit-file-diff/request",(Z,J)=>{this.handleCommitFileDiffRequest(J)}),this.registerHandler("git/sync/request",(Z,J)=>{this.handleSyncRequest(J)}),this.registerHandler("git/create-pr/request",(Z,J)=>{this.handleCreatePRRequest(J)}),this.registerHandler("git/default-branch/request",(Z,J)=>{this.handleDefaultBranchRequest(J)}),this.registerHandler("git/existing-pr/request",(Z,J)=>{this.handleExistingPRRequest(J)}),this.registerHandler("git/remote-branches/request",(Z,J)=>{this.handleRemoteBranchesRequest(J)}),this.registerHandler("git/create-branch/request",(Z,J)=>{this.handleCreateBranchRequest(J)}),this.registerHandler("git/local-branches/request",(Z,J)=>{this.handleLocalBranchesRequest(J)}),this.registerHandler("git/checkout-branch/request",(Z,J)=>{this.handleCheckoutBranchRequest(J)}),Z1.debug("[GitService] MQTT handlers registered")}async handleOrgsRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;if(Z1.debug("[GitService] Orgs request",{clientId:$.clientId}),!this.ghAuthResult.authenticated){let W={orgs:[],error:this.ghAuthResult.error||"GitHub CLI not available.",timestamp:Date.now()};await this.publishResponse(`git/orgs/${$.clientId}/response`,W,X);return}let Q={orgs:await iT(),timestamp:Date.now()};await this.publishResponse(`git/orgs/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(J){Z1.error("[GitService] Error handling orgs request",{error:J})}}async handleReposRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J,Y=$.requestId||$.clientId;if(Z1.debug("[GitService] Repos request",{clientId:$.clientId,requestId:$.requestId,org:$.org,limit:$.limit}),!this.ghAuthResult.authenticated){let K={repos:[],error:this.ghAuthResult.error||"GitHub CLI not available.",timestamp:Date.now()};await this.publishResponse(`git/repos/${Y}/response`,K,X);return}let W={repos:await JF($.org,$.limit||20),timestamp:Date.now()};await this.publishResponse(`git/repos/${Y}/response`,W,X),this.requestsHandled++}catch(J){Z1.error("[GitService] Error handling repos request",{error:J})}}async handleSearchReposRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;if(Z1.debug("[GitService] Search repos request",{clientId:$.clientId,query:$.query,limit:$.limit}),!this.ghAuthResult.authenticated){let Q={repos:[],error:this.ghAuthResult.error||"GitHub CLI not available.",timestamp:Date.now()};await this.publishResponse(`git/repos/search/${$.clientId}/response`,Q,X);return}let Y=$.clientId;await yW1($.query,async(Q,W,K)=>{let z={repos:Q,timestamp:Date.now(),source:W,isComplete:K};await this.publishResponse(`git/repos/search/${Y}/response`,z,X),Z1.debug("[GitService] Sent search results",{source:W,count:Q.length,isComplete:K})},$.limit||50),this.requestsHandled++}catch(J){Z1.error("[GitService] Error handling search repos request",{error:J})}}async handleBranchesRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;if(Z1.debug("[GitService] Branches request",{clientId:$.clientId,owner:$.owner,repo:$.repo}),!this.ghAuthResult.authenticated){let W={branches:[],error:this.ghAuthResult.error||"GitHub CLI not available.",timestamp:Date.now()};await this.publishResponse(`git/branches/${$.clientId}/response`,W,X);return}let Y=await kW1($.owner,$.repo),Q={branches:Y.branches,defaultBranch:Y.defaultBranch,timestamp:Date.now()};await this.publishResponse(`git/branches/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(J){Z1.error("[GitService] Error handling branches request",{error:J})}}async handleCloneRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;if(Z1.debug("[GitService] Clone request",{clientId:$.clientId,repoUrl:$.repoUrl,targetPath:$.targetPath,branch:$.branch}),!this.ghAuthResult.authenticated){let W={success:!1,error:this.ghAuthResult.error||"GitHub CLI not available.",timestamp:Date.now()};await this.publishResponse(`git/clone/${$.clientId}/response`,W,X);return}let Y=await xW1($.repoUrl,$.targetPath,$.branch),Q=Y.success?{success:!0,path:Y.path,defaultBranch:Y.defaultBranch,timestamp:Date.now()}:{success:!1,error:Y.error||"Clone failed",timestamp:Date.now()};await this.publishResponse(`git/clone/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(J){Z1.error("[GitService] Error handling clone request",{error:J})}}async handleIsRepoRequest(Z){let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;try{Z1.debug("[GitService] Is-repo request",{clientId:$.clientId,path:$.path});let Y=await I6($.path),Q;if(Y){let[W,K,z]=await Promise.all([a4($.path),$$($.path),iW1($.path)]);Q={isGitRepo:!0,repoRoot:W||void 0,defaultBranch:K||void 0,remoteUrl:z||void 0,timestamp:Date.now()}}else Q={isGitRepo:!1,timestamp:Date.now()};await this.publishResponse(`git/is-repo/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(Y){Z1.error("[GitService] Error handling is-repo request",{error:Y});let Q={isGitRepo:!1,timestamp:Date.now()};await this.publishResponse(`git/is-repo/${$.clientId}/response`,Q,X)}}async handleWorktreeGetOrCreateRequest(Z){let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;try{Z1.debug("[GitService] Worktree get-or-create request",{clientId:$.clientId,repoPath:$.repoPath,sessionId:$.sessionId});let{worktree:Y,isNew:Q}=await this.worktreeManager.getOrCreateForSession($.sessionId,$.repoPath),W={success:!0,worktreePath:Y.path,branch:Y.branch,isNew:Q,timestamp:Date.now()};await this.publishResponse(`git/worktree/get-or-create/${$.clientId}/response`,W,X),this.requestsHandled++}catch(Y){Z1.error("[GitService] Error handling worktree get-or-create request",{error:Y});let Q={success:!1,error:Y instanceof Error?Y.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/worktree/get-or-create/${$.clientId}/response`,Q,X)}}async handleWorktreeGetRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;Z1.debug("[GitService] Worktree get request",{clientId:$.clientId,repoPath:$.repoPath,sessionId:$.sessionId});let Y=await this.worktreeManager.getWorktreeForSession($.sessionId,$.repoPath),Q=Y?{exists:!0,worktreePath:Y.path,branch:Y.branch,timestamp:Date.now()}:{exists:!1,timestamp:Date.now()};await this.publishResponse(`git/worktree/get/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(J){Z1.error("[GitService] Error handling worktree get request",{error:J})}}async handleWorktreeListRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;Z1.debug("[GitService] Worktree list request",{clientId:$.clientId,repoPath:$.repoPath});let Q={worktrees:await this.worktreeManager.listWorktreesForRepo($.repoPath),timestamp:Date.now()};await this.publishResponse(`git/worktree/list/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(J){Z1.error("[GitService] Error handling worktree list request",{error:J})}}async handleStatusRequest(Z){let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;try{Z1.debug("[GitService] Status request",{clientId:$.clientId,path:$.path});let Q={success:!0,status:await nT($.path),timestamp:Date.now()};await this.publishResponse(`git/status/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(Y){Z1.error("[GitService] Error handling status request",{error:Y});let Q={success:!1,error:Y instanceof Error?Y.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/status/${$.clientId}/response`,Q,X)}}async handleDiffRequest(Z){let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;try{Z1.debug("[GitService] Diff request",{clientId:$.clientId,path:$.path,file:$.file,staged:$.staged});let Y=await hW1($.path,$.file,$.staged),Q={success:!0,diff:Y.diff,isBinary:Y.isBinary,timestamp:Date.now()};await this.publishResponse(`git/diff/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(Y){Z1.error("[GitService] Error handling diff request",{error:Y});let Q={success:!1,error:Y instanceof Error?Y.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/diff/${$.clientId}/response`,Q,X)}}async handleChangesAllRequest(Z){let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;try{Z1.debug("[GitService] Changes all request",{clientId:$.clientId,repoPath:$.repoPath});let Y=await this.worktreeManager.listWorktreesForRepo($.repoPath),Q={repoPath:$.repoPath,worktrees:[],totalChanges:0};for(let K of Y)try{let z=await nT(K.path);Q.worktrees.push({worktreePath:K.path,branch:K.branch,sessionId:K.sessionId,changes:z.files,totalCount:z.files.length}),Q.totalChanges+=z.files.length}catch(z){Z1.warn("[GitService] Failed to get status for worktree",{path:K.path,error:z})}let W={success:!0,changes:Q,timestamp:Date.now()};await this.publishResponse(`git/changes/all/${$.clientId}/response`,W,X),this.requestsHandled++}catch(Y){Z1.error("[GitService] Error handling changes all request",{error:Y});let Q={success:!1,error:Y instanceof Error?Y.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/changes/all/${$.clientId}/response`,Q,X)}}async handleStageRequest(Z){let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;try{Z1.debug("[GitService] Stage request",{clientId:$.clientId,path:$.path,files:$.files}),await fW1($.path,$.files);let Y={success:!0,timestamp:Date.now()};await this.publishResponse(`git/stage/${$.clientId}/response`,Y,X),this.requestsHandled++}catch(Y){Z1.error("[GitService] Error handling stage request",{error:Y});let Q={success:!1,error:Y instanceof Error?Y.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/stage/${$.clientId}/response`,Q,X)}}async handleUnstageRequest(Z){let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;try{Z1.debug("[GitService] Unstage request",{clientId:$.clientId,path:$.path,files:$.files}),await bW1($.path,$.files);let Y={success:!0,timestamp:Date.now()};await this.publishResponse(`git/unstage/${$.clientId}/response`,Y,X),this.requestsHandled++}catch(Y){Z1.error("[GitService] Error handling unstage request",{error:Y});let Q={success:!1,error:Y instanceof Error?Y.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/unstage/${$.clientId}/response`,Q,X)}}async handleCommitRequest(Z){let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;try{Z1.debug("[GitService] Commit request",{clientId:$.clientId,path:$.path,signoff:$.signoff});let Q={success:!0,commit:await gW1($.path,$.message,$.signoff),timestamp:Date.now()};await this.publishResponse(`git/commit/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(Y){Z1.error("[GitService] Error handling commit request",{error:Y});let Q={success:!1,error:Y instanceof Error?Y.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/commit/${$.clientId}/response`,Q,X)}}async handleUnpushedCommitsRequest(Z){let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;try{Z1.debug("[GitService] Unpushed commits request",{clientId:$.clientId,path:$.path});let Y=await VY($.path),Q={success:!0,commits:Y.commits,upstream:Y.upstream,ahead:Y.ahead,timestamp:Date.now()};await this.publishResponse(`git/unpushed/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(Y){Z1.error("[GitService] Error handling unpushed commits request",{error:Y});let Q={success:!1,error:Y instanceof Error?Y.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/unpushed/${$.clientId}/response`,Q,X)}}async handlePushRequest(Z){let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;try{Z1.debug("[GitService] Push request",{clientId:$.clientId,path:$.path,force:$.force});let Y=await nW1($.path,$.force),Q={success:!0,commitsPushed:Y.commitsPushed,remote:Y.remote,branch:Y.branch,timestamp:Date.now()};await this.publishResponse(`git/push/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(Y){Z1.error("[GitService] Error handling push request",{error:Y});let Q={success:!1,error:Y instanceof Error?Y.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/push/${$.clientId}/response`,Q,X)}}async handleHistoryRequest(Z){let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;try{Z1.debug("[GitService] History request",{clientId:$.clientId,path:$.path,limit:$.limit});let Y=await aW1($.path,$.limit||50),Q={success:!0,commits:Y.commits,totalCount:Y.totalCount,timestamp:Date.now()};await this.publishResponse(`git/history/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(Y){Z1.error("[GitService] Error handling history request",{error:Y});let Q={success:!1,error:Y instanceof Error?Y.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/history/${$.clientId}/response`,Q,X)}}async handleCommitDetailsRequest(Z){let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;try{Z1.debug("[GitService] Commit details request",{clientId:$.clientId,path:$.path,commitHash:$.commitHash});let Q={success:!0,commit:await oW1($.path,$.commitHash),timestamp:Date.now()};await this.publishResponse(`git/commit-details/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(Y){Z1.error("[GitService] Error handling commit details request",{error:Y});let Q={success:!1,error:Y instanceof Error?Y.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/commit-details/${$.clientId}/response`,Q,X)}}async handleCommitFileDiffRequest(Z){let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;try{Z1.debug("[GitService] Commit file diff request",{clientId:$.clientId,path:$.path,commitHash:$.commitHash,filePath:$.filePath});let Y=await sW1($.path,$.commitHash,$.filePath),Q={success:!0,diff:Y.diff,isBinary:Y.isBinary,timestamp:Date.now()};await this.publishResponse(`git/commit-file-diff/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(Y){Z1.error("[GitService] Error handling commit file diff request",{error:Y});let Q={success:!1,error:Y instanceof Error?Y.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/commit-file-diff/${$.clientId}/response`,Q,X)}}async handleSyncRequest(Z){let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;try{Z1.debug("[GitService] Sync request",{clientId:$.clientId,path:$.path});let Y=await rW1($.path),Q=Y.success?{success:!0,action:Y.action,commitsPulled:Y.commitsPulled,commitsPushed:Y.commitsPushed,timestamp:Date.now()}:{success:!1,action:Y.action,commitsPulled:Y.commitsPulled,commitsPushed:Y.commitsPushed,error:Y.error||"Sync failed",conflictedFiles:Y.conflictedFiles,timestamp:Date.now()};await this.publishResponse(`git/sync/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(Y){Z1.error("[GitService] Error handling sync request",{error:Y});let Q={success:!1,action:"error",commitsPulled:0,commitsPushed:0,error:Y instanceof Error?Y.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/sync/${$.clientId}/response`,Q,X)}}async handleCreatePRRequest(Z){let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;try{Z1.debug("[GitService] Create PR request",{clientId:$.clientId,path:$.path,title:$.title,baseBranch:$.baseBranch,draft:$.draft});let Y=await tW1($.path,$.title,$.body,$.baseBranch,$.draft),Q=Y.success?{success:!0,prNumber:Y.prNumber,prUrl:Y.prUrl,timestamp:Date.now()}:{success:!1,error:Y.error||"Failed to create pull request",timestamp:Date.now()};await this.publishResponse(`git/create-pr/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(Y){Z1.error("[GitService] Error handling create PR request",{error:Y});let Q={success:!1,error:Y instanceof Error?Y.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/create-pr/${$.clientId}/response`,Q,X)}}async handleDefaultBranchRequest(Z){let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;try{Z1.debug("[GitService] Default branch request",{clientId:$.clientId,path:$.path});let Y=await aT($.path),Q=Y?{success:!0,defaultBranch:Y,timestamp:Date.now()}:{success:!1,error:"Could not determine default branch",timestamp:Date.now()};await this.publishResponse(`git/default-branch/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(Y){Z1.error("[GitService] Error handling default branch request",{error:Y});let Q={success:!1,error:Y instanceof Error?Y.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/default-branch/${$.clientId}/response`,Q,X)}}async handleExistingPRRequest(Z){let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;try{Z1.debug("[GitService] Existing PR request",{clientId:$.clientId,path:$.path});let Y=await eW1($.path),Q={exists:Y.exists,prNumber:Y.prNumber,prUrl:Y.prUrl,title:Y.title,state:Y.state,draft:Y.draft,error:Y.error,timestamp:Date.now()};await this.publishResponse(`git/existing-pr/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(Y){Z1.error("[GitService] Error handling existing PR request",{error:Y});let Q={exists:!1,error:Y instanceof Error?Y.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/existing-pr/${$.clientId}/response`,Q,X)}}async handleRemoteBranchesRequest(Z){let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;try{Z1.debug("[GitService] Remote branches request",{clientId:$.clientId,path:$.path});let Y=await ZK1($.path),Q={success:!0,branches:Y.branches,defaultBranch:Y.defaultBranch,timestamp:Date.now()};await this.publishResponse(`git/remote-branches/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(Y){Z1.error("[GitService] Error handling remote branches request",{error:Y});let Q={success:!1,error:Y instanceof Error?Y.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/remote-branches/${$.clientId}/response`,Q,X)}}async handleCreateBranchRequest(Z){let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;try{Z1.debug("[GitService] Create branch request",{clientId:$.clientId,path:$.path,branchName:$.branchName,checkout:$.checkout});let Y=await mW1($.path,$.branchName,$.checkout!==!1),Q=Y.success?{success:!0,branchName:$.branchName,timestamp:Date.now()}:{success:!1,error:Y.error||"Failed to create branch",timestamp:Date.now()};await this.publishResponse(`git/create-branch/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(Y){Z1.error("[GitService] Error handling create branch request",{error:Y});let Q={success:!1,error:Y instanceof Error?Y.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/create-branch/${$.clientId}/response`,Q,X)}}async handleLocalBranchesRequest(Z){let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;try{Z1.debug("[GitService] Local branches request",{clientId:$.clientId,path:$.path});let Y=await dW1($.path),Q={success:!0,branches:Y.branches,currentBranch:Y.currentBranch,timestamp:Date.now()};await this.publishResponse(`git/local-branches/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(Y){Z1.error("[GitService] Error handling local branches request",{error:Y});let Q={success:!1,error:Y instanceof Error?Y.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/local-branches/${$.clientId}/response`,Q,X)}}async handleCheckoutBranchRequest(Z){let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;try{Z1.debug("[GitService] Checkout branch request",{clientId:$.clientId,path:$.path,branchName:$.branchName});let Y=await uW1($.path,$.branchName),Q=Y.success?{success:!0,branchName:$.branchName,timestamp:Date.now()}:{success:!1,error:Y.error||"Failed to checkout branch",timestamp:Date.now()};await this.publishResponse(`git/checkout-branch/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(Y){Z1.error("[GitService] Error handling checkout branch request",{error:Y});let Q={success:!1,error:Y instanceof Error?Y.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/checkout-branch/${$.clientId}/response`,Q,X)}}getStatus(){return{name:this.name,running:this.running,startedAt:this.startedAt,requestsHandled:this.requestsHandled,activeWorktrees:this.worktreeManager.getActiveWorktreeCount(),ghAuthenticated:this.ghAuthResult.authenticated,ghInstalled:this.ghAuthResult.installed,ghInPath:this.ghAuthResult.inPath,ghError:this.ghAuthResult.error,ghUsername:this.ghAuthResult.username}}}import*as Oz1 from"path";import*as wF from"path";import*as Bz1 from"os";import*as AF from"fs";var M0=S(),JK=wF.join(Bz1.homedir(),".ccc"),eW=wF.join(JK,"device-tokens.json"),ZK=wF.join(JK,"notification-preferences.json");class Uz1{tokensCache=null;preferencesCache=null;async ensureDirectory(){try{if(!AF.existsSync(JK))AF.mkdirSync(JK,{recursive:!0}),M0.debug("[NotificationStorage] Created .ccc directory:",JK)}catch(Z){throw M0.error("[NotificationStorage] Error ensuring directory:",Z),Z}}async loadTokens(){if(this.tokensCache)return this.tokensCache;try{let Z=Bun.file(eW);if(await Z.exists()){let J=await Z.text(),$=JSON.parse(J);if($&&typeof $==="object"&&Array.isArray($.tokens)){let X=$;return this.tokensCache=X,M0.debug("[NotificationStorage] Loaded tokens:",{count:X.tokens.length}),X}else if($&&typeof $==="object")return M0.warn("[NotificationStorage] Invalid tokens file format, attempting to recover data"),this.tokensCache={tokens:Array.isArray($.tokens)?$.tokens:[]},await this.saveTokens(this.tokensCache),this.tokensCache;else{M0.error("[NotificationStorage] Completely invalid tokens file format, creating backup");let X=`${eW}.backup.${Date.now()}`;await Bun.write(X,J),M0.error("[NotificationStorage] Backup saved to:",X)}}}catch(Z){M0.error("[NotificationStorage] Error loading tokens:",Z);try{let J=Bun.file(eW);if(await J.exists()){let $=await J.text(),X=`${eW}.backup.${Date.now()}`;await Bun.write(X,$),M0.error("[NotificationStorage] Corrupted file backed up to:",X)}}catch{}}return this.tokensCache={tokens:[]},this.tokensCache}async saveTokens(Z){try{await this.ensureDirectory(),await Bun.write(eW,JSON.stringify(Z,null,2)),this.tokensCache=Z,M0.debug("[NotificationStorage] Saved tokens:",{count:Z.tokens.length})}catch(J){throw M0.error("[NotificationStorage] Error saving tokens:",J),J}}async registerToken(Z,J,$,X,Y){let Q=await this.loadTokens(),W=new Date().toISOString(),K=Q.tokens.findIndex((H)=>H.deviceId===Z),z=K>=0?Q.tokens[K]:void 0,G={deviceId:Z,fcmToken:J,expoPushToken:$,platform:X,deviceInfo:Y,createdAt:z?.createdAt??W,lastUsed:W};if(K>=0)Q.tokens[K]=G,M0.debug("[NotificationStorage] Updated device token:",{deviceId:Z,platform:X,hasExpoPushToken:!!$});else Q.tokens.push(G),M0.debug("[NotificationStorage] Registered new device token:",{deviceId:Z,platform:X,hasExpoPushToken:!!$});return await this.saveTokens(Q),G}async unregisterToken(Z){let J=await this.loadTokens(),$=J.tokens.length;if(J.tokens=J.tokens.filter((X)=>X.deviceId!==Z),J.tokens.length<$)return await this.saveTokens(J),M0.debug("[NotificationStorage] Unregistered device token:",{deviceId:Z}),!0;return!1}async getToken(Z){return(await this.loadTokens()).tokens.find(($)=>$.deviceId===Z)}async getAllTokens(){return(await this.loadTokens()).tokens}async getDeviceCount(){return(await this.loadTokens()).tokens.length}async updateLastUsed(Z){let J=await this.loadTokens(),$=J.tokens.find((X)=>X.deviceId===Z);if($)$.lastUsed=new Date().toISOString(),await this.saveTokens(J)}async cleanupOldTokens(Z=90){let J=await this.loadTokens(),$=new Date;$.setDate($.getDate()-Z);let X=$.toISOString(),Y=J.tokens.length;J.tokens=J.tokens.filter((W)=>W.lastUsed>X);let Q=Y-J.tokens.length;if(Q>0)await this.saveTokens(J),M0.debug("[NotificationStorage] Cleaned up old tokens:",{removed:Q,remaining:J.tokens.length});return Q}async loadPreferences(){if(this.preferencesCache)return this.preferencesCache;try{let Z=Bun.file(ZK);if(await Z.exists()){let J=await Z.text(),$=JSON.parse(J);if($&&typeof $==="object"&&typeof $.preferences==="object"&&!Array.isArray($.preferences)){let X=$;return this.preferencesCache=X,M0.debug("[NotificationStorage] Loaded preferences:",{count:Object.keys(X.preferences).length}),X}else if($&&typeof $==="object")return M0.warn("[NotificationStorage] Invalid preferences file format, attempting to recover data"),this.preferencesCache={preferences:$.preferences&&typeof $.preferences==="object"&&!Array.isArray($.preferences)?$.preferences:{}},await this.savePreferences(this.preferencesCache),this.preferencesCache;else{M0.error("[NotificationStorage] Completely invalid preferences file format, creating backup");let X=`${ZK}.backup.${Date.now()}`;await Bun.write(X,J),M0.error("[NotificationStorage] Backup saved to:",X)}}}catch(Z){M0.error("[NotificationStorage] Error loading preferences:",Z);try{let J=Bun.file(ZK);if(await J.exists()){let $=await J.text(),X=`${ZK}.backup.${Date.now()}`;await Bun.write(X,$),M0.error("[NotificationStorage] Corrupted file backed up to:",X)}}catch{}}return this.preferencesCache={preferences:{}},this.preferencesCache}async savePreferences(Z){try{await this.ensureDirectory(),await Bun.write(ZK,JSON.stringify(Z,null,2)),this.preferencesCache=Z,M0.debug("[NotificationStorage] Saved preferences:",{count:Object.keys(Z.preferences).length})}catch(J){throw M0.error("[NotificationStorage] Error saving preferences:",J),J}}getDefaultPreferences(Z){return{deviceId:Z,allMessages:!0,needsAttention:!0,updatedAt:new Date().toISOString()}}async getPreferences(Z){let J=await this.loadPreferences();if(!J.preferences[Z])J.preferences[Z]=this.getDefaultPreferences(Z),await this.savePreferences(J),M0.debug("[NotificationStorage] Created default preferences for device:",{deviceId:Z});return J.preferences[Z]}async updatePreferences(Z,J){let $=await this.loadPreferences(),X=await this.getPreferences(Z);return $.preferences[Z]={...X,...J,deviceId:Z,updatedAt:new Date().toISOString()},await this.savePreferences($),M0.debug("[NotificationStorage] Updated preferences:",{deviceId:Z,updates:J}),$.preferences[Z]}async isNotificationEnabled(Z,J){return(await this.getPreferences(Z))[J]}clearCache(){this.tokensCache=null,this.preferencesCache=null,M0.debug("[NotificationStorage] Cleared cache")}}var v8=new Uz1;import{Expo as RY0}from"expo-server-sdk";function CY0(Z){return typeof Z==="string"&&((Z.startsWith("ExponentPushToken[")||Z.startsWith("ExpoPushToken["))&&Z.endsWith("]")||/^[a-z\d]{8}-[a-z\d]{4}-[a-z\d]{4}-[a-z\d]{4}-[a-z\d]{12}$/i.test(Z))}var S6=S();class Lz1{expo=null;notificationsSent=0;lastNotificationAt;pendingTickets=new Map;getExpo(){if(!this.expo)this.expo=new RY0;return this.expo}isValidToken(Z){return CY0(Z)}async sendNotification(Z,J){if(!this.isValidToken(Z))return S6.warn("[ExpoPushClient] Invalid Expo push token:",{token:Z.substring(0,20)+"..."}),null;let $={to:Z,title:J.title,body:J.body,data:J.data,sound:J.sound||"default",channelId:J.channelId||"default",priority:J.priority||"high",badge:J.badge};try{let Q=(await this.getExpo().sendPushNotificationsAsync([$]))[0];if(this.notificationsSent++,this.lastNotificationAt=new Date,Q.id){let W=Q;this.pendingTickets.set(W.id,{ticketId:W.id,token:Z,createdAt:new Date})}if(Q&&Q.status==="error"){let W=Q;await this.handleTicketError(W,Z)}return S6.debug("[ExpoPushClient] Sent notification:",{token:Z.substring(0,20)+"...",status:Q?.status}),Q??null}catch(X){return S6.error("[ExpoPushClient] Error sending notification:",X),null}}async sendBatchNotifications(Z,J){let $=[];for(let K of Z)if(!this.isValidToken(K))S6.warn("[ExpoPushClient] Skipping invalid token:",{token:K.substring(0,20)+"..."});else $.push(K);if($.length===0)return S6.warn("[ExpoPushClient] No valid tokens to send to"),[];let X=$.map((K)=>({to:K,title:J.title,body:J.body,data:J.data,sound:J.sound||"default",channelId:J.channelId||"default",priority:J.priority||"high",badge:J.badge})),Y=this.getExpo(),Q=Y.chunkPushNotifications(X),W=[];for(let K of Q)try{let z=await Y.sendPushNotificationsAsync(K);W.push(...z);for(let G=0;G<z.length;G++){let H=z[G],V=W.length-z.length+G,F=$[V];if(!H||!F)continue;if(H.id){let B=H;this.pendingTickets.set(B.id,{ticketId:B.id,token:F,createdAt:new Date})}if(H.status==="error")await this.handleTicketError(H,F)}this.notificationsSent+=z.length,this.lastNotificationAt=new Date}catch(z){S6.error("[ExpoPushClient] Error sending batch chunk:",z)}return S6.debug("[ExpoPushClient] Sent batch notifications:",{total:$.length,successful:W.filter((K)=>K.status==="ok").length,failed:W.filter((K)=>K.status==="error").length}),W}async handleTicketError(Z,J){if(S6.warn("[ExpoPushClient] Ticket error:",{message:Z.message,details:Z.details}),Z.details?.error==="DeviceNotRegistered"){S6.debug("[ExpoPushClient] Removing invalid token:",{token:J.substring(0,20)+"..."});let X=(await v8.getAllTokens()).find((Y)=>Y.expoPushToken===J);if(X)await v8.unregisterToken(X.deviceId)}}async checkReceipts(){let Z=new Date;Z.setMinutes(Z.getMinutes()-15);let J=[];for(let[Q,W]of this.pendingTickets.entries())if(W.createdAt<Z)J.push(Q);if(J.length===0)return;S6.debug("[ExpoPushClient] Checking receipts:",{count:J.length});let $=this.getExpo(),X=$.chunkPushNotificationReceiptIds(J);for(let Q of X)try{let W=await $.getPushNotificationReceiptsAsync(Q);for(let[K,z]of Object.entries(W)){let G=this.pendingTickets.get(K),H=z;if(H.status==="ok")S6.debug("[ExpoPushClient] Receipt OK:",{ticketId:K});else if(H.status==="error"){let V=z;if(S6.warn("[ExpoPushClient] Receipt error:",{ticketId:K,message:V.message,details:V.details}),V.details?.error==="DeviceNotRegistered"&&G){let B=(await v8.getAllTokens()).find((U)=>U.expoPushToken===G.token);if(B)S6.debug("[ExpoPushClient] Removing invalid token from receipt:",{deviceId:B.deviceId}),await v8.unregisterToken(B.deviceId)}}this.pendingTickets.delete(K)}}catch(W){S6.error("[ExpoPushClient] Error checking receipts:",W)}let Y=new Date;Y.setHours(Y.getHours()-24);for(let[Q,W]of this.pendingTickets.entries())if(W.createdAt<Y)this.pendingTickets.delete(Q)}getStats(){return{notificationsSent:this.notificationsSent,lastNotificationAt:this.lastNotificationAt,pendingReceipts:this.pendingTickets.size}}}var $K=new Lz1;var l0=S(),Dz1=200,qY0=900000;class TF extends Q0{name="Notification Service";get logPrefix(){return"[Notification]"}claudeAgentService=null;openCodeAgentService=null;codexAgentService=null;piAgentService=null;receiptCheckInterval;setClaudeAgentService(Z){this.claudeAgentService=Z}setOpenCodeAgentService(Z){this.openCodeAgentService=Z}setCodexAgentService(Z){this.codexAgentService=Z}setPiAgentService(Z){this.piAgentService=Z}async onStart(){this.receiptCheckInterval=setInterval(()=>{$K.checkReceipts().catch((Z)=>{l0.error("[Notification] Error checking receipts:",Z)})},qY0),l0.info("[Notification] Ready to send notifications")}async onStop(){if(this.receiptCheckInterval)clearInterval(this.receiptCheckInterval),this.receiptCheckInterval=void 0}registerMQTTHandlers(){this.registerHandler("notifications/register/request",this.handleRegisterToken.bind(this)),this.registerHandler("notifications/preferences/get/request",this.handleGetPreferences.bind(this)),this.registerHandler("notifications/preferences/update/request",this.handleUpdatePreferences.bind(this)),this.registerHandler("claude/+/output/+",this.handleClaudeOutput.bind(this)),this.registerHandler("claude/+/permission/request/+",this.handlePermissionRequest.bind(this)),this.registerHandler("opencode/+/output/+",this.handleClaudeOutput.bind(this)),this.registerHandler("opencode/+/permission/request/+",this.handlePermissionRequest.bind(this)),this.registerHandler("codex/+/output/+",this.handleClaudeOutput.bind(this)),this.registerHandler("codex/+/permission/request/+",this.handlePermissionRequest.bind(this)),this.registerHandler("pi/+/output/+",this.handleClaudeOutput.bind(this)),this.registerHandler("pi/+/permission/request/+",this.handlePermissionRequest.bind(this)),l0.debug("[Notification] MQTT handlers registered")}async handleRegisterToken(Z,J){try{let $=await this.parseMessage(J);if(!$)return;let{data:X,profileId:Y}=$;l0.debug("[Notification] Register token request:",{deviceId:X.deviceId,platform:X.platform,hasExpoPushToken:!!X.expoPushToken,hasFcmToken:!!X.fcmToken}),await v8.registerToken(X.deviceId,X.fcmToken,X.expoPushToken,X.platform,X.deviceInfo);let Q=this.buildResponseTopic("notifications/register",X.clientId||Y,X.requestId),W={requestId:X.requestId,success:!0};await this.publishResponse(Q,W,Y),l0.debug("[Notification] Token registered successfully:",{deviceId:X.deviceId})}catch($){l0.error("[Notification] Error registering token:",$);try{let X=await this.parseMessage(J);if(X?.data?.requestId){let Y=this.buildResponseTopic("notifications/register",X.data.clientId||X.profileId,X.data.requestId),Q={requestId:X.data.requestId,success:!1,error:$ instanceof Error?$.message:"Unknown error"};await this.publishResponse(Y,Q,X.profileId)}}catch{}}}async handleGetPreferences(Z,J){try{let $=await this.parseMessage(J);if(!$)return;let{data:X,profileId:Y}=$;l0.debug("[Notification] Get preferences request:",{deviceId:X.deviceId});let Q=await v8.getPreferences(X.deviceId),W=this.buildResponseTopic("notifications/preferences/get",X.clientId||Y,X.requestId),K={requestId:X.requestId,success:!0,preferences:Q};await this.publishResponse(W,K,Y),l0.debug("[Notification] Sent preferences:",{deviceId:X.deviceId})}catch($){l0.error("[Notification] Error getting preferences:",$);try{let X=await this.parseMessage(J);if(X?.data?.requestId){let Y=this.buildResponseTopic("notifications/preferences/get",X.data.clientId||X.profileId,X.data.requestId),Q={requestId:X.data.requestId,success:!1,error:$ instanceof Error?$.message:"Unknown error"};await this.publishResponse(Y,Q,X.profileId)}}catch{}}}async handleUpdatePreferences(Z,J){try{let $=await this.parseMessage(J);if(!$)return;let{data:X,profileId:Y}=$;l0.debug("[Notification] Update preferences request:",{deviceId:X.deviceId,preferences:X.preferences});let Q=await v8.updatePreferences(X.deviceId,X.preferences),W=this.buildResponseTopic("notifications/preferences/update",X.clientId||Y,X.requestId),K={requestId:X.requestId,success:!0,preferences:Q};await this.publishResponse(W,K,Y),l0.debug("[Notification] Preferences updated:",{deviceId:X.deviceId})}catch($){l0.error("[Notification] Error updating preferences:",$);try{let X=await this.parseMessage(J);if(X?.data?.requestId){let Y=this.buildResponseTopic("notifications/preferences/update",X.data.clientId||X.profileId,X.data.requestId),Q={requestId:X.data.requestId,success:!1,error:$ instanceof Error?$.message:"Unknown error"};await this.publishResponse(Y,Q,X.profileId)}}catch{}}}async handleClaudeOutput(Z,J){try{let $=Z.split("/")[3],X=await this.parseMessage(J);if(!X)return;let Y=X.data;if(Y.type!=="assistant")return;let Q=this.getSessionInfo($??"");if(!Q){l0.debug("[Notification] Session not found for notification:",{sessionId:$});return}let W=this.buildNotificationTitle(Q),K=this.extractMessageBody(Y);if(!K)return;let z={type:"message",projectId:Q.projectPath,sessionId:$??""};await this.sendToDevicesWithPreference("allMessages",{title:W,body:K,data:z,priority:"high",channelId:"messages"}),l0.debug("[Notification] Sent message notification:",{sessionId:$,title:W})}catch($){l0.error("[Notification] Error handling Claude output:",$)}}async handlePermissionRequest(Z,J){try{let $=Z.split("/")[4],X=await this.parseMessage(J);if(!X)return;let Y=X.data,Q=this.getSessionInfo($??"");if(!Q){l0.debug("[Notification] Session not found for permission notification:",{sessionId:$});return}let W=this.buildNotificationTitle(Q),K=this.buildPermissionBody(Y),z={type:"permission",projectId:Q.projectPath,sessionId:$??"",requestId:Y.request_id,action:Y.action};await this.sendToDevicesWithPreference("needsAttention",{title:W,body:K,data:z,priority:"high",channelId:"default"}),l0.debug("[Notification] Sent permission notification:",{sessionId:$,action:Y.action})}catch($){l0.error("[Notification] Error handling permission request:",$)}}getSessionInfo(Z){if(this.claudeAgentService){let $=this.claudeAgentService.getActiveSessions().find((X)=>X.sessionId===Z);if($)return{sessionId:$.sessionId,projectPath:$.projectPath,worktreeBranch:$.worktreeBranch}}if(this.openCodeAgentService){let $=this.openCodeAgentService.getActiveSessions().find((X)=>X.sessionId===Z);if($)return{sessionId:$.sessionId,projectPath:$.projectPath,worktreeBranch:$.worktreeBranch}}if(this.codexAgentService){let $=this.codexAgentService.getActiveSessions().find((X)=>X.threadId===Z||X.tempId===Z);if($)return{sessionId:$.threadId||$.tempId,projectPath:$.directoryPath,worktreeBranch:$.worktreeBranch}}if(this.piAgentService){let $=this.piAgentService.getActiveSessions().find((X)=>X.sessionId===Z||X.tempId===Z);if($)return{sessionId:$.sessionId||$.tempId,projectPath:$.directoryPath,worktreeBranch:$.worktreeBranch}}return null}buildNotificationTitle(Z){let J=Oz1.basename(Z.projectPath);if(Z.worktreeBranch){let $=Z.worktreeBranch.replace("session/","");return`${J} (${$})`}return J}extractMessageBody(Z){let J="",$=Z.message;if($?.content&&Array.isArray($.content))J=$.content.filter((Y)=>Y.type==="text").map((Y)=>Y.text).filter(Boolean).join(`
|
|
2411
2411
|
`);else if(Z.content){if(typeof Z.content==="string")J=Z.content;else if(Array.isArray(Z.content))J=Z.content.filter((Y)=>Y.type==="text").map((Y)=>Y.text).filter(Boolean).join(`
|
|
2412
2412
|
`)}if(!J.trim())return null;if(J.length>Dz1)J=J.substring(0,Dz1)+"...";return J}buildPermissionBody(Z){let J=Z.action||"Unknown tool",$=Z.params||{},X="";switch(J.toLowerCase()){case"bash":case"execute_command":X=$.command||"";break;case"read":case"read_file":X=$.file_path||"";break;case"write":case"write_file":X=$.file_path||"";break;case"edit":X=$.file_path||"";break;case"webfetch":X=$.url||"";break;case"websearch":X=$.query||"";break;default:X=$.file_path||$.command||$.path||""}if(X.length>100)X=X.substring(0,100)+"...";if(X)return`Permission requested: ${J}: ${X}`;return`Permission requested: ${J}`}async sendToDevicesWithPreference(Z,J){try{let $=await v8.getAllTokens();if($.length===0){l0.debug("[Notification] No registered devices");return}let X=[];for(let Y of $){if(!Y.expoPushToken)continue;if((await v8.getPreferences(Y.deviceId))[Z])X.push(Y.expoPushToken)}if(X.length===0){l0.debug("[Notification] No devices with preference enabled:",{preferenceType:Z});return}await $K.sendBatchNotifications(X,J),l0.debug("[Notification] Sent to devices:",{count:X.length,preferenceType:Z})}catch($){l0.error("[Notification] Error sending to devices:",$)}}getStatus(){let Z=$K.getStats();return{name:this.name,running:this.running,startedAt:this.startedAt,requestsHandled:this.requestsHandled,registeredDevices:0,notificationsSent:Z.notificationsSent,lastNotificationAt:Z.lastNotificationAt}}}import*as PZ from"fs/promises";import*as p0 from"path";import*as MF from"os";var{YAML:SY0}=globalThis.Bun;import*as wY from"fs/promises";import*as AY from"path";import*as _z1 from"os";var EY0=S();function PY0(){return AY.join(_z1.homedir(),".config","opencode")}function K9(){return AY.join(PY0(),"opencode.json")}function TY(Z){return AY.join(Z,"opencode.json")}function IY0(Z){let J=Z.replace(/\/\*[\s\S]*?\*\//g,"");return J=J.replace(/(^|[^:])\/\/.*$/gm,"$1"),J}async function K4(Z){try{let J=await wY.readFile(Z,"utf-8"),$=IY0(J);return JSON.parse($)}catch(J){if(J.code==="ENOENT")return{};return EY0.warn("[OpenCodeConfig] Failed to read config",{configPath:Z,error:J instanceof Error?J.message:"Unknown error"}),{}}}async function h8(Z,J){let $=AY.dirname(Z);await wY.mkdir($,{recursive:!0});let Y={...await K4(Z),...J};await wY.writeFile(Z,JSON.stringify(Y,null,2),"utf-8")}var EZ=S();class jF extends Q0{name="Slash Commands Service";get logPrefix(){return"[SlashCommands]"}getStatus(){return{...super.getStatus()}}registerMQTTHandlers(){this.registerHandler("commands/list/request",(Z,J)=>{this.handleListCommandsRequest(J)}),this.registerHandler("commands/read/request",(Z,J)=>{this.handleReadCommandRequest(J)}),this.registerHandler("commands/write/request",(Z,J)=>{this.handleWriteCommandRequest(J)}),this.registerHandler("commands/delete/request",(Z,J)=>{this.handleDeleteCommandRequest(J)}),EZ.debug("[SlashCommands] MQTT handlers registered")}getCommandsDir(Z,J,$){if($==="opencode"){if(Z==="global")return p0.join(MF.homedir(),".config","opencode","commands");if(!J)throw Error("Project path is required for project-scoped commands");return p0.join(J,".opencode","commands")}if($==="codex")throw Error("Codex does not support custom commands (deprecated in favor of skills)");if($==="pi"){if(Z==="global")return p0.join(MF.homedir(),".pi","agent","prompts");if(!J)throw Error("Project path is required for project-scoped commands");return p0.join(J,".pi","prompts")}if(Z==="global")return p0.join(MF.homedir(),".claude","commands");if(!J)throw Error("Project path is required for project-scoped commands");return p0.join(J,".claude","commands")}getOpenCodeConfigPath(Z,J){if(Z==="global")return K9();if(!J)throw Error("Project path is required for project-scoped commands");return TY(J)}async listOpenCodeConfigCommands(Z,J){let $=this.getOpenCodeConfigPath(Z,J),Y=(await K4($)).command||{};return Object.entries(Y).map(([Q,W])=>({name:Q,filename:`${Q}.config`,description:typeof W?.description==="string"?W.description:void 0,argumentHint:typeof W?.arguments==="string"?W.arguments:void 0,scope:Z,provider:"opencode",source:"config",modified:void 0}))}async readOpenCodeConfigCommand(Z,J,$){let X=this.getOpenCodeConfigPath(Z,$),W=((await K4(X)).command||{})[J];if(!W)return null;let K={};if(W.description)K.description=String(W.description);if(W.model)K.model=String(W.model);if(W.agent)K.agent=String(W.agent);if(W.arguments)K["argument-hint"]=String(W.arguments);let z=String(W.prompt||""),G=z;return{name:J,filename:`${J}.config`,description:K.description,argumentHint:K["argument-hint"],scope:Z,content:z,frontmatter:Object.keys(K).length>0?K:void 0,rawContent:G,provider:"opencode",source:"config",modified:void 0}}async writeOpenCodeConfigCommand(Z,J,$,X,Y){let Q=this.getOpenCodeConfigPath(Z,Y),W=await K4(Q),K=W.command||{};K[J]={...X?.description?{description:X.description}:{},...X?.model?{model:X.model}:{},...X?.agent?{agent:X.agent}:{},...X?.["argument-hint"]?{arguments:X["argument-hint"]}:{},prompt:$},await h8(Q,{...W,command:K})}async deleteOpenCodeConfigCommand(Z,J,$){let X=this.getOpenCodeConfigPath(Z,$),Y=await K4(X),Q=Y.command||{};if(!Q[J])return!1;return delete Q[J],await h8(X,{...Y,command:Q}),!0}parseHooksManually(Z){let J={},$=(W,K)=>{let z=new RegExp(`${K}:\\s*\\n`,"m"),G=W.match(z);if(!G||G.index===void 0)return null;let H=G.index+G[0].length,V=W.slice(H),B=V.match(/^ [A-Z]/m)?.index??V.length;return V.slice(0,B)},X=$(Z,"PreToolUse");if(X){let W=this.parseHookItems(X);if(W.length>0)J.PreToolUse=W}let Y=$(Z,"PostToolUse");if(Y){let W=this.parseHookItems(Y);if(W.length>0)J.PostToolUse=W}let Q=$(Z,"Stop");if(Q){let W=[],K=Q.matchAll(/- command:\s*(.+)/g);for(let z of K){let G=(z[1]||"").trim();if(G.startsWith('"')&&G.endsWith('"')||G.startsWith("'")&&G.endsWith("'"))G=G.slice(1,-1);W.push({command:G})}if(W.length>0)J.Stop=W}return Object.keys(J).length>0?J:void 0}parseHookItems(Z){let J=[],$=Z.split(/(?=- matcher:)/);for(let X of $){if(!X.trim())continue;let Y=X.match(/- matcher:\s*(.+)/);if(!Y||!Y[1])continue;let Q=Y[1].trim(),W=[],K=X.matchAll(/- command:\s*(.+)/g);for(let z of K){let G=(z[1]||"").trim();if(G.startsWith('"')&&G.endsWith('"')||G.startsWith("'")&&G.endsWith("'"))G=G.slice(1,-1);W.push({command:G})}if(W.length>0)J.push({matcher:Q,hooks:W})}return J}parseFrontmatter(Z){let J=/^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/,$=Z.match(J);if(!$)return{body:Z};let X=$[1]||"",Y=$[2]||"";try{let Q;try{Q=SY0.parse(X)}catch(K){EZ.debug("[SlashCommands] YAML parse failed, attempting manual extraction",{yamlError:K});let z={},G=X.match(/^description:\s*["'](.+?)["']\s*$/m);if(G)z.description=G[1];let H=X.match(/^argument-hint:\s*(.+?)\s*$/m);if(H&&H[1]){let L=H[1].trim();if(L.startsWith('"')&&L.endsWith('"')||L.startsWith("'")&&L.endsWith("'"))L=L.slice(1,-1);z["argument-hint"]=L}let V=X.match(/^allowed-tools:\s*(.+?)\s*$/m);if(V&&V[1])z["allowed-tools"]=V[1].trim();let F=X.match(/^context:\s*(fork|inline)\s*$/m);if(F)z.context=F[1];let B=X.match(/^agent:\s*(.+?)\s*$/m);if(B&&B[1])z.agent=B[1].trim();let U=X.match(/^model:\s*(.+?)\s*$/m);if(U&&U[1])z.model=U[1].trim();if(X.includes("hooks:")){let L=X.match(/^hooks:\s*\n([\s\S]*?)(?=^[a-z]|$(?![\s\S]))/m);if(L&&L[1])z.hooks=this.parseHooksManually(L[1]);else{let O=X.indexOf(`hooks:
|