claude-mem 13.24.12 → 13.24.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,23 +1,23 @@
1
1
  #!/usr/bin/env bun
2
- "use strict";var Dl=Object.create;var zn=Object.defineProperty;var Ll=Object.getOwnPropertyDescriptor;var Nl=Object.getOwnPropertyNames;var Ul=Object.getPrototypeOf,$l=Object.prototype.hasOwnProperty;var bt=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(n){throw t=[n],n}};var jl=(r,e)=>{for(var t in e)zn(r,t,{get:e[t],enumerable:!0})},Bl=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Nl(e))!$l.call(r,s)&&s!==t&&zn(r,s,{get:()=>e[s],enumerable:!(n=Ll(e,s))||n.enumerable});return r};var fe=(r,e,t)=>(t=r!=null?Dl(Ul(r)):{},Bl(e||!r||!r.__esModule?zn(t,"default",{value:r,enumerable:!0}):t,r));function Yn(r){return(Wl??process.stderr.write.bind(process.stderr))(r)}function Ie(r){Yn(r)}function Li(r,e={}){cr&&cr.length>0&&(Yn(cr.join("")),cr=[]),Yn(r.endsWith(`
2
+ "use strict";var Dl=Object.create;var Yn=Object.defineProperty;var Ll=Object.getOwnPropertyDescriptor;var Nl=Object.getOwnPropertyNames;var Ul=Object.getPrototypeOf,$l=Object.prototype.hasOwnProperty;var bt=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(n){throw t=[n],n}};var jl=(r,e)=>{for(var t in e)Yn(r,t,{get:e[t],enumerable:!0})},Bl=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Nl(e))!$l.call(r,s)&&s!==t&&Yn(r,s,{get:()=>e[s],enumerable:!(n=Ll(e,s))||n.enumerable});return r};var pe=(r,e,t)=>(t=r!=null?Dl(Ul(r)):{},Bl(e||!r||!r.__esModule?Yn(t,"default",{value:r,enumerable:!0}):t,r));function Jn(r){return(Wl??process.stderr.write.bind(process.stderr))(r)}function Re(r){Jn(r)}function Di(r,e={}){cr&&cr.length>0&&(Jn(cr.join("")),cr=[]),Jn(r.endsWith(`
3
3
  `)?r:`${r}
4
- `),e.skipExit||process.exit(2)}var Wl,cr,lr=bt(()=>{"use strict";Wl=null;cr=null});function Gl(r){return r.replace(/^\uFEFF/,"")}function Re(r){return JSON.parse(Gl(r))}function Kl(r){(0,T.existsSync)(r)||(0,T.mkdirSync)(r,{recursive:!0})}function Ze(r,e){let t=r;try{if((0,T.lstatSync)(r).isSymbolicLink())try{t=(0,T.realpathSync)(r)}catch(l){let u=l instanceof Error?l:new Error(String(l));Ie(`claude-mem: realpathSync failed for ${r}, resolving symlink manually: ${u.message}
5
- `);let d=(0,T.readlinkSync)(r);t=(0,se.resolve)((0,se.dirname)(r),d)}}catch(l){let u=l.code;if(u!=="ENOENT"&&u!=="ENOTDIR")throw l}Kl((0,se.dirname)(t));let n=(0,se.dirname)(t),s=(0,se.basename)(t),i=(0,se.join)(n,`.${s}.${process.pid}.${(0,Ni.randomBytes)(6).toString("hex")}.tmp`),o=Buffer.from(JSON.stringify(e,null,2)+`
6
- `,"utf-8"),a;try{a=(0,T.statSync)(t).mode&511}catch{}let c;try{c=a!==void 0?(0,T.openSync)(i,"w",a):(0,T.openSync)(i,"w");let l=0;for(;l<o.length;){let u=(0,T.writeSync)(c,o,l,o.length-l);if(u===0)throw new Error(`writeSync stalled at ${l}/${o.length} bytes`);l+=u}if((0,T.fsyncSync)(c),(0,T.closeSync)(c),c=void 0,(0,T.renameSync)(i,t),!Hl){let u;try{u=(0,T.openSync)(n,"r"),(0,T.fsyncSync)(u)}catch(d){let g=d instanceof Error?d:new Error(String(d));Ie(`claude-mem: directory fsync failed for ${n}: ${g.message}
7
- `)}finally{if(u!==void 0)try{(0,T.closeSync)(u)}catch{}}}}catch(l){if(c!==void 0)try{(0,T.closeSync)(c)}catch{}try{(0,T.unlinkSync)(i)}catch{}throw l}}var T,Ni,se,Hl,et=bt(()=>{"use strict";T=require("fs"),Ni=require("crypto"),se=require("path");lr();Hl=process.platform==="win32"});function je(r,e=process.platform,t=(0,Ui.homedir)()){return typeof r!="string"||r.length===0?r:r==="~"?t:r.startsWith("~/")||e==="win32"&&r.startsWith("~\\")?(0,$i.join)(t,r.slice(2)):r}var Ui,$i,ur=bt(()=>{"use strict";Ui=require("os"),$i=require("path")});function Vl(){return typeof __dirname<"u"?__dirname:(0,I.dirname)((0,ji.fileURLToPath)(Xl.url))}function Ce(){if(process.env.CLAUDE_MEM_DATA_DIR)return je(process.env.CLAUDE_MEM_DATA_DIR);let r=(0,I.join)((0,Jn.homedir)(),".claude-mem"),e=(0,I.join)(r,"settings.json");try{if((0,wt.existsSync)(e)){let t=Re((0,wt.readFileSync)(e,"utf-8")),n=t.env??t;if(n.CLAUDE_MEM_DATA_DIR)return je(n.CLAUDE_MEM_DATA_DIR)}}catch{}return r}var I,Jn,wt,ji,Xl,$h,M,ql,zl,dr,Yl,tt,Bi,jh,Xn,Jl,L,U=bt(()=>{"use strict";I=require("path"),Jn=require("os"),wt=require("fs"),ji=require("url");et();ur();ur();Xl={};$h=Vl();M=Ce(),ql=(0,I.join)((0,Jn.homedir)(),".claude"),zl=process.env.CLAUDE_CONFIG_DIR||ql,dr=(0,I.join)(zl,"plugins","marketplaces","thedotmack"),Yl=(0,I.join)(M,"logs"),tt=(0,I.join)(M,"settings.json"),Bi="claude-mem.db",jh=(0,I.join)(M,Bi),Xn=(0,I.join)(M,"observer-sessions"),Jl=(0,I.basename)(Xn),L={dataDir:()=>M,workerPid:()=>(0,I.join)(M,"worker.pid"),serverPid:()=>(0,I.join)(M,".server-beta.pid"),serverPort:()=>(0,I.join)(M,".server-beta.port"),serverRuntime:()=>(0,I.join)(M,".server-beta.runtime.json"),settings:()=>(0,I.join)(M,"settings.json"),database:()=>(0,I.join)(M,Bi),chroma:()=>(0,I.join)(M,"chroma"),combinedCerts:()=>(0,I.join)(M,"combined_certs.pem"),transcriptsConfig:()=>(0,I.join)(M,"transcript-watch.json"),transcriptsState:()=>(0,I.join)(M,"transcript-watch-state.json"),corpora:()=>(0,I.join)(M,"corpora"),supervisorRegistry:()=>(0,I.join)(M,"supervisor.json"),envFile:()=>(0,I.join)(M,".env"),logsDir:()=>Yl}});var ge,Hi,es,Zn,ts,f,A=bt(()=>{"use strict";ge=require("fs"),Hi=require("path");U();lr();et();es=(i=>(i[i.DEBUG=0]="DEBUG",i[i.INFO=1]="INFO",i[i.WARN=2]="WARN",i[i.ERROR=3]="ERROR",i[i.SILENT=4]="SILENT",i))(es||{}),Zn=null,ts=class{level=null;useColor;logFilePath=null;logFileInitialized=!1;constructor(){this.useColor=process.stdout.isTTY??!1}ensureLogFileInitialized(){if(!this.logFileInitialized){this.logFileInitialized=!0;try{let e=L.logsDir();(0,ge.existsSync)(e)||(0,ge.mkdirSync)(e,{recursive:!0});let t=new Date().toISOString().split("T")[0];this.logFilePath=(0,Hi.join)(e,`claude-mem-${t}.log`)}catch(e){console.error("[LOGGER] Failed to initialize log file:",e instanceof Error?e.message:String(e)),this.logFilePath=null}}}getLevel(){if(this.level===null)try{let e=L.settings();if((0,ge.existsSync)(e)){let t=(0,ge.readFileSync)(e,"utf-8"),s=(Re(t).CLAUDE_MEM_LOG_LEVEL||"INFO").toUpperCase();this.level=es[s]??1}else this.level=1}catch(e){console.error("[LOGGER] Failed to load log level from settings:",e instanceof Error?e.message:String(e)),this.level=1}return this.level}formatData(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="object"){if(e instanceof Error)return this.getLevel()===0?`${e.message}
8
- ${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let t=Object.keys(e);return t.length===0?"{}":t.length<=3?JSON.stringify(e):`{${t.length} keys: ${t.slice(0,3).join(", ")}...}`}return String(e)}formatTool(e,t){if(!t)return e;let n=t;if(typeof t=="string")try{n=JSON.parse(t)}catch{n=t}if(e==="Bash"&&n.command)return`${e}(${n.command})`;if(n.file_path)return`${e}(${n.file_path})`;if(n.notebook_path)return`${e}(${n.notebook_path})`;if(e==="Glob"&&n.pattern)return`${e}(${n.pattern})`;if(e==="Grep"&&n.pattern)return`${e}(${n.pattern})`;if(n.url)return`${e}(${n.url})`;if(n.query)return`${e}(${n.query})`;if(e==="Task"){if(n.subagent_type)return`${e}(${n.subagent_type})`;if(n.description)return`${e}(${n.description})`}return e==="Skill"&&n.skill?`${e}(${n.skill})`:e==="LSP"&&n.operation?`${e}(${n.operation})`:e}formatTimestamp(e){let t=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),s=String(e.getDate()).padStart(2,"0"),i=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0"),a=String(e.getSeconds()).padStart(2,"0"),c=String(e.getMilliseconds()).padStart(3,"0");return`${t}-${n}-${s} ${i}:${o}:${a}.${c}`}log(e,t,n,s,i){if(e<this.getLevel())return;this.ensureLogFileInitialized();let o=this.formatTimestamp(new Date),a=es[e].padEnd(5),c=t.padEnd(6),l="";s?.correlationId?l=`[${s.correlationId}] `:s?.sessionId&&(l=`[session-${s.sessionId}] `);let u="";if(i!=null)if(i instanceof Error)u=this.getLevel()===0?`
4
+ `),e.skipExit||process.exit(2)}var Wl,cr,lr=bt(()=>{"use strict";Wl=null;cr=null});function Gl(r){return r.replace(/^\uFEFF/,"")}function Ce(r){return JSON.parse(Gl(r))}function Kl(r){(0,T.existsSync)(r)||(0,T.mkdirSync)(r,{recursive:!0})}function Ze(r,e){let t=r;try{if((0,T.lstatSync)(r).isSymbolicLink())try{t=(0,T.realpathSync)(r)}catch(l){let u=l instanceof Error?l:new Error(String(l));Re(`claude-mem: realpathSync failed for ${r}, resolving symlink manually: ${u.message}
5
+ `);let d=(0,T.readlinkSync)(r);t=(0,se.resolve)((0,se.dirname)(r),d)}}catch(l){let u=l.code;if(u!=="ENOENT"&&u!=="ENOTDIR")throw l}Kl((0,se.dirname)(t));let n=(0,se.dirname)(t),s=(0,se.basename)(t),i=(0,se.join)(n,`.${s}.${process.pid}.${(0,Li.randomBytes)(6).toString("hex")}.tmp`),o=Buffer.from(JSON.stringify(e,null,2)+`
6
+ `,"utf-8"),a;try{a=(0,T.statSync)(t).mode&511}catch{}let c;try{c=a!==void 0?(0,T.openSync)(i,"w",a):(0,T.openSync)(i,"w");let l=0;for(;l<o.length;){let u=(0,T.writeSync)(c,o,l,o.length-l);if(u===0)throw new Error(`writeSync stalled at ${l}/${o.length} bytes`);l+=u}if((0,T.fsyncSync)(c),(0,T.closeSync)(c),c=void 0,(0,T.renameSync)(i,t),!Hl){let u;try{u=(0,T.openSync)(n,"r"),(0,T.fsyncSync)(u)}catch(d){let g=d instanceof Error?d:new Error(String(d));Re(`claude-mem: directory fsync failed for ${n}: ${g.message}
7
+ `)}finally{if(u!==void 0)try{(0,T.closeSync)(u)}catch{}}}}catch(l){if(c!==void 0)try{(0,T.closeSync)(c)}catch{}try{(0,T.unlinkSync)(i)}catch{}throw l}}var T,Li,se,Hl,et=bt(()=>{"use strict";T=require("fs"),Li=require("crypto"),se=require("path");lr();Hl=process.platform==="win32"});function ie(r,e=process.platform,t=(0,Ni.homedir)()){return typeof r!="string"||r.length===0?r:r==="~"?t:r.startsWith("~/")||e==="win32"&&r.startsWith("~\\")?(0,Ui.join)(t,r.slice(2)):r}var Ni,Ui,wt=bt(()=>{"use strict";Ni=require("os"),Ui=require("path")});function Vl(){return typeof __dirname<"u"?__dirname:(0,I.dirname)((0,$i.fileURLToPath)(Xl.url))}function Me(){if(process.env.CLAUDE_MEM_DATA_DIR)return ie(process.env.CLAUDE_MEM_DATA_DIR);let r=(0,I.join)((0,ur.homedir)(),".claude-mem"),e=(0,I.join)(r,"settings.json");try{if((0,vt.existsSync)(e)){let t=Ce((0,vt.readFileSync)(e,"utf-8")),n=t.env??t;if(n.CLAUDE_MEM_DATA_DIR)return ie(n.CLAUDE_MEM_DATA_DIR)}}catch{}return r}function Bi(r,e=(0,ur.homedir)(),t=process.platform){return ie(r,t,e)}var I,ur,vt,$i,Xl,$h,M,ql,zl,dr,Yl,tt,ji,jh,Xn,Jl,L,U=bt(()=>{"use strict";I=require("path"),ur=require("os"),vt=require("fs"),$i=require("url");et();wt();wt();Xl={};$h=Vl();M=Me(),ql=(0,I.join)((0,ur.homedir)(),".claude"),zl=process.env.CLAUDE_CONFIG_DIR||ql,dr=(0,I.join)(zl,"plugins","marketplaces","thedotmack"),Yl=(0,I.join)(M,"logs"),tt=(0,I.join)(M,"settings.json"),ji="claude-mem.db",jh=(0,I.join)(M,ji),Xn=(0,I.join)(M,"observer-sessions"),Jl=(0,I.basename)(Xn);L={dataDir:()=>M,workerPid:()=>(0,I.join)(M,"worker.pid"),serverPid:()=>(0,I.join)(M,".server-beta.pid"),serverPort:()=>(0,I.join)(M,".server-beta.port"),serverRuntime:()=>(0,I.join)(M,".server-beta.runtime.json"),settings:()=>(0,I.join)(M,"settings.json"),database:()=>(0,I.join)(M,ji),chroma:()=>(0,I.join)(M,"chroma"),combinedCerts:()=>(0,I.join)(M,"combined_certs.pem"),transcriptsConfig:()=>(0,I.join)(M,"transcript-watch.json"),transcriptsState:()=>(0,I.join)(M,"transcript-watch-state.json"),corpora:()=>(0,I.join)(M,"corpora"),supervisorRegistry:()=>(0,I.join)(M,"supervisor.json"),envFile:()=>(0,I.join)(M,".env"),logsDir:()=>Yl}});var he,Gi,Zn,Qn,es,f,A=bt(()=>{"use strict";he=require("fs"),Gi=require("path");U();lr();et();Zn=(i=>(i[i.DEBUG=0]="DEBUG",i[i.INFO=1]="INFO",i[i.WARN=2]="WARN",i[i.ERROR=3]="ERROR",i[i.SILENT=4]="SILENT",i))(Zn||{}),Qn=null,es=class{level=null;useColor;logFilePath=null;logFileInitialized=!1;constructor(){this.useColor=process.stdout.isTTY??!1}ensureLogFileInitialized(){if(!this.logFileInitialized){this.logFileInitialized=!0;try{let e=L.logsDir();(0,he.existsSync)(e)||(0,he.mkdirSync)(e,{recursive:!0});let t=new Date().toISOString().split("T")[0];this.logFilePath=(0,Gi.join)(e,`claude-mem-${t}.log`)}catch(e){console.error("[LOGGER] Failed to initialize log file:",e instanceof Error?e.message:String(e)),this.logFilePath=null}}}getLevel(){if(this.level===null)try{let e=L.settings();if((0,he.existsSync)(e)){let t=(0,he.readFileSync)(e,"utf-8"),s=(Ce(t).CLAUDE_MEM_LOG_LEVEL||"INFO").toUpperCase();this.level=Zn[s]??1}else this.level=1}catch(e){console.error("[LOGGER] Failed to load log level from settings:",e instanceof Error?e.message:String(e)),this.level=1}return this.level}formatData(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="object"){if(e instanceof Error)return this.getLevel()===0?`${e.message}
8
+ ${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let t=Object.keys(e);return t.length===0?"{}":t.length<=3?JSON.stringify(e):`{${t.length} keys: ${t.slice(0,3).join(", ")}...}`}return String(e)}formatTool(e,t){if(!t)return e;let n=t;if(typeof t=="string")try{n=JSON.parse(t)}catch{n=t}if(e==="Bash"&&n.command)return`${e}(${n.command})`;if(n.file_path)return`${e}(${n.file_path})`;if(n.notebook_path)return`${e}(${n.notebook_path})`;if(e==="Glob"&&n.pattern)return`${e}(${n.pattern})`;if(e==="Grep"&&n.pattern)return`${e}(${n.pattern})`;if(n.url)return`${e}(${n.url})`;if(n.query)return`${e}(${n.query})`;if(e==="Task"){if(n.subagent_type)return`${e}(${n.subagent_type})`;if(n.description)return`${e}(${n.description})`}return e==="Skill"&&n.skill?`${e}(${n.skill})`:e==="LSP"&&n.operation?`${e}(${n.operation})`:e}formatTimestamp(e){let t=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),s=String(e.getDate()).padStart(2,"0"),i=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0"),a=String(e.getSeconds()).padStart(2,"0"),c=String(e.getMilliseconds()).padStart(3,"0");return`${t}-${n}-${s} ${i}:${o}:${a}.${c}`}log(e,t,n,s,i){if(e<this.getLevel())return;this.ensureLogFileInitialized();let o=this.formatTimestamp(new Date),a=Zn[e].padEnd(5),c=t.padEnd(6),l="";s?.correlationId?l=`[${s.correlationId}] `:s?.sessionId&&(l=`[session-${s.sessionId}] `);let u="";if(i!=null)if(i instanceof Error)u=this.getLevel()===0?`
9
9
  ${i.message}
10
10
  ${i.stack}`:` ${i.message}`;else if(this.getLevel()===0&&typeof i=="object")try{u=`
11
- `+JSON.stringify(i,null,2)}catch{u=" "+this.formatData(i)}else u=" "+this.formatData(i);let d="";if(s){let{sessionId:p,memorySessionId:h,correlationId:m,...E}=s;Object.keys(E).length>0&&(d=` {${Object.entries(E).map(([b,P])=>`${b}=${P}`).join(", ")}}`)}let g=`[${o}] [${a}] [${c}] ${l}${n}${d}${u}`;if(this.logFilePath)try{(0,ge.appendFileSync)(this.logFilePath,g+`
12
- `,"utf8")}catch(p){let h=p instanceof Error?p:new Error(String(p));Ie(`[LOGGER] Failed to write to log file: ${h.message}
11
+ `+JSON.stringify(i,null,2)}catch{u=" "+this.formatData(i)}else u=" "+this.formatData(i);let d="";if(s){let{sessionId:p,memorySessionId:h,correlationId:m,...E}=s;Object.keys(E).length>0&&(d=` {${Object.entries(E).map(([b,P])=>`${b}=${P}`).join(", ")}}`)}let g=`[${o}] [${a}] [${c}] ${l}${n}${d}${u}`;if(this.logFilePath)try{(0,he.appendFileSync)(this.logFilePath,g+`
12
+ `,"utf8")}catch(p){let h=p instanceof Error?p:new Error(String(p));Re(`[LOGGER] Failed to write to log file: ${h.message}
13
13
  ${h.stack??""}
14
- `)}else Ie(g+`
15
- `)}debug(e,t,n,s){this.log(0,e,t,n,s)}info(e,t,n,s){this.log(1,e,t,n,s)}warn(e,t,n,s){this.log(2,e,t,n,s)}setErrorSink(e){Zn=e}error(e,t,n,s){this.log(3,e,t,n,s),this.routeErrorToSink(t,n,s)}routeErrorToSink(e,t,n){try{if(!Zn||!(n instanceof Error))return;Zn(n)}catch{}}dataIn(e,t,n,s){this.info(e,`\u2192 ${t}`,n,s)}dataOut(e,t,n,s){this.info(e,`\u2190 ${t}`,n,s)}success(e,t,n,s){this.info(e,`\u2713 ${t}`,n,s)}failure(e,t,n,s){this.error(e,`\u2717 ${t}`,n,s)}},f=new ts});var pe=require("fs"),Qn=require("os"),vt=require("path");U();var rt=L.transcriptsConfig(),fr=L.transcriptsState(),Ql={version:1,schemas:{},watches:[],stateFile:fr};function Zl(r){let e=typeof r.schema=="string"?r.schema:r.schema?.name;if(!(r.name==="codex"||e==="codex")||!r.path)return!1;let n=K(r.path).replace(/\\/g,"/"),s=(0,vt.join)((0,Qn.homedir)(),".codex","sessions").replace(/\\/g,"/");return n===`${s}/**/*.jsonl`}function Wi(r){let e=typeof r.schema=="string"?r.schema:r.schema?.name,t=r.name==="codex"&&(!e||e==="codex");return r.context?.mode==="agents"&&t&&Zl(r)}function K(r){return r&&(r.startsWith("~")?(0,vt.join)((0,Qn.homedir)(),r.slice(1)):r)}function At(r=rt){let e=K(r);if(!(0,pe.existsSync)(e))throw new Error(`Transcript watch config not found: ${e}`);let t=(0,pe.readFileSync)(e,"utf-8"),n=JSON.parse(t);if(!n.version||!n.watches)throw new Error(`Invalid transcript watch config: ${e}`);return n.stateFile||(n.stateFile=fr),n}function pr(r=rt){let e=K(r),t=(0,vt.dirname)(e);(0,pe.existsSync)(t)||(0,pe.mkdirSync)(t,{recursive:!0}),(0,pe.writeFileSync)(e,JSON.stringify(Ql,null,2))}var W=require("fs"),ne=require("path");A();var he=require("fs"),Gi=require("path");A();function Ki(r){try{if(!(0,he.existsSync)(r))return{offsets:{}};let e=(0,he.readFileSync)(r,"utf-8"),t=JSON.parse(e);return t.offsets?t:{offsets:{}}}catch(e){return f.warn("TRANSCRIPT","Failed to load watch state, starting fresh",{statePath:r,error:e instanceof Error?e.message:String(e)}),{offsets:{}}}}function Vi(r,e){try{let t=(0,Gi.dirname)(r);(0,he.existsSync)(t)||(0,he.mkdirSync)(t,{recursive:!0}),(0,he.writeFileSync)(r,JSON.stringify(e,null,2))}catch(t){f.warn("TRANSCRIPT","Failed to save watch state",{statePath:r,error:t instanceof Error?t.message:String(t)})}}var ar=fe(require("path"),1);var k=fe(require("path"),1),x=require("fs");var rs=require("node:child_process");function Tt(r,e,t){return(0,rs.spawn)(r,e??[],{windowsHide:!0,...t})}var eu=new Set([".cmd",".bat"]),tu=new Set([".exe",".com"]),Xh=new Set([...tu,...eu]);A();var V={HEALTH_CHECK:3e3,API_REQUEST:3e4,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5},Me={SUCCESS:0,BLOCKING_ERROR:2};function xe(r){return process.platform==="win32"?Math.round(r*V.WINDOWS_MULTIPLIER):r}var gr=require("fs"),ns=require("path"),Pt=require("os");et();var ru="security_alert",q=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-haiku-4-5-20251001",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:String(37700+(process.getuid?.()??77)%100),CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_API_TIMEOUT_MS:String(xe(V.API_REQUEST)),CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"subscription",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-flash-latest",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_MODEL:"xiaomi/mimo-v2-flash:free",CLAUDE_MEM_OPENROUTER_BASE_URL:"",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_DATA_DIR:(0,ns.join)((0,Pt.homedir)(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_CLAUDE_CONFIG_DIR:"",CLAUDE_MEM_MODE:"code",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_FULL_COUNT:"0",CLAUDE_MEM_CONTEXT_FULL_FIELD:"narrative",CLAUDE_MEM_CONTEXT_SESSION_COUNT:"10",CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false",CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",CLAUDE_MEM_WELCOME_HINT_ENABLED:"true",CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_FOLDER_USE_LOCAL_MD:"false",CLAUDE_MEM_TRANSCRIPTS_ENABLED:"true",CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH:(0,ns.join)((0,Pt.homedir)(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_OBSERVER_MAX_CONVERSATION_CHARS:"400000",CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_FOLDER_MD_SKELETON_DENYLIST:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"false",CLAUDE_MEM_SEMANTIC_INJECT_LIMIT:"5",CLAUDE_MEM_TIER_ROUTING_ENABLED:"true",CLAUDE_MEM_TIER_SIMPLE_MODEL:"haiku",CLAUDE_MEM_TIER_SUMMARY_MODEL:"",CLAUDE_MEM_TIER_FAST_MODEL:"haiku",CLAUDE_MEM_TIER_SMART_MODEL:"sonnet",CLAUDE_MEM_CHROMA_ENABLED:"true",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database",CLAUDE_MEM_CHROMA_PREWARM_TIMEOUT_MS:"120000",CLAUDE_MEM_CHROMA_MAX_PENDING_MUTATIONS:"5000",CLAUDE_MEM_CLOUD_SYNC_TOKEN:"",CLAUDE_MEM_CLOUD_SYNC_USER_ID:"",CLAUDE_MEM_CLOUD_SYNC_HUB_URL:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_ID:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_NAME:(0,Pt.hostname)(),CLAUDE_MEM_CLOUD_SYNC_WS:"true",CLAUDE_MEM_CLOUD_SYNC_CONTENT_BATCH_SIZE:"40",CLAUDE_MEM_CLOUD_SYNC_REQUEST_TIMEOUT_MS:"90000",CLAUDE_MEM_TV_TOKEN:"",CLAUDE_MEM_PRO_TRIAL_EMAIL:"",CLAUDE_MEM_PRO_TRIAL_AT:"",CLAUDE_MEM_PRO_TRIAL_STATE:"",CLAUDE_MEM_PRO_TRIAL_ENDS_AT:"",CLAUDE_MEM_PRO_PLAN:"",CLAUDE_MEM_PRO_FALLBACK_AT:"",CLAUDE_MEM_PRO_MEMORY_KEY:"",CLAUDE_MEM_PRO_MEMORY_BASE_URL:"",CLAUDE_MEM_PRO_MEMORY_MODEL:"",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert,sensitive",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:"",CLAUDE_MEM_GROK_BOT_AWARENESS_ENABLED:"true",CLAUDE_MEM_GROK_BOT_AWARENESS_AGENT_IDS:"521e962d-2ec3-4488-bfbc-54d5209ce118,95601360-61f7-4fd9-bb3a-2c976b2b85c0",CLAUDE_MEM_GROK_BOT_AWARENESS_TRIGGER_TYPES:"decision,bugfix,security_alert,sensitive",CLAUDE_MEM_GROK_BOT_AWARENESS_TRIGGER_CONCEPTS:"",CLAUDE_MEM_CCS_ALIGN_ENABLED:"true",CLAUDE_MEM_CCS_ALIGN_VIEWER_IDS:"ccs-align",CLAUDE_MEM_CCS_ALIGN_TRIGGER_TYPES:"decision,bugfix,security_alert,sensitive",CLAUDE_MEM_CCS_ALIGN_PATCH_SHADOWS:"false",CLAUDE_MEM_QUEUE_ENGINE:"sqlite",CLAUDE_MEM_REDIS_URL:"",CLAUDE_MEM_REDIS_HOST:"127.0.0.1",CLAUDE_MEM_REDIS_PORT:"6379",CLAUDE_MEM_REDIS_MODE:"external",CLAUDE_MEM_QUEUE_REDIS_PREFIX:`claude_mem_${process.env.CLAUDE_MEM_WORKER_PORT??String(37700+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_AUTH_MODE:"api-key",CLAUDE_MEM_RUNTIME:"worker",CLAUDE_MEM_SERVER_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_API_KEY:"",CLAUDE_MEM_SERVER_PROJECT_ID:"",CLAUDE_MEM_SERVER_BETA_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_BETA_API_KEY:"",CLAUDE_MEM_SERVER_BETA_PROJECT_ID:""};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){return process.env[e]??this.DEFAULTS[e]}static getInt(e){let t=this.get(e);return parseInt(t,10)}static applyEnvOverrides(e){let t={...e};for(let n of Object.keys(this.DEFAULTS))process.env[n]!==void 0&&(t[n]=process.env[n]);return t}static loadFromFile(e,t=!0){try{if(!(0,gr.existsSync)(e)){let l=this.getAllDefaults();try{Ze(e,l),console.warn("[SETTINGS] Created settings file with defaults:",e)}catch(u){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,u instanceof Error?u.message:String(u))}return t?this.applyEnvOverrides(l):l}let n=(0,gr.readFileSync)(e,"utf-8"),s=Re(n),i=s,o=s.env&&typeof s.env=="object"&&!Array.isArray(s.env),a=o&&Object.keys(s).some(l=>l!=="env");if(o&&(i=s.env,!a))try{Ze(e,i),console.warn("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(l){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,l instanceof Error?l.message:String(l))}if(i.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES===ru){i={...i,CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:this.DEFAULTS.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES};try{Ze(e,a?{...s,env:i}:i),console.warn("[SETTINGS] Migrated Telegram trigger types off the legacy default:",e)}catch(l){console.warn("[SETTINGS] Failed to migrate Telegram trigger types:",e,l instanceof Error?l.message:String(l))}}let c={...this.DEFAULTS};for(let l of Object.keys(this.DEFAULTS))i[l]!==void 0&&(c[l]=i[l]);return t?this.applyEnvOverrides(c):c}catch(n){console.warn("[SETTINGS] Failed to load settings, using defaults:",e,n instanceof Error?n.message:String(n));let s=this.getAllDefaults();return t?this.applyEnvOverrides(s):s}}};U();U();var hr=null;function me(){return hr!==null||(hr=q.loadFromFile(tt)),hr}var ye=require("fs");A();var Ee=require("fs"),ls=fe(require("path"),1);A();var nu=["CLAUDECODE_","CLAUDE_CODE_"],su=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),iu=new Set(["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy","npm_config_noproxy"]),ou=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_SKIP_BEDROCK_AUTH","CLAUDE_CODE_SKIP_VERTEX_AUTH","CLAUDE_CODE_SKIP_FOUNDRY_AUTH","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS",...iu]);function It(r=process.env){let e={};for(let[t,n]of Object.entries(r))if(n!==void 0){if(ou.has(t)){e[t]=n;continue}su.has(t)||nu.some(s=>t.startsWith(s))||(e[t]=n)}return e}U();var is=require("child_process"),zi=require("fs");A();var au=5e3,qi=new Map,ss=0;function cu(r){ss+=1;let e=(0,is.spawnSync)("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${r}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...It(process.env),LC_ALL:"C",LANG:"C"}});if(e.status===0){let t=e.stdout.trim();return t.length>0?t:null}return null}function lu(r,e=!1){if(!e){let n=qi.get(r);if(n&&Date.now()-n.capturedAtMs<au)return n.token}let t=null;try{t=cu(r)}catch(n){f.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:r,error:n instanceof Error?n.message:String(n)}),t=null}return qi.set(r,{token:t,capturedAtMs:Date.now()}),t}function Yi(r,e){if(!Number.isInteger(r)||r<=0)return null;if(process.platform==="linux"){ss+=1;try{let t=(0,zi.readFileSync)(`/proc/${r}/stat`,"utf-8"),n=t.lastIndexOf(") ");if(n<0)return null;let i=t.slice(n+2).split(" ")[19];return i&&/^\d+$/.test(i)?i:null}catch(t){return f.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:r,error:t instanceof Error?t.message:String(t)}),null}}if(process.platform==="win32")return lu(r,e);ss+=1;try{let t=(0,is.spawnSync)("ps",["-p",String(r),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...It(process.env),LC_ALL:"C",LANG:"C"}});if(t.status!==0)return null;let n=t.stdout.trim();return n.length>0?n:null}catch(t){return f.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:r,error:t instanceof Error?t.message:String(t)}),null}}function Fe(r){return Yi(r,!1)}function _e(r,e){if(e===null)return!0;let t=Yi(r,!0);return t===null?!0:t===e}var Ji=require("child_process"),Er=require("fs"),Xi=require("util");A();var os=(0,Xi.promisify)(Ji.execFile),uu=128,du=/not found|no running instance|no tasks/i,mr=class extends Error{pid;constructor(e,t,n){super(t,n),this.name="ProcessTreeKillError",this.pid=e}};async function ie(r,e={}){let t=e.signalMode==="immediate",n=e.expectedStartToken!==void 0?e.expectedStartToken:Fe(r),s=()=>_e(r,n);if(!s()){f.warn("PROCESS","Skipping tree-kill: root PID was reused since it was captured",{pid:r});return}if(f.debug("PROCESS",`Killing process tree rooted at PID ${r}`,{immediate:t}),process.platform==="win32"){try{await os("taskkill",["/PID",String(r),"/T","/F"],{timeout:5e3,windowsHide:!0})}catch(i){let o=i.code,a=String(i.stderr??""),c=i instanceof Error?i.message:String(i);if(o===uu||du.test(`${a} ${c}`)){f.debug("PROCESS","taskkill reported the process was already gone",{pid:r});return}throw new mr(r,`taskkill failed for PID ${r} (exit ${String(o)}): ${a.trim()||c}`,{cause:i})}return}try{let i=t?"SIGKILL":"SIGTERM",o=await _r(r);for(let l of o){if(!_e(l.pid,l.startToken)){f.debug("PROCESS",`Skipping ${i}: descendant PID was reused since enumeration`,{pid:l.pid,rootPid:r});continue}try{process.kill(l.pid,i)}catch{}}if(s())try{process.kill(r,i)}catch(l){let u=l instanceof Error?l:new Error(String(l)),d=u.code;d!=="ESRCH"&&f.debug("PROCESS",`Failed to ${i} PID ${r}`,{code:d},u)}else f.warn("PROCESS","Skipping root signal: PID was reused during descendant enumeration",{pid:r,signal:i});t||await new Promise(l=>setTimeout(l,500));let a=s()?await _r(r):[],c=new Map;for(let l of o)c.set(l.pid,l.startToken);for(let l of a)c.set(l.pid,l.startToken);for(let[l,u]of c){if(!_e(l,u)){f.debug("PROCESS","Skipping SIGKILL: descendant PID was reused since the scan",{pid:l,rootPid:r});continue}try{process.kill(l,"SIGKILL")}catch{}}if(!t&&s())try{process.kill(r,"SIGKILL")}catch{}}catch(i){throw new mr(r,`tree-kill failed for PID ${r}: ${i instanceof Error?i.message:String(i)}`,{cause:i})}}async function fu(){return process.platform==="win32"?hu():process.platform==="linux"?pu():gu()}function pu(){let r=[],e;try{e=(0,Er.readdirSync)("/proc")}catch(t){return f.warn("PROCESS","Cannot read /proc \u2014 tree-kill degrades to a single-PID kill",{error:t instanceof Error?t.message:String(t)}),r}for(let t of e){if(!/^\d+$/.test(t))continue;let n;try{n=(0,Er.readFileSync)(`/proc/${t}/stat`,"utf-8")}catch{continue}let s=n.lastIndexOf(") ");if(s<0)continue;let i=n.slice(s+2).split(" "),o=Number.parseInt(i[1]??"",10),a=i[19];Number.isFinite(o)&&r.push({pid:Number.parseInt(t,10),ppid:o,startToken:a&&/^\d+$/.test(a)?a:null})}return r}async function gu(){let r;try{r=(await os("ps",["-eo","pid=,ppid=,lstart="],{timeout:1e4,maxBuffer:33554432,env:{...process.env,LC_ALL:"C",LANG:"C"}})).stdout}catch(t){return f.warn("PROCESS","Cannot enumerate the process table \u2014 tree-kill degrades to a single-PID kill",{error:t instanceof Error?t.message:String(t)}),[]}let e=[];for(let t of r.split(`
16
- `)){let n=t.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);if(!n)continue;let s=n[3].trim();e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),startToken:s.length>0?s:null})}return e}async function hu(){let r;try{r=(await os("powershell.exe",["-NoProfile","-NonInteractive","-Command","Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,@{Name='StartToken';Expression={$_.CreationDate.ToString('yyyyMMddHHmmss.ffffff')}} | ConvertTo-Csv -NoTypeInformation"],{timeout:3e4,windowsHide:!0,maxBuffer:33554432})).stdout}catch(t){return f.warn("PROCESS","Cannot enumerate the Windows process table \u2014 tree-kill degrades to a single-PID kill",{error:t instanceof Error?t.message:String(t)}),[]}let e=[];for(let t of r.split(/\r?\n/).slice(1)){let n=t.match(/^"(\d+)","(\d+)","(.*)"$/);if(!n)continue;let s=n[3].trim();e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),startToken:s.length>0?s:null})}return e}async function _r(r){let e=await fu(),t=new Map;for(let o of e){let a=t.get(o.ppid);a?a.push(o):t.set(o.ppid,[o])}let n=new Set([r]),s=[],i=o=>{for(let a of t.get(o)??[])n.has(a.pid)||(n.add(a.pid),i(a.pid),s.push({pid:a.pid,startToken:a.startToken}))};return i(r),s}var mu=5e3,_u=1e3,Eu=L.supervisorRegistry();function H(r){if(!Number.isInteger(r)||r<0||r===0)return!1;try{return process.kill(r,0),!0}catch(e){if(e instanceof Error){let t=e.code;return t==="EPERM"?!0:(f.debug("SYSTEM","PID check failed",{pid:r,code:t}),!1)}return f.warn("SYSTEM","PID check threw non-Error",{pid:r,error:String(e)}),!1}}async function yr(r,e){let t=Date.now()+e;for(;Date.now()<t;){if(r.every(n=>!H(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}function Sr(r){if(!r||!H(r.pid))return!1;if(!r.startToken)return!0;let e=Fe(r.pid);if(e===null)return!0;let t=e===r.startToken;return t||f.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:r.pid,stored:r.startToken,current:e}),t}var us=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=Eu){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,Ee.mkdirSync)(ls.default.dirname(this.registryPath),{recursive:!0}),!(0,Ee.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,Ee.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[s,i]of Object.entries(n))this.entries.set(s,i)}catch(t){t instanceof Error?f.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},t):f.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(t)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&f.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}register(e,t,n){this.initialize(),this.entries.set(e,t),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e){this.initialize();let t=this.entries.get(e);this.entries.delete(e),this.runtimeProcesses.delete(e),this.persist(),t?.type==="sdk"&&cs()}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,t])=>({id:e,...t})).sort((e,t)=>{let n=Date.parse(e.startedAt),s=Date.parse(t.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(s)?0:s)})}getBySession(e){let t=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===t)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}pruneDeadEntries(){this.initialize();let e=0,t=0;for(let[n,s]of this.entries)H(s.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),e+=1,s.type==="sdk"&&(t+=1));e>0&&this.persist();for(let n=0;n<t;n+=1)cs();return e}async reapSession(e){this.initialize();let t=this.getBySession(e);if(t.length===0)return 0;let n=typeof e=="number"?e:Number(e)||void 0;f.info("SYSTEM",`Reaping ${t.length} process(es) for session ${e}`,{sessionId:n,pids:t.map(a=>a.pid)});let s=t.filter(a=>H(a.pid)),i=new Map(s.map(a=>[a.pid,Fe(a.pid)]));for(let a of s)try{process.platform==="win32"?await ie(a.pid,{expectedStartToken:i.get(a.pid)??null}):typeof a.pgid=="number"?process.kill(-a.pgid,"SIGTERM"):process.kill(a.pid,"SIGTERM")}catch(c){c instanceof Error?c.code!=="ESRCH"&&f.debug("SYSTEM",`Failed to SIGTERM session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},c):f.warn("SYSTEM",`Failed to SIGTERM session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(c)})}await yr(s,mu);let o=s.filter(a=>H(a.pid));for(let a of o){f.warn("SYSTEM",`Session process PID ${a.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:a.pid,pgid:a.pgid,sessionId:n});let c=i.get(a.pid)??null;if(!_e(a.pid,c)){f.warn("SYSTEM","Skipping SIGKILL: session process PID was reused during the grace window",{pid:a.pid,sessionId:n});continue}try{process.platform==="win32"?await ie(a.pid,{expectedStartToken:c}):typeof a.pgid=="number"?process.kill(-a.pgid,"SIGKILL"):process.kill(a.pid,"SIGKILL")}catch(l){l instanceof Error?l.code!=="ESRCH"&&f.debug("SYSTEM",`Failed to SIGKILL session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},l):f.warn("SYSTEM",`Failed to SIGKILL session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(l)})}}if(o.length>0){let a=Date.now()+_u;for(;Date.now()<a&&o.filter(l=>H(l.pid)).length!==0;)await new Promise(l=>setTimeout(l,100))}for(let a of t)this.entries.delete(a.id),this.runtimeProcesses.delete(a.id);this.persist();for(let a of t)a.type==="sdk"&&cs();return f.info("SYSTEM",`Reaped ${t.length} process(es) for session ${e}`,{sessionId:n,reaped:t.length}),t.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};(0,Ee.mkdirSync)(ls.default.dirname(this.registryPath),{recursive:!0}),(0,Ee.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},as=null;function br(){return as||(as=new us),as}var ym=180*1e3,yu=[];function cs(){let r=yu.shift();r&&r.notify()}var nt=require("fs");A();U();var Su=L.workerPid();async function Zi(r){let e=r.currentPid??process.pid,t=r.pidFilePath??Su,n=r.registry.getAll(),s=[...n].filter(c=>c.pid!==e).sort((c,l)=>Date.parse(l.startedAt)-Date.parse(c.startedAt)),i=new Map,o=new Map;for(let c of s){if(!H(c.pid)){r.registry.unregister(c.id);continue}o.set(c.id,Fe(c.pid)),i.set(c.id,await _r(c.pid));try{await Qi(c,"SIGTERM")}catch(l){l instanceof Error?f.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:c.pid,pgid:c.pgid,type:c.type},l):f.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(l)})}}await yr(s,5e3);let a=s.filter(c=>H(c.pid)||(i.get(c.id)??[]).some(l=>H(l.pid)));for(let c of a){let l=_e(c.pid,o.get(c.id)??null);l||f.warn("SYSTEM","Skipping tree-kill: root PID was reused during the grace window",{pid:c.pid,type:c.type});try{l&&await Qi(c,"SIGKILL")}catch(u){u instanceof Error?f.debug("SYSTEM","Failed to force kill child process",{pid:c.pid,pgid:c.pgid,type:c.type},u):f.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(u)})}finally{bu(i.get(c.id)??[],c.pid)}}await yr(a,1e3);for(let c of s)r.registry.unregister(c.id);for(let c of n.filter(l=>l.pid===e))r.registry.unregister(c.id);eo(t,e),r.registry.pruneDeadEntries()}function eo(r,e,t=!1){if(!(0,nt.existsSync)(r))return;let n=null;try{let o=JSON.parse((0,nt.readFileSync)(r,"utf-8"));n=typeof o.pid=="number"?o.pid:null}catch(o){f.debug("SYSTEM","PID file unreadable \u2014 leaving it (cannot prove ownership)",{pidFilePath:r,error:o instanceof Error?o.message:String(o)});return}let s=e!==null&&n===e,i=n===null||!H(n);if(!s&&!(t&&i)){f.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:r,recordedPid:n,currentPid:e});return}try{(0,nt.rmSync)(r,{force:!0})}catch(o){o instanceof Error?f.debug("SYSTEM","Failed to remove PID file",{pidFilePath:r},o):f.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:r,error:String(o)})}}function bu(r,e){for(let{pid:t,startToken:n}of r)if(!(t===e||!H(t))){if(!_e(t,n)){f.debug("SYSTEM","Skipping reap: PID was recycled during the grace window",{pid:t,rootPid:e});continue}try{process.kill(t,"SIGKILL"),f.debug("SYSTEM","Reaped orphaned descendant during shutdown cascade",{pid:t,rootPid:e})}catch(s){let i=s instanceof Error?s.code:void 0;i!=="ESRCH"&&f.warn("SYSTEM","Failed to reap orphaned descendant during shutdown cascade",{pid:t,rootPid:e,errno:i})}}}async function Qi(r,e){let{pid:t,pgid:n}=r;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(s){if((s instanceof Error?s.code:void 0)!=="ESRCH")throw s}if(e==="SIGKILL"){await ie(t,{signalMode:"immediate"});return}try{process.kill(t,e)}catch(s){if((s instanceof Error?s.code:void 0)!=="ESRCH")throw s}return}await ie(t)}A();var to=3e4,st=null;function wu(){let e=br().pruneDeadEntries();e>0&&f.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function ro(){st===null&&(st=setInterval(wu,to),st.unref(),f.debug("SYSTEM","Health checker started",{intervalMs:to}))}function no(){st!==null&&(clearInterval(st),st=null,f.debug("SYSTEM","Health checker stopped"))}var so=require("child_process"),io=require("util");A();var vu=(0,io.promisify)(so.execFile),Au=/(?:^|\/)(?:uvx|uv|python[\d.]*)(?:\s|$).*chroma-mcp/;function Tu(r){let e=[];for(let t of r.split(`
17
- `)){let n=t.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);n&&e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),command:n[3].trim()})}return e}async function Pu(){let r=await vu("ps",["-eo","pid=,ppid=,command="],{timeout:1e4,maxBuffer:33554432});return Tu(r.stdout)}function Iu(r,e){let t=r.filter(o=>Au.test(o.command)&&o.pid!==e.selfPid),n=new Set(t.map(o=>o.pid)),s=t.filter(o=>!n.has(o.ppid)),i=s.filter(o=>o.ppid===e.selfPid?!1:o.ppid===1?!0:!e.isAlive(o.ppid));return{matched:t,roots:s,orphans:i}}async function oo(r={}){let e=r.platform??process.platform,t={matched:0,trees:0,orphans:0,killed:0,failed:0,unregistered:0,skipped:null};if(e==="win32")return t.skipped="windows",t;let n=r.readTable??Pu,s=r.isAlive??H,i=r.killTree??(p=>ie(p,{signalMode:"graceful"})),o=r.selfPid??process.pid,a;try{a=await n()}catch(p){return f.warn("PROCESS","Orphaned chroma-mcp sweep skipped: cannot read the process table",{error:p instanceof Error?p.message:String(p)}),t.skipped="unreadable",t}let{matched:c,roots:l,orphans:u}=Iu(a,{isAlive:s,selfPid:o});if(t.matched=c.length,t.trees=l.length,t.orphans=u.length,u.length===0)return f.debug("PROCESS","No orphaned chroma-mcp trees found",{matched:t.matched,trees:t.trees}),t;f.warn("PROCESS","Reaping orphaned chroma-mcp trees left by dead workers",{orphans:u.length,roots:u.map(p=>p.pid)});let d=new Set,g=8;for(let p=0;p<u.length;p+=g){let h=u.slice(p,p+g);(await Promise.allSettled(h.map(E=>i(E.pid)))).forEach((E,_)=>{let b=h[_];E.status==="fulfilled"?(t.killed+=1,d.add(b.pid)):(t.failed+=1,f.warn("PROCESS","Failed to reap an orphaned chroma-mcp tree",{pid:b.pid,ppid:b.ppid,error:E.reason instanceof Error?E.reason.message:String(E.reason)}))})}if(r.registry)for(let p of r.registry.getAll())p.type==="chroma"&&d.has(p.pid)&&(r.registry.unregister(p.id),t.unregistered+=1);return f.info("PROCESS","Orphaned chroma-mcp sweep finished",{orphans:t.orphans,killed:t.killed,failed:t.failed,unregistered:t.unregistered}),t}U();var ds=L.workerPid(),fs=class{registry;started=!1;stopPromise=null;signalHandlersRegistered=!1;shutdownInitiated=!1;shutdownHandler=null;constructor(e){this.registry=e}async start(){if(this.started)return;if(this.registry.initialize(),wr({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,oo({registry:this.registry}).catch(t=>{f.warn("PROCESS","Orphaned chroma-mcp sweep failed",{error:t instanceof Error?t.message:String(t)})}),ro()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let t=async n=>{if(this.shutdownInitiated){f.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,f.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(s){s instanceof Error?f.error("SYSTEM","Error during shutdown",{},s):f.error("SYSTEM","Error during shutdown (non-Error)",{error:String(s)});try{await this.stop()}catch(i){i instanceof Error?f.debug("SYSTEM","Supervisor shutdown fallback failed",{},i):f.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(i)})}}process.exit(0)};process.on("SIGTERM",()=>{t("SIGTERM")}),process.on("SIGINT",()=>{t("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{f.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{t("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}no(),this.stopPromise=Zi({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,t,n){this.registry.register(e,t,n)}unregisterProcess(e){this.registry.unregister(e)}getRegistry(){return this.registry}},$m=new fs(br());function ps(){if(!(0,ye.existsSync)(ds))return null;let r;try{r=JSON.parse((0,ye.readFileSync)(ds,"utf-8"))}catch{return null}return r!==null&&Sr(r)?r:null}function wr(r={}){let e=r.pidFilePath??ds;if(!(0,ye.existsSync)(e))return"missing";let t=null;try{t=JSON.parse((0,ye.readFileSync)(e,"utf-8"))}catch(s){return s instanceof Error?f.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},s):f.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(s)}),(0,ye.rmSync)(e,{force:!0}),"invalid"}return Sr(t)&&t?((r.logAlive??!0)&&f.info("SYSTEM","Worker already running (PID alive)",{existingPid:t.pid,existingPort:t.port,startedAt:t.startedAt}),"alive"):(f.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:t?.pid,port:t?.port,startedAt:t?.startedAt}),(0,ye.rmSync)(e,{force:!0}),"stale")}lr();var gs=require("path"),Ar=require("fs"),co=require("crypto");U();var vr=require("fs");et();function ao(r,e){if(!(0,vr.existsSync)(r))return e;try{return Re((0,vr.readFileSync)(r,"utf-8"))}catch(t){throw new Error(`Corrupt JSON file, refusing to overwrite: ${r}: ${t instanceof Error?t.message:String(t)}`)}}A();var lo="telemetry.json";function Ru(r){let e=r.DO_NOT_TRACK;return e===void 0||e===""?!1:e!=="0"&&e!=="false"}function Cu(r,e){if(Ru(r))return{enabled:!1,source:"DO_NOT_TRACK"};let t=r.CLAUDE_MEM_TELEMETRY?.toLowerCase();return t==="0"||t==="false"||t==="off"?{enabled:!1,source:"env"}:t==="1"||t==="true"||t==="on"?{enabled:!0,source:"env"}:e?.enabled===!0?{enabled:!0,source:"config"}:e?.enabled===!1?{enabled:!1,source:"config"}:{enabled:!0,source:"default"}}function Tr(r,e){return Cu(r,e).enabled}function uo(r){let e=r.CLAUDE_MEM_TELEMETRY_ERRORS?.toLowerCase();return!(e==="0"||e==="false"||e==="off")}function Mu(){return(0,gs.join)(Ce(),lo)}function Rt(){let r;try{r=ao(Mu(),null)}catch(e){let t=e instanceof Error?e:new Error(String(e));return f.warn("SYSTEM","Telemetry: corrupt telemetry.json; treating as no recorded consent",void 0,t),null}return!r||typeof r!="object"||typeof r.installId!="string"||r.enabled!==void 0&&typeof r.enabled!="boolean"?null:{enabled:r.enabled,installId:r.installId,decidedAt:typeof r.decidedAt=="string"?r.decidedAt:""}}function xu(r){let e=Ce();(0,Ar.mkdirSync)(e,{recursive:!0}),(0,Ar.writeFileSync)((0,gs.join)(e,lo),JSON.stringify(r,null,2)+`
18
- `)}function Pr(){let r=Rt();if(r?.installId)return r.installId;let e=(0,co.randomUUID)();return xu({installId:e,decidedAt:""}),e}var Fu=new Set(["version","os","os_version","is_wsl","arch","runtime","runtime_version","node_version","duration_ms","outcome","error_category","locale","is_ci","endpoint","ide","provider","runtime_mode","trigger","count","has_summary","is_update","stage","install_method","interactive","bun_version","uv_version","claude_code_version","trial_days","trial_variant","offer_surface","funnel_source","observation_count","session_count","timeline_depth_days","has_session_summary","obs_type_bugfix","obs_type_discovery","obs_type_decision","obs_type_refactor","obs_type_other","tokens_injected","tokens_saved_vs_naive","mode","search_strategy","observation_type","hook","compression_ms","tokens_input","tokens_output","compression_ratio","model","cost_usd","endpoint_class","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs","result_count","chroma_available","fallback_reason","invalid_output_class","consecutive_invalid_outputs","respawn_triggered","abort_reason","previous_shutdown","previous_uptime_seconds","uptime_seconds","shutdown_reason","process_rss_mb","heap_used_mb","hook_type","error_mode","consecutive_failures","threshold_tripped","limit_window","overage_status","is_using_overage","resets_in_minutes","discovery_tokens","read_tokens","summary_count","prompt_count","project_count","backfilled","first_active_date","session_completed_count","session_failed_count","sessions_claude_count","sessions_codex_count","sessions_gemini_count","sessions_other_platform_count","subagent_obs_count","total_tokens_input","total_tokens_output","total_cost_usd","avg_duration_ms","avg_compression_ms","outcomes_ok","outcomes_error","outcomes_aborted","outcomes_invalid_output","top_model","observed_model","observed_billing","window_start_ts","rollup_reason","window_seq","total_tokens","avg_tokens","skill_id","skill_source","skill_trigger","observations_created","total_observations_injected","total_tokens_saved_vs_naive"]),fo=200;function Ou(r,e){if(!(!r||typeof r!="object"))for(let t of Object.keys(r)){if(!Fu.has(t))continue;let n=r[t];typeof n=="string"?e[t]=n.length>fo?n.slice(0,fo):n:(typeof n=="number"&&Number.isFinite(n)||typeof n=="boolean")&&(e[t]=n)}}function Ir(r){let e={};try{Ou(r,e)}catch{}return e}var hs=fe(require("os"),1);A();var ku="13.24.12",Du="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",Lu="https://us.i.posthog.com";function Rr(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||Du}function Cr(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||Lu}var Nu=["version","os","os_version","is_wsl","arch","runtime","locale","ide","provider","runtime_mode","install_method","claude_code_version","first_active_date","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs"];function Mr(r){let e={};for(let t of Nu)r[t]!==void 0&&(e[t]=r[t]);return e}function Uu(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||hs.default.release().toLowerCase().includes("microsoft")}catch(r){let e=r instanceof Error?r:new Error(String(r));return f.warn("SYSTEM","Telemetry: WSL detection failed; reporting is_wsl=false",void 0,e),!1}}function xr(){return{version:ku,os:process.platform,os_version:hs.default.release(),is_wsl:Uu(),arch:process.arch,runtime:process.versions.bun?"bun":"node",runtime_version:process.versions.bun??process.versions.node,node_version:process.versions.node,is_ci:!!process.env.CI,locale:Intl.DateTimeFormat().resolvedOptions().locale}}var $u=2e3;async function po(r,e,t){try{if(!Tr(process.env,Rt()))return;let n=Ir({...xr(),...e??{}});if(t?.person?n.$set=Mr(n):n.$process_person_profile=!1,process.env.CLAUDE_MEM_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:r,properties:n})+`
19
- `);return}let s=Rr(),i=new AbortController,o=setTimeout(()=>i.abort(),$u);try{await ju(s,r,n,i.signal)}finally{clearTimeout(o)}}catch{}}async function ju(r,e,t,n){await fetch(`${Cr()}/capture/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:r,event:e,distinct_id:Pr(),properties:t}),signal:n})}var Be=fe(require("path"),1),ho=require("os"),Se=require("fs"),_s=require("child_process");A();A();A();U();var __=L.dataDir(),E_=L.workerPid();function go(r){return r?/(^|[\\/])bun(\.exe)?$/i.test(r.trim()):!1}function Wu(r,e){let t=e==="win32"?`where ${r}`:`which ${r}`,n;try{n=(0,_s.execSync)(t,{stdio:["ignore","pipe","ignore"],encoding:"utf-8",windowsHide:!0})}catch(i){return i instanceof Error?f.debug("SYSTEM",`Binary lookup failed for ${r}`,{command:t},i):f.debug("SYSTEM",`Binary lookup failed for ${r}`,{command:t},new Error(String(i))),null}return n.split(/\r?\n/).map(i=>i.trim()).find(i=>i.length>0)||null}var ms;function Es(r={}){let e=Object.keys(r).length===0;if(e&&ms!==void 0)return ms;let t=Hu(r);return e&&t!==null&&(ms=t),t}function Hu(r){let e=r.platform??process.platform,t=r.execPath??process.execPath;if(go(t))return t;let n=r.env??process.env,s=r.homeDirectory??(0,ho.homedir)(),i=r.pathExists??Se.existsSync,o=r.lookupInPath??Wu,a=e==="win32"?[n.BUN,n.BUN_PATH,Be.default.join(s,".bun","bin","bun.exe"),Be.default.join(s,".bun","bin","bun"),n.USERPROFILE?Be.default.join(n.USERPROFILE,".bun","bin","bun.exe"):void 0,n.LOCALAPPDATA?Be.default.join(n.LOCALAPPDATA,"bun","bun.exe"):void 0,n.LOCALAPPDATA?Be.default.join(n.LOCALAPPDATA,"bun","bin","bun.exe"):void 0]:[n.BUN,n.BUN_PATH,Be.default.join(s,".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun","/usr/bin/bun","/snap/bin/bun"];for(let c of a){let l=c?.trim();if(l&&(go(l)&&i(l)||l.toLowerCase()==="bun"))return l}return o("bun",e)}var mo=fe(require("net"),1);A();U();function ys(){return q.loadFromFile(tt).CLAUDE_MEM_WORKER_HOST}function _o(r){return r.startsWith("[")&&r.endsWith("]")?r:r.includes(":")?`[${r}]`:r}var Eo=5e3;async function Gu(r,e,t="GET"){let n=await fetch(`http://${_o(ys())}:${r}${e}`,{method:t,signal:AbortSignal.timeout(Eo)}),s="";try{s=await n.text()}catch{}return{ok:n.ok,statusCode:n.status,body:s}}async function yo(r){if(process.platform==="win32")try{let e=await fetch(`http://${_o(ys())}:${r}/api/health`,{signal:AbortSignal.timeout(Eo)});if(e.ok)return!0;f.debug("SYSTEM","Windows health check returned non-ok; falling through to socket probe",{port:r,status:e.status})}catch(e){e instanceof Error?f.debug("SYSTEM","Windows health check threw; falling through to socket probe",{port:r,message:e.message}):f.debug("SYSTEM","Windows health check threw; falling through to socket probe",{port:r,error:String(e)})}return new Promise(e=>{let t=mo.default.createServer(),n=ys();t.once("error",s=>{s.code==="EADDRINUSE"?e(!0):e(!1)}),t.once("listening",()=>{t.close(()=>e(!1))}),t.listen(r,n)})}async function Ku(r){try{let e=await Gu(r,"/api/health");return e.ok?JSON.parse(e.body).version:null}catch{return f.debug("SYSTEM","Could not fetch worker version",{}),null}}async function So(r,e){let t=e??"unknown",n=await Ku(r);return!n||t==="unknown"?{matches:!0,pluginVersion:t,workerVersion:n}:{matches:t===n,pluginVersion:t,workerVersion:n}}A();var Fr=require("path"),z=require("fs");U();A();var Vu=9e4;function bo(){return(0,Fr.join)(Ce(),"spawn.lock")}function Ss(){let r=bo(),e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let t=0;t<2;t++)try{return(0,z.mkdirSync)((0,Fr.dirname)(r),{recursive:!0}),(0,z.writeFileSync)(r,e,{flag:"wx"}),!0}catch(n){let s=n instanceof Error?n:new Error(String(n)),i=s.code;if(i!=="EEXIST")return f.warn("SYSTEM","Spawn lock write failed for a non-contention reason; failing open (spawning unlocked)",{lockPath:r,code:i},s),!0;if(t>0)return!1;let o;try{o=(0,z.statSync)(r).mtimeMs}catch{continue}if(Date.now()-o<=Vu)return!1;let a;try{a=(0,z.statSync)(r).mtimeMs}catch{continue}if(a!==o)return!1;try{(0,z.unlinkSync)(r)}catch{return!1}}return!1}function bs(){let r=bo();try{if(JSON.parse((0,z.readFileSync)(r,"utf-8")).pid!==process.pid)return;(0,z.unlinkSync)(r)}catch{}}et();function Io(r,e,t){let n=process.env[r];if(n){let s=parseInt(n,10);if(Number.isFinite(s)&&s>=t.min&&s<=t.max)return s;f.warn("SYSTEM",`Invalid ${r}, using default`,{value:n,min:t.min,max:t.max})}return e}var jr=Io("CLAUDE_MEM_HEALTH_TIMEOUT_MS",xe(V.HEALTH_CHECK),{min:500,max:3e5}),qu=Io("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",xe(V.HOOK_READINESS_WAIT),{min:0,max:3e5}),zu={min:500,max:3e5};function Ro(r=process.env){let e=r.CLAUDE_MEM_FETCH_VERBOSE;if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="on"||t==="yes"}function Yu(r){return Ro()?{...r,verbose:!0}:r}function Ju(r){let e={},t=r;for(let n=0;t&&n<4;n++){let s=n===0?"error":`cause${n}`;if(t instanceof Error){let i=t;e[s]={name:t.name,message:t.message,...i.code!==void 0?{code:i.code}:{}},t=t.cause;continue}e[s]=String(t);break}return e}function Xu(r,e,t){let n=typeof e.method=="string"?e.method:"GET",s=Ju(t),i=JSON.stringify(s);f.warn("SYSTEM","Worker IPC fetch failed",{url:r,method:n},i),Ie(`[claude-mem] fetch verbose: ${n} ${r} ${i}
20
- `)}async function Co(r,e={}){let t=Yu(e);try{return await fetch(r,t)}catch(n){throw Ro()&&Xu(r,e,n),n}}async function As(r,e={},t){try{return await Co(r,{...e,signal:AbortSignal.timeout(t)})}catch(n){throw n instanceof DOMException&&n.name==="TimeoutError"?new Error(`Request timed out after ${t}ms`):n}}var Or=null,kr=null,Dr=null,Lr=null;function Qu(){return k.default.join(q.get("CLAUDE_MEM_DATA_DIR"),"settings.json")}function Ts(){return Dr!==null||(Dr=q.loadFromFile(Qu())),Dr}function wo(r,e){if(!r)return null;let t=parseInt(r,10);return Number.isFinite(t)&&t>=e.min&&t<=e.max?t:null}function Zu(r,e,t){let n=process.env[r];if(n!==void 0){let o=wo(n,t);return o!==null?o:(f.warn("SYSTEM",`Invalid ${r}, using default`,{value:n,min:t.min,max:t.max}),e)}let s=Ts()[r],i=wo(s,t);return i!==null?i:(f.warn("SYSTEM",`Invalid ${r} in settings.json, using default`,{value:s,min:t.min,max:t.max}),e)}function We(){if(Or!==null)return Or;let r=Ts();return Or=parseInt(r.CLAUDE_MEM_WORKER_PORT,10),Or}function ed(){return kr!==null||(kr=Ts().CLAUDE_MEM_WORKER_HOST),kr}function td(){return Lr!==null||(Lr=Zu("CLAUDE_MEM_API_TIMEOUT_MS",xe(V.API_REQUEST),zu)),Lr}function rd(r){return r.startsWith("[")&&r.endsWith("]")?r:r.includes(":")?`[${r}]`:r}function nd(r){return`http://${rd(ed())}:${We()}${r}`}function be(r,e={}){let t=e.method??"GET",n=e.timeoutMs??td(),s=nd(r),i={method:t};return e.headers&&(i.headers=e.headers),e.body&&(i.body=e.body),n>0?As(s,i,n):Co(s,i)}async function sd(){return(await be("/api/health",{timeoutMs:jr})).ok}async function vs(r=jr){return(await be("/api/readiness",{timeoutMs:r})).ok}function Mo(r){let e=(0,x.existsSync)(k.default.join(r,"plugin","scripts"))?k.default.join(r,"plugin"):r;return k.default.join(e,"scripts","worker-service.cjs")}function id(r,e){let t=d=>{let g=d.split("-")[0].split(".");return[parseInt(g[0],10)||0,parseInt(g[1],10)||0,parseInt(g[2],10)||0]},[n,s,i]=t(r),[o,a,c]=t(e);if(o!==n)return o-n;if(a!==s)return a-s;if(c!==i)return c-i;let l=r.includes("-")?1:0,u=e.includes("-")?1:0;return l!==u?l-u:r<e?1:r>e?-1:0}function od(r=k.default.join(k.default.dirname(k.default.dirname(dr)),"cache","thedotmack","claude-mem")){try{return(0,x.readdirSync)(r).filter(e=>/^\d/.test(e)).map(e=>k.default.join(r,e)).filter(e=>{try{if(!(0,x.statSync)(e).isDirectory())return!1}catch{return!1}return!(0,x.existsSync)(k.default.join(e,".orphaned_at"))}).map(e=>({scriptPath:Mo(e),version:k.default.basename(e)}))}catch{return[]}}function vo(r){try{let e=JSON.parse((0,x.readFileSync)(r,"utf-8"));return typeof e.version=="string"?e.version:null}catch(e){let t=e.code;return t!=="ENOENT"&&f.debug("SYSTEM","Could not read package version for worker resolution",{packageJsonPath:r,code:t}),null}}function xo(){let r=process.env.CLAUDE_MEM_WORKER_SCRIPT_PATH?.trim();if(r){if((0,x.existsSync)(r))return{scriptPath:r,version:null};f.debug("SYSTEM","Ignoring missing CLAUDE_MEM_WORKER_SCRIPT_PATH override",{override:r})}let e=[...od(),{scriptPath:Mo(k.default.join(dr,"plugin")),version:vo(k.default.join(dr,"package.json"))},{scriptPath:k.default.join(process.cwd(),"plugin","scripts","worker-service.cjs"),version:vo(k.default.join(process.cwd(),"package.json"))}];return ad(e)}function ad(r){let e=r.filter(t=>(0,x.existsSync)(t.scriptPath));return e.length===0?null:(e.sort((t,n)=>t.version===null&&n.version===null?0:t.version===null?1:n.version===null?-1:id(t.version,n.version)),e[0])}function cd(){return xo()?.scriptPath??null}async function ld(r){let e=r.backoffMs;for(let t=1;t<=r.attempts;t++){if(await Oo())return!0;t<r.attempts&&(await new Promise(n=>setTimeout(n,e)),e*=2)}return!1}async function ws(r=qu){if(r<=0)try{return await vs()}catch(t){let n=t instanceof Error?t:new Error(String(t));return f.debug("SYSTEM","Worker readiness check threw",{},n),!1}let e=Date.now();for(;Date.now()-e<r;){try{if(await vs())return!0}catch(n){f.debug("SYSTEM","Worker readiness check threw",{error:n instanceof Error?n.message:String(n)})}let t=r-(Date.now()-e);if(t<=0)break;await new Promise(n=>setTimeout(n,Math.min(250,t)))}return!1}async function ud(){try{let e=await(await be("/api/health",{timeoutMs:jr})).json();return typeof e.version=="string"?e.version:null}catch(r){let e=r instanceof Error?r:new Error(String(r));return f.debug("SYSTEM","Worker health-version fetch failed",{},e),null}}async function dd(r=5e3){let e=Date.now();for(;;){try{await be("/api/health",{timeoutMs:jr})}catch{return!0}if(Date.now()-e>=r)return!1;await new Promise(t=>setTimeout(t,200))}}function fd(r,e){if(!r)return null;try{let t=(0,x.statSync)(r.scriptPath);return JSON.stringify([r.scriptPath,e,t.size,t.mtimeMs,t.ctimeMs])}catch{return null}}function Fo(){return k.default.join(Ce(),"worker-version-recycle.json")}function pd(r,e){if(r===null||e===null)return!1;try{let t=JSON.parse((0,x.readFileSync)(Fo(),"utf-8"));return t?.buildKey===r&&t?.workerVersion===e}catch{return!1}}async function Ao(r,e=null){let t=await ud();if(t!==null&&t!==r){if(e!==null)try{Ze(Fo(),{buildKey:e,workerVersion:t})}catch(n){f.warn("SYSTEM","Could not persist the failed worker version recycle",{error:n instanceof Error?n.message:String(n)})}f.warn("SYSTEM","Worker is ready but still reports a stale version; rebuild or reinstall the worker bundle before retrying",{pluginVersion:r,workerVersion:t})}}async function Oo(){let r;try{r=await sd()}catch(t){return f.debug("SYSTEM","Worker health check threw",{error:t instanceof Error?t.message:String(t)}),!1}if(!r)return!1;let e=wr({logAlive:!1});return e==="missing"||e==="alive"}async function Br(){let r=xo(),e=null,t=null;if(await Oo()){let{matches:a,pluginVersion:c,workerVersion:l}=await So(We(),r?.version??null);if(c!=="unknown"&&(e=c),a)return await ws()?(e!==null&&await Ao(e),!0):(f.warn("SYSTEM","Worker is healthy but not ready; skipping hook API call"),!1);if(t=fd(r,c),pd(t,l))return f.warn("SYSTEM","Skipping repeated worker recycle: the unchanged bundle still reports a stale version; rebuild or reinstall it",{pluginVersion:c,workerVersion:l,scriptPath:r?.scriptPath}),ws();f.info("SYSTEM","Worker version mismatch \u2014 killing stale worker",{pluginVersion:c,workerVersion:l});let u=ps();if(u===null||u.port!==We())return f.error("SYSTEM","Stale worker is serving the port but the PID file does not identify it; kill the claude-mem worker process manually",{port:We(),pidFilePid:u?.pid??null,pidFilePort:u?.port??null}),!1;try{await ie(u.pid,{signalMode:"immediate"})}catch(d){return f.error("SYSTEM","Could not kill stale worker",{pid:u.pid,port:u.port},d instanceof Error?d:new Error(String(d))),!1}if(!await dd())return f.error("SYSTEM","Stale worker port still open after SIGKILL; skipping spawn this hook event",{pid:u.pid,port:We()}),!1}let n=Es(),s=r?.scriptPath??null;if(!n)return f.warn("SYSTEM","Cannot lazy-spawn worker: Bun runtime not found on PATH"),!1;if(!s)return f.warn("SYSTEM","Cannot lazy-spawn worker: worker-service.cjs not found in plugin/scripts"),!1;let i=Ss();try{if(i){f.info("SYSTEM","Worker not running \u2014 lazy-spawning",{runtimePath:n,scriptPath:s});try{Tt(n,[s,"--daemon"],{detached:!0,stdio:["ignore","ignore","ignore"]}).unref()}catch(c){return c instanceof Error?f.error("SYSTEM","Lazy-spawn of worker failed",{runtimePath:n,scriptPath:s},c):f.error("SYSTEM","Lazy-spawn of worker failed (non-Error)",{runtimePath:n,scriptPath:s,error:String(c)}),!1}}else f.info("SYSTEM","Another launcher holds the spawn lock \u2014 skipping lazy-spawn and waiting for its worker");if(!await ld({attempts:6,backoffMs:500}))return f.warn("SYSTEM",i?"Worker port did not open after lazy-spawn within the cold-boot wait (~15s)":"Spawn-lock holder's worker port did not open within the cold-boot wait (~15s)"),ps()===null&&await yo(We())&&($r=We(),f.error("SYSTEM","Worker port is occupied by an unreachable process that no PID file claims (likely an orphaned OS socket); every lazy-spawn on this port will be silently refused",{port:$r,fix:ko})),!1}finally{i&&bs()}return await ws()?(e!==null&&await Ao(e,t),!0):(f.warn("SYSTEM","Worker lazy-spawned but did not become ready before hook readiness timeout"),!1)}var ko="Set CLAUDE_MEM_WORKER_PORT to a different port in claude-mem settings, or reboot to release the stuck port",$r=null,Nr=null;async function gd(){return Nr!==null||(Nr=await Br()),Nr}async function hd(r){let e=Date.now()+r,t=async()=>{let o=e-Date.now();if(o<=0)return!1;try{return await vs(Math.min(500,o))}catch{return!1}};if(await t())return!0;let n=Es(),s=cd();if(!n||!s)return!1;let i=Ss();try{for(i&&Tt(n,[s,"--daemon"],{detached:!0,stdio:["ignore","ignore","ignore"]}).unref();Date.now()<e;){if(await t())return!0;let o=e-Date.now();o>0&&await new Promise(a=>setTimeout(a,Math.min(100,o)))}return!1}catch(o){return f.debug("SYSTEM","Bounded worker startup failed",{error:o instanceof Error?o.message:String(o)}),!1}finally{i&&bs()}}var md=3;function Do(){return k.default.join(M,"state")}function Lo(){return k.default.join(Do(),"hook-failures.json")}function _d(r){let e=JSON.parse(r);return{consecutiveFailures:typeof e.consecutiveFailures=="number"&&Number.isFinite(e.consecutiveFailures)?Math.max(0,Math.floor(e.consecutiveFailures)):0,lastFailureAt:typeof e.lastFailureAt=="number"&&Number.isFinite(e.lastFailureAt)?e.lastFailureAt:0}}function No(){try{return _d((0,x.readFileSync)(Lo(),"utf-8"))}catch{return{consecutiveFailures:0,lastFailureAt:0}}}function Uo(r){let e=Do(),t=Lo(),n=`${t}.tmp`;try{(0,x.existsSync)(e)||(0,x.mkdirSync)(e,{recursive:!0}),(0,x.writeFileSync)(n,JSON.stringify(r),"utf-8"),(0,x.renameSync)(n,t)}catch(s){f.debug("SYSTEM","Failed to persist hook-failure counter",{error:s instanceof Error?s.message:String(s)})}}function Ed(){try{let e=me().CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD,t=parseInt(e,10);if(Number.isFinite(t)&&t>=1)return t}catch{}return md}var To=null;async function yd(){let e={consecutiveFailures:No().consecutiveFailures+1,lastFailureAt:Date.now()};Uo(e);let t=Ed();return e.consecutiveFailures>=t&&(e.consecutiveFailures===t&&await po("hook_failed",{...To!==null?{hook_type:To}:{},error_mode:"worker_unavailable",consecutive_failures:e.consecutiveFailures,threshold_tripped:!0}),Li($r!==null?`claude-mem worker unreachable for ${e.consecutiveFailures} consecutive hooks: port ${$r} is held by an unreachable process that no PID file claims, so the worker cannot bind it. ${ko}.`:`claude-mem worker unreachable for ${e.consecutiveFailures} consecutive hooks.`)),e.consecutiveFailures}function Po(){No().consecutiveFailures!==0&&Uo({consecutiveFailures:0,lastFailureAt:0})}var Ur=Symbol.for("claude-mem/worker-fallback");function Wr(r){return typeof r=="object"&&r!==null&&r[Ur]===!0}async function Hr(r,e,t,n={}){let s=n.workerStartupTimeoutMs!==void 0;if(!(s?await hd(n.workerStartupTimeoutMs):await gd()))return s||await yd(),{continue:!0,reason:"worker_unreachable",[Ur]:!0};let o={method:e};t!==void 0&&(o.headers={"Content-Type":"application/json"},o.body=JSON.stringify(t)),n.timeoutMs!==void 0&&(o.timeoutMs=n.timeoutMs);let a;try{a=await be(r,o)}catch(l){if(!s)throw l;return f.debug("SYSTEM","Worker unavailable for best-effort hook call",{error:l instanceof Error?l.message:String(l)}),{continue:!0,reason:"worker_unreachable",[Ur]:!0}}if(!a.ok){let l=await a.text().catch(()=>"");if(Po(),a.status===429||a.status>=500)return f.warn("SYSTEM",`Worker API ${e} ${r} returned ${a.status}; skipping hook API call`,{body:l.substring(0,200)}),{continue:!0,reason:`worker_api_${a.status}`,[Ur]:!0};let u=l;try{u=JSON.parse(l)}catch{}return u}Po();let c=await a.text();if(c.length!==0)try{return JSON.parse(c)}catch{return c}}var jo=fe(require("path"),1),Bo=require("child_process");ur();A();var Gr=require("fs"),it=fe(require("path"),1);A();var Ct={isWorktree:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null};function $o(r){let e=it.default.join(r,".git"),t;try{t=(0,Gr.statSync)(e)}catch(u){return u instanceof Error&&u.code!=="ENOENT"&&f.warn("GIT","Unexpected error checking .git",{error:u instanceof Error?u.message:String(u)}),Ct}if(!t.isFile())return Ct;let n;try{n=(0,Gr.readFileSync)(e,"utf-8").trim()}catch(u){return f.warn("GIT","Failed to read .git file",{error:u instanceof Error?u.message:String(u)}),Ct}let s=n.match(/^gitdir:\s*(.+)$/);if(!s)return Ct;let o=it.default.resolve(it.default.dirname(e),s[1]).match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(!o)return Ct;let a=o[1],c=it.default.basename(r),l=it.default.basename(a);return{isWorktree:!0,worktreeName:c,parentRepoPath:a,parentProjectName:l}}function Wo(r){try{return(0,Bo.execFileSync)("git",["rev-parse","--show-toplevel"],{cwd:r,encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0}).trim()||null}catch(e){let t=e instanceof Error?e:new Error(String(e));return f.debug("PROJECT_NAME","git rev-parse failed, falling back to basename",{dir:r},t),null}}function Sd(r,e=process.platform){if(!r||r.trim()==="")return f.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:r}),"unknown-project";let t=je(r,e),s=Wo(t)??t,i=jo.default.basename(s);if(i===""){if(process.platform==="win32"){let a=r.match(/^([A-Z]):\\/i);if(a){let l=`drive-${a[1].toUpperCase()}`;return f.info("PROJECT_NAME","Drive root detected",{cwd:r,projectName:l}),l}}return f.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:r}),"unknown-project"}return i}function He(r,e=process.platform){let t=Sd(r,e);if(!r)return{primary:t,parent:null,isWorktree:!1,allProjects:[t]};let n=je(r,e),s=$o(Wo(n)??n);if(s.isWorktree&&s.parentProjectName){let i=`${s.parentProjectName}/${t}`;return{primary:i,parent:s.parentProjectName,isWorktree:!0,allProjects:[s.parentProjectName,i]}}return{primary:t,parent:null,isWorktree:!1,allProjects:[t]}}A();var Ge=require("path");var Ho=require("os"),Go=require("path");A();function bd(r){let e=r.startsWith("~")?(0,Ho.homedir)()+r.slice(1):r;e=e.replace(/\\/g,"/");let t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return t=t.replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/<<<GLOBSTAR>>>/g,".*"),new RegExp(`^${t}$`)}function Kr(r,e){if(!e||!e.trim())return!1;let t=r.replace(/\\/g,"/"),n=(0,Go.basename)(t),s=e.split(",").map(i=>i.trim()).filter(Boolean);for(let i of s)try{let o=bd(i);if(o.test(t)||o.test(n))return!0}catch(o){f.warn("PROJECT_NAME","Invalid exclusion pattern",{pattern:i,error:o instanceof Error?o.message:String(o)});continue}return!1}U();function wd(r,e){let t=(0,Ge.normalize)(r),n=(0,Ge.normalize)(e);if(t===n)return!0;let s=(0,Ge.relative)(n,t);return s.length>0&&!s.startsWith("..")&&!(0,Ge.isAbsolute)(s)}function Vr(r){if(process.env.CLAUDE_MEM_INTERNAL==="1")return!1;if(!r)return!0;if(wd(r,Xn))return!1;let e=me();return!Kr(r,e.CLAUDE_MEM_EXCLUDED_PROJECTS)}var Ko="claude";function vd(r){return r.trim().toLowerCase().replace(/\s+/g,"-")}function oe(r){if(!r)return Ko;let e=vd(r);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:Ko}A();var zo=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],Vo=new RegExp(`<(${zo.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`,"g");var qo=100;function Ad(r){let e=Object.fromEntries(zo.map(s=>[s,0]));Vo.lastIndex=0;let t=0,n=r.replace(Vo,(s,i)=>(e[i]=(e[i]??0)+1,t+=1,""));return t>qo&&f.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:t,maxAllowed:qo,contentLength:r.length}),{stripped:n.trim(),counts:e}}function Ps(r){return Ad(r).stripped}var Td=["task-notification"],Pd=new RegExp(`^\\s*<(${Td.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),Id=256*1024;function Yo(r){return!r||r.length>Id?!1:Pd.test(r)}A();var Rd=xe(V.API_REQUEST),we=class extends Error{kind;status;cause;constructor(e,t,n={}){super(t),this.name="ServerClientError",this.kind=e,this.status=n.status??null,this.cause=n.cause}isFallbackEligible(){return this.kind==="transport"||this.kind==="timeout"||this.kind==="missing_api_key"||this.kind==="http_error"&&(this.status!==null&&this.status>=500||this.status===429)}},qr=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=Cd(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??Rd}async startSession(e){let t=this.buildStartSessionPayload(e);return this.request("POST","/v1/sessions/start",t)}async recordEvent(e){let t=this.buildEventPayload(e),n=e.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",n,t)}async endSession(e){if(!e.sessionId)throw new we("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(e.sessionId)}/end`,{})}async addObservation(e){return this.request("POST","/v1/memories",this.buildAddObservationPayload(e))}async searchObservations(e){return this.request("POST","/v1/search",this.buildSearchPayload(e))}async contextObservations(e){return this.request("POST","/v1/context",this.buildSearchPayload(e))}async getJobStatus(e){if(!e)throw new we("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(e)}`)}buildAddObservationPayload(e){let t=e.content,n=e.kind??"manual",s=typeof e.metadata?.title=="string"?e.metadata.title:void 0;return{projectId:e.projectId,kind:n,type:n,narrative:t,...s?{title:s}:{},...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.platformSource!==void 0?{platformSource:e.platformSource}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildSearchPayload(e){return{projectId:e.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:Is(e.platformSource)}:{}}}buildStartSessionPayload(e){return{projectId:e.projectId,...e.externalSessionId!==void 0?{externalSessionId:e.externalSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.agentId!==void 0?{agentId:e.agentId}:{},...e.agentType!==void 0?{agentType:e.agentType}:{},...e.platformSource!==void 0?{platformSource:Is(e.platformSource)}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildEventPayload(e){return{projectId:e.projectId,sourceType:e.sourceType,eventType:e.eventType,occurredAtEpoch:e.occurredAtEpoch,...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.memorySessionId!==void 0?{memorySessionId:e.memorySessionId}:{},...e.platformSource!==void 0?{platformSource:Is(e.platformSource)}:{},...e.payload!==void 0?{payload:e.payload}:{}}}async request(e,t,n){if(!this.apiKey||!this.apiKey.trim())throw new we("missing_api_key","Server API key is not configured (CLAUDE_MEM_SERVER_API_KEY).");let s=`${this.baseUrl}${t}`,i={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(i.body=JSON.stringify(n));let o;try{o=await As(s,i,this.timeoutMs)}catch(c){let l=c instanceof Error?c.message:String(c),u=/timed out|timeout/i.test(l);throw new we(u?"timeout":"transport",`Server ${e} ${t} failed: ${l}`,{cause:c})}if(!o.ok){let c=await o.text().catch(()=>"");throw new we("http_error",`Server ${e} ${t} returned ${o.status}: ${Md(c,200)}`,{status:o.status})}let a=await o.text();if(!a||a.length===0)return{};try{return JSON.parse(a)}catch(c){let l=c instanceof Error?c:new Error(String(c));throw new we("invalid_response",`Server ${e} ${t} returned non-JSON response`,{cause:l})}}};function Jo(r){return r instanceof we}function Cd(r){return r.replace(/\/+$/,"")}function Is(r){return typeof r=="string"?oe(r):null}function Md(r,e){return r.length<=e?r:`${r.slice(0,e)}\u2026`}function xd(){let e=(me().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function Fd(){let r=me(),e=(...o)=>{for(let a of o){let c=(a??"").trim();if(c.length>0)return c}return""},t=e(r.CLAUDE_MEM_SERVER_URL,r.CLAUDE_MEM_SERVER_BETA_URL),n=e(r.CLAUDE_MEM_SERVER_API_KEY,r.CLAUDE_MEM_SERVER_BETA_API_KEY),s=e(r.CLAUDE_MEM_SERVER_PROJECT_ID,r.CLAUDE_MEM_SERVER_BETA_PROJECT_ID);if(!t)return f.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!n)return f.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!s)return f.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let i={serverBaseUrl:t,apiKey:n};return{runtime:"server",client:new qr(i),projectId:s,serverBaseUrl:t}}function Xo(){if(xd()!=="server")return{runtime:"worker"};let r=Fd();return r||{runtime:"worker"}}function Qo(r,e){f.warn("HOOK",`[server-fallback] reason=${r}`,e??{})}var Od={executeWithWorkerFallback:Hr,isWorkerFallback:Wr,loadFromFileOnce:me,resolveRuntimeContext:Xo,logServerFallback:Qo,shouldTrackProject:Vr},Oe=Od;var Zo={async execute(r){let{sessionId:e,prompt:t}=r,n=r.cwd??process.cwd();if(!e)return f.warn("HOOK","session-init: No sessionId provided, skipping (Codex CLI or unknown platform)"),{continue:!0,suppressOutput:!0,exitCode:Me.SUCCESS};if(!Oe.shouldTrackProject(n))return f.info("HOOK","Project excluded from tracking",{cwd:n}),{continue:!0,suppressOutput:!0};if(t&&Yo(t))return f.debug("HOOK","session-init: skipping internal protocol payload",{preview:t.slice(0,80)}),{continue:!0,suppressOutput:!0};let s=!t||!t.trim()?"[media prompt]":t,i=He(n).primary,o=oe(r.platform),a=Oe.loadFromFileOnce(),c=String(a.CLAUDE_MEM_SEMANTIC_INJECT).toLowerCase()==="true",l=Oe.resolveRuntimeContext();if(l.runtime==="server")try{return await kd(l,r,e,o,i,s),{continue:!0,suppressOutput:!0}}catch(h){if(Jo(h)&&h.isFallbackEligible())Oe.logServerFallback(h.kind,{status:h.status,message:h.message,route:"/v1/sessions/start"});else return f.error("HOOK","Server session-start failed (non-recoverable)",{error:h instanceof Error?h.message:String(h)}),{continue:!0,suppressOutput:!0,exitCode:Me.SUCCESS}}f.debug("HOOK","session-init: Calling /api/sessions/init",{contentSessionId:e,project:i});let u=await Oe.executeWithWorkerFallback("/api/sessions/init","POST",{contentSessionId:e,project:i,prompt:s,platformSource:o},o==="codex"?{workerStartupTimeoutMs:V.POST_SPAWN_WAIT,timeoutMs:2e3}:void 0);if(Oe.isWorkerFallback(u))return{continue:!0,suppressOutput:!0,exitCode:Me.SUCCESS};if(typeof u?.sessionDbId!="number")return f.failure("HOOK","Session initialization returned malformed response",{contentSessionId:e,project:i}),{continue:!0,suppressOutput:!0,exitCode:Me.SUCCESS};let d=u.sessionDbId,g=u.promptNumber;if(f.debug("HOOK","session-init: Received from /api/sessions/init",{sessionDbId:d,promptNumber:g,skipped:u.skipped,contextInjected:u.contextInjected}),f.debug("HOOK",`[ALIGNMENT] Hook Entry | contentSessionId=${e} | prompt#=${g} | sessionDbId=${d}`),u.skipped&&u.reason==="private")return f.info("HOOK",`INIT_COMPLETE | sessionDbId=${d} | promptNumber=${g} | skipped=true | reason=private`,{sessionId:d}),{continue:!0,suppressOutput:!0};let p="";if(c&&s&&s.length>=20&&s!=="[media prompt]"){let h=a.CLAUDE_MEM_SEMANTIC_INJECT_LIMIT||"5",m=await Oe.executeWithWorkerFallback("/api/context/semantic","POST",{q:s,project:i,limit:h,platformSource:o},o==="codex"?{workerStartupTimeoutMs:V.POST_SPAWN_WAIT,timeoutMs:2e3}:void 0);!Oe.isWorkerFallback(m)&&m?.context&&(f.debug("HOOK",`Semantic injection: ${m.count} observations for prompt`,{sessionId:d,count:m.count}),p=m.context)}return f.info("HOOK",`INIT_COMPLETE | sessionDbId=${d} | promptNumber=${g} | project=${i}`,{sessionId:d}),p?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:p}}:{continue:!0,suppressOutput:!0}}};async function kd(r,e,t,n,s,i){await r.client.startSession({projectId:r.projectId,externalSessionId:t,contentSessionId:t,agentId:e.agentId??null,agentType:e.agentType??null,platformSource:n,metadata:{project:s,prompt:i}}),f.info("HOOK","session-init: server session started",{contentSessionId:t,project:s})}A();var ea={async execute(r){let{sessionId:e,cwd:t,filePath:n,edits:s}=r,i=oe(r.platform);if(!n)throw new Error("fileEditHandler requires filePath");if(f.dataIn("HOOK",`FileEdit: ${n}`,{editCount:s?.length??0}),!t)throw new Error(`Missing cwd in FileEdit hook input for session ${e}, file ${n}`);if(!Vr(t))return f.debug("HOOK","Project excluded from tracking, skipping file edit observation",{cwd:t,filePath:n}),{continue:!0,suppressOutput:!0,exitCode:Me.SUCCESS};let o=await Hr("/api/sessions/observations","POST",{contentSessionId:e,platformSource:i,tool_name:"write_file",tool_input:{filePath:n,edits:s},tool_response:{success:!0},cwd:t});return Wr(o)?{continue:!0,suppressOutput:!0,exitCode:Me.SUCCESS}:(f.debug("HOOK","File edit observation sent successfully",{filePath:n}),{continue:!0,suppressOutput:!0})}};U();A();var te=require("fs"),zr=require("path");A();A();U();var JE=L.settings();function ta(r,e){let t="<claude-mem-context>",n="</claude-mem-context>";if(!r)return`${t}
14
+ `)}else Re(g+`
15
+ `)}debug(e,t,n,s){this.log(0,e,t,n,s)}info(e,t,n,s){this.log(1,e,t,n,s)}warn(e,t,n,s){this.log(2,e,t,n,s)}setErrorSink(e){Qn=e}error(e,t,n,s){this.log(3,e,t,n,s),this.routeErrorToSink(t,n,s)}routeErrorToSink(e,t,n){try{if(!Qn||!(n instanceof Error))return;Qn(n)}catch{}}dataIn(e,t,n,s){this.info(e,`\u2192 ${t}`,n,s)}dataOut(e,t,n,s){this.info(e,`\u2190 ${t}`,n,s)}success(e,t,n,s){this.info(e,`\u2713 ${t}`,n,s)}failure(e,t,n,s){this.error(e,`\u2717 ${t}`,n,s)}},f=new es});var ge=require("fs"),Wi=require("os"),fr=require("path");U();var rt=L.transcriptsConfig(),pr=L.transcriptsState(),Ql={version:1,schemas:{},watches:[],stateFile:pr};function Zl(r){let e=typeof r.schema=="string"?r.schema:r.schema?.name;if(!(r.name==="codex"||e==="codex")||!r.path)return!1;let n=K(r.path).replace(/\\/g,"/"),s=(0,fr.join)((0,Wi.homedir)(),".codex","sessions").replace(/\\/g,"/");return n===`${s}/**/*.jsonl`}function Hi(r){let e=typeof r.schema=="string"?r.schema:r.schema?.name,t=r.name==="codex"&&(!e||e==="codex");return r.context?.mode==="agents"&&t&&Zl(r)}function K(r){return r&&Bi(r)}function At(r=rt){let e=K(r);if(!(0,ge.existsSync)(e))throw new Error(`Transcript watch config not found: ${e}`);let t=(0,ge.readFileSync)(e,"utf-8"),n=JSON.parse(t);if(!n.version||!n.watches)throw new Error(`Invalid transcript watch config: ${e}`);return n.stateFile||(n.stateFile=pr),n}function gr(r=rt){let e=K(r),t=(0,fr.dirname)(e);(0,ge.existsSync)(t)||(0,ge.mkdirSync)(t,{recursive:!0}),(0,ge.writeFileSync)(e,JSON.stringify(Ql,null,2))}var W=require("fs"),ne=require("path");A();var me=require("fs"),Ki=require("path");A();function Vi(r){try{if(!(0,me.existsSync)(r))return{offsets:{}};let e=(0,me.readFileSync)(r,"utf-8"),t=JSON.parse(e);return t.offsets?t:{offsets:{}}}catch(e){return f.warn("TRANSCRIPT","Failed to load watch state, starting fresh",{statePath:r,error:e instanceof Error?e.message:String(e)}),{offsets:{}}}}function qi(r,e){try{let t=(0,Ki.dirname)(r);(0,me.existsSync)(t)||(0,me.mkdirSync)(t,{recursive:!0}),(0,me.writeFileSync)(r,JSON.stringify(e,null,2))}catch(t){f.warn("TRANSCRIPT","Failed to save watch state",{statePath:r,error:t instanceof Error?t.message:String(t)})}}var ar=pe(require("path"),1);var k=pe(require("path"),1),x=require("fs");var ts=require("node:child_process");function Tt(r,e,t){return(0,ts.spawn)(r,e??[],{windowsHide:!0,...t})}var eu=new Set([".cmd",".bat"]),tu=new Set([".exe",".com"]),Xh=new Set([...tu,...eu]);A();var V={HEALTH_CHECK:3e3,API_REQUEST:3e4,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5},xe={SUCCESS:0,BLOCKING_ERROR:2};function Fe(r){return process.platform==="win32"?Math.round(r*V.WINDOWS_MULTIPLIER):r}var hr=require("fs"),rs=require("path"),Pt=require("os");et();var ru="security_alert",q=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-haiku-4-5-20251001",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:String(37700+(process.getuid?.()??77)%100),CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_API_TIMEOUT_MS:String(Fe(V.API_REQUEST)),CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"subscription",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-flash-latest",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_MODEL:"xiaomi/mimo-v2-flash:free",CLAUDE_MEM_OPENROUTER_BASE_URL:"",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_DATA_DIR:(0,rs.join)((0,Pt.homedir)(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_CLAUDE_CONFIG_DIR:"",CLAUDE_MEM_MODE:"code",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_FULL_COUNT:"0",CLAUDE_MEM_CONTEXT_FULL_FIELD:"narrative",CLAUDE_MEM_CONTEXT_SESSION_COUNT:"10",CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false",CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",CLAUDE_MEM_WELCOME_HINT_ENABLED:"true",CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_FOLDER_USE_LOCAL_MD:"false",CLAUDE_MEM_TRANSCRIPTS_ENABLED:"true",CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH:(0,rs.join)((0,Pt.homedir)(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_OBSERVER_MAX_CONVERSATION_CHARS:"400000",CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_FOLDER_MD_SKELETON_DENYLIST:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"false",CLAUDE_MEM_SEMANTIC_INJECT_LIMIT:"5",CLAUDE_MEM_TIER_ROUTING_ENABLED:"true",CLAUDE_MEM_TIER_SIMPLE_MODEL:"haiku",CLAUDE_MEM_TIER_SUMMARY_MODEL:"",CLAUDE_MEM_TIER_FAST_MODEL:"haiku",CLAUDE_MEM_TIER_SMART_MODEL:"sonnet",CLAUDE_MEM_CHROMA_ENABLED:"true",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database",CLAUDE_MEM_CHROMA_PREWARM_TIMEOUT_MS:"120000",CLAUDE_MEM_CHROMA_MAX_PENDING_MUTATIONS:"5000",CLAUDE_MEM_CLOUD_SYNC_TOKEN:"",CLAUDE_MEM_CLOUD_SYNC_USER_ID:"",CLAUDE_MEM_CLOUD_SYNC_HUB_URL:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_ID:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_NAME:(0,Pt.hostname)(),CLAUDE_MEM_CLOUD_SYNC_WS:"true",CLAUDE_MEM_CLOUD_SYNC_CONTENT_BATCH_SIZE:"40",CLAUDE_MEM_CLOUD_SYNC_REQUEST_TIMEOUT_MS:"90000",CLAUDE_MEM_TV_TOKEN:"",CLAUDE_MEM_PRO_TRIAL_EMAIL:"",CLAUDE_MEM_PRO_TRIAL_AT:"",CLAUDE_MEM_PRO_TRIAL_STATE:"",CLAUDE_MEM_PRO_TRIAL_ENDS_AT:"",CLAUDE_MEM_PRO_PLAN:"",CLAUDE_MEM_PRO_FALLBACK_AT:"",CLAUDE_MEM_PRO_MEMORY_KEY:"",CLAUDE_MEM_PRO_MEMORY_BASE_URL:"",CLAUDE_MEM_PRO_MEMORY_MODEL:"",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert,sensitive",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:"",CLAUDE_MEM_GROK_BOT_AWARENESS_ENABLED:"true",CLAUDE_MEM_GROK_BOT_AWARENESS_AGENT_IDS:"521e962d-2ec3-4488-bfbc-54d5209ce118,95601360-61f7-4fd9-bb3a-2c976b2b85c0",CLAUDE_MEM_GROK_BOT_AWARENESS_TRIGGER_TYPES:"decision,bugfix,security_alert,sensitive",CLAUDE_MEM_GROK_BOT_AWARENESS_TRIGGER_CONCEPTS:"",CLAUDE_MEM_CCS_ALIGN_ENABLED:"true",CLAUDE_MEM_CCS_ALIGN_VIEWER_IDS:"ccs-align",CLAUDE_MEM_CCS_ALIGN_TRIGGER_TYPES:"decision,bugfix,security_alert,sensitive",CLAUDE_MEM_CCS_ALIGN_PATCH_SHADOWS:"false",CLAUDE_MEM_QUEUE_ENGINE:"sqlite",CLAUDE_MEM_REDIS_URL:"",CLAUDE_MEM_REDIS_HOST:"127.0.0.1",CLAUDE_MEM_REDIS_PORT:"6379",CLAUDE_MEM_REDIS_MODE:"external",CLAUDE_MEM_QUEUE_REDIS_PREFIX:`claude_mem_${process.env.CLAUDE_MEM_WORKER_PORT??String(37700+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_AUTH_MODE:"api-key",CLAUDE_MEM_RUNTIME:"worker",CLAUDE_MEM_SERVER_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_API_KEY:"",CLAUDE_MEM_SERVER_PROJECT_ID:"",CLAUDE_MEM_SERVER_BETA_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_BETA_API_KEY:"",CLAUDE_MEM_SERVER_BETA_PROJECT_ID:""};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){return process.env[e]??this.DEFAULTS[e]}static getInt(e){let t=this.get(e);return parseInt(t,10)}static applyEnvOverrides(e){let t={...e};for(let n of Object.keys(this.DEFAULTS))process.env[n]!==void 0&&(t[n]=process.env[n]);return t}static loadFromFile(e,t=!0){try{if(!(0,hr.existsSync)(e)){let l=this.getAllDefaults();try{Ze(e,l),console.warn("[SETTINGS] Created settings file with defaults:",e)}catch(u){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,u instanceof Error?u.message:String(u))}return t?this.applyEnvOverrides(l):l}let n=(0,hr.readFileSync)(e,"utf-8"),s=Ce(n),i=s,o=s.env&&typeof s.env=="object"&&!Array.isArray(s.env),a=o&&Object.keys(s).some(l=>l!=="env");if(o&&(i=s.env,!a))try{Ze(e,i),console.warn("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(l){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,l instanceof Error?l.message:String(l))}if(i.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES===ru){i={...i,CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:this.DEFAULTS.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES};try{Ze(e,a?{...s,env:i}:i),console.warn("[SETTINGS] Migrated Telegram trigger types off the legacy default:",e)}catch(l){console.warn("[SETTINGS] Failed to migrate Telegram trigger types:",e,l instanceof Error?l.message:String(l))}}let c={...this.DEFAULTS};for(let l of Object.keys(this.DEFAULTS))i[l]!==void 0&&(c[l]=i[l]);return t?this.applyEnvOverrides(c):c}catch(n){console.warn("[SETTINGS] Failed to load settings, using defaults:",e,n instanceof Error?n.message:String(n));let s=this.getAllDefaults();return t?this.applyEnvOverrides(s):s}}};U();U();var mr=null;function _e(){return mr!==null||(mr=q.loadFromFile(tt)),mr}var Se=require("fs");A();var ye=require("fs"),cs=pe(require("path"),1);A();var nu=["CLAUDECODE_","CLAUDE_CODE_"],su=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),iu=new Set(["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy","npm_config_noproxy"]),ou=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_SKIP_BEDROCK_AUTH","CLAUDE_CODE_SKIP_VERTEX_AUTH","CLAUDE_CODE_SKIP_FOUNDRY_AUTH","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS",...iu]);function It(r=process.env){let e={};for(let[t,n]of Object.entries(r))if(n!==void 0){if(ou.has(t)){e[t]=n;continue}su.has(t)||nu.some(s=>t.startsWith(s))||(e[t]=n)}return e}U();var ss=require("child_process"),Yi=require("fs");A();var au=5e3,zi=new Map,ns=0;function cu(r){ns+=1;let e=(0,ss.spawnSync)("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${r}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...It(process.env),LC_ALL:"C",LANG:"C"}});if(e.status===0){let t=e.stdout.trim();return t.length>0?t:null}return null}function lu(r,e=!1){if(!e){let n=zi.get(r);if(n&&Date.now()-n.capturedAtMs<au)return n.token}let t=null;try{t=cu(r)}catch(n){f.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:r,error:n instanceof Error?n.message:String(n)}),t=null}return zi.set(r,{token:t,capturedAtMs:Date.now()}),t}function Ji(r,e){if(!Number.isInteger(r)||r<=0)return null;if(process.platform==="linux"){ns+=1;try{let t=(0,Yi.readFileSync)(`/proc/${r}/stat`,"utf-8"),n=t.lastIndexOf(") ");if(n<0)return null;let i=t.slice(n+2).split(" ")[19];return i&&/^\d+$/.test(i)?i:null}catch(t){return f.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:r,error:t instanceof Error?t.message:String(t)}),null}}if(process.platform==="win32")return lu(r,e);ns+=1;try{let t=(0,ss.spawnSync)("ps",["-p",String(r),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...It(process.env),LC_ALL:"C",LANG:"C"}});if(t.status!==0)return null;let n=t.stdout.trim();return n.length>0?n:null}catch(t){return f.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:r,error:t instanceof Error?t.message:String(t)}),null}}function Oe(r){return Ji(r,!1)}function Ee(r,e){if(e===null)return!0;let t=Ji(r,!0);return t===null?!0:t===e}var Xi=require("child_process"),yr=require("fs"),Qi=require("util");A();var is=(0,Qi.promisify)(Xi.execFile),uu=128,du=/not found|no running instance|no tasks/i,_r=class extends Error{pid;constructor(e,t,n){super(t,n),this.name="ProcessTreeKillError",this.pid=e}};async function oe(r,e={}){let t=e.signalMode==="immediate",n=e.expectedStartToken!==void 0?e.expectedStartToken:Oe(r),s=()=>Ee(r,n);if(!s()){f.warn("PROCESS","Skipping tree-kill: root PID was reused since it was captured",{pid:r});return}if(f.debug("PROCESS",`Killing process tree rooted at PID ${r}`,{immediate:t}),process.platform==="win32"){try{await is("taskkill",["/PID",String(r),"/T","/F"],{timeout:5e3,windowsHide:!0})}catch(i){let o=i.code,a=String(i.stderr??""),c=i instanceof Error?i.message:String(i);if(o===uu||du.test(`${a} ${c}`)){f.debug("PROCESS","taskkill reported the process was already gone",{pid:r});return}throw new _r(r,`taskkill failed for PID ${r} (exit ${String(o)}): ${a.trim()||c}`,{cause:i})}return}try{let i=t?"SIGKILL":"SIGTERM",o=await Er(r);for(let l of o){if(!Ee(l.pid,l.startToken)){f.debug("PROCESS",`Skipping ${i}: descendant PID was reused since enumeration`,{pid:l.pid,rootPid:r});continue}try{process.kill(l.pid,i)}catch{}}if(s())try{process.kill(r,i)}catch(l){let u=l instanceof Error?l:new Error(String(l)),d=u.code;d!=="ESRCH"&&f.debug("PROCESS",`Failed to ${i} PID ${r}`,{code:d},u)}else f.warn("PROCESS","Skipping root signal: PID was reused during descendant enumeration",{pid:r,signal:i});t||await new Promise(l=>setTimeout(l,500));let a=s()?await Er(r):[],c=new Map;for(let l of o)c.set(l.pid,l.startToken);for(let l of a)c.set(l.pid,l.startToken);for(let[l,u]of c){if(!Ee(l,u)){f.debug("PROCESS","Skipping SIGKILL: descendant PID was reused since the scan",{pid:l,rootPid:r});continue}try{process.kill(l,"SIGKILL")}catch{}}if(!t&&s())try{process.kill(r,"SIGKILL")}catch{}}catch(i){throw new _r(r,`tree-kill failed for PID ${r}: ${i instanceof Error?i.message:String(i)}`,{cause:i})}}async function fu(){return process.platform==="win32"?hu():process.platform==="linux"?pu():gu()}function pu(){let r=[],e;try{e=(0,yr.readdirSync)("/proc")}catch(t){return f.warn("PROCESS","Cannot read /proc \u2014 tree-kill degrades to a single-PID kill",{error:t instanceof Error?t.message:String(t)}),r}for(let t of e){if(!/^\d+$/.test(t))continue;let n;try{n=(0,yr.readFileSync)(`/proc/${t}/stat`,"utf-8")}catch{continue}let s=n.lastIndexOf(") ");if(s<0)continue;let i=n.slice(s+2).split(" "),o=Number.parseInt(i[1]??"",10),a=i[19];Number.isFinite(o)&&r.push({pid:Number.parseInt(t,10),ppid:o,startToken:a&&/^\d+$/.test(a)?a:null})}return r}async function gu(){let r;try{r=(await is("ps",["-eo","pid=,ppid=,lstart="],{timeout:1e4,maxBuffer:33554432,env:{...process.env,LC_ALL:"C",LANG:"C"}})).stdout}catch(t){return f.warn("PROCESS","Cannot enumerate the process table \u2014 tree-kill degrades to a single-PID kill",{error:t instanceof Error?t.message:String(t)}),[]}let e=[];for(let t of r.split(`
16
+ `)){let n=t.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);if(!n)continue;let s=n[3].trim();e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),startToken:s.length>0?s:null})}return e}async function hu(){let r;try{r=(await is("powershell.exe",["-NoProfile","-NonInteractive","-Command","Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,@{Name='StartToken';Expression={$_.CreationDate.ToString('yyyyMMddHHmmss.ffffff')}} | ConvertTo-Csv -NoTypeInformation"],{timeout:3e4,windowsHide:!0,maxBuffer:33554432})).stdout}catch(t){return f.warn("PROCESS","Cannot enumerate the Windows process table \u2014 tree-kill degrades to a single-PID kill",{error:t instanceof Error?t.message:String(t)}),[]}let e=[];for(let t of r.split(/\r?\n/).slice(1)){let n=t.match(/^"(\d+)","(\d+)","(.*)"$/);if(!n)continue;let s=n[3].trim();e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),startToken:s.length>0?s:null})}return e}async function Er(r){let e=await fu(),t=new Map;for(let o of e){let a=t.get(o.ppid);a?a.push(o):t.set(o.ppid,[o])}let n=new Set([r]),s=[],i=o=>{for(let a of t.get(o)??[])n.has(a.pid)||(n.add(a.pid),i(a.pid),s.push({pid:a.pid,startToken:a.startToken}))};return i(r),s}var mu=5e3,_u=1e3,Eu=L.supervisorRegistry();function H(r){if(!Number.isInteger(r)||r<0||r===0)return!1;try{return process.kill(r,0),!0}catch(e){if(e instanceof Error){let t=e.code;return t==="EPERM"?!0:(f.debug("SYSTEM","PID check failed",{pid:r,code:t}),!1)}return f.warn("SYSTEM","PID check threw non-Error",{pid:r,error:String(e)}),!1}}async function Sr(r,e){let t=Date.now()+e;for(;Date.now()<t;){if(r.every(n=>!H(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}function br(r){if(!r||!H(r.pid))return!1;if(!r.startToken)return!0;let e=Oe(r.pid);if(e===null)return!0;let t=e===r.startToken;return t||f.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:r.pid,stored:r.startToken,current:e}),t}var ls=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=Eu){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,ye.mkdirSync)(cs.default.dirname(this.registryPath),{recursive:!0}),!(0,ye.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,ye.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[s,i]of Object.entries(n))this.entries.set(s,i)}catch(t){t instanceof Error?f.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},t):f.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(t)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&f.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}register(e,t,n){this.initialize(),this.entries.set(e,t),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e){this.initialize();let t=this.entries.get(e);this.entries.delete(e),this.runtimeProcesses.delete(e),this.persist(),t?.type==="sdk"&&as()}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,t])=>({id:e,...t})).sort((e,t)=>{let n=Date.parse(e.startedAt),s=Date.parse(t.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(s)?0:s)})}getBySession(e){let t=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===t)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}pruneDeadEntries(){this.initialize();let e=0,t=0;for(let[n,s]of this.entries)H(s.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),e+=1,s.type==="sdk"&&(t+=1));e>0&&this.persist();for(let n=0;n<t;n+=1)as();return e}async reapSession(e){this.initialize();let t=this.getBySession(e);if(t.length===0)return 0;let n=typeof e=="number"?e:Number(e)||void 0;f.info("SYSTEM",`Reaping ${t.length} process(es) for session ${e}`,{sessionId:n,pids:t.map(a=>a.pid)});let s=t.filter(a=>H(a.pid)),i=new Map(s.map(a=>[a.pid,Oe(a.pid)]));for(let a of s)try{process.platform==="win32"?await oe(a.pid,{expectedStartToken:i.get(a.pid)??null}):typeof a.pgid=="number"?process.kill(-a.pgid,"SIGTERM"):process.kill(a.pid,"SIGTERM")}catch(c){c instanceof Error?c.code!=="ESRCH"&&f.debug("SYSTEM",`Failed to SIGTERM session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},c):f.warn("SYSTEM",`Failed to SIGTERM session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(c)})}await Sr(s,mu);let o=s.filter(a=>H(a.pid));for(let a of o){f.warn("SYSTEM",`Session process PID ${a.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:a.pid,pgid:a.pgid,sessionId:n});let c=i.get(a.pid)??null;if(!Ee(a.pid,c)){f.warn("SYSTEM","Skipping SIGKILL: session process PID was reused during the grace window",{pid:a.pid,sessionId:n});continue}try{process.platform==="win32"?await oe(a.pid,{expectedStartToken:c}):typeof a.pgid=="number"?process.kill(-a.pgid,"SIGKILL"):process.kill(a.pid,"SIGKILL")}catch(l){l instanceof Error?l.code!=="ESRCH"&&f.debug("SYSTEM",`Failed to SIGKILL session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},l):f.warn("SYSTEM",`Failed to SIGKILL session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(l)})}}if(o.length>0){let a=Date.now()+_u;for(;Date.now()<a&&o.filter(l=>H(l.pid)).length!==0;)await new Promise(l=>setTimeout(l,100))}for(let a of t)this.entries.delete(a.id),this.runtimeProcesses.delete(a.id);this.persist();for(let a of t)a.type==="sdk"&&as();return f.info("SYSTEM",`Reaped ${t.length} process(es) for session ${e}`,{sessionId:n,reaped:t.length}),t.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};(0,ye.mkdirSync)(cs.default.dirname(this.registryPath),{recursive:!0}),(0,ye.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},os=null;function wr(){return os||(os=new ls),os}var ym=180*1e3,yu=[];function as(){let r=yu.shift();r&&r.notify()}var nt=require("fs");A();U();var Su=L.workerPid();async function eo(r){let e=r.currentPid??process.pid,t=r.pidFilePath??Su,n=r.registry.getAll(),s=[...n].filter(c=>c.pid!==e).sort((c,l)=>Date.parse(l.startedAt)-Date.parse(c.startedAt)),i=new Map,o=new Map;for(let c of s){if(!H(c.pid)){r.registry.unregister(c.id);continue}o.set(c.id,Oe(c.pid)),i.set(c.id,await Er(c.pid));try{await Zi(c,"SIGTERM")}catch(l){l instanceof Error?f.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:c.pid,pgid:c.pgid,type:c.type},l):f.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(l)})}}await Sr(s,5e3);let a=s.filter(c=>H(c.pid)||(i.get(c.id)??[]).some(l=>H(l.pid)));for(let c of a){let l=Ee(c.pid,o.get(c.id)??null);l||f.warn("SYSTEM","Skipping tree-kill: root PID was reused during the grace window",{pid:c.pid,type:c.type});try{l&&await Zi(c,"SIGKILL")}catch(u){u instanceof Error?f.debug("SYSTEM","Failed to force kill child process",{pid:c.pid,pgid:c.pgid,type:c.type},u):f.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(u)})}finally{bu(i.get(c.id)??[],c.pid)}}await Sr(a,1e3);for(let c of s)r.registry.unregister(c.id);for(let c of n.filter(l=>l.pid===e))r.registry.unregister(c.id);to(t,e),r.registry.pruneDeadEntries()}function to(r,e,t=!1){if(!(0,nt.existsSync)(r))return;let n=null;try{let o=JSON.parse((0,nt.readFileSync)(r,"utf-8"));n=typeof o.pid=="number"?o.pid:null}catch(o){f.debug("SYSTEM","PID file unreadable \u2014 leaving it (cannot prove ownership)",{pidFilePath:r,error:o instanceof Error?o.message:String(o)});return}let s=e!==null&&n===e,i=n===null||!H(n);if(!s&&!(t&&i)){f.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:r,recordedPid:n,currentPid:e});return}try{(0,nt.rmSync)(r,{force:!0})}catch(o){o instanceof Error?f.debug("SYSTEM","Failed to remove PID file",{pidFilePath:r},o):f.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:r,error:String(o)})}}function bu(r,e){for(let{pid:t,startToken:n}of r)if(!(t===e||!H(t))){if(!Ee(t,n)){f.debug("SYSTEM","Skipping reap: PID was recycled during the grace window",{pid:t,rootPid:e});continue}try{process.kill(t,"SIGKILL"),f.debug("SYSTEM","Reaped orphaned descendant during shutdown cascade",{pid:t,rootPid:e})}catch(s){let i=s instanceof Error?s.code:void 0;i!=="ESRCH"&&f.warn("SYSTEM","Failed to reap orphaned descendant during shutdown cascade",{pid:t,rootPid:e,errno:i})}}}async function Zi(r,e){let{pid:t,pgid:n}=r;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(s){if((s instanceof Error?s.code:void 0)!=="ESRCH")throw s}if(e==="SIGKILL"){await oe(t,{signalMode:"immediate"});return}try{process.kill(t,e)}catch(s){if((s instanceof Error?s.code:void 0)!=="ESRCH")throw s}return}await oe(t)}A();var ro=3e4,st=null;function wu(){let e=wr().pruneDeadEntries();e>0&&f.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function no(){st===null&&(st=setInterval(wu,ro),st.unref(),f.debug("SYSTEM","Health checker started",{intervalMs:ro}))}function so(){st!==null&&(clearInterval(st),st=null,f.debug("SYSTEM","Health checker stopped"))}var io=require("child_process"),oo=require("util");A();var vu=(0,oo.promisify)(io.execFile),Au=/(?:^|\/)(?:uvx|uv|python[\d.]*)(?:\s|$).*chroma-mcp/;function Tu(r){let e=[];for(let t of r.split(`
17
+ `)){let n=t.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);n&&e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),command:n[3].trim()})}return e}async function Pu(){let r=await vu("ps",["-eo","pid=,ppid=,command="],{timeout:1e4,maxBuffer:33554432});return Tu(r.stdout)}function Iu(r,e){let t=r.filter(o=>Au.test(o.command)&&o.pid!==e.selfPid),n=new Set(t.map(o=>o.pid)),s=t.filter(o=>!n.has(o.ppid)),i=s.filter(o=>o.ppid===e.selfPid?!1:o.ppid===1?!0:!e.isAlive(o.ppid));return{matched:t,roots:s,orphans:i}}async function ao(r={}){let e=r.platform??process.platform,t={matched:0,trees:0,orphans:0,killed:0,failed:0,unregistered:0,skipped:null};if(e==="win32")return t.skipped="windows",t;let n=r.readTable??Pu,s=r.isAlive??H,i=r.killTree??(p=>oe(p,{signalMode:"graceful"})),o=r.selfPid??process.pid,a;try{a=await n()}catch(p){return f.warn("PROCESS","Orphaned chroma-mcp sweep skipped: cannot read the process table",{error:p instanceof Error?p.message:String(p)}),t.skipped="unreadable",t}let{matched:c,roots:l,orphans:u}=Iu(a,{isAlive:s,selfPid:o});if(t.matched=c.length,t.trees=l.length,t.orphans=u.length,u.length===0)return f.debug("PROCESS","No orphaned chroma-mcp trees found",{matched:t.matched,trees:t.trees}),t;f.warn("PROCESS","Reaping orphaned chroma-mcp trees left by dead workers",{orphans:u.length,roots:u.map(p=>p.pid)});let d=new Set,g=8;for(let p=0;p<u.length;p+=g){let h=u.slice(p,p+g);(await Promise.allSettled(h.map(E=>i(E.pid)))).forEach((E,_)=>{let b=h[_];E.status==="fulfilled"?(t.killed+=1,d.add(b.pid)):(t.failed+=1,f.warn("PROCESS","Failed to reap an orphaned chroma-mcp tree",{pid:b.pid,ppid:b.ppid,error:E.reason instanceof Error?E.reason.message:String(E.reason)}))})}if(r.registry)for(let p of r.registry.getAll())p.type==="chroma"&&d.has(p.pid)&&(r.registry.unregister(p.id),t.unregistered+=1);return f.info("PROCESS","Orphaned chroma-mcp sweep finished",{orphans:t.orphans,killed:t.killed,failed:t.failed,unregistered:t.unregistered}),t}U();var us=L.workerPid(),ds=class{registry;started=!1;stopPromise=null;signalHandlersRegistered=!1;shutdownInitiated=!1;shutdownHandler=null;constructor(e){this.registry=e}async start(){if(this.started)return;if(this.registry.initialize(),vr({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,ao({registry:this.registry}).catch(t=>{f.warn("PROCESS","Orphaned chroma-mcp sweep failed",{error:t instanceof Error?t.message:String(t)})}),no()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let t=async n=>{if(this.shutdownInitiated){f.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,f.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(s){s instanceof Error?f.error("SYSTEM","Error during shutdown",{},s):f.error("SYSTEM","Error during shutdown (non-Error)",{error:String(s)});try{await this.stop()}catch(i){i instanceof Error?f.debug("SYSTEM","Supervisor shutdown fallback failed",{},i):f.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(i)})}}process.exit(0)};process.on("SIGTERM",()=>{t("SIGTERM")}),process.on("SIGINT",()=>{t("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{f.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{t("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}so(),this.stopPromise=eo({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,t,n){this.registry.register(e,t,n)}unregisterProcess(e){this.registry.unregister(e)}getRegistry(){return this.registry}},$m=new ds(wr());function fs(){if(!(0,Se.existsSync)(us))return null;let r;try{r=JSON.parse((0,Se.readFileSync)(us,"utf-8"))}catch{return null}return r!==null&&br(r)?r:null}function vr(r={}){let e=r.pidFilePath??us;if(!(0,Se.existsSync)(e))return"missing";let t=null;try{t=JSON.parse((0,Se.readFileSync)(e,"utf-8"))}catch(s){return s instanceof Error?f.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},s):f.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(s)}),(0,Se.rmSync)(e,{force:!0}),"invalid"}return br(t)&&t?((r.logAlive??!0)&&f.info("SYSTEM","Worker already running (PID alive)",{existingPid:t.pid,existingPort:t.port,startedAt:t.startedAt}),"alive"):(f.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:t?.pid,port:t?.port,startedAt:t?.startedAt}),(0,Se.rmSync)(e,{force:!0}),"stale")}lr();var ps=require("path"),Tr=require("fs"),lo=require("crypto");U();var Ar=require("fs");et();function co(r,e){if(!(0,Ar.existsSync)(r))return e;try{return Ce((0,Ar.readFileSync)(r,"utf-8"))}catch(t){throw new Error(`Corrupt JSON file, refusing to overwrite: ${r}: ${t instanceof Error?t.message:String(t)}`)}}A();var uo="telemetry.json";function Ru(r){let e=r.DO_NOT_TRACK;return e===void 0||e===""?!1:e!=="0"&&e!=="false"}function Cu(r,e){if(Ru(r))return{enabled:!1,source:"DO_NOT_TRACK"};let t=r.CLAUDE_MEM_TELEMETRY?.toLowerCase();return t==="0"||t==="false"||t==="off"?{enabled:!1,source:"env"}:t==="1"||t==="true"||t==="on"?{enabled:!0,source:"env"}:e?.enabled===!0?{enabled:!0,source:"config"}:e?.enabled===!1?{enabled:!1,source:"config"}:{enabled:!0,source:"default"}}function Pr(r,e){return Cu(r,e).enabled}function fo(r){let e=r.CLAUDE_MEM_TELEMETRY_ERRORS?.toLowerCase();return!(e==="0"||e==="false"||e==="off")}function Mu(){return(0,ps.join)(Me(),uo)}function Rt(){let r;try{r=co(Mu(),null)}catch(e){let t=e instanceof Error?e:new Error(String(e));return f.warn("SYSTEM","Telemetry: corrupt telemetry.json; treating as no recorded consent",void 0,t),null}return!r||typeof r!="object"||typeof r.installId!="string"||r.enabled!==void 0&&typeof r.enabled!="boolean"?null:{enabled:r.enabled,installId:r.installId,decidedAt:typeof r.decidedAt=="string"?r.decidedAt:""}}function xu(r){let e=Me();(0,Tr.mkdirSync)(e,{recursive:!0}),(0,Tr.writeFileSync)((0,ps.join)(e,uo),JSON.stringify(r,null,2)+`
18
+ `)}function Ir(){let r=Rt();if(r?.installId)return r.installId;let e=(0,lo.randomUUID)();return xu({installId:e,decidedAt:""}),e}var Fu=new Set(["version","os","os_version","is_wsl","arch","runtime","runtime_version","node_version","duration_ms","outcome","error_category","locale","is_ci","endpoint","ide","provider","runtime_mode","trigger","count","has_summary","is_update","stage","install_method","interactive","bun_version","uv_version","claude_code_version","trial_days","trial_variant","offer_surface","funnel_source","observation_count","session_count","timeline_depth_days","has_session_summary","obs_type_bugfix","obs_type_discovery","obs_type_decision","obs_type_refactor","obs_type_other","tokens_injected","tokens_saved_vs_naive","mode","search_strategy","observation_type","hook","compression_ms","tokens_input","tokens_output","compression_ratio","model","cost_usd","endpoint_class","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs","result_count","chroma_available","fallback_reason","invalid_output_class","consecutive_invalid_outputs","respawn_triggered","abort_reason","previous_shutdown","previous_uptime_seconds","uptime_seconds","shutdown_reason","process_rss_mb","heap_used_mb","hook_type","error_mode","consecutive_failures","threshold_tripped","limit_window","overage_status","is_using_overage","resets_in_minutes","discovery_tokens","read_tokens","summary_count","prompt_count","project_count","backfilled","first_active_date","session_completed_count","session_failed_count","sessions_claude_count","sessions_codex_count","sessions_gemini_count","sessions_other_platform_count","subagent_obs_count","total_tokens_input","total_tokens_output","total_cost_usd","avg_duration_ms","avg_compression_ms","outcomes_ok","outcomes_error","outcomes_aborted","outcomes_invalid_output","top_model","observed_model","observed_billing","window_start_ts","rollup_reason","window_seq","total_tokens","avg_tokens","skill_id","skill_source","skill_trigger","observations_created","total_observations_injected","total_tokens_saved_vs_naive"]),po=200;function Ou(r,e){if(!(!r||typeof r!="object"))for(let t of Object.keys(r)){if(!Fu.has(t))continue;let n=r[t];typeof n=="string"?e[t]=n.length>po?n.slice(0,po):n:(typeof n=="number"&&Number.isFinite(n)||typeof n=="boolean")&&(e[t]=n)}}function Rr(r){let e={};try{Ou(r,e)}catch{}return e}var gs=pe(require("os"),1);A();var ku="13.24.13",Du="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",Lu="https://us.i.posthog.com";function Cr(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||Du}function Mr(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||Lu}var Nu=["version","os","os_version","is_wsl","arch","runtime","locale","ide","provider","runtime_mode","install_method","claude_code_version","first_active_date","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs"];function xr(r){let e={};for(let t of Nu)r[t]!==void 0&&(e[t]=r[t]);return e}function Uu(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||gs.default.release().toLowerCase().includes("microsoft")}catch(r){let e=r instanceof Error?r:new Error(String(r));return f.warn("SYSTEM","Telemetry: WSL detection failed; reporting is_wsl=false",void 0,e),!1}}function Fr(){return{version:ku,os:process.platform,os_version:gs.default.release(),is_wsl:Uu(),arch:process.arch,runtime:process.versions.bun?"bun":"node",runtime_version:process.versions.bun??process.versions.node,node_version:process.versions.node,is_ci:!!process.env.CI,locale:Intl.DateTimeFormat().resolvedOptions().locale}}var $u=2e3;async function go(r,e,t){try{if(!Pr(process.env,Rt()))return;let n=Rr({...Fr(),...e??{}});if(t?.person?n.$set=xr(n):n.$process_person_profile=!1,process.env.CLAUDE_MEM_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:r,properties:n})+`
19
+ `);return}let s=Cr(),i=new AbortController,o=setTimeout(()=>i.abort(),$u);try{await ju(s,r,n,i.signal)}finally{clearTimeout(o)}}catch{}}async function ju(r,e,t,n){await fetch(`${Mr()}/capture/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:r,event:e,distinct_id:Ir(),properties:t}),signal:n})}var Be=pe(require("path"),1),mo=require("os"),be=require("fs"),ms=require("child_process");A();A();A();U();var __=L.dataDir(),E_=L.workerPid();function ho(r){return r?/(^|[\\/])bun(\.exe)?$/i.test(r.trim()):!1}function Wu(r,e){let t=e==="win32"?`where ${r}`:`which ${r}`,n;try{n=(0,ms.execSync)(t,{stdio:["ignore","pipe","ignore"],encoding:"utf-8",windowsHide:!0})}catch(i){return i instanceof Error?f.debug("SYSTEM",`Binary lookup failed for ${r}`,{command:t},i):f.debug("SYSTEM",`Binary lookup failed for ${r}`,{command:t},new Error(String(i))),null}return n.split(/\r?\n/).map(i=>i.trim()).find(i=>i.length>0)||null}var hs;function _s(r={}){let e=Object.keys(r).length===0;if(e&&hs!==void 0)return hs;let t=Hu(r);return e&&t!==null&&(hs=t),t}function Hu(r){let e=r.platform??process.platform,t=r.execPath??process.execPath;if(ho(t))return t;let n=r.env??process.env,s=r.homeDirectory??(0,mo.homedir)(),i=r.pathExists??be.existsSync,o=r.lookupInPath??Wu,a=e==="win32"?[n.BUN,n.BUN_PATH,Be.default.join(s,".bun","bin","bun.exe"),Be.default.join(s,".bun","bin","bun"),n.USERPROFILE?Be.default.join(n.USERPROFILE,".bun","bin","bun.exe"):void 0,n.LOCALAPPDATA?Be.default.join(n.LOCALAPPDATA,"bun","bun.exe"):void 0,n.LOCALAPPDATA?Be.default.join(n.LOCALAPPDATA,"bun","bin","bun.exe"):void 0]:[n.BUN,n.BUN_PATH,Be.default.join(s,".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun","/usr/bin/bun","/snap/bin/bun"];for(let c of a){let l=c?.trim();if(l&&(ho(l)&&i(l)||l.toLowerCase()==="bun"))return l}return o("bun",e)}var _o=pe(require("net"),1);A();U();function Es(){return q.loadFromFile(tt).CLAUDE_MEM_WORKER_HOST}function Eo(r){return r.startsWith("[")&&r.endsWith("]")?r:r.includes(":")?`[${r}]`:r}var yo=5e3;async function Gu(r,e,t="GET"){let n=await fetch(`http://${Eo(Es())}:${r}${e}`,{method:t,signal:AbortSignal.timeout(yo)}),s="";try{s=await n.text()}catch{}return{ok:n.ok,statusCode:n.status,body:s}}async function So(r){if(process.platform==="win32")try{let e=await fetch(`http://${Eo(Es())}:${r}/api/health`,{signal:AbortSignal.timeout(yo)});if(e.ok)return!0;f.debug("SYSTEM","Windows health check returned non-ok; falling through to socket probe",{port:r,status:e.status})}catch(e){e instanceof Error?f.debug("SYSTEM","Windows health check threw; falling through to socket probe",{port:r,message:e.message}):f.debug("SYSTEM","Windows health check threw; falling through to socket probe",{port:r,error:String(e)})}return new Promise(e=>{let t=_o.default.createServer(),n=Es();t.once("error",s=>{s.code==="EADDRINUSE"?e(!0):e(!1)}),t.once("listening",()=>{t.close(()=>e(!1))}),t.listen(r,n)})}async function Ku(r){try{let e=await Gu(r,"/api/health");return e.ok?JSON.parse(e.body).version:null}catch{return f.debug("SYSTEM","Could not fetch worker version",{}),null}}async function bo(r,e){let t=e??"unknown",n=await Ku(r);return!n||t==="unknown"?{matches:!0,pluginVersion:t,workerVersion:n}:{matches:t===n,pluginVersion:t,workerVersion:n}}A();var Or=require("path"),z=require("fs");U();A();var Vu=9e4;function wo(){return(0,Or.join)(Me(),"spawn.lock")}function ys(){let r=wo(),e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let t=0;t<2;t++)try{return(0,z.mkdirSync)((0,Or.dirname)(r),{recursive:!0}),(0,z.writeFileSync)(r,e,{flag:"wx"}),!0}catch(n){let s=n instanceof Error?n:new Error(String(n)),i=s.code;if(i!=="EEXIST")return f.warn("SYSTEM","Spawn lock write failed for a non-contention reason; failing open (spawning unlocked)",{lockPath:r,code:i},s),!0;if(t>0)return!1;let o;try{o=(0,z.statSync)(r).mtimeMs}catch{continue}if(Date.now()-o<=Vu)return!1;let a;try{a=(0,z.statSync)(r).mtimeMs}catch{continue}if(a!==o)return!1;try{(0,z.unlinkSync)(r)}catch{return!1}}return!1}function Ss(){let r=wo();try{if(JSON.parse((0,z.readFileSync)(r,"utf-8")).pid!==process.pid)return;(0,z.unlinkSync)(r)}catch{}}et();function Ro(r,e,t){let n=process.env[r];if(n){let s=parseInt(n,10);if(Number.isFinite(s)&&s>=t.min&&s<=t.max)return s;f.warn("SYSTEM",`Invalid ${r}, using default`,{value:n,min:t.min,max:t.max})}return e}var Br=Ro("CLAUDE_MEM_HEALTH_TIMEOUT_MS",Fe(V.HEALTH_CHECK),{min:500,max:3e5}),qu=Ro("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",Fe(V.HOOK_READINESS_WAIT),{min:0,max:3e5}),zu={min:500,max:3e5};function Co(r=process.env){let e=r.CLAUDE_MEM_FETCH_VERBOSE;if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="on"||t==="yes"}function Yu(r){return Co()?{...r,verbose:!0}:r}function Ju(r){let e={},t=r;for(let n=0;t&&n<4;n++){let s=n===0?"error":`cause${n}`;if(t instanceof Error){let i=t;e[s]={name:t.name,message:t.message,...i.code!==void 0?{code:i.code}:{}},t=t.cause;continue}e[s]=String(t);break}return e}function Xu(r,e,t){let n=typeof e.method=="string"?e.method:"GET",s=Ju(t),i=JSON.stringify(s);f.warn("SYSTEM","Worker IPC fetch failed",{url:r,method:n},i),Re(`[claude-mem] fetch verbose: ${n} ${r} ${i}
20
+ `)}async function Mo(r,e={}){let t=Yu(e);try{return await fetch(r,t)}catch(n){throw Co()&&Xu(r,e,n),n}}async function vs(r,e={},t){try{return await Mo(r,{...e,signal:AbortSignal.timeout(t)})}catch(n){throw n instanceof DOMException&&n.name==="TimeoutError"?new Error(`Request timed out after ${t}ms`):n}}var kr=null,Dr=null,Lr=null,Nr=null;function Qu(){return k.default.join(q.get("CLAUDE_MEM_DATA_DIR"),"settings.json")}function As(){return Lr!==null||(Lr=q.loadFromFile(Qu())),Lr}function vo(r,e){if(!r)return null;let t=parseInt(r,10);return Number.isFinite(t)&&t>=e.min&&t<=e.max?t:null}function Zu(r,e,t){let n=process.env[r];if(n!==void 0){let o=vo(n,t);return o!==null?o:(f.warn("SYSTEM",`Invalid ${r}, using default`,{value:n,min:t.min,max:t.max}),e)}let s=As()[r],i=vo(s,t);return i!==null?i:(f.warn("SYSTEM",`Invalid ${r} in settings.json, using default`,{value:s,min:t.min,max:t.max}),e)}function We(){if(kr!==null)return kr;let r=As();return kr=parseInt(r.CLAUDE_MEM_WORKER_PORT,10),kr}function ed(){return Dr!==null||(Dr=As().CLAUDE_MEM_WORKER_HOST),Dr}function td(){return Nr!==null||(Nr=Zu("CLAUDE_MEM_API_TIMEOUT_MS",Fe(V.API_REQUEST),zu)),Nr}function rd(r){return r.startsWith("[")&&r.endsWith("]")?r:r.includes(":")?`[${r}]`:r}function nd(r){return`http://${rd(ed())}:${We()}${r}`}function we(r,e={}){let t=e.method??"GET",n=e.timeoutMs??td(),s=nd(r),i={method:t};return e.headers&&(i.headers=e.headers),e.body&&(i.body=e.body),n>0?vs(s,i,n):Mo(s,i)}async function sd(){return(await we("/api/health",{timeoutMs:Br})).ok}async function ws(r=Br){return(await we("/api/readiness",{timeoutMs:r})).ok}function xo(r){let e=(0,x.existsSync)(k.default.join(r,"plugin","scripts"))?k.default.join(r,"plugin"):r;return k.default.join(e,"scripts","worker-service.cjs")}function id(r,e){let t=d=>{let g=d.split("-")[0].split(".");return[parseInt(g[0],10)||0,parseInt(g[1],10)||0,parseInt(g[2],10)||0]},[n,s,i]=t(r),[o,a,c]=t(e);if(o!==n)return o-n;if(a!==s)return a-s;if(c!==i)return c-i;let l=r.includes("-")?1:0,u=e.includes("-")?1:0;return l!==u?l-u:r<e?1:r>e?-1:0}function od(r=k.default.join(k.default.dirname(k.default.dirname(dr)),"cache","thedotmack","claude-mem")){try{return(0,x.readdirSync)(r).filter(e=>/^\d/.test(e)).map(e=>k.default.join(r,e)).filter(e=>{try{if(!(0,x.statSync)(e).isDirectory())return!1}catch{return!1}return!(0,x.existsSync)(k.default.join(e,".orphaned_at"))}).map(e=>({scriptPath:xo(e),version:k.default.basename(e)}))}catch{return[]}}function Ao(r){try{let e=JSON.parse((0,x.readFileSync)(r,"utf-8"));return typeof e.version=="string"?e.version:null}catch(e){let t=e.code;return t!=="ENOENT"&&f.debug("SYSTEM","Could not read package version for worker resolution",{packageJsonPath:r,code:t}),null}}function Fo(){let r=process.env.CLAUDE_MEM_WORKER_SCRIPT_PATH?.trim();if(r){if((0,x.existsSync)(r))return{scriptPath:r,version:null};f.debug("SYSTEM","Ignoring missing CLAUDE_MEM_WORKER_SCRIPT_PATH override",{override:r})}let e=[...od(),{scriptPath:xo(k.default.join(dr,"plugin")),version:Ao(k.default.join(dr,"package.json"))},{scriptPath:k.default.join(process.cwd(),"plugin","scripts","worker-service.cjs"),version:Ao(k.default.join(process.cwd(),"package.json"))}];return ad(e)}function ad(r){let e=r.filter(t=>(0,x.existsSync)(t.scriptPath));return e.length===0?null:(e.sort((t,n)=>t.version===null&&n.version===null?0:t.version===null?1:n.version===null?-1:id(t.version,n.version)),e[0])}function cd(){return Fo()?.scriptPath??null}async function ld(r){let e=r.backoffMs;for(let t=1;t<=r.attempts;t++){if(await ko())return!0;t<r.attempts&&(await new Promise(n=>setTimeout(n,e)),e*=2)}return!1}async function bs(r=qu){if(r<=0)try{return await ws()}catch(t){let n=t instanceof Error?t:new Error(String(t));return f.debug("SYSTEM","Worker readiness check threw",{},n),!1}let e=Date.now();for(;Date.now()-e<r;){try{if(await ws())return!0}catch(n){f.debug("SYSTEM","Worker readiness check threw",{error:n instanceof Error?n.message:String(n)})}let t=r-(Date.now()-e);if(t<=0)break;await new Promise(n=>setTimeout(n,Math.min(250,t)))}return!1}async function ud(){try{let e=await(await we("/api/health",{timeoutMs:Br})).json();return typeof e.version=="string"?e.version:null}catch(r){let e=r instanceof Error?r:new Error(String(r));return f.debug("SYSTEM","Worker health-version fetch failed",{},e),null}}async function dd(r=5e3){let e=Date.now();for(;;){try{await we("/api/health",{timeoutMs:Br})}catch{return!0}if(Date.now()-e>=r)return!1;await new Promise(t=>setTimeout(t,200))}}function fd(r,e){if(!r)return null;try{let t=(0,x.statSync)(r.scriptPath);return JSON.stringify([r.scriptPath,e,t.size,t.mtimeMs,t.ctimeMs])}catch{return null}}function Oo(){return k.default.join(Me(),"worker-version-recycle.json")}function pd(r,e){if(r===null||e===null)return!1;try{let t=JSON.parse((0,x.readFileSync)(Oo(),"utf-8"));return t?.buildKey===r&&t?.workerVersion===e}catch{return!1}}async function To(r,e=null){let t=await ud();if(t!==null&&t!==r){if(e!==null)try{Ze(Oo(),{buildKey:e,workerVersion:t})}catch(n){f.warn("SYSTEM","Could not persist the failed worker version recycle",{error:n instanceof Error?n.message:String(n)})}f.warn("SYSTEM","Worker is ready but still reports a stale version; rebuild or reinstall the worker bundle before retrying",{pluginVersion:r,workerVersion:t})}}async function ko(){let r;try{r=await sd()}catch(t){return f.debug("SYSTEM","Worker health check threw",{error:t instanceof Error?t.message:String(t)}),!1}if(!r)return!1;let e=vr({logAlive:!1});return e==="missing"||e==="alive"}async function Wr(){let r=Fo(),e=null,t=null;if(await ko()){let{matches:a,pluginVersion:c,workerVersion:l}=await bo(We(),r?.version??null);if(c!=="unknown"&&(e=c),a)return await bs()?(e!==null&&await To(e),!0):(f.warn("SYSTEM","Worker is healthy but not ready; skipping hook API call"),!1);if(t=fd(r,c),pd(t,l))return f.warn("SYSTEM","Skipping repeated worker recycle: the unchanged bundle still reports a stale version; rebuild or reinstall it",{pluginVersion:c,workerVersion:l,scriptPath:r?.scriptPath}),bs();f.info("SYSTEM","Worker version mismatch \u2014 killing stale worker",{pluginVersion:c,workerVersion:l});let u=fs();if(u===null||u.port!==We())return f.error("SYSTEM","Stale worker is serving the port but the PID file does not identify it; kill the claude-mem worker process manually",{port:We(),pidFilePid:u?.pid??null,pidFilePort:u?.port??null}),!1;try{await oe(u.pid,{signalMode:"immediate"})}catch(d){return f.error("SYSTEM","Could not kill stale worker",{pid:u.pid,port:u.port},d instanceof Error?d:new Error(String(d))),!1}if(!await dd())return f.error("SYSTEM","Stale worker port still open after SIGKILL; skipping spawn this hook event",{pid:u.pid,port:We()}),!1}let n=_s(),s=r?.scriptPath??null;if(!n)return f.warn("SYSTEM","Cannot lazy-spawn worker: Bun runtime not found on PATH"),!1;if(!s)return f.warn("SYSTEM","Cannot lazy-spawn worker: worker-service.cjs not found in plugin/scripts"),!1;let i=ys();try{if(i){f.info("SYSTEM","Worker not running \u2014 lazy-spawning",{runtimePath:n,scriptPath:s});try{Tt(n,[s,"--daemon"],{detached:!0,stdio:["ignore","ignore","ignore"]}).unref()}catch(c){return c instanceof Error?f.error("SYSTEM","Lazy-spawn of worker failed",{runtimePath:n,scriptPath:s},c):f.error("SYSTEM","Lazy-spawn of worker failed (non-Error)",{runtimePath:n,scriptPath:s,error:String(c)}),!1}}else f.info("SYSTEM","Another launcher holds the spawn lock \u2014 skipping lazy-spawn and waiting for its worker");if(!await ld({attempts:6,backoffMs:500}))return f.warn("SYSTEM",i?"Worker port did not open after lazy-spawn within the cold-boot wait (~15s)":"Spawn-lock holder's worker port did not open within the cold-boot wait (~15s)"),fs()===null&&await So(We())&&(jr=We(),f.error("SYSTEM","Worker port is occupied by an unreachable process that no PID file claims (likely an orphaned OS socket); every lazy-spawn on this port will be silently refused",{port:jr,fix:Do})),!1}finally{i&&Ss()}return await bs()?(e!==null&&await To(e,t),!0):(f.warn("SYSTEM","Worker lazy-spawned but did not become ready before hook readiness timeout"),!1)}var Do="Set CLAUDE_MEM_WORKER_PORT to a different port in claude-mem settings, or reboot to release the stuck port",jr=null,Ur=null;async function gd(){return Ur!==null||(Ur=await Wr()),Ur}async function hd(r){let e=Date.now()+r,t=async()=>{let o=e-Date.now();if(o<=0)return!1;try{return await ws(Math.min(500,o))}catch{return!1}};if(await t())return!0;let n=_s(),s=cd();if(!n||!s)return!1;let i=ys();try{for(i&&Tt(n,[s,"--daemon"],{detached:!0,stdio:["ignore","ignore","ignore"]}).unref();Date.now()<e;){if(await t())return!0;let o=e-Date.now();o>0&&await new Promise(a=>setTimeout(a,Math.min(100,o)))}return!1}catch(o){return f.debug("SYSTEM","Bounded worker startup failed",{error:o instanceof Error?o.message:String(o)}),!1}finally{i&&Ss()}}var md=3;function Lo(){return k.default.join(M,"state")}function No(){return k.default.join(Lo(),"hook-failures.json")}function _d(r){let e=JSON.parse(r);return{consecutiveFailures:typeof e.consecutiveFailures=="number"&&Number.isFinite(e.consecutiveFailures)?Math.max(0,Math.floor(e.consecutiveFailures)):0,lastFailureAt:typeof e.lastFailureAt=="number"&&Number.isFinite(e.lastFailureAt)?e.lastFailureAt:0}}function Uo(){try{return _d((0,x.readFileSync)(No(),"utf-8"))}catch{return{consecutiveFailures:0,lastFailureAt:0}}}function $o(r){let e=Lo(),t=No(),n=`${t}.tmp`;try{(0,x.existsSync)(e)||(0,x.mkdirSync)(e,{recursive:!0}),(0,x.writeFileSync)(n,JSON.stringify(r),"utf-8"),(0,x.renameSync)(n,t)}catch(s){f.debug("SYSTEM","Failed to persist hook-failure counter",{error:s instanceof Error?s.message:String(s)})}}function Ed(){try{let e=_e().CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD,t=parseInt(e,10);if(Number.isFinite(t)&&t>=1)return t}catch{}return md}var Po=null;async function yd(){let e={consecutiveFailures:Uo().consecutiveFailures+1,lastFailureAt:Date.now()};$o(e);let t=Ed();return e.consecutiveFailures>=t&&(e.consecutiveFailures===t&&await go("hook_failed",{...Po!==null?{hook_type:Po}:{},error_mode:"worker_unavailable",consecutive_failures:e.consecutiveFailures,threshold_tripped:!0}),Di(jr!==null?`claude-mem worker unreachable for ${e.consecutiveFailures} consecutive hooks: port ${jr} is held by an unreachable process that no PID file claims, so the worker cannot bind it. ${Do}.`:`claude-mem worker unreachable for ${e.consecutiveFailures} consecutive hooks.`)),e.consecutiveFailures}function Io(){Uo().consecutiveFailures!==0&&$o({consecutiveFailures:0,lastFailureAt:0})}var $r=Symbol.for("claude-mem/worker-fallback");function Hr(r){return typeof r=="object"&&r!==null&&r[$r]===!0}async function Gr(r,e,t,n={}){let s=n.workerStartupTimeoutMs!==void 0;if(!(s?await hd(n.workerStartupTimeoutMs):await gd()))return s||await yd(),{continue:!0,reason:"worker_unreachable",[$r]:!0};let o={method:e};t!==void 0&&(o.headers={"Content-Type":"application/json"},o.body=JSON.stringify(t)),n.timeoutMs!==void 0&&(o.timeoutMs=n.timeoutMs);let a;try{a=await we(r,o)}catch(l){if(!s)throw l;return f.debug("SYSTEM","Worker unavailable for best-effort hook call",{error:l instanceof Error?l.message:String(l)}),{continue:!0,reason:"worker_unreachable",[$r]:!0}}if(!a.ok){let l=await a.text().catch(()=>"");if(Io(),a.status===429||a.status>=500)return f.warn("SYSTEM",`Worker API ${e} ${r} returned ${a.status}; skipping hook API call`,{body:l.substring(0,200)}),{continue:!0,reason:`worker_api_${a.status}`,[$r]:!0};let u=l;try{u=JSON.parse(l)}catch{}return u}Io();let c=await a.text();if(c.length!==0)try{return JSON.parse(c)}catch{return c}}var Bo=pe(require("path"),1),Wo=require("child_process");wt();A();var Kr=require("fs"),it=pe(require("path"),1);A();var Ct={isWorktree:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null};function jo(r){let e=it.default.join(r,".git"),t;try{t=(0,Kr.statSync)(e)}catch(u){return u instanceof Error&&u.code!=="ENOENT"&&f.warn("GIT","Unexpected error checking .git",{error:u instanceof Error?u.message:String(u)}),Ct}if(!t.isFile())return Ct;let n;try{n=(0,Kr.readFileSync)(e,"utf-8").trim()}catch(u){return f.warn("GIT","Failed to read .git file",{error:u instanceof Error?u.message:String(u)}),Ct}let s=n.match(/^gitdir:\s*(.+)$/);if(!s)return Ct;let o=it.default.resolve(it.default.dirname(e),s[1]).match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(!o)return Ct;let a=o[1],c=it.default.basename(r),l=it.default.basename(a);return{isWorktree:!0,worktreeName:c,parentRepoPath:a,parentProjectName:l}}function Ho(r){try{return(0,Wo.execFileSync)("git",["rev-parse","--show-toplevel"],{cwd:r,encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0}).trim()||null}catch(e){let t=e instanceof Error?e:new Error(String(e));return f.debug("PROJECT_NAME","git rev-parse failed, falling back to basename",{dir:r},t),null}}function Sd(r,e=process.platform){if(!r||r.trim()==="")return f.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:r}),"unknown-project";let t=ie(r,e),s=Ho(t)??t,i=Bo.default.basename(s);if(i===""){if(process.platform==="win32"){let a=r.match(/^([A-Z]):\\/i);if(a){let l=`drive-${a[1].toUpperCase()}`;return f.info("PROJECT_NAME","Drive root detected",{cwd:r,projectName:l}),l}}return f.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:r}),"unknown-project"}return i}function He(r,e=process.platform){let t=Sd(r,e);if(!r)return{primary:t,parent:null,isWorktree:!1,allProjects:[t]};let n=ie(r,e),s=jo(Ho(n)??n);if(s.isWorktree&&s.parentProjectName){let i=`${s.parentProjectName}/${t}`;return{primary:i,parent:s.parentProjectName,isWorktree:!0,allProjects:[s.parentProjectName,i]}}return{primary:t,parent:null,isWorktree:!1,allProjects:[t]}}A();var Ge=require("path");var Go=require("path");wt();A();function bd(r){let e=ie(r.replace(/\\/g,"/"));e=e.replace(/\\/g,"/");let t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return t=t.replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/<<<GLOBSTAR>>>/g,".*"),new RegExp(`^${t}$`)}function Vr(r,e){if(!e||!e.trim())return!1;let t=r.replace(/\\/g,"/"),n=(0,Go.basename)(t),s=e.split(",").map(i=>i.trim()).filter(Boolean);for(let i of s)try{let o=bd(i);if(o.test(t)||o.test(n))return!0}catch(o){f.warn("PROJECT_NAME","Invalid exclusion pattern",{pattern:i,error:o instanceof Error?o.message:String(o)});continue}return!1}U();function wd(r,e){let t=(0,Ge.normalize)(r),n=(0,Ge.normalize)(e);if(t===n)return!0;let s=(0,Ge.relative)(n,t);return s.length>0&&!s.startsWith("..")&&!(0,Ge.isAbsolute)(s)}function qr(r){if(process.env.CLAUDE_MEM_INTERNAL==="1")return!1;if(!r)return!0;if(wd(r,Xn))return!1;let e=_e();return!Vr(r,e.CLAUDE_MEM_EXCLUDED_PROJECTS)}var Ko="claude";function vd(r){return r.trim().toLowerCase().replace(/\s+/g,"-")}function ae(r){if(!r)return Ko;let e=vd(r);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:Ko}A();var zo=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],Vo=new RegExp(`<(${zo.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`,"g");var qo=100;function Ad(r){let e=Object.fromEntries(zo.map(s=>[s,0]));Vo.lastIndex=0;let t=0,n=r.replace(Vo,(s,i)=>(e[i]=(e[i]??0)+1,t+=1,""));return t>qo&&f.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:t,maxAllowed:qo,contentLength:r.length}),{stripped:n.trim(),counts:e}}function Ts(r){return Ad(r).stripped}var Td=["task-notification"],Pd=new RegExp(`^\\s*<(${Td.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),Id=256*1024;function Yo(r){return!r||r.length>Id?!1:Pd.test(r)}A();var Rd=Fe(V.API_REQUEST),ve=class extends Error{kind;status;cause;constructor(e,t,n={}){super(t),this.name="ServerClientError",this.kind=e,this.status=n.status??null,this.cause=n.cause}isFallbackEligible(){return this.kind==="transport"||this.kind==="timeout"||this.kind==="missing_api_key"||this.kind==="http_error"&&(this.status!==null&&this.status>=500||this.status===429)}},zr=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=Cd(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??Rd}async startSession(e){let t=this.buildStartSessionPayload(e);return this.request("POST","/v1/sessions/start",t)}async recordEvent(e){let t=this.buildEventPayload(e),n=e.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",n,t)}async endSession(e){if(!e.sessionId)throw new ve("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(e.sessionId)}/end`,{})}async addObservation(e){return this.request("POST","/v1/memories",this.buildAddObservationPayload(e))}async searchObservations(e){return this.request("POST","/v1/search",this.buildSearchPayload(e))}async contextObservations(e){return this.request("POST","/v1/context",this.buildSearchPayload(e))}async getJobStatus(e){if(!e)throw new ve("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(e)}`)}buildAddObservationPayload(e){let t=e.content,n=e.kind??"manual",s=typeof e.metadata?.title=="string"?e.metadata.title:void 0;return{projectId:e.projectId,kind:n,type:n,narrative:t,...s?{title:s}:{},...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.platformSource!==void 0?{platformSource:e.platformSource}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildSearchPayload(e){return{projectId:e.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:Ps(e.platformSource)}:{}}}buildStartSessionPayload(e){return{projectId:e.projectId,...e.externalSessionId!==void 0?{externalSessionId:e.externalSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.agentId!==void 0?{agentId:e.agentId}:{},...e.agentType!==void 0?{agentType:e.agentType}:{},...e.platformSource!==void 0?{platformSource:Ps(e.platformSource)}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildEventPayload(e){return{projectId:e.projectId,sourceType:e.sourceType,eventType:e.eventType,occurredAtEpoch:e.occurredAtEpoch,...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.memorySessionId!==void 0?{memorySessionId:e.memorySessionId}:{},...e.platformSource!==void 0?{platformSource:Ps(e.platformSource)}:{},...e.payload!==void 0?{payload:e.payload}:{}}}async request(e,t,n){if(!this.apiKey||!this.apiKey.trim())throw new ve("missing_api_key","Server API key is not configured (CLAUDE_MEM_SERVER_API_KEY).");let s=`${this.baseUrl}${t}`,i={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(i.body=JSON.stringify(n));let o;try{o=await vs(s,i,this.timeoutMs)}catch(c){let l=c instanceof Error?c.message:String(c),u=/timed out|timeout/i.test(l);throw new ve(u?"timeout":"transport",`Server ${e} ${t} failed: ${l}`,{cause:c})}if(!o.ok){let c=await o.text().catch(()=>"");throw new ve("http_error",`Server ${e} ${t} returned ${o.status}: ${Md(c,200)}`,{status:o.status})}let a=await o.text();if(!a||a.length===0)return{};try{return JSON.parse(a)}catch(c){let l=c instanceof Error?c:new Error(String(c));throw new ve("invalid_response",`Server ${e} ${t} returned non-JSON response`,{cause:l})}}};function Jo(r){return r instanceof ve}function Cd(r){return r.replace(/\/+$/,"")}function Ps(r){return typeof r=="string"?ae(r):null}function Md(r,e){return r.length<=e?r:`${r.slice(0,e)}\u2026`}function xd(){let e=(_e().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function Fd(){let r=_e(),e=(...o)=>{for(let a of o){let c=(a??"").trim();if(c.length>0)return c}return""},t=e(r.CLAUDE_MEM_SERVER_URL,r.CLAUDE_MEM_SERVER_BETA_URL),n=e(r.CLAUDE_MEM_SERVER_API_KEY,r.CLAUDE_MEM_SERVER_BETA_API_KEY),s=e(r.CLAUDE_MEM_SERVER_PROJECT_ID,r.CLAUDE_MEM_SERVER_BETA_PROJECT_ID);if(!t)return f.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!n)return f.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!s)return f.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let i={serverBaseUrl:t,apiKey:n};return{runtime:"server",client:new zr(i),projectId:s,serverBaseUrl:t}}function Xo(){if(xd()!=="server")return{runtime:"worker"};let r=Fd();return r||{runtime:"worker"}}function Qo(r,e){f.warn("HOOK",`[server-fallback] reason=${r}`,e??{})}var Od={executeWithWorkerFallback:Gr,isWorkerFallback:Hr,loadFromFileOnce:_e,resolveRuntimeContext:Xo,logServerFallback:Qo,shouldTrackProject:qr},ke=Od;var Zo={async execute(r){let{sessionId:e,prompt:t}=r,n=r.cwd??process.cwd();if(!e)return f.warn("HOOK","session-init: No sessionId provided, skipping (Codex CLI or unknown platform)"),{continue:!0,suppressOutput:!0,exitCode:xe.SUCCESS};if(!ke.shouldTrackProject(n))return f.info("HOOK","Project excluded from tracking",{cwd:n}),{continue:!0,suppressOutput:!0};if(t&&Yo(t))return f.debug("HOOK","session-init: skipping internal protocol payload",{preview:t.slice(0,80)}),{continue:!0,suppressOutput:!0};let s=!t||!t.trim()?"[media prompt]":t,i=He(n).primary,o=ae(r.platform),a=ke.loadFromFileOnce(),c=String(a.CLAUDE_MEM_SEMANTIC_INJECT).toLowerCase()==="true",l=ke.resolveRuntimeContext();if(l.runtime==="server")try{return await kd(l,r,e,o,i,s),{continue:!0,suppressOutput:!0}}catch(h){if(Jo(h)&&h.isFallbackEligible())ke.logServerFallback(h.kind,{status:h.status,message:h.message,route:"/v1/sessions/start"});else return f.error("HOOK","Server session-start failed (non-recoverable)",{error:h instanceof Error?h.message:String(h)}),{continue:!0,suppressOutput:!0,exitCode:xe.SUCCESS}}f.debug("HOOK","session-init: Calling /api/sessions/init",{contentSessionId:e,project:i});let u=await ke.executeWithWorkerFallback("/api/sessions/init","POST",{contentSessionId:e,project:i,prompt:s,platformSource:o},o==="codex"?{workerStartupTimeoutMs:V.POST_SPAWN_WAIT,timeoutMs:2e3}:void 0);if(ke.isWorkerFallback(u))return{continue:!0,suppressOutput:!0,exitCode:xe.SUCCESS};if(typeof u?.sessionDbId!="number")return f.failure("HOOK","Session initialization returned malformed response",{contentSessionId:e,project:i}),{continue:!0,suppressOutput:!0,exitCode:xe.SUCCESS};let d=u.sessionDbId,g=u.promptNumber;if(f.debug("HOOK","session-init: Received from /api/sessions/init",{sessionDbId:d,promptNumber:g,skipped:u.skipped,contextInjected:u.contextInjected}),f.debug("HOOK",`[ALIGNMENT] Hook Entry | contentSessionId=${e} | prompt#=${g} | sessionDbId=${d}`),u.skipped&&u.reason==="private")return f.info("HOOK",`INIT_COMPLETE | sessionDbId=${d} | promptNumber=${g} | skipped=true | reason=private`,{sessionId:d}),{continue:!0,suppressOutput:!0};let p="";if(c&&s&&s.length>=20&&s!=="[media prompt]"){let h=a.CLAUDE_MEM_SEMANTIC_INJECT_LIMIT||"5",m=await ke.executeWithWorkerFallback("/api/context/semantic","POST",{q:s,project:i,limit:h,platformSource:o},o==="codex"?{workerStartupTimeoutMs:V.POST_SPAWN_WAIT,timeoutMs:2e3}:void 0);!ke.isWorkerFallback(m)&&m?.context&&(f.debug("HOOK",`Semantic injection: ${m.count} observations for prompt`,{sessionId:d,count:m.count}),p=m.context)}return f.info("HOOK",`INIT_COMPLETE | sessionDbId=${d} | promptNumber=${g} | project=${i}`,{sessionId:d}),p?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:p}}:{continue:!0,suppressOutput:!0}}};async function kd(r,e,t,n,s,i){await r.client.startSession({projectId:r.projectId,externalSessionId:t,contentSessionId:t,agentId:e.agentId??null,agentType:e.agentType??null,platformSource:n,metadata:{project:s,prompt:i}}),f.info("HOOK","session-init: server session started",{contentSessionId:t,project:s})}A();var ea={async execute(r){let{sessionId:e,cwd:t,filePath:n,edits:s}=r,i=ae(r.platform);if(!n)throw new Error("fileEditHandler requires filePath");if(f.dataIn("HOOK",`FileEdit: ${n}`,{editCount:s?.length??0}),!t)throw new Error(`Missing cwd in FileEdit hook input for session ${e}, file ${n}`);if(!qr(t))return f.debug("HOOK","Project excluded from tracking, skipping file edit observation",{cwd:t,filePath:n}),{continue:!0,suppressOutput:!0,exitCode:xe.SUCCESS};let o=await Gr("/api/sessions/observations","POST",{contentSessionId:e,platformSource:i,tool_name:"write_file",tool_input:{filePath:n,edits:s},tool_response:{success:!0},cwd:t});return Hr(o)?{continue:!0,suppressOutput:!0,exitCode:xe.SUCCESS}:(f.debug("HOOK","File edit observation sent successfully",{filePath:n}),{continue:!0,suppressOutput:!0})}};U();A();var te=require("fs"),Yr=require("path");A();A();U();var XE=L.settings();function ta(r,e){let t="<claude-mem-context>",n="</claude-mem-context>";if(!r)return`${t}
21
21
  ${e}
22
22
  ${n}`;let s=r.indexOf(t),i=r.indexOf(n);return s!==-1&&i!==-1?r.substring(0,s)+`${t}
23
23
  ${e}
@@ -25,16 +25,16 @@ ${n}`+r.substring(i+n.length):r+`
25
25
 
26
26
  ${t}
27
27
  ${e}
28
- ${n}`}A();function ra(r,e){if(!r)return;let t=(0,zr.resolve)(r);if(t.includes("/.git/")||t.includes("\\.git\\")||t.endsWith("/.git")||t.endsWith("\\.git"))return;let n=(0,zr.dirname)(r);(0,te.existsSync)(n)||(0,te.mkdirSync)(n,{recursive:!0});let s="";(0,te.existsSync)(r)&&(s=(0,te.readFileSync)(r,"utf-8"));let i=`# Memory Context
28
+ ${n}`}A();function ra(r,e){if(!r)return;let t=(0,Yr.resolve)(r);if(t.includes("/.git/")||t.includes("\\.git\\")||t.endsWith("/.git")||t.endsWith("\\.git"))return;let n=(0,Yr.dirname)(r);(0,te.existsSync)(n)||(0,te.mkdirSync)(n,{recursive:!0});let s="";(0,te.existsSync)(r)&&(s=(0,te.readFileSync)(r,"utf-8"));let i=`# Memory Context
29
29
 
30
- ${e}`,o=ta(s,i),a=`${r}.tmp`;try{(0,te.writeFileSync)(a,o),(0,te.renameSync)(a,r)}catch(c){f.error("AGENTS_MD","Failed to write AGENTS.md",{agentsPath:r},c instanceof Error?c:new Error(String(c)))}}A();function Dd(r){let e=r.trim().replace(/^\$\.?/,"");if(!e)return[];let t=[],n=e.split(".");for(let s of n){let i=/([^[\]]+)|\[(\d+)\]/g,o;for(;(o=i.exec(s))!==null;)o[1]?t.push(o[1]):o[2]&&t.push(parseInt(o[2],10))}return t}function Rs(r,e){if(!e)return;let t=Dd(e),n=r;for(let s of t){if(n==null)return;n=n[s]}return n}function na(r){return r==null||r===""}function sa(r,e){if(r.startsWith("$watch.")){let t=r.slice(7);return e.watch[t]}if(r.startsWith("$schema.")){let t=r.slice(8);return e.schema[t]}if(r.startsWith("$session.")){let t=r.slice(9);return e.session?e.session[t]:void 0}if(r==="$cwd")return e.watch.workspace;if(r==="$project")return e.watch.project}function ot(r,e,t){if(r!==void 0){if(typeof r=="string"){let n=sa(r,t);return n!==void 0?n:Rs(e,r)}if(r.coalesce&&Array.isArray(r.coalesce))for(let n of r.coalesce){let s=ot(n,e,t);if(!na(s))return s}if(r.path){let n=sa(r.path,t);if(n!==void 0)return n;let s=Rs(e,r.path);if(!na(s))return s}if(r.value!==void 0)return r.value;if(r.default!==void 0)return r.default}}function ia(r,e,t){let n={};if(!r)return n;for(let[s,i]of Object.entries(r))n[s]=ot(i,e,t);return n}function oa(r,e,t){if(!e)return!0;let n=e.path||t.eventTypePath||"type",s=n?Rs(r,n):void 0,i=s==null||s==="";if(e.exists!==void 0&&(e.exists&&i||!e.exists&&!i)||e.equals!==void 0&&s!==e.equals||e.not_equals!==void 0&&s===e.not_equals||e.in&&Array.isArray(e.in)&&!e.in.includes(s)||e.not_in&&Array.isArray(e.not_in)&&e.not_in.includes(s)||e.contains!==void 0&&(typeof s!="string"||!s.includes(e.contains))||e.not_contains!==void 0&&typeof s=="string"&&s.includes(e.not_contains))return!1;if(e.regex)try{if(!new RegExp(e.regex).test(String(s??"")))return!1}catch(o){return f.debug("WORKER","Invalid regex in match rule",{regex:e.regex},o instanceof Error?o:void 0),!1}return!0}A();U();A();var Yr=class{static checkUserPromptPrivacy(e,t,n,s,i,o){let a=e.getUserPrompt(t,n,i);return a===null?(f.warn("HOOK",`${s}: no user_prompts row for prompt #${n} \u2014 ingesting anyway (session-init likely raced worker boot; see #2794/#2795)`,{sessionId:i,contentSessionId:t,promptNumber:n,...o}),{allow:!0,prompt:""}):a.trim()===""?(f.debug("HOOK",`Skipping ${s} - user prompt was entirely private`,{sessionId:i,promptNumber:n,...o}),{allow:!1,reason:"private"}):{allow:!0,prompt:a}}};var at=require("path");function ca(){let r=Ld();return async e=>{for(let t of e)t.module=r(t.filename);return e}}function Ld(r=process.argv[1]?(0,at.dirname)(process.argv[1]):process.cwd(),e=at.sep==="\\"){let t=e?aa(r):r;return n=>{if(!n)return;let s=e?aa(n):n,{dir:i,base:o,ext:a}=at.posix.parse(s);(a===".js"||a===".mjs"||a===".cjs")&&(o=o.slice(0,-1*a.length));let c=decodeURIComponent(o);i||(i=".");let l=i.lastIndexOf("/node_modules");if(l>-1)return`${i.slice(l+14).replace(/\//g,".")}:${c}`;if(i.startsWith(t)){let u=i.slice(t.length+1).replace(/\//g,".");return u?`${u}:${c}`:c}return c}}function aa(r){return r.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var D={};jl(D,{DEFAULT_EXCEPTION_STEPS_CONFIG:()=>pn,DOMExceptionCoercer:()=>Hs,EXCEPTION_STEP_INTERNAL_FIELDS:()=>$t,ErrorCoercer:()=>Dt,ErrorEventCoercer:()=>Gs,ErrorPropertiesBuilder:()=>kt,EventCoercer:()=>Ks,ExceptionStepsBuffer:()=>Ys,ObjectCoercer:()=>Nt,PrimitiveCoercer:()=>Ut,PromiseRejectionEventCoercer:()=>Vs,ReduceableCache:()=>qs,StringCoercer:()=>Lt,chromeStackLineParser:()=>$s,createDefaultStackParser:()=>Ws,createStackParser:()=>Ja,geckoStackLineParser:()=>js,getInjectedReleaseId:()=>qf,getUtf8ByteLength:()=>Qa,nodeStackLineParser:()=>Ga,opera10StackLineParser:()=>Ba,opera11StackLineParser:()=>Wa,resolveExceptionStepsConfig:()=>zs,reverseAndStripFrames:()=>Ya,stripReservedExceptionStepFields:()=>Gf,winjsStackLineParser:()=>ja});var G=(function(r){return r.AnonymousId="anonymous_id",r.DistinctId="distinct_id",r.Props="props",r.EnablePersonProcessing="enable_person_processing",r.PersonMode="person_mode",r.FeatureFlagDetails="feature_flag_details",r.FeatureFlags="feature_flags",r.FeatureFlagPayloads="feature_flag_payloads",r.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",r.BootstrapFeatureFlags="bootstrap_feature_flags",r.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",r.OverrideFeatureFlags="override_feature_flags",r.Queue="queue",r.AiQueue="ai_queue",r.AiCaptureQueue="ai_capture_queue",r.LogsQueue="logs_queue",r.OptedOut="opted_out",r.SessionId="session_id",r.SessionStartTimestamp="session_start_timestamp",r.SessionLastTimestamp="session_timestamp",r.PersonProperties="person_properties",r.GroupProperties="group_properties",r.InstalledAppBuild="installed_app_build",r.InstalledAppVersion="installed_app_version",r.SessionReplay="session_replay",r.PushRegistered="push_registered",r.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",r.SurveyLastSeenDate="survey_last_seen_date",r.SurveysSeen="surveys_seen",r.Surveys="surveys",r.RemoteConfig="remote_config",r.FlagsEndpointWasHit="flags_endpoint_was_hit",r.DeviceId="device_id",r})({});function ke(r){let e=[];return JSON.stringify(r,function(t,n){if(typeof n=="bigint")return n.toString();if(!(typeof n=="function"||typeof n=="symbol")){if(n instanceof Error)return{name:n.name,message:n.message,stack:n.stack};if(n&&typeof n=="object"){for(;e.length>0&&e[e.length-1]!==this;)e.pop();if(e.includes(n))return"[Circular]";e.push(n)}return n}})??"null"}var Nd=Array.isArray,ua=Object.prototype,fy=ua.hasOwnProperty,Jr=ua.toString,Y=Nd||function(r){return Jr.call(r)==="[object Array]"};var Mt=r=>r===Object(r)&&!Y(r);var ve=r=>r===void 0,$=r=>Jr.call(r)=="[object String]",Cs=r=>$(r)&&r.trim().length===0,Ms=r=>r===null,re=r=>ve(r)||Ms(r),ct=r=>Jr.call(r)=="[object Number]"&&r===r;var da=r=>Jr.call(r)==="[object Boolean]";function Xr(r){return r===null||typeof r!="object"}function Ke(r,e){return Object.prototype.toString.call(r)===`[object ${e}]`}function lt(r){switch(Object.prototype.toString.call(r)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return ga(r,Error)}}function fa(r){return Ke(r,"ErrorEvent")}function ut(r){return"u">typeof Event&&ga(r,Event)}function pa(r){return Ke(r,"Object")}function ga(r,e){try{return r instanceof e}catch{return!1}}var Ud=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterestbot","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],ha=function(r,e=[]){if(!r)return!1;let t=r.toLowerCase();return Ud.concat(e).some(n=>{let s=n.toLowerCase();return t.indexOf(s)!==-1})};function xt(r,e,t,n,s){return e>t&&(n.warn("min cannot be greater than max."),e=t),ct(r)?r>t?(n.warn(" cannot be greater than max: "+t+". Using max value instead."),t):r<e?(n.warn(" cannot be less than min: "+e+". Using min value instead."),e):r:(n.warn(" must be a number. using max or fallback. max: "+t+", fallback: "+s),xt(s??t,e,t,n))}var $d=864e5,jd=1,Bd=10;function ma(r={}){return{refillRate:r.exceptionRateLimiterRefillRate??r.__exceptionRateLimiterRefillRate??jd,bucketSize:r.exceptionRateLimiterBucketSize??r.__exceptionRateLimiterBucketSize??Bd}}var Qr=class{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=xt(e.bucketSize,0,100,e._logger),this._refillRate=xt(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=xt(e.refillInterval,0,$d,e._logger)}_applyRefill(e,t){let n=t-e.lastAccess,s=Math.floor(n/this._refillInterval);if(s>0){let i=s*this._refillRate;e.tokens=Math.min(e.tokens+i,this._bucketSize),e.lastAccess=e.lastAccess+s*this._refillInterval}}consumeRateLimit(e){let t=Date.now(),n=String(e),s=this._buckets[n];return s?this._applyRefill(s,t):(s={tokens:this._bucketSize,lastAccess:t},this._buckets[n]=s),s.tokens===0?!0:(s.tokens--,s.tokens===0&&this._onBucketRateLimited?.(e),s.tokens===0)}stop(){this._buckets={}}};var Zr="0123456789abcdef",en=class r{constructor(e){this.bytes=e}static ofInner(e){if(e.length===16)return new r(e);throw new TypeError("not 128-bit length")}static fromFieldsV7(e,t,n,s){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(n)||!Number.isInteger(s)||e<0||t<0||n<0||s<0||e>0xffffffffffff||t>4095||n>1073741823||s>4294967295)throw new RangeError("invalid field value");let i=new Uint8Array(16);return i[0]=e/2**40,i[1]=e/2**32,i[2]=e/2**24,i[3]=e/2**16,i[4]=e/256,i[5]=e,i[6]=112|t>>>8,i[7]=t,i[8]=128|n>>>24,i[9]=n>>>16,i[10]=n>>>8,i[11]=n,i[12]=s>>>24,i[13]=s>>>16,i[14]=s>>>8,i[15]=s,new r(i)}static parse(e){let t;switch(e.length){case 32:t=/^[0-9a-f]{32}$/i.exec(e)?.[0];break;case 36:t=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("");break;case 38:t=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(e)?.slice(1,6).join("");break;case 45:t=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("");break;default:break}if(t){let n=new Uint8Array(16);for(let s=0;s<16;s+=4){let i=parseInt(t.substring(2*s,2*s+8),16);n[s+0]=i>>>24,n[s+1]=i>>>16,n[s+2]=i>>>8,n[s+3]=i}return new r(n)}throw new SyntaxError("could not parse UUID string")}toString(){let e="";for(let t=0;t<this.bytes.length;t++)e+=Zr.charAt(this.bytes[t]>>>4),e+=Zr.charAt(15&this.bytes[t]),(t===3||t===5||t===7||t===9)&&(e+="-");return e}toHex(){let e="";for(let t=0;t<this.bytes.length;t++)e+=Zr.charAt(this.bytes[t]>>>4),e+=Zr.charAt(15&this.bytes[t]);return e}toJSON(){return this.toString()}getVariant(){let e=this.bytes[8]>>>4;if(e<0)throw new Error("unreachable");if(e<=7)return this.bytes.every(t=>t===0)?"NIL":"VAR_0";if(e<=11)return"VAR_10";if(e<=13)return"VAR_110";if(e<=15)return this.bytes.every(t=>t===255)?"MAX":"VAR_RESERVED";throw new Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new r(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(let t=0;t<16;t++){let n=this.bytes[t]-e.bytes[t];if(n!==0)return Math.sign(n)}return 0}},xs=class{constructor(e){this.timestamp=0,this.counter=0,this.random=e??Wd()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(e,t){let n=this.generateOrAbortCore(e,t);return n===void 0&&(this.timestamp=0,n=this.generateOrAbortCore(e,t)),n}generateOrAbortCore(e,t){if(!Number.isInteger(e)||e<1||e>0xffffffffffff)throw new RangeError("`unixTsMs` must be a 48-bit positive integer");if(t<0||t>0xffffffffffff)throw new RangeError("`rollbackAllowance` out of reasonable range");if(e>this.timestamp)this.timestamp=e,this.resetCounter();else{if(!(e+t>=this.timestamp))return;this.counter++,this.counter>4398046511103&&(this.timestamp++,this.resetCounter())}return en.fromFieldsV7(this.timestamp,Math.trunc(this.counter/2**30),this.counter&2**30-1,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}generateV4(){let e=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return e[6]=64|e[6]>>>4,e[8]=128|e[8]>>>2,en.ofInner(e)}},Wd=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())>>>0}),_a,j=()=>Hd().toString(),Hd=()=>(_a||(_a=new xs)).generate();var tn=class{add(e){let t=j(),n=++this.nextId;return this.promiseByIds[t]={id:n,promise:e},e.catch(()=>{}).finally(()=>{delete this.promiseByIds[t]}),e}async join(){let e=Object.values(this.promiseByIds).map(n=>n.promise),t=e.length;for(;t>0;)await Promise.all(e),e=Object.values(this.promiseByIds).map(n=>n.promise),t=e.length}getPromises(e=[],t=this.nextId){let n=new Set(e);return Object.values(this.promiseByIds).filter(s=>s.id<=t&&!n.has(s.promise)).map(s=>s.promise)}get maxId(){return this.nextId}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={},this.nextId=0}};function Gd(r=console){return{log:r.log.bind(r),warn:r.warn.bind(r),error:r.error.bind(r),debug:r.debug.bind(r)}}var Ea=(r,e,t)=>{function n(i,...o){e(()=>{let a=t[i];a(r,...o)})}return{debug:(...i)=>{n("debug",...i)},info:(...i)=>{n("log",...i)},warn:(...i)=>{n("warn",...i)},error:(...i)=>{n("error",...i)},critical:(...i)=>{t.error(r,...i)},createLogger:i=>Ea(`${r} ${i}`,e,t)}},Kd=r=>r();function ya(r,e=Kd){return Ea(r,e,Gd())}var ft="Mobile",nn="iOS",dt="Android",Aa="Tablet",Iy=dt+" "+Aa;var qd="Apple",Ry=qd+" Watch",Ta="Safari",sn="BlackBerry",Pa="Samsung",zd=Pa+"Browser",Yd=Pa+" Internet",on="Chrome",Jd=on+" OS",Xd=on+" "+nn,Ia="Internet Explorer",Qd=Ia+" "+ft,ks="Opera",Cy=ks+" Mini",Ra="Edge",Zd="Microsoft "+Ra,Ds="Firefox",ef=Ds+" "+nn,Ls="Nintendo",Ns="PlayStation",rn="Xbox",tf=dt+" "+ft,rf=ft+" "+Ta,Ft="Windows",nf=Ft+" Phone";var Ca="Generic",My=Ca+" "+ft.toLowerCase(),xy=Ca+" "+Aa.toLowerCase(),sf="Konqueror",of="Oculus Browser",Sa="Vivaldi",af="Yandex",ba="Whale",cf="DuckDuckGo",lf="Pale Moon",wa="Waterfox",va="Brave",Ma="Claude",xa="Codex",Fa="ChatGPT",uf="Google Search App",C="(\\d+(\\.\\d+)?)",Fs=new RegExp("Version/"+C),Os=new RegExp("("+Ma+"|"+xa+"|"+Fa+")\\/"+C);var Fy=new RegExp(rn,"i"),Oy=new RegExp(Ns+" \\w+","i"),ky=new RegExp(Ls+" \\w+","i"),df=new RegExp(sn+"|PlayBook|BB10","i"),ff={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000","5.1":"XP","5.2":"XP","6.0":"Vista","6.1":"7","6.2":"8","6.3":"8.1","6.4":"10","10.0":"10"};var Dy={[Qd]:[new RegExp("rv:"+C)],[Zd]:[new RegExp(Ra+"?\\/"+C)],[on]:[new RegExp("("+on+"|CrMo)\\/"+C)],[Xd]:[new RegExp("CriOS\\/"+C)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+C)],[Ta]:[Fs],[rf]:[Fs],[ks]:[new RegExp("("+ks+"|OPR)\\/"+C)],[Ds]:[new RegExp(Ds+"\\/"+C)],[ef]:[new RegExp("FxiOS\\/"+C)],[sf]:[new RegExp("Konqueror[:/]?"+C,"i")],[sn]:[new RegExp(sn+" "+C),Fs],[tf]:[new RegExp("android\\s"+C,"i")],[Yd]:[new RegExp(zd+"\\/"+C)],[of]:[new RegExp("OculusBrowser\\/"+C)],[Sa]:[new RegExp(Sa+"\\/"+C)],[af]:[new RegExp("YaBrowser\\/"+C)],[ba]:[new RegExp(ba+"\\/"+C)],[va]:[new RegExp(va+"\\/"+C)],[Ma]:[Os],[xa]:[Os],[Fa]:[Os],[cf]:[new RegExp("(DuckDuckGo|Ddg)\\/"+C)],[lf]:[new RegExp("PaleMoon\\/"+C)],[wa]:[new RegExp(wa+"\\/"+C)],[uf]:[new RegExp("GSA\\/"+C)],[Ia]:[new RegExp("(rv:|MSIE )"+C)],Mozilla:[new RegExp("rv:"+C)]};var Ly=[[new RegExp(rn+"; "+rn+" (.*?)[);]","i"),r=>[rn,r&&r[1]||""]],[new RegExp(Ls,"i"),[Ls,""]],[new RegExp(Ns,"i"),[Ns,""]],[df,[sn,""]],[new RegExp(Ft,"i"),(r,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[nf,""];if(new RegExp(ft).test(e)&&!/IEMobile\b/.test(e))return[Ft+" "+ft,""];let t=/Windows NT ([0-9.]+)/i.exec(e);if(t&&t[1]){let n=t[1],s=ff[n]||"";return/arm/i.test(e)&&(s="RT"),[Ft,s]}return[Ft,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,r=>{if(r&&r[3]){let e=[r[3],r[4],r[5]||"0"];return[nn,e.join(".")]}return[nn,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,r=>{let e="";return r&&r.length>=3&&(e=ve(r[2])?r[3]:r[2]),["watchOS",e]}],[new RegExp("("+dt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+dt+")","i"),r=>{if(r&&r[2]){let e=[r[2],r[3],r[4]||"0"];return[dt,e.join(".")]}return[dt,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,r=>{let e=["Mac OS X",""];if(r&&r[1]){let t=[r[1],r[2],r[3]||"0"];e[1]=t.join(".")}return e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[Jd,""]],[/Linux|debian/i,["Linux",""]]];var an="[Circular]",cn="[Truncated]",J="[Unserializable]",Oa="[Function]",$y=Date.prototype.getTime,jy=Date.prototype.toISOString;function ae(r){let e="";for(let t=0;t<r.length;t++){let n=r.charCodeAt(t);if(n>=55296&&n<=56319){let s=r.charCodeAt(t+1);s>=56320&&s<=57343?(e+=r[t]+r[t+1],t++):e+="\uFFFD"}else e+=n>=56320&&n<=57343?"\uFFFD":r[t]}return e}function Ae(r,e){if(!e)return r;let t=[];try{t=Object.keys(e)}catch{t=[]}for(let n of t){let s;try{s=e[n]}catch{s=J}Object.defineProperty(r,n,{value:s,enumerable:!0,writable:!0,configurable:!0})}return r}var ka="utf8",pf=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function gf(r){return typeof r=="string"&&pf.test(r)}function Ve(r,e){return gf(r)?r:e()}function pt(r,e){let t=new Error(e);try{Object.defineProperty(t,"name",{value:r,writable:!0,enumerable:!0,configurable:!0})}catch{}return t}function Da(r){return r?.replace(/\/+$/,"")}async function La(r,e){let t=null;for(let n=0;n<e.retryCount+1;n++){n>0&&await new Promise(s=>setTimeout(s,e.retryDelay));try{return await r()}catch(s){if(t=s,!e.retryCheck(s))throw s}}throw t}function Us(){return new Date().toISOString()}function B(r,e){let t=setTimeout(r,e);return t?.unref&&t?.unref(),t}async function De(r,e,t){let n;try{return await Promise.race([r,new Promise((s,i)=>{n=B(()=>{try{t?.(),s()}catch(o){i(o)}},e)})])}finally{clearTimeout(n)}}var Na=r=>r&&typeof r.then=="function";function Ot(r){return Promise.all(r.map(e=>(e??Promise.resolve()).then(t=>({status:"fulfilled",value:t}),t=>({status:"rejected",reason:t}))))}var ln,Ua,un;function $a(r){let e=globalThis._posthogChunkIds;if(!e)return;let t=Object.keys(e);return un&&t.length===Ua||(Ua=t.length,un=t.reduce((n,s)=>{ln||(ln={});let i=ln[s];if(i)n[i[0]]=i[1];else{let o=r(s);for(let a=o.length-1;a>=0;a--){let l=o[a]?.filename,u=e[s];if(l&&u){n[l]=u,ln[s]=[l,u];break}}}return n},{})),un}var hf=4,kt=class{constructor(e,t,n=[]){this.coercers=e,this.stackParser=t,this.modifiers=n}buildFromUnknown(e,t={}){let s=t&&t.mechanism||{handled:!0,type:"generic"},o=this.buildCoercingContext(s,t,0).apply(e),a=this.buildParsingContext(t),c=this.parseStacktrace(o,a);return{$exception_list:this.convertToExceptionList(c,s),$exception_level:"error"}}async modifyFrames(e){for(let t of e)t.stacktrace&&t.stacktrace.frames&&Y(t.stacktrace.frames)&&(t.stacktrace.frames=await this.applyModifiers(t.stacktrace.frames));return e}coerceFallback(e){return{type:"Error",value:"Unknown error",stack:e.syntheticException?.stack,synthetic:!0}}parseStacktrace(e,t){let n;e.cause!=null&&(n=this.parseStacktrace(e.cause,t));let s;return e.stack!=""&&e.stack!=null&&(s=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap)),{...e,cause:n,stack:s}}applyChunkIds(e,t){return e.map(n=>(n.filename&&t&&(n.chunk_id=t[n.filename]),n))}applyCoercers(e,t){for(let n of this.coercers)if(n.match(e))return n.coerce(e,t);return this.coerceFallback(t)}async applyModifiers(e){let t=e;for(let n of this.modifiers)t=await n(t);return t}convertToExceptionList(e,t){let n={type:e.type,value:e.value,mechanism:{type:t.type??"generic",handled:t.handled??!0,synthetic:e.synthetic??!1}};e.stack&&(n.stacktrace={type:"raw",frames:e.stack});let s=[n];return e.cause!=null&&s.push(...this.convertToExceptionList(e.cause,{...t,handled:!0})),s}buildParsingContext(e){return{chunkIdMap:$a(this.stackParser),skipFirstLines:e.skipFirstLines??1}}buildCoercingContext(e,t,n=0){let s=(o,a)=>{if(a<=hf){let c=this.buildCoercingContext(e,t,a);return this.applyCoercers(o,c)}};return{...t,syntheticException:n==0?t.syntheticException:void 0,mechanism:e,apply:o=>s(o,n),next:o=>s(o,n+1)}}};var N="?",mf="<anonymous>",_f=/^([a-z][a-z0-9.+-]+):/i,Ef=["http","https","file","blob","app","capacitor","ionic","webpack","webpack-internal","ng"];function yf(r){if(!r||r===mf)return!1;let e=_f.exec(r);return!e||Ef.includes(e[1].toLowerCase())}function ce(r,e,t,n,s){let i={platform:r,filename:e,function:t==="<anonymous>"?N:t,in_app:yf(e)};return ve(n)||(i.lineno=n),ve(s)||(i.colno=s),i}var dn=(r,e)=>{let t=r.indexOf("safari-extension")!==-1,n=r.indexOf("safari-web-extension")!==-1;return t||n?[r.indexOf("@")!==-1?r.split("@")[0]:N,t?`safari-extension:${e}`:`safari-web-extension:${e}`]:[r,e]};var Sf=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,bf=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,wf=/\((\S*)(?::(\d+))(?::(\d+))\)/,$s=(r,e)=>{let t=Sf.exec(r);if(t){let[,s,i,o]=t;return ce(e,s,N,+i,+o)}let n=bf.exec(r);if(n){if(n[2]&&n[2].indexOf("eval")===0){let a=wf.exec(n[2]);a&&(n[2]=a[1],n[3]=a[2],n[4]=a[3])}let[i,o]=dn(n[1]||N,n[2]);return ce(e,o,i,n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}};var vf=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Af=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,js=(r,e)=>{let t=vf.exec(r);if(t){if(t[3]&&t[3].indexOf(" > eval")>-1){let o=Af.exec(t[3]);o&&(t[1]=t[1]||"eval",t[3]=o[1],t[4]=o[2],t[5]="")}let s=t[3],i=t[1]||N;return[i,s]=dn(i,s),ce(e,s,i,t[4]?+t[4]:void 0,t[5]?+t[5]:void 0)}};var Tf=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,ja=(r,e)=>{let t=Tf.exec(r);return t?ce(e,t[2],t[1]||N,+t[3],t[4]?+t[4]:void 0):void 0};var Pf=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,Ba=(r,e)=>{let t=Pf.exec(r);return t?ce(e,t[2],t[3]||N,+t[1]):void 0},If=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,Wa=(r,e)=>{let t=If.exec(r);return t?ce(e,t[5],t[3]||t[4]||N,+t[1],+t[2]):void 0};var Rf=/^\s*[-]{4,}$/,Cf=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,Mf=/^Promise\.(?:all|any)$/,xf=/^index \d+$/,Ff="node:internal/promise",Ga=(r,e)=>{let t=r.match(Cf);if(t){let n,s,i,o,a;if(t[1]){i=t[1];let u=i.lastIndexOf(".");if(i[u-1]==="."&&u--,u>0){n=i.slice(0,u),s=i.slice(u+1);let d=n.indexOf(".Module");d>0&&(i=i.slice(d+1),n=n.slice(0,d))}o=void 0}s&&(o=n,a=s),s==="<anonymous>"&&(a=void 0,i=void 0),i===void 0&&(a=a||N,i=o?`${o}.${a}`:a);let c=t[2]?.startsWith("file://")?t[2].slice(7):t[2],l=t[5]==="native";return c?.match(/\/[A-Z]:/)&&(c=c.slice(1)),!c&&t[5]&&!l&&(c=t[5]),Mf.test(i)&&xf.test(c||"")&&(c=Ff),{filename:c?decodeURI(c):void 0,module:void 0,function:i,lineno:Ha(t[3]),colno:Ha(t[4]),in_app:Of(c||"",l),platform:e}}if(r.match(Rf))return{filename:r,platform:e}};function Of(r,e=!1){return!(e||r&&!r.startsWith("/")&&!r.match(/^[A-Z]:/)&&!r.startsWith(".")&&!r.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&r!==void 0&&!r.includes("node_modules/")}function Ha(r){return parseInt(r||"",10)||void 0}var Ka=/\(error: (.*)\)/,Va=50,kf=10,Df=1e3;function Bs(r,e){return r.filename===e.filename&&r.function===e.function&&r.module===e.module&&r.lineno===e.lineno&&r.colno===e.colno}function Lf(r){for(let e=1;e<=kf;e++){let t=r.length-2*e;if(t<0)break;let n=!0;for(let s=0;s<e;s++){let i=r[t+s];if(!Bs(i,r[t+e+s])){n=!1;break}}if(n){for(let s=0;s<e;s++)r[t+s]=r[t+e+s];return r.length=t+e,{start:t,length:e}}}}function Nf(r,e){let t=e.start+e.length,n=za(r,e);n&&r.splice(t+n===r.length?t:e.start,n)}function qa(r,e){let t=e.start;for(;t>0&&Bs(r[t-1],r[t-1+e.length]);)t--;return e.start-t}function za(r,e){let t=e.start+e.length,n=t;for(;n<r.length&&Bs(r[n],r[n-e.length]);)n++;return n-t}function Uf(r,e){let t=e[0],n=r.length-(t?qa(r,t):0);for(let s of e)n-=za(r,s);return n}function $f(r){let e=r.map(n=>`${n.function}|${n.filename}|${n.lineno}|${n.colno}|${n.module}`),t=0;for(let n=1;n<e.length;n++)jf(e,n,t)&&(t=n);r.push(...r.splice(0,t))}function jf(r,e,t){for(let n=0;n<r.length;n++){let s=r[(e+n)%r.length],i=r[(t+n)%r.length];if(s!==i)return s<i}return!1}function Ya(r){if(!r.length)return[];let e=Array.from(r);return e.reverse(),e.slice(0,Va).map(t=>({...t,filename:t.filename||Bf(e).filename,function:t.function||N}))}function Bf(r){return r[r.length-1]||{}}function Ws(){return Ja("web:javascript",$s,js)}function Ja(r,...e){return(t,n=0)=>{let s=[],i=t.split(`
31
- `),o=Math.min(i.length,n+Df),a=[];for(let u=n;u<o;u++){let d=i[u];if(d.length>1024)continue;let g=Ka.test(d)?d.replace(Ka,"$1"):d;if(!g.match(/\S*Error: /)){for(let p of e){let h=p(g,r);if(h){s.push(h);let m=Lf(s);if(m){for(let E=a.length-1;E>=0;E--){let _=a[E];if(_.start+_.length<=m.start)break;a.pop()}a.push(m)}break}}if(Uf(s,a)>=Va)break}}let c=[...a].sort((u,d)=>d.start-u.start),l=c[c.length-1];if(l){let u=qa(s,l);s.splice(l.start-u,u);for(let d of c)d.start-=u}for(let u of c)Nf(s,u);return a.some(u=>u.start===0&&s.length===u.length)&&$f(s),Ya(s)}}var Hs=class{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){let n=$(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:n?e.stack:void 0,cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){let t=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?`${t}: ${e.message}`:t}isDOMException(e){return Ke(e,"DOMException")}isDOMError(e){return Ke(e,"DOMError")}};var Dt=class{match(e){return lt(e)}coerce(e,t){let n=this.getStack(e),s=n===void 0;return{type:this.getType(e),value:this.getMessage(e,t),stack:n??t.syntheticException?.stack,cause:e.cause?t.next(e.cause):void 0,synthetic:s}}getType(e){return e.name||e.constructor.name}getMessage(e,t){let n=e.message;return n.error&&typeof n.error.message=="string"?String(n.error.message):String(n)}getStack(e){return e.stacktrace||e.stack||void 0}};var Gs=class{match(e){if(!fa(e))return!1;let t=e;return t.error!=null||this._hasUsableMessage(t)}coerce(e,t){if(e.error!=null)return t.apply(e.error);let n=t.apply(e.message);return{...n,stack:this._buildLocationStack(e)??n.stack,synthetic:!0}}_hasUsableMessage(e){return $(e.message)&&e.message.length>0}_buildLocationStack(e){let t=e,n=t.lineno??0,s=t.colno??0;if(!(!$(t.filename)||t.filename.length===0)&&n!==0)return`Error
32
- at ${t.filename}:${n}:${s}`}};var Wf=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,Lt=class{match(e){return typeof e=="string"}coerce(e,t){let[n,s]=this.getInfos(e);return{type:n??"Error",value:s??e,stack:t.syntheticException?.stack,synthetic:!0}}getInfos(e){let t="Error",n=e,s=e.match(Wf);return s&&(t=s[1],n=s[2]),[t,n]}};var Xa=["fatal","error","warning","log","info","debug"];function fn(r,e=40){let t=Object.keys(r);if(t.sort(),!t.length)return"[object has no keys]";for(let n=t.length;n>0;n--){let s=t.slice(0,n).join(", ");if(!(s.length>e))return n===t.length||s.length<=e?s:`${s.slice(0,e)}...`}return""}var Nt=class{match(e){return typeof e=="object"&&e!==null}coerce(e,t){let n=this.getErrorPropertyFromObject(e);return n?t.apply(n):{type:this.getType(e),value:this.getValue(e),stack:this.getStack(e)??t.syntheticException?.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){if(ut(e))return e.constructor.name;let t="name"in e?e.name:void 0;return $(t)&&!Cs(t)?t:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){let s=`'${e.name}' captured as exception`;return"message"in e&&typeof e.message=="string"&&(s+=` with message: '${e.message}'`),s}if("message"in e&&typeof e.message=="string")return e.message;let t=this.getObjectClassName(e),n=fn(e);return`${t&&t!=="Object"?`'${t}'`:"Object"} captured as exception with keys: ${n}`}isSeverityLevel(e){return $(e)&&!Cs(e)&&Xa.indexOf(e)>=0}getStack(e){try{return $(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:$(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let n=e[t];if(lt(n))return n}}getObjectClassName(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch{return}}};var Ks=class{match(e){return ut(e)}coerce(e,t){let n=e.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${fn(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}};var Ut=class{match(e){return Xr(e)}coerce(e,t){return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}};var Vs=class{match(e){return Ke(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!ut(e))return!1;try{let t=e.detail;return t!=null&&typeof t=="object"&&"reason"in t}catch{return!1}}coerce(e,t){let n=this.getUnhandledRejectionReason(e);return Xr(n)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(n)}`,stack:t.syntheticException?.stack,synthetic:!0}:t.apply(n)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}};var qs=class{constructor(e){this._maxSize=e,this._cache=new Map}get(e){let t=this._cache.get(e);if(t!==void 0)return this._cache.delete(e),this._cache.set(e,t),t}set(e,t){this._cache.set(e,t)}reduce(){for(;this._cache.size>=this._maxSize;){let e=this._cache.keys().next().value;e&&this._cache.delete(e)}}};var $t={MESSAGE:"$message",TIMESTAMP:"$timestamp"},Hf=new Set([$t.MESSAGE,$t.TIMESTAMP]),pn={enabled:!0,max_bytes:32768};function zs(r){return r?{enabled:r.enabled??pn.enabled,max_bytes:Kf(r.max_bytes,pn.max_bytes)}:{...pn}}function Gf(r){if(!r)return{sanitizedProperties:{},droppedKeys:[]};let e=[];return{sanitizedProperties:Object.keys(r).reduce((n,s)=>Hf.has(s)?(e.push(s),n):(n[s]=r[s],n),{}),droppedKeys:e}}var Ys=class{constructor(e){this._entries=[],this._totalBytes=0,this._config=zs(e)}setConfig(e){this._config=zs(e),this._trimToMaxBytes()}add(e){let t=Vf(e);if(!t)return;let n=Qa(t.json);n>this._config.max_bytes||(this._entries.push({step:t.step,bytes:n}),this._totalBytes+=n,this._trimToMaxBytes())}getAttachable(){return this._entries.map(e=>e.step)}clear(){this._entries=[],this._totalBytes=0}size(){return this._entries.length}_trimToMaxBytes(){for(;this._totalBytes>this._config.max_bytes&&this._entries.length>0;){let e=this._entries.shift();e&&(this._totalBytes-=e.bytes)}}};function Kf(r,e){if(!ct(r)||r===1/0||r===-1/0)return e;let t=Math.floor(r);return t<0?e:t}function Vf(r){let e;try{e=ke(r)}catch{return}try{let t=JSON.parse(e);if(!Mt(t))return;let n=t,s=n[$t.MESSAGE],i=n[$t.TIMESTAMP];return!$(s)||s.trim().length===0||!$(i)&&!ct(i)?void 0:{step:n,json:e}}catch{return}}function Qa(r){if("u">typeof TextEncoder)return new TextEncoder().encode(r).length;let e=encodeURIComponent(r),t=0;for(let n=0;n<e.length;n++)e[n]==="%"?(t+=1,n+=2):t+=1;return t}function qf(){let r=globalThis._posthogReleaseId;return typeof r=="string"&&r.length>0?r:void 0}var Js=r=>{if("flags"in r){let e=Za(r.flags),t=ec(r.flags);return{...r,featureFlags:e,featureFlagPayloads:t}}{let e=r.featureFlags??{},t=Object.fromEntries(Object.entries(r.featureFlagPayloads||{}).map(([s,i])=>[s,gt(i)])),n=Object.fromEntries(Object.entries(e).map(([s,i])=>[s,zf(s,i,t[s])]));return{...r,featureFlags:e,featureFlagPayloads:t,flags:n}}};function zf(r,e,t){return{key:r,enabled:typeof e=="string"?!0:e,variant:typeof e=="string"?e:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:t?JSON.stringify(t):void 0,description:void 0}}}var Za=r=>Object.fromEntries(Object.entries(r??{}).map(([e,t])=>[e,jt(t)]).filter(([,e])=>e!==void 0)),ec=r=>{let e=r??{};return Object.fromEntries(Object.keys(e).filter(t=>{let n=e[t];return n.enabled&&n.metadata&&n.metadata.payload!==void 0}).map(t=>{let n=e[t].metadata?.payload;return[t,n?gt(n):void 0]}))},jt=r=>r===void 0?void 0:r.variant??r.enabled,gt=r=>{if(typeof r!="string")return r;try{return JSON.parse(r)}catch{return r}};var tc=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],Yf=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain",...tc,"$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],Bt=(r,e=[])=>{let t={},n=s=>{r[s]!==void 0&&(t[s]=r[s])};return Yf.forEach(n),e.forEach(n),t};var gn=class{constructor(){this.events={},this.events={}}on(e,t){return this.events[e]||(this.events[e]=[]),this.events[e].push(t),()=>{this.events[e]=this.events[e].filter(n=>n!==t)}}emit(e,t){for(let n of this.events[e]||[])n(t);for(let n of this.events["*"]||[])n(e,t)}};function Xs(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}var Xf="NativeGzipValidationError",Qf=31,Zf=139,ep=8,tp=r=>r.length>=2&&r[0]===Qf&&r[1]===Zf;var Wt,rp=()=>{if(Wt)return Wt;Wt=[];for(let r=0;r<256;r++){let e=r;for(let t=0;t<8;t++)e=1&e?3988292384^e>>>1:e>>>1;Wt[r]=e>>>0}return Wt},np=r=>{let e=rp(),t=4294967295;for(let n=0;n<r.length;n++)t=e[(t^r[n])&255]^t>>>8;return(4294967295^t)>>>0},hn=r=>{throw pt(Xf,`Native gzip produced invalid output: ${r}`)},sp=async(r,e)=>{r.size<18&&hn("too-short");let t=new Uint8Array(await r.slice(0,10).arrayBuffer());(!tp(t)||t[2]!==ep)&&hn("invalid-header");let n=new DataView(await r.slice(r.size-8).arrayBuffer());n.getUint32(0,!0)!==np(e)&&hn("invalid-crc");let s=e.length>>>0;n.getUint32(4,!0)!==s&&hn("invalid-size")};async function Ht(r,e=!0,t){try{let n=new TextEncoder().encode(r),s=new globalThis.CompressionStream("gzip"),i=s.writable.getWriter(),o=i.write(n).then(()=>i.close()).catch(async l=>{try{await i.abort(l)}catch{}throw l}),a=new Response(s.readable).blob(),[c]=await Promise.all([a,o]);return await sp(c,n),c}catch(n){if(t?.rethrow)throw n;return e&&console.error("Failed to gzip compress data",n),null}}function rc(r,e=Date.now()){if(typeof r!="string"||!r)return;let t=r.trim(),n=/^\d+\s*,/.test(t)?t.slice(0,t.indexOf(",")).trim():t,s=/^\d+$/.test(n)?Number(n):NaN;if(!Number.isFinite(s)&&/^[+-]?[\d.]+$/.test(n))return;let i=Number.isFinite(s)?1e3*s:Date.parse(n)-e;if(!(!Number.isFinite(i)||i<=0))return Math.min(i,3e5)}var qe=class{record(e){if(e.kind==="too-large")return;if(e.kind!=="retry-later")return void this.reset();if(!e.retryAfterMs)return;let t=this.isOpen(),n=Date.now(),s=Math.min(e.retryAfterMs,3e5);if(!t){this._installedAt=n,this._until=n+s;return}this._until=Math.max(this._until,Math.min(n+s,this._installedAt+3e5))}remainingMs(){let e=Date.now();if(e<this._installedAt-5e3)return this.reset(),0;let t=Math.min(3e5,Math.max(0,this._until-e));return t===0&&this.reset(),t}isOpen(){return this.remainingMs()>0}reset(){this._until=0,this._installedAt=0}constructor(){this._until=0,this._installedAt=0}};var X=class extends Error{constructor(e,t,n,s){super("HTTP error while fetching PostHog: status="+e.status+", reqByteLength="+t),this.response=e,this.reqByteLength=t,this.responseBodyDeadline=n,this.abortController=s,this.name="PostHogFetchHttpError",this._bodyReadTimedOut=!1}get status(){return this.response.status}get retryAfterMs(){try{return rc(this.response.headers?.get("retry-after"))}catch{return}}get bodyReadTimedOut(){return this._bodyReadTimedOut}get text(){if(!this.responseBodyTextPromise)if(Date.now()>=this.responseBodyDeadline){this._bodyReadTimedOut=!0;let e=pt("AbortError","Response body read timed out");this.cancelResponseBody(e),this.responseBodyTextPromise=Promise.reject(e)}else{let e=new Promise((n,s)=>{this.responseBodyTimer=B(()=>{this._bodyReadTimedOut=!0;let i=pt("AbortError","Response body read timed out");s(i),this.cancelResponseBody(i)},this.responseBodyDeadline-Date.now())}),t;try{t=Promise.resolve(this.response.text())}catch(n){t=Promise.reject(n)}this.responseBodyTextPromise=Promise.race([t,e]).finally(()=>clearTimeout(this.responseBodyTimer))}return this.responseBodyTextPromise}get json(){return this.text.then(e=>JSON.parse(e))}cancelResponseBody(e){clearTimeout(this.responseBodyTimer),this.abortController.signal.aborted||this.abortController.abort(e),(async()=>{try{await this.response.body?.cancel()}catch{}})()}},Te=class extends Error{constructor(e){super("Network error while fetching PostHog",e instanceof Error?{cause:e}:{}),this.error=e,this.name="PostHogFetchNetworkError"}};var ac=(r,e)=>{for(let t of Object.keys(e))(t.startsWith("$feature/")||t==="$active_feature_flags")&&(r[t]=e[t])};async function nc(r){if(r instanceof X){let e="";try{e=await r.text}catch{r.bodyReadTimedOut&&(e="<response body read timed out>")}console.error(`Error while flushing PostHog: message=${r.message}, response body=${e}`,r)}else console.error("Error while flushing PostHog",r);return Promise.resolve()}function ip(r){return typeof r=="object"&&(r instanceof X||cc(r))}function cc(r){return r instanceof Te}function op(r){if(r instanceof X)return r.status===502||r.status===504;if(!(r instanceof Te))return!1;let e=r.error;return(e?.code??e?.cause?.code)!=="ECONNREFUSED"}var sc=10485760;function ic(r){try{return typeof r!="string"?r instanceof Uint8Array?r.byteLength:r.size:"u">typeof Buffer?Buffer.byteLength(r,ka):new TextEncoder().encode(r).length}catch{return 0}}function ht(r){return typeof r=="object"&&r instanceof X&&r.status===413}function mn(r){return r instanceof X?r.status===408||r.status===429||r.status>=500:cc(r)}function oc(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}var Qs="default",Gt=class{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new kt([new Dt,new Nt,new Lt,new Ut],Ws())}constructor(e,t={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new tn,this._events=new gn,this._isInitialized=!1;let n=typeof e=="string"?e.trim():"",s=typeof t.host=="string"?t.host.trim():"",i=!n;this._logger=ya("[PostHog]",this.logMsgIfDebug.bind(this)),i&&this._logger.error("You must pass your PostHog project's api key. The client will be disabled."),this.apiKey=n,this.host=Da(s||"https://us.i.posthog.com"),this.flushAt=t.flushAt?Math.max(t.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,t.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,t.maxQueueSize??1e3),this.flushInterval=t.flushInterval??1e4,this.preloadFeatureFlags=t.preloadFeatureFlags??!0,this.defaultOptIn=t.defaultOptIn??!0,this.disableSurveys=t.disableSurveys??!1,this._retryOptions={retryCount:t.fetchRetryCount??3,retryDelay:t.fetchRetryDelay??3e3,retryCheck:mn},this.requestTimeout=t.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=t.featureFlagsRequestTimeoutMs??3e3,this.featureFlagsRequestMaxRetries=t.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=t.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=t.disableGeoip??!0,this.disabled=(t.disabled??!1)||i,this.historicalMigration=t?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=t?.evaluationContexts??t?.evaluationEnvironments,t?.evaluationEnvironments&&!t?.evaluationContexts&&this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version."),this.disableCompression=!Xs()||(t?.disableCompression??!1)}logMsgIfDebug(e){this.isDebug&&e()}wrap(e){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized)return e();this._initPromise.then(()=>e())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(G.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(G.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(G.OptedOut,!0)})}on(e,t){return this._events.on(e,t)}debug(e=!0){if(this.removeDebugCallback?.(),e){let t=this.on("*",(n,s)=>this._logger.info(n,s));this.removeDebugCallback=()=>{t(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(e){let t=e.properties||{},n={...t,...this.getCommonEventProperties()};return ac(n,t),e.event==="$feature_flag_called"&&n.$feature_flag_has_experiment===!1&&this.isMinimalFlagCalledEventsEnabled()&&(n=Bt(n)),{distinct_id:e.distinct_id,event:e.event,properties:n}}isMinimalFlagCalledEventsEnabled(){return!1}addPendingPromise(e){return this.promiseQueue.add(e)}identifyStateless(e,t,n){this.wrap(()=>{let s={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};this.enqueue("identify",s,n)})}async identifyStatelessImmediate(e,t,n){let s={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};await this.sendImmediate("identify",s,n)}captureStateless(e,t,n,s){this.wrap(()=>{let i=this.buildPayload({distinct_id:e,event:t,properties:n});this.enqueue("capture",i,s)})}async captureStatelessImmediate(e,t,n,s){let i=this.buildPayload({distinct_id:e,event:t,properties:n});await this.sendImmediate("capture",i,s)}aliasStateless(e,t,n,s){this.wrap(()=>{let i=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...n||{},distinct_id:t,alias:e}});this.enqueue("alias",i,s)})}async aliasStatelessImmediate(e,t,n,s){let i=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...n||{},distinct_id:t,alias:e}});await this.sendImmediate("alias",i,s)}groupIdentifyStateless(e,t,n,s,i,o){this.wrap(()=>{let a=this.buildPayload({distinct_id:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:n||{},...o||{}}});this.enqueue("capture",a,s)})}async groupIdentifyStatelessImmediate(e,t,n,s,i,o){let a=this.buildPayload({distinct_id:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:n||{},...o||{}}});await this.sendImmediate("capture",a,s)}async getRemoteConfig(){await this._initPromise;let e=this.host;e==="https://us.i.posthog.com"?e="https://us-assets.i.posthog.com":e==="https://eu.i.posthog.com"&&(e="https://eu-assets.i.posthog.com");let t=`${e}/array/${this.apiKey}/config`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(t,n,{type:"required",consume:s=>s.json()},{retryCount:0},this.remoteConfigRequestTimeoutMs).catch(s=>{this._logger.error("Remote config could not be loaded",s),this._events.emit("error",s)})}async getFlags(e,t={},n={},s={},i={},o=!1){await this._initPromise;let a=o?"&config=true":"",c=`${this.host}/flags/?v=2${a}`,l={token:this.apiKey,distinct_id:e,groups:t,person_properties:n,group_properties:s,...i};n.$device_id&&(l.$device_id=n.$device_id),this.evaluationContexts&&this.evaluationContexts.length>0&&(l.evaluation_contexts=this.evaluationContexts);let u={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(l)};return this._logger.info("Flags URL",c),this.fetchWithRetry(c,u,{type:"required",consume:d=>d.json()},{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:op},this.featureFlagsRequestTimeoutMs).then(d=>({success:!0,response:Js(d)})).catch(d=>(this._events.emit("error",d),{success:!1,error:this.categorizeRequestError(d)}))}categorizeRequestError(e){if(e instanceof X)return{type:"api_error",statusCode:e.status};if(e instanceof Te){let t=e.error;return t instanceof Error&&(t.name==="AbortError"||t.name==="TimeoutError")?{type:"timeout"}:{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(e,t,n={},s={},i={},o){await this._initPromise;let a=await this.getFeatureFlagDetailStateless(e,t,n,s,i,o);if(a===void 0)return{response:void 0,requestId:void 0};let c=jt(a.response);return c===void 0&&(c=!1),{response:c,requestId:a.requestId}}async getFeatureFlagDetailStateless(e,t,n={},s={},i={},o){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(t,n,s,i,o,[e]);return a===void 0?void 0:{response:a.flags[e],requestId:a.requestId,evaluatedAt:a.evaluatedAt}}async getFeatureFlagPayloadStateless(e,t,n={},s={},i={},o){await this._initPromise;let a=await this.getFeatureFlagPayloadsStateless(t,n,s,i,o,[e]);if(!a)return;let c=a[e];return c===void 0?null:c}async getFeatureFlagPayloadsStateless(e,t={},n={},s={},i,o){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(e,t,n,s,i,o)).payloads}async getFeatureFlagsStateless(e,t={},n={},s={},i,o){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(e,t,n,s,i,o)}async getFeatureFlagsAndPayloadsStateless(e,t={},n={},s={},i,o){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(e,t,n,s,i,o);return a?{flags:a.featureFlags,payloads:a.featureFlagPayloads,requestId:a.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(e,t={},n={},s={},i,o){await this._initPromise;let a={geoip_disable:i??this.disableGeoip};o&&(a.flag_keys_to_evaluate=o);let c=await this.getFlags(e,t,n,s,a);if(!c.success)return;let l=c.response;return l.errorsWhileComputingFlags&&console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices"),l.quotaLimited?.includes("feature_flags")?(console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:l?.requestId,quotaLimited:l.quotaLimited}):l}async getSurveysStateless(){if(await this._initPromise,this.disabled)return[];if(this.disableSurveys===!0)return this._logger.info("Loading surveys is disabled."),[];let e=`${this.host}/api/surveys/?token=${this.apiKey}`,t={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},s=(await this.fetchWithRetry(e,t,{type:"required",consume:i=>{if(i.status!==200||!i.json){let o=`Surveys API could not be loaded: ${i.status}`,a=new Error(o);return this._logger.error(a),this._events.emit("error",new Error(o)),Promise.resolve(void 0)}return i.json()}}).catch(i=>{this._logger.error("Surveys API could not be loaded",i),this._events.emit("error",i)}))?.surveys;return s&&this._logger.info("Surveys fetched from API: ",JSON.stringify(s)),s??[]}get props(){return this._props||(this._props=this.getPersistedProperty(G.Props)),this._props||{}}set props(e){this._props=e}async register(e){this.wrap(()=>{this.props={...this.props,...e},this.setPersistedProperty(G.Props,this.props)})}async unregister(e){this.wrap(()=>{delete this.props[e],this.setPersistedProperty(G.Props,this.props)})}processBeforeEnqueue(e){return e}async flushStorage(){}getQueueRouteKey(e){return Qs}persistedQueueKeyForRoute(e){return G.Queue}getActiveQueueRoutes(){return[Qs]}getRouteQueue(e){return this.getPersistedProperty(this.persistedQueueKeyForRoute(e))||[]}enqueue(e,t,n,s){this.wrap(()=>{if(this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let i=this.prepareMessage(t,n);if(i=this.processBeforeEnqueue(i),i===null)return;i=this.normalizeMessage(i);let o=this.persistedQueueKeyForRoute(s??this.getQueueRouteKey(i)),a=this.getPersistedProperty(o)||[];a.length>=this.maxQueueSize&&(a.shift(),this._logger.warn("Queue is full, the oldest event is dropped.")),a.push({message:i}),this.setPersistedProperty(o,a),this._events.emit(e,i),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=B(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(e,t,n,s){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized||await this._initPromise,this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let i=this.prepareMessage(t,n);if(i=this.processBeforeEnqueue(i),i!==null){i=this.normalizeMessage(i);try{await this.sendBatch([i],void 0,s??this.getQueueRouteKey(i))}catch(o){this._events.emit("error",o)}}}normalizeMessage(e){let{type:t,library:n,library_version:s,...i}=e,o=oc(i.properties)?i.properties:void 0;return n!==void 0&&o?.$lib===void 0&&(o={...o||{},$lib:n}),s!==void 0&&o?.$lib_version===void 0&&(o={...o||{},$lib_version:s}),o&&(i.properties=o),i.uuid=Ve(i.uuid,j),i}normalizeTimestampForWire(e){let t=e instanceof Date?e:typeof e=="string"?new Date(e):null;if(!t||Number.isNaN(t.getTime()))return e;let n=t.toISOString(),s=typeof e=="string"?e.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1]:void 0;return s&&s.length>3?n.replace(/\.\d{3}Z$/,`.${s}Z`):n}prepareMessage(e,t){let n={...e,timestamp:t?.timestamp?t?.timestamp:Us(),uuid:Ve(t?.uuid,j)};return(t?.disableGeoip??this.disableGeoip)&&(oc(n.properties)||(n.properties={}),n.properties.$geoip_disable=!0),n.distinctId&&(n.distinct_id=n.distinctId,delete n.distinctId),n}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.pendingFlushPromise||this.flushAutomatic().catch(async e=>{await nc(e)})}flushAutomatic(){return this.flush()}async waitForPendingPromises(e,t=[]){let n=t.filter(i=>!!i),s=0;for(;;){let i=this.promiseQueue.getPromises([...n,...this.flushPromises],e);if(i.length===0)return;s>0&&this._logger.debug(`flush() re-checking ${i.length} pending promise(s) before flushing`),await Promise.all(i.map(o=>o.catch(()=>{}))),s++}}flushWithPendingPromises(){return this.flushInternal(!0)}flush(){return this.flushInternal(!1)}flushInternal(e){if(this.disabled)return Promise.resolve();if(!e&&this.pendingFlushPromise)return this.pendingFlushPromise;let t=this.flushPromise,n=this.promiseQueue.maxId,s=Promise.resolve().then(()=>{if(e)return this.waitForPendingPromises(n,[t,s])}).then(()=>Ot([t])).then(()=>(this.pendingFlushPromise===s&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=s,this.flushPromise=s,this.flushPromises.add(s),this.addPendingPromise(s),Ot([s]).then(()=>{this.flushPromises.delete(s),this.pendingFlushPromise===s&&(this.pendingFlushPromise=null),this.flushPromise===s&&(this.flushPromise=null)}),s}getCustomHeaders(){let e=this.getCustomUserAgent(),t={};return e&&e!==""&&(t["User-Agent"]=e),t}compressPayload(e){return Ht(e,this.isDebug)}getBatchEndpointPath(e){return"/batch/"}async sendBatch(e,t,n=Qs){let s={api_key:this.apiKey,batch:e.map(l=>{if(!l)return l;let u=this.normalizeTimestampForWire(l.timestamp);return u===l.timestamp?l:{...l,timestamp:u}}),sent_at:Us()};this.historicalMigration&&(s.historical_migration=!0);let i=ke(s),o=`${this.host}${this.getBatchEndpointPath(n)}`,a=this.disableCompression?null:await this.compressPayload(i),c={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...a!==null&&{"Content-Encoding":"gzip"}},body:a||i};await this.fetchWithRetry(o,c,{type:"successful-write"},t)}async _flush(){this.clearFlushTimer(),await this._initPromise;let e=this.getActiveQueueRoutes();if(!e.some(s=>this.getRouteQueue(s).length>0))return;let t=[],n;for(let s of e)try{await this._flushRoute(s,t)}catch(i){n===void 0&&(n=i)}if(n!==void 0)throw n;this._events.emit("flush",t)}async _flushRoute(e,t){let n=this.persistedQueueKeyForRoute(e),s=this.getPersistedProperty(n)||[];if(!s.length)return;let i=s.length,o=0;for(;s.length>0&&o<i;){let a=s.slice(0,this.maxBatchSize),c=a.map(d=>d.message===void 0?d.message:this.normalizeMessage(d.message)),l=async()=>{let d=this.getPersistedProperty(n)||[],g=[...a],p=d.filter(h=>{let m=h.message?.uuid,E=g.findIndex(_=>_===h||typeof m=="string"&&m.length>0&&_.message?.uuid===m);return E===-1?!0:(g.splice(E,1),!1)});this.setPersistedProperty(n,p),s=p,this._dequeuedMessagesCount+=a.length,await this.flushStorage()},u={retryCheck:d=>ht(d)?!1:mn(d)};try{await this.sendBatch(c,u,e)}catch(d){if(ht(d)&&c.length>1){this.maxBatchSize=Math.max(1,Math.floor(c.length/2)),this._logger.warn(`Received 413 when sending batch of size ${c.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw d instanceof Te||await l(),this._events.emit("error",d),d}await l(),t.push(...c),o+=c.length}}async _sendOtlpBatch({path:e,auth:t,payload:n}){if(this.disabled)return{kind:"fatal",error:new Error("The client is disabled")};let s;try{s=JSON.stringify(n)}catch(u){return this.logMsgIfDebug(()=>console.warn(`[PostHog] Could not serialize a ${e} batch; reporting it as too large`,u)),{kind:"too-large",measuredLocally:!0}}let i=ic(s);if(i>sc)return this.logMsgIfDebug(()=>console.warn(`[PostHog] Not sending a ${e} batch of ${i} bytes: the endpoint accepts at most ${sc}`)),{kind:"too-large",measuredLocally:!0};let o=t==="bearer"?`${this.host}/i/v1/${e}`:`${this.host}/i/v1/${e}?token=${encodeURIComponent(this.apiKey)}`,a=this.disableCompression?null:await this.compressPayload(s),c=a||s,l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...t==="bearer"&&{Authorization:`Bearer ${this.apiKey}`},...a!==null&&{"Content-Encoding":"gzip"}},body:c};try{return await this.fetchWithRetry(o,l,{type:"successful-write"},{retryCheck:u=>ht(u)||u instanceof X&&u.retryAfterMs!==void 0?!1:mn(u)}),{kind:"ok"}}catch(u){if(ht(u))return{kind:"too-large"};if(mn(u)){let d=u instanceof X?u.retryAfterMs:void 0;return{kind:"retry-later",error:u,...d!==void 0&&{retryAfterMs:d}}}return{kind:"fatal",error:u}}}async _sendLogsBatch(e){return this._sendOtlpBatch({path:"logs",auth:"query-token",payload:e})}async _sendMetricsBatch(e){return this._sendOtlpBatch({path:"metrics",auth:"query-token",payload:e})}async _sendTracesBatch(e){return this._sendOtlpBatch({path:"traces",auth:"bearer",payload:e})}async fetchWithRetry(e,t,n,s,i){let o=t.body?t.body:"",a=ic(o),c={...this._retryOptions,...s},l=0;return await La(async()=>{l++;let u=new AbortController,d=i??this.requestTimeout,g=Date.now()+d,p,h=new Promise((P,R)=>{p=B(()=>{let O=pt("AbortError",`Request timed out after ${d}ms`);R(O),u.abort(O)},d)}),m,E=!1,_,b=()=>_??=(async()=>{try{await m?.body?.cancel()}catch{}})();try{let P;try{P=this.fetch(e,{signal:u.signal,...t})}catch(O){throw new Te(O)}P.then(O=>{u.signal.aborted&&!E&&Promise.resolve(O.body?.cancel()).catch(()=>{})}).catch(()=>{});try{m=await Promise.race([P,h]),E=!0}catch(O){throw new Te(O)}if(!(t.mode==="no-cors")&&(m.status<200||m.status>=400))throw new X(m,a,g,u);if(n.type==="successful-write"){try{await Promise.race([b(),h])}catch{}return}try{return await Promise.race([n.consume(m),h])}catch(O){throw u.signal.aborted?new Te(O):O}}finally{clearTimeout(p),u.signal.aborted&&m&&b()}},{...c,retryCheck:u=>{let d=c.retryCheck(u);return d&&l<=c.retryCount&&u instanceof X&&u.cancelResponseBody(),d}})}async _shutdown(e=3e4){await this._initPromise;let t=!1;return this.clearFlushTimer(),this.disabled?void 0:De((async()=>{try{for(await this.promiseQueue.join();this.getActiveQueueRoutes().some(o=>this.getRouteQueue(o).length>0);){let i=this._dequeuedMessagesCount;if(await this.flush(),t)break;if(this._dequeuedMessagesCount===i){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(s){if(!ip(s))throw s;await nc(s)}})(),e,()=>{this._logger.critical("Timeout while shutting down PostHog. Some events may not have been sent.",{shutdownTimeoutMs:e}),t=!0})}async shutdown(e=3e4){return this.shutdownPromise?this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup"):this.shutdownPromise=this._shutdown(e).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}};var dp=["is_not","is_set"],fp=1152921504606847e3,S=class r extends Error{constructor(e){super(e),this.name=this.constructor.name,Object.setPrototypeOf(this,r.prototype)}};function dc(r){if(typeof r=="boolean")return!0;if(typeof r=="string"){let e=r.toLowerCase();return e==="true"||e==="false"}if(!Array.isArray(r))return!1;for(let e=0;e<r.length;e++)if(!dc(e in r?r[e]:null))return!1;return!0}function Zs(r){if(typeof r=="boolean")return r;if(typeof r=="string")return r.toLowerCase()==="true";if(!Array.isArray(r))return!1;for(let e=0;e<r.length;e++)if(!Zs(e in r?r[e]:null))return!1;return!0}function Kt(r){for(let e=0;e<r.length;e++){let t=r.charCodeAt(e);if(t>=55296&&t<=56319){let n=r.charCodeAt(e+1);if(e+1>=r.length||n<56320||n>57343)throw new S("Cannot stringify an unpaired surrogate like the flags service");e++}else if(t>=56320&&t<=57343)throw new S("Cannot stringify an unpaired surrogate like the flags service")}}function ei(r,e=new Set){if(!(r===null||typeof r=="boolean")){if(typeof r=="string")return void Kt(r);if(typeof r=="number"){if(!Number.isFinite(r))throw new S(`Cannot represent non-finite number ${r} like the flags service`);return}if(Array.isArray(r)){if(e.has(r))throw new S("Cannot represent a circular array during local evaluation");e.add(r);try{for(let t=0;t<r.length;t++)t in r&&ei(r[t],e)}finally{e.delete(r)}return}if(typeof r=="object"){let t=Object.getPrototypeOf(r);if(t!==Object.prototype&&t!==null)throw new S("Cannot represent a non-JSON object like the flags service");if(e.has(r))throw new S("Cannot represent a circular object during local evaluation");e.add(r);try{for(let n of Object.keys(r))Kt(n),ei(r[n],e)}finally{e.delete(r)}return}throw new S(`Cannot represent ${typeof r} like the flags service`)}}function pp(r,e){let t=0,n=0;for(;t<r.length&&n<e.length;){let s=r.charCodeAt(t),i=e.charCodeAt(n),o=s>=55296&&s<=56319,a=i>=55296&&i<=56319,c=o?r.charCodeAt(t+1):0,l=a?e.charCodeAt(n+1):0,u=o?(s-55296)*1024+c-56320+65536:s,d=a?(i-55296)*1024+l-56320+65536:i;if(u!==d)return u-d;t+=o?2:1,n+=a?2:1}return r.length-e.length}function ti(r,e=new Set){if(r===null)return"null";if(typeof r=="string")return Kt(r),JSON.stringify(r);if(typeof r=="boolean")return r?"true":"false";if(typeof r=="number"){if(!Number.isFinite(r))throw new S(`Cannot stringify non-finite number ${r} like the flags service`);if(Number.isInteger(r))throw new S(`Cannot distinguish integer ${r} from an integral JSON float during local evaluation`);return String(r)}if(Array.isArray(r)){if(e.has(r))throw new S("Cannot stringify a circular array during local evaluation");e.add(r);try{let t=[];for(let n=0;n<r.length;n++)t.push(n in r?ti(r[n],e):"null");return`[${t.join(",")}]`}finally{e.delete(r)}}if(typeof r=="object"){let t=Object.getPrototypeOf(r);if(t!==Object.prototype&&t!==null)throw new S("Cannot stringify a non-JSON object like the flags service");if(e.has(r))throw new S("Cannot stringify a circular object during local evaluation");e.add(r);try{let n=Object.keys(r);return n.forEach(Kt),`{${n.sort(pp).map(s=>`${JSON.stringify(s)}:${ti(r[s],e)}`).join(",")}}`}finally{e.delete(r)}}throw new S(`Cannot stringify ${typeof r} like the flags service`)}function _n(r){return typeof r=="string"?(Kt(r),r):ti(r)}function lc(r){try{return new RegExp(r),!0}catch{return!1}}function Q(r){return String(r).replace(/[A-Z]/g,e=>e.toLowerCase())}function fc(r,e,t){if(!/^\d+$/.test(r)||t==="strict"&&r.length>1&&r[0]==="0")throw new S(`Invalid semver: ${e}`);return parseInt(r,10)}function F(r,e="strict"){let n=String(r).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!n||n.startsWith("."))throw new S(`Invalid semver: ${r}`);let s=n.split("."),i=o=>o===void 0||o===""?0:fc(o,r,e);return[i(s[0]),i(s[1]),i(s[2])]}function Z(r,e){for(let t=0;t<3;t++){if(r[t]<e[t])return-1;if(r[t]>e[t])return 1}return 0}function gp(r,e){let t=F(r,e);return{lower:[t[0],t[1],t[2]],upper:[t[0],t[1]+1,0]}}function hp(r,e){let[t,n,s]=F(r,e),i=[t,n,s],o;return o=t>0?[t+1,0,0]:n>0?[0,n+1,0]:[0,0,s+1],{lower:i,upper:o}}function mp(r,e){let n=String(r).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!n)throw new S(`Invalid wildcard semver: ${r}`);let s=n.split("."),i=c=>{if(e==="legacy-permissive"){let l=parseInt(c,10);if(!isNaN(l))return l}else try{return fc(c,r,e)}catch{}throw new S(`Invalid wildcard semver: ${r}`)},o=i(s[0]);if(s.length===1)return{lower:[o,0,0],upper:[o+1,0,0]};let a=i(s[1]);return{lower:[o,a,0],upper:[o,a+1,0]}}function uc(r){if(r instanceof Date)return r;if(typeof r=="string"||typeof r=="number"){let e=new Date(r);if(!isNaN(e.valueOf()))return e;throw new S(`${r} is in an invalid date format`)}throw new S(`The date provided ${r} must be a string, number, or date object`)}function ri(r){let e=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,t=r.match(e),n=new Date(new Date().toISOString());if(!t||!t.groups)return null;let s=parseInt(t.groups.number);if(s>=1e4)return null;let i=t.groups.interval;if(i==="h")n.setUTCHours(n.getUTCHours()-s);else if(i==="d")n.setUTCDate(n.getUTCDate()-s);else if(i==="w")n.setUTCDate(n.getUTCDate()-7*s);else if(i==="m")n.setUTCMonth(n.getUTCMonth()-s);else{if(i!=="y")return null;n.setUTCFullYear(n.getUTCFullYear()-s)}return n}function ni(r,e,t={}){let n=r.key,s=r.value,i=r.operator||"exact",o=t.semverParsingPolicy??"strict";if(Object.prototype.hasOwnProperty.call(e,n)){if(i==="is_not_set")return!1;if(i==="is_set")return!0}else throw new S(`Property ${n} not found in propertyValues`);let c=e[n];if(c===void 0)return t.warnFunction?.(`Property ${n} cannot have a value of undefined with the ${i} operator`),i==="is_not";if(c===null&&!dp.includes(i)&&i!=="exact"&&i!=="is_not")return t.warnFunction?.(`Property ${n} cannot have a value of null with the ${i} operator`),!1;let l=(d,g)=>{if(dc(d))return ei(g),Zs(d)===Zs(g);if(Array.isArray(d)){let p=_n(g).toLowerCase();return d.some(h=>_n(h).toLowerCase()===p)}return _n(d).toLowerCase()===_n(g).toLowerCase()},u=(d,g,p)=>{if(p==="gt")return d>g;if(p==="gte")return d>=g;if(p==="lt")return d<g;if(p==="lte")return d<=g;throw new Error(`Invalid operator: ${p}`)};switch(i){case"exact":return l(s,c);case"is_not":return!l(s,c);case"is_set":return!0;case"icontains":return Q(c).includes(Q(s));case"not_icontains":return!Q(c).includes(Q(s));case"starts_with":return Q(c).startsWith(Q(s));case"not_starts_with":return!Q(c).startsWith(Q(s));case"ends_with":return Q(c).endsWith(Q(s));case"not_ends_with":return!Q(c).endsWith(Q(s));case"regex":return lc(String(s))&&String(c).match(String(s))!==null;case"not_regex":return lc(String(s))&&String(c).match(String(s))===null;case"gt":case"gte":case"lt":case"lte":{let d=typeof s=="number"?s:parseFloat(String(s)),g=typeof c=="number"?c:c!=null?parseFloat(String(c)):NaN;return Number.isFinite(d)&&Number.isFinite(g)?u(g,d,i):u(String(c),String(s),i)}case"is_date_after":case"is_date_before":{if(typeof s=="boolean")throw new S("Date operations cannot be performed on boolean values");let d=ri(String(s));d==null&&(d=uc(s));let g=uc(c);return i==="is_date_before"?g<d:g>d}case"semver_eq":return Z(F(String(c),o),F(String(s),o))===0;case"semver_neq":return Z(F(String(c),o),F(String(s),o))!==0;case"semver_gt":return Z(F(String(c),o),F(String(s),o))>0;case"semver_gte":return Z(F(String(c),o),F(String(s),o))>=0;case"semver_lt":return Z(F(String(c),o),F(String(s),o))<0;case"semver_lte":return Z(F(String(c),o),F(String(s),o))<=0;case"semver_tilde":{let d=F(String(c),o),{lower:g,upper:p}=gp(String(s),o);return Z(d,g)>=0&&Z(d,p)<0}case"semver_caret":{let d=F(String(c),o),{lower:g,upper:p}=hp(String(s),o);return Z(d,g)>=0&&Z(d,p)<0}case"semver_wildcard":{let d=F(String(c),o),{lower:g,upper:p}=mp(String(s),o);return Z(d,g)>=0&&Z(d,p)<0}default:throw new S(`Unknown operator: ${i}`)}}async function pc(r){let e=globalThis.crypto?.subtle;if(!e)throw new Error("SubtleCrypto API not available");let t=await e.digest("SHA-1",new TextEncoder().encode(r));return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}async function En(r,e,t=""){let n=await pc(`${r}.${e}${t}`);return parseInt(n.slice(0,15),16)/fp}function yn(r){let e=[],t=0;for(let n of r){let s=t+n.rollout_percentage/100;e.push({valueMin:t,valueMax:s,key:n.key}),t=s}return e}async function si(r,e,t){let n=await En(r,e,"variant");return yn(t).find(s=>n>=s.valueMin&&n<s.valueMax)?.key}function ii(r,e){if(e===!1||e==null||!r)return null;let t=typeof e=="boolean"?e.toString():e,n=r[t]||null;return n==null?null:gt(n)}var gc=9223372036854776e3,_p="9223372036854775808",Ep=Object.prototype.propertyIsEnumerable;function yp(){return{ancestors:new WeakSet,remainingNodes:1e4}}function le(r,e){try{return hc(r,e,yp(),0)}catch{return[]}}function Sp(r,e){let t=r.toString(),n=BigInt(_p);return r>=n||r<-n?(e?.debug(`Attribute ${t} is outside the int64 range; encoding it as a string`),{stringValue:t}):{intValue:t}}function ci(r,e,t,n){if(t.remainingNodes<=0)return{stringValue:cn};if(t.remainingNodes--,da(r))return{boolValue:r};if(typeof r=="bigint")return Sp(r,e);if(typeof r=="number"){if(!Number.isFinite(r))return{stringValue:String(r)};if(Number.isInteger(r)){if(Number.isSafeInteger(r))return{intValue:String(r)};if("u"<typeof BigInt)return{stringValue:String(r)};let s=BigInt(r).toString();return r>=gc||r<-gc?(e?.debug(`Attribute ${s} is outside the int64 range; encoding it as a string`),{stringValue:s}):{intValue:s}}return{doubleValue:r}}if(typeof r=="string")return{stringValue:ae(r)};if(typeof r=="function")return{stringValue:Oa};if(typeof r=="symbol")return{stringValue:String(r)};if(typeof r=="object"&&r!==null){if(t.ancestors.has(r))return{stringValue:an};if(n>=20)return{stringValue:cn};if(r instanceof Date){let s=r.getTime(),i=Number.isFinite(s)?r.toISOString():String(r);return{stringValue:typeof i=="string"?ae(i):String(i)}}t.ancestors.add(r);try{try{let s=r.toJSON;if(typeof s=="function")return ci(s.call(r),e,t,n+1)}catch{}return Y(r)?{arrayValue:{values:bp(r,e,t,n+1)}}:{kvlistValue:{values:hc(r,e,t,n+1)}}}finally{t.ancestors.delete(r)}}return{stringValue:ae(String(r))}}function bp(r,e,t,n){let s=[],i=Math.min(r.length,1e3),o=0;for(;o<i&&t.remainingNodes>0;o++)try{let a=o in r?r[o]:void 0;if(re(a))continue;s.push(ci(a,e,t,n))}catch{s.push({stringValue:J})}return r.length>o&&s.push({stringValue:cn}),s}function hc(r,e,t,n){let s=[];for(let i in r)if(Ep.call(r,i)){if(!i){e?.debug("Dropping an attribute with an empty key");continue}if(s.length>=1e3||t.remainingNodes<=0){e?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{let o=r[i];if(Ms(o)||ve(o))continue;s.push({key:ae(i),value:ci(o,e,t,n)})}catch{s.push({key:ae(i),value:{stringValue:J}})}}return s}function qt(r,e,t){return{...Ae({},r.resourceAttributes),"service.name":r.serviceName||"unknown_service",...r.environment&&{"deployment.environment":r.environment},...r.serviceVersion&&{"service.version":r.serviceVersion},"telemetry.sdk.name":e,"telemetry.sdk.version":t}}var wp=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function zt(r,e){let t=Ae({},r),n={};for(let s of wp)Object.prototype.hasOwnProperty.call(t,s)&&(n[s]=t[s],delete t[s]);return[...le(t,e),...le(n,e)]}var mc={darwin:"macOS",win32:"Windows",cygwin:"Windows",linux:"Linux",android:"Android",freebsd:"FreeBSD",openbsd:"OpenBSD",netbsd:"NetBSD",sunos:"SunOS",aix:"AIX",haiku:"Haiku","Mac OS X":"macOS"};function vp(r){if(r)return Object.prototype.hasOwnProperty.call(mc,r)?mc[r]:r}function li(r,e){let t=vp(r);return{...t?{"os.name":t}:{},...e?{"os.version":e}:{}}}var Ap={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:{text:"INFO",number:9},warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}},iw=Ap.info;var ze=class{constructor(e){this._onFire=e,this._firesAt=0}get pending(){return!!this._timer}arm(e){this.clear(),this._firesAt=Date.now()+e,this._timer=B(()=>{this._timer=void 0,this._onFire()},e)}armNoEarlierThan(e){this._timer&&Date.now()+e<=this._firesAt||this.arm(e)}clear(){this._timer&&(clearTimeout(this._timer),this._timer=void 0)}};function Yt(){return 1-.25+Math.random()*.25*2}var ee=1;function Jt(r,e,t,n){let s=Math.min(Math.max(0,e-1),6),i=r*2**s,o=n===void 0?i:Math.min(i,Math.max(n,r));return Math.round(o*t)}var Xt=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function ui(r){return String(r)+"000000"}function di(r,e,t,n){let s="";return n&&(s=Object.keys(n).sort().map(o=>`${JSON.stringify(o)}:${JSON.stringify(n[o])}`).join(",")),`${r}\0${e}\0${t??""}\0${s}`}function _c(r,e){for(let t=0;t<e.length;t++)if(r<=e[t])return t;return e.length}function fi(r,e,t){return qt(r,e,t)}function pi(r,e,t,n){return{resourceMetrics:[{resource:{attributes:zt(e)},scopeMetrics:[{scope:{name:t,version:n},metrics:r}]}]}}function bn(r){let e=r?.resourceAttributes;return{serviceName:e?.["service.name"]??r?.serviceName,serviceVersion:e?.["service.version"]??r?.serviceVersion,environment:e?.["deployment.environment"]??r?.environment,resourceAttributes:e,beforeSend:r?.beforeSend,flushIntervalMs:r?.flushIntervalMs??1e4,maxSeriesPerFlush:r?.maxSeriesPerFlush??1e3}}var Ec=1,Qt=class{constructor(e,t,n){this._instance=e,this._config=t,this._logger=n,this._series=new Map,this._flushTimer=new ze(()=>this.flush().catch(s=>{this._logger.error("Metrics flush failed:",s)})),this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._retryAfter=new qe,this._consecutiveFlushFailures=0,this._flushJitter=ee,this._generation=0}count(e,t=1,n){this._capture({name:e,type:"count",value:t,unit:n?.unit,attributes:n?.attributes})}gauge(e,t,n){this._capture({name:e,type:"gauge",value:t,unit:n?.unit,attributes:n?.attributes})}histogram(e,t,n){this._capture({name:e,type:"histogram",value:t,unit:n?.unit,attributes:n?.attributes})}flush(){let e=this._flushPromise,n=(async()=>{e&&await e.catch(()=>{}),await this._doFlush()})().finally(()=>{this._flushPromise===n&&(this._flushPromise=null)});return this._flushPromise=n,n}drainWindow(){if(this._series.size===0)return null;let e=this._series;return this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._buildPayload(e)}reset(){this._generation++,this._retryAfter.reset(),this._consecutiveFlushFailures=0,this._flushJitter=ee,this._flushTimer.clear(),this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set}_capture(e){if(this._instance.isDisabled||this._instance.optedOut)return;let t=this._runBeforeSend(e);if(t===null)return;if(!t.name||typeof t.name!="string")return void this._logger.warn("Dropping metric with empty name");if(typeof t.value!="number"||!Number.isFinite(t.value))return void this._logger.warn(`Dropping metric '${t.name}': value must be a finite number`);if(t.type==="count"&&t.value<0)return void this._logger.warn(`Dropping count '${t.name}': counters are monotonic, value must be >= 0`);let n,s;try{n=t.attributes?{...t.attributes}:void 0,s=di(t.type,t.name,t.unit,n)}catch(a){this._logger.warn(`Dropping metric '${t.name}': attributes could not be serialized`,a);return}let i=this._series.get(s);if(!i){if(!this._admitNewSeries())return;i={name:t.name,type:t.type,unit:t.unit,attributes:n,windowStartMs:Date.now()},this._series.set(s,i)}let o=this._typeByName.get(t.name);o===void 0?this._typeByName.set(t.name,t.type):o!==t.type&&!this._typeCollisionWarned.has(t.name)&&(this._typeCollisionWarned.add(t.name),this._logger.warn(`Metric name '${t.name}' is already used as a ${o}; recording it as a ${t.type} too will blend both series in charts. Use a distinct name.`)),this._fold(i,t.value),this._armFlushTimer()}_admitNewSeries(){return this._series.size<this._config.maxSeriesPerFlush?!0:(this._seriesCapWarned||(this._seriesCapWarned=!0,this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`)),!1)}_fold(e,t){switch(e.type){case"count":e.total=(e.total??0)+t;break;case"gauge":e.last=t;break;case"histogram":{e.hist||(e.hist={count:0,sum:0,min:t,max:t,bucketCounts:new Array(Xt.length+1).fill(0)});let n=e.hist;n.count+=1,n.sum+=t,n.min=Math.min(n.min,t),n.max=Math.max(n.max,t),n.bucketCounts[_c(t,Xt)]+=1;break}}}_runBeforeSend(e){let t=this._config.beforeSend;if(!t)return e;let n=Y(t)?t:[t],s=e;for(let i of n)try{let o=i(s);if(!o)return this._logger.info("Metric was rejected in beforeSend function"),null;s=o}catch(o){return this._logger.error("Error in beforeSend function for metric:",o),null}return s}_armFlushTimer(){this._flushTimer.pending||this._flushTimer.arm(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(Jt(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}async _doFlush(){if(this._flushTimer.clear(),this._series.size===0)return;let e=this._series;this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set;let t=this._generation,n=await this._instance._sendMetricsBatch(this._buildPayload(e));if(t===this._generation)switch(this._retryAfter.record(n),n.kind==="retry-later"?(this._consecutiveFlushFailures++,this._flushJitter=Yt()):(this._consecutiveFlushFailures=0,this._flushJitter=ee),this._flushTimer.pending&&this._flushTimer.arm(this._nextFlushDelay()),n.kind){case"ok":return;case"retry-later":this._mergeWindowBack(e),this._flushTimer.armNoEarlierThan(this._nextFlushDelay());return;case"too-large":this._logger.warn("Metrics batch exceeded the server size limit and was dropped");return;case"fatal":this._logger.error("Failed to send metrics batch:",n.error);return}}_buildPayload(e){return pi(this._buildMetrics(e),fi(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._instance.getLibraryId(),this._instance.getLibraryVersion())}_buildMetrics(e){let t=ui(Date.now()),n=new Map;for(let s of e.values()){let i=di(s.type,s.name,s.unit,void 0),o=n.get(i);o||(o={name:s.name,...s.unit&&{unit:s.unit}},s.type==="count"?o.sum={aggregationTemporality:Ec,isMonotonic:!0,dataPoints:[]}:s.type==="gauge"?o.gauge={dataPoints:[]}:o.histogram={aggregationTemporality:Ec,dataPoints:[]},n.set(i,o));let a=le(s.attributes??{},this._logger),c=ui(s.windowStartMs);if(s.type==="count"){let l={attributes:a,startTimeUnixNano:c,timeUnixNano:t,asDouble:s.total??0};o.sum.dataPoints.push(l)}else if(s.type==="gauge"){let l={attributes:a,timeUnixNano:t,asDouble:s.last??0};o.gauge.dataPoints.push(l)}else if(s.hist){let l={attributes:a,startTimeUnixNano:c,timeUnixNano:t,count:s.hist.count,sum:s.hist.sum,min:s.hist.min,max:s.hist.max,bucketCounts:s.hist.bucketCounts,explicitBounds:Xt};o.histogram.dataPoints.push(l)}}return Array.from(n.values())}_mergeWindowBack(e){for(let[t,n]of e){let s=this._series.get(t);if(!s){this._admitNewSeries()&&this._series.set(t,n);continue}switch(s.windowStartMs=Math.min(s.windowStartMs,n.windowStartMs),s.type){case"count":s.total=(s.total??0)+(n.total??0);break;case"gauge":break;case"histogram":if(n.hist)if(s.hist){s.hist.count+=n.hist.count,s.hist.sum+=n.hist.sum,s.hist.min=Math.min(s.hist.min,n.hist.min),s.hist.max=Math.max(s.hist.max,n.hist.max);for(let i=0;i<s.hist.bucketCounts.length;i++)s.hist.bucketCounts[i]+=n.hist.bucketCounts[i]}else s.hist=n.hist;break}}}};var Rp="0".repeat(32),Cp="0".repeat(16),Mp=/^[0-9a-f]+$/;function xp(r){let e=new Uint8Array(r),t=globalThis.crypto;if(t&&typeof t.getRandomValues=="function")try{return t.getRandomValues(e),e}catch{}for(let n=0;n<r;n++)e[n]=Math.floor(256*Math.random());return e}function Fp(r){let e="";for(let t=0;t<r.length;t++)e+=r[t].toString(16).padStart(2,"0");return e}function yc(r){let e=Fp(xp(r));return/[^0]/.test(e)?e:e.slice(0,-1)+"1"}function Sc(){return yc(16)}function bc(){return yc(8)}function wc(r,e,t){return typeof r=="string"&&r.length===e&&r!==t&&Mp.test(r)}function vc(r){return wc(r,32,Rp)}function Ac(r){return wc(r,16,Cp)}var Op=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;function Tc(r){let e=Pc(r);return e&&{traceId:e.traceId,spanId:e.spanId,flags:kp(e.flags)}}function kp(r){return 1&parseInt(r,16)?vn:Dp}function Pc(r){if(typeof r!="string")return;let e=Op.exec(r.trim());if(!e)return;let[,t,n,s,i,o]=e;if(t!=="ff"&&!(t==="00"&&o)&&!(!vc(n)||!Ac(s)))return{version:t,traceId:n,spanId:s,flags:i}}function Ic(r){return Pc(r)&&r.trim()}function wn(r){return Array.isArray(r)&&r.length===1?r[0]:r}var vn="01",Dp="00";function Rc(r,e,t=vn){return`00-${r}-${e}-${t}`}var Lp=32,gi=512;function An(r){if(typeof r!="string")return;let e=r.trim();if(!e||/[^\x20-\x7e\t]/.test(e))return;let t=e.split(",");if(!(t.length>Lp)){for(let n of t)if(n.trim()&&!n.includes("="))return;return e.length<=gi?e:Up(t)}}var Np=128;function Up(r){let e=[...r],t=()=>e.reduce((n,s)=>n+s.length,0)+e.length-1;for(let n=e.length-1;n>=0&&t()>gi;n--)e[n].length>Np&&e.splice(n,1);for(;e.length&&t()>gi;)e.pop();return e.length?e.join(","):void 0}var Cc="unknown";function Ye(r,e,t,n){return typeof r=="string"&&r.trim()?r.length>t?r.slice(0,t):r:(n?.debug(`${e} must be a non-empty string; using "${Cc}"`),Cc)}function mt(r){if(r==null)return;let e=r;if(r instanceof Date)try{e=r.getTime()}catch{return}if(!(typeof e!="number"||!Number.isFinite(e))&&!(e<0||e>9223372036854))return e}function Mc(r,e,t){let n=mt(r);return n===void 0?(r!==void 0&&t?.debug("Span startTime is out of range or not a valid time; using the current time"),e):(e-n>864e5?t?.debug("Span startTime is more than 24 hours in the past; the server will clamp it to receive time and keep the original in $originalTimestamp"):n>e&&t?.debug("Span startTime is in the future; the span may export with a zero duration"),n)}function Tn(r,e){return r<e?e:r}function Zt(r,e,t,n){let s=mt(r);return s===void 0?(r!==void 0&&n?.debug(`Span ${t} is out of range or not a valid time; using the derived time`),e):s}function In(){let r=globalThis.performance;return typeof r?.now=="function"?r.now():void 0}var _t=class{constructor(e,t,n){this._onEnd=t,this._logger=n,this._events=[],this._ended=!1,this._userAttributeCount=0,this._userEventCount=0,this._droppedAttributes=0,this._droppedEvents=0,this._traceId=e.traceId,this._spanId=e.spanId,this._parentSpanId=e.parentSpanId,this._traceState=e.traceState,this._traceFlags=e.traceFlags??vn,this._parentIsRemote=e.parentIsRemote??!1,this._name=e.name,this._kind=e.kind,this._autoKeys=new Set(e.autoAttributeKeys),this._maxAttributes=e.maxAttributes,this._maxEvents=e.maxEvents,this._maxAttributesPerEvent=e.maxAttributesPerEvent,this._maxAttributeValueLength=e.maxAttributeValueLength,this._attributes=Object.create(null);for(let s of Object.keys(e.attributes))this._writeAttribute(s,e.attributes[s]);this._startMono=e.backdated?void 0:In(),this._startTime=e.clockAnchor&&this._startMono!==void 0?e.clockAnchor.wall+(this._startMono-e.clockAnchor.mono):e.startTime,this._startMono!==void 0&&(this._clockAnchor=e.clockAnchor??{wall:this._startTime,mono:this._startMono})}_now(){if(this._startMono!==void 0){let e=In();if(e!==void 0)return this._startTime+Math.max(0,e-this._startMono)}return Date.now()}_mutable(e){return this._ended?(this._logger?.debug(`Ignoring ${e} on a span that has already ended`),!1):!0}_writeAttribute(e,t){if(re(t)){e in this._attributes&&!this._autoKeys.has(e)&&this._userAttributeCount--,delete this._attributes[e];return}if(!this._autoKeys.has(e)&&!(e in this._attributes)){if(this._userAttributeCount>=this._maxAttributes)return void this._droppedAttributes++;this._userAttributeCount++}this._attributes[e]=Cn(t,this._maxAttributeValueLength)}setAttribute(e,t){return this._mutable("setAttribute")&&this._writeAttribute(e,t),this}setAttributes(e){if(this._mutable("setAttributes")){let t=Ae({},e);for(let n of Object.keys(t))this._writeAttribute(n,t[n])}return this}addEvent(e,t,n){if(this._mutable("addEvent")){if(this._userEventCount>=this._maxEvents)return this._droppedEvents++,this;this._userEventCount++;let s=t&&kc(t,this._maxAttributesPerEvent,this._maxAttributeValueLength);this._events.push({name:Ye(e,"Span event name",this._maxAttributeValueLength,this._logger),timestamp:Zt(n,this._now(),"event timestamp",this._logger),...s&&{attributes:s.attributes,...s.dropped&&{droppedAttributesCount:s.dropped}}})}return this}setStatus(e,t){if(this._mutable("setStatus")){if(e!=="ok"&&e!=="error")return this._logger?.debug(`Ignoring unknown span status "${String(e)}"; expected "ok" or "error"`),this;this._status={code:e,...t&&{message:hi(t,this._maxAttributeValueLength)}}}return this}get statusIsExplicitlyOk(){return this._status?.code==="ok"}recordException(e){if(!this._mutable("recordException"))return this;let{type:t,message:n,stack:s}=mi(e);return this.addEvent($p,{"exception.type":t,"exception.message":n,...s&&{"exception.stacktrace":s}}),this.setStatus("error",n)}updateName(e){return this._mutable("updateName")&&(this._name=Ye(e,"Span name",this._maxAttributeValueLength,this._logger)),this}traceparent(){return Rc(this._traceId,this._spanId,this._traceFlags)}tracestate(){return this._traceState??null}childContext(){return{traceId:this._traceId,parentSpanId:this._spanId,traceState:this._traceState,traceFlags:this._traceFlags,clockAnchor:this._clockAnchor}}end(e){if(this._ended)return void this._logger?.debug("Ignoring end() on a span that has already ended");this._ended=!0;let t=this._now(),n=Zt(e,t,"end time",this._logger);this._onEnd({traceId:this._traceId,spanId:this._spanId,...this._parentSpanId&&{parentSpanId:this._parentSpanId},...this._traceState&&{traceState:this._traceState},traceFlags:this._traceFlags,parentIsRemote:this._parentIsRemote,name:this._name,kind:this._kind,...this._status&&{status:this._status},attributes:{...this._attributes},events:this._events,startTime:this._startTime,endTime:Tn(n,this._startTime),...this._droppedAttributes&&{droppedAttributesCount:this._droppedAttributes},...this._droppedEvents&&{droppedEventsCount:this._droppedEvents}},this._autoKeys)}},$p="exception",jp=4294967295;function Bp(r){try{return typeof r=="string"?r:String(r)}catch{return J}}function Je(r){return typeof r!="number"||!Number.isFinite(r)||r<=0?0:Math.min(Math.floor(r),jp)}function Wp(r,e){if(!e.length)return Object.keys(r);let t=e.filter(s=>Object.prototype.propertyIsEnumerable.call(r,s)),n=new Set(t);return[...t,...Object.keys(r).filter(s=>!n.has(s))]}function Fc(r,e,t,n,s,i,o=[]){let a=0,c=0,l={};for(let p of Wp(r.attributes,o)){let h=r.attributes[p];if(!re(h)){if(!e.has(p)){if(a>=t){c++;continue}a++}Object.defineProperty(l,p,{value:Cn(h,i),enumerable:!0,writable:!0,configurable:!0})}}r.attributes=l,c&&(r.droppedAttributesCount=Je(r.droppedAttributesCount)+c);let u=0,d=0,g=[];for(let p of r.events){if(u>=n){d++;continue}if(u++,p.attributes){let h=kc(p.attributes,s,i);p.attributes=h.attributes,h.dropped&&(p.droppedAttributesCount=Je(p.droppedAttributesCount)+h.dropped)}g.push(p)}r.events=g,d&&(r.droppedEventsCount=Je(r.droppedEventsCount)+d),r.status?.message&&(r.status={...r.status,message:hi(Bp(r.status.message),i)})}var Rn=class{setAttribute(){return this}setAttributes(){return this}addEvent(){return this}setStatus(){return this}recordException(){return this}updateName(){return this}traceparent(){return null}tracestate(){return null}end(){}},Oc=new Rn,er=class extends Rn{constructor(e,t){super(),this._traceparent=e,this._tracestate=t}traceparent(){return this._traceparent}tracestate(){return this._tracestate??null}};function Hp(r){try{let e=r.stack;return typeof e=="string"&&e?{stack:e}:{}}catch{return{}}}function Le(r,e){let t=wn(r?.parent)??e,n=typeof t=="string"||t==null?t:xc(t,"traceparent"),s=Ic(n);if(!s)return Oc;let i=typeof t=="string"||t==null?r?.tracestate:xc(t,"tracestate");return new er(s,An(i))}function xc(r,e){try{let t=r[e];return typeof t=="function"?t.call(r):void 0}catch{return}}function hi(r,e){return r.length>e?r.slice(0,e):r}function Cn(r,e){return Pn(r,e,{ancestors:new WeakSet,remainingNodes:1e4},0)}function Pn(r,e,t,n){if(r===null||typeof r!="object")return re(r)||t.remainingNodes<=0?r:(t.remainingNodes--,typeof r=="string"?hi(r,e):r);if(t.ancestors.has(r))return an;if(t.remainingNodes<=0||n>=20)return r;t.remainingNodes--,t.ancestors.add(r);try{if(r instanceof Date)return r;let s=Gp(r);if(s.selfDescribed)return re(s.value)?String(s.value):Pn(s.value,e,t,n+1);if(Y(r)){let a=Math.min(r.length,1e3),c=[];for(let l=0;l<a;l++)try{c.push(Pn(r[l],e,t,n+1))}catch{c.push(J)}return r.length>a&&(c.length=r.length),c}let i={},o=0;for(let a of Object.keys(r)){if(o>=1e3)break;let c;try{c=Pn(r[a],e,t,n+1)}catch{c=J}a&&!re(c)&&o++,Object.defineProperty(i,a,{value:c,enumerable:!0,writable:!0,configurable:!0})}return i}catch{return r}finally{t.ancestors.delete(r)}}function Gp(r){try{let e=r.toJSON;if(typeof e=="function")return{selfDescribed:!0,value:e.call(r)}}catch{}return{selfDescribed:!1}}function kc(r,e,t){let n;try{n=Object.keys(r)}catch{return{attributes:{},dropped:0}}let s={},i=0,o=0;for(let a of n){if(i>=e){o++;continue}let c;try{c=Cn(r[a],t)}catch{c=J}re(c)||(i++,Object.defineProperty(s,a,{value:c,enumerable:!0,writable:!0,configurable:!0}))}return{attributes:s,dropped:o}}function Dc(r,e){for(let t of Object.keys(r))r[t]=Cn(r[t],e);return r}function tr(r,e,t){return e===Oc?t(e):r.with(e,()=>t(e))}function mi(r){try{let e=Hp(r);if(lt(r))return{type:r.name||"Error",message:r.message||"",...e};if(typeof r=="string")return{type:"string",message:r};if(r&&typeof r=="object"){let t=r;if(typeof t.message=="string")return{type:typeof t.name=="string"?t.name:"Object",message:t.message,...e}}return{type:typeof r,message:String(r)}}catch{return{type:typeof r,message:""}}}var _i={internal:1,server:2,client:3,producer:4,consumer:5},Kp={ok:1,error:2},Vp=1,qp=256,zp=512;function Yp(r){let e=parseInt(r.traceFlags,16);return(Number.isFinite(e)?255&e:Vp)|qp|(r.parentIsRemote?zp:0)}function Mn(r){if(typeof r=="string")return ae(r);try{return ae(String(r))}catch{return J}}function Jp(r){return r&&Object.prototype.hasOwnProperty.call(_i,r)?_i[r]:_i.internal}function Ei(r){let e=Math.floor(r),t=Math.round((r-e)*1e6);return t>=1e6&&(e+=1,t=0),String(e)+String(t).padStart(6,"0")}function Xp(r,e){let t={name:Mn(r.name),timeUnixNano:Ei(r.timestamp)};if(r.attributes){let s=le(r.attributes,e);s.length&&(t.attributes=s)}let n=Je(r.droppedAttributesCount);return n&&(t.droppedAttributesCount=n),t}function Lc(r,e){let t={traceId:r.traceId,spanId:r.spanId,name:Mn(r.name),kind:Jp(r.kind),startTimeUnixNano:Ei(r.startTime),endTimeUnixNano:Ei(r.endTime),flags:Yp(r)};r.parentSpanId&&(t.parentSpanId=r.parentSpanId),r.traceState&&(t.traceState=Mn(r.traceState));let n=le(r.attributes,e);n.length&&(t.attributes=n),r.events.length&&(t.events=r.events.map(o=>Xp(o,e)));let s=Je(r.droppedAttributesCount);s&&(t.droppedAttributesCount=s);let i=Je(r.droppedEventsCount);return i&&(t.droppedEventsCount=i),r.status&&(t.status={code:Kp[r.status.code],...r.status.message&&{message:Mn(r.status.message)}}),t}function Nc(r,e,t){return qt(r,e,t)}function Uc(r,e,t,n,s){return{resourceSpans:[{resource:{attributes:zt(e,s)},scopeSpans:[{scope:{name:t,version:n},spans:r}]}]}}var $c=8;function xn(){return In()??Date.now()}function yi(r){try{return r instanceof _t}catch{return!1}}function jc(r,e){let t=Tc(r);if(t)return{traceId:t.traceId,parentSpanId:t.spanId,traceState:An(e),traceFlags:t.flags,isRemote:!0}}function Qp(r){try{return typeof r.traceparent=="function"}catch{return!1}}function Zp(r){return!!r.attributes&&typeof r.attributes=="object"&&!Array.isArray(r.attributes)&&Array.isArray(r.events)&&r.name!==void 0&&r.kind!==void 0&&r.startTime!==void 0&&r.endTime!==void 0}function Fn(r,e,t){r[e]!==t&&(r[e]=t)}function eg(r,e){try{let t=Object.getOwnPropertyDescriptors(r);for(let n of["traceId","spanId","parentSpanId","traceState"])t[n]={value:e[n],enumerable:!0,writable:!0,configurable:!0};return Object.create(Object.getPrototypeOf(r),t)}catch{return r}}var rr=class{constructor(e,t,n,s,i,o){this._instance=e,this._config=t,this._logger=n,this._getContext=s,this._contextManager=i,this._onSpanQueued=o,this._queue=[],this._flushTimer=new ze(()=>this._flushInBackground()),this._flushPromise=null,this._droppedSinceWarning=0,this._lastDropWarningAt=0,this._dropReasons=new Set,this._consecutiveFlushFailures=0,this._flushJitter=ee,this._retryAfter=new qe,this._headBatchFailures=0,this._headBatchSize=0,this._headBatchChargeableAt=0,this._generation=0,this._liveSpans=new Map,this._maxExportBatchSize=t.maxExportBatchSize}startSpan(e,t){if(this._instance.isDisabled||this._instance.optedOut)return Le(t,this._contextManager.active());let n=wn(t?.parent);if(n&&typeof n!="string"&&!yi(n)){if(Qp(n))return this._logger.debug("Span parent is not a span from this SDK; returning an inert span"),Le(t,this._contextManager.active());this._logger.debug("Ignoring an unusable span parent")}let s=this._resolveParent(n,t);if(this._evictAgedSpans(),this._liveSpans.size>=this._config.maxLiveSpans)return this._recordDrop(1,`the live-span limit (${this._config.maxLiveSpans}) was reached \u2014 spans are being started and never ended`),Le(t,this._contextManager.active());let i=Date.now(),o=Mc(t?.startTime,i,this._logger),a=bc();this._liveSpans.set(a,xn());let c=this._autoContextAttributes();return new _t({traceId:s?.traceId??Sc(),spanId:a,parentSpanId:s?.parentSpanId,traceState:s?.traceState,traceFlags:s?.traceFlags,parentIsRemote:s?.isRemote,name:Ye(e,"Span name",this._config.maxAttributeValueLength,this._logger),kind:t?.kind??"internal",attributes:Ae({...c},t?.attributes),autoAttributeKeys:Object.keys(c),maxAttributes:this._config.maxAttributesPerSpan,maxEvents:this._config.maxEventsPerSpan,maxAttributesPerEvent:this._config.maxAttributesPerEvent,maxAttributeValueLength:this._config.maxAttributeValueLength,startTime:o,backdated:o!==i,clockAnchor:mt(t?.startTime)===void 0?s?.clockAnchor:void 0},(l,u)=>this._onSpanEnd(l,u),this._logger)}withSpan(e,t,n){let s=typeof t=="function"?void 0:t,i=typeof t=="function"?t:n,o=this.startSpan(e,s);try{let a=tr(this._contextManager,o,i);return Na(a)?a.then(c=>(o.end(),c),c=>{throw this._recordCallbackError(o,c),o.end(),c}):(o.end(),a)}catch(a){throw this._recordCallbackError(o,a),o.end(),a}}getActiveSpan(){return this._contextManager.active()??null}get throttled(){return this._retryAfter.isOpen()}async flush(){for(;;)if(!this._queue.length||!await(this._flushPromise??this._startFlush()))return}_startFlush(){this._flushTimer.clear();let e=this._generation,t=Promise.resolve().then(()=>e===this._generation?this._flushInner():0).finally(()=>{this._flushPromise===t&&(this._flushPromise=null),this._armFlushTimerIfQueuedNoEarlierThan()});return this._flushPromise=t,t}reset(){this._flushTimer.clear(),this._queue.length&&this._logger.critical(`Discarding ${this._queue.length} span(s) that were still queued when tracing was shut down. Raise the shutdown timeout or flush earlier if they matter.`),this._queue=[],this._liveSpans.clear(),this._flushPromise=null,this._generation++,this._maxExportBatchSize=this._config.maxExportBatchSize,this._droppedSinceWarning=0,this._dropReasons.clear(),this._lastDropWarningAt=0,this._consecutiveFlushFailures=0,this._flushJitter=ee,this._retryAfter.reset(),this._resetHeadBatchBudget()}_resetHeadBatchBudget(){this._headBatchFailures=0,this._headBatchChargeableAt=0}_resolveParent(e,t){if(typeof e=="string"){let s=jc(e,t?.tracestate);return s||this._logger.debug("Ignoring malformed traceparent; starting a new trace"),s}if(yi(e))return e.childContext();let n=this._contextManager.active();if(yi(n))return n.childContext();if(n instanceof er)return jc(n.traceparent(),n.tracestate()??void 0)}_autoContextAttributes(){let e;try{e=this._getContext()}catch(n){return this._logger.debug("Failed to read tracing context; span will carry no PostHog attributes",n),{}}let t={};return e.distinctId&&(t.posthogDistinctId=e.distinctId),e.sessionId&&(t.sessionId=e.sessionId),e.currentUrl&&(t["url.full"]=e.currentUrl),e.screenName&&(t["screen.name"]=e.screenName),e.appState&&(t["app.state"]=e.appState),t}_recordCallbackError(e,t){if(!(e instanceof _t))return;let{type:n,message:s,stack:i}=mi(t);e.addEvent("exception",{"exception.type":n,"exception.message":s,...i&&{"exception.stacktrace":i}}),e.statusIsExplicitlyOk||e.setStatus("error",s)}_evictAgedSpans(){let e=xn()-this._config.maxSpanAgeMs,t=0;for(let[n,s]of this._liveSpans){if(s>e)break;this._liveSpans.delete(n),t++}t&&this._recordDrop(t,`they were still live after ${this._config.maxSpanAgeMs}ms`)}_onSpanEnd(e,t){if(!this._liveSpans.delete(e.spanId))return;if(this._instance.isDisabled||this._instance.optedOut)return void this._recordDrop(1,"the user has opted out");let n=this._runBeforeSpanSend(e,t);if(n){if(this._reportLimitDrops(n),this._queue.length>=this._config.maxQueueSize)return void this._recordDrop(1,`the queue is full (${this._config.maxQueueSize}) \u2014 raise the flush frequency or reduce span volume`);this._queue.push(n);try{this._onSpanQueued?.()}catch(s){this._logger.debug("Span queue notification failed",s)}!(this._queue.length>=this._maxExportBatchSize)||this._consecutiveFlushFailures||this._retryAfter.isOpen()?this._armFlushTimerIfQueued():this._flushInBackground()}}_reportLimitDrops(e){let t=e.droppedAttributesCount??0,n=e.droppedEventsCount??0,s=0;for(let i of e.events)s+=i.droppedAttributesCount??0;(t||n||s)&&this._logger.debug(`Span limits discarded data from "${e.name}": ${t} attributes, ${n} events, ${s} event attributes`)}_runBeforeSpanSend(e,t){if(!this._config.beforeSpanSend.length)return e;let n={traceId:e.traceId,spanId:e.spanId,parentSpanId:e.parentSpanId,traceState:e.traceState},s={startTime:e.startTime,endTime:e.endTime},i={attributes:e.droppedAttributesCount,events:e.droppedEventsCount},o=Object.keys(e.attributes),a={traceFlags:e.traceFlags,parentIsRemote:e.parentIsRemote},c=e.status&&{...e.status},l=e,u=e;try{for(let p of this._config.beforeSpanSend){let h=p(l);if(!h)return this._recordDrop(1,"beforeSpanSend dropped it"),null;l=this._keepSpanIdentity(h,n)}if(u={traceId:n.traceId,spanId:n.spanId,parentSpanId:n.parentSpanId,traceState:n.traceState,name:l.name,kind:l.kind,status:l.status,attributes:l.attributes,events:l.events,startTime:l.startTime,endTime:l.endTime,traceFlags:a.traceFlags,parentIsRemote:a.parentIsRemote,droppedAttributesCount:i.attributes,droppedEventsCount:i.events},!Zp(u))return this._logger.debug("beforeSpanSend did not return a span record; dropping the span"),this._recordDrop(1,"beforeSpanSend returned an unusable record"),null;u.name=Ye(u.name,"Span name",this._config.maxAttributeValueLength,this._logger),u.status&&u.status.code!=="ok"&&u.status.code!=="error"&&(this._logger.debug("beforeSpanSend set an unknown span status; keeping the original"),u.status=c),u.startTime=mt(u.startTime)??s.startTime,u.endTime=Tn(mt(u.endTime)??s.endTime,u.startTime);let g=[];for(let p of u.events)try{g.push({...p,name:Ye(p.name,"Span event name",this._config.maxAttributeValueLength,this._logger),timestamp:Zt(p.timestamp,u.startTime,"event timestamp",this._logger)})}catch{this._logger.debug("beforeSpanSend left an unreadable span event; dropping it")}return u.events=g,Fc(u,t,this._config.maxAttributesPerSpan,this._config.maxEventsPerSpan,this._config.maxAttributesPerEvent,this._config.maxAttributeValueLength,o),u}catch(d){return this._logger.debug("beforeSpanSend failed; dropping the span rather than exporting it unscrubbed",d),this._recordDrop(1,"beforeSpanSend failed"),null}}_keepSpanIdentity(e,t){(e.traceId!==t.traceId||e.spanId!==t.spanId||e.parentSpanId!==t.parentSpanId)&&this._logger.debug("beforeSpanSend changed a span identity field; keeping the original ids");try{Fn(e,"traceId",t.traceId),Fn(e,"spanId",t.spanId),Fn(e,"parentSpanId",t.parentSpanId),Fn(e,"traceState",t.traceState)}catch{return eg(e,t)}return e}_recordDrop(e,t){this._droppedSinceWarning+=e,this._dropReasons.add(t),Date.now()-this._lastDropWarningAt>=this._config.flushIntervalMs&&this._warnAboutDrops()}_warnAboutDrops(){this._droppedSinceWarning&&(this._lastDropWarningAt=Date.now(),this._logger.warn(`Dropping ${this._droppedSinceWarning} span(s): ${[...this._dropReasons].join("; ")}`),this._droppedSinceWarning=0,this._dropReasons.clear())}_encodeBatch(e){let t=[];for(let n of e)try{t.push(Lc(n,this._logger))}catch(s){this._logger.debug("Failed to encode a span; dropping it",s),this._recordDrop(1,"its attributes could not be encoded")}return t}_discardQueueIfConsentWithdrawn(){if(!this._instance.isDisabled&&!this._instance.optedOut)return 0;let e=this._queue.length;return this._queue=[],this._resetHeadBatchBudget(),this._recordDrop(e,"the user has opted out"),this._warnAboutDrops(),e}async _flushInner(){if(!this._queue.length)return 0;let e=this._discardQueueIfConsentWithdrawn();if(e)return e;let t=Dc(Nc(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._config.maxAttributeValueLength),n=this._instance.getLibraryId(),s=this._instance.getLibraryVersion(),i=this._queue.length,o=0,a=1/0,c=this._generation;try{for(;i>0&&this._queue.length>0;){let l=this._discardQueueIfConsentWithdrawn();if(l)return o+l;let u=this._headBatchFailures>0?Math.min(this._maxExportBatchSize,this._headBatchSize):this._maxExportBatchSize,d=Math.max(1,Math.min(u,a,i,this._queue.length)),g=this._queue.slice(0,d),p=this._encodeBatch(g);if(!p.length){this._queue.splice(0,d),i-=d,o+=d,this._resetHeadBatchBudget();continue}let h=xn()>=this._headBatchChargeableAt&&!this._retryAfter.isOpen(),m=await this._instance._sendTracesBatch(Uc(p,t,n,s,this._logger));if(c!==this._generation)break;if(this._retryAfter.record(m),m.kind==="ok"){this._consecutiveFlushFailures=0,this._flushJitter=ee,this._resetHeadBatchBudget(),this._queue.splice(0,d),i-=d,o+=d,this._maxExportBatchSize<this._config.maxExportBatchSize&&this._maxExportBatchSize++;continue}if(m.kind==="too-large"){if(d===1){this._queue.splice(0,1),i-=1,o+=1,this._recordDrop(1,"it is too large for the ingestion endpoint"),this._consecutiveFlushFailures=0,this._flushJitter=ee,this._resetHeadBatchBudget();continue}let E=Math.max(1,Math.floor(d/2));m.measuredLocally?a=E:this._maxExportBatchSize=E,this._resetHeadBatchBudget(),this._logger.debug(`Batch too large; retrying the same spans in batches of ${E}`);continue}if(m.kind==="retry-later"){if(this._consecutiveFlushFailures++,this._flushJitter=Yt(),this._headBatchSize=d,h&&(this._headBatchFailures++,this._headBatchChargeableAt=xn()+this._nextFlushDelay()),this._headBatchFailures<$c)return this._logger.debug("Span export failed; retrying on the next flush",m.error),o;if(this._queue.splice(0,d),i-=d,o+=d,this._consecutiveFlushFailures=0,this._flushJitter=ee,this._resetHeadBatchBudget(),this._recordDrop(d,`the ingestion endpoint failed ${$c} times in a row`),this._retryAfter.isOpen())return o;continue}this._logger.debug("Dropping a span batch the ingestion endpoint rejected",m.error),this._queue.splice(0,d),i-=d,o+=d,this._consecutiveFlushFailures=0,this._flushJitter=ee,this._resetHeadBatchBudget(),this._recordDrop(d,"the ingestion endpoint rejected the batch")}return o}finally{this._warnAboutDrops()}}_flushInBackground(){this._backgroundFlush||(this._backgroundFlush=this.flush().catch(e=>{this._logger.debug("Background span flush failed",e)}).finally(()=>{this._backgroundFlush=void 0,this._armFlushTimerIfQueuedNoEarlierThan()}))}_armFlushTimerIfQueued(){this._flushTimer.pending||!this._queue.length||this._flushTimer.arm(this._nextFlushDelay())}_armFlushTimerIfQueuedNoEarlierThan(){this._queue.length&&this._flushTimer.armNoEarlierThan(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(Jt(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}};var nr=class{active(){return this._active}with(e,t){let n=this._active;this._active=e;try{return t()}finally{this._active=n}}};var tg=5e3,rg=512,ng=2048,sg=128,ig=128,og=128,ag=8192,cg=1e4,lg=36e5;function Ne(r,e){return typeof r=="number"&&Number.isInteger(r)&&r>=1?r:e}var Bc=["service.name","service.version","deployment.environment"];function ug(r){if(!(!r||typeof r!="object"||Array.isArray(r)))try{if(Bc.every(t=>!(t in r)||typeof r[t]=="string"))return r;let e={...r};for(let t of Bc)t in e&&typeof e[t]!="string"&&delete e[t];return e}catch{return}}function dg(r,e){if(!r)return[];let t=[r].flat().filter(s=>!!s),n=t.filter(s=>typeof s=="function");return n.length!==t.length&&e?.critical(`beforeSpanSend: ignoring ${t.length-n.length} of ${t.length} entries that are not functions. Spans export without them, so whatever they were redacting is not redacted.`),n}function Si(r,e,t){let n=Ae({...e},ug(r?.resourceAttributes)),s=Ne(r?.maxExportBatchSize,rg);return{serviceName:n?.["service.name"]??r?.serviceName,serviceVersion:n?.["service.version"]??r?.serviceVersion,environment:n?.["deployment.environment"]??r?.environment,resourceAttributes:n,beforeSpanSend:dg(r?.beforeSpanSend,t),maxAttributesPerSpan:Ne(r?.maxAttributesPerSpan,sg),maxEventsPerSpan:Ne(r?.maxEventsPerSpan,ig),maxAttributesPerEvent:og,maxAttributeValueLength:Ne(r?.maxAttributeValueLength,ag),flushIntervalMs:Ne(r?.flushIntervalMs,tg),maxExportBatchSize:s,maxQueueSize:Math.max(Ne(r?.maxQueueSize,ng),s),maxLiveSpans:Ne(r?.maxLiveSpans,cg),maxSpanAgeMs:Ne(r?.maxSpanAgeMs,lg)}}var bi=require("node:fs"),Gc=require("node:fs/promises"),vi=require("node:path"),Kc=require("node:readline"),On=new D.ReduceableCache(25),sr=new D.ReduceableCache(20),Ai=7,fg=1e3,pg=1e4,wi=10485760;async function Vc(r,e=Gc.open,t){let n={},s;try{s=process.cwd()}catch{}for(let a=r.length-1;a>=0;a--){let c=r[a],l=c?.filename;if(!c||typeof l!="string"||typeof c.lineno!="number"||Eg(l)||yg(c)||!(0,vi.isAbsolute)(l)&&s===void 0)continue;n[l]||(n[l]=[]),n[l].push(c.lineno)}let i=Object.keys(n);if(i.length==0)return r;let o=[];for(let a of i){let c=qc(a,s);if(c===void 0||sr.get(c))continue;let l=n[a];if(!l)continue;l.sort((g,p)=>g-p);let u=bg(l);if(u.every(g=>Sg(c,g)))continue;let d=wg(On,c,{});o.push(hg(a,u,d,c,e,t))}return await Promise.all(o).catch(()=>{}),r&&r.length>0&&mg(r,On,s),On.reduce(),r}async function gg(r,e,t){let n,s=!1;try{n=await e(r,bi.constants.O_RDONLY|bi.constants.O_NONBLOCK);let i=await n.stat();return i.isFile()?i.size>wi?void t?.debug(`Skipping source context for oversized file ${r}: ${i.size} bytes exceeds ${wi}`):(s=!0,n):void 0}catch{return}finally{n&&!s&&await n.close().catch(()=>{})}}async function hg(r,e,t,n,s,i){let o=await gg(r,s,i);if(o===void 0)return void sr.set(n,1);let a=o;return new Promise(c=>{let l=!1;function u(P){l||(l=!0,P?.destroy(),a.close().then(c,c))}let d;try{d=a.createReadStream({autoClose:!1,start:0,end:wi-1})}catch{sr.set(n,1),u();return}let g;try{g=(0,Kc.createInterface)({input:d})}catch{sr.set(n,1),u(d);return}let p=0,h=0,m=e[h];if(m===void 0)return void u(d);let E=m[0],_=m[1];function b(){sr.set(n,1),g.close(),g.removeAllListeners(),u(d)}d.on("error",b),g.on("error",b),g.on("close",()=>u(d)),g.on("line",P=>{if(p++,!(p<E)&&(t[p]=vg(P,0),p>=_)){if(h===e.length-1){g.close(),g.removeAllListeners();return}h++;let R=e[h];if(R===void 0){g.close(),g.removeAllListeners();return}E=R[0],_=R[1]}})})}function mg(r,e,t){for(let n of r)if(n.filename&&n.context_line===void 0&&typeof n.lineno=="number"){let s=qc(n.filename,t),i=s===void 0?void 0:e.get(s);if(i===void 0)continue;_g(n.lineno,n,i)}}function _g(r,e,t){if(e.lineno===void 0||t===void 0)return;e.pre_context=[];for(let s=zc(r);s<r;s++){let i=t[s];if(i===void 0)return void Wc(e);e.pre_context.push(i)}if(t[r]===void 0)return void Wc(e);e.context_line=t[r];let n=Yc(r);e.post_context=[];for(let s=r+1;s<=n;s++){let i=t[s];if(i===void 0)break;e.post_context.push(i)}}function Wc(r){delete r.pre_context,delete r.context_line,delete r.post_context}function Eg(r){return r.startsWith("node:")||r.endsWith(".min.js")||r.endsWith(".min.cjs")||r.endsWith(".min.mjs")||r.startsWith("data:")}function yg(r){return r.lineno!==void 0&&r.lineno>pg||r.colno!==void 0&&r.colno>fg}function qc(r,e){return(0,vi.isAbsolute)(r)?JSON.stringify([null,r]):e===void 0?void 0:JSON.stringify([e,r])}function Sg(r,e){let t=On.get(r);if(t===void 0)return!1;for(let n=e[0];n<=e[1];n++)if(t[n]===void 0)return!1;return!0}function bg(r){if(!r.length)return[];let e=0,t=r[0];if(typeof t!="number")return[];let n=Hc(t),s=[];for(;;){if(e===r.length-1){s.push(n);break}let i=r[e+1];if(typeof i!="number")break;i<=n[1]?n[1]=i+Ai:(s.push(n),n=Hc(i)),e++}return s}function Hc(r){return[zc(r),Yc(r)]}function zc(r){return Math.max(1,r-Ai)}function Yc(r){return r+Ai}function wg(r,e,t){let n=r.get(e);return n===void 0?(r.set(e,t),t):n}function vg(r,e){let t=r,n=t.length;if(n<=150)return t;e>n&&(e=n);let s=Math.max(e-60,0);s<5&&(s=0);let i=Math.min(s+140,n);return i>n-5&&(i=n),i===n&&(s=Math.max(i-140,0)),t=t.slice(s,i),s>0&&(t=`...${t}`),i<n&&(t+="..."),t}var Et=require("path");function Jc(r=process.cwd()){let e=Et.sep==="\\",t=s=>e?s.replace(/\\/g,"/"):s,n=t(r);return async s=>{for(let i of s)!i.filename||i.filename.startsWith("node:")||i.filename.startsWith("data:")||(0,Et.isAbsolute)(i.filename)&&(i.filename=t((0,Et.relative)(n,t(i.filename))));return s}}var Xc="5.52.1";var Pe={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};var Ue=class r{constructor(e){this._host=e.host,this._distinctId=e.distinctId,this._groups=e.groups,this._disableGeoip=e.disableGeoip,this._flags=e.flags,this._requestId=e.requestId,this._evaluatedAt=e.evaluatedAt,this._flagDefinitionsLoadedAt=e.flagDefinitionsLoadedAt,this._errorsWhileComputing=e.errorsWhileComputing??!1,this._quotaLimited=e.quotaLimited??!1,this._accessed=e.accessed??new Set,this._isSlice=e.isSlice??!1}isEnabled(e,t={}){let n=this._flags[e];return this._recordAccess(e),n?.enabled??t.defaultValue??!1}getFlag(e){let t=this._flags[e];if(this._recordAccess(e),!!t)return t.enabled?t.variant??!0:!1}getFlagPayload(e){return this._flags[e]?.payload}onlyAccessed(){let e={};for(let t of this._accessed){let n=this._flags[t];n&&(e[t]=n)}return this._cloneWith(e)}only(e){let t={},n=[];for(let s of e){let i=this._flags[s];i?t[s]=i:n.push(s)}return n.length>0&&this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${n.join(", ")}`),this._cloneWith(t)}get keys(){return Object.keys(this._flags)}_getEventProperties(){let e={},t=[];for(let[n,s]of Object.entries(this._flags)){let i=s.enabled===!1?!1:s.variant??!0;e[`$feature/${n}`]=i,s.enabled&&t.push(n)}return t.length>0&&(t.sort(),e.$active_feature_flags=t),e}_cloneWith(e){return new r({host:this._host,distinctId:this._distinctId,groups:this._groups,disableGeoip:this._disableGeoip,flags:e,requestId:this._requestId,evaluatedAt:this._evaluatedAt,flagDefinitionsLoadedAt:this._flagDefinitionsLoadedAt,errorsWhileComputing:this._errorsWhileComputing,quotaLimited:this._quotaLimited,accessed:new Set(this._accessed),isSlice:!0})}_recordAccess(e){if(this._accessed.add(e),this._distinctId===""||this._isSlice&&!(e in this._flags))return;let t=this._flags[e],n=t===void 0?void 0:t.enabled===!1?!1:t.variant??!0,s={$feature_flag:e,$feature_flag_response:n,$feature_flag_id:t?.id,$feature_flag_version:t?.version,$feature_flag_reason:t?.reason,locally_evaluated:t?.locallyEvaluated??!1,[`$feature/${e}`]:n,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:t?.locallyEvaluated?Date.now():this._evaluatedAt};t?.hasExperiment!==void 0&&(s.$feature_flag_has_experiment=t.hasExperiment),t?.locallyEvaluated&&this._flagDefinitionsLoadedAt!==void 0&&(s.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt);let i=[];this._errorsWhileComputing&&i.push(Pe.ERRORS_WHILE_COMPUTING),this._quotaLimited&&i.push(Pe.QUOTA_LIMITED),t===void 0&&i.push(Pe.FLAG_MISSING),i.length>0&&(s.$feature_flag_error=i.join(",")),this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:e,response:n,groups:this._groups,disableGeoip:this._disableGeoip,properties:s})}};var Ag=6e4,yt=class r extends Error{constructor(e){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=e,Object.setPrototypeOf(this,r.prototype)}};function Tg(r,e){r.name=e.name,Error.captureStackTrace(r,e),Object.setPrototypeOf(r,e.prototype)}var ue=class r extends Error{constructor(e){super(e),Tg(this,r)}},kn=class{constructor({pollingInterval:e,personalApiKey:t,projectApiKey:n,timeout:s,host:i,customHeaders:o,...a}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollerStopped=!1,this.filteredOutFlagKeys=new Set,this.pollingInterval=e,this.personalApiKey=t,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=s,this.projectApiKey=n,this.host=i,this.poller=void 0,this.fetch=a.fetch||fetch,this.onError=a.onError,this.customHeaders=o,this.onLoad=a.onLoad,this.onMinimalFlagCalledEvents=a.onMinimalFlagCalledEvents,this.cacheProvider=a.cacheProvider,this.strictLocalEvaluation=a.strictLocalEvaluation??!1,this.evaluationContexts=a.evaluationContexts,this.loadFeatureFlags()}debug(e=!0){this.debugMode=e}logMsgIfDebug(e){this.debugMode&&e()}createEvaluationContext(e,t={},n={},s={},i={}){return{distinctId:e,groups:t,personProperties:n,groupProperties:s,evaluationCache:i}}async getFeatureFlag(e,t,n={},s={},i={}){await this.loadFeatureFlags();let o,a;if(!this.loadedSuccessfullyOnce)return o;if(a=this.featureFlagsByKey[e],a!==void 0){let c=this.createEvaluationContext(t,n,s,i);try{o=(await this.computeFlagAndPayloadLocally(a,c)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${e} -> ${o}`))}catch(l){l instanceof ue||l instanceof S?this.logMsgIfDebug(()=>console.debug(`${l.name} when computing flag locally: ${e}: ${l.message}`)):l instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${e}: ${l}`))}}return o}async getAllFlagsAndPayloads(e,t){await this.loadFeatureFlags();let n={},s={},i=this.featureFlags.length==0,o=t?t.map(c=>this.featureFlagsByKey[c]).filter(Boolean):this.featureFlags,a={...e,evaluationCache:e.evaluationCache??{}};return await Promise.all(o.map(async c=>{try{let{value:l,payload:u}=await this.computeFlagAndPayloadLocally(c,a);n[c.key]=l,u&&(s[c.key]=u)}catch(l){l instanceof ue||l instanceof S?this.logMsgIfDebug(()=>console.debug(`${l.name} when computing flag locally: ${c.key}: ${l.message}`)):l instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${c.key}: ${l}`)),i=!0}})),{response:n,payloads:s,fallbackToFlags:i}}async computeFlagAndPayloadLocally(e,t,n={}){let{matchValue:s,skipLoadCheck:i=!1}=n;if(i||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let o;o=s!==void 0?s:await this.computeFlagValueLocally(e,t);let a=this.getFeatureFlagPayload(e.key,o);return{value:o,payload:a}}async computeFlagValueLocally(e,t){let{distinctId:n,groups:s,personProperties:i,groupProperties:o}=t;if(!e.active)return!1;if(e.ensure_experience_continuity)throw new S("Flag has experience continuity enabled");let c=(e.filters||{}).aggregation_group_type_index;if(c!=null){let l=this.groupTypeMapping[String(c)];if(!l)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${c} for feature flag ${e.key}`)),new S("Flag has unknown group type index");if(!(l in s))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${e.key} without group names passed in`)),!1;e.bucketing_identifier==="device_id"&&(i?.$device_id===void 0||i?.$device_id===null||i?.$device_id==="")&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${e.key}`));let u=o[l];return await this.matchFeatureFlagProperties(e,s[l],u,t)}{let l=this.getBucketingValueForFlag(e,n,i);if(l===void 0)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${e.key} without $device_id, falling back to server evaluation`)),new S(`Can't compute feature flag: ${e.key} without $device_id`);return await this.matchFeatureFlagProperties(e,l,i,t)}}getBucketingValueForFlag(e,t,n){if(e.filters?.aggregation_group_type_index!=null)return t;if(e.bucketing_identifier==="device_id"){let s=n?.$device_id;return s==null||s===""?void 0:s}return t}getFeatureFlagPayload(e,t){return ii(this.featureFlagsByKey?.[e]?.filters?.payloads,t)}async evaluateFlagDependency(e,t,n){let{evaluationCache:s}=n,i=e.key;if(!this.featureFlagsByKey)throw new S("Feature flags not available for dependency evaluation");if(!("dependency_chain"in e))throw new S(`Flag dependency property for '${i}' is missing required 'dependency_chain' field`);let o=e.dependency_chain;if(!Array.isArray(o))throw new S(`Flag dependency property for '${i}' has an invalid 'dependency_chain' (expected array, got ${typeof o})`);if(o.length===0)throw new S(`Circular dependency detected for flag '${i}' (empty dependency chain)`);for(let c of o){if(!(c in s)){let u=this.featureFlagsByKey[c];if(u)if(u.active)try{let d=await this.computeFlagValueLocally(u,n);s[c]=d}catch(d){throw new S(`Error evaluating flag dependency '${c}' for flag '${i}': ${d}`)}else s[c]=!1;else if(this.filteredOutFlagKeys.has(c))s[c]=!1;else throw new S(`Missing flag dependency '${c}' for flag '${i}'`)}if(s[c]==null)throw new S(`Dependency '${c}' could not be evaluated`)}let a=s[i];return this.flagEvaluatesToExpectedValue(e.value,a)}flagEvaluatesToExpectedValue(e,t){return typeof e=="boolean"?e===t||typeof t=="string"&&t!==""&&e===!0:typeof e=="string"?t===e:!1}async matchFeatureFlagProperties(e,t,n,s){let i=e.filters||{},o=i.groups||[],a=i.aggregation_group_type_index,c=i.early_exit??!1,{groups:l,groupProperties:u}=s,d=!1,g;for(let p of o)try{let h=p.aggregation_group_type_index!==void 0?p.aggregation_group_type_index:a,m=n,E=t;if(h!==a&&h!=null){let b=this.groupTypeMapping[String(h)];if(!b||!(b in l)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${e.key}': group type index ${h} not available`));continue}if(!(b in u)){d=!0;continue}m=u[b],E=l[b]}let _=await this.isConditionMatch(e,E,p,m,s);if(_==="match"){let b=p.variant,P=i.multivariate?.variants||[];g=b&&P.some(R=>R.key===b)?b:await this.getMatchingVariant(e,E)||!0;break}if(c&&_==="out_of_rollout_bound"){if(d)break;return!1}}catch(h){if(h instanceof ue)throw h;if(h instanceof S)d=!0;else throw h}if(g!==void 0)return g;if(d)throw new S("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(e,t,n,s,i){let o=n.rollout_percentage,a=c=>{this.logMsgIfDebug(()=>console.warn(c))};if((n.properties||[]).length>0){for(let c of n.properties){let l=c.type,u=!1;if(l==="cohort"){let d=await Zc(c,s,this.cohorts,this.debugMode,g=>this.evaluateFlagDependency(g,s,i));u=c.operator==="not_in"?!d:d}else u=l==="flag"?await this.evaluateFlagDependency(c,s,i):Qc(c,s,a);if(!u)return"no_match"}if(o==null)return"match"}return o!=null&&await En(e.key,t)>o/100?"out_of_rollout_bound":"match"}async getMatchingVariant(e,t){return si(e.key,t,e.filters?.multivariate?.variants||[])}variantLookupTable(e){return yn(e.filters?.multivariate?.variants||[])}filterFlagsByEvaluationContexts(e){if(!this.evaluationContexts||this.evaluationContexts.length===0)return e;let t=new Set(this.evaluationContexts);return e.filter(n=>{let s=n.evaluation_contexts??n.evaluation_tags;return!s||s.length===0?!0:s.some(i=>t.has(i))})}updateFlagState(e){let t=this.filterFlagsByEvaluationContexts(e.flags);this.featureFlags=t,this.featureFlagsByKey=t.reduce((s,i)=>(s[i.key]=i,s),{});let n=new Set(t.map(s=>s.key));this.filteredOutFlagKeys=new Set(e.flags.filter(s=>!n.has(s.key)).map(s=>s.key)),this.groupTypeMapping=e.groupTypeMapping,this.cohorts=e.cohorts,this.loadedSuccessfullyOnce=!0,this.onMinimalFlagCalledEvents?.(e.minimalFlagCalledEvents===!0)}warnAboutExperienceContinuityFlags(e){if(this.strictLocalEvaluation)return;let t=e.filter(n=>n.ensure_experience_continuity);t.length>0&&console.warn(`[PostHog] You are using local evaluation but ${t.length} flag(s) have experience continuity enabled: ${t.map(n=>n.key).join(", ")}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`)}async loadFromCache(e){if(!this.cacheProvider)return!1;try{let t=await this.cacheProvider.getFlagDefinitions();return t?(this.updateFlagState(t),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${e} (${t.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(this.featureFlags),!0):!1}catch(t){return this.onError?.(new Error(`Failed to load from cache: ${t}`)),!1}}async loadFeatureFlags(e=!1){if(!(this.loadedSuccessfullyOnce&&!e))return!e&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt?void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period")):(this.loadingPromise||(this.loadingPromise=this._loadFeatureFlags().catch(t=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${t}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise)}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(Ag,this.pollingInterval*2**this.backOffCount):this.pollingInterval}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0);try{let e=!0;if(this.cacheProvider)try{e=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(n){this.onError?.(new Error(`Error in shouldFetchFlagDefinitions: ${n}`))}if(!e&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||this.loadedSuccessfullyOnce))return;let t=await this._requestFeatureFlagDefinitions();if(!t)return;switch(t.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=t.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new yt(`Your project key or secret key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.filteredOutFlagKeys=new Set,this.groupTypeMapping={},this.cohorts={},this.onMinimalFlagCalledEvents?.(!1);return;case 403:throw this.beginBackoff(),new yt(`Your secret key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct secret and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new yt(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let n=await t.json()??{};if(!("flags"in n))return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(n)}`));this.flagsEtag=t.headers?.get("ETag")??void 0;let s={flags:n.flags??[],groupTypeMapping:n.group_type_mapping||{},cohorts:n.cohorts||{},minimalFlagCalledEvents:n.minimal_flag_called_events===!0};if(this.updateFlagState(s),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&e)try{await this.cacheProvider.onFlagDefinitionsReceived(s)}catch(i){this.onError?.(new Error(`Failed to store in cache: ${i}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(this.featureFlags);break}default:return}}catch(e){e instanceof yt&&this.onError?.(e)}finally{this.pollerStopped||(this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval()))}}getPersonalApiKeyRequestOptions(e="GET",t){let n={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return t&&(n["If-None-Match"]=t),{method:e,headers:n}}async _requestFeatureFlagDefinitions(){let e=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,t=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),n=null;if(this.timeout&&typeof this.timeout=="number"){let i=new AbortController;n=B(()=>{i.abort()},this.timeout),t.signal=i.signal}let s=()=>clearTimeout(n);try{let i=this.fetch,o=await i(e,t);return o.status!==200?(s(),o):{status:o.status,headers:o.headers,body:o.body,text:async()=>{try{return await o.text()}finally{s()}},json:async()=>{try{return await o.json()}finally{s()}}}}catch(i){throw s(),i}}async stopPoller(e=3e4){if(this.pollerStopped=!0,clearTimeout(this.poller),this.poller=void 0,this.cacheProvider)try{let t=this.cacheProvider.shutdown();t instanceof Promise&&await De(t,e,()=>{throw new Error(`Cache shutdown timeout after ${e}ms`)})}catch(t){this.onError?.(new Error(`Error during cache shutdown: ${t}`))}}};function Qc(r,e,t){return ni(r,e,{warnFunction:t})}function Pg(r,e){if(!(r in e))throw new ue(`cohort ${r} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function Zc(r,e,t,n=!1,s){let i=String(r.value);Pg(i,t);let o=t[i];return el(o,e,t,n,s)}async function el(r,e,t,n=!1,s){if(!r)return!0;let i=r.type,o=r.values;if(!o||o.length===0)return!0;let a=!1;if("values"in o[0]){for(let c of o)try{let l=await el(c,e,t,n,s);if(i==="AND"){if(!l)return!1}else if(l)return!0}catch(l){if(l instanceof ue)throw l;if(l instanceof S)n&&console.debug(`Failed to compute property ${c} locally: ${l}`),a=!0;else throw l}if(a)throw new S("Can't match cohort without a given cohort property value");return i==="AND"}for(let c of o)try{let l;if(c.type==="cohort")l=await Zc(c,e,t,n,s);else if(c.type==="flag"){if(!s)throw new S(`Flag dependency '${c.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);l=await s(c)}else l=Qc(c,e);let u=c.negation||!1;if(i==="AND"){if(!l&&!u||l&&u)return!1}else if(l&&!u||!l&&u)return!0}catch(l){if(l instanceof ue)throw l;if(l instanceof S)n&&console.debug(`Failed to compute property ${c} locally: ${l}`),a=!0;else throw l}if(a)throw new S("can't match cohort without a given cohort property value");return i==="AND"}var Ig=["--unhandled-rejections","--unhandled_rejections"],Rg=new Set(["throw","strict","warn","warn-with-error-code","none"]),Cg=[...globalThis.process?.execArgv??[]],Mg=globalThis.process?.env?.NODE_OPTIONS;function xg(r){let e=[],t="",n=!1;for(let s=0;s<r.length;s++){let i=r[s];i==="\\"&&n&&s+1<r.length?t+=r[++s]:i!==" "||n?i==='"'?n=!n:t+=i:t&&(e.push(t),t="")}return t&&e.push(t),e}function tl(r){let e;for(let t=0;t<r.length;t++){let n=r[t],s=Ig.find(o=>n===o||n.startsWith(`${o}=`));if(!s)continue;let i=n===s?r[++t]:n.slice(s.length+1);Rg.has(i)&&(e=i)}return e}function Fg(r=Cg,e=Mg){return tl(r)??tl(xg(e??""))??"throw"}var rl=Fg();function nl(r,e,t){r(e,{mechanism:{type:t==="unhandledRejection"?"onunhandledrejection":"onuncaughtexception",handled:!1}})}function Og(r,e){let t=!1;return Object.assign((n,s)=>{let i=global.process.listeners("uncaughtException").filter(o=>o.name!=="domainUncaughtExceptionClear"&&o._posthogErrorHandler!==!0).length;nl(r,n,s),!t&&i===0&&(t=!0,e(n))},{_posthogErrorHandler:!0})}function sl(r,e,t=rl){let n=globalThis.process;if(n){if(t==="strict")return void n.on("uncaughtExceptionMonitor",(s,i)=>nl(r,s,i));n.on("uncaughtException",Og(r,e))}}function il(r,e=rl){let t=globalThis.process;!t||e==="throw"||e==="strict"||e==="warn-with-error-code"||t.on("unhandledRejection",n=>{r(n,{mechanism:{type:"onunhandledrejection",handled:!1}})})}var kg=2e3,Ti=class r{constructor(e,t,n){this.client=e,this._exceptionAutocaptureEnabled=t.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new Qr({...ma(t),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(e){return Mt(e)&&"__posthog_previously_captured_error"in e&&e.__posthog_previously_captured_error===!0}static async buildEventMessage(e,t,n,s,i){let o={...i},a=e.buildFromUnknown(t,n);a.$exception_list=await e.modifyFrames(a.$exception_list);let c=D.getInjectedReleaseId();return c&&(o.$release_id=c),{event:"$exception",distinctId:s,properties:{...a,...o},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(sl(this.onException.bind(this),this.onFatalError.bind(this)),il(this.onException.bind(this)))}onException(e,t){this.client.addPendingPromise((async()=>{if(!r.isPreviouslyCapturedError(e)){let n=await r.buildEventMessage(this.client.getErrorPropertiesBuilder(),e,t),i=n.properties?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(i)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:i}):this.client._capturePreparedEvent(n,!1)}})())}async onFatalError(e){console.error(e),await this.client.shutdown(kg),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}},Xe=Ti;var Dn=class{getProperty(e){return this._memoryStorage[e]}setProperty(e,t){this._memoryStorage[e]=t!==null?t:void 0}constructor(){this._memoryStorage={}}};function Dg(r){return r==="v0"||r==="v1"}function ol(){let r="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0;return Dg(r)?r:"v0"}var Lg="$ai_",ir="analytics";function al(r){return typeof r.event=="string"&&r.event.startsWith(Lg)}var St=class r extends Error{constructor({requestId:e,drops:t,retryExhausted:n,cause:s}){super(r.buildMessage(e,t,n,s)),this.name="CaptureV1Error",this.requestId=e,this.drops=t,this.retryExhausted=n,this.cause=s}static buildMessage(e,t,n,s){let i=`Capture V1 batch ${e} did not fully deliver: ${t.length} dropped, ${n.length} undelivered`;return s instanceof Error&&(i+=` (${s.message})`),i}};function Pi(r){if(typeof r=="boolean")return r;if(typeof r=="number")return r!==0;if(typeof r=="string"){let e=r.trim().toLowerCase();if(e==="true"||e==="1")return!0;if(e==="false"||e==="0")return!1}}function Ng(r){return typeof r=="string"?r:void 0}var Ug=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:Pi},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:Pi},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:Pi},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:Ng}],$g=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function jg(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function Bg(r){if(typeof r=="string"){let t=new Date(r);if(Number.isNaN(t.getTime()))return new Date().toISOString();let n=t.toISOString(),s=r.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1];return s&&s.length>3?n.replace(/\.\d{3}Z$/,`.${s}Z`):n}if(r instanceof Date)return Number.isNaN(r.getTime())?new Date().toISOString():r.toISOString();let e=r==null?new Date:new Date(r);return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString()}function cl(r,e,t){t!==void 0&&!(e in r)&&(r[e]=t)}function Wg(r){let t={...jg(r.properties)?r.properties:{}},n={};for(let{property:i,optionKey:o,coerce:a}of Ug)if(i in t){let c=a(t[i]);c!==void 0&&(n[o]=c),delete t[i]}let s={};for(let{property:i,field:o}of $g)if(i in t){let a=t[i];typeof a=="string"&&(s[o]=a),delete t[i]}return delete t.$lib,delete t.$lib_version,cl(t,"$set",r.$set),cl(t,"$set_once",r.$set_once),{event:String(r.event??""),uuid:String(r.uuid??""),distinct_id:String(r.distinct_id??""),timestamp:Bg(r.timestamp),...s,options:n,properties:t}}function ll(r,{createdAt:e,historicalMigration:t}){let n={created_at:e,batch:r.map(Wg)};return t&&(n.historical_migration=!0),n}var Hg="/i/v1/analytics/events",Gg=3e4,Kg=new Set([408,500,502,503,504]),Ln=class{constructor(e,t){this.config=e,this.maxBackoffMs=e.maxBackoffMs??Gg,this.fetchFn=t.fetch,this.onError=t.onError,this.now=t.now??Date.now,this.sleep=t.sleep??(n=>new Promise(s=>B(s,n))),this.generateRequestId=t.generateRequestId??j,this.compress=t.compress??Ht}async sendV1Batch(e){if(e.length===0)return;let t=this.generateRequestId(),n=new Date(this.now()).toISOString(),{batch:s}=ll(e,{createdAt:n,historicalMigration:this.config.historicalMigration}),i=`${this.config.host}${Hg}`,o=[],a=s,c=Math.max(1,this.config.maxAttempts);for(let l=1;l<=c;l++){let u=l===c,d=ke({created_at:n,...this.config.historicalMigration?{historical_migration:!0}:{},batch:a}),g,p;try{g=await this.sendOnce(i,d,l,t);let{response:h,signal:m}=g,{status:E}=h;if(E<200||E>=300)if(!u&&Kg.has(E)){let _=this.parseRetryAfter(h);await g.waitFor(g.cancelBody()).catch(()=>{}),p=this.backoffDelay(l,_)}else{let _=await this.buildHttpError(h,E,g.waitFor);return this.surfaceBatchFailure(t,o,a,_)}else{let _;try{_=await g.waitFor(this.parseResponse(h))}catch(R){if(m.aborted)throw R;return this.surfaceBatchFailure(t,o,a,new Error(`Capture V1 returned an unparseable ${E} response body`))}let b=this.classify(a,_,o);if(b.length===0)return this.surfacePartialDrops(t,o);if(u)return void this.onError(new St({requestId:t,drops:o,retryExhausted:b.map(R=>R.uuid)}));a=b;let P=this.parseRetryAfter(h);p=this.backoffDelay(l,P)}}catch(h){if(g&&!g.signal.aborted)throw h;if(u)return this.surfaceBatchFailure(t,o,a,h);p=this.backoffDelay(l)}finally{g?.cleanup()}p!==void 0&&await this.sleep(p)}}async sendOnce(e,t,n,s){let i=this.buildHeaders(n,s),o=t;if(this.config.compressionEnabled){let d=await this.compress(t,this.config.isDebug);d!==null&&(o=d,i["Content-Encoding"]="gzip")}let a=new AbortController,c="waiting for response headers",l,u=new Promise((d,g)=>{l=B(()=>{let p=new Error(`Capture V1 request timed out ${c} after ${this.config.requestTimeoutMs}ms`);p.name="AbortError",g(p),a.abort(p)},this.config.requestTimeoutMs)});try{let d=this.fetchFn(e,{method:"POST",headers:i,body:o,signal:a.signal}),g=!1;d.then(_=>{a.signal.aborted&&!g&&this.cancelBody(_)}).catch(()=>{});let p=await Promise.race([d,u]);g=!0,c="while reading the response body";let h=!1,m,E=()=>m??=this.cancelBody(p);return{response:p,signal:a.signal,waitFor:_=>Promise.race([_,u]),cancelBody:E,cleanup:()=>{h||(h=!0,clearTimeout(l),a.signal.aborted&&E())}}}catch(d){throw clearTimeout(l),d}}buildHeaders(e,t){let n=`${this.config.libraryId}/${this.config.libraryVersion}`,s={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"PostHog-Sdk-Info":n,"PostHog-Attempt":String(e),"PostHog-Request-Id":t,"PostHog-Request-Timestamp":new Date(this.now()).toISOString()};return this.config.userAgent&&(s["User-Agent"]=this.config.userAgent),s}classify(e,t,n){let s=t.results??{},i=[];for(let o of e){let a=s[o.uuid];a&&(a.result==="drop"?n.push({uuid:o.uuid,details:a.details??void 0}):a.result==="retry"&&i.push(o))}return i}backoffDelay(e,t){let n=Math.min(this.config.initialRetryDelayMs*2**(e-1),this.maxBackoffMs);return t===void 0?n:Math.max(n,Math.min(t,this.maxBackoffMs))}parseRetryAfter(e){let t=e.headers?.get("Retry-After");if(!t)return;let n=t.trim();if(/^\d+$/.test(n)){let o=parseInt(n,10);return Number.isFinite(o)&&o>0?1e3*o:void 0}let s=Date.parse(n);if(Number.isNaN(s))return;let i=s-this.now();return i>0?i:void 0}async parseResponse(e){let t=await e.text(),n=JSON.parse(t);if(typeof n!="object"||n===null||Array.isArray(n))throw new Error("unexpected response shape");let s=n.results;if(s!==void 0&&(typeof s!="object"||s===null||Array.isArray(s)))throw new Error("unexpected results shape");return{results:s??{}}}async buildHttpError(e,t,n){let s="";try{s=(await n(e.text())).slice(0,512)}catch{}let i=s?`: ${s}`:"";return new Error(`Capture V1 request failed with HTTP ${t}${i}`)}surfaceBatchFailure(e,t,n,s){this.onError(new St({requestId:e,drops:t,retryExhausted:n.map(i=>i.uuid),cause:s}))}surfacePartialDrops(e,t){t.length>0&&this.onError(new St({requestId:e,drops:t,retryExhausted:[]}))}async cancelBody(e){try{await e.body?.cancel()}catch{}}};var Qe="ai-capture",Nn="/i/v0/ai/batch/";var qg=new TextEncoder;function Ri(r){return qg.encode(ke(r)).length}function ul(r,e=8388608,t=5242880){let n=[],s=[],i=[],o=0;for(let a of r){if(a===void 0)continue;let c=Ri(a);if(c>e){s.push({event:typeof a.event=="string"?a.event:"unknown",bytes:c});continue}i.length>0&&o+c>t&&(n.push(i),i=[],o=0),i.push(a),o+=c}return i.length>0&&n.push(i),{batches:n,dropped:s}}var zg=100,dl=3e4,Yg=5e4,Jg=50,Xg=500,Qg="https://us.i.posthog.com",fl=new Set;function $n(r,e){fl.has(r)||(fl.add(r),console.warn(`[PostHog] ${e}`))}function Zg(r){return typeof r=="string"?r.trim():""}function eh(r){return(typeof r=="string"?r.trim():"")||void 0}function th(r){return(typeof r=="string"?r.trim():"")||Qg}function rh(r){return(Array.isArray(r)?r:[r]).filter(t=>typeof t=="string"&&t.trim().length>0)}function nh(r){if(!r)return{};let e={};for(let[n,s]of Object.entries(r))e[`$feature/${n}`]=s;let t=Object.keys(r).filter(n=>r[n]!==!1).sort();return t.length>0&&(e.$active_feature_flags=t),e}var jn=class extends Gt{constructor(e,t={}){let n=Zg(e),s={...t,maxQueueSize:t.maxQueueSize??1e4,flushInterval:t.flushInterval??5e3,host:th(t.host),personalApiKey:eh(t.secretKey??t.personalApiKey)};if(super(n,s),this._memoryStorage=new Dn,this._aiCaptureRouteActive=!1,this._minimalFlagCalledEvents=!1,this.options=s,this.captureMode=ol(),this.enableFullAiCapture=s.enableFullAiCapture===!0,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof s.featureFlagsPollingInterval=="number"?Math.max(s.featureFlagsPollingInterval,zg):dl,typeof s.waitUntilDebounceMs=="number"&&(this.options.waitUntilDebounceMs=Math.max(s.waitUntilDebounceMs,0)),typeof s.waitUntilMaxWaitMs=="number"&&(this.options.waitUntilMaxWaitMs=Math.max(s.waitUntilMaxWaitMs,0)),!this.disabled&&s.personalApiKey){if(s.personalApiKey.includes("phc_"))throw new Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');s.enableLocalEvaluation!==!1&&(this.featureFlagsPoller=new kn({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:s.personalApiKey,projectApiKey:n,timeout:s.requestTimeout??1e4,host:this.host,fetch:s.fetch,onError:o=>{this._events.emit("error",o)},onLoad:o=>{this._events.emit("localEvaluationFlagsLoaded",o)},onMinimalFlagCalledEvents:o=>{this._minimalFlagCalledEvents=o},customHeaders:this.getCustomHeaders(),cacheProvider:s.flagDefinitionCacheProvider,strictLocalEvaluation:s.strictLocalEvaluation,evaluationContexts:s.evaluationContexts??s.evaluationEnvironments}))}this.errorTracking=new Xe(this,s,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=s.maxCacheSize||Yg}enqueue(e,t,n,s){super.enqueue(e,t,n,s),this.scheduleDebouncedFlush()}_flushEventsAndSpans(e=!1){let t=this.flushWithPendingPromises();return!this._traces||e&&this._traces.throttled?t:Ot([t,this._traces.flush().catch(()=>{})]).then(([n])=>{if(n.status==="rejected")throw n.reason})}flushAutomatic(){return this._flushKeepingRuntimeAlive(!0)}async flush(){return this._flushKeepingRuntimeAlive(!1)}_flushKeepingRuntimeAlive(e){let t=this._flushEventsAndSpans(e),n=this.options.waitUntil;if(n&&!this._waitUntilCycle)try{n(t.catch(()=>{}))}catch{}return t}scheduleDebouncedFlush(){let e=this.options.waitUntil;if(!e||this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let o,a=new Promise(c=>{o=c});try{e(a)}catch{return}this._waitUntilCycle={resolve:o,startedAt:Date.now(),timer:void 0}}let t=Date.now()-this._waitUntilCycle.startedAt,n=this.options.waitUntilMaxWaitMs??Xg,s=t>=n;if(this._waitUntilCycle.timer!==void 0&&clearTimeout(this._waitUntilCycle.timer),s)return void this.resolveWaitUntilFlush();let i=this.options.waitUntilDebounceMs??Jg;this._waitUntilCycle.timer=B(()=>{this.resolveWaitUntilFlush()},i)}_consumeWaitUntilCycle(){let e=this._waitUntilCycle;return e&&(clearTimeout(e.timer),this._waitUntilCycle=void 0),e?.resolve}async resolveWaitUntilFlush(){let e=this._consumeWaitUntilCycle();try{await this._flushEventsAndSpans()}catch{}finally{e?.()}}getPersistedProperty(e){return this._memoryStorage.getProperty(e)}setPersistedProperty(e,t){return this._memoryStorage.setProperty(e,t)}fetch(e,t){return this.options.fetch?this.options.fetch(e,t):fetch(e,t)}getQueueRouteKey(e){return this.captureMode==="v1"&&al(e)?"ai":ir}persistedQueueKeyForRoute(e){return e===Qe?G.AiCaptureQueue:e==="ai"?G.AiQueue:G.Queue}getActiveQueueRoutes(){let e=this.captureMode==="v1"?[ir,"ai"]:[ir];return this._aiCaptureRouteActive&&e.push(Qe),e}getBatchEndpointPath(e){return e===Qe?Nn:super.getBatchEndpointPath(e)}async sendBatch(e,t,n=ir){if(n===Qe)return this.sendAiCaptureBatch(e,t);if(this.captureMode!=="v1"||n==="ai")return super.sendBatch(e,t,n);let s=e.filter(i=>i!==void 0);await this.getV1Sender().sendV1Batch(s)}async sendAiCaptureBatch(e,t){let{batches:n,dropped:s}=ul(e);for(let{event:i,bytes:o}of s){let a=`Event ${i} (${o} bytes) exceeds the ${8388608/1048576}MiB limit for ${Nn}, dropping.`;this._logger.error(a),this._events.emit("error",new Error(a))}for(let i of n)await this.sendAiSubBatch(i,t)}async sendAiSubBatch(e,t){try{await super.sendBatch(e,t,Qe)}catch(n){if(!ht(n))throw n;if(e.length===1){let[i]=e,a=`Event ${typeof i.event=="string"?i.event:"unknown"} (${Ri(i)} bytes) was rejected with 413 by ${Nn} on its own, dropping.`;this._logger.error(a),this._events.emit("error",new Error(a));return}let s=Math.ceil(e.length/2);await this.sendAiSubBatch(e.slice(0,s),t),await this.sendAiSubBatch(e.slice(s),t)}}getV1Sender(){return this._v1Sender||(this._v1Sender=new Ln({host:this.host,apiKey:this.apiKey,libraryId:this.getLibraryId(),libraryVersion:this.getLibraryVersion(),userAgent:this.getCustomUserAgent()||void 0,historicalMigration:this.historicalMigration,compressionEnabled:!this.disableCompression,requestTimeoutMs:this.requestTimeout,maxAttempts:(this.options.fetchRetryCount??3)+1,initialRetryDelayMs:this.options.fetchRetryDelay??3e3,isDebug:this.isDebug},{fetch:(e,t)=>this.fetch(e,t),onError:e=>this._events.emit("error",e),compress:e=>this.compressPayload(e)})),this._v1Sender}getLibraryVersion(){return Xc}get metrics(){return this._metrics||(this._metrics=new Qt(this,bn(this.options.metrics),this._logger)),this._metrics}initializeSpanContextManager(){return new nr}hostResourceAttributes(){return{}}get _spanContextManager(){return this._spanContext||(this._spanContext=this.initializeSpanContextManager()),this._spanContext}get _tracesPipeline(){if(this.options.traces)return this._traces||(this._traces=new rr(this,Si(this.options.traces,this.hostResourceAttributes(),this._logger),this._logger,()=>this._tracingContext(),this._spanContextManager,()=>this.scheduleDebouncedFlush())),this._traces}_tracingContext(){let e=this.context?.get();return{distinctId:e?.distinctId,sessionId:e?.sessionId}}startSpan(e,t){return this._tracesPipeline?.startSpan(e,t)??Le(t,this._spanContextManager.active())}withSpan(e,t,n){let s=typeof t=="function"?void 0:t,i=typeof t=="function"?t:n,o=this._tracesPipeline;return o?s?o.withSpan(e,s,i):o.withSpan(e,i):tr(this._spanContextManager,Le(s,this._spanContextManager.active()),i)}getActiveSpan(){return this._spanContextManager.active()??null}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}getCommonEventProperties(){let e=super.getCommonEventProperties();return(this.options.isServer??!0)&&(e.$is_server=!0),e}enable(){return super.optIn()}disable(){return super.optOut()}debug(e=!0){super.debug(e),this.featureFlagsPoller?.debug(e)}_warnIfInvalidCapture(e,t,n){typeof e=="string"&&this._logger.warn(t),e.event==="$exception"&&!e._originatedFromCaptureException&&this._logger.warn(n)}_sendPreparedEvent(e,t,n,s,i){return this.addPendingPromise(this._prepareEventMessage(t,s).then(({distinctId:o,event:a,properties:c,options:l})=>{let u={timestamp:l.timestamp,disableGeoip:l.disableGeoip,uuid:l.uuid},d={distinctId:o,event:a,properties:{...c,...this.getCommonEventProperties()}};return n?this.sendImmediate(e,d,u,i):this.enqueue(e,d,u,i)}).catch(o=>{o&&console.error(o)}))}_capturePreparedEvent(e,t){return this._sendPreparedEvent("capture",e,t)}capture(e){this._warnIfInvalidCapture(e,"Called capture() with a string as the first argument when an object was expected.","Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this._capturePreparedEvent(e,!1)}async captureImmediate(e){return this._warnIfInvalidCapture(e,"Called captureImmediate() with a string as the first argument when an object was expected.","Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default."),this._capturePreparedEvent(e,!0)}captureAi(e){if(this.disabled)return;let t=Ve(e.uuid,j);return this._sendPreparedAiEvent({...e,uuid:t},!1),t}async captureAiImmediate(e){if(this.disabled)return;let t=Ve(e.uuid,j);return await this._sendPreparedAiEvent({...e,uuid:t},!0),t}_sendPreparedAiEvent(e,t){return typeof e?.event=="string"&&!e.event.startsWith("$ai_")&&this._logger.debug(`captureAi called with non-AI event ${e.event}; routing it to the AI endpoint anyway.`),this._aiCaptureRouteActive=!0,this._sendPreparedEvent("capture",e,t,void 0,Qe)}identify({distinctId:e,properties:t={},disableGeoip:n}){let{$set:s,$set_once:i,$anon_distinct_id:o,...a}=t,u={$set:s||a,$set_once:i||{},$anon_distinct_id:o??void 0};this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:u,disableGeoip:n},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:e,properties:t={},disableGeoip:n}){let{$set:s,$set_once:i,$anon_distinct_id:o,...a}=t,u={$set:s||a,$set_once:i||{},$anon_distinct_id:o??void 0};await this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:u,disableGeoip:n},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:e,properties:t={},propertiesOnce:n={}}){if(Object.keys(t).length===0&&Object.keys(n).length===0)return;let s={};Object.keys(t).length>0&&(s.$set=t),Object.keys(n).length>0&&(s.$set_once=n),this.capture({distinctId:e,event:"$set",properties:s})}unsetPersonProperties({distinctId:e,properties:t}){let n=rh(t);n.length!==0&&this.capture({distinctId:e,event:"$set",properties:{$unset:n}})}alias(e){this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!1,{includeContextProperties:!1})}async aliasImmediate(e){await this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!0,{includeContextProperties:!1})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(e=dl){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(t=>{let n=setTimeout(()=>{s(),t(!1)},e),s=this._events.on("localEvaluationFlagsLoaded",i=>{clearTimeout(n),s(),t(i>0)})})}_resolveDistinctId(e,t){return typeof e=="string"?{distinctId:e,options:t}:{distinctId:this.context?.get()?.distinctId,options:e}}async _getFeatureFlagResult(e,t,n={},s){if(this.disabled)return void this._logger.warn("The client is disabled");let i=n.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&e in this._flagOverrides){let y=this._flagOverrides[e];if(y===void 0)return;let v=this._payloadOverrides?.[e];return{key:e,enabled:y!==!1,variant:typeof y=="string"?y:void 0,payload:v}}let{groups:o,disableGeoip:a}=n,{onlyEvaluateLocally:c,personProperties:l,groupProperties:u}=n,d=this.addLocalPersonAndGroupProperties(t,o,l,u);l=d.allPersonProperties,u=d.allGroupProperties;let g=this.createFeatureFlagEvaluationContext(t,o,this.personPropertiesForLocalEvaluation(t,l),u);c==null&&(c=this.options.strictLocalEvaluation??!1);let p,h=!1,m,E,_,b,P,R,O;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let y=this.featureFlagsPoller?.featureFlagsByKey[e];if(y)try{let v=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(y,g,{matchValue:s});if(v){h=!0;let w=v.value;b=y.id,R="Evaluated locally",O=y.has_experiment,p={key:e,enabled:w!==!1,variant:typeof w=="string"?w:void 0,payload:v.payload??void 0}}}catch(v){if(v instanceof ue||v instanceof S)this._logger?.info(`${v.name} when computing flag locally: ${e}: ${v.message}`);else throw v}}if(!h&&!c){let y=await super.getFeatureFlagDetailsStateless(g.distinctId,g.groups,l,u,a,[e]);if(y===void 0)_=Pe.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=y.minimalFlagCalledEvents===!0,m=y.requestId,E=y.evaluatedAt;let v=[];y.errorsWhileComputingFlags&&v.push(Pe.ERRORS_WHILE_COMPUTING),y.quotaLimited?.includes("feature_flags")&&v.push(Pe.QUOTA_LIMITED);let w=y.flags[e];if(w===void 0)v.push(Pe.FLAG_MISSING);else{b=w.metadata?.id,P=w.metadata?.version,R=w.reason?.description??w.reason?.code,O=w.metadata?.has_experiment;let $e;if(w.metadata?.payload!==void 0)try{$e=JSON.parse(w.metadata.payload)}catch{$e=w.metadata.payload}p={key:e,enabled:w.enabled,variant:w.variant??void 0,payload:$e}}v.length>0&&(_=v.join(","))}}if(i){let y=p===void 0?void 0:p.enabled===!1?!1:p.variant??!0,v={$feature_flag:e,$feature_flag_response:y,$feature_flag_id:b,$feature_flag_version:P,$feature_flag_reason:R,locally_evaluated:h,[`$feature/${e}`]:y,$feature_flag_request_id:m,$feature_flag_evaluated_at:h?Date.now():E};if(O!==void 0&&(v.$feature_flag_has_experiment=O),h&&this.featureFlagsPoller){let w=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();w!==void 0&&(v.$feature_flag_definitions_loaded_at=w)}_&&(v.$feature_flag_error=_),this._captureFlagCalledEventIfNeeded({distinctId:t,key:e,response:y,groups:o,disableGeoip:a,properties:v})}return p!==void 0&&this._payloadOverrides!==void 0&&e in this._payloadOverrides&&(p={...p,payload:this._payloadOverrides[e]}),p}async getFeatureFlag(e,t,n){$n("getFeatureFlag","`getFeatureFlag` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlag(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let s=await this._getFeatureFlagResult(e,t,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(s!==void 0)return s.enabled===!1?!1:s.variant??!0}async getFeatureFlagPayload(e,t,n,s){if($n("getFeatureFlagPayload","`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request."),this._payloadOverrides!==void 0&&e in this._payloadOverrides)return this._payloadOverrides[e];let i=await this._getFeatureFlagResult(e,t,{...s,sendFeatureFlagEvents:!1},n);if(i!==void 0)return i.payload??null}async getFeatureFlagResult(e,t,n){let{distinctId:s,options:i}=this._resolveDistinctId(t,n);return s?this._getFeatureFlagResult(e,s,{...i,sendFeatureFlagEvents:i?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0}):void this._logger.warn("[PostHog] distinctId is required \u2014 pass it explicitly or use withContext()")}async getRemoteConfigPayload(e){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this.options.personalApiKey)throw new Error("Personal API key is required for remote config payload decryption");let t=await this._requestRemoteConfigPayload(e);if(!t)return;let n=await t.json();if(typeof n=="string")try{return JSON.parse(n)}catch{}return n}async isFeatureEnabled(e,t,n){$n("isFeatureEnabled","`isFeatureEnabled` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.isEnabled(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let s=await this._getFeatureFlagResult(e,t,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});return s===void 0?void 0:s.enabled===!1?!1:!!(s.variant??!0)||!1}async getAllFlags(e,t){let{distinctId:n,options:s}=this._resolveDistinctId(e,t);return n?(await this.getAllFlagsAndPayloads(n,s)).featureFlags||{}:(this._logger.warn("[PostHog] distinctId is required to get feature flags \u2014 pass it explicitly or use withContext()"),{})}async getAllFlagsAndPayloads(e,t){let{distinctId:n,options:s}=this._resolveDistinctId(e,t);if(!n)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads \u2014 pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};if(this.disabled)return this._logger.warn("The client is disabled"),{featureFlags:{},featureFlagPayloads:{}};let{groups:i,disableGeoip:o,flagKeys:a}=s||{},{onlyEvaluateLocally:c,personProperties:l,groupProperties:u}=s||{},d=this.addLocalPersonAndGroupProperties(n,i,l,u);l=d.allPersonProperties,u=d.allGroupProperties;let g=this.createFeatureFlagEvaluationContext(n,i,this.personPropertiesForLocalEvaluation(n,l),u);c==null&&(c=this.options.strictLocalEvaluation??!1);let p=await this.featureFlagsPoller?.getAllFlagsAndPayloads(g,a),h={},m={},E=!0;if(p&&(h=p.response,m=p.payloads,E=p.fallbackToFlags),E&&!c){let _=await super.getFeatureFlagsAndPayloadsStateless(g.distinctId,g.groups,l,u,o,a);h={...h,..._.flags||{}},m={...m,..._.payloads||{}}}return this._flagOverrides!==void 0&&(h={...h,...this._flagOverrides}),this._payloadOverrides!==void 0&&(m={...m,...this._payloadOverrides}),{featureFlags:h,featureFlagPayloads:m}}async evaluateFlags(e,t){let{distinctId:n,options:s}=this._resolveDistinctId(e,t);if(!n)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags \u2014 pass it explicitly or use withContext()"),new Ue({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new Ue({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,flags:{}});let{groups:i,disableGeoip:o}=s||{},a=s?.flagKeys??void 0;if(a?.length===0)return new Ue({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:i,disableGeoip:o,flags:{}});let{onlyEvaluateLocally:c,personProperties:l,groupProperties:u}=s||{},d=this.addLocalPersonAndGroupProperties(n,i,l,u);l=d.allPersonProperties,u=d.allGroupProperties;let g=this.createFeatureFlagEvaluationContext(n,i,this.personPropertiesForLocalEvaluation(n,l),u);c==null&&(c=this.options.strictLocalEvaluation??!1);let p=a?new Set(a):void 0,h={},m,E,_=!1,b=!1,P=await this.featureFlagsPoller?.getAllFlagsAndPayloads(g,a),R=new Set;if(P)for(let[y,v]of Object.entries(P.response)){let w=this.featureFlagsPoller?.featureFlagsByKey[y];h[y]={key:y,enabled:v!==!1,variant:typeof v=="string"?v:void 0,payload:P.payloads[y],id:w?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:w?.has_experiment},R.add(y)}let O=p!==void 0&&Array.from(p).some(y=>this.featureFlagsPoller?.featureFlagsByKey[y]===void 0);if((P?P.fallbackToFlags||O:!0)&&!c){let y=await super.getFeatureFlagDetailsStateless(g.distinctId,g.groups,l,u,o,a);if(y){this._minimalFlagCalledEvents=y.minimalFlagCalledEvents===!0,m=y.requestId,E=y.evaluatedAt,_=!!y.errorsWhileComputingFlags,b=Array.isArray(y.quotaLimited)&&y.quotaLimited.includes("feature_flags");for(let[v,w]of Object.entries(y.flags)){if(R.has(v))continue;let $e;if(w.metadata?.payload!==void 0)try{$e=JSON.parse(w.metadata.payload)}catch{$e=w.metadata.payload}h[v]={key:v,enabled:w.enabled,variant:w.variant,payload:$e,id:w.metadata?.id,version:w.metadata?.version,reason:w.reason?.description??w.reason?.code,locallyEvaluated:!1,hasExperiment:w.metadata?.has_experiment}}}}if(this._flagOverrides!==void 0)for(let[y,v]of Object.entries(this._flagOverrides)){if(v===void 0){delete h[y];continue}let w=h[y];h[y]={key:y,enabled:v!==!1,variant:typeof v=="string"?v:void 0,payload:w?.payload,id:w?.id,version:w?.version,reason:w?.reason,locallyEvaluated:w?.locallyEvaluated??!1,hasExperiment:w?.hasExperiment}}if(this._payloadOverrides!==void 0)for(let[y,v]of Object.entries(this._payloadOverrides)){let w=h[y];w&&(h[y]={...w,payload:v})}if(p!==void 0)for(let y of Object.keys(h))p.has(y)||delete h[y];return new Ue({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:i,disableGeoip:o,flags:h,requestId:m,evaluatedAt:E,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:_,quotaLimited:b})}_shouldSendMinimalFlagCalledEvent(e,t){return e==="$feature_flag_called"&&this._minimalFlagCalledEvents&&t.$feature_flag_has_experiment===!1}_captureFlagCalledEventIfNeeded(e){let{distinctId:t,key:n,response:s,groups:i,disableGeoip:o,properties:a}=e,c=i&&Object.keys(i).length>0?`_${JSON.stringify(Object.entries(i).sort(([u],[d])=>u<d?-1:u>d?1:0))}`:"",l=`${n}_${s}${c}`;t in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[t].has(l)||(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),this.distinctIdHasSentFlagCalls[t]instanceof Set?this.distinctIdHasSentFlagCalls[t].add(l):this.distinctIdHasSentFlagCalls[t]=new Set([l]),this.capture({distinctId:t,event:"$feature_flag_called",properties:a,groups:i,disableGeoip:o}))}_getFeatureFlagEvaluationsHost(){return this._featureFlagEvaluationsHost||(this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:e=>this._captureFlagCalledEventIfNeeded(e),logWarning:e=>{this.options.featureFlagsLogWarnings!==!1&&console.warn(`[PostHog] ${e}`)}}),this._featureFlagEvaluationsHost}groupIdentify({groupType:e,groupKey:t,properties:n,distinctId:s,disableGeoip:i}){this._sendPreparedEvent("capture",{distinctId:s||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:n||{}},disableGeoip:i},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:e,groupKey:t,properties:n,distinctId:s,disableGeoip:i}){await this._sendPreparedEvent("capture",{distinctId:s||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:n||{}},disableGeoip:i},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(e){let t=n=>Object.fromEntries(n.map(s=>[s,!0]));if(e===!1){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(e)){this._flagOverrides=t(e);return}if(this._isFeatureFlagOverrideOptions(e)){"flags"in e&&(e.flags===!1?this._flagOverrides=void 0:Array.isArray(e.flags)?this._flagOverrides=t(e.flags):e.flags!==void 0&&(this._flagOverrides={...e.flags})),"payloads"in e&&(e.payloads===!1?this._payloadOverrides=void 0:e.payloads!==void 0&&(this._payloadOverrides={...e.payloads}));return}this._flagOverrides={...e}}_isFeatureFlagOverrideOptions(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;if("flags"in t){let n=t.flags;if(n===!1||Array.isArray(n)||typeof n=="object"&&n!==null)return!0}if("payloads"in t){let n=t.payloads;if(n===!1||typeof n=="object"&&n!==null)return!0}return!1}withContext(e,t,n){return this.context?this.context.run(e,t,n):t()}getContext(){return this.context?.get()}enterContext(e,t){this.context?.enter(e,t)}async _shutdown(e){let t=Date.now()+(e??3e4),n=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(e),this.errorTracking.shutdown(),this._metrics&&(await De(this._metrics.flush().catch(()=>{}),Math.max(0,t-Date.now())),this._metrics.reset()),this._traces&&(await De(this._traces.flush().catch(()=>{}),Math.max(0,t-Date.now())),this._traces.reset());try{return await super._shutdown(Math.max(0,t-Date.now()))}finally{this.distinctIdHasSentFlagCalls={},n?.()}}async _requestRemoteConfigPayload(e){if(this.disabled||!this.apiKey||!this.options.personalApiKey)return;let t=`${this.host}/api/projects/@current/feature_flags/${e}/remote_config?token=${encodeURIComponent(this.apiKey)}`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},s=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let i=new AbortController;s=B(()=>{i.abort()},this.options.requestTimeout),n.signal=i.signal}try{return await this.fetch(t,n)}catch(i){this._events.emit("error",i);return}finally{s&&clearTimeout(s)}}extractPropertiesFromEvent(e,t){if(!e)return{personProperties:{},groupProperties:{}};let n={},s={};for(let[i,o]of Object.entries(e))if(pa(o)&&t&&i in t){let a={};for(let[c,l]of Object.entries(o))a[String(c)]=String(l);s[String(i)]=a}else n[String(i)]=String(o);return{personProperties:n,groupProperties:s}}async getFeatureFlagsForEvent(e,t,n,s){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let i=s?.personProperties||{},o=s?.groupProperties||{},a=s?.flagKeys;if(s?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let l={};for(let[u,d]of Object.entries(t||{}))l[u]=String(d);return await this.getAllFlags(e,{groups:l,personProperties:i,groupProperties:o,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let l={};for(let[u,d]of Object.entries(t||{}))l[u]=String(d);return await this.getAllFlags(e,{groups:l,personProperties:i,groupProperties:o,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}return(await super.getFeatureFlagsStateless(e,t,i,o,n)).flags}addLocalPersonAndGroupProperties(e,t,n,s){let i={...n||{}},o={};if(t)for(let a of Object.keys(t))o[a]={$group_key:t[a],...s?.[a]||{}};return{allPersonProperties:i,allGroupProperties:o}}personPropertiesForLocalEvaluation(e,t){return{distinct_id:e,...t||{}}}createFeatureFlagEvaluationContext(e,t,n,s){return{distinctId:e,groups:t||{},personProperties:n||{},groupProperties:s||{},evaluationCache:{}}}captureException(e,t,n,s,i){if(!Xe.isPreviouslyCapturedError(e)){let o=new Error("PostHog syntheticException");this.addPendingPromise(Xe.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:o},t,n).then(a=>this._capturePreparedEvent({...a,uuid:s,flags:i},!1)))}}async captureExceptionImmediate(e,t,n,s){if(!Xe.isPreviouslyCapturedError(e)){let i=new Error("PostHog syntheticException");return this.addPendingPromise(Xe.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:i},t,n).then(o=>this.captureImmediate({...o,flags:s})))}}async prepareEventMessage(e){return this._prepareEventMessage(e)}async _prepareEventMessage(e,t={}){let{distinctId:n,event:s,properties:i,groups:o,flags:a,sendFeatureFlags:c,timestamp:l,disableGeoip:u,uuid:d}=e,g=this.context?.get(),p=t.includeContextProperties??!0,h=n||g?.distinctId,m=p?{...this.props,...g?.properties||{},...i||{}}:{...i||{}};h||(h=j(),m.$process_person_profile=!1),p&&g?.sessionId&&!m.$session_id&&(m.$session_id=g.sessionId);let E=this._shouldSendMinimalFlagCalledEvent(s,m)?Bt(m):m,_=this._runBeforeSend({distinctId:h,event:s,properties:E,groups:o,flags:a,sendFeatureFlags:c,timestamp:l,disableGeoip:u,uuid:d});if(!_)return Promise.reject(null);let b=await Promise.resolve().then(async()=>{if(a)return c&&console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`."),a._getEventProperties();if(c){$n("sendFeatureFlags","`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead \u2014 it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");let P=typeof c=="object"?c:void 0,R=await this.getFeatureFlagsForEvent(_.distinctId,o,u,P);return nh(R)}return{}}).catch(()=>({})).then(P=>{let R=_.groups||o;return{...P,..._.properties||{},...R!==void 0&&Object.keys(R).length>0?{$groups:R}:{}}});return _.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof b.$raw_user_agent=="string"&&ha(b.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(_.event="$bot_pageview",b.$browser_type="bot"),{distinctId:_.distinctId,event:_.event,properties:b,options:{timestamp:_.timestamp,disableGeoip:_.disableGeoip,uuid:_.uuid}}}_runBeforeSend(e){let t=this.options.before_send;if(!t)return e;let n=Array.isArray(t)?t:[t],s=e;for(let i of n)try{if(s=i(s),!s)return this._logger.info(`Event '${e.event}' was rejected in beforeSend function`),null;if(!s.properties||Object.keys(s.properties).length===0){let o=`Event '${s.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(o)}}catch(o){return this._logger.error(`Error in before_send function for event '${e.event}':`,o),null}return s}};var pl=require("node:async_hooks"),Bn=class{constructor(){this.storage=new pl.AsyncLocalStorage}get(){return this.storage.getStore()}run(e,t,n){return this.storage.run(this.resolve(e,n),t)}enter(e,t){this.storage.enterWith(this.resolve(e,t))}resolve(e,t){if(t?.fresh===!0)return e;let n=this.get()||{};return{distinctId:e.distinctId??n.distinctId,sessionId:e.sessionId??n.sessionId,properties:{...n.properties||{},...e.properties||{}}}}};var gl=require("node:async_hooks"),Wn=class{active(){return this._storage.getStore()}with(e,t){return this._storage.run(e,t)}constructor(){this._storage=new gl.AsyncLocalStorage}};var hl=require("node:zlib"),ml=require("node:util"),sh=(0,ml.promisify)(hl.gzip);async function _l(r,e=!0){try{let t=await sh(r);return new Uint8Array(t)}catch(t){return e&&console.error("Failed to gzip compress data",t),null}}var Hn=require("node:os");function El(){let r,e;try{r=(0,Hn.platform)(),e=(0,Hn.release)()}catch{}return li(r,e)}var yl="posthog-node";function ih(r,{organization:e,projectId:t,prefix:n,severityAllowList:s=["error"],sendExceptionsToPostHog:i=!0}={}){return o=>{if(!(s==="*"||s.includes(o.level)))return o;o.tags||(o.tags={});let c=o.tags[Ci.POSTHOG_ID_TAG];if(c===void 0)return o;let l=r.options.host??"https://us.i.posthog.com",u=new URL(`/project/${r.apiKey}/person/${c}`,l).toString();o.tags["PostHog Person URL"]=u;let d=o.exception?.values||[],g=d.map(m=>({...m,stacktrace:m.stacktrace?{...m.stacktrace,type:"raw",frames:(m.stacktrace.frames||[]).map(E=>({...E,platform:"node:javascript"}))}:void 0})),p={$exception_message:d[0]?.value||o.message,$exception_type:d[0]?.type,$exception_level:o.level,$exception_list:g,$sentry_event_id:o.event_id,$sentry_exception:o.exception,$sentry_exception_message:d[0]?.value||o.message,$sentry_exception_type:d[0]?.type,$sentry_tags:o.tags},h=D.getInjectedReleaseId();return h&&(p.$release_id=h),e&&t&&(p.$sentry_url=(n||"https://sentry.io/organizations/")+e+"/issues/?project="+t+"&query="+o.event_id),i&&r.capture({event:"$exception",distinctId:c,properties:p}),o}}var Ci=class{static{this.POSTHOG_ID_TAG="posthog_distinct_id"}constructor(e,t,n,s,i){this.name=yl,this.name=yl,this.setupOnce=function(o,a){let c=a()?.getClient()?.getDsn()?.projectId;o(ih(e,{organization:t,projectId:c,prefix:n,severityAllowList:s,sendExceptionsToPostHog:i??!0}))}}};var Gn=class extends jn{getLibraryId(){return"posthog-node"}compressPayload(e){return _l(e,this.isDebug)}initializeContext(){return new Bn}initializeSpanContextManager(){return new Wn}hostResourceAttributes(){return El()}createErrorPropertiesBuilder(){return new D.ErrorPropertiesBuilder([new D.EventCoercer,new D.ErrorCoercer,new D.ObjectCoercer,new D.StringCoercer,new D.PrimitiveCoercer],D.createStackParser("node:javascript",D.nodeStackLineParser),[ca(),e=>Vc(e,void 0,this._logger),Jc()])}};var wl=fe(require("os"),1);A();var Sl=500;var bl=8192,de="[REDACTED]";function vl(r){try{if(typeof r!="string"){if(r==null)return"";try{r=String(r)}catch(t){let n=t instanceof Error?t:new Error(String(t));return f.warn("SYSTEM","error-scrub: String() coercion of non-string input failed",void 0,n),""}}let e=r;return e.length>bl?e.slice(0,bl):e}catch{return""}}function Mi(r){if(typeof r!="string"||r.length===0)return r??"";let e="";try{e=wl.default.homedir()||""}catch(n){let s=n instanceof Error?n:new Error(String(n));f.warn("SYSTEM","error-scrub: os.homedir() failed; skipping home-dir redaction",void 0,s),e=""}if(!e)return r;let t=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");try{return r.replace(new RegExp(t,"g"),"~")}catch(n){let s=n instanceof Error?n:new Error(String(n));return f.warn("SYSTEM","error-scrub: home-dir RegExp replace failed; using split/join fallback",void 0,s),r.split(e).join("~")}}function xi(r){return typeof r!="string"||r.length===0?r??"":r.replace(/(?<![~\w])\/(?:[^\s/:"'()]+\/)+([^\s/:"'()]+)/g,"$1").replace(/[A-Za-z]:\\(?:[^\s\\:"'()]+\\)*([^\s\\:"'()]+)/g,"$1").replace(/\\\\[^\s\\:"'()]+(?:\\[^\s\\:"'()]+)*\\([^\s\\:"'()]+)/g,"$1")}function oh(r){return typeof r!="string"||r.length===0?r??"":r.replace(/\b[A-Za-z][A-Za-z0-9+.-]*:\/\/[^\s"'()]+/g,e=>e.replace(/[?#].*$/,"").replace(/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)[^/@\s]+@/,`$1${de}@`))}function ah(r){if(typeof r!="string"||r.length===0)return r??"";let e=r;return e=e.replace(/[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,255}\.[A-Za-z]{2,24}/g,de),e=e.replace(/\b[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\b/g,de),e=e.replace(/\b(?:sk|pk|rk|ak|phc|phx|ph|ghp|gho|ghs|xox[bpasr])[-_][A-Za-z0-9_-]{8,512}\b/gi,de),e=e.replace(/\bBearer\s+[A-Za-z0-9._-]{8,512}\b/gi,de),e=e.replace(/\b(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA|ANVA|AIPA)[0-9A-Z]{16}\b/g,de),e=e.replace(/\b[0-9a-fA-F]{24,4096}\b/g,de),e=e.replace(/\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b/g,de),e=e.replace(/\b(?=[A-Za-z0-9+/_-]{0,4096}\d)[A-Za-z0-9+/_-]{32,4096}={0,2}\b/g,de),e=e.replace(/\b(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}\b/g,de),e}function ch(r){return typeof r!="string"||r.length===0?r??"":r.replace(/[ \t\f\v]+/g," ").replace(/ *\n */g,`
33
- `).trim()}function lh(r){let e=vl(r);return e.length===0?"":(e=Mi(e),e=xi(e),e=oh(e),e=ah(e),e)}function Al(r){try{let e=ch(lh(vl(r)));return e.length>Sl?e.slice(0,Sl):e}catch(e){let t=e instanceof Error?e:new Error(String(e));return f.warn("SYSTEM","error-scrub: message scrub failed; emitting empty message",void 0,t),""}}function Tl(r){return(typeof r=="string"?r:"").replace(/\[REDACTED\]/g,"\xA7").replace(/'[^']*'/g,"'\xA7'").replace(/"[^"]*"/g,'"\xA7"').replace(/\b\d+\b/g,"\xA7").replace(/[ \t]+/g," ").trim().slice(0,200)}var gT=300*1e3,hT=3600*1e3;A();var Oi=null,uh=!1,dh=3e4,Kn=null;function Il(){let r=Date.now();if(Kn&&r<Kn.expiresAt)return Kn.value;let e=Tr(process.env,Rt());return Kn={value:e,expiresAt:r+dh},e}var fh=!1;function ph(){if(!Oi){let r=fh&&uo(process.env)&&Il();Oi=new Gn(Rr(),{host:Cr(),flushAt:20,flushInterval:1e4,disableGeoip:!1,enableExceptionAutocapture:r,before_send:bh})}return Oi}var gh=6e4,hh=500,or=new Map;function mh(r,e,t){let n="";try{let s=(t||"").split(`
34
- `).map(i=>i.trim()).filter(Boolean);n=s.find(i=>i.startsWith("at "))??s[1]??""}catch(s){let i=s instanceof Error?s:new Error(String(s));f.warn("SYSTEM","Telemetry: stack parse failed while fingerprinting; using empty top frame",void 0,i),n=""}return`${r}::${Tl(e)}::${n}`.slice(0,400)}function _h(r,e){try{return Eh(r,e)}catch(t){let n=t instanceof Error?t:new Error(String(t));return f.warn("SYSTEM","Telemetry: error rate-limit bookkeeping failed; failing closed (event dropped)",void 0,n),{send:!1,count:0}}}function Eh(r,e){let t=or.get(r);if(!t){if(or.size>=hh){let n=null,s=1/0;for(let[i,o]of or){let a=Math.max(o.lastSentTs,o.firstTs);a<s&&(s=a,n=i)}n!==null&&or.delete(n)}return t={count:1,firstTs:e,lastSentTs:e},or.set(r,t),{send:!0,count:1}}if(t.count+=1,e-t.lastSentTs>=gh){t.lastSentTs=e;let n=t.count;return t.count=0,{send:!0,count:n}}return{send:!1,count:t.count}}var Pl="__cm_rate_limited";function yh(r){try{return typeof r!="string"||r.length===0?"":xi(Mi(r))}catch(e){let t=e instanceof Error?e:new Error(String(e));return f.warn("SYSTEM","Telemetry: frame filename redaction failed; stripping value entirely",void 0,t),""}}function Sh(r){let e=r.$exception_list;if(Array.isArray(e))for(let t of e){if(!t||typeof t!="object")continue;let n=t;typeof n.value=="string"&&(n.value=Al(n.value));let i=n.stacktrace?.frames;if(Array.isArray(i))for(let o of i){if(!o||typeof o!="object")continue;let a=o;delete a.context_line,delete a.pre_context,delete a.post_context,typeof a.filename=="string"&&(a.filename=yh(a.filename))}}}function bh(r){try{if(!r||typeof r!="object")return r;let e=r;if(e.event!=="$exception")return r;let t=e.properties??{};if(t[Pl]){try{delete t[Pl],e.properties=t}catch{}return r}Sh(t),t.$process_person_profile=!1,e.properties=t;let n="Error",s="",i="";try{let c=t.$exception_list;if(Array.isArray(c)&&c[0]&&typeof c[0]=="object"){let l=c[0];typeof l.type=="string"&&(n=l.type),typeof l.value=="string"&&(s=l.value);let u=l.stacktrace?.frames;Array.isArray(u)&&u.length>0&&(i="at "+JSON.stringify(u[u.length-1]).slice(0,200))}}catch{}typeof t.$exception_type=="string"&&(n=t.$exception_type),typeof t.$exception_message=="string"&&(s=t.$exception_message);let o=mh(n,s,i),a=_h(o,Date.now());if(!a.send)return null;try{t.occurrence_count=a.count,e.properties=t}catch{}return r}catch{return null}}function Fi(r,e,t){try{wh(r,e,t)}catch(n){let s=n instanceof Error?n:new Error(String(n));f.warn("SYSTEM","Telemetry: captureEvent failed; event dropped",{event:r},s)}}function wh(r,e,t){if(uh||!Il())return;let n=Ir({...xr(),...e??{}});if(t?.person?n.$set=Mr(n):n.$process_person_profile=!1,process.env.CLAUDE_MEM_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:r,properties:n})+`
35
- `);return}ph().capture({distinctId:Pr(),event:r,properties:n})}var vh=["babysit","ccs-align","cloud-sync","design-is","do","how-it-works","knowledge-agent","learn-codebase","make-plan","mem-search","mode-creator","oh-my-issues","pathfinder","smart-explore","standup","timeline-report","version-bump","weekly-digests","what-the","wowerpoint"],Ah=new Set(vh),Rl={skill_id:"other",skill_source:"third_party"};function Cl(r){let e=Th(r);return e&&Ah.has(e)?{skill_id:e,skill_source:"first_party"}:Rl}function Ml(r,e){if(r==="Skill"&&!(!e||typeof e!="object"))return e.skill}function Th(r){if(typeof r!="string")return null;let e=r.trim().toLowerCase();if(!e)return null;e=e.replace(/^\/+/,"");let t=e.lastIndexOf(":");return t!==-1&&(e=e.slice(t+1).replace(/^\/+/,"")),e||null}var xl=null;function Ph(){if(!xl)throw new Error("ingest helpers used before setIngestContext() \u2014 wiring bug");return xl}async function Fl(r){let{sessionManager:e,dbManager:t,eventBroadcaster:n,ensureGeneratorRunning:s}=Ph(),i=oe(r.platformSource),o=typeof r.cwd=="string"?r.cwd:"",a=o.trim()?He(o).primary:"",c=q.loadFromFile(tt);if(o&&Kr(o,c.CLAUDE_MEM_EXCLUDED_PROJECTS))return{ok:!0,status:"skipped",reason:"project_excluded"};if(new Set(c.CLAUDE_MEM_SKIP_TOOLS.split(",").map(_=>_.trim()).filter(Boolean)).has(r.toolName)){if(r.toolName==="Skill"){let{skill_id:_,skill_source:b}=Cl(Ml(r.toolName,r.toolInput));Fi("skill_invoked",{skill_id:_,skill_source:b,skill_trigger:"tool",ide:i})}return{ok:!0,status:"skipped",reason:"tool_excluded"}}if(new Set(["Edit","Write","Read","NotebookEdit"]).has(r.toolName)&&r.toolInput&&typeof r.toolInput=="object"){let _=r.toolInput,b=_.file_path||_.notebook_path;if(b&&b.includes("session-memory"))return{ok:!0,status:"skipped",reason:"session_memory_meta"}}let d=t.getSessionStore(),g,p;try{g=d.createSDKSession(r.contentSessionId,a,"",void 0,i),p=d.getPromptNumberFromUserPrompts(r.contentSessionId,g)}catch(_){let b=_ instanceof Error?_.message:String(_);return f.error("INGEST","Observation session resolution failed",{contentSessionId:r.contentSessionId,toolName:r.toolName},_ instanceof Error?_:new Error(b)),{ok:!1,reason:b,status:500}}if(!Yr.checkUserPromptPrivacy(d,r.contentSessionId,p,"observation",g,{tool_name:r.toolName}).allow)return{ok:!0,status:"skipped",reason:"private"};let m=r.toolInput!==void 0?Ps(JSON.stringify(r.toolInput)):"{}",E=r.toolResponse!==void 0?Ps(JSON.stringify(r.toolResponse)):"{}";if(r.toolUseId)try{d.upsertToolUse({toolUseId:r.toolUseId,contentSessionId:r.contentSessionId,sessionDbId:g,project:a,platformSource:i,toolName:r.toolName,toolInput:m,toolResponse:E,cwd:o||null,promptNumber:p,agentType:typeof r.agentType=="string"?r.agentType:null,agentId:typeof r.agentId=="string"?r.agentId:null,orGenerationId:typeof r.orGenerationId=="string"?r.orGenerationId:null,orSessionId:typeof r.orSessionId=="string"?r.orSessionId:null})}catch(_){f.warn("INGEST","tool_uses backup write failed (observation still queued)",{sessionId:g,toolName:r.toolName,toolUseId:r.toolUseId},_ instanceof Error?_:new Error(String(_)))}return await e.queueObservation(g,{tool_name:r.toolName,tool_input:m,tool_response:E,prompt_number:p,cwd:o||(f.error("INGEST","Missing cwd when ingesting observation",{sessionId:g,toolName:r.toolName}),""),agentId:typeof r.agentId=="string"?r.agentId:void 0,agentType:typeof r.agentType=="string"?r.agentType:void 0,toolUseId:typeof r.toolUseId=="string"?r.toolUseId:void 0}),await s?.(g,"observation"),n.broadcastObservationQueued(g),{ok:!0,sessionDbId:g}}var Ih=/agent-transcripts[/\\]([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:[/\\]|$)/i;function Rh(r){let e=typeof r.agentId=="string"?r.agentId.trim():"";return e&&e!=="*"?e:r.path.match(Ih)?.[1]}var Vn=class{sessions=new Map;async processEntry(e,t,n,s){for(let i of n.events)oa(e,i.match,n)&&await this.handleEvent(e,t,n,i,s??void 0)}getSessionKey(e,t){return`${e.name}:${t}`}getOrCreateSession(e,t){let n=this.getSessionKey(e,t),s=this.sessions.get(n);return s||(s={sessionId:t,platformSource:oe(e.name)},this.sessions.set(n,s)),s}resolveSessionId(e,t,n,s,i){let o={watch:t,schema:n},a=s.fields?.sessionId??(n.sessionIdPath?{path:n.sessionIdPath}:void 0),c=ot(a,e,o);return typeof c=="string"&&c.trim()?c:typeof c=="number"?String(c):i&&i.trim()?i:null}resolveCwd(e,t,n,s,i){let o={watch:t,schema:n,session:i},a=s.fields?.cwd??(n.cwdPath?{path:n.cwdPath}:void 0),c=ot(a,e,o);return typeof c=="string"&&c.trim()?c:t.workspace?t.workspace:i.cwd}resolveProject(e,t,n,s,i){let o={watch:t,schema:n,session:i},a=s.fields?.project??(n.projectPath?{path:n.projectPath}:void 0),c=ot(a,e,o);return typeof c=="string"&&c.trim()?c:t.project?t.project:i.cwd?He(i.cwd).primary:i.project}async handleEvent(e,t,n,s,i){let o=this.resolveSessionId(e,t,n,s,i);if(!o){f.debug("TRANSCRIPT","Skipping event without sessionId",{event:s.name,watch:t.name});return}let a=this.getOrCreateSession(t,o),c=this.resolveCwd(e,t,n,s,a);c&&(a.cwd=c);let l=this.resolveProject(e,t,n,s,a);l&&(a.project=l);let u=ia(s.fields,e,{watch:t,schema:n,session:a});switch(s.action){case"session_context":this.applySessionContext(a,u);break;case"session_init":await this.handleSessionInit(a,u),t.context?.updateOn?.includes("session_start")&&await this.updateContext(a,t);break;case"user_message":typeof u.message=="string"&&(a.lastUserMessage=u.message),typeof u.prompt=="string"&&(a.lastUserMessage=u.prompt);break;case"assistant_message":typeof u.message=="string"&&(a.lastAssistantMessage=u.message);break;case"tool_use":await this.handleToolUse(a,t,u);break;case"tool_result":await this.handleToolResult(a,t,u);break;case"observation":await this.sendObservation(a,t,u);break;case"file_edit":await this.sendFileEdit(a,u);break;case"session_end":await this.handleSessionEnd(a,t);break;default:break}}applySessionContext(e,t){let n=typeof t.cwd=="string"?t.cwd:void 0,s=typeof t.project=="string"?t.project:void 0;n&&(e.cwd=n),s&&(e.project=s)}async handleSessionInit(e,t){let n=typeof t.prompt=="string"?t.prompt:"",s=e.cwd??process.cwd();n&&(e.lastUserMessage=n),await Zo.execute({sessionId:e.sessionId,cwd:s,prompt:n,platform:e.platformSource})}async handleToolUse(e,t,n){let s=typeof n.toolId=="string"?n.toolId:void 0,i=typeof n.toolName=="string"?n.toolName:void 0,o=this.maybeParseJson(n.toolInput),a=this.maybeParseJson(n.toolResponse);if(i==="apply_patch"&&typeof o=="string"){let c=this.parseApplyPatchFiles(o);for(let l of c)await this.sendFileEdit(e,{filePath:l,edits:[{type:"apply_patch",patch:o}]})}i&&a!==void 0?await this.sendObservation(e,t,{toolName:i,toolInput:o,toolResponse:a,toolUseId:s}):i&&s&&(e.pendingTools||(e.pendingTools=new Map),e.pendingTools.set(s,{toolName:i,toolInput:o}))}async handleToolResult(e,t,n){let s=typeof n.toolId=="string"?n.toolId:void 0,i=typeof n.toolName=="string"?n.toolName:void 0,o=this.maybeParseJson(n.toolResponse),a=this.maybeParseJson(n.toolInput);if(s&&e.pendingTools){let c=e.pendingTools.get(s);c&&(i||(i=c.toolName),a===void 0&&(a=c.toolInput),e.pendingTools.delete(s))}i?await this.sendObservation(e,t,{toolName:i,toolInput:a,toolResponse:o,toolUseId:s}):f.debug("TRANSCRIPT","Dropping tool_result with no resolvable toolName",{sessionId:e.sessionId,toolId:s})}async sendObservation(e,t,n){let s=typeof n.toolName=="string"?n.toolName:void 0;if(!s)return;let i=await Fl({contentSessionId:e.sessionId,cwd:e.cwd??process.cwd(),toolName:s,toolInput:this.maybeParseJson(n.toolInput),toolResponse:this.maybeParseJson(n.toolResponse),platformSource:e.platformSource,toolUseId:typeof n.toolUseId=="string"?n.toolUseId:void 0,agentId:Rh(t)});if(!i.ok)throw new Error(`ingestObservation failed: ${i.reason}`)}async sendFileEdit(e,t){let n=typeof t.filePath=="string"?t.filePath:void 0;n&&await ea.execute({sessionId:e.sessionId,cwd:e.cwd??process.cwd(),filePath:n,edits:Array.isArray(t.edits)?t.edits:void 0,platform:e.platformSource})}maybeParseJson(e){if(typeof e!="string")return e;let t=e.trim();if(!t||!(t.startsWith("{")||t.startsWith("[")))return e;try{return JSON.parse(t)}catch(n){return f.debug("TRANSCRIPT","Field looked like JSON but did not parse; using raw string",{preview:t.slice(0,120)},n instanceof Error?n:void 0),e}}parseApplyPatchFiles(e){let t=[],n=e.split(`
36
- `);for(let s of n){let i=s.trim();if(i.startsWith("*** Update File: "))t.push(i.replace("*** Update File: ","").trim());else if(i.startsWith("*** Add File: "))t.push(i.replace("*** Add File: ","").trim());else if(i.startsWith("*** Delete File: "))t.push(i.replace("*** Delete File: ","").trim());else if(i.startsWith("*** Move to: "))t.push(i.replace("*** Move to: ","").trim());else if(i.startsWith("+++ ")){let o=i.replace("+++ ","").replace(/^b\//,"").trim();o&&o!=="/dev/null"&&t.push(o)}}return Array.from(new Set(t))}async handleSessionEnd(e,t){await this.queueSummary(e),await this.updateContext(e,t),e.pendingTools?.clear();let n=this.getSessionKey(t,e.sessionId);this.sessions.delete(n)}async queueSummary(e){if(!await Br())return;let n=e.lastAssistantMessage??"",s=JSON.stringify({contentSessionId:e.sessionId,last_assistant_message:n,platformSource:e.platformSource});try{await be("/api/sessions/summarize",{method:"POST",headers:{"Content-Type":"application/json"},body:s})}catch(i){f.warn("TRANSCRIPT","Summary request failed",{error:i instanceof Error?i.message:String(i)})}}async updateContext(e,t){if(!t.context||t.context.mode!=="agents"||Wi(t)||!await Br())return;let s=e.cwd??t.workspace;if(!s)return;let o=He(s).allProjects.join(","),a=`/api/context/inject?projects=${encodeURIComponent(o)}&platformSource=${encodeURIComponent(e.platformSource)}`,c=K(t.context.path??`${s}/AGENTS.md`),l=ar.default.resolve(c),u=[ar.default.resolve(s),ar.default.resolve(M)];if(!u.some(h=>l.startsWith(h+ar.default.sep)||l===h)){f.warn("SECURITY","Rejected path traversal attempt in watch.context.path",{original:t.context.path,resolved:l,allowedRoots:u});return}let g;try{g=await be(a)}catch(h){f.warn("TRANSCRIPT","Failed to fetch AGENTS.md context",{error:h instanceof Error?h.message:String(h)});return}if(!g.ok)return;let p=(await g.text()).trim();p&&(ra(c,p),f.debug("TRANSCRIPT","Updated AGENTS.md context",{agentsPath:c,watch:t.name}))}};var ki=class{constructor(e,t,n,s){this.filePath=e;this.onLine=n;this.onOffset=s;this.tailState={offset:t,partial:""}}filePath;onLine;onOffset;watcher=null;tailState;start(){this.readNewData().catch(()=>{}),this.watcher=(0,W.watch)(this.filePath,{persistent:!0},()=>{this.readNewData().catch(()=>{})})}close(){this.watcher?.close(),this.watcher=null}poke(){this.readNewData().catch(()=>{})}async readNewData(){if(!(0,W.existsSync)(this.filePath))return;let e=0;try{e=(0,W.statSync)(this.filePath).size}catch(o){f.debug("WORKER","Failed to stat transcript file",{file:this.filePath},o instanceof Error?o:void 0);return}if(e<this.tailState.offset&&(this.tailState.offset=0),e===this.tailState.offset)return;let t=(0,W.createReadStream)(this.filePath,{start:this.tailState.offset,end:e-1,encoding:"utf8"}),n="";for await(let o of t)n+=o;this.tailState.offset=e,this.onOffset(this.tailState.offset);let i=(this.tailState.partial+n).split(`
37
- `);this.tailState.partial=i.pop()??"";for(let o of i){let a=o.trim();a&&await this.onLine(a)}}},qn=class{constructor(e,t){this.config=e;this.statePath=t;this.state=Ki(t)}config;statePath;processor=new Vn;tailers=new Map;state;rootWatchers=[];async start(){for(let e of this.config.watches)await this.setupWatch(e)}stop(){for(let e of this.tailers.values())e.close();this.tailers.clear();for(let e of this.rootWatchers)e.close();this.rootWatchers=[]}async setupWatch(e){let t=this.resolveSchema(e);if(!t){f.warn("TRANSCRIPT","Missing schema for watch",{watch:e.name});return}let n=K(e.path),s=this.resolveWatchFiles(n);for(let o of s)await this.addTailer(o,e,t);let i=this.deepestNonGlobAncestor(n);if(!i||!(0,W.existsSync)(i)){f.debug("TRANSCRIPT","Watch root does not exist, skipping fs.watch",{watch:e.name,watchRoot:i});return}try{let o=(0,W.watch)(i,{recursive:!0,persistent:!0},(a,c)=>{this.handleRootWatchEvent(i,n,e,t,c)});this.rootWatchers.push(o),f.info("TRANSCRIPT","Watching transcript root recursively",{watch:e.name,watchRoot:i})}catch(o){f.warn("TRANSCRIPT","Failed to start recursive fs.watch on transcript root",{watch:e.name,watchRoot:i},o instanceof Error?o:void 0)}}handleRootWatchEvent(e,t,n,s,i){if(!i)return;let o=(0,ne.resolve)(e,i).replace(/\\/g,"/"),a=this.tailers.get(o);if(a){a.poke();return}let c=this.resolveWatchFiles(t);for(let l of c)this.tailers.has(l)||this.addTailer(l,n,s)}deepestNonGlobAncestor(e){if(!this.hasGlob(e)){if((0,W.existsSync)(e))try{return(0,W.statSync)(e).isDirectory()?e:(0,ne.resolve)(e,"..")}catch(s){return f.debug("TRANSCRIPT","Failed to stat watch path ancestor, falling back to parent directory",{path:e},s instanceof Error?s:new Error(String(s))),(0,ne.resolve)(e,"..")}return e}let t=e.split(/[/\\]/),n=[];for(let s of t){if(/[*?[\]{}()]/.test(s))break;n.push(s)}return n.length===0||n.length===1&&n[0]===""?"":n.join(ne.sep)}resolveSchema(e){return typeof e.schema=="string"?this.config.schemas?.[e.schema]??null:e.schema}resolveWatchFiles(e){if(this.hasGlob(e))return this.scanGlob(this.normalizeGlobPattern(e));if((0,W.existsSync)(e))try{if((0,W.statSync)(e).isDirectory()){let n=(0,ne.join)(e,"**","*.jsonl");return this.scanGlob(this.normalizeGlobPattern(n))}return[e]}catch(t){return f.debug("WORKER","Failed to stat watch path",{path:e},t instanceof Error?t:void 0),[]}return[]}scanGlob(e){return Array.from(new Bun.Glob(e).scanSync({absolute:!0,onlyFiles:!0}))}normalizeGlobPattern(e){return e.replace(/\\/g,"/")}hasGlob(e){return/[*?[\]{}()]/.test(e)}async addTailer(e,t,n){if(this.tailers.has(e))return;let s=this.extractSessionIdFromPath(e),i=this.state.offsets[e]??0;if(i===0&&t.startAtEnd)try{i=(0,W.statSync)(e).size}catch(a){f.debug("WORKER","Failed to stat file for startAtEnd offset",{file:e},a instanceof Error?a:void 0),i=0}let o=new ki(e,i,async a=>{await this.handleLine(a,t,n,e,s)},a=>{this.state.offsets[e]=a,Vi(this.statePath,this.state)});o.start(),this.tailers.set(e,o),f.info("TRANSCRIPT","Watching transcript file",{file:e,watch:t.name,schema:n.name})}async handleLine(e,t,n,s,i){try{let o=JSON.parse(e);await this.processor.processEntry(o,t,n,i??void 0)}catch(o){o instanceof Error?f.debug("TRANSCRIPT","Failed to parse transcript line",{watch:t.name,file:(0,ne.basename)(s)},o):f.warn("TRANSCRIPT","Failed to parse transcript line (non-Error thrown)",{watch:t.name,file:(0,ne.basename)(s),error:String(o)})}}extractSessionIdFromPath(e){let t=e.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i);return t?t[0]:null}};function Di(r,e){let t=r.indexOf(e);return t===-1?null:r[t+1]??null}async function Ol(r,e){switch(r){case"init":{let t=Di(e,"--config")??rt;return pr(t),console.log(`Created sample config: ${K(t)}`),0}case"watch":{let t=Di(e,"--config")??rt,n;try{n=At(t)}catch(a){if(a instanceof Error&&a.message.includes("not found"))pr(t),console.log(`Created sample config: ${K(t)}`),n=At(t);else throw a}let s=K(n.stateFile??fr),i=new qn(n,s);await i.start(),console.log("Transcript watcher running. Press Ctrl+C to stop.");let o=()=>{i.stop(),process.exit(0)};return process.on("SIGINT",o),process.on("SIGTERM",o),await new Promise(()=>{})}case"validate":{let t=Di(e,"--config")??rt;try{At(t)}catch(n){if(n instanceof Error&&n.message.includes("not found"))pr(t),console.log(`Created sample config: ${K(t)}`),At(t);else throw n}return console.log(`Config OK: ${K(t)}`),0}default:return console.log("Usage: claude-mem transcript <init|watch|validate> [--config <path>]"),1}}var Ch=process.argv[2],Mh=process.argv.slice(3);Ol(Ch,Mh).then(r=>{process.exit(r)}).catch(r=>{console.error(r),process.exit(1)});
30
+ ${e}`,o=ta(s,i),a=`${r}.tmp`;try{(0,te.writeFileSync)(a,o),(0,te.renameSync)(a,r)}catch(c){f.error("AGENTS_MD","Failed to write AGENTS.md",{agentsPath:r},c instanceof Error?c:new Error(String(c)))}}A();function Dd(r){let e=r.trim().replace(/^\$\.?/,"");if(!e)return[];let t=[],n=e.split(".");for(let s of n){let i=/([^[\]]+)|\[(\d+)\]/g,o;for(;(o=i.exec(s))!==null;)o[1]?t.push(o[1]):o[2]&&t.push(parseInt(o[2],10))}return t}function Is(r,e){if(!e)return;let t=Dd(e),n=r;for(let s of t){if(n==null)return;n=n[s]}return n}function na(r){return r==null||r===""}function sa(r,e){if(r.startsWith("$watch.")){let t=r.slice(7);return e.watch[t]}if(r.startsWith("$schema.")){let t=r.slice(8);return e.schema[t]}if(r.startsWith("$session.")){let t=r.slice(9);return e.session?e.session[t]:void 0}if(r==="$cwd")return e.watch.workspace;if(r==="$project")return e.watch.project}function ot(r,e,t){if(r!==void 0){if(typeof r=="string"){let n=sa(r,t);return n!==void 0?n:Is(e,r)}if(r.coalesce&&Array.isArray(r.coalesce))for(let n of r.coalesce){let s=ot(n,e,t);if(!na(s))return s}if(r.path){let n=sa(r.path,t);if(n!==void 0)return n;let s=Is(e,r.path);if(!na(s))return s}if(r.value!==void 0)return r.value;if(r.default!==void 0)return r.default}}function ia(r,e,t){let n={};if(!r)return n;for(let[s,i]of Object.entries(r))n[s]=ot(i,e,t);return n}function oa(r,e,t){if(!e)return!0;let n=e.path||t.eventTypePath||"type",s=n?Is(r,n):void 0,i=s==null||s==="";if(e.exists!==void 0&&(e.exists&&i||!e.exists&&!i)||e.equals!==void 0&&s!==e.equals||e.not_equals!==void 0&&s===e.not_equals||e.in&&Array.isArray(e.in)&&!e.in.includes(s)||e.not_in&&Array.isArray(e.not_in)&&e.not_in.includes(s)||e.contains!==void 0&&(typeof s!="string"||!s.includes(e.contains))||e.not_contains!==void 0&&typeof s=="string"&&s.includes(e.not_contains))return!1;if(e.regex)try{if(!new RegExp(e.regex).test(String(s??"")))return!1}catch(o){return f.debug("WORKER","Invalid regex in match rule",{regex:e.regex},o instanceof Error?o:void 0),!1}return!0}A();U();A();var Jr=class{static checkUserPromptPrivacy(e,t,n,s,i,o){let a=e.getUserPrompt(t,n,i);return a===null?(f.warn("HOOK",`${s}: no user_prompts row for prompt #${n} \u2014 ingesting anyway (session-init likely raced worker boot; see #2794/#2795)`,{sessionId:i,contentSessionId:t,promptNumber:n,...o}),{allow:!0,prompt:""}):a.trim()===""?(f.debug("HOOK",`Skipping ${s} - user prompt was entirely private`,{sessionId:i,promptNumber:n,...o}),{allow:!1,reason:"private"}):{allow:!0,prompt:a}}};var at=require("path");function ca(){let r=Ld();return async e=>{for(let t of e)t.module=r(t.filename);return e}}function Ld(r=process.argv[1]?(0,at.dirname)(process.argv[1]):process.cwd(),e=at.sep==="\\"){let t=e?aa(r):r;return n=>{if(!n)return;let s=e?aa(n):n,{dir:i,base:o,ext:a}=at.posix.parse(s);(a===".js"||a===".mjs"||a===".cjs")&&(o=o.slice(0,-1*a.length));let c=decodeURIComponent(o);i||(i=".");let l=i.lastIndexOf("/node_modules");if(l>-1)return`${i.slice(l+14).replace(/\//g,".")}:${c}`;if(i.startsWith(t)){let u=i.slice(t.length+1).replace(/\//g,".");return u?`${u}:${c}`:c}return c}}function aa(r){return r.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var D={};jl(D,{DEFAULT_EXCEPTION_STEPS_CONFIG:()=>gn,DOMExceptionCoercer:()=>Ws,EXCEPTION_STEP_INTERNAL_FIELDS:()=>$t,ErrorCoercer:()=>Dt,ErrorEventCoercer:()=>Hs,ErrorPropertiesBuilder:()=>kt,EventCoercer:()=>Gs,ExceptionStepsBuffer:()=>zs,ObjectCoercer:()=>Nt,PrimitiveCoercer:()=>Ut,PromiseRejectionEventCoercer:()=>Ks,ReduceableCache:()=>Vs,StringCoercer:()=>Lt,chromeStackLineParser:()=>Us,createDefaultStackParser:()=>Bs,createStackParser:()=>Ja,geckoStackLineParser:()=>$s,getInjectedReleaseId:()=>qf,getUtf8ByteLength:()=>Qa,nodeStackLineParser:()=>Ga,opera10StackLineParser:()=>Ba,opera11StackLineParser:()=>Wa,resolveExceptionStepsConfig:()=>qs,reverseAndStripFrames:()=>Ya,stripReservedExceptionStepFields:()=>Gf,winjsStackLineParser:()=>ja});var G=(function(r){return r.AnonymousId="anonymous_id",r.DistinctId="distinct_id",r.Props="props",r.EnablePersonProcessing="enable_person_processing",r.PersonMode="person_mode",r.FeatureFlagDetails="feature_flag_details",r.FeatureFlags="feature_flags",r.FeatureFlagPayloads="feature_flag_payloads",r.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",r.BootstrapFeatureFlags="bootstrap_feature_flags",r.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",r.OverrideFeatureFlags="override_feature_flags",r.Queue="queue",r.AiQueue="ai_queue",r.AiCaptureQueue="ai_capture_queue",r.LogsQueue="logs_queue",r.OptedOut="opted_out",r.SessionId="session_id",r.SessionStartTimestamp="session_start_timestamp",r.SessionLastTimestamp="session_timestamp",r.PersonProperties="person_properties",r.GroupProperties="group_properties",r.InstalledAppBuild="installed_app_build",r.InstalledAppVersion="installed_app_version",r.SessionReplay="session_replay",r.PushRegistered="push_registered",r.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",r.SurveyLastSeenDate="survey_last_seen_date",r.SurveysSeen="surveys_seen",r.Surveys="surveys",r.RemoteConfig="remote_config",r.FlagsEndpointWasHit="flags_endpoint_was_hit",r.DeviceId="device_id",r})({});function De(r){let e=[];return JSON.stringify(r,function(t,n){if(typeof n=="bigint")return n.toString();if(!(typeof n=="function"||typeof n=="symbol")){if(n instanceof Error)return{name:n.name,message:n.message,stack:n.stack};if(n&&typeof n=="object"){for(;e.length>0&&e[e.length-1]!==this;)e.pop();if(e.includes(n))return"[Circular]";e.push(n)}return n}})??"null"}var Nd=Array.isArray,ua=Object.prototype,py=ua.hasOwnProperty,Xr=ua.toString,Y=Nd||function(r){return Xr.call(r)==="[object Array]"};var Mt=r=>r===Object(r)&&!Y(r);var Ae=r=>r===void 0,$=r=>Xr.call(r)=="[object String]",Rs=r=>$(r)&&r.trim().length===0,Cs=r=>r===null,re=r=>Ae(r)||Cs(r),ct=r=>Xr.call(r)=="[object Number]"&&r===r;var da=r=>Xr.call(r)==="[object Boolean]";function Qr(r){return r===null||typeof r!="object"}function Ke(r,e){return Object.prototype.toString.call(r)===`[object ${e}]`}function lt(r){switch(Object.prototype.toString.call(r)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return ga(r,Error)}}function fa(r){return Ke(r,"ErrorEvent")}function ut(r){return"u">typeof Event&&ga(r,Event)}function pa(r){return Ke(r,"Object")}function ga(r,e){try{return r instanceof e}catch{return!1}}var Ud=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterestbot","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],ha=function(r,e=[]){if(!r)return!1;let t=r.toLowerCase();return Ud.concat(e).some(n=>{let s=n.toLowerCase();return t.indexOf(s)!==-1})};function xt(r,e,t,n,s){return e>t&&(n.warn("min cannot be greater than max."),e=t),ct(r)?r>t?(n.warn(" cannot be greater than max: "+t+". Using max value instead."),t):r<e?(n.warn(" cannot be less than min: "+e+". Using min value instead."),e):r:(n.warn(" must be a number. using max or fallback. max: "+t+", fallback: "+s),xt(s??t,e,t,n))}var $d=864e5,jd=1,Bd=10;function ma(r={}){return{refillRate:r.exceptionRateLimiterRefillRate??r.__exceptionRateLimiterRefillRate??jd,bucketSize:r.exceptionRateLimiterBucketSize??r.__exceptionRateLimiterBucketSize??Bd}}var Zr=class{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=xt(e.bucketSize,0,100,e._logger),this._refillRate=xt(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=xt(e.refillInterval,0,$d,e._logger)}_applyRefill(e,t){let n=t-e.lastAccess,s=Math.floor(n/this._refillInterval);if(s>0){let i=s*this._refillRate;e.tokens=Math.min(e.tokens+i,this._bucketSize),e.lastAccess=e.lastAccess+s*this._refillInterval}}consumeRateLimit(e){let t=Date.now(),n=String(e),s=this._buckets[n];return s?this._applyRefill(s,t):(s={tokens:this._bucketSize,lastAccess:t},this._buckets[n]=s),s.tokens===0?!0:(s.tokens--,s.tokens===0&&this._onBucketRateLimited?.(e),s.tokens===0)}stop(){this._buckets={}}};var en="0123456789abcdef",tn=class r{constructor(e){this.bytes=e}static ofInner(e){if(e.length===16)return new r(e);throw new TypeError("not 128-bit length")}static fromFieldsV7(e,t,n,s){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(n)||!Number.isInteger(s)||e<0||t<0||n<0||s<0||e>0xffffffffffff||t>4095||n>1073741823||s>4294967295)throw new RangeError("invalid field value");let i=new Uint8Array(16);return i[0]=e/2**40,i[1]=e/2**32,i[2]=e/2**24,i[3]=e/2**16,i[4]=e/256,i[5]=e,i[6]=112|t>>>8,i[7]=t,i[8]=128|n>>>24,i[9]=n>>>16,i[10]=n>>>8,i[11]=n,i[12]=s>>>24,i[13]=s>>>16,i[14]=s>>>8,i[15]=s,new r(i)}static parse(e){let t;switch(e.length){case 32:t=/^[0-9a-f]{32}$/i.exec(e)?.[0];break;case 36:t=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("");break;case 38:t=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(e)?.slice(1,6).join("");break;case 45:t=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("");break;default:break}if(t){let n=new Uint8Array(16);for(let s=0;s<16;s+=4){let i=parseInt(t.substring(2*s,2*s+8),16);n[s+0]=i>>>24,n[s+1]=i>>>16,n[s+2]=i>>>8,n[s+3]=i}return new r(n)}throw new SyntaxError("could not parse UUID string")}toString(){let e="";for(let t=0;t<this.bytes.length;t++)e+=en.charAt(this.bytes[t]>>>4),e+=en.charAt(15&this.bytes[t]),(t===3||t===5||t===7||t===9)&&(e+="-");return e}toHex(){let e="";for(let t=0;t<this.bytes.length;t++)e+=en.charAt(this.bytes[t]>>>4),e+=en.charAt(15&this.bytes[t]);return e}toJSON(){return this.toString()}getVariant(){let e=this.bytes[8]>>>4;if(e<0)throw new Error("unreachable");if(e<=7)return this.bytes.every(t=>t===0)?"NIL":"VAR_0";if(e<=11)return"VAR_10";if(e<=13)return"VAR_110";if(e<=15)return this.bytes.every(t=>t===255)?"MAX":"VAR_RESERVED";throw new Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new r(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(let t=0;t<16;t++){let n=this.bytes[t]-e.bytes[t];if(n!==0)return Math.sign(n)}return 0}},Ms=class{constructor(e){this.timestamp=0,this.counter=0,this.random=e??Wd()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(e,t){let n=this.generateOrAbortCore(e,t);return n===void 0&&(this.timestamp=0,n=this.generateOrAbortCore(e,t)),n}generateOrAbortCore(e,t){if(!Number.isInteger(e)||e<1||e>0xffffffffffff)throw new RangeError("`unixTsMs` must be a 48-bit positive integer");if(t<0||t>0xffffffffffff)throw new RangeError("`rollbackAllowance` out of reasonable range");if(e>this.timestamp)this.timestamp=e,this.resetCounter();else{if(!(e+t>=this.timestamp))return;this.counter++,this.counter>4398046511103&&(this.timestamp++,this.resetCounter())}return tn.fromFieldsV7(this.timestamp,Math.trunc(this.counter/2**30),this.counter&2**30-1,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}generateV4(){let e=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return e[6]=64|e[6]>>>4,e[8]=128|e[8]>>>2,tn.ofInner(e)}},Wd=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())>>>0}),_a,j=()=>Hd().toString(),Hd=()=>(_a||(_a=new Ms)).generate();var rn=class{add(e){let t=j(),n=++this.nextId;return this.promiseByIds[t]={id:n,promise:e},e.catch(()=>{}).finally(()=>{delete this.promiseByIds[t]}),e}async join(){let e=Object.values(this.promiseByIds).map(n=>n.promise),t=e.length;for(;t>0;)await Promise.all(e),e=Object.values(this.promiseByIds).map(n=>n.promise),t=e.length}getPromises(e=[],t=this.nextId){let n=new Set(e);return Object.values(this.promiseByIds).filter(s=>s.id<=t&&!n.has(s.promise)).map(s=>s.promise)}get maxId(){return this.nextId}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={},this.nextId=0}};function Gd(r=console){return{log:r.log.bind(r),warn:r.warn.bind(r),error:r.error.bind(r),debug:r.debug.bind(r)}}var Ea=(r,e,t)=>{function n(i,...o){e(()=>{let a=t[i];a(r,...o)})}return{debug:(...i)=>{n("debug",...i)},info:(...i)=>{n("log",...i)},warn:(...i)=>{n("warn",...i)},error:(...i)=>{n("error",...i)},critical:(...i)=>{t.error(r,...i)},createLogger:i=>Ea(`${r} ${i}`,e,t)}},Kd=r=>r();function ya(r,e=Kd){return Ea(r,e,Gd())}var ft="Mobile",sn="iOS",dt="Android",Aa="Tablet",Ry=dt+" "+Aa;var qd="Apple",Cy=qd+" Watch",Ta="Safari",on="BlackBerry",Pa="Samsung",zd=Pa+"Browser",Yd=Pa+" Internet",an="Chrome",Jd=an+" OS",Xd=an+" "+sn,Ia="Internet Explorer",Qd=Ia+" "+ft,Os="Opera",My=Os+" Mini",Ra="Edge",Zd="Microsoft "+Ra,ks="Firefox",ef=ks+" "+sn,Ds="Nintendo",Ls="PlayStation",nn="Xbox",tf=dt+" "+ft,rf=ft+" "+Ta,Ft="Windows",nf=Ft+" Phone";var Ca="Generic",xy=Ca+" "+ft.toLowerCase(),Fy=Ca+" "+Aa.toLowerCase(),sf="Konqueror",of="Oculus Browser",Sa="Vivaldi",af="Yandex",ba="Whale",cf="DuckDuckGo",lf="Pale Moon",wa="Waterfox",va="Brave",Ma="Claude",xa="Codex",Fa="ChatGPT",uf="Google Search App",C="(\\d+(\\.\\d+)?)",xs=new RegExp("Version/"+C),Fs=new RegExp("("+Ma+"|"+xa+"|"+Fa+")\\/"+C);var Oy=new RegExp(nn,"i"),ky=new RegExp(Ls+" \\w+","i"),Dy=new RegExp(Ds+" \\w+","i"),df=new RegExp(on+"|PlayBook|BB10","i"),ff={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000","5.1":"XP","5.2":"XP","6.0":"Vista","6.1":"7","6.2":"8","6.3":"8.1","6.4":"10","10.0":"10"};var Ly={[Qd]:[new RegExp("rv:"+C)],[Zd]:[new RegExp(Ra+"?\\/"+C)],[an]:[new RegExp("("+an+"|CrMo)\\/"+C)],[Xd]:[new RegExp("CriOS\\/"+C)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+C)],[Ta]:[xs],[rf]:[xs],[Os]:[new RegExp("("+Os+"|OPR)\\/"+C)],[ks]:[new RegExp(ks+"\\/"+C)],[ef]:[new RegExp("FxiOS\\/"+C)],[sf]:[new RegExp("Konqueror[:/]?"+C,"i")],[on]:[new RegExp(on+" "+C),xs],[tf]:[new RegExp("android\\s"+C,"i")],[Yd]:[new RegExp(zd+"\\/"+C)],[of]:[new RegExp("OculusBrowser\\/"+C)],[Sa]:[new RegExp(Sa+"\\/"+C)],[af]:[new RegExp("YaBrowser\\/"+C)],[ba]:[new RegExp(ba+"\\/"+C)],[va]:[new RegExp(va+"\\/"+C)],[Ma]:[Fs],[xa]:[Fs],[Fa]:[Fs],[cf]:[new RegExp("(DuckDuckGo|Ddg)\\/"+C)],[lf]:[new RegExp("PaleMoon\\/"+C)],[wa]:[new RegExp(wa+"\\/"+C)],[uf]:[new RegExp("GSA\\/"+C)],[Ia]:[new RegExp("(rv:|MSIE )"+C)],Mozilla:[new RegExp("rv:"+C)]};var Ny=[[new RegExp(nn+"; "+nn+" (.*?)[);]","i"),r=>[nn,r&&r[1]||""]],[new RegExp(Ds,"i"),[Ds,""]],[new RegExp(Ls,"i"),[Ls,""]],[df,[on,""]],[new RegExp(Ft,"i"),(r,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[nf,""];if(new RegExp(ft).test(e)&&!/IEMobile\b/.test(e))return[Ft+" "+ft,""];let t=/Windows NT ([0-9.]+)/i.exec(e);if(t&&t[1]){let n=t[1],s=ff[n]||"";return/arm/i.test(e)&&(s="RT"),[Ft,s]}return[Ft,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,r=>{if(r&&r[3]){let e=[r[3],r[4],r[5]||"0"];return[sn,e.join(".")]}return[sn,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,r=>{let e="";return r&&r.length>=3&&(e=Ae(r[2])?r[3]:r[2]),["watchOS",e]}],[new RegExp("("+dt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+dt+")","i"),r=>{if(r&&r[2]){let e=[r[2],r[3],r[4]||"0"];return[dt,e.join(".")]}return[dt,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,r=>{let e=["Mac OS X",""];if(r&&r[1]){let t=[r[1],r[2],r[3]||"0"];e[1]=t.join(".")}return e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[Jd,""]],[/Linux|debian/i,["Linux",""]]];var cn="[Circular]",ln="[Truncated]",J="[Unserializable]",Oa="[Function]",jy=Date.prototype.getTime,By=Date.prototype.toISOString;function ce(r){let e="";for(let t=0;t<r.length;t++){let n=r.charCodeAt(t);if(n>=55296&&n<=56319){let s=r.charCodeAt(t+1);s>=56320&&s<=57343?(e+=r[t]+r[t+1],t++):e+="\uFFFD"}else e+=n>=56320&&n<=57343?"\uFFFD":r[t]}return e}function Te(r,e){if(!e)return r;let t=[];try{t=Object.keys(e)}catch{t=[]}for(let n of t){let s;try{s=e[n]}catch{s=J}Object.defineProperty(r,n,{value:s,enumerable:!0,writable:!0,configurable:!0})}return r}var ka="utf8",pf=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function gf(r){return typeof r=="string"&&pf.test(r)}function Ve(r,e){return gf(r)?r:e()}function pt(r,e){let t=new Error(e);try{Object.defineProperty(t,"name",{value:r,writable:!0,enumerable:!0,configurable:!0})}catch{}return t}function Da(r){return r?.replace(/\/+$/,"")}async function La(r,e){let t=null;for(let n=0;n<e.retryCount+1;n++){n>0&&await new Promise(s=>setTimeout(s,e.retryDelay));try{return await r()}catch(s){if(t=s,!e.retryCheck(s))throw s}}throw t}function Ns(){return new Date().toISOString()}function B(r,e){let t=setTimeout(r,e);return t?.unref&&t?.unref(),t}async function Le(r,e,t){let n;try{return await Promise.race([r,new Promise((s,i)=>{n=B(()=>{try{t?.(),s()}catch(o){i(o)}},e)})])}finally{clearTimeout(n)}}var Na=r=>r&&typeof r.then=="function";function Ot(r){return Promise.all(r.map(e=>(e??Promise.resolve()).then(t=>({status:"fulfilled",value:t}),t=>({status:"rejected",reason:t}))))}var un,Ua,dn;function $a(r){let e=globalThis._posthogChunkIds;if(!e)return;let t=Object.keys(e);return dn&&t.length===Ua||(Ua=t.length,dn=t.reduce((n,s)=>{un||(un={});let i=un[s];if(i)n[i[0]]=i[1];else{let o=r(s);for(let a=o.length-1;a>=0;a--){let l=o[a]?.filename,u=e[s];if(l&&u){n[l]=u,un[s]=[l,u];break}}}return n},{})),dn}var hf=4,kt=class{constructor(e,t,n=[]){this.coercers=e,this.stackParser=t,this.modifiers=n}buildFromUnknown(e,t={}){let s=t&&t.mechanism||{handled:!0,type:"generic"},o=this.buildCoercingContext(s,t,0).apply(e),a=this.buildParsingContext(t),c=this.parseStacktrace(o,a);return{$exception_list:this.convertToExceptionList(c,s),$exception_level:"error"}}async modifyFrames(e){for(let t of e)t.stacktrace&&t.stacktrace.frames&&Y(t.stacktrace.frames)&&(t.stacktrace.frames=await this.applyModifiers(t.stacktrace.frames));return e}coerceFallback(e){return{type:"Error",value:"Unknown error",stack:e.syntheticException?.stack,synthetic:!0}}parseStacktrace(e,t){let n;e.cause!=null&&(n=this.parseStacktrace(e.cause,t));let s;return e.stack!=""&&e.stack!=null&&(s=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap)),{...e,cause:n,stack:s}}applyChunkIds(e,t){return e.map(n=>(n.filename&&t&&(n.chunk_id=t[n.filename]),n))}applyCoercers(e,t){for(let n of this.coercers)if(n.match(e))return n.coerce(e,t);return this.coerceFallback(t)}async applyModifiers(e){let t=e;for(let n of this.modifiers)t=await n(t);return t}convertToExceptionList(e,t){let n={type:e.type,value:e.value,mechanism:{type:t.type??"generic",handled:t.handled??!0,synthetic:e.synthetic??!1}};e.stack&&(n.stacktrace={type:"raw",frames:e.stack});let s=[n];return e.cause!=null&&s.push(...this.convertToExceptionList(e.cause,{...t,handled:!0})),s}buildParsingContext(e){return{chunkIdMap:$a(this.stackParser),skipFirstLines:e.skipFirstLines??1}}buildCoercingContext(e,t,n=0){let s=(o,a)=>{if(a<=hf){let c=this.buildCoercingContext(e,t,a);return this.applyCoercers(o,c)}};return{...t,syntheticException:n==0?t.syntheticException:void 0,mechanism:e,apply:o=>s(o,n),next:o=>s(o,n+1)}}};var N="?",mf="<anonymous>",_f=/^([a-z][a-z0-9.+-]+):/i,Ef=["http","https","file","blob","app","capacitor","ionic","webpack","webpack-internal","ng"];function yf(r){if(!r||r===mf)return!1;let e=_f.exec(r);return!e||Ef.includes(e[1].toLowerCase())}function le(r,e,t,n,s){let i={platform:r,filename:e,function:t==="<anonymous>"?N:t,in_app:yf(e)};return Ae(n)||(i.lineno=n),Ae(s)||(i.colno=s),i}var fn=(r,e)=>{let t=r.indexOf("safari-extension")!==-1,n=r.indexOf("safari-web-extension")!==-1;return t||n?[r.indexOf("@")!==-1?r.split("@")[0]:N,t?`safari-extension:${e}`:`safari-web-extension:${e}`]:[r,e]};var Sf=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,bf=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,wf=/\((\S*)(?::(\d+))(?::(\d+))\)/,Us=(r,e)=>{let t=Sf.exec(r);if(t){let[,s,i,o]=t;return le(e,s,N,+i,+o)}let n=bf.exec(r);if(n){if(n[2]&&n[2].indexOf("eval")===0){let a=wf.exec(n[2]);a&&(n[2]=a[1],n[3]=a[2],n[4]=a[3])}let[i,o]=fn(n[1]||N,n[2]);return le(e,o,i,n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}};var vf=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Af=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,$s=(r,e)=>{let t=vf.exec(r);if(t){if(t[3]&&t[3].indexOf(" > eval")>-1){let o=Af.exec(t[3]);o&&(t[1]=t[1]||"eval",t[3]=o[1],t[4]=o[2],t[5]="")}let s=t[3],i=t[1]||N;return[i,s]=fn(i,s),le(e,s,i,t[4]?+t[4]:void 0,t[5]?+t[5]:void 0)}};var Tf=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,ja=(r,e)=>{let t=Tf.exec(r);return t?le(e,t[2],t[1]||N,+t[3],t[4]?+t[4]:void 0):void 0};var Pf=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,Ba=(r,e)=>{let t=Pf.exec(r);return t?le(e,t[2],t[3]||N,+t[1]):void 0},If=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,Wa=(r,e)=>{let t=If.exec(r);return t?le(e,t[5],t[3]||t[4]||N,+t[1],+t[2]):void 0};var Rf=/^\s*[-]{4,}$/,Cf=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,Mf=/^Promise\.(?:all|any)$/,xf=/^index \d+$/,Ff="node:internal/promise",Ga=(r,e)=>{let t=r.match(Cf);if(t){let n,s,i,o,a;if(t[1]){i=t[1];let u=i.lastIndexOf(".");if(i[u-1]==="."&&u--,u>0){n=i.slice(0,u),s=i.slice(u+1);let d=n.indexOf(".Module");d>0&&(i=i.slice(d+1),n=n.slice(0,d))}o=void 0}s&&(o=n,a=s),s==="<anonymous>"&&(a=void 0,i=void 0),i===void 0&&(a=a||N,i=o?`${o}.${a}`:a);let c=t[2]?.startsWith("file://")?t[2].slice(7):t[2],l=t[5]==="native";return c?.match(/\/[A-Z]:/)&&(c=c.slice(1)),!c&&t[5]&&!l&&(c=t[5]),Mf.test(i)&&xf.test(c||"")&&(c=Ff),{filename:c?decodeURI(c):void 0,module:void 0,function:i,lineno:Ha(t[3]),colno:Ha(t[4]),in_app:Of(c||"",l),platform:e}}if(r.match(Rf))return{filename:r,platform:e}};function Of(r,e=!1){return!(e||r&&!r.startsWith("/")&&!r.match(/^[A-Z]:/)&&!r.startsWith(".")&&!r.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&r!==void 0&&!r.includes("node_modules/")}function Ha(r){return parseInt(r||"",10)||void 0}var Ka=/\(error: (.*)\)/,Va=50,kf=10,Df=1e3;function js(r,e){return r.filename===e.filename&&r.function===e.function&&r.module===e.module&&r.lineno===e.lineno&&r.colno===e.colno}function Lf(r){for(let e=1;e<=kf;e++){let t=r.length-2*e;if(t<0)break;let n=!0;for(let s=0;s<e;s++){let i=r[t+s];if(!js(i,r[t+e+s])){n=!1;break}}if(n){for(let s=0;s<e;s++)r[t+s]=r[t+e+s];return r.length=t+e,{start:t,length:e}}}}function Nf(r,e){let t=e.start+e.length,n=za(r,e);n&&r.splice(t+n===r.length?t:e.start,n)}function qa(r,e){let t=e.start;for(;t>0&&js(r[t-1],r[t-1+e.length]);)t--;return e.start-t}function za(r,e){let t=e.start+e.length,n=t;for(;n<r.length&&js(r[n],r[n-e.length]);)n++;return n-t}function Uf(r,e){let t=e[0],n=r.length-(t?qa(r,t):0);for(let s of e)n-=za(r,s);return n}function $f(r){let e=r.map(n=>`${n.function}|${n.filename}|${n.lineno}|${n.colno}|${n.module}`),t=0;for(let n=1;n<e.length;n++)jf(e,n,t)&&(t=n);r.push(...r.splice(0,t))}function jf(r,e,t){for(let n=0;n<r.length;n++){let s=r[(e+n)%r.length],i=r[(t+n)%r.length];if(s!==i)return s<i}return!1}function Ya(r){if(!r.length)return[];let e=Array.from(r);return e.reverse(),e.slice(0,Va).map(t=>({...t,filename:t.filename||Bf(e).filename,function:t.function||N}))}function Bf(r){return r[r.length-1]||{}}function Bs(){return Ja("web:javascript",Us,$s)}function Ja(r,...e){return(t,n=0)=>{let s=[],i=t.split(`
31
+ `),o=Math.min(i.length,n+Df),a=[];for(let u=n;u<o;u++){let d=i[u];if(d.length>1024)continue;let g=Ka.test(d)?d.replace(Ka,"$1"):d;if(!g.match(/\S*Error: /)){for(let p of e){let h=p(g,r);if(h){s.push(h);let m=Lf(s);if(m){for(let E=a.length-1;E>=0;E--){let _=a[E];if(_.start+_.length<=m.start)break;a.pop()}a.push(m)}break}}if(Uf(s,a)>=Va)break}}let c=[...a].sort((u,d)=>d.start-u.start),l=c[c.length-1];if(l){let u=qa(s,l);s.splice(l.start-u,u);for(let d of c)d.start-=u}for(let u of c)Nf(s,u);return a.some(u=>u.start===0&&s.length===u.length)&&$f(s),Ya(s)}}var Ws=class{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){let n=$(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:n?e.stack:void 0,cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){let t=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?`${t}: ${e.message}`:t}isDOMException(e){return Ke(e,"DOMException")}isDOMError(e){return Ke(e,"DOMError")}};var Dt=class{match(e){return lt(e)}coerce(e,t){let n=this.getStack(e),s=n===void 0;return{type:this.getType(e),value:this.getMessage(e,t),stack:n??t.syntheticException?.stack,cause:e.cause?t.next(e.cause):void 0,synthetic:s}}getType(e){return e.name||e.constructor.name}getMessage(e,t){let n=e.message;return n.error&&typeof n.error.message=="string"?String(n.error.message):String(n)}getStack(e){return e.stacktrace||e.stack||void 0}};var Hs=class{match(e){if(!fa(e))return!1;let t=e;return t.error!=null||this._hasUsableMessage(t)}coerce(e,t){if(e.error!=null)return t.apply(e.error);let n=t.apply(e.message);return{...n,stack:this._buildLocationStack(e)??n.stack,synthetic:!0}}_hasUsableMessage(e){return $(e.message)&&e.message.length>0}_buildLocationStack(e){let t=e,n=t.lineno??0,s=t.colno??0;if(!(!$(t.filename)||t.filename.length===0)&&n!==0)return`Error
32
+ at ${t.filename}:${n}:${s}`}};var Wf=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,Lt=class{match(e){return typeof e=="string"}coerce(e,t){let[n,s]=this.getInfos(e);return{type:n??"Error",value:s??e,stack:t.syntheticException?.stack,synthetic:!0}}getInfos(e){let t="Error",n=e,s=e.match(Wf);return s&&(t=s[1],n=s[2]),[t,n]}};var Xa=["fatal","error","warning","log","info","debug"];function pn(r,e=40){let t=Object.keys(r);if(t.sort(),!t.length)return"[object has no keys]";for(let n=t.length;n>0;n--){let s=t.slice(0,n).join(", ");if(!(s.length>e))return n===t.length||s.length<=e?s:`${s.slice(0,e)}...`}return""}var Nt=class{match(e){return typeof e=="object"&&e!==null}coerce(e,t){let n=this.getErrorPropertyFromObject(e);return n?t.apply(n):{type:this.getType(e),value:this.getValue(e),stack:this.getStack(e)??t.syntheticException?.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){if(ut(e))return e.constructor.name;let t="name"in e?e.name:void 0;return $(t)&&!Rs(t)?t:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){let s=`'${e.name}' captured as exception`;return"message"in e&&typeof e.message=="string"&&(s+=` with message: '${e.message}'`),s}if("message"in e&&typeof e.message=="string")return e.message;let t=this.getObjectClassName(e),n=pn(e);return`${t&&t!=="Object"?`'${t}'`:"Object"} captured as exception with keys: ${n}`}isSeverityLevel(e){return $(e)&&!Rs(e)&&Xa.indexOf(e)>=0}getStack(e){try{return $(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:$(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let n=e[t];if(lt(n))return n}}getObjectClassName(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch{return}}};var Gs=class{match(e){return ut(e)}coerce(e,t){let n=e.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${pn(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}};var Ut=class{match(e){return Qr(e)}coerce(e,t){return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}};var Ks=class{match(e){return Ke(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!ut(e))return!1;try{let t=e.detail;return t!=null&&typeof t=="object"&&"reason"in t}catch{return!1}}coerce(e,t){let n=this.getUnhandledRejectionReason(e);return Qr(n)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(n)}`,stack:t.syntheticException?.stack,synthetic:!0}:t.apply(n)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}};var Vs=class{constructor(e){this._maxSize=e,this._cache=new Map}get(e){let t=this._cache.get(e);if(t!==void 0)return this._cache.delete(e),this._cache.set(e,t),t}set(e,t){this._cache.set(e,t)}reduce(){for(;this._cache.size>=this._maxSize;){let e=this._cache.keys().next().value;e&&this._cache.delete(e)}}};var $t={MESSAGE:"$message",TIMESTAMP:"$timestamp"},Hf=new Set([$t.MESSAGE,$t.TIMESTAMP]),gn={enabled:!0,max_bytes:32768};function qs(r){return r?{enabled:r.enabled??gn.enabled,max_bytes:Kf(r.max_bytes,gn.max_bytes)}:{...gn}}function Gf(r){if(!r)return{sanitizedProperties:{},droppedKeys:[]};let e=[];return{sanitizedProperties:Object.keys(r).reduce((n,s)=>Hf.has(s)?(e.push(s),n):(n[s]=r[s],n),{}),droppedKeys:e}}var zs=class{constructor(e){this._entries=[],this._totalBytes=0,this._config=qs(e)}setConfig(e){this._config=qs(e),this._trimToMaxBytes()}add(e){let t=Vf(e);if(!t)return;let n=Qa(t.json);n>this._config.max_bytes||(this._entries.push({step:t.step,bytes:n}),this._totalBytes+=n,this._trimToMaxBytes())}getAttachable(){return this._entries.map(e=>e.step)}clear(){this._entries=[],this._totalBytes=0}size(){return this._entries.length}_trimToMaxBytes(){for(;this._totalBytes>this._config.max_bytes&&this._entries.length>0;){let e=this._entries.shift();e&&(this._totalBytes-=e.bytes)}}};function Kf(r,e){if(!ct(r)||r===1/0||r===-1/0)return e;let t=Math.floor(r);return t<0?e:t}function Vf(r){let e;try{e=De(r)}catch{return}try{let t=JSON.parse(e);if(!Mt(t))return;let n=t,s=n[$t.MESSAGE],i=n[$t.TIMESTAMP];return!$(s)||s.trim().length===0||!$(i)&&!ct(i)?void 0:{step:n,json:e}}catch{return}}function Qa(r){if("u">typeof TextEncoder)return new TextEncoder().encode(r).length;let e=encodeURIComponent(r),t=0;for(let n=0;n<e.length;n++)e[n]==="%"?(t+=1,n+=2):t+=1;return t}function qf(){let r=globalThis._posthogReleaseId;return typeof r=="string"&&r.length>0?r:void 0}var Ys=r=>{if("flags"in r){let e=Za(r.flags),t=ec(r.flags);return{...r,featureFlags:e,featureFlagPayloads:t}}{let e=r.featureFlags??{},t=Object.fromEntries(Object.entries(r.featureFlagPayloads||{}).map(([s,i])=>[s,gt(i)])),n=Object.fromEntries(Object.entries(e).map(([s,i])=>[s,zf(s,i,t[s])]));return{...r,featureFlags:e,featureFlagPayloads:t,flags:n}}};function zf(r,e,t){return{key:r,enabled:typeof e=="string"?!0:e,variant:typeof e=="string"?e:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:t?JSON.stringify(t):void 0,description:void 0}}}var Za=r=>Object.fromEntries(Object.entries(r??{}).map(([e,t])=>[e,jt(t)]).filter(([,e])=>e!==void 0)),ec=r=>{let e=r??{};return Object.fromEntries(Object.keys(e).filter(t=>{let n=e[t];return n.enabled&&n.metadata&&n.metadata.payload!==void 0}).map(t=>{let n=e[t].metadata?.payload;return[t,n?gt(n):void 0]}))},jt=r=>r===void 0?void 0:r.variant??r.enabled,gt=r=>{if(typeof r!="string")return r;try{return JSON.parse(r)}catch{return r}};var tc=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],Yf=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain",...tc,"$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],Bt=(r,e=[])=>{let t={},n=s=>{r[s]!==void 0&&(t[s]=r[s])};return Yf.forEach(n),e.forEach(n),t};var hn=class{constructor(){this.events={},this.events={}}on(e,t){return this.events[e]||(this.events[e]=[]),this.events[e].push(t),()=>{this.events[e]=this.events[e].filter(n=>n!==t)}}emit(e,t){for(let n of this.events[e]||[])n(t);for(let n of this.events["*"]||[])n(e,t)}};function Js(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}var Xf="NativeGzipValidationError",Qf=31,Zf=139,ep=8,tp=r=>r.length>=2&&r[0]===Qf&&r[1]===Zf;var Wt,rp=()=>{if(Wt)return Wt;Wt=[];for(let r=0;r<256;r++){let e=r;for(let t=0;t<8;t++)e=1&e?3988292384^e>>>1:e>>>1;Wt[r]=e>>>0}return Wt},np=r=>{let e=rp(),t=4294967295;for(let n=0;n<r.length;n++)t=e[(t^r[n])&255]^t>>>8;return(4294967295^t)>>>0},mn=r=>{throw pt(Xf,`Native gzip produced invalid output: ${r}`)},sp=async(r,e)=>{r.size<18&&mn("too-short");let t=new Uint8Array(await r.slice(0,10).arrayBuffer());(!tp(t)||t[2]!==ep)&&mn("invalid-header");let n=new DataView(await r.slice(r.size-8).arrayBuffer());n.getUint32(0,!0)!==np(e)&&mn("invalid-crc");let s=e.length>>>0;n.getUint32(4,!0)!==s&&mn("invalid-size")};async function Ht(r,e=!0,t){try{let n=new TextEncoder().encode(r),s=new globalThis.CompressionStream("gzip"),i=s.writable.getWriter(),o=i.write(n).then(()=>i.close()).catch(async l=>{try{await i.abort(l)}catch{}throw l}),a=new Response(s.readable).blob(),[c]=await Promise.all([a,o]);return await sp(c,n),c}catch(n){if(t?.rethrow)throw n;return e&&console.error("Failed to gzip compress data",n),null}}function rc(r,e=Date.now()){if(typeof r!="string"||!r)return;let t=r.trim(),n=/^\d+\s*,/.test(t)?t.slice(0,t.indexOf(",")).trim():t,s=/^\d+$/.test(n)?Number(n):NaN;if(!Number.isFinite(s)&&/^[+-]?[\d.]+$/.test(n))return;let i=Number.isFinite(s)?1e3*s:Date.parse(n)-e;if(!(!Number.isFinite(i)||i<=0))return Math.min(i,3e5)}var qe=class{record(e){if(e.kind==="too-large")return;if(e.kind!=="retry-later")return void this.reset();if(!e.retryAfterMs)return;let t=this.isOpen(),n=Date.now(),s=Math.min(e.retryAfterMs,3e5);if(!t){this._installedAt=n,this._until=n+s;return}this._until=Math.max(this._until,Math.min(n+s,this._installedAt+3e5))}remainingMs(){let e=Date.now();if(e<this._installedAt-5e3)return this.reset(),0;let t=Math.min(3e5,Math.max(0,this._until-e));return t===0&&this.reset(),t}isOpen(){return this.remainingMs()>0}reset(){this._until=0,this._installedAt=0}constructor(){this._until=0,this._installedAt=0}};var X=class extends Error{constructor(e,t,n,s){super("HTTP error while fetching PostHog: status="+e.status+", reqByteLength="+t),this.response=e,this.reqByteLength=t,this.responseBodyDeadline=n,this.abortController=s,this.name="PostHogFetchHttpError",this._bodyReadTimedOut=!1}get status(){return this.response.status}get retryAfterMs(){try{return rc(this.response.headers?.get("retry-after"))}catch{return}}get bodyReadTimedOut(){return this._bodyReadTimedOut}get text(){if(!this.responseBodyTextPromise)if(Date.now()>=this.responseBodyDeadline){this._bodyReadTimedOut=!0;let e=pt("AbortError","Response body read timed out");this.cancelResponseBody(e),this.responseBodyTextPromise=Promise.reject(e)}else{let e=new Promise((n,s)=>{this.responseBodyTimer=B(()=>{this._bodyReadTimedOut=!0;let i=pt("AbortError","Response body read timed out");s(i),this.cancelResponseBody(i)},this.responseBodyDeadline-Date.now())}),t;try{t=Promise.resolve(this.response.text())}catch(n){t=Promise.reject(n)}this.responseBodyTextPromise=Promise.race([t,e]).finally(()=>clearTimeout(this.responseBodyTimer))}return this.responseBodyTextPromise}get json(){return this.text.then(e=>JSON.parse(e))}cancelResponseBody(e){clearTimeout(this.responseBodyTimer),this.abortController.signal.aborted||this.abortController.abort(e),(async()=>{try{await this.response.body?.cancel()}catch{}})()}},Pe=class extends Error{constructor(e){super("Network error while fetching PostHog",e instanceof Error?{cause:e}:{}),this.error=e,this.name="PostHogFetchNetworkError"}};var ac=(r,e)=>{for(let t of Object.keys(e))(t.startsWith("$feature/")||t==="$active_feature_flags")&&(r[t]=e[t])};async function nc(r){if(r instanceof X){let e="";try{e=await r.text}catch{r.bodyReadTimedOut&&(e="<response body read timed out>")}console.error(`Error while flushing PostHog: message=${r.message}, response body=${e}`,r)}else console.error("Error while flushing PostHog",r);return Promise.resolve()}function ip(r){return typeof r=="object"&&(r instanceof X||cc(r))}function cc(r){return r instanceof Pe}function op(r){if(r instanceof X)return r.status===502||r.status===504;if(!(r instanceof Pe))return!1;let e=r.error;return(e?.code??e?.cause?.code)!=="ECONNREFUSED"}var sc=10485760;function ic(r){try{return typeof r!="string"?r instanceof Uint8Array?r.byteLength:r.size:"u">typeof Buffer?Buffer.byteLength(r,ka):new TextEncoder().encode(r).length}catch{return 0}}function ht(r){return typeof r=="object"&&r instanceof X&&r.status===413}function _n(r){return r instanceof X?r.status===408||r.status===429||r.status>=500:cc(r)}function oc(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}var Xs="default",Gt=class{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new kt([new Dt,new Nt,new Lt,new Ut],Bs())}constructor(e,t={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new rn,this._events=new hn,this._isInitialized=!1;let n=typeof e=="string"?e.trim():"",s=typeof t.host=="string"?t.host.trim():"",i=!n;this._logger=ya("[PostHog]",this.logMsgIfDebug.bind(this)),i&&this._logger.error("You must pass your PostHog project's api key. The client will be disabled."),this.apiKey=n,this.host=Da(s||"https://us.i.posthog.com"),this.flushAt=t.flushAt?Math.max(t.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,t.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,t.maxQueueSize??1e3),this.flushInterval=t.flushInterval??1e4,this.preloadFeatureFlags=t.preloadFeatureFlags??!0,this.defaultOptIn=t.defaultOptIn??!0,this.disableSurveys=t.disableSurveys??!1,this._retryOptions={retryCount:t.fetchRetryCount??3,retryDelay:t.fetchRetryDelay??3e3,retryCheck:_n},this.requestTimeout=t.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=t.featureFlagsRequestTimeoutMs??3e3,this.featureFlagsRequestMaxRetries=t.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=t.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=t.disableGeoip??!0,this.disabled=(t.disabled??!1)||i,this.historicalMigration=t?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=t?.evaluationContexts??t?.evaluationEnvironments,t?.evaluationEnvironments&&!t?.evaluationContexts&&this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version."),this.disableCompression=!Js()||(t?.disableCompression??!1)}logMsgIfDebug(e){this.isDebug&&e()}wrap(e){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized)return e();this._initPromise.then(()=>e())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(G.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(G.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(G.OptedOut,!0)})}on(e,t){return this._events.on(e,t)}debug(e=!0){if(this.removeDebugCallback?.(),e){let t=this.on("*",(n,s)=>this._logger.info(n,s));this.removeDebugCallback=()=>{t(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(e){let t=e.properties||{},n={...t,...this.getCommonEventProperties()};return ac(n,t),e.event==="$feature_flag_called"&&n.$feature_flag_has_experiment===!1&&this.isMinimalFlagCalledEventsEnabled()&&(n=Bt(n)),{distinct_id:e.distinct_id,event:e.event,properties:n}}isMinimalFlagCalledEventsEnabled(){return!1}addPendingPromise(e){return this.promiseQueue.add(e)}identifyStateless(e,t,n){this.wrap(()=>{let s={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};this.enqueue("identify",s,n)})}async identifyStatelessImmediate(e,t,n){let s={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};await this.sendImmediate("identify",s,n)}captureStateless(e,t,n,s){this.wrap(()=>{let i=this.buildPayload({distinct_id:e,event:t,properties:n});this.enqueue("capture",i,s)})}async captureStatelessImmediate(e,t,n,s){let i=this.buildPayload({distinct_id:e,event:t,properties:n});await this.sendImmediate("capture",i,s)}aliasStateless(e,t,n,s){this.wrap(()=>{let i=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...n||{},distinct_id:t,alias:e}});this.enqueue("alias",i,s)})}async aliasStatelessImmediate(e,t,n,s){let i=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...n||{},distinct_id:t,alias:e}});await this.sendImmediate("alias",i,s)}groupIdentifyStateless(e,t,n,s,i,o){this.wrap(()=>{let a=this.buildPayload({distinct_id:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:n||{},...o||{}}});this.enqueue("capture",a,s)})}async groupIdentifyStatelessImmediate(e,t,n,s,i,o){let a=this.buildPayload({distinct_id:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:n||{},...o||{}}});await this.sendImmediate("capture",a,s)}async getRemoteConfig(){await this._initPromise;let e=this.host;e==="https://us.i.posthog.com"?e="https://us-assets.i.posthog.com":e==="https://eu.i.posthog.com"&&(e="https://eu-assets.i.posthog.com");let t=`${e}/array/${this.apiKey}/config`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(t,n,{type:"required",consume:s=>s.json()},{retryCount:0},this.remoteConfigRequestTimeoutMs).catch(s=>{this._logger.error("Remote config could not be loaded",s),this._events.emit("error",s)})}async getFlags(e,t={},n={},s={},i={},o=!1){await this._initPromise;let a=o?"&config=true":"",c=`${this.host}/flags/?v=2${a}`,l={token:this.apiKey,distinct_id:e,groups:t,person_properties:n,group_properties:s,...i};n.$device_id&&(l.$device_id=n.$device_id),this.evaluationContexts&&this.evaluationContexts.length>0&&(l.evaluation_contexts=this.evaluationContexts);let u={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(l)};return this._logger.info("Flags URL",c),this.fetchWithRetry(c,u,{type:"required",consume:d=>d.json()},{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:op},this.featureFlagsRequestTimeoutMs).then(d=>({success:!0,response:Ys(d)})).catch(d=>(this._events.emit("error",d),{success:!1,error:this.categorizeRequestError(d)}))}categorizeRequestError(e){if(e instanceof X)return{type:"api_error",statusCode:e.status};if(e instanceof Pe){let t=e.error;return t instanceof Error&&(t.name==="AbortError"||t.name==="TimeoutError")?{type:"timeout"}:{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(e,t,n={},s={},i={},o){await this._initPromise;let a=await this.getFeatureFlagDetailStateless(e,t,n,s,i,o);if(a===void 0)return{response:void 0,requestId:void 0};let c=jt(a.response);return c===void 0&&(c=!1),{response:c,requestId:a.requestId}}async getFeatureFlagDetailStateless(e,t,n={},s={},i={},o){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(t,n,s,i,o,[e]);return a===void 0?void 0:{response:a.flags[e],requestId:a.requestId,evaluatedAt:a.evaluatedAt}}async getFeatureFlagPayloadStateless(e,t,n={},s={},i={},o){await this._initPromise;let a=await this.getFeatureFlagPayloadsStateless(t,n,s,i,o,[e]);if(!a)return;let c=a[e];return c===void 0?null:c}async getFeatureFlagPayloadsStateless(e,t={},n={},s={},i,o){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(e,t,n,s,i,o)).payloads}async getFeatureFlagsStateless(e,t={},n={},s={},i,o){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(e,t,n,s,i,o)}async getFeatureFlagsAndPayloadsStateless(e,t={},n={},s={},i,o){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(e,t,n,s,i,o);return a?{flags:a.featureFlags,payloads:a.featureFlagPayloads,requestId:a.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(e,t={},n={},s={},i,o){await this._initPromise;let a={geoip_disable:i??this.disableGeoip};o&&(a.flag_keys_to_evaluate=o);let c=await this.getFlags(e,t,n,s,a);if(!c.success)return;let l=c.response;return l.errorsWhileComputingFlags&&console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices"),l.quotaLimited?.includes("feature_flags")?(console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:l?.requestId,quotaLimited:l.quotaLimited}):l}async getSurveysStateless(){if(await this._initPromise,this.disabled)return[];if(this.disableSurveys===!0)return this._logger.info("Loading surveys is disabled."),[];let e=`${this.host}/api/surveys/?token=${this.apiKey}`,t={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},s=(await this.fetchWithRetry(e,t,{type:"required",consume:i=>{if(i.status!==200||!i.json){let o=`Surveys API could not be loaded: ${i.status}`,a=new Error(o);return this._logger.error(a),this._events.emit("error",new Error(o)),Promise.resolve(void 0)}return i.json()}}).catch(i=>{this._logger.error("Surveys API could not be loaded",i),this._events.emit("error",i)}))?.surveys;return s&&this._logger.info("Surveys fetched from API: ",JSON.stringify(s)),s??[]}get props(){return this._props||(this._props=this.getPersistedProperty(G.Props)),this._props||{}}set props(e){this._props=e}async register(e){this.wrap(()=>{this.props={...this.props,...e},this.setPersistedProperty(G.Props,this.props)})}async unregister(e){this.wrap(()=>{delete this.props[e],this.setPersistedProperty(G.Props,this.props)})}processBeforeEnqueue(e){return e}async flushStorage(){}getQueueRouteKey(e){return Xs}persistedQueueKeyForRoute(e){return G.Queue}getActiveQueueRoutes(){return[Xs]}getRouteQueue(e){return this.getPersistedProperty(this.persistedQueueKeyForRoute(e))||[]}enqueue(e,t,n,s){this.wrap(()=>{if(this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let i=this.prepareMessage(t,n);if(i=this.processBeforeEnqueue(i),i===null)return;i=this.normalizeMessage(i);let o=this.persistedQueueKeyForRoute(s??this.getQueueRouteKey(i)),a=this.getPersistedProperty(o)||[];a.length>=this.maxQueueSize&&(a.shift(),this._logger.warn("Queue is full, the oldest event is dropped.")),a.push({message:i}),this.setPersistedProperty(o,a),this._events.emit(e,i),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=B(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(e,t,n,s){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized||await this._initPromise,this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let i=this.prepareMessage(t,n);if(i=this.processBeforeEnqueue(i),i!==null){i=this.normalizeMessage(i);try{await this.sendBatch([i],void 0,s??this.getQueueRouteKey(i))}catch(o){this._events.emit("error",o)}}}normalizeMessage(e){let{type:t,library:n,library_version:s,...i}=e,o=oc(i.properties)?i.properties:void 0;return n!==void 0&&o?.$lib===void 0&&(o={...o||{},$lib:n}),s!==void 0&&o?.$lib_version===void 0&&(o={...o||{},$lib_version:s}),o&&(i.properties=o),i.uuid=Ve(i.uuid,j),i}normalizeTimestampForWire(e){let t=e instanceof Date?e:typeof e=="string"?new Date(e):null;if(!t||Number.isNaN(t.getTime()))return e;let n=t.toISOString(),s=typeof e=="string"?e.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1]:void 0;return s&&s.length>3?n.replace(/\.\d{3}Z$/,`.${s}Z`):n}prepareMessage(e,t){let n={...e,timestamp:t?.timestamp?t?.timestamp:Ns(),uuid:Ve(t?.uuid,j)};return(t?.disableGeoip??this.disableGeoip)&&(oc(n.properties)||(n.properties={}),n.properties.$geoip_disable=!0),n.distinctId&&(n.distinct_id=n.distinctId,delete n.distinctId),n}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.pendingFlushPromise||this.flushAutomatic().catch(async e=>{await nc(e)})}flushAutomatic(){return this.flush()}async waitForPendingPromises(e,t=[]){let n=t.filter(i=>!!i),s=0;for(;;){let i=this.promiseQueue.getPromises([...n,...this.flushPromises],e);if(i.length===0)return;s>0&&this._logger.debug(`flush() re-checking ${i.length} pending promise(s) before flushing`),await Promise.all(i.map(o=>o.catch(()=>{}))),s++}}flushWithPendingPromises(){return this.flushInternal(!0)}flush(){return this.flushInternal(!1)}flushInternal(e){if(this.disabled)return Promise.resolve();if(!e&&this.pendingFlushPromise)return this.pendingFlushPromise;let t=this.flushPromise,n=this.promiseQueue.maxId,s=Promise.resolve().then(()=>{if(e)return this.waitForPendingPromises(n,[t,s])}).then(()=>Ot([t])).then(()=>(this.pendingFlushPromise===s&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=s,this.flushPromise=s,this.flushPromises.add(s),this.addPendingPromise(s),Ot([s]).then(()=>{this.flushPromises.delete(s),this.pendingFlushPromise===s&&(this.pendingFlushPromise=null),this.flushPromise===s&&(this.flushPromise=null)}),s}getCustomHeaders(){let e=this.getCustomUserAgent(),t={};return e&&e!==""&&(t["User-Agent"]=e),t}compressPayload(e){return Ht(e,this.isDebug)}getBatchEndpointPath(e){return"/batch/"}async sendBatch(e,t,n=Xs){let s={api_key:this.apiKey,batch:e.map(l=>{if(!l)return l;let u=this.normalizeTimestampForWire(l.timestamp);return u===l.timestamp?l:{...l,timestamp:u}}),sent_at:Ns()};this.historicalMigration&&(s.historical_migration=!0);let i=De(s),o=`${this.host}${this.getBatchEndpointPath(n)}`,a=this.disableCompression?null:await this.compressPayload(i),c={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...a!==null&&{"Content-Encoding":"gzip"}},body:a||i};await this.fetchWithRetry(o,c,{type:"successful-write"},t)}async _flush(){this.clearFlushTimer(),await this._initPromise;let e=this.getActiveQueueRoutes();if(!e.some(s=>this.getRouteQueue(s).length>0))return;let t=[],n;for(let s of e)try{await this._flushRoute(s,t)}catch(i){n===void 0&&(n=i)}if(n!==void 0)throw n;this._events.emit("flush",t)}async _flushRoute(e,t){let n=this.persistedQueueKeyForRoute(e),s=this.getPersistedProperty(n)||[];if(!s.length)return;let i=s.length,o=0;for(;s.length>0&&o<i;){let a=s.slice(0,this.maxBatchSize),c=a.map(d=>d.message===void 0?d.message:this.normalizeMessage(d.message)),l=async()=>{let d=this.getPersistedProperty(n)||[],g=[...a],p=d.filter(h=>{let m=h.message?.uuid,E=g.findIndex(_=>_===h||typeof m=="string"&&m.length>0&&_.message?.uuid===m);return E===-1?!0:(g.splice(E,1),!1)});this.setPersistedProperty(n,p),s=p,this._dequeuedMessagesCount+=a.length,await this.flushStorage()},u={retryCheck:d=>ht(d)?!1:_n(d)};try{await this.sendBatch(c,u,e)}catch(d){if(ht(d)&&c.length>1){this.maxBatchSize=Math.max(1,Math.floor(c.length/2)),this._logger.warn(`Received 413 when sending batch of size ${c.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw d instanceof Pe||await l(),this._events.emit("error",d),d}await l(),t.push(...c),o+=c.length}}async _sendOtlpBatch({path:e,auth:t,payload:n}){if(this.disabled)return{kind:"fatal",error:new Error("The client is disabled")};let s;try{s=JSON.stringify(n)}catch(u){return this.logMsgIfDebug(()=>console.warn(`[PostHog] Could not serialize a ${e} batch; reporting it as too large`,u)),{kind:"too-large",measuredLocally:!0}}let i=ic(s);if(i>sc)return this.logMsgIfDebug(()=>console.warn(`[PostHog] Not sending a ${e} batch of ${i} bytes: the endpoint accepts at most ${sc}`)),{kind:"too-large",measuredLocally:!0};let o=t==="bearer"?`${this.host}/i/v1/${e}`:`${this.host}/i/v1/${e}?token=${encodeURIComponent(this.apiKey)}`,a=this.disableCompression?null:await this.compressPayload(s),c=a||s,l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...t==="bearer"&&{Authorization:`Bearer ${this.apiKey}`},...a!==null&&{"Content-Encoding":"gzip"}},body:c};try{return await this.fetchWithRetry(o,l,{type:"successful-write"},{retryCheck:u=>ht(u)||u instanceof X&&u.retryAfterMs!==void 0?!1:_n(u)}),{kind:"ok"}}catch(u){if(ht(u))return{kind:"too-large"};if(_n(u)){let d=u instanceof X?u.retryAfterMs:void 0;return{kind:"retry-later",error:u,...d!==void 0&&{retryAfterMs:d}}}return{kind:"fatal",error:u}}}async _sendLogsBatch(e){return this._sendOtlpBatch({path:"logs",auth:"query-token",payload:e})}async _sendMetricsBatch(e){return this._sendOtlpBatch({path:"metrics",auth:"query-token",payload:e})}async _sendTracesBatch(e){return this._sendOtlpBatch({path:"traces",auth:"bearer",payload:e})}async fetchWithRetry(e,t,n,s,i){let o=t.body?t.body:"",a=ic(o),c={...this._retryOptions,...s},l=0;return await La(async()=>{l++;let u=new AbortController,d=i??this.requestTimeout,g=Date.now()+d,p,h=new Promise((P,R)=>{p=B(()=>{let O=pt("AbortError",`Request timed out after ${d}ms`);R(O),u.abort(O)},d)}),m,E=!1,_,b=()=>_??=(async()=>{try{await m?.body?.cancel()}catch{}})();try{let P;try{P=this.fetch(e,{signal:u.signal,...t})}catch(O){throw new Pe(O)}P.then(O=>{u.signal.aborted&&!E&&Promise.resolve(O.body?.cancel()).catch(()=>{})}).catch(()=>{});try{m=await Promise.race([P,h]),E=!0}catch(O){throw new Pe(O)}if(!(t.mode==="no-cors")&&(m.status<200||m.status>=400))throw new X(m,a,g,u);if(n.type==="successful-write"){try{await Promise.race([b(),h])}catch{}return}try{return await Promise.race([n.consume(m),h])}catch(O){throw u.signal.aborted?new Pe(O):O}}finally{clearTimeout(p),u.signal.aborted&&m&&b()}},{...c,retryCheck:u=>{let d=c.retryCheck(u);return d&&l<=c.retryCount&&u instanceof X&&u.cancelResponseBody(),d}})}async _shutdown(e=3e4){await this._initPromise;let t=!1;return this.clearFlushTimer(),this.disabled?void 0:Le((async()=>{try{for(await this.promiseQueue.join();this.getActiveQueueRoutes().some(o=>this.getRouteQueue(o).length>0);){let i=this._dequeuedMessagesCount;if(await this.flush(),t)break;if(this._dequeuedMessagesCount===i){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(s){if(!ip(s))throw s;await nc(s)}})(),e,()=>{this._logger.critical("Timeout while shutting down PostHog. Some events may not have been sent.",{shutdownTimeoutMs:e}),t=!0})}async shutdown(e=3e4){return this.shutdownPromise?this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup"):this.shutdownPromise=this._shutdown(e).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}};var dp=["is_not","is_set"],fp=1152921504606847e3,S=class r extends Error{constructor(e){super(e),this.name=this.constructor.name,Object.setPrototypeOf(this,r.prototype)}};function dc(r){if(typeof r=="boolean")return!0;if(typeof r=="string"){let e=r.toLowerCase();return e==="true"||e==="false"}if(!Array.isArray(r))return!1;for(let e=0;e<r.length;e++)if(!dc(e in r?r[e]:null))return!1;return!0}function Qs(r){if(typeof r=="boolean")return r;if(typeof r=="string")return r.toLowerCase()==="true";if(!Array.isArray(r))return!1;for(let e=0;e<r.length;e++)if(!Qs(e in r?r[e]:null))return!1;return!0}function Kt(r){for(let e=0;e<r.length;e++){let t=r.charCodeAt(e);if(t>=55296&&t<=56319){let n=r.charCodeAt(e+1);if(e+1>=r.length||n<56320||n>57343)throw new S("Cannot stringify an unpaired surrogate like the flags service");e++}else if(t>=56320&&t<=57343)throw new S("Cannot stringify an unpaired surrogate like the flags service")}}function Zs(r,e=new Set){if(!(r===null||typeof r=="boolean")){if(typeof r=="string")return void Kt(r);if(typeof r=="number"){if(!Number.isFinite(r))throw new S(`Cannot represent non-finite number ${r} like the flags service`);return}if(Array.isArray(r)){if(e.has(r))throw new S("Cannot represent a circular array during local evaluation");e.add(r);try{for(let t=0;t<r.length;t++)t in r&&Zs(r[t],e)}finally{e.delete(r)}return}if(typeof r=="object"){let t=Object.getPrototypeOf(r);if(t!==Object.prototype&&t!==null)throw new S("Cannot represent a non-JSON object like the flags service");if(e.has(r))throw new S("Cannot represent a circular object during local evaluation");e.add(r);try{for(let n of Object.keys(r))Kt(n),Zs(r[n],e)}finally{e.delete(r)}return}throw new S(`Cannot represent ${typeof r} like the flags service`)}}function pp(r,e){let t=0,n=0;for(;t<r.length&&n<e.length;){let s=r.charCodeAt(t),i=e.charCodeAt(n),o=s>=55296&&s<=56319,a=i>=55296&&i<=56319,c=o?r.charCodeAt(t+1):0,l=a?e.charCodeAt(n+1):0,u=o?(s-55296)*1024+c-56320+65536:s,d=a?(i-55296)*1024+l-56320+65536:i;if(u!==d)return u-d;t+=o?2:1,n+=a?2:1}return r.length-e.length}function ei(r,e=new Set){if(r===null)return"null";if(typeof r=="string")return Kt(r),JSON.stringify(r);if(typeof r=="boolean")return r?"true":"false";if(typeof r=="number"){if(!Number.isFinite(r))throw new S(`Cannot stringify non-finite number ${r} like the flags service`);if(Number.isInteger(r))throw new S(`Cannot distinguish integer ${r} from an integral JSON float during local evaluation`);return String(r)}if(Array.isArray(r)){if(e.has(r))throw new S("Cannot stringify a circular array during local evaluation");e.add(r);try{let t=[];for(let n=0;n<r.length;n++)t.push(n in r?ei(r[n],e):"null");return`[${t.join(",")}]`}finally{e.delete(r)}}if(typeof r=="object"){let t=Object.getPrototypeOf(r);if(t!==Object.prototype&&t!==null)throw new S("Cannot stringify a non-JSON object like the flags service");if(e.has(r))throw new S("Cannot stringify a circular object during local evaluation");e.add(r);try{let n=Object.keys(r);return n.forEach(Kt),`{${n.sort(pp).map(s=>`${JSON.stringify(s)}:${ei(r[s],e)}`).join(",")}}`}finally{e.delete(r)}}throw new S(`Cannot stringify ${typeof r} like the flags service`)}function En(r){return typeof r=="string"?(Kt(r),r):ei(r)}function lc(r){try{return new RegExp(r),!0}catch{return!1}}function Q(r){return String(r).replace(/[A-Z]/g,e=>e.toLowerCase())}function fc(r,e,t){if(!/^\d+$/.test(r)||t==="strict"&&r.length>1&&r[0]==="0")throw new S(`Invalid semver: ${e}`);return parseInt(r,10)}function F(r,e="strict"){let n=String(r).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!n||n.startsWith("."))throw new S(`Invalid semver: ${r}`);let s=n.split("."),i=o=>o===void 0||o===""?0:fc(o,r,e);return[i(s[0]),i(s[1]),i(s[2])]}function Z(r,e){for(let t=0;t<3;t++){if(r[t]<e[t])return-1;if(r[t]>e[t])return 1}return 0}function gp(r,e){let t=F(r,e);return{lower:[t[0],t[1],t[2]],upper:[t[0],t[1]+1,0]}}function hp(r,e){let[t,n,s]=F(r,e),i=[t,n,s],o;return o=t>0?[t+1,0,0]:n>0?[0,n+1,0]:[0,0,s+1],{lower:i,upper:o}}function mp(r,e){let n=String(r).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!n)throw new S(`Invalid wildcard semver: ${r}`);let s=n.split("."),i=c=>{if(e==="legacy-permissive"){let l=parseInt(c,10);if(!isNaN(l))return l}else try{return fc(c,r,e)}catch{}throw new S(`Invalid wildcard semver: ${r}`)},o=i(s[0]);if(s.length===1)return{lower:[o,0,0],upper:[o+1,0,0]};let a=i(s[1]);return{lower:[o,a,0],upper:[o,a+1,0]}}function uc(r){if(r instanceof Date)return r;if(typeof r=="string"||typeof r=="number"){let e=new Date(r);if(!isNaN(e.valueOf()))return e;throw new S(`${r} is in an invalid date format`)}throw new S(`The date provided ${r} must be a string, number, or date object`)}function ti(r){let e=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,t=r.match(e),n=new Date(new Date().toISOString());if(!t||!t.groups)return null;let s=parseInt(t.groups.number);if(s>=1e4)return null;let i=t.groups.interval;if(i==="h")n.setUTCHours(n.getUTCHours()-s);else if(i==="d")n.setUTCDate(n.getUTCDate()-s);else if(i==="w")n.setUTCDate(n.getUTCDate()-7*s);else if(i==="m")n.setUTCMonth(n.getUTCMonth()-s);else{if(i!=="y")return null;n.setUTCFullYear(n.getUTCFullYear()-s)}return n}function ri(r,e,t={}){let n=r.key,s=r.value,i=r.operator||"exact",o=t.semverParsingPolicy??"strict";if(Object.prototype.hasOwnProperty.call(e,n)){if(i==="is_not_set")return!1;if(i==="is_set")return!0}else throw new S(`Property ${n} not found in propertyValues`);let c=e[n];if(c===void 0)return t.warnFunction?.(`Property ${n} cannot have a value of undefined with the ${i} operator`),i==="is_not";if(c===null&&!dp.includes(i)&&i!=="exact"&&i!=="is_not")return t.warnFunction?.(`Property ${n} cannot have a value of null with the ${i} operator`),!1;let l=(d,g)=>{if(dc(d))return Zs(g),Qs(d)===Qs(g);if(Array.isArray(d)){let p=En(g).toLowerCase();return d.some(h=>En(h).toLowerCase()===p)}return En(d).toLowerCase()===En(g).toLowerCase()},u=(d,g,p)=>{if(p==="gt")return d>g;if(p==="gte")return d>=g;if(p==="lt")return d<g;if(p==="lte")return d<=g;throw new Error(`Invalid operator: ${p}`)};switch(i){case"exact":return l(s,c);case"is_not":return!l(s,c);case"is_set":return!0;case"icontains":return Q(c).includes(Q(s));case"not_icontains":return!Q(c).includes(Q(s));case"starts_with":return Q(c).startsWith(Q(s));case"not_starts_with":return!Q(c).startsWith(Q(s));case"ends_with":return Q(c).endsWith(Q(s));case"not_ends_with":return!Q(c).endsWith(Q(s));case"regex":return lc(String(s))&&String(c).match(String(s))!==null;case"not_regex":return lc(String(s))&&String(c).match(String(s))===null;case"gt":case"gte":case"lt":case"lte":{let d=typeof s=="number"?s:parseFloat(String(s)),g=typeof c=="number"?c:c!=null?parseFloat(String(c)):NaN;return Number.isFinite(d)&&Number.isFinite(g)?u(g,d,i):u(String(c),String(s),i)}case"is_date_after":case"is_date_before":{if(typeof s=="boolean")throw new S("Date operations cannot be performed on boolean values");let d=ti(String(s));d==null&&(d=uc(s));let g=uc(c);return i==="is_date_before"?g<d:g>d}case"semver_eq":return Z(F(String(c),o),F(String(s),o))===0;case"semver_neq":return Z(F(String(c),o),F(String(s),o))!==0;case"semver_gt":return Z(F(String(c),o),F(String(s),o))>0;case"semver_gte":return Z(F(String(c),o),F(String(s),o))>=0;case"semver_lt":return Z(F(String(c),o),F(String(s),o))<0;case"semver_lte":return Z(F(String(c),o),F(String(s),o))<=0;case"semver_tilde":{let d=F(String(c),o),{lower:g,upper:p}=gp(String(s),o);return Z(d,g)>=0&&Z(d,p)<0}case"semver_caret":{let d=F(String(c),o),{lower:g,upper:p}=hp(String(s),o);return Z(d,g)>=0&&Z(d,p)<0}case"semver_wildcard":{let d=F(String(c),o),{lower:g,upper:p}=mp(String(s),o);return Z(d,g)>=0&&Z(d,p)<0}default:throw new S(`Unknown operator: ${i}`)}}async function pc(r){let e=globalThis.crypto?.subtle;if(!e)throw new Error("SubtleCrypto API not available");let t=await e.digest("SHA-1",new TextEncoder().encode(r));return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}async function yn(r,e,t=""){let n=await pc(`${r}.${e}${t}`);return parseInt(n.slice(0,15),16)/fp}function Sn(r){let e=[],t=0;for(let n of r){let s=t+n.rollout_percentage/100;e.push({valueMin:t,valueMax:s,key:n.key}),t=s}return e}async function ni(r,e,t){let n=await yn(r,e,"variant");return Sn(t).find(s=>n>=s.valueMin&&n<s.valueMax)?.key}function si(r,e){if(e===!1||e==null||!r)return null;let t=typeof e=="boolean"?e.toString():e,n=r[t]||null;return n==null?null:gt(n)}var gc=9223372036854776e3,_p="9223372036854775808",Ep=Object.prototype.propertyIsEnumerable;function yp(){return{ancestors:new WeakSet,remainingNodes:1e4}}function ue(r,e){try{return hc(r,e,yp(),0)}catch{return[]}}function Sp(r,e){let t=r.toString(),n=BigInt(_p);return r>=n||r<-n?(e?.debug(`Attribute ${t} is outside the int64 range; encoding it as a string`),{stringValue:t}):{intValue:t}}function ai(r,e,t,n){if(t.remainingNodes<=0)return{stringValue:ln};if(t.remainingNodes--,da(r))return{boolValue:r};if(typeof r=="bigint")return Sp(r,e);if(typeof r=="number"){if(!Number.isFinite(r))return{stringValue:String(r)};if(Number.isInteger(r)){if(Number.isSafeInteger(r))return{intValue:String(r)};if("u"<typeof BigInt)return{stringValue:String(r)};let s=BigInt(r).toString();return r>=gc||r<-gc?(e?.debug(`Attribute ${s} is outside the int64 range; encoding it as a string`),{stringValue:s}):{intValue:s}}return{doubleValue:r}}if(typeof r=="string")return{stringValue:ce(r)};if(typeof r=="function")return{stringValue:Oa};if(typeof r=="symbol")return{stringValue:String(r)};if(typeof r=="object"&&r!==null){if(t.ancestors.has(r))return{stringValue:cn};if(n>=20)return{stringValue:ln};if(r instanceof Date){let s=r.getTime(),i=Number.isFinite(s)?r.toISOString():String(r);return{stringValue:typeof i=="string"?ce(i):String(i)}}t.ancestors.add(r);try{try{let s=r.toJSON;if(typeof s=="function")return ai(s.call(r),e,t,n+1)}catch{}return Y(r)?{arrayValue:{values:bp(r,e,t,n+1)}}:{kvlistValue:{values:hc(r,e,t,n+1)}}}finally{t.ancestors.delete(r)}}return{stringValue:ce(String(r))}}function bp(r,e,t,n){let s=[],i=Math.min(r.length,1e3),o=0;for(;o<i&&t.remainingNodes>0;o++)try{let a=o in r?r[o]:void 0;if(re(a))continue;s.push(ai(a,e,t,n))}catch{s.push({stringValue:J})}return r.length>o&&s.push({stringValue:ln}),s}function hc(r,e,t,n){let s=[];for(let i in r)if(Ep.call(r,i)){if(!i){e?.debug("Dropping an attribute with an empty key");continue}if(s.length>=1e3||t.remainingNodes<=0){e?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{let o=r[i];if(Cs(o)||Ae(o))continue;s.push({key:ce(i),value:ai(o,e,t,n)})}catch{s.push({key:ce(i),value:{stringValue:J}})}}return s}function qt(r,e,t){return{...Te({},r.resourceAttributes),"service.name":r.serviceName||"unknown_service",...r.environment&&{"deployment.environment":r.environment},...r.serviceVersion&&{"service.version":r.serviceVersion},"telemetry.sdk.name":e,"telemetry.sdk.version":t}}var wp=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function zt(r,e){let t=Te({},r),n={};for(let s of wp)Object.prototype.hasOwnProperty.call(t,s)&&(n[s]=t[s],delete t[s]);return[...ue(t,e),...ue(n,e)]}var mc={darwin:"macOS",win32:"Windows",cygwin:"Windows",linux:"Linux",android:"Android",freebsd:"FreeBSD",openbsd:"OpenBSD",netbsd:"NetBSD",sunos:"SunOS",aix:"AIX",haiku:"Haiku","Mac OS X":"macOS"};function vp(r){if(r)return Object.prototype.hasOwnProperty.call(mc,r)?mc[r]:r}function ci(r,e){let t=vp(r);return{...t?{"os.name":t}:{},...e?{"os.version":e}:{}}}var Ap={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:{text:"INFO",number:9},warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}},ow=Ap.info;var ze=class{constructor(e){this._onFire=e,this._firesAt=0}get pending(){return!!this._timer}arm(e){this.clear(),this._firesAt=Date.now()+e,this._timer=B(()=>{this._timer=void 0,this._onFire()},e)}armNoEarlierThan(e){this._timer&&Date.now()+e<=this._firesAt||this.arm(e)}clear(){this._timer&&(clearTimeout(this._timer),this._timer=void 0)}};function Yt(){return 1-.25+Math.random()*.25*2}var ee=1;function Jt(r,e,t,n){let s=Math.min(Math.max(0,e-1),6),i=r*2**s,o=n===void 0?i:Math.min(i,Math.max(n,r));return Math.round(o*t)}var Xt=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function li(r){return String(r)+"000000"}function ui(r,e,t,n){let s="";return n&&(s=Object.keys(n).sort().map(o=>`${JSON.stringify(o)}:${JSON.stringify(n[o])}`).join(",")),`${r}\0${e}\0${t??""}\0${s}`}function _c(r,e){for(let t=0;t<e.length;t++)if(r<=e[t])return t;return e.length}function di(r,e,t){return qt(r,e,t)}function fi(r,e,t,n){return{resourceMetrics:[{resource:{attributes:zt(e)},scopeMetrics:[{scope:{name:t,version:n},metrics:r}]}]}}function wn(r){let e=r?.resourceAttributes;return{serviceName:e?.["service.name"]??r?.serviceName,serviceVersion:e?.["service.version"]??r?.serviceVersion,environment:e?.["deployment.environment"]??r?.environment,resourceAttributes:e,beforeSend:r?.beforeSend,flushIntervalMs:r?.flushIntervalMs??1e4,maxSeriesPerFlush:r?.maxSeriesPerFlush??1e3}}var Ec=1,Qt=class{constructor(e,t,n){this._instance=e,this._config=t,this._logger=n,this._series=new Map,this._flushTimer=new ze(()=>this.flush().catch(s=>{this._logger.error("Metrics flush failed:",s)})),this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._retryAfter=new qe,this._consecutiveFlushFailures=0,this._flushJitter=ee,this._generation=0}count(e,t=1,n){this._capture({name:e,type:"count",value:t,unit:n?.unit,attributes:n?.attributes})}gauge(e,t,n){this._capture({name:e,type:"gauge",value:t,unit:n?.unit,attributes:n?.attributes})}histogram(e,t,n){this._capture({name:e,type:"histogram",value:t,unit:n?.unit,attributes:n?.attributes})}flush(){let e=this._flushPromise,n=(async()=>{e&&await e.catch(()=>{}),await this._doFlush()})().finally(()=>{this._flushPromise===n&&(this._flushPromise=null)});return this._flushPromise=n,n}drainWindow(){if(this._series.size===0)return null;let e=this._series;return this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._buildPayload(e)}reset(){this._generation++,this._retryAfter.reset(),this._consecutiveFlushFailures=0,this._flushJitter=ee,this._flushTimer.clear(),this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set}_capture(e){if(this._instance.isDisabled||this._instance.optedOut)return;let t=this._runBeforeSend(e);if(t===null)return;if(!t.name||typeof t.name!="string")return void this._logger.warn("Dropping metric with empty name");if(typeof t.value!="number"||!Number.isFinite(t.value))return void this._logger.warn(`Dropping metric '${t.name}': value must be a finite number`);if(t.type==="count"&&t.value<0)return void this._logger.warn(`Dropping count '${t.name}': counters are monotonic, value must be >= 0`);let n,s;try{n=t.attributes?{...t.attributes}:void 0,s=ui(t.type,t.name,t.unit,n)}catch(a){this._logger.warn(`Dropping metric '${t.name}': attributes could not be serialized`,a);return}let i=this._series.get(s);if(!i){if(!this._admitNewSeries())return;i={name:t.name,type:t.type,unit:t.unit,attributes:n,windowStartMs:Date.now()},this._series.set(s,i)}let o=this._typeByName.get(t.name);o===void 0?this._typeByName.set(t.name,t.type):o!==t.type&&!this._typeCollisionWarned.has(t.name)&&(this._typeCollisionWarned.add(t.name),this._logger.warn(`Metric name '${t.name}' is already used as a ${o}; recording it as a ${t.type} too will blend both series in charts. Use a distinct name.`)),this._fold(i,t.value),this._armFlushTimer()}_admitNewSeries(){return this._series.size<this._config.maxSeriesPerFlush?!0:(this._seriesCapWarned||(this._seriesCapWarned=!0,this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`)),!1)}_fold(e,t){switch(e.type){case"count":e.total=(e.total??0)+t;break;case"gauge":e.last=t;break;case"histogram":{e.hist||(e.hist={count:0,sum:0,min:t,max:t,bucketCounts:new Array(Xt.length+1).fill(0)});let n=e.hist;n.count+=1,n.sum+=t,n.min=Math.min(n.min,t),n.max=Math.max(n.max,t),n.bucketCounts[_c(t,Xt)]+=1;break}}}_runBeforeSend(e){let t=this._config.beforeSend;if(!t)return e;let n=Y(t)?t:[t],s=e;for(let i of n)try{let o=i(s);if(!o)return this._logger.info("Metric was rejected in beforeSend function"),null;s=o}catch(o){return this._logger.error("Error in beforeSend function for metric:",o),null}return s}_armFlushTimer(){this._flushTimer.pending||this._flushTimer.arm(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(Jt(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}async _doFlush(){if(this._flushTimer.clear(),this._series.size===0)return;let e=this._series;this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set;let t=this._generation,n=await this._instance._sendMetricsBatch(this._buildPayload(e));if(t===this._generation)switch(this._retryAfter.record(n),n.kind==="retry-later"?(this._consecutiveFlushFailures++,this._flushJitter=Yt()):(this._consecutiveFlushFailures=0,this._flushJitter=ee),this._flushTimer.pending&&this._flushTimer.arm(this._nextFlushDelay()),n.kind){case"ok":return;case"retry-later":this._mergeWindowBack(e),this._flushTimer.armNoEarlierThan(this._nextFlushDelay());return;case"too-large":this._logger.warn("Metrics batch exceeded the server size limit and was dropped");return;case"fatal":this._logger.error("Failed to send metrics batch:",n.error);return}}_buildPayload(e){return fi(this._buildMetrics(e),di(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._instance.getLibraryId(),this._instance.getLibraryVersion())}_buildMetrics(e){let t=li(Date.now()),n=new Map;for(let s of e.values()){let i=ui(s.type,s.name,s.unit,void 0),o=n.get(i);o||(o={name:s.name,...s.unit&&{unit:s.unit}},s.type==="count"?o.sum={aggregationTemporality:Ec,isMonotonic:!0,dataPoints:[]}:s.type==="gauge"?o.gauge={dataPoints:[]}:o.histogram={aggregationTemporality:Ec,dataPoints:[]},n.set(i,o));let a=ue(s.attributes??{},this._logger),c=li(s.windowStartMs);if(s.type==="count"){let l={attributes:a,startTimeUnixNano:c,timeUnixNano:t,asDouble:s.total??0};o.sum.dataPoints.push(l)}else if(s.type==="gauge"){let l={attributes:a,timeUnixNano:t,asDouble:s.last??0};o.gauge.dataPoints.push(l)}else if(s.hist){let l={attributes:a,startTimeUnixNano:c,timeUnixNano:t,count:s.hist.count,sum:s.hist.sum,min:s.hist.min,max:s.hist.max,bucketCounts:s.hist.bucketCounts,explicitBounds:Xt};o.histogram.dataPoints.push(l)}}return Array.from(n.values())}_mergeWindowBack(e){for(let[t,n]of e){let s=this._series.get(t);if(!s){this._admitNewSeries()&&this._series.set(t,n);continue}switch(s.windowStartMs=Math.min(s.windowStartMs,n.windowStartMs),s.type){case"count":s.total=(s.total??0)+(n.total??0);break;case"gauge":break;case"histogram":if(n.hist)if(s.hist){s.hist.count+=n.hist.count,s.hist.sum+=n.hist.sum,s.hist.min=Math.min(s.hist.min,n.hist.min),s.hist.max=Math.max(s.hist.max,n.hist.max);for(let i=0;i<s.hist.bucketCounts.length;i++)s.hist.bucketCounts[i]+=n.hist.bucketCounts[i]}else s.hist=n.hist;break}}}};var Rp="0".repeat(32),Cp="0".repeat(16),Mp=/^[0-9a-f]+$/;function xp(r){let e=new Uint8Array(r),t=globalThis.crypto;if(t&&typeof t.getRandomValues=="function")try{return t.getRandomValues(e),e}catch{}for(let n=0;n<r;n++)e[n]=Math.floor(256*Math.random());return e}function Fp(r){let e="";for(let t=0;t<r.length;t++)e+=r[t].toString(16).padStart(2,"0");return e}function yc(r){let e=Fp(xp(r));return/[^0]/.test(e)?e:e.slice(0,-1)+"1"}function Sc(){return yc(16)}function bc(){return yc(8)}function wc(r,e,t){return typeof r=="string"&&r.length===e&&r!==t&&Mp.test(r)}function vc(r){return wc(r,32,Rp)}function Ac(r){return wc(r,16,Cp)}var Op=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;function Tc(r){let e=Pc(r);return e&&{traceId:e.traceId,spanId:e.spanId,flags:kp(e.flags)}}function kp(r){return 1&parseInt(r,16)?An:Dp}function Pc(r){if(typeof r!="string")return;let e=Op.exec(r.trim());if(!e)return;let[,t,n,s,i,o]=e;if(t!=="ff"&&!(t==="00"&&o)&&!(!vc(n)||!Ac(s)))return{version:t,traceId:n,spanId:s,flags:i}}function Ic(r){return Pc(r)&&r.trim()}function vn(r){return Array.isArray(r)&&r.length===1?r[0]:r}var An="01",Dp="00";function Rc(r,e,t=An){return`00-${r}-${e}-${t}`}var Lp=32,pi=512;function Tn(r){if(typeof r!="string")return;let e=r.trim();if(!e||/[^\x20-\x7e\t]/.test(e))return;let t=e.split(",");if(!(t.length>Lp)){for(let n of t)if(n.trim()&&!n.includes("="))return;return e.length<=pi?e:Up(t)}}var Np=128;function Up(r){let e=[...r],t=()=>e.reduce((n,s)=>n+s.length,0)+e.length-1;for(let n=e.length-1;n>=0&&t()>pi;n--)e[n].length>Np&&e.splice(n,1);for(;e.length&&t()>pi;)e.pop();return e.length?e.join(","):void 0}var Cc="unknown";function Ye(r,e,t,n){return typeof r=="string"&&r.trim()?r.length>t?r.slice(0,t):r:(n?.debug(`${e} must be a non-empty string; using "${Cc}"`),Cc)}function mt(r){if(r==null)return;let e=r;if(r instanceof Date)try{e=r.getTime()}catch{return}if(!(typeof e!="number"||!Number.isFinite(e))&&!(e<0||e>9223372036854))return e}function Mc(r,e,t){let n=mt(r);return n===void 0?(r!==void 0&&t?.debug("Span startTime is out of range or not a valid time; using the current time"),e):(e-n>864e5?t?.debug("Span startTime is more than 24 hours in the past; the server will clamp it to receive time and keep the original in $originalTimestamp"):n>e&&t?.debug("Span startTime is in the future; the span may export with a zero duration"),n)}function Pn(r,e){return r<e?e:r}function Zt(r,e,t,n){let s=mt(r);return s===void 0?(r!==void 0&&n?.debug(`Span ${t} is out of range or not a valid time; using the derived time`),e):s}function Rn(){let r=globalThis.performance;return typeof r?.now=="function"?r.now():void 0}var _t=class{constructor(e,t,n){this._onEnd=t,this._logger=n,this._events=[],this._ended=!1,this._userAttributeCount=0,this._userEventCount=0,this._droppedAttributes=0,this._droppedEvents=0,this._traceId=e.traceId,this._spanId=e.spanId,this._parentSpanId=e.parentSpanId,this._traceState=e.traceState,this._traceFlags=e.traceFlags??An,this._parentIsRemote=e.parentIsRemote??!1,this._name=e.name,this._kind=e.kind,this._autoKeys=new Set(e.autoAttributeKeys),this._maxAttributes=e.maxAttributes,this._maxEvents=e.maxEvents,this._maxAttributesPerEvent=e.maxAttributesPerEvent,this._maxAttributeValueLength=e.maxAttributeValueLength,this._attributes=Object.create(null);for(let s of Object.keys(e.attributes))this._writeAttribute(s,e.attributes[s]);this._startMono=e.backdated?void 0:Rn(),this._startTime=e.clockAnchor&&this._startMono!==void 0?e.clockAnchor.wall+(this._startMono-e.clockAnchor.mono):e.startTime,this._startMono!==void 0&&(this._clockAnchor=e.clockAnchor??{wall:this._startTime,mono:this._startMono})}_now(){if(this._startMono!==void 0){let e=Rn();if(e!==void 0)return this._startTime+Math.max(0,e-this._startMono)}return Date.now()}_mutable(e){return this._ended?(this._logger?.debug(`Ignoring ${e} on a span that has already ended`),!1):!0}_writeAttribute(e,t){if(re(t)){e in this._attributes&&!this._autoKeys.has(e)&&this._userAttributeCount--,delete this._attributes[e];return}if(!this._autoKeys.has(e)&&!(e in this._attributes)){if(this._userAttributeCount>=this._maxAttributes)return void this._droppedAttributes++;this._userAttributeCount++}this._attributes[e]=Mn(t,this._maxAttributeValueLength)}setAttribute(e,t){return this._mutable("setAttribute")&&this._writeAttribute(e,t),this}setAttributes(e){if(this._mutable("setAttributes")){let t=Te({},e);for(let n of Object.keys(t))this._writeAttribute(n,t[n])}return this}addEvent(e,t,n){if(this._mutable("addEvent")){if(this._userEventCount>=this._maxEvents)return this._droppedEvents++,this;this._userEventCount++;let s=t&&kc(t,this._maxAttributesPerEvent,this._maxAttributeValueLength);this._events.push({name:Ye(e,"Span event name",this._maxAttributeValueLength,this._logger),timestamp:Zt(n,this._now(),"event timestamp",this._logger),...s&&{attributes:s.attributes,...s.dropped&&{droppedAttributesCount:s.dropped}}})}return this}setStatus(e,t){if(this._mutable("setStatus")){if(e!=="ok"&&e!=="error")return this._logger?.debug(`Ignoring unknown span status "${String(e)}"; expected "ok" or "error"`),this;this._status={code:e,...t&&{message:gi(t,this._maxAttributeValueLength)}}}return this}get statusIsExplicitlyOk(){return this._status?.code==="ok"}recordException(e){if(!this._mutable("recordException"))return this;let{type:t,message:n,stack:s}=hi(e);return this.addEvent($p,{"exception.type":t,"exception.message":n,...s&&{"exception.stacktrace":s}}),this.setStatus("error",n)}updateName(e){return this._mutable("updateName")&&(this._name=Ye(e,"Span name",this._maxAttributeValueLength,this._logger)),this}traceparent(){return Rc(this._traceId,this._spanId,this._traceFlags)}tracestate(){return this._traceState??null}childContext(){return{traceId:this._traceId,parentSpanId:this._spanId,traceState:this._traceState,traceFlags:this._traceFlags,clockAnchor:this._clockAnchor}}end(e){if(this._ended)return void this._logger?.debug("Ignoring end() on a span that has already ended");this._ended=!0;let t=this._now(),n=Zt(e,t,"end time",this._logger);this._onEnd({traceId:this._traceId,spanId:this._spanId,...this._parentSpanId&&{parentSpanId:this._parentSpanId},...this._traceState&&{traceState:this._traceState},traceFlags:this._traceFlags,parentIsRemote:this._parentIsRemote,name:this._name,kind:this._kind,...this._status&&{status:this._status},attributes:{...this._attributes},events:this._events,startTime:this._startTime,endTime:Pn(n,this._startTime),...this._droppedAttributes&&{droppedAttributesCount:this._droppedAttributes},...this._droppedEvents&&{droppedEventsCount:this._droppedEvents}},this._autoKeys)}},$p="exception",jp=4294967295;function Bp(r){try{return typeof r=="string"?r:String(r)}catch{return J}}function Je(r){return typeof r!="number"||!Number.isFinite(r)||r<=0?0:Math.min(Math.floor(r),jp)}function Wp(r,e){if(!e.length)return Object.keys(r);let t=e.filter(s=>Object.prototype.propertyIsEnumerable.call(r,s)),n=new Set(t);return[...t,...Object.keys(r).filter(s=>!n.has(s))]}function Fc(r,e,t,n,s,i,o=[]){let a=0,c=0,l={};for(let p of Wp(r.attributes,o)){let h=r.attributes[p];if(!re(h)){if(!e.has(p)){if(a>=t){c++;continue}a++}Object.defineProperty(l,p,{value:Mn(h,i),enumerable:!0,writable:!0,configurable:!0})}}r.attributes=l,c&&(r.droppedAttributesCount=Je(r.droppedAttributesCount)+c);let u=0,d=0,g=[];for(let p of r.events){if(u>=n){d++;continue}if(u++,p.attributes){let h=kc(p.attributes,s,i);p.attributes=h.attributes,h.dropped&&(p.droppedAttributesCount=Je(p.droppedAttributesCount)+h.dropped)}g.push(p)}r.events=g,d&&(r.droppedEventsCount=Je(r.droppedEventsCount)+d),r.status?.message&&(r.status={...r.status,message:gi(Bp(r.status.message),i)})}var Cn=class{setAttribute(){return this}setAttributes(){return this}addEvent(){return this}setStatus(){return this}recordException(){return this}updateName(){return this}traceparent(){return null}tracestate(){return null}end(){}},Oc=new Cn,er=class extends Cn{constructor(e,t){super(),this._traceparent=e,this._tracestate=t}traceparent(){return this._traceparent}tracestate(){return this._tracestate??null}};function Hp(r){try{let e=r.stack;return typeof e=="string"&&e?{stack:e}:{}}catch{return{}}}function Ne(r,e){let t=vn(r?.parent)??e,n=typeof t=="string"||t==null?t:xc(t,"traceparent"),s=Ic(n);if(!s)return Oc;let i=typeof t=="string"||t==null?r?.tracestate:xc(t,"tracestate");return new er(s,Tn(i))}function xc(r,e){try{let t=r[e];return typeof t=="function"?t.call(r):void 0}catch{return}}function gi(r,e){return r.length>e?r.slice(0,e):r}function Mn(r,e){return In(r,e,{ancestors:new WeakSet,remainingNodes:1e4},0)}function In(r,e,t,n){if(r===null||typeof r!="object")return re(r)||t.remainingNodes<=0?r:(t.remainingNodes--,typeof r=="string"?gi(r,e):r);if(t.ancestors.has(r))return cn;if(t.remainingNodes<=0||n>=20)return r;t.remainingNodes--,t.ancestors.add(r);try{if(r instanceof Date)return r;let s=Gp(r);if(s.selfDescribed)return re(s.value)?String(s.value):In(s.value,e,t,n+1);if(Y(r)){let a=Math.min(r.length,1e3),c=[];for(let l=0;l<a;l++)try{c.push(In(r[l],e,t,n+1))}catch{c.push(J)}return r.length>a&&(c.length=r.length),c}let i={},o=0;for(let a of Object.keys(r)){if(o>=1e3)break;let c;try{c=In(r[a],e,t,n+1)}catch{c=J}a&&!re(c)&&o++,Object.defineProperty(i,a,{value:c,enumerable:!0,writable:!0,configurable:!0})}return i}catch{return r}finally{t.ancestors.delete(r)}}function Gp(r){try{let e=r.toJSON;if(typeof e=="function")return{selfDescribed:!0,value:e.call(r)}}catch{}return{selfDescribed:!1}}function kc(r,e,t){let n;try{n=Object.keys(r)}catch{return{attributes:{},dropped:0}}let s={},i=0,o=0;for(let a of n){if(i>=e){o++;continue}let c;try{c=Mn(r[a],t)}catch{c=J}re(c)||(i++,Object.defineProperty(s,a,{value:c,enumerable:!0,writable:!0,configurable:!0}))}return{attributes:s,dropped:o}}function Dc(r,e){for(let t of Object.keys(r))r[t]=Mn(r[t],e);return r}function tr(r,e,t){return e===Oc?t(e):r.with(e,()=>t(e))}function hi(r){try{let e=Hp(r);if(lt(r))return{type:r.name||"Error",message:r.message||"",...e};if(typeof r=="string")return{type:"string",message:r};if(r&&typeof r=="object"){let t=r;if(typeof t.message=="string")return{type:typeof t.name=="string"?t.name:"Object",message:t.message,...e}}return{type:typeof r,message:String(r)}}catch{return{type:typeof r,message:""}}}var mi={internal:1,server:2,client:3,producer:4,consumer:5},Kp={ok:1,error:2},Vp=1,qp=256,zp=512;function Yp(r){let e=parseInt(r.traceFlags,16);return(Number.isFinite(e)?255&e:Vp)|qp|(r.parentIsRemote?zp:0)}function xn(r){if(typeof r=="string")return ce(r);try{return ce(String(r))}catch{return J}}function Jp(r){return r&&Object.prototype.hasOwnProperty.call(mi,r)?mi[r]:mi.internal}function _i(r){let e=Math.floor(r),t=Math.round((r-e)*1e6);return t>=1e6&&(e+=1,t=0),String(e)+String(t).padStart(6,"0")}function Xp(r,e){let t={name:xn(r.name),timeUnixNano:_i(r.timestamp)};if(r.attributes){let s=ue(r.attributes,e);s.length&&(t.attributes=s)}let n=Je(r.droppedAttributesCount);return n&&(t.droppedAttributesCount=n),t}function Lc(r,e){let t={traceId:r.traceId,spanId:r.spanId,name:xn(r.name),kind:Jp(r.kind),startTimeUnixNano:_i(r.startTime),endTimeUnixNano:_i(r.endTime),flags:Yp(r)};r.parentSpanId&&(t.parentSpanId=r.parentSpanId),r.traceState&&(t.traceState=xn(r.traceState));let n=ue(r.attributes,e);n.length&&(t.attributes=n),r.events.length&&(t.events=r.events.map(o=>Xp(o,e)));let s=Je(r.droppedAttributesCount);s&&(t.droppedAttributesCount=s);let i=Je(r.droppedEventsCount);return i&&(t.droppedEventsCount=i),r.status&&(t.status={code:Kp[r.status.code],...r.status.message&&{message:xn(r.status.message)}}),t}function Nc(r,e,t){return qt(r,e,t)}function Uc(r,e,t,n,s){return{resourceSpans:[{resource:{attributes:zt(e,s)},scopeSpans:[{scope:{name:t,version:n},spans:r}]}]}}var $c=8;function Fn(){return Rn()??Date.now()}function Ei(r){try{return r instanceof _t}catch{return!1}}function jc(r,e){let t=Tc(r);if(t)return{traceId:t.traceId,parentSpanId:t.spanId,traceState:Tn(e),traceFlags:t.flags,isRemote:!0}}function Qp(r){try{return typeof r.traceparent=="function"}catch{return!1}}function Zp(r){return!!r.attributes&&typeof r.attributes=="object"&&!Array.isArray(r.attributes)&&Array.isArray(r.events)&&r.name!==void 0&&r.kind!==void 0&&r.startTime!==void 0&&r.endTime!==void 0}function On(r,e,t){r[e]!==t&&(r[e]=t)}function eg(r,e){try{let t=Object.getOwnPropertyDescriptors(r);for(let n of["traceId","spanId","parentSpanId","traceState"])t[n]={value:e[n],enumerable:!0,writable:!0,configurable:!0};return Object.create(Object.getPrototypeOf(r),t)}catch{return r}}var rr=class{constructor(e,t,n,s,i,o){this._instance=e,this._config=t,this._logger=n,this._getContext=s,this._contextManager=i,this._onSpanQueued=o,this._queue=[],this._flushTimer=new ze(()=>this._flushInBackground()),this._flushPromise=null,this._droppedSinceWarning=0,this._lastDropWarningAt=0,this._dropReasons=new Set,this._consecutiveFlushFailures=0,this._flushJitter=ee,this._retryAfter=new qe,this._headBatchFailures=0,this._headBatchSize=0,this._headBatchChargeableAt=0,this._generation=0,this._liveSpans=new Map,this._maxExportBatchSize=t.maxExportBatchSize}startSpan(e,t){if(this._instance.isDisabled||this._instance.optedOut)return Ne(t,this._contextManager.active());let n=vn(t?.parent);if(n&&typeof n!="string"&&!Ei(n)){if(Qp(n))return this._logger.debug("Span parent is not a span from this SDK; returning an inert span"),Ne(t,this._contextManager.active());this._logger.debug("Ignoring an unusable span parent")}let s=this._resolveParent(n,t);if(this._evictAgedSpans(),this._liveSpans.size>=this._config.maxLiveSpans)return this._recordDrop(1,`the live-span limit (${this._config.maxLiveSpans}) was reached \u2014 spans are being started and never ended`),Ne(t,this._contextManager.active());let i=Date.now(),o=Mc(t?.startTime,i,this._logger),a=bc();this._liveSpans.set(a,Fn());let c=this._autoContextAttributes();return new _t({traceId:s?.traceId??Sc(),spanId:a,parentSpanId:s?.parentSpanId,traceState:s?.traceState,traceFlags:s?.traceFlags,parentIsRemote:s?.isRemote,name:Ye(e,"Span name",this._config.maxAttributeValueLength,this._logger),kind:t?.kind??"internal",attributes:Te({...c},t?.attributes),autoAttributeKeys:Object.keys(c),maxAttributes:this._config.maxAttributesPerSpan,maxEvents:this._config.maxEventsPerSpan,maxAttributesPerEvent:this._config.maxAttributesPerEvent,maxAttributeValueLength:this._config.maxAttributeValueLength,startTime:o,backdated:o!==i,clockAnchor:mt(t?.startTime)===void 0?s?.clockAnchor:void 0},(l,u)=>this._onSpanEnd(l,u),this._logger)}withSpan(e,t,n){let s=typeof t=="function"?void 0:t,i=typeof t=="function"?t:n,o=this.startSpan(e,s);try{let a=tr(this._contextManager,o,i);return Na(a)?a.then(c=>(o.end(),c),c=>{throw this._recordCallbackError(o,c),o.end(),c}):(o.end(),a)}catch(a){throw this._recordCallbackError(o,a),o.end(),a}}getActiveSpan(){return this._contextManager.active()??null}get throttled(){return this._retryAfter.isOpen()}async flush(){for(;;)if(!this._queue.length||!await(this._flushPromise??this._startFlush()))return}_startFlush(){this._flushTimer.clear();let e=this._generation,t=Promise.resolve().then(()=>e===this._generation?this._flushInner():0).finally(()=>{this._flushPromise===t&&(this._flushPromise=null),this._armFlushTimerIfQueuedNoEarlierThan()});return this._flushPromise=t,t}reset(){this._flushTimer.clear(),this._queue.length&&this._logger.critical(`Discarding ${this._queue.length} span(s) that were still queued when tracing was shut down. Raise the shutdown timeout or flush earlier if they matter.`),this._queue=[],this._liveSpans.clear(),this._flushPromise=null,this._generation++,this._maxExportBatchSize=this._config.maxExportBatchSize,this._droppedSinceWarning=0,this._dropReasons.clear(),this._lastDropWarningAt=0,this._consecutiveFlushFailures=0,this._flushJitter=ee,this._retryAfter.reset(),this._resetHeadBatchBudget()}_resetHeadBatchBudget(){this._headBatchFailures=0,this._headBatchChargeableAt=0}_resolveParent(e,t){if(typeof e=="string"){let s=jc(e,t?.tracestate);return s||this._logger.debug("Ignoring malformed traceparent; starting a new trace"),s}if(Ei(e))return e.childContext();let n=this._contextManager.active();if(Ei(n))return n.childContext();if(n instanceof er)return jc(n.traceparent(),n.tracestate()??void 0)}_autoContextAttributes(){let e;try{e=this._getContext()}catch(n){return this._logger.debug("Failed to read tracing context; span will carry no PostHog attributes",n),{}}let t={};return e.distinctId&&(t.posthogDistinctId=e.distinctId),e.sessionId&&(t.sessionId=e.sessionId),e.currentUrl&&(t["url.full"]=e.currentUrl),e.screenName&&(t["screen.name"]=e.screenName),e.appState&&(t["app.state"]=e.appState),t}_recordCallbackError(e,t){if(!(e instanceof _t))return;let{type:n,message:s,stack:i}=hi(t);e.addEvent("exception",{"exception.type":n,"exception.message":s,...i&&{"exception.stacktrace":i}}),e.statusIsExplicitlyOk||e.setStatus("error",s)}_evictAgedSpans(){let e=Fn()-this._config.maxSpanAgeMs,t=0;for(let[n,s]of this._liveSpans){if(s>e)break;this._liveSpans.delete(n),t++}t&&this._recordDrop(t,`they were still live after ${this._config.maxSpanAgeMs}ms`)}_onSpanEnd(e,t){if(!this._liveSpans.delete(e.spanId))return;if(this._instance.isDisabled||this._instance.optedOut)return void this._recordDrop(1,"the user has opted out");let n=this._runBeforeSpanSend(e,t);if(n){if(this._reportLimitDrops(n),this._queue.length>=this._config.maxQueueSize)return void this._recordDrop(1,`the queue is full (${this._config.maxQueueSize}) \u2014 raise the flush frequency or reduce span volume`);this._queue.push(n);try{this._onSpanQueued?.()}catch(s){this._logger.debug("Span queue notification failed",s)}!(this._queue.length>=this._maxExportBatchSize)||this._consecutiveFlushFailures||this._retryAfter.isOpen()?this._armFlushTimerIfQueued():this._flushInBackground()}}_reportLimitDrops(e){let t=e.droppedAttributesCount??0,n=e.droppedEventsCount??0,s=0;for(let i of e.events)s+=i.droppedAttributesCount??0;(t||n||s)&&this._logger.debug(`Span limits discarded data from "${e.name}": ${t} attributes, ${n} events, ${s} event attributes`)}_runBeforeSpanSend(e,t){if(!this._config.beforeSpanSend.length)return e;let n={traceId:e.traceId,spanId:e.spanId,parentSpanId:e.parentSpanId,traceState:e.traceState},s={startTime:e.startTime,endTime:e.endTime},i={attributes:e.droppedAttributesCount,events:e.droppedEventsCount},o=Object.keys(e.attributes),a={traceFlags:e.traceFlags,parentIsRemote:e.parentIsRemote},c=e.status&&{...e.status},l=e,u=e;try{for(let p of this._config.beforeSpanSend){let h=p(l);if(!h)return this._recordDrop(1,"beforeSpanSend dropped it"),null;l=this._keepSpanIdentity(h,n)}if(u={traceId:n.traceId,spanId:n.spanId,parentSpanId:n.parentSpanId,traceState:n.traceState,name:l.name,kind:l.kind,status:l.status,attributes:l.attributes,events:l.events,startTime:l.startTime,endTime:l.endTime,traceFlags:a.traceFlags,parentIsRemote:a.parentIsRemote,droppedAttributesCount:i.attributes,droppedEventsCount:i.events},!Zp(u))return this._logger.debug("beforeSpanSend did not return a span record; dropping the span"),this._recordDrop(1,"beforeSpanSend returned an unusable record"),null;u.name=Ye(u.name,"Span name",this._config.maxAttributeValueLength,this._logger),u.status&&u.status.code!=="ok"&&u.status.code!=="error"&&(this._logger.debug("beforeSpanSend set an unknown span status; keeping the original"),u.status=c),u.startTime=mt(u.startTime)??s.startTime,u.endTime=Pn(mt(u.endTime)??s.endTime,u.startTime);let g=[];for(let p of u.events)try{g.push({...p,name:Ye(p.name,"Span event name",this._config.maxAttributeValueLength,this._logger),timestamp:Zt(p.timestamp,u.startTime,"event timestamp",this._logger)})}catch{this._logger.debug("beforeSpanSend left an unreadable span event; dropping it")}return u.events=g,Fc(u,t,this._config.maxAttributesPerSpan,this._config.maxEventsPerSpan,this._config.maxAttributesPerEvent,this._config.maxAttributeValueLength,o),u}catch(d){return this._logger.debug("beforeSpanSend failed; dropping the span rather than exporting it unscrubbed",d),this._recordDrop(1,"beforeSpanSend failed"),null}}_keepSpanIdentity(e,t){(e.traceId!==t.traceId||e.spanId!==t.spanId||e.parentSpanId!==t.parentSpanId)&&this._logger.debug("beforeSpanSend changed a span identity field; keeping the original ids");try{On(e,"traceId",t.traceId),On(e,"spanId",t.spanId),On(e,"parentSpanId",t.parentSpanId),On(e,"traceState",t.traceState)}catch{return eg(e,t)}return e}_recordDrop(e,t){this._droppedSinceWarning+=e,this._dropReasons.add(t),Date.now()-this._lastDropWarningAt>=this._config.flushIntervalMs&&this._warnAboutDrops()}_warnAboutDrops(){this._droppedSinceWarning&&(this._lastDropWarningAt=Date.now(),this._logger.warn(`Dropping ${this._droppedSinceWarning} span(s): ${[...this._dropReasons].join("; ")}`),this._droppedSinceWarning=0,this._dropReasons.clear())}_encodeBatch(e){let t=[];for(let n of e)try{t.push(Lc(n,this._logger))}catch(s){this._logger.debug("Failed to encode a span; dropping it",s),this._recordDrop(1,"its attributes could not be encoded")}return t}_discardQueueIfConsentWithdrawn(){if(!this._instance.isDisabled&&!this._instance.optedOut)return 0;let e=this._queue.length;return this._queue=[],this._resetHeadBatchBudget(),this._recordDrop(e,"the user has opted out"),this._warnAboutDrops(),e}async _flushInner(){if(!this._queue.length)return 0;let e=this._discardQueueIfConsentWithdrawn();if(e)return e;let t=Dc(Nc(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._config.maxAttributeValueLength),n=this._instance.getLibraryId(),s=this._instance.getLibraryVersion(),i=this._queue.length,o=0,a=1/0,c=this._generation;try{for(;i>0&&this._queue.length>0;){let l=this._discardQueueIfConsentWithdrawn();if(l)return o+l;let u=this._headBatchFailures>0?Math.min(this._maxExportBatchSize,this._headBatchSize):this._maxExportBatchSize,d=Math.max(1,Math.min(u,a,i,this._queue.length)),g=this._queue.slice(0,d),p=this._encodeBatch(g);if(!p.length){this._queue.splice(0,d),i-=d,o+=d,this._resetHeadBatchBudget();continue}let h=Fn()>=this._headBatchChargeableAt&&!this._retryAfter.isOpen(),m=await this._instance._sendTracesBatch(Uc(p,t,n,s,this._logger));if(c!==this._generation)break;if(this._retryAfter.record(m),m.kind==="ok"){this._consecutiveFlushFailures=0,this._flushJitter=ee,this._resetHeadBatchBudget(),this._queue.splice(0,d),i-=d,o+=d,this._maxExportBatchSize<this._config.maxExportBatchSize&&this._maxExportBatchSize++;continue}if(m.kind==="too-large"){if(d===1){this._queue.splice(0,1),i-=1,o+=1,this._recordDrop(1,"it is too large for the ingestion endpoint"),this._consecutiveFlushFailures=0,this._flushJitter=ee,this._resetHeadBatchBudget();continue}let E=Math.max(1,Math.floor(d/2));m.measuredLocally?a=E:this._maxExportBatchSize=E,this._resetHeadBatchBudget(),this._logger.debug(`Batch too large; retrying the same spans in batches of ${E}`);continue}if(m.kind==="retry-later"){if(this._consecutiveFlushFailures++,this._flushJitter=Yt(),this._headBatchSize=d,h&&(this._headBatchFailures++,this._headBatchChargeableAt=Fn()+this._nextFlushDelay()),this._headBatchFailures<$c)return this._logger.debug("Span export failed; retrying on the next flush",m.error),o;if(this._queue.splice(0,d),i-=d,o+=d,this._consecutiveFlushFailures=0,this._flushJitter=ee,this._resetHeadBatchBudget(),this._recordDrop(d,`the ingestion endpoint failed ${$c} times in a row`),this._retryAfter.isOpen())return o;continue}this._logger.debug("Dropping a span batch the ingestion endpoint rejected",m.error),this._queue.splice(0,d),i-=d,o+=d,this._consecutiveFlushFailures=0,this._flushJitter=ee,this._resetHeadBatchBudget(),this._recordDrop(d,"the ingestion endpoint rejected the batch")}return o}finally{this._warnAboutDrops()}}_flushInBackground(){this._backgroundFlush||(this._backgroundFlush=this.flush().catch(e=>{this._logger.debug("Background span flush failed",e)}).finally(()=>{this._backgroundFlush=void 0,this._armFlushTimerIfQueuedNoEarlierThan()}))}_armFlushTimerIfQueued(){this._flushTimer.pending||!this._queue.length||this._flushTimer.arm(this._nextFlushDelay())}_armFlushTimerIfQueuedNoEarlierThan(){this._queue.length&&this._flushTimer.armNoEarlierThan(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(Jt(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}};var nr=class{active(){return this._active}with(e,t){let n=this._active;this._active=e;try{return t()}finally{this._active=n}}};var tg=5e3,rg=512,ng=2048,sg=128,ig=128,og=128,ag=8192,cg=1e4,lg=36e5;function Ue(r,e){return typeof r=="number"&&Number.isInteger(r)&&r>=1?r:e}var Bc=["service.name","service.version","deployment.environment"];function ug(r){if(!(!r||typeof r!="object"||Array.isArray(r)))try{if(Bc.every(t=>!(t in r)||typeof r[t]=="string"))return r;let e={...r};for(let t of Bc)t in e&&typeof e[t]!="string"&&delete e[t];return e}catch{return}}function dg(r,e){if(!r)return[];let t=[r].flat().filter(s=>!!s),n=t.filter(s=>typeof s=="function");return n.length!==t.length&&e?.critical(`beforeSpanSend: ignoring ${t.length-n.length} of ${t.length} entries that are not functions. Spans export without them, so whatever they were redacting is not redacted.`),n}function yi(r,e,t){let n=Te({...e},ug(r?.resourceAttributes)),s=Ue(r?.maxExportBatchSize,rg);return{serviceName:n?.["service.name"]??r?.serviceName,serviceVersion:n?.["service.version"]??r?.serviceVersion,environment:n?.["deployment.environment"]??r?.environment,resourceAttributes:n,beforeSpanSend:dg(r?.beforeSpanSend,t),maxAttributesPerSpan:Ue(r?.maxAttributesPerSpan,sg),maxEventsPerSpan:Ue(r?.maxEventsPerSpan,ig),maxAttributesPerEvent:og,maxAttributeValueLength:Ue(r?.maxAttributeValueLength,ag),flushIntervalMs:Ue(r?.flushIntervalMs,tg),maxExportBatchSize:s,maxQueueSize:Math.max(Ue(r?.maxQueueSize,ng),s),maxLiveSpans:Ue(r?.maxLiveSpans,cg),maxSpanAgeMs:Ue(r?.maxSpanAgeMs,lg)}}var Si=require("node:fs"),Gc=require("node:fs/promises"),wi=require("node:path"),Kc=require("node:readline"),kn=new D.ReduceableCache(25),sr=new D.ReduceableCache(20),vi=7,fg=1e3,pg=1e4,bi=10485760;async function Vc(r,e=Gc.open,t){let n={},s;try{s=process.cwd()}catch{}for(let a=r.length-1;a>=0;a--){let c=r[a],l=c?.filename;if(!c||typeof l!="string"||typeof c.lineno!="number"||Eg(l)||yg(c)||!(0,wi.isAbsolute)(l)&&s===void 0)continue;n[l]||(n[l]=[]),n[l].push(c.lineno)}let i=Object.keys(n);if(i.length==0)return r;let o=[];for(let a of i){let c=qc(a,s);if(c===void 0||sr.get(c))continue;let l=n[a];if(!l)continue;l.sort((g,p)=>g-p);let u=bg(l);if(u.every(g=>Sg(c,g)))continue;let d=wg(kn,c,{});o.push(hg(a,u,d,c,e,t))}return await Promise.all(o).catch(()=>{}),r&&r.length>0&&mg(r,kn,s),kn.reduce(),r}async function gg(r,e,t){let n,s=!1;try{n=await e(r,Si.constants.O_RDONLY|Si.constants.O_NONBLOCK);let i=await n.stat();return i.isFile()?i.size>bi?void t?.debug(`Skipping source context for oversized file ${r}: ${i.size} bytes exceeds ${bi}`):(s=!0,n):void 0}catch{return}finally{n&&!s&&await n.close().catch(()=>{})}}async function hg(r,e,t,n,s,i){let o=await gg(r,s,i);if(o===void 0)return void sr.set(n,1);let a=o;return new Promise(c=>{let l=!1;function u(P){l||(l=!0,P?.destroy(),a.close().then(c,c))}let d;try{d=a.createReadStream({autoClose:!1,start:0,end:bi-1})}catch{sr.set(n,1),u();return}let g;try{g=(0,Kc.createInterface)({input:d})}catch{sr.set(n,1),u(d);return}let p=0,h=0,m=e[h];if(m===void 0)return void u(d);let E=m[0],_=m[1];function b(){sr.set(n,1),g.close(),g.removeAllListeners(),u(d)}d.on("error",b),g.on("error",b),g.on("close",()=>u(d)),g.on("line",P=>{if(p++,!(p<E)&&(t[p]=vg(P,0),p>=_)){if(h===e.length-1){g.close(),g.removeAllListeners();return}h++;let R=e[h];if(R===void 0){g.close(),g.removeAllListeners();return}E=R[0],_=R[1]}})})}function mg(r,e,t){for(let n of r)if(n.filename&&n.context_line===void 0&&typeof n.lineno=="number"){let s=qc(n.filename,t),i=s===void 0?void 0:e.get(s);if(i===void 0)continue;_g(n.lineno,n,i)}}function _g(r,e,t){if(e.lineno===void 0||t===void 0)return;e.pre_context=[];for(let s=zc(r);s<r;s++){let i=t[s];if(i===void 0)return void Wc(e);e.pre_context.push(i)}if(t[r]===void 0)return void Wc(e);e.context_line=t[r];let n=Yc(r);e.post_context=[];for(let s=r+1;s<=n;s++){let i=t[s];if(i===void 0)break;e.post_context.push(i)}}function Wc(r){delete r.pre_context,delete r.context_line,delete r.post_context}function Eg(r){return r.startsWith("node:")||r.endsWith(".min.js")||r.endsWith(".min.cjs")||r.endsWith(".min.mjs")||r.startsWith("data:")}function yg(r){return r.lineno!==void 0&&r.lineno>pg||r.colno!==void 0&&r.colno>fg}function qc(r,e){return(0,wi.isAbsolute)(r)?JSON.stringify([null,r]):e===void 0?void 0:JSON.stringify([e,r])}function Sg(r,e){let t=kn.get(r);if(t===void 0)return!1;for(let n=e[0];n<=e[1];n++)if(t[n]===void 0)return!1;return!0}function bg(r){if(!r.length)return[];let e=0,t=r[0];if(typeof t!="number")return[];let n=Hc(t),s=[];for(;;){if(e===r.length-1){s.push(n);break}let i=r[e+1];if(typeof i!="number")break;i<=n[1]?n[1]=i+vi:(s.push(n),n=Hc(i)),e++}return s}function Hc(r){return[zc(r),Yc(r)]}function zc(r){return Math.max(1,r-vi)}function Yc(r){return r+vi}function wg(r,e,t){let n=r.get(e);return n===void 0?(r.set(e,t),t):n}function vg(r,e){let t=r,n=t.length;if(n<=150)return t;e>n&&(e=n);let s=Math.max(e-60,0);s<5&&(s=0);let i=Math.min(s+140,n);return i>n-5&&(i=n),i===n&&(s=Math.max(i-140,0)),t=t.slice(s,i),s>0&&(t=`...${t}`),i<n&&(t+="..."),t}var Et=require("path");function Jc(r=process.cwd()){let e=Et.sep==="\\",t=s=>e?s.replace(/\\/g,"/"):s,n=t(r);return async s=>{for(let i of s)!i.filename||i.filename.startsWith("node:")||i.filename.startsWith("data:")||(0,Et.isAbsolute)(i.filename)&&(i.filename=t((0,Et.relative)(n,t(i.filename))));return s}}var Xc="5.52.1";var Ie={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};var $e=class r{constructor(e){this._host=e.host,this._distinctId=e.distinctId,this._groups=e.groups,this._disableGeoip=e.disableGeoip,this._flags=e.flags,this._requestId=e.requestId,this._evaluatedAt=e.evaluatedAt,this._flagDefinitionsLoadedAt=e.flagDefinitionsLoadedAt,this._errorsWhileComputing=e.errorsWhileComputing??!1,this._quotaLimited=e.quotaLimited??!1,this._accessed=e.accessed??new Set,this._isSlice=e.isSlice??!1}isEnabled(e,t={}){let n=this._flags[e];return this._recordAccess(e),n?.enabled??t.defaultValue??!1}getFlag(e){let t=this._flags[e];if(this._recordAccess(e),!!t)return t.enabled?t.variant??!0:!1}getFlagPayload(e){return this._flags[e]?.payload}onlyAccessed(){let e={};for(let t of this._accessed){let n=this._flags[t];n&&(e[t]=n)}return this._cloneWith(e)}only(e){let t={},n=[];for(let s of e){let i=this._flags[s];i?t[s]=i:n.push(s)}return n.length>0&&this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${n.join(", ")}`),this._cloneWith(t)}get keys(){return Object.keys(this._flags)}_getEventProperties(){let e={},t=[];for(let[n,s]of Object.entries(this._flags)){let i=s.enabled===!1?!1:s.variant??!0;e[`$feature/${n}`]=i,s.enabled&&t.push(n)}return t.length>0&&(t.sort(),e.$active_feature_flags=t),e}_cloneWith(e){return new r({host:this._host,distinctId:this._distinctId,groups:this._groups,disableGeoip:this._disableGeoip,flags:e,requestId:this._requestId,evaluatedAt:this._evaluatedAt,flagDefinitionsLoadedAt:this._flagDefinitionsLoadedAt,errorsWhileComputing:this._errorsWhileComputing,quotaLimited:this._quotaLimited,accessed:new Set(this._accessed),isSlice:!0})}_recordAccess(e){if(this._accessed.add(e),this._distinctId===""||this._isSlice&&!(e in this._flags))return;let t=this._flags[e],n=t===void 0?void 0:t.enabled===!1?!1:t.variant??!0,s={$feature_flag:e,$feature_flag_response:n,$feature_flag_id:t?.id,$feature_flag_version:t?.version,$feature_flag_reason:t?.reason,locally_evaluated:t?.locallyEvaluated??!1,[`$feature/${e}`]:n,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:t?.locallyEvaluated?Date.now():this._evaluatedAt};t?.hasExperiment!==void 0&&(s.$feature_flag_has_experiment=t.hasExperiment),t?.locallyEvaluated&&this._flagDefinitionsLoadedAt!==void 0&&(s.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt);let i=[];this._errorsWhileComputing&&i.push(Ie.ERRORS_WHILE_COMPUTING),this._quotaLimited&&i.push(Ie.QUOTA_LIMITED),t===void 0&&i.push(Ie.FLAG_MISSING),i.length>0&&(s.$feature_flag_error=i.join(",")),this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:e,response:n,groups:this._groups,disableGeoip:this._disableGeoip,properties:s})}};var Ag=6e4,yt=class r extends Error{constructor(e){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=e,Object.setPrototypeOf(this,r.prototype)}};function Tg(r,e){r.name=e.name,Error.captureStackTrace(r,e),Object.setPrototypeOf(r,e.prototype)}var de=class r extends Error{constructor(e){super(e),Tg(this,r)}},Dn=class{constructor({pollingInterval:e,personalApiKey:t,projectApiKey:n,timeout:s,host:i,customHeaders:o,...a}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollerStopped=!1,this.filteredOutFlagKeys=new Set,this.pollingInterval=e,this.personalApiKey=t,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=s,this.projectApiKey=n,this.host=i,this.poller=void 0,this.fetch=a.fetch||fetch,this.onError=a.onError,this.customHeaders=o,this.onLoad=a.onLoad,this.onMinimalFlagCalledEvents=a.onMinimalFlagCalledEvents,this.cacheProvider=a.cacheProvider,this.strictLocalEvaluation=a.strictLocalEvaluation??!1,this.evaluationContexts=a.evaluationContexts,this.loadFeatureFlags()}debug(e=!0){this.debugMode=e}logMsgIfDebug(e){this.debugMode&&e()}createEvaluationContext(e,t={},n={},s={},i={}){return{distinctId:e,groups:t,personProperties:n,groupProperties:s,evaluationCache:i}}async getFeatureFlag(e,t,n={},s={},i={}){await this.loadFeatureFlags();let o,a;if(!this.loadedSuccessfullyOnce)return o;if(a=this.featureFlagsByKey[e],a!==void 0){let c=this.createEvaluationContext(t,n,s,i);try{o=(await this.computeFlagAndPayloadLocally(a,c)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${e} -> ${o}`))}catch(l){l instanceof de||l instanceof S?this.logMsgIfDebug(()=>console.debug(`${l.name} when computing flag locally: ${e}: ${l.message}`)):l instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${e}: ${l}`))}}return o}async getAllFlagsAndPayloads(e,t){await this.loadFeatureFlags();let n={},s={},i=this.featureFlags.length==0,o=t?t.map(c=>this.featureFlagsByKey[c]).filter(Boolean):this.featureFlags,a={...e,evaluationCache:e.evaluationCache??{}};return await Promise.all(o.map(async c=>{try{let{value:l,payload:u}=await this.computeFlagAndPayloadLocally(c,a);n[c.key]=l,u&&(s[c.key]=u)}catch(l){l instanceof de||l instanceof S?this.logMsgIfDebug(()=>console.debug(`${l.name} when computing flag locally: ${c.key}: ${l.message}`)):l instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${c.key}: ${l}`)),i=!0}})),{response:n,payloads:s,fallbackToFlags:i}}async computeFlagAndPayloadLocally(e,t,n={}){let{matchValue:s,skipLoadCheck:i=!1}=n;if(i||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let o;o=s!==void 0?s:await this.computeFlagValueLocally(e,t);let a=this.getFeatureFlagPayload(e.key,o);return{value:o,payload:a}}async computeFlagValueLocally(e,t){let{distinctId:n,groups:s,personProperties:i,groupProperties:o}=t;if(!e.active)return!1;if(e.ensure_experience_continuity)throw new S("Flag has experience continuity enabled");let c=(e.filters||{}).aggregation_group_type_index;if(c!=null){let l=this.groupTypeMapping[String(c)];if(!l)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${c} for feature flag ${e.key}`)),new S("Flag has unknown group type index");if(!(l in s))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${e.key} without group names passed in`)),!1;e.bucketing_identifier==="device_id"&&(i?.$device_id===void 0||i?.$device_id===null||i?.$device_id==="")&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${e.key}`));let u=o[l];return await this.matchFeatureFlagProperties(e,s[l],u,t)}{let l=this.getBucketingValueForFlag(e,n,i);if(l===void 0)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${e.key} without $device_id, falling back to server evaluation`)),new S(`Can't compute feature flag: ${e.key} without $device_id`);return await this.matchFeatureFlagProperties(e,l,i,t)}}getBucketingValueForFlag(e,t,n){if(e.filters?.aggregation_group_type_index!=null)return t;if(e.bucketing_identifier==="device_id"){let s=n?.$device_id;return s==null||s===""?void 0:s}return t}getFeatureFlagPayload(e,t){return si(this.featureFlagsByKey?.[e]?.filters?.payloads,t)}async evaluateFlagDependency(e,t,n){let{evaluationCache:s}=n,i=e.key;if(!this.featureFlagsByKey)throw new S("Feature flags not available for dependency evaluation");if(!("dependency_chain"in e))throw new S(`Flag dependency property for '${i}' is missing required 'dependency_chain' field`);let o=e.dependency_chain;if(!Array.isArray(o))throw new S(`Flag dependency property for '${i}' has an invalid 'dependency_chain' (expected array, got ${typeof o})`);if(o.length===0)throw new S(`Circular dependency detected for flag '${i}' (empty dependency chain)`);for(let c of o){if(!(c in s)){let u=this.featureFlagsByKey[c];if(u)if(u.active)try{let d=await this.computeFlagValueLocally(u,n);s[c]=d}catch(d){throw new S(`Error evaluating flag dependency '${c}' for flag '${i}': ${d}`)}else s[c]=!1;else if(this.filteredOutFlagKeys.has(c))s[c]=!1;else throw new S(`Missing flag dependency '${c}' for flag '${i}'`)}if(s[c]==null)throw new S(`Dependency '${c}' could not be evaluated`)}let a=s[i];return this.flagEvaluatesToExpectedValue(e.value,a)}flagEvaluatesToExpectedValue(e,t){return typeof e=="boolean"?e===t||typeof t=="string"&&t!==""&&e===!0:typeof e=="string"?t===e:!1}async matchFeatureFlagProperties(e,t,n,s){let i=e.filters||{},o=i.groups||[],a=i.aggregation_group_type_index,c=i.early_exit??!1,{groups:l,groupProperties:u}=s,d=!1,g;for(let p of o)try{let h=p.aggregation_group_type_index!==void 0?p.aggregation_group_type_index:a,m=n,E=t;if(h!==a&&h!=null){let b=this.groupTypeMapping[String(h)];if(!b||!(b in l)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${e.key}': group type index ${h} not available`));continue}if(!(b in u)){d=!0;continue}m=u[b],E=l[b]}let _=await this.isConditionMatch(e,E,p,m,s);if(_==="match"){let b=p.variant,P=i.multivariate?.variants||[];g=b&&P.some(R=>R.key===b)?b:await this.getMatchingVariant(e,E)||!0;break}if(c&&_==="out_of_rollout_bound"){if(d)break;return!1}}catch(h){if(h instanceof de)throw h;if(h instanceof S)d=!0;else throw h}if(g!==void 0)return g;if(d)throw new S("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(e,t,n,s,i){let o=n.rollout_percentage,a=c=>{this.logMsgIfDebug(()=>console.warn(c))};if((n.properties||[]).length>0){for(let c of n.properties){let l=c.type,u=!1;if(l==="cohort"){let d=await Zc(c,s,this.cohorts,this.debugMode,g=>this.evaluateFlagDependency(g,s,i));u=c.operator==="not_in"?!d:d}else u=l==="flag"?await this.evaluateFlagDependency(c,s,i):Qc(c,s,a);if(!u)return"no_match"}if(o==null)return"match"}return o!=null&&await yn(e.key,t)>o/100?"out_of_rollout_bound":"match"}async getMatchingVariant(e,t){return ni(e.key,t,e.filters?.multivariate?.variants||[])}variantLookupTable(e){return Sn(e.filters?.multivariate?.variants||[])}filterFlagsByEvaluationContexts(e){if(!this.evaluationContexts||this.evaluationContexts.length===0)return e;let t=new Set(this.evaluationContexts);return e.filter(n=>{let s=n.evaluation_contexts??n.evaluation_tags;return!s||s.length===0?!0:s.some(i=>t.has(i))})}updateFlagState(e){let t=this.filterFlagsByEvaluationContexts(e.flags);this.featureFlags=t,this.featureFlagsByKey=t.reduce((s,i)=>(s[i.key]=i,s),{});let n=new Set(t.map(s=>s.key));this.filteredOutFlagKeys=new Set(e.flags.filter(s=>!n.has(s.key)).map(s=>s.key)),this.groupTypeMapping=e.groupTypeMapping,this.cohorts=e.cohorts,this.loadedSuccessfullyOnce=!0,this.onMinimalFlagCalledEvents?.(e.minimalFlagCalledEvents===!0)}warnAboutExperienceContinuityFlags(e){if(this.strictLocalEvaluation)return;let t=e.filter(n=>n.ensure_experience_continuity);t.length>0&&console.warn(`[PostHog] You are using local evaluation but ${t.length} flag(s) have experience continuity enabled: ${t.map(n=>n.key).join(", ")}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`)}async loadFromCache(e){if(!this.cacheProvider)return!1;try{let t=await this.cacheProvider.getFlagDefinitions();return t?(this.updateFlagState(t),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${e} (${t.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(this.featureFlags),!0):!1}catch(t){return this.onError?.(new Error(`Failed to load from cache: ${t}`)),!1}}async loadFeatureFlags(e=!1){if(!(this.loadedSuccessfullyOnce&&!e))return!e&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt?void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period")):(this.loadingPromise||(this.loadingPromise=this._loadFeatureFlags().catch(t=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${t}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise)}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(Ag,this.pollingInterval*2**this.backOffCount):this.pollingInterval}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0);try{let e=!0;if(this.cacheProvider)try{e=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(n){this.onError?.(new Error(`Error in shouldFetchFlagDefinitions: ${n}`))}if(!e&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||this.loadedSuccessfullyOnce))return;let t=await this._requestFeatureFlagDefinitions();if(!t)return;switch(t.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=t.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new yt(`Your project key or secret key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.filteredOutFlagKeys=new Set,this.groupTypeMapping={},this.cohorts={},this.onMinimalFlagCalledEvents?.(!1);return;case 403:throw this.beginBackoff(),new yt(`Your secret key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct secret and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new yt(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let n=await t.json()??{};if(!("flags"in n))return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(n)}`));this.flagsEtag=t.headers?.get("ETag")??void 0;let s={flags:n.flags??[],groupTypeMapping:n.group_type_mapping||{},cohorts:n.cohorts||{},minimalFlagCalledEvents:n.minimal_flag_called_events===!0};if(this.updateFlagState(s),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&e)try{await this.cacheProvider.onFlagDefinitionsReceived(s)}catch(i){this.onError?.(new Error(`Failed to store in cache: ${i}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(this.featureFlags);break}default:return}}catch(e){e instanceof yt&&this.onError?.(e)}finally{this.pollerStopped||(this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval()))}}getPersonalApiKeyRequestOptions(e="GET",t){let n={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return t&&(n["If-None-Match"]=t),{method:e,headers:n}}async _requestFeatureFlagDefinitions(){let e=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,t=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),n=null;if(this.timeout&&typeof this.timeout=="number"){let i=new AbortController;n=B(()=>{i.abort()},this.timeout),t.signal=i.signal}let s=()=>clearTimeout(n);try{let i=this.fetch,o=await i(e,t);return o.status!==200?(s(),o):{status:o.status,headers:o.headers,body:o.body,text:async()=>{try{return await o.text()}finally{s()}},json:async()=>{try{return await o.json()}finally{s()}}}}catch(i){throw s(),i}}async stopPoller(e=3e4){if(this.pollerStopped=!0,clearTimeout(this.poller),this.poller=void 0,this.cacheProvider)try{let t=this.cacheProvider.shutdown();t instanceof Promise&&await Le(t,e,()=>{throw new Error(`Cache shutdown timeout after ${e}ms`)})}catch(t){this.onError?.(new Error(`Error during cache shutdown: ${t}`))}}};function Qc(r,e,t){return ri(r,e,{warnFunction:t})}function Pg(r,e){if(!(r in e))throw new de(`cohort ${r} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function Zc(r,e,t,n=!1,s){let i=String(r.value);Pg(i,t);let o=t[i];return el(o,e,t,n,s)}async function el(r,e,t,n=!1,s){if(!r)return!0;let i=r.type,o=r.values;if(!o||o.length===0)return!0;let a=!1;if("values"in o[0]){for(let c of o)try{let l=await el(c,e,t,n,s);if(i==="AND"){if(!l)return!1}else if(l)return!0}catch(l){if(l instanceof de)throw l;if(l instanceof S)n&&console.debug(`Failed to compute property ${c} locally: ${l}`),a=!0;else throw l}if(a)throw new S("Can't match cohort without a given cohort property value");return i==="AND"}for(let c of o)try{let l;if(c.type==="cohort")l=await Zc(c,e,t,n,s);else if(c.type==="flag"){if(!s)throw new S(`Flag dependency '${c.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);l=await s(c)}else l=Qc(c,e);let u=c.negation||!1;if(i==="AND"){if(!l&&!u||l&&u)return!1}else if(l&&!u||!l&&u)return!0}catch(l){if(l instanceof de)throw l;if(l instanceof S)n&&console.debug(`Failed to compute property ${c} locally: ${l}`),a=!0;else throw l}if(a)throw new S("can't match cohort without a given cohort property value");return i==="AND"}var Ig=["--unhandled-rejections","--unhandled_rejections"],Rg=new Set(["throw","strict","warn","warn-with-error-code","none"]),Cg=[...globalThis.process?.execArgv??[]],Mg=globalThis.process?.env?.NODE_OPTIONS;function xg(r){let e=[],t="",n=!1;for(let s=0;s<r.length;s++){let i=r[s];i==="\\"&&n&&s+1<r.length?t+=r[++s]:i!==" "||n?i==='"'?n=!n:t+=i:t&&(e.push(t),t="")}return t&&e.push(t),e}function tl(r){let e;for(let t=0;t<r.length;t++){let n=r[t],s=Ig.find(o=>n===o||n.startsWith(`${o}=`));if(!s)continue;let i=n===s?r[++t]:n.slice(s.length+1);Rg.has(i)&&(e=i)}return e}function Fg(r=Cg,e=Mg){return tl(r)??tl(xg(e??""))??"throw"}var rl=Fg();function nl(r,e,t){r(e,{mechanism:{type:t==="unhandledRejection"?"onunhandledrejection":"onuncaughtexception",handled:!1}})}function Og(r,e){let t=!1;return Object.assign((n,s)=>{let i=global.process.listeners("uncaughtException").filter(o=>o.name!=="domainUncaughtExceptionClear"&&o._posthogErrorHandler!==!0).length;nl(r,n,s),!t&&i===0&&(t=!0,e(n))},{_posthogErrorHandler:!0})}function sl(r,e,t=rl){let n=globalThis.process;if(n){if(t==="strict")return void n.on("uncaughtExceptionMonitor",(s,i)=>nl(r,s,i));n.on("uncaughtException",Og(r,e))}}function il(r,e=rl){let t=globalThis.process;!t||e==="throw"||e==="strict"||e==="warn-with-error-code"||t.on("unhandledRejection",n=>{r(n,{mechanism:{type:"onunhandledrejection",handled:!1}})})}var kg=2e3,Ai=class r{constructor(e,t,n){this.client=e,this._exceptionAutocaptureEnabled=t.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new Zr({...ma(t),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(e){return Mt(e)&&"__posthog_previously_captured_error"in e&&e.__posthog_previously_captured_error===!0}static async buildEventMessage(e,t,n,s,i){let o={...i},a=e.buildFromUnknown(t,n);a.$exception_list=await e.modifyFrames(a.$exception_list);let c=D.getInjectedReleaseId();return c&&(o.$release_id=c),{event:"$exception",distinctId:s,properties:{...a,...o},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(sl(this.onException.bind(this),this.onFatalError.bind(this)),il(this.onException.bind(this)))}onException(e,t){this.client.addPendingPromise((async()=>{if(!r.isPreviouslyCapturedError(e)){let n=await r.buildEventMessage(this.client.getErrorPropertiesBuilder(),e,t),i=n.properties?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(i)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:i}):this.client._capturePreparedEvent(n,!1)}})())}async onFatalError(e){console.error(e),await this.client.shutdown(kg),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}},Xe=Ai;var Ln=class{getProperty(e){return this._memoryStorage[e]}setProperty(e,t){this._memoryStorage[e]=t!==null?t:void 0}constructor(){this._memoryStorage={}}};function Dg(r){return r==="v0"||r==="v1"}function ol(){let r="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0;return Dg(r)?r:"v0"}var Lg="$ai_",ir="analytics";function al(r){return typeof r.event=="string"&&r.event.startsWith(Lg)}var St=class r extends Error{constructor({requestId:e,drops:t,retryExhausted:n,cause:s}){super(r.buildMessage(e,t,n,s)),this.name="CaptureV1Error",this.requestId=e,this.drops=t,this.retryExhausted=n,this.cause=s}static buildMessage(e,t,n,s){let i=`Capture V1 batch ${e} did not fully deliver: ${t.length} dropped, ${n.length} undelivered`;return s instanceof Error&&(i+=` (${s.message})`),i}};function Ti(r){if(typeof r=="boolean")return r;if(typeof r=="number")return r!==0;if(typeof r=="string"){let e=r.trim().toLowerCase();if(e==="true"||e==="1")return!0;if(e==="false"||e==="0")return!1}}function Ng(r){return typeof r=="string"?r:void 0}var Ug=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:Ti},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:Ti},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:Ti},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:Ng}],$g=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function jg(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function Bg(r){if(typeof r=="string"){let t=new Date(r);if(Number.isNaN(t.getTime()))return new Date().toISOString();let n=t.toISOString(),s=r.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1];return s&&s.length>3?n.replace(/\.\d{3}Z$/,`.${s}Z`):n}if(r instanceof Date)return Number.isNaN(r.getTime())?new Date().toISOString():r.toISOString();let e=r==null?new Date:new Date(r);return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString()}function cl(r,e,t){t!==void 0&&!(e in r)&&(r[e]=t)}function Wg(r){let t={...jg(r.properties)?r.properties:{}},n={};for(let{property:i,optionKey:o,coerce:a}of Ug)if(i in t){let c=a(t[i]);c!==void 0&&(n[o]=c),delete t[i]}let s={};for(let{property:i,field:o}of $g)if(i in t){let a=t[i];typeof a=="string"&&(s[o]=a),delete t[i]}return delete t.$lib,delete t.$lib_version,cl(t,"$set",r.$set),cl(t,"$set_once",r.$set_once),{event:String(r.event??""),uuid:String(r.uuid??""),distinct_id:String(r.distinct_id??""),timestamp:Bg(r.timestamp),...s,options:n,properties:t}}function ll(r,{createdAt:e,historicalMigration:t}){let n={created_at:e,batch:r.map(Wg)};return t&&(n.historical_migration=!0),n}var Hg="/i/v1/analytics/events",Gg=3e4,Kg=new Set([408,500,502,503,504]),Nn=class{constructor(e,t){this.config=e,this.maxBackoffMs=e.maxBackoffMs??Gg,this.fetchFn=t.fetch,this.onError=t.onError,this.now=t.now??Date.now,this.sleep=t.sleep??(n=>new Promise(s=>B(s,n))),this.generateRequestId=t.generateRequestId??j,this.compress=t.compress??Ht}async sendV1Batch(e){if(e.length===0)return;let t=this.generateRequestId(),n=new Date(this.now()).toISOString(),{batch:s}=ll(e,{createdAt:n,historicalMigration:this.config.historicalMigration}),i=`${this.config.host}${Hg}`,o=[],a=s,c=Math.max(1,this.config.maxAttempts);for(let l=1;l<=c;l++){let u=l===c,d=De({created_at:n,...this.config.historicalMigration?{historical_migration:!0}:{},batch:a}),g,p;try{g=await this.sendOnce(i,d,l,t);let{response:h,signal:m}=g,{status:E}=h;if(E<200||E>=300)if(!u&&Kg.has(E)){let _=this.parseRetryAfter(h);await g.waitFor(g.cancelBody()).catch(()=>{}),p=this.backoffDelay(l,_)}else{let _=await this.buildHttpError(h,E,g.waitFor);return this.surfaceBatchFailure(t,o,a,_)}else{let _;try{_=await g.waitFor(this.parseResponse(h))}catch(R){if(m.aborted)throw R;return this.surfaceBatchFailure(t,o,a,new Error(`Capture V1 returned an unparseable ${E} response body`))}let b=this.classify(a,_,o);if(b.length===0)return this.surfacePartialDrops(t,o);if(u)return void this.onError(new St({requestId:t,drops:o,retryExhausted:b.map(R=>R.uuid)}));a=b;let P=this.parseRetryAfter(h);p=this.backoffDelay(l,P)}}catch(h){if(g&&!g.signal.aborted)throw h;if(u)return this.surfaceBatchFailure(t,o,a,h);p=this.backoffDelay(l)}finally{g?.cleanup()}p!==void 0&&await this.sleep(p)}}async sendOnce(e,t,n,s){let i=this.buildHeaders(n,s),o=t;if(this.config.compressionEnabled){let d=await this.compress(t,this.config.isDebug);d!==null&&(o=d,i["Content-Encoding"]="gzip")}let a=new AbortController,c="waiting for response headers",l,u=new Promise((d,g)=>{l=B(()=>{let p=new Error(`Capture V1 request timed out ${c} after ${this.config.requestTimeoutMs}ms`);p.name="AbortError",g(p),a.abort(p)},this.config.requestTimeoutMs)});try{let d=this.fetchFn(e,{method:"POST",headers:i,body:o,signal:a.signal}),g=!1;d.then(_=>{a.signal.aborted&&!g&&this.cancelBody(_)}).catch(()=>{});let p=await Promise.race([d,u]);g=!0,c="while reading the response body";let h=!1,m,E=()=>m??=this.cancelBody(p);return{response:p,signal:a.signal,waitFor:_=>Promise.race([_,u]),cancelBody:E,cleanup:()=>{h||(h=!0,clearTimeout(l),a.signal.aborted&&E())}}}catch(d){throw clearTimeout(l),d}}buildHeaders(e,t){let n=`${this.config.libraryId}/${this.config.libraryVersion}`,s={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"PostHog-Sdk-Info":n,"PostHog-Attempt":String(e),"PostHog-Request-Id":t,"PostHog-Request-Timestamp":new Date(this.now()).toISOString()};return this.config.userAgent&&(s["User-Agent"]=this.config.userAgent),s}classify(e,t,n){let s=t.results??{},i=[];for(let o of e){let a=s[o.uuid];a&&(a.result==="drop"?n.push({uuid:o.uuid,details:a.details??void 0}):a.result==="retry"&&i.push(o))}return i}backoffDelay(e,t){let n=Math.min(this.config.initialRetryDelayMs*2**(e-1),this.maxBackoffMs);return t===void 0?n:Math.max(n,Math.min(t,this.maxBackoffMs))}parseRetryAfter(e){let t=e.headers?.get("Retry-After");if(!t)return;let n=t.trim();if(/^\d+$/.test(n)){let o=parseInt(n,10);return Number.isFinite(o)&&o>0?1e3*o:void 0}let s=Date.parse(n);if(Number.isNaN(s))return;let i=s-this.now();return i>0?i:void 0}async parseResponse(e){let t=await e.text(),n=JSON.parse(t);if(typeof n!="object"||n===null||Array.isArray(n))throw new Error("unexpected response shape");let s=n.results;if(s!==void 0&&(typeof s!="object"||s===null||Array.isArray(s)))throw new Error("unexpected results shape");return{results:s??{}}}async buildHttpError(e,t,n){let s="";try{s=(await n(e.text())).slice(0,512)}catch{}let i=s?`: ${s}`:"";return new Error(`Capture V1 request failed with HTTP ${t}${i}`)}surfaceBatchFailure(e,t,n,s){this.onError(new St({requestId:e,drops:t,retryExhausted:n.map(i=>i.uuid),cause:s}))}surfacePartialDrops(e,t){t.length>0&&this.onError(new St({requestId:e,drops:t,retryExhausted:[]}))}async cancelBody(e){try{await e.body?.cancel()}catch{}}};var Qe="ai-capture",Un="/i/v0/ai/batch/";var qg=new TextEncoder;function Ii(r){return qg.encode(De(r)).length}function ul(r,e=8388608,t=5242880){let n=[],s=[],i=[],o=0;for(let a of r){if(a===void 0)continue;let c=Ii(a);if(c>e){s.push({event:typeof a.event=="string"?a.event:"unknown",bytes:c});continue}i.length>0&&o+c>t&&(n.push(i),i=[],o=0),i.push(a),o+=c}return i.length>0&&n.push(i),{batches:n,dropped:s}}var zg=100,dl=3e4,Yg=5e4,Jg=50,Xg=500,Qg="https://us.i.posthog.com",fl=new Set;function jn(r,e){fl.has(r)||(fl.add(r),console.warn(`[PostHog] ${e}`))}function Zg(r){return typeof r=="string"?r.trim():""}function eh(r){return(typeof r=="string"?r.trim():"")||void 0}function th(r){return(typeof r=="string"?r.trim():"")||Qg}function rh(r){return(Array.isArray(r)?r:[r]).filter(t=>typeof t=="string"&&t.trim().length>0)}function nh(r){if(!r)return{};let e={};for(let[n,s]of Object.entries(r))e[`$feature/${n}`]=s;let t=Object.keys(r).filter(n=>r[n]!==!1).sort();return t.length>0&&(e.$active_feature_flags=t),e}var Bn=class extends Gt{constructor(e,t={}){let n=Zg(e),s={...t,maxQueueSize:t.maxQueueSize??1e4,flushInterval:t.flushInterval??5e3,host:th(t.host),personalApiKey:eh(t.secretKey??t.personalApiKey)};if(super(n,s),this._memoryStorage=new Ln,this._aiCaptureRouteActive=!1,this._minimalFlagCalledEvents=!1,this.options=s,this.captureMode=ol(),this.enableFullAiCapture=s.enableFullAiCapture===!0,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof s.featureFlagsPollingInterval=="number"?Math.max(s.featureFlagsPollingInterval,zg):dl,typeof s.waitUntilDebounceMs=="number"&&(this.options.waitUntilDebounceMs=Math.max(s.waitUntilDebounceMs,0)),typeof s.waitUntilMaxWaitMs=="number"&&(this.options.waitUntilMaxWaitMs=Math.max(s.waitUntilMaxWaitMs,0)),!this.disabled&&s.personalApiKey){if(s.personalApiKey.includes("phc_"))throw new Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');s.enableLocalEvaluation!==!1&&(this.featureFlagsPoller=new Dn({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:s.personalApiKey,projectApiKey:n,timeout:s.requestTimeout??1e4,host:this.host,fetch:s.fetch,onError:o=>{this._events.emit("error",o)},onLoad:o=>{this._events.emit("localEvaluationFlagsLoaded",o)},onMinimalFlagCalledEvents:o=>{this._minimalFlagCalledEvents=o},customHeaders:this.getCustomHeaders(),cacheProvider:s.flagDefinitionCacheProvider,strictLocalEvaluation:s.strictLocalEvaluation,evaluationContexts:s.evaluationContexts??s.evaluationEnvironments}))}this.errorTracking=new Xe(this,s,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=s.maxCacheSize||Yg}enqueue(e,t,n,s){super.enqueue(e,t,n,s),this.scheduleDebouncedFlush()}_flushEventsAndSpans(e=!1){let t=this.flushWithPendingPromises();return!this._traces||e&&this._traces.throttled?t:Ot([t,this._traces.flush().catch(()=>{})]).then(([n])=>{if(n.status==="rejected")throw n.reason})}flushAutomatic(){return this._flushKeepingRuntimeAlive(!0)}async flush(){return this._flushKeepingRuntimeAlive(!1)}_flushKeepingRuntimeAlive(e){let t=this._flushEventsAndSpans(e),n=this.options.waitUntil;if(n&&!this._waitUntilCycle)try{n(t.catch(()=>{}))}catch{}return t}scheduleDebouncedFlush(){let e=this.options.waitUntil;if(!e||this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let o,a=new Promise(c=>{o=c});try{e(a)}catch{return}this._waitUntilCycle={resolve:o,startedAt:Date.now(),timer:void 0}}let t=Date.now()-this._waitUntilCycle.startedAt,n=this.options.waitUntilMaxWaitMs??Xg,s=t>=n;if(this._waitUntilCycle.timer!==void 0&&clearTimeout(this._waitUntilCycle.timer),s)return void this.resolveWaitUntilFlush();let i=this.options.waitUntilDebounceMs??Jg;this._waitUntilCycle.timer=B(()=>{this.resolveWaitUntilFlush()},i)}_consumeWaitUntilCycle(){let e=this._waitUntilCycle;return e&&(clearTimeout(e.timer),this._waitUntilCycle=void 0),e?.resolve}async resolveWaitUntilFlush(){let e=this._consumeWaitUntilCycle();try{await this._flushEventsAndSpans()}catch{}finally{e?.()}}getPersistedProperty(e){return this._memoryStorage.getProperty(e)}setPersistedProperty(e,t){return this._memoryStorage.setProperty(e,t)}fetch(e,t){return this.options.fetch?this.options.fetch(e,t):fetch(e,t)}getQueueRouteKey(e){return this.captureMode==="v1"&&al(e)?"ai":ir}persistedQueueKeyForRoute(e){return e===Qe?G.AiCaptureQueue:e==="ai"?G.AiQueue:G.Queue}getActiveQueueRoutes(){let e=this.captureMode==="v1"?[ir,"ai"]:[ir];return this._aiCaptureRouteActive&&e.push(Qe),e}getBatchEndpointPath(e){return e===Qe?Un:super.getBatchEndpointPath(e)}async sendBatch(e,t,n=ir){if(n===Qe)return this.sendAiCaptureBatch(e,t);if(this.captureMode!=="v1"||n==="ai")return super.sendBatch(e,t,n);let s=e.filter(i=>i!==void 0);await this.getV1Sender().sendV1Batch(s)}async sendAiCaptureBatch(e,t){let{batches:n,dropped:s}=ul(e);for(let{event:i,bytes:o}of s){let a=`Event ${i} (${o} bytes) exceeds the ${8388608/1048576}MiB limit for ${Un}, dropping.`;this._logger.error(a),this._events.emit("error",new Error(a))}for(let i of n)await this.sendAiSubBatch(i,t)}async sendAiSubBatch(e,t){try{await super.sendBatch(e,t,Qe)}catch(n){if(!ht(n))throw n;if(e.length===1){let[i]=e,a=`Event ${typeof i.event=="string"?i.event:"unknown"} (${Ii(i)} bytes) was rejected with 413 by ${Un} on its own, dropping.`;this._logger.error(a),this._events.emit("error",new Error(a));return}let s=Math.ceil(e.length/2);await this.sendAiSubBatch(e.slice(0,s),t),await this.sendAiSubBatch(e.slice(s),t)}}getV1Sender(){return this._v1Sender||(this._v1Sender=new Nn({host:this.host,apiKey:this.apiKey,libraryId:this.getLibraryId(),libraryVersion:this.getLibraryVersion(),userAgent:this.getCustomUserAgent()||void 0,historicalMigration:this.historicalMigration,compressionEnabled:!this.disableCompression,requestTimeoutMs:this.requestTimeout,maxAttempts:(this.options.fetchRetryCount??3)+1,initialRetryDelayMs:this.options.fetchRetryDelay??3e3,isDebug:this.isDebug},{fetch:(e,t)=>this.fetch(e,t),onError:e=>this._events.emit("error",e),compress:e=>this.compressPayload(e)})),this._v1Sender}getLibraryVersion(){return Xc}get metrics(){return this._metrics||(this._metrics=new Qt(this,wn(this.options.metrics),this._logger)),this._metrics}initializeSpanContextManager(){return new nr}hostResourceAttributes(){return{}}get _spanContextManager(){return this._spanContext||(this._spanContext=this.initializeSpanContextManager()),this._spanContext}get _tracesPipeline(){if(this.options.traces)return this._traces||(this._traces=new rr(this,yi(this.options.traces,this.hostResourceAttributes(),this._logger),this._logger,()=>this._tracingContext(),this._spanContextManager,()=>this.scheduleDebouncedFlush())),this._traces}_tracingContext(){let e=this.context?.get();return{distinctId:e?.distinctId,sessionId:e?.sessionId}}startSpan(e,t){return this._tracesPipeline?.startSpan(e,t)??Ne(t,this._spanContextManager.active())}withSpan(e,t,n){let s=typeof t=="function"?void 0:t,i=typeof t=="function"?t:n,o=this._tracesPipeline;return o?s?o.withSpan(e,s,i):o.withSpan(e,i):tr(this._spanContextManager,Ne(s,this._spanContextManager.active()),i)}getActiveSpan(){return this._spanContextManager.active()??null}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}getCommonEventProperties(){let e=super.getCommonEventProperties();return(this.options.isServer??!0)&&(e.$is_server=!0),e}enable(){return super.optIn()}disable(){return super.optOut()}debug(e=!0){super.debug(e),this.featureFlagsPoller?.debug(e)}_warnIfInvalidCapture(e,t,n){typeof e=="string"&&this._logger.warn(t),e.event==="$exception"&&!e._originatedFromCaptureException&&this._logger.warn(n)}_sendPreparedEvent(e,t,n,s,i){return this.addPendingPromise(this._prepareEventMessage(t,s).then(({distinctId:o,event:a,properties:c,options:l})=>{let u={timestamp:l.timestamp,disableGeoip:l.disableGeoip,uuid:l.uuid},d={distinctId:o,event:a,properties:{...c,...this.getCommonEventProperties()}};return n?this.sendImmediate(e,d,u,i):this.enqueue(e,d,u,i)}).catch(o=>{o&&console.error(o)}))}_capturePreparedEvent(e,t){return this._sendPreparedEvent("capture",e,t)}capture(e){this._warnIfInvalidCapture(e,"Called capture() with a string as the first argument when an object was expected.","Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this._capturePreparedEvent(e,!1)}async captureImmediate(e){return this._warnIfInvalidCapture(e,"Called captureImmediate() with a string as the first argument when an object was expected.","Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default."),this._capturePreparedEvent(e,!0)}captureAi(e){if(this.disabled)return;let t=Ve(e.uuid,j);return this._sendPreparedAiEvent({...e,uuid:t},!1),t}async captureAiImmediate(e){if(this.disabled)return;let t=Ve(e.uuid,j);return await this._sendPreparedAiEvent({...e,uuid:t},!0),t}_sendPreparedAiEvent(e,t){return typeof e?.event=="string"&&!e.event.startsWith("$ai_")&&this._logger.debug(`captureAi called with non-AI event ${e.event}; routing it to the AI endpoint anyway.`),this._aiCaptureRouteActive=!0,this._sendPreparedEvent("capture",e,t,void 0,Qe)}identify({distinctId:e,properties:t={},disableGeoip:n}){let{$set:s,$set_once:i,$anon_distinct_id:o,...a}=t,u={$set:s||a,$set_once:i||{},$anon_distinct_id:o??void 0};this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:u,disableGeoip:n},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:e,properties:t={},disableGeoip:n}){let{$set:s,$set_once:i,$anon_distinct_id:o,...a}=t,u={$set:s||a,$set_once:i||{},$anon_distinct_id:o??void 0};await this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:u,disableGeoip:n},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:e,properties:t={},propertiesOnce:n={}}){if(Object.keys(t).length===0&&Object.keys(n).length===0)return;let s={};Object.keys(t).length>0&&(s.$set=t),Object.keys(n).length>0&&(s.$set_once=n),this.capture({distinctId:e,event:"$set",properties:s})}unsetPersonProperties({distinctId:e,properties:t}){let n=rh(t);n.length!==0&&this.capture({distinctId:e,event:"$set",properties:{$unset:n}})}alias(e){this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!1,{includeContextProperties:!1})}async aliasImmediate(e){await this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!0,{includeContextProperties:!1})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(e=dl){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(t=>{let n=setTimeout(()=>{s(),t(!1)},e),s=this._events.on("localEvaluationFlagsLoaded",i=>{clearTimeout(n),s(),t(i>0)})})}_resolveDistinctId(e,t){return typeof e=="string"?{distinctId:e,options:t}:{distinctId:this.context?.get()?.distinctId,options:e}}async _getFeatureFlagResult(e,t,n={},s){if(this.disabled)return void this._logger.warn("The client is disabled");let i=n.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&e in this._flagOverrides){let y=this._flagOverrides[e];if(y===void 0)return;let v=this._payloadOverrides?.[e];return{key:e,enabled:y!==!1,variant:typeof y=="string"?y:void 0,payload:v}}let{groups:o,disableGeoip:a}=n,{onlyEvaluateLocally:c,personProperties:l,groupProperties:u}=n,d=this.addLocalPersonAndGroupProperties(t,o,l,u);l=d.allPersonProperties,u=d.allGroupProperties;let g=this.createFeatureFlagEvaluationContext(t,o,this.personPropertiesForLocalEvaluation(t,l),u);c==null&&(c=this.options.strictLocalEvaluation??!1);let p,h=!1,m,E,_,b,P,R,O;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let y=this.featureFlagsPoller?.featureFlagsByKey[e];if(y)try{let v=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(y,g,{matchValue:s});if(v){h=!0;let w=v.value;b=y.id,R="Evaluated locally",O=y.has_experiment,p={key:e,enabled:w!==!1,variant:typeof w=="string"?w:void 0,payload:v.payload??void 0}}}catch(v){if(v instanceof de||v instanceof S)this._logger?.info(`${v.name} when computing flag locally: ${e}: ${v.message}`);else throw v}}if(!h&&!c){let y=await super.getFeatureFlagDetailsStateless(g.distinctId,g.groups,l,u,a,[e]);if(y===void 0)_=Ie.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=y.minimalFlagCalledEvents===!0,m=y.requestId,E=y.evaluatedAt;let v=[];y.errorsWhileComputingFlags&&v.push(Ie.ERRORS_WHILE_COMPUTING),y.quotaLimited?.includes("feature_flags")&&v.push(Ie.QUOTA_LIMITED);let w=y.flags[e];if(w===void 0)v.push(Ie.FLAG_MISSING);else{b=w.metadata?.id,P=w.metadata?.version,R=w.reason?.description??w.reason?.code,O=w.metadata?.has_experiment;let je;if(w.metadata?.payload!==void 0)try{je=JSON.parse(w.metadata.payload)}catch{je=w.metadata.payload}p={key:e,enabled:w.enabled,variant:w.variant??void 0,payload:je}}v.length>0&&(_=v.join(","))}}if(i){let y=p===void 0?void 0:p.enabled===!1?!1:p.variant??!0,v={$feature_flag:e,$feature_flag_response:y,$feature_flag_id:b,$feature_flag_version:P,$feature_flag_reason:R,locally_evaluated:h,[`$feature/${e}`]:y,$feature_flag_request_id:m,$feature_flag_evaluated_at:h?Date.now():E};if(O!==void 0&&(v.$feature_flag_has_experiment=O),h&&this.featureFlagsPoller){let w=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();w!==void 0&&(v.$feature_flag_definitions_loaded_at=w)}_&&(v.$feature_flag_error=_),this._captureFlagCalledEventIfNeeded({distinctId:t,key:e,response:y,groups:o,disableGeoip:a,properties:v})}return p!==void 0&&this._payloadOverrides!==void 0&&e in this._payloadOverrides&&(p={...p,payload:this._payloadOverrides[e]}),p}async getFeatureFlag(e,t,n){jn("getFeatureFlag","`getFeatureFlag` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlag(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let s=await this._getFeatureFlagResult(e,t,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(s!==void 0)return s.enabled===!1?!1:s.variant??!0}async getFeatureFlagPayload(e,t,n,s){if(jn("getFeatureFlagPayload","`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request."),this._payloadOverrides!==void 0&&e in this._payloadOverrides)return this._payloadOverrides[e];let i=await this._getFeatureFlagResult(e,t,{...s,sendFeatureFlagEvents:!1},n);if(i!==void 0)return i.payload??null}async getFeatureFlagResult(e,t,n){let{distinctId:s,options:i}=this._resolveDistinctId(t,n);return s?this._getFeatureFlagResult(e,s,{...i,sendFeatureFlagEvents:i?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0}):void this._logger.warn("[PostHog] distinctId is required \u2014 pass it explicitly or use withContext()")}async getRemoteConfigPayload(e){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this.options.personalApiKey)throw new Error("Personal API key is required for remote config payload decryption");let t=await this._requestRemoteConfigPayload(e);if(!t)return;let n=await t.json();if(typeof n=="string")try{return JSON.parse(n)}catch{}return n}async isFeatureEnabled(e,t,n){jn("isFeatureEnabled","`isFeatureEnabled` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.isEnabled(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let s=await this._getFeatureFlagResult(e,t,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});return s===void 0?void 0:s.enabled===!1?!1:!!(s.variant??!0)||!1}async getAllFlags(e,t){let{distinctId:n,options:s}=this._resolveDistinctId(e,t);return n?(await this.getAllFlagsAndPayloads(n,s)).featureFlags||{}:(this._logger.warn("[PostHog] distinctId is required to get feature flags \u2014 pass it explicitly or use withContext()"),{})}async getAllFlagsAndPayloads(e,t){let{distinctId:n,options:s}=this._resolveDistinctId(e,t);if(!n)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads \u2014 pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};if(this.disabled)return this._logger.warn("The client is disabled"),{featureFlags:{},featureFlagPayloads:{}};let{groups:i,disableGeoip:o,flagKeys:a}=s||{},{onlyEvaluateLocally:c,personProperties:l,groupProperties:u}=s||{},d=this.addLocalPersonAndGroupProperties(n,i,l,u);l=d.allPersonProperties,u=d.allGroupProperties;let g=this.createFeatureFlagEvaluationContext(n,i,this.personPropertiesForLocalEvaluation(n,l),u);c==null&&(c=this.options.strictLocalEvaluation??!1);let p=await this.featureFlagsPoller?.getAllFlagsAndPayloads(g,a),h={},m={},E=!0;if(p&&(h=p.response,m=p.payloads,E=p.fallbackToFlags),E&&!c){let _=await super.getFeatureFlagsAndPayloadsStateless(g.distinctId,g.groups,l,u,o,a);h={...h,..._.flags||{}},m={...m,..._.payloads||{}}}return this._flagOverrides!==void 0&&(h={...h,...this._flagOverrides}),this._payloadOverrides!==void 0&&(m={...m,...this._payloadOverrides}),{featureFlags:h,featureFlagPayloads:m}}async evaluateFlags(e,t){let{distinctId:n,options:s}=this._resolveDistinctId(e,t);if(!n)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags \u2014 pass it explicitly or use withContext()"),new $e({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new $e({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,flags:{}});let{groups:i,disableGeoip:o}=s||{},a=s?.flagKeys??void 0;if(a?.length===0)return new $e({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:i,disableGeoip:o,flags:{}});let{onlyEvaluateLocally:c,personProperties:l,groupProperties:u}=s||{},d=this.addLocalPersonAndGroupProperties(n,i,l,u);l=d.allPersonProperties,u=d.allGroupProperties;let g=this.createFeatureFlagEvaluationContext(n,i,this.personPropertiesForLocalEvaluation(n,l),u);c==null&&(c=this.options.strictLocalEvaluation??!1);let p=a?new Set(a):void 0,h={},m,E,_=!1,b=!1,P=await this.featureFlagsPoller?.getAllFlagsAndPayloads(g,a),R=new Set;if(P)for(let[y,v]of Object.entries(P.response)){let w=this.featureFlagsPoller?.featureFlagsByKey[y];h[y]={key:y,enabled:v!==!1,variant:typeof v=="string"?v:void 0,payload:P.payloads[y],id:w?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:w?.has_experiment},R.add(y)}let O=p!==void 0&&Array.from(p).some(y=>this.featureFlagsPoller?.featureFlagsByKey[y]===void 0);if((P?P.fallbackToFlags||O:!0)&&!c){let y=await super.getFeatureFlagDetailsStateless(g.distinctId,g.groups,l,u,o,a);if(y){this._minimalFlagCalledEvents=y.minimalFlagCalledEvents===!0,m=y.requestId,E=y.evaluatedAt,_=!!y.errorsWhileComputingFlags,b=Array.isArray(y.quotaLimited)&&y.quotaLimited.includes("feature_flags");for(let[v,w]of Object.entries(y.flags)){if(R.has(v))continue;let je;if(w.metadata?.payload!==void 0)try{je=JSON.parse(w.metadata.payload)}catch{je=w.metadata.payload}h[v]={key:v,enabled:w.enabled,variant:w.variant,payload:je,id:w.metadata?.id,version:w.metadata?.version,reason:w.reason?.description??w.reason?.code,locallyEvaluated:!1,hasExperiment:w.metadata?.has_experiment}}}}if(this._flagOverrides!==void 0)for(let[y,v]of Object.entries(this._flagOverrides)){if(v===void 0){delete h[y];continue}let w=h[y];h[y]={key:y,enabled:v!==!1,variant:typeof v=="string"?v:void 0,payload:w?.payload,id:w?.id,version:w?.version,reason:w?.reason,locallyEvaluated:w?.locallyEvaluated??!1,hasExperiment:w?.hasExperiment}}if(this._payloadOverrides!==void 0)for(let[y,v]of Object.entries(this._payloadOverrides)){let w=h[y];w&&(h[y]={...w,payload:v})}if(p!==void 0)for(let y of Object.keys(h))p.has(y)||delete h[y];return new $e({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:i,disableGeoip:o,flags:h,requestId:m,evaluatedAt:E,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:_,quotaLimited:b})}_shouldSendMinimalFlagCalledEvent(e,t){return e==="$feature_flag_called"&&this._minimalFlagCalledEvents&&t.$feature_flag_has_experiment===!1}_captureFlagCalledEventIfNeeded(e){let{distinctId:t,key:n,response:s,groups:i,disableGeoip:o,properties:a}=e,c=i&&Object.keys(i).length>0?`_${JSON.stringify(Object.entries(i).sort(([u],[d])=>u<d?-1:u>d?1:0))}`:"",l=`${n}_${s}${c}`;t in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[t].has(l)||(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),this.distinctIdHasSentFlagCalls[t]instanceof Set?this.distinctIdHasSentFlagCalls[t].add(l):this.distinctIdHasSentFlagCalls[t]=new Set([l]),this.capture({distinctId:t,event:"$feature_flag_called",properties:a,groups:i,disableGeoip:o}))}_getFeatureFlagEvaluationsHost(){return this._featureFlagEvaluationsHost||(this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:e=>this._captureFlagCalledEventIfNeeded(e),logWarning:e=>{this.options.featureFlagsLogWarnings!==!1&&console.warn(`[PostHog] ${e}`)}}),this._featureFlagEvaluationsHost}groupIdentify({groupType:e,groupKey:t,properties:n,distinctId:s,disableGeoip:i}){this._sendPreparedEvent("capture",{distinctId:s||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:n||{}},disableGeoip:i},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:e,groupKey:t,properties:n,distinctId:s,disableGeoip:i}){await this._sendPreparedEvent("capture",{distinctId:s||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:n||{}},disableGeoip:i},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(e){let t=n=>Object.fromEntries(n.map(s=>[s,!0]));if(e===!1){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(e)){this._flagOverrides=t(e);return}if(this._isFeatureFlagOverrideOptions(e)){"flags"in e&&(e.flags===!1?this._flagOverrides=void 0:Array.isArray(e.flags)?this._flagOverrides=t(e.flags):e.flags!==void 0&&(this._flagOverrides={...e.flags})),"payloads"in e&&(e.payloads===!1?this._payloadOverrides=void 0:e.payloads!==void 0&&(this._payloadOverrides={...e.payloads}));return}this._flagOverrides={...e}}_isFeatureFlagOverrideOptions(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;if("flags"in t){let n=t.flags;if(n===!1||Array.isArray(n)||typeof n=="object"&&n!==null)return!0}if("payloads"in t){let n=t.payloads;if(n===!1||typeof n=="object"&&n!==null)return!0}return!1}withContext(e,t,n){return this.context?this.context.run(e,t,n):t()}getContext(){return this.context?.get()}enterContext(e,t){this.context?.enter(e,t)}async _shutdown(e){let t=Date.now()+(e??3e4),n=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(e),this.errorTracking.shutdown(),this._metrics&&(await Le(this._metrics.flush().catch(()=>{}),Math.max(0,t-Date.now())),this._metrics.reset()),this._traces&&(await Le(this._traces.flush().catch(()=>{}),Math.max(0,t-Date.now())),this._traces.reset());try{return await super._shutdown(Math.max(0,t-Date.now()))}finally{this.distinctIdHasSentFlagCalls={},n?.()}}async _requestRemoteConfigPayload(e){if(this.disabled||!this.apiKey||!this.options.personalApiKey)return;let t=`${this.host}/api/projects/@current/feature_flags/${e}/remote_config?token=${encodeURIComponent(this.apiKey)}`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},s=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let i=new AbortController;s=B(()=>{i.abort()},this.options.requestTimeout),n.signal=i.signal}try{return await this.fetch(t,n)}catch(i){this._events.emit("error",i);return}finally{s&&clearTimeout(s)}}extractPropertiesFromEvent(e,t){if(!e)return{personProperties:{},groupProperties:{}};let n={},s={};for(let[i,o]of Object.entries(e))if(pa(o)&&t&&i in t){let a={};for(let[c,l]of Object.entries(o))a[String(c)]=String(l);s[String(i)]=a}else n[String(i)]=String(o);return{personProperties:n,groupProperties:s}}async getFeatureFlagsForEvent(e,t,n,s){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let i=s?.personProperties||{},o=s?.groupProperties||{},a=s?.flagKeys;if(s?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let l={};for(let[u,d]of Object.entries(t||{}))l[u]=String(d);return await this.getAllFlags(e,{groups:l,personProperties:i,groupProperties:o,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let l={};for(let[u,d]of Object.entries(t||{}))l[u]=String(d);return await this.getAllFlags(e,{groups:l,personProperties:i,groupProperties:o,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}return(await super.getFeatureFlagsStateless(e,t,i,o,n)).flags}addLocalPersonAndGroupProperties(e,t,n,s){let i={...n||{}},o={};if(t)for(let a of Object.keys(t))o[a]={$group_key:t[a],...s?.[a]||{}};return{allPersonProperties:i,allGroupProperties:o}}personPropertiesForLocalEvaluation(e,t){return{distinct_id:e,...t||{}}}createFeatureFlagEvaluationContext(e,t,n,s){return{distinctId:e,groups:t||{},personProperties:n||{},groupProperties:s||{},evaluationCache:{}}}captureException(e,t,n,s,i){if(!Xe.isPreviouslyCapturedError(e)){let o=new Error("PostHog syntheticException");this.addPendingPromise(Xe.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:o},t,n).then(a=>this._capturePreparedEvent({...a,uuid:s,flags:i},!1)))}}async captureExceptionImmediate(e,t,n,s){if(!Xe.isPreviouslyCapturedError(e)){let i=new Error("PostHog syntheticException");return this.addPendingPromise(Xe.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:i},t,n).then(o=>this.captureImmediate({...o,flags:s})))}}async prepareEventMessage(e){return this._prepareEventMessage(e)}async _prepareEventMessage(e,t={}){let{distinctId:n,event:s,properties:i,groups:o,flags:a,sendFeatureFlags:c,timestamp:l,disableGeoip:u,uuid:d}=e,g=this.context?.get(),p=t.includeContextProperties??!0,h=n||g?.distinctId,m=p?{...this.props,...g?.properties||{},...i||{}}:{...i||{}};h||(h=j(),m.$process_person_profile=!1),p&&g?.sessionId&&!m.$session_id&&(m.$session_id=g.sessionId);let E=this._shouldSendMinimalFlagCalledEvent(s,m)?Bt(m):m,_=this._runBeforeSend({distinctId:h,event:s,properties:E,groups:o,flags:a,sendFeatureFlags:c,timestamp:l,disableGeoip:u,uuid:d});if(!_)return Promise.reject(null);let b=await Promise.resolve().then(async()=>{if(a)return c&&console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`."),a._getEventProperties();if(c){jn("sendFeatureFlags","`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead \u2014 it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");let P=typeof c=="object"?c:void 0,R=await this.getFeatureFlagsForEvent(_.distinctId,o,u,P);return nh(R)}return{}}).catch(()=>({})).then(P=>{let R=_.groups||o;return{...P,..._.properties||{},...R!==void 0&&Object.keys(R).length>0?{$groups:R}:{}}});return _.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof b.$raw_user_agent=="string"&&ha(b.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(_.event="$bot_pageview",b.$browser_type="bot"),{distinctId:_.distinctId,event:_.event,properties:b,options:{timestamp:_.timestamp,disableGeoip:_.disableGeoip,uuid:_.uuid}}}_runBeforeSend(e){let t=this.options.before_send;if(!t)return e;let n=Array.isArray(t)?t:[t],s=e;for(let i of n)try{if(s=i(s),!s)return this._logger.info(`Event '${e.event}' was rejected in beforeSend function`),null;if(!s.properties||Object.keys(s.properties).length===0){let o=`Event '${s.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(o)}}catch(o){return this._logger.error(`Error in before_send function for event '${e.event}':`,o),null}return s}};var pl=require("node:async_hooks"),Wn=class{constructor(){this.storage=new pl.AsyncLocalStorage}get(){return this.storage.getStore()}run(e,t,n){return this.storage.run(this.resolve(e,n),t)}enter(e,t){this.storage.enterWith(this.resolve(e,t))}resolve(e,t){if(t?.fresh===!0)return e;let n=this.get()||{};return{distinctId:e.distinctId??n.distinctId,sessionId:e.sessionId??n.sessionId,properties:{...n.properties||{},...e.properties||{}}}}};var gl=require("node:async_hooks"),Hn=class{active(){return this._storage.getStore()}with(e,t){return this._storage.run(e,t)}constructor(){this._storage=new gl.AsyncLocalStorage}};var hl=require("node:zlib"),ml=require("node:util"),sh=(0,ml.promisify)(hl.gzip);async function _l(r,e=!0){try{let t=await sh(r);return new Uint8Array(t)}catch(t){return e&&console.error("Failed to gzip compress data",t),null}}var Gn=require("node:os");function El(){let r,e;try{r=(0,Gn.platform)(),e=(0,Gn.release)()}catch{}return ci(r,e)}var yl="posthog-node";function ih(r,{organization:e,projectId:t,prefix:n,severityAllowList:s=["error"],sendExceptionsToPostHog:i=!0}={}){return o=>{if(!(s==="*"||s.includes(o.level)))return o;o.tags||(o.tags={});let c=o.tags[Ri.POSTHOG_ID_TAG];if(c===void 0)return o;let l=r.options.host??"https://us.i.posthog.com",u=new URL(`/project/${r.apiKey}/person/${c}`,l).toString();o.tags["PostHog Person URL"]=u;let d=o.exception?.values||[],g=d.map(m=>({...m,stacktrace:m.stacktrace?{...m.stacktrace,type:"raw",frames:(m.stacktrace.frames||[]).map(E=>({...E,platform:"node:javascript"}))}:void 0})),p={$exception_message:d[0]?.value||o.message,$exception_type:d[0]?.type,$exception_level:o.level,$exception_list:g,$sentry_event_id:o.event_id,$sentry_exception:o.exception,$sentry_exception_message:d[0]?.value||o.message,$sentry_exception_type:d[0]?.type,$sentry_tags:o.tags},h=D.getInjectedReleaseId();return h&&(p.$release_id=h),e&&t&&(p.$sentry_url=(n||"https://sentry.io/organizations/")+e+"/issues/?project="+t+"&query="+o.event_id),i&&r.capture({event:"$exception",distinctId:c,properties:p}),o}}var Ri=class{static{this.POSTHOG_ID_TAG="posthog_distinct_id"}constructor(e,t,n,s,i){this.name=yl,this.name=yl,this.setupOnce=function(o,a){let c=a()?.getClient()?.getDsn()?.projectId;o(ih(e,{organization:t,projectId:c,prefix:n,severityAllowList:s,sendExceptionsToPostHog:i??!0}))}}};var Kn=class extends Bn{getLibraryId(){return"posthog-node"}compressPayload(e){return _l(e,this.isDebug)}initializeContext(){return new Wn}initializeSpanContextManager(){return new Hn}hostResourceAttributes(){return El()}createErrorPropertiesBuilder(){return new D.ErrorPropertiesBuilder([new D.EventCoercer,new D.ErrorCoercer,new D.ObjectCoercer,new D.StringCoercer,new D.PrimitiveCoercer],D.createStackParser("node:javascript",D.nodeStackLineParser),[ca(),e=>Vc(e,void 0,this._logger),Jc()])}};var wl=pe(require("os"),1);A();var Sl=500;var bl=8192,fe="[REDACTED]";function vl(r){try{if(typeof r!="string"){if(r==null)return"";try{r=String(r)}catch(t){let n=t instanceof Error?t:new Error(String(t));return f.warn("SYSTEM","error-scrub: String() coercion of non-string input failed",void 0,n),""}}let e=r;return e.length>bl?e.slice(0,bl):e}catch{return""}}function Ci(r){if(typeof r!="string"||r.length===0)return r??"";let e="";try{e=wl.default.homedir()||""}catch(n){let s=n instanceof Error?n:new Error(String(n));f.warn("SYSTEM","error-scrub: os.homedir() failed; skipping home-dir redaction",void 0,s),e=""}if(!e)return r;let t=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");try{return r.replace(new RegExp(t,"g"),"~")}catch(n){let s=n instanceof Error?n:new Error(String(n));return f.warn("SYSTEM","error-scrub: home-dir RegExp replace failed; using split/join fallback",void 0,s),r.split(e).join("~")}}function Mi(r){return typeof r!="string"||r.length===0?r??"":r.replace(/(?<![~\w])\/(?:[^\s/:"'()]+\/)+([^\s/:"'()]+)/g,"$1").replace(/[A-Za-z]:\\(?:[^\s\\:"'()]+\\)*([^\s\\:"'()]+)/g,"$1").replace(/\\\\[^\s\\:"'()]+(?:\\[^\s\\:"'()]+)*\\([^\s\\:"'()]+)/g,"$1")}function oh(r){return typeof r!="string"||r.length===0?r??"":r.replace(/\b[A-Za-z][A-Za-z0-9+.-]*:\/\/[^\s"'()]+/g,e=>e.replace(/[?#].*$/,"").replace(/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)[^/@\s]+@/,`$1${fe}@`))}function ah(r){if(typeof r!="string"||r.length===0)return r??"";let e=r;return e=e.replace(/[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,255}\.[A-Za-z]{2,24}/g,fe),e=e.replace(/\b[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\b/g,fe),e=e.replace(/\b(?:sk|pk|rk|ak|phc|phx|ph|ghp|gho|ghs|xox[bpasr])[-_][A-Za-z0-9_-]{8,512}\b/gi,fe),e=e.replace(/\bBearer\s+[A-Za-z0-9._-]{8,512}\b/gi,fe),e=e.replace(/\b(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA|ANVA|AIPA)[0-9A-Z]{16}\b/g,fe),e=e.replace(/\b[0-9a-fA-F]{24,4096}\b/g,fe),e=e.replace(/\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b/g,fe),e=e.replace(/\b(?=[A-Za-z0-9+/_-]{0,4096}\d)[A-Za-z0-9+/_-]{32,4096}={0,2}\b/g,fe),e=e.replace(/\b(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}\b/g,fe),e}function ch(r){return typeof r!="string"||r.length===0?r??"":r.replace(/[ \t\f\v]+/g," ").replace(/ *\n */g,`
33
+ `).trim()}function lh(r){let e=vl(r);return e.length===0?"":(e=Ci(e),e=Mi(e),e=oh(e),e=ah(e),e)}function Al(r){try{let e=ch(lh(vl(r)));return e.length>Sl?e.slice(0,Sl):e}catch(e){let t=e instanceof Error?e:new Error(String(e));return f.warn("SYSTEM","error-scrub: message scrub failed; emitting empty message",void 0,t),""}}function Tl(r){return(typeof r=="string"?r:"").replace(/\[REDACTED\]/g,"\xA7").replace(/'[^']*'/g,"'\xA7'").replace(/"[^"]*"/g,'"\xA7"').replace(/\b\d+\b/g,"\xA7").replace(/[ \t]+/g," ").trim().slice(0,200)}var hT=300*1e3,mT=3600*1e3;A();var Fi=null,uh=!1,dh=3e4,Vn=null;function Il(){let r=Date.now();if(Vn&&r<Vn.expiresAt)return Vn.value;let e=Pr(process.env,Rt());return Vn={value:e,expiresAt:r+dh},e}var fh=!1;function ph(){if(!Fi){let r=fh&&fo(process.env)&&Il();Fi=new Kn(Cr(),{host:Mr(),flushAt:20,flushInterval:1e4,disableGeoip:!1,enableExceptionAutocapture:r,before_send:bh})}return Fi}var gh=6e4,hh=500,or=new Map;function mh(r,e,t){let n="";try{let s=(t||"").split(`
34
+ `).map(i=>i.trim()).filter(Boolean);n=s.find(i=>i.startsWith("at "))??s[1]??""}catch(s){let i=s instanceof Error?s:new Error(String(s));f.warn("SYSTEM","Telemetry: stack parse failed while fingerprinting; using empty top frame",void 0,i),n=""}return`${r}::${Tl(e)}::${n}`.slice(0,400)}function _h(r,e){try{return Eh(r,e)}catch(t){let n=t instanceof Error?t:new Error(String(t));return f.warn("SYSTEM","Telemetry: error rate-limit bookkeeping failed; failing closed (event dropped)",void 0,n),{send:!1,count:0}}}function Eh(r,e){let t=or.get(r);if(!t){if(or.size>=hh){let n=null,s=1/0;for(let[i,o]of or){let a=Math.max(o.lastSentTs,o.firstTs);a<s&&(s=a,n=i)}n!==null&&or.delete(n)}return t={count:1,firstTs:e,lastSentTs:e},or.set(r,t),{send:!0,count:1}}if(t.count+=1,e-t.lastSentTs>=gh){t.lastSentTs=e;let n=t.count;return t.count=0,{send:!0,count:n}}return{send:!1,count:t.count}}var Pl="__cm_rate_limited";function yh(r){try{return typeof r!="string"||r.length===0?"":Mi(Ci(r))}catch(e){let t=e instanceof Error?e:new Error(String(e));return f.warn("SYSTEM","Telemetry: frame filename redaction failed; stripping value entirely",void 0,t),""}}function Sh(r){let e=r.$exception_list;if(Array.isArray(e))for(let t of e){if(!t||typeof t!="object")continue;let n=t;typeof n.value=="string"&&(n.value=Al(n.value));let i=n.stacktrace?.frames;if(Array.isArray(i))for(let o of i){if(!o||typeof o!="object")continue;let a=o;delete a.context_line,delete a.pre_context,delete a.post_context,typeof a.filename=="string"&&(a.filename=yh(a.filename))}}}function bh(r){try{if(!r||typeof r!="object")return r;let e=r;if(e.event!=="$exception")return r;let t=e.properties??{};if(t[Pl]){try{delete t[Pl],e.properties=t}catch{}return r}Sh(t),t.$process_person_profile=!1,e.properties=t;let n="Error",s="",i="";try{let c=t.$exception_list;if(Array.isArray(c)&&c[0]&&typeof c[0]=="object"){let l=c[0];typeof l.type=="string"&&(n=l.type),typeof l.value=="string"&&(s=l.value);let u=l.stacktrace?.frames;Array.isArray(u)&&u.length>0&&(i="at "+JSON.stringify(u[u.length-1]).slice(0,200))}}catch{}typeof t.$exception_type=="string"&&(n=t.$exception_type),typeof t.$exception_message=="string"&&(s=t.$exception_message);let o=mh(n,s,i),a=_h(o,Date.now());if(!a.send)return null;try{t.occurrence_count=a.count,e.properties=t}catch{}return r}catch{return null}}function xi(r,e,t){try{wh(r,e,t)}catch(n){let s=n instanceof Error?n:new Error(String(n));f.warn("SYSTEM","Telemetry: captureEvent failed; event dropped",{event:r},s)}}function wh(r,e,t){if(uh||!Il())return;let n=Rr({...Fr(),...e??{}});if(t?.person?n.$set=xr(n):n.$process_person_profile=!1,process.env.CLAUDE_MEM_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:r,properties:n})+`
35
+ `);return}ph().capture({distinctId:Ir(),event:r,properties:n})}var vh=["babysit","ccs-align","cloud-sync","design-is","do","how-it-works","knowledge-agent","learn-codebase","make-plan","mem-search","mode-creator","oh-my-issues","pathfinder","smart-explore","standup","timeline-report","version-bump","weekly-digests","what-the","wowerpoint"],Ah=new Set(vh),Rl={skill_id:"other",skill_source:"third_party"};function Cl(r){let e=Th(r);return e&&Ah.has(e)?{skill_id:e,skill_source:"first_party"}:Rl}function Ml(r,e){if(r==="Skill"&&!(!e||typeof e!="object"))return e.skill}function Th(r){if(typeof r!="string")return null;let e=r.trim().toLowerCase();if(!e)return null;e=e.replace(/^\/+/,"");let t=e.lastIndexOf(":");return t!==-1&&(e=e.slice(t+1).replace(/^\/+/,"")),e||null}var xl=null;function Ph(){if(!xl)throw new Error("ingest helpers used before setIngestContext() \u2014 wiring bug");return xl}async function Fl(r){let{sessionManager:e,dbManager:t,eventBroadcaster:n,ensureGeneratorRunning:s}=Ph(),i=ae(r.platformSource),o=typeof r.cwd=="string"?r.cwd:"",a=o.trim()?He(o).primary:"",c=q.loadFromFile(tt);if(o&&Vr(o,c.CLAUDE_MEM_EXCLUDED_PROJECTS))return{ok:!0,status:"skipped",reason:"project_excluded"};if(new Set(c.CLAUDE_MEM_SKIP_TOOLS.split(",").map(_=>_.trim()).filter(Boolean)).has(r.toolName)){if(r.toolName==="Skill"){let{skill_id:_,skill_source:b}=Cl(Ml(r.toolName,r.toolInput));xi("skill_invoked",{skill_id:_,skill_source:b,skill_trigger:"tool",ide:i})}return{ok:!0,status:"skipped",reason:"tool_excluded"}}if(new Set(["Edit","Write","Read","NotebookEdit"]).has(r.toolName)&&r.toolInput&&typeof r.toolInput=="object"){let _=r.toolInput,b=_.file_path||_.notebook_path;if(b&&b.includes("session-memory"))return{ok:!0,status:"skipped",reason:"session_memory_meta"}}let d=t.getSessionStore(),g,p;try{g=d.createSDKSession(r.contentSessionId,a,"",void 0,i),p=d.getPromptNumberFromUserPrompts(r.contentSessionId,g)}catch(_){let b=_ instanceof Error?_.message:String(_);return f.error("INGEST","Observation session resolution failed",{contentSessionId:r.contentSessionId,toolName:r.toolName},_ instanceof Error?_:new Error(b)),{ok:!1,reason:b,status:500}}if(!Jr.checkUserPromptPrivacy(d,r.contentSessionId,p,"observation",g,{tool_name:r.toolName}).allow)return{ok:!0,status:"skipped",reason:"private"};let m=r.toolInput!==void 0?Ts(JSON.stringify(r.toolInput)):"{}",E=r.toolResponse!==void 0?Ts(JSON.stringify(r.toolResponse)):"{}";if(r.toolUseId)try{d.upsertToolUse({toolUseId:r.toolUseId,contentSessionId:r.contentSessionId,sessionDbId:g,project:a,platformSource:i,toolName:r.toolName,toolInput:m,toolResponse:E,cwd:o||null,promptNumber:p,agentType:typeof r.agentType=="string"?r.agentType:null,agentId:typeof r.agentId=="string"?r.agentId:null,orGenerationId:typeof r.orGenerationId=="string"?r.orGenerationId:null,orSessionId:typeof r.orSessionId=="string"?r.orSessionId:null})}catch(_){f.warn("INGEST","tool_uses backup write failed (observation still queued)",{sessionId:g,toolName:r.toolName,toolUseId:r.toolUseId},_ instanceof Error?_:new Error(String(_)))}return await e.queueObservation(g,{tool_name:r.toolName,tool_input:m,tool_response:E,prompt_number:p,cwd:o||(f.error("INGEST","Missing cwd when ingesting observation",{sessionId:g,toolName:r.toolName}),""),agentId:typeof r.agentId=="string"?r.agentId:void 0,agentType:typeof r.agentType=="string"?r.agentType:void 0,toolUseId:typeof r.toolUseId=="string"?r.toolUseId:void 0}),await s?.(g,"observation"),n.broadcastObservationQueued(g),{ok:!0,sessionDbId:g}}var Ih=/agent-transcripts[/\\]([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:[/\\]|$)/i;function Rh(r){let e=typeof r.agentId=="string"?r.agentId.trim():"";return e&&e!=="*"?e:r.path.match(Ih)?.[1]}var qn=class{sessions=new Map;async processEntry(e,t,n,s){for(let i of n.events)oa(e,i.match,n)&&await this.handleEvent(e,t,n,i,s??void 0)}getSessionKey(e,t){return`${e.name}:${t}`}getOrCreateSession(e,t){let n=this.getSessionKey(e,t),s=this.sessions.get(n);return s||(s={sessionId:t,platformSource:ae(e.name)},this.sessions.set(n,s)),s}resolveSessionId(e,t,n,s,i){let o={watch:t,schema:n},a=s.fields?.sessionId??(n.sessionIdPath?{path:n.sessionIdPath}:void 0),c=ot(a,e,o);return typeof c=="string"&&c.trim()?c:typeof c=="number"?String(c):i&&i.trim()?i:null}resolveCwd(e,t,n,s,i){let o={watch:t,schema:n,session:i},a=s.fields?.cwd??(n.cwdPath?{path:n.cwdPath}:void 0),c=ot(a,e,o);return typeof c=="string"&&c.trim()?c:t.workspace?t.workspace:i.cwd}resolveProject(e,t,n,s,i){let o={watch:t,schema:n,session:i},a=s.fields?.project??(n.projectPath?{path:n.projectPath}:void 0),c=ot(a,e,o);return typeof c=="string"&&c.trim()?c:t.project?t.project:i.cwd?He(i.cwd).primary:i.project}async handleEvent(e,t,n,s,i){let o=this.resolveSessionId(e,t,n,s,i);if(!o){f.debug("TRANSCRIPT","Skipping event without sessionId",{event:s.name,watch:t.name});return}let a=this.getOrCreateSession(t,o),c=this.resolveCwd(e,t,n,s,a);c&&(a.cwd=c);let l=this.resolveProject(e,t,n,s,a);l&&(a.project=l);let u=ia(s.fields,e,{watch:t,schema:n,session:a});switch(s.action){case"session_context":this.applySessionContext(a,u);break;case"session_init":await this.handleSessionInit(a,u),t.context?.updateOn?.includes("session_start")&&await this.updateContext(a,t);break;case"user_message":typeof u.message=="string"&&(a.lastUserMessage=u.message),typeof u.prompt=="string"&&(a.lastUserMessage=u.prompt);break;case"assistant_message":typeof u.message=="string"&&(a.lastAssistantMessage=u.message);break;case"tool_use":await this.handleToolUse(a,t,u);break;case"tool_result":await this.handleToolResult(a,t,u);break;case"observation":await this.sendObservation(a,t,u);break;case"file_edit":await this.sendFileEdit(a,u);break;case"session_end":await this.handleSessionEnd(a,t);break;default:break}}applySessionContext(e,t){let n=typeof t.cwd=="string"?t.cwd:void 0,s=typeof t.project=="string"?t.project:void 0;n&&(e.cwd=n),s&&(e.project=s)}async handleSessionInit(e,t){let n=typeof t.prompt=="string"?t.prompt:"",s=e.cwd??process.cwd();n&&(e.lastUserMessage=n),await Zo.execute({sessionId:e.sessionId,cwd:s,prompt:n,platform:e.platformSource})}async handleToolUse(e,t,n){let s=typeof n.toolId=="string"?n.toolId:void 0,i=typeof n.toolName=="string"?n.toolName:void 0,o=this.maybeParseJson(n.toolInput),a=this.maybeParseJson(n.toolResponse);if(i==="apply_patch"&&typeof o=="string"){let c=this.parseApplyPatchFiles(o);for(let l of c)await this.sendFileEdit(e,{filePath:l,edits:[{type:"apply_patch",patch:o}]})}i&&a!==void 0?await this.sendObservation(e,t,{toolName:i,toolInput:o,toolResponse:a,toolUseId:s}):i&&s&&(e.pendingTools||(e.pendingTools=new Map),e.pendingTools.set(s,{toolName:i,toolInput:o}))}async handleToolResult(e,t,n){let s=typeof n.toolId=="string"?n.toolId:void 0,i=typeof n.toolName=="string"?n.toolName:void 0,o=this.maybeParseJson(n.toolResponse),a=this.maybeParseJson(n.toolInput);if(s&&e.pendingTools){let c=e.pendingTools.get(s);c&&(i||(i=c.toolName),a===void 0&&(a=c.toolInput),e.pendingTools.delete(s))}i?await this.sendObservation(e,t,{toolName:i,toolInput:a,toolResponse:o,toolUseId:s}):f.debug("TRANSCRIPT","Dropping tool_result with no resolvable toolName",{sessionId:e.sessionId,toolId:s})}async sendObservation(e,t,n){let s=typeof n.toolName=="string"?n.toolName:void 0;if(!s)return;let i=await Fl({contentSessionId:e.sessionId,cwd:e.cwd??process.cwd(),toolName:s,toolInput:this.maybeParseJson(n.toolInput),toolResponse:this.maybeParseJson(n.toolResponse),platformSource:e.platformSource,toolUseId:typeof n.toolUseId=="string"?n.toolUseId:void 0,agentId:Rh(t)});if(!i.ok)throw new Error(`ingestObservation failed: ${i.reason}`)}async sendFileEdit(e,t){let n=typeof t.filePath=="string"?t.filePath:void 0;n&&await ea.execute({sessionId:e.sessionId,cwd:e.cwd??process.cwd(),filePath:n,edits:Array.isArray(t.edits)?t.edits:void 0,platform:e.platformSource})}maybeParseJson(e){if(typeof e!="string")return e;let t=e.trim();if(!t||!(t.startsWith("{")||t.startsWith("[")))return e;try{return JSON.parse(t)}catch(n){return f.debug("TRANSCRIPT","Field looked like JSON but did not parse; using raw string",{preview:t.slice(0,120)},n instanceof Error?n:void 0),e}}parseApplyPatchFiles(e){let t=[],n=e.split(`
36
+ `);for(let s of n){let i=s.trim();if(i.startsWith("*** Update File: "))t.push(i.replace("*** Update File: ","").trim());else if(i.startsWith("*** Add File: "))t.push(i.replace("*** Add File: ","").trim());else if(i.startsWith("*** Delete File: "))t.push(i.replace("*** Delete File: ","").trim());else if(i.startsWith("*** Move to: "))t.push(i.replace("*** Move to: ","").trim());else if(i.startsWith("+++ ")){let o=i.replace("+++ ","").replace(/^b\//,"").trim();o&&o!=="/dev/null"&&t.push(o)}}return Array.from(new Set(t))}async handleSessionEnd(e,t){await this.queueSummary(e),await this.updateContext(e,t),e.pendingTools?.clear();let n=this.getSessionKey(t,e.sessionId);this.sessions.delete(n)}async queueSummary(e){if(!await Wr())return;let n=e.lastAssistantMessage??"",s=JSON.stringify({contentSessionId:e.sessionId,last_assistant_message:n,platformSource:e.platformSource});try{await we("/api/sessions/summarize",{method:"POST",headers:{"Content-Type":"application/json"},body:s})}catch(i){f.warn("TRANSCRIPT","Summary request failed",{error:i instanceof Error?i.message:String(i)})}}async updateContext(e,t){if(!t.context||t.context.mode!=="agents"||Hi(t)||!await Wr())return;let s=e.cwd??t.workspace;if(!s)return;let o=He(s).allProjects.join(","),a=`/api/context/inject?projects=${encodeURIComponent(o)}&platformSource=${encodeURIComponent(e.platformSource)}`,c=K(t.context.path??`${s}/AGENTS.md`),l=ar.default.resolve(c),u=[ar.default.resolve(s),ar.default.resolve(M)];if(!u.some(h=>l.startsWith(h+ar.default.sep)||l===h)){f.warn("SECURITY","Rejected path traversal attempt in watch.context.path",{original:t.context.path,resolved:l,allowedRoots:u});return}let g;try{g=await we(a)}catch(h){f.warn("TRANSCRIPT","Failed to fetch AGENTS.md context",{error:h instanceof Error?h.message:String(h)});return}if(!g.ok)return;let p=(await g.text()).trim();p&&(ra(c,p),f.debug("TRANSCRIPT","Updated AGENTS.md context",{agentsPath:c,watch:t.name}))}};var Oi=class{constructor(e,t,n,s){this.filePath=e;this.onLine=n;this.onOffset=s;this.tailState={offset:t,partial:""}}filePath;onLine;onOffset;watcher=null;tailState;start(){this.readNewData().catch(()=>{}),this.watcher=(0,W.watch)(this.filePath,{persistent:!0},()=>{this.readNewData().catch(()=>{})})}close(){this.watcher?.close(),this.watcher=null}poke(){this.readNewData().catch(()=>{})}async readNewData(){if(!(0,W.existsSync)(this.filePath))return;let e=0;try{e=(0,W.statSync)(this.filePath).size}catch(o){f.debug("WORKER","Failed to stat transcript file",{file:this.filePath},o instanceof Error?o:void 0);return}if(e<this.tailState.offset&&(this.tailState.offset=0),e===this.tailState.offset)return;let t=(0,W.createReadStream)(this.filePath,{start:this.tailState.offset,end:e-1,encoding:"utf8"}),n="";for await(let o of t)n+=o;this.tailState.offset=e,this.onOffset(this.tailState.offset);let i=(this.tailState.partial+n).split(`
37
+ `);this.tailState.partial=i.pop()??"";for(let o of i){let a=o.trim();a&&await this.onLine(a)}}},zn=class{constructor(e,t){this.config=e;this.statePath=t;this.state=Vi(t)}config;statePath;processor=new qn;tailers=new Map;state;rootWatchers=[];async start(){for(let e of this.config.watches)await this.setupWatch(e)}stop(){for(let e of this.tailers.values())e.close();this.tailers.clear();for(let e of this.rootWatchers)e.close();this.rootWatchers=[]}async setupWatch(e){let t=this.resolveSchema(e);if(!t){f.warn("TRANSCRIPT","Missing schema for watch",{watch:e.name});return}let n=K(e.path),s=this.resolveWatchFiles(n);for(let o of s)await this.addTailer(o,e,t);let i=this.deepestNonGlobAncestor(n);if(!i||!(0,W.existsSync)(i)){f.debug("TRANSCRIPT","Watch root does not exist, skipping fs.watch",{watch:e.name,watchRoot:i});return}try{let o=(0,W.watch)(i,{recursive:!0,persistent:!0},(a,c)=>{this.handleRootWatchEvent(i,n,e,t,c)});this.rootWatchers.push(o),f.info("TRANSCRIPT","Watching transcript root recursively",{watch:e.name,watchRoot:i})}catch(o){f.warn("TRANSCRIPT","Failed to start recursive fs.watch on transcript root",{watch:e.name,watchRoot:i},o instanceof Error?o:void 0)}}handleRootWatchEvent(e,t,n,s,i){if(!i)return;let o=(0,ne.resolve)(e,i).replace(/\\/g,"/"),a=this.tailers.get(o);if(a){a.poke();return}let c=this.resolveWatchFiles(t);for(let l of c)this.tailers.has(l)||this.addTailer(l,n,s)}deepestNonGlobAncestor(e){if(!this.hasGlob(e)){if((0,W.existsSync)(e))try{return(0,W.statSync)(e).isDirectory()?e:(0,ne.resolve)(e,"..")}catch(s){return f.debug("TRANSCRIPT","Failed to stat watch path ancestor, falling back to parent directory",{path:e},s instanceof Error?s:new Error(String(s))),(0,ne.resolve)(e,"..")}return e}let t=e.split(/[/\\]/),n=[];for(let s of t){if(/[*?[\]{}()]/.test(s))break;n.push(s)}return n.length===0||n.length===1&&n[0]===""?"":n.join(ne.sep)}resolveSchema(e){return typeof e.schema=="string"?this.config.schemas?.[e.schema]??null:e.schema}resolveWatchFiles(e){if(this.hasGlob(e))return this.scanGlob(this.normalizeGlobPattern(e));if((0,W.existsSync)(e))try{if((0,W.statSync)(e).isDirectory()){let n=(0,ne.join)(e,"**","*.jsonl");return this.scanGlob(this.normalizeGlobPattern(n))}return[e]}catch(t){return f.debug("WORKER","Failed to stat watch path",{path:e},t instanceof Error?t:void 0),[]}return[]}scanGlob(e){return Array.from(new Bun.Glob(e).scanSync({absolute:!0,onlyFiles:!0}))}normalizeGlobPattern(e){return e.replace(/\\/g,"/")}hasGlob(e){return/[*?[\]{}()]/.test(e)}async addTailer(e,t,n){if(this.tailers.has(e))return;let s=this.extractSessionIdFromPath(e),i=this.state.offsets[e]??0;if(i===0&&t.startAtEnd)try{i=(0,W.statSync)(e).size}catch(a){f.debug("WORKER","Failed to stat file for startAtEnd offset",{file:e},a instanceof Error?a:void 0),i=0}let o=new Oi(e,i,async a=>{await this.handleLine(a,t,n,e,s)},a=>{this.state.offsets[e]=a,qi(this.statePath,this.state)});o.start(),this.tailers.set(e,o),f.info("TRANSCRIPT","Watching transcript file",{file:e,watch:t.name,schema:n.name})}async handleLine(e,t,n,s,i){try{let o=JSON.parse(e);await this.processor.processEntry(o,t,n,i??void 0)}catch(o){o instanceof Error?f.debug("TRANSCRIPT","Failed to parse transcript line",{watch:t.name,file:(0,ne.basename)(s)},o):f.warn("TRANSCRIPT","Failed to parse transcript line (non-Error thrown)",{watch:t.name,file:(0,ne.basename)(s),error:String(o)})}}extractSessionIdFromPath(e){let t=e.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i);return t?t[0]:null}};function ki(r,e){let t=r.indexOf(e);return t===-1?null:r[t+1]??null}async function Ol(r,e){switch(r){case"init":{let t=ki(e,"--config")??rt;return gr(t),console.log(`Created sample config: ${K(t)}`),0}case"watch":{let t=ki(e,"--config")??rt,n;try{n=At(t)}catch(a){if(a instanceof Error&&a.message.includes("not found"))gr(t),console.log(`Created sample config: ${K(t)}`),n=At(t);else throw a}let s=K(n.stateFile??pr),i=new zn(n,s);await i.start(),console.log("Transcript watcher running. Press Ctrl+C to stop.");let o=()=>{i.stop(),process.exit(0)};return process.on("SIGINT",o),process.on("SIGTERM",o),await new Promise(()=>{})}case"validate":{let t=ki(e,"--config")??rt;try{At(t)}catch(n){if(n instanceof Error&&n.message.includes("not found"))gr(t),console.log(`Created sample config: ${K(t)}`),At(t);else throw n}return console.log(`Config OK: ${K(t)}`),0}default:return console.log("Usage: claude-mem transcript <init|watch|validate> [--config <path>]"),1}}var Ch=process.argv[2],Mh=process.argv.slice(3);Ol(Ch,Mh).then(r=>{process.exit(r)}).catch(r=>{console.error(r),process.exit(1)});
38
38
  /*! Bundled license information:
39
39
 
40
40
  @posthog/core/dist/vendor/uuidv7.mjs: