@passiveintent/core 1.0.0

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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH;;;;;;GAMG;AAGH,OAAO,EACL,WAAW,EACX,kBAAkB,EAClB,WAAW,EACX,aAAa,EACb,aAAa,EACb,gBAAgB,EAChB,sBAAsB,EACtB,6BAA6B,EAC7B,sBAAsB,EACtB,sBAAsB,EACtB,mBAAmB,EACnB,iBAAiB,EACjB,YAAY,EACZ,YAAY,EACZ,qBAAqB,EACrB,iBAAiB,GAClB,MAAM,iBAAiB,CAAC;AAEzB,YAAY,EACV,eAAe,EACf,cAAc,EACd,kBAAkB,EAClB,wBAAwB,EACxB,uBAAuB,EACvB,kBAAkB,EAClB,kBAAkB,EAClB,yBAAyB,EACzB,mBAAmB,EACnB,sBAAsB,EACtB,eAAe,EACf,kBAAkB,EAClB,iBAAiB,EACjB,iBAAiB,EACjB,sBAAsB,EACtB,iBAAiB,EACjB,iBAAiB,EACjB,mBAAmB,EACnB,kBAAkB,EAClB,eAAe,EACf,qBAAqB,EACrB,eAAe,EACf,eAAe,EACf,kBAAkB,EAClB,aAAa,EACb,uBAAuB,EACvB,mBAAmB,EACnB,yBAAyB,EACzB,kBAAkB,GACnB,MAAM,iBAAiB,CAAC;AAGzB,OAAO,EACL,qBAAqB,EACrB,mBAAmB,EACnB,oBAAoB,EACpB,uBAAuB,GACxB,MAAM,eAAe,CAAC;AAEvB,YAAY,EACV,cAAc,EACd,mBAAmB,EACnB,YAAY,EACZ,WAAW,EACX,gBAAgB,GACjB,MAAM,eAAe,CAAC;AAGvB,YAAY,EACV,eAAe,EACf,qBAAqB,EACrB,cAAc,EACd,iBAAiB,GAClB,MAAM,kCAAkC,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ function B(o){let e=[];for(let r=0;r<o.length;r+=32768){let s=o.subarray(r,Math.min(r+32768,o.length));e.push(String.fromCharCode.apply(null,s))}return btoa(e.join(""))}function N(o){let t=atob(o),e=new Uint8Array(t.length);for(let r=0;r<t.length;r+=1)e[r]=t.charCodeAt(r);return e}function ot(o,t=2166136261){let e=t>>>0;for(let r=0;r<o.length;r+=1)e^=o.charCodeAt(r),e+=(e<<1)+(e<<4)+(e<<7)+(e<<8)+(e<<24);return e>>>0}var O=(()=>{let o=globalThis.__PFIE_WM__;return(typeof o=="number"?o:2343432205)>>>0})(),v=new Uint32Array(2),y=class o{constructor(t={},e){this.bitSize=t.bitSize??2048,this.hashCount=t.hashCount??4;let r=Math.ceil(this.bitSize/8);this.bits=e&&e.length===r?e:new Uint8Array(r)}add(t){this.computeHashes(t);let e=v[0],r=v[1];for(let s=0;s<this.hashCount;s+=1){let n=(e+s*r>>>0)%this.bitSize;this.setBit(n)}}check(t){this.computeHashes(t);let e=v[0],r=v[1];for(let s=0;s<this.hashCount;s+=1){let n=(e+s*r>>>0)%this.bitSize;if(!this.getBit(n))return!1}return!0}static computeOptimal(t,e){if(t<=0)return{bitSize:8,hashCount:1};e<=0&&(e=1e-10),e>=1&&(e=.99);let r=Math.LN2,s=r*r,n=Math.ceil(-(t*Math.log(e))/s),i=Math.max(1,Math.round(n/t*r));return{bitSize:n,hashCount:i}}estimateCurrentFPR(t){if(t<=0)return 0;let e=-(this.hashCount*t)/this.bitSize,r=Math.exp(e);return Math.pow(1-r,this.hashCount)}getBitsetByteSize(){return this.bits.byteLength}toBase64(){return B(this.bits)}static fromBase64(t,e={}){return new o(e,N(t))}setBit(t){let e=t>>3,r=1<<(t&7);this.bits[e]|=r}getBit(t){let e=t>>3,r=1<<(t&7);return(this.bits[e]&r)!==0}computeHashes(t){v[0]=(ot(t,2166136261)^O^O)>>>0,v[1]=(ot(t,16777619)^O^O)>>>0}};function st(o,t){o<=0&&(o=1),t<=0&&(t=1e-10),t>=1&&(t=.99);let e=Math.ceil(-(o*Math.log(t))/(Math.LN2*Math.LN2)),r=Math.max(1,Math.round(e/o*Math.log(2))),s=Math.exp(-(r*o)/e),n=Math.pow(1-s,r);return{bitSize:e,hashCount:r,estimatedFpRate:n}}var u=class o{constructor(t={}){this.rows=new Map;this.stateToIndex=new Map;this.indexToState=[];this.freedIndices=[];this.highEntropyThreshold=t.highEntropyThreshold??.75,this.divergenceThreshold=Math.abs(t.divergenceThreshold??3.5),this.smoothingEpsilon=t.smoothingEpsilon??.01,this.baselineMeanLL=t.baselineMeanLL,this.baselineStdLL=t.baselineStdLL,this.maxStates=t.maxStates??500;let e=t.smoothingAlpha??.1;this.smoothingAlpha=Number.isFinite(e)&&e>=0?e:0}ensureState(t){if(t==="")throw new Error("MarkovGraph: state label must not be empty string");let e=this.stateToIndex.get(t);if(e!==void 0)return e;let r;return this.freedIndices.length>0?(r=this.freedIndices.pop(),this.indexToState[r]=t):(r=this.indexToState.length,this.indexToState.push(t)),this.stateToIndex.set(t,r),r}incrementTransition(t,e){this.stateToIndex.size>=this.maxStates*1.5&&this.prune();let r=this.ensureState(t),s=this.ensureState(e),n=this.rows.get(r)??{total:0,toCounts:new Map},i=(n.toCounts.get(s)??0)+1;n.toCounts.set(s,i),n.total+=1,this.rows.set(r,n)}getProbability(t,e){let r=this.stateToIndex.get(t),s=this.stateToIndex.get(e);if(r===void 0||s===void 0)return 0;let n=this.rows.get(r);if(!n||n.total===0)return 0;let i=n.toCounts.get(s)??0;return this.smoothingAlpha===0?i/n.total:(i+this.smoothingAlpha)/(n.total+this.smoothingAlpha*this.stateToIndex.size)}entropyForState(t){let e=this.stateToIndex.get(t);if(e===void 0)return 0;let r=this.rows.get(e);if(!r||r.total===0)return 0;let s=0;if(this.smoothingAlpha===0)r.toCounts.forEach(n=>{let i=n/r.total;i>0&&(s-=i*Math.log(i))});else{let n=this.stateToIndex.size,i=r.total+this.smoothingAlpha*n;r.toCounts.forEach(l=>{let h=(l+this.smoothingAlpha)/i;s-=h*Math.log(h)});let a=n-r.toCounts.size;if(a>0){let l=this.smoothingAlpha/i;l>0&&(s-=a*l*Math.log(l))}}return s}normalizedEntropyForState(t){let e=this.stateToIndex.get(t);if(e===void 0)return 0;let r=this.rows.get(e);if(!r||r.total===0)return 0;let s=Math.max(2,r.toCounts.size),n=Math.log(s);if(n<=0)return 0;let i=0;r.toCounts.forEach(l=>{let h=l/r.total;h>0&&(i-=h*Math.log(h))});let a=i/n;return Math.min(1,Math.max(0,a))}static logLikelihoodTrajectory(t,e,r=.01){if(e.length<2)return 0;let s=0;for(let n=0;n<e.length-1;n+=1){let i=t.getProbability(e[n],e[n+1]);s+=Math.log(i>0?i:r)}return s}getLikelyNextStates(t,e){let r=this.stateToIndex.get(t);if(r===void 0)return[];let s=this.rows.get(r);if(!s||s.total===0)return[];let n=[],i=this.smoothingAlpha===0?s.total:s.total+this.smoothingAlpha*this.stateToIndex.size;return s.toCounts.forEach((a,l)=>{let h=this.smoothingAlpha===0?a/i:(a+this.smoothingAlpha)/i;if(h>=e){let c=this.indexToState[l];c&&c!==""&&n.push({state:c,probability:h})}}),n.sort((a,l)=>l.probability-a.probability),n}rowTotal(t){let e=this.stateToIndex.get(t);return e===void 0?0:this.rows.get(e)?.total??0}stateCount(){return this.indexToState.length}totalTransitions(){let t=0;return this.rows.forEach(e=>{t+=e.total}),t}prune(){let t=this.stateToIndex.size;if(t<=this.maxStates)return;let e=[];this.stateToIndex.forEach(n=>{let i=this.rows.get(n);e.push({index:n,total:i?.total??0})}),e.sort((n,i)=>n.total-i.total);let r=Math.max(1,Math.min(Math.ceil(t*.2),t-this.maxStates)),s=new Set;for(let n=0;n<r&&n<e.length;n+=1)s.add(e[n].index);s.forEach(n=>{this.rows.delete(n)}),this.rows.forEach(n=>{let i=0;s.forEach(a=>{let l=n.toCounts.get(a);l!==void 0&&(i+=l,n.toCounts.delete(a))}),n.total-=i}),s.forEach(n=>{let i=this.indexToState[n];i!==void 0&&i!==""&&this.stateToIndex.delete(i),this.freedIndices.push(n),this.indexToState[n]=""})}toJSON(){let t=[];return this.rows.forEach((e,r)=>{let s=[];e.toCounts.forEach((n,i)=>{s.push([i,n])}),t.push([r,e.total,s])}),{states:[...this.indexToState],rows:t,freedIndices:[...this.freedIndices]}}static fromJSON(t,e={}){let r=new o(e),s=new Set(t.freedIndices);for(let n=0;n<t.states.length;n+=1){let i=t.states[n];if(r.indexToState.push(i),s.has(n)){if(i!=="")throw new Error(`MarkovGraph.fromJSON: slot ${n} is listed in freedIndices but has non-empty label "${i}"`);r.freedIndices.push(n)}else{if(i==="")throw new Error(`MarkovGraph.fromJSON: slot ${n} has an empty-string label but is not listed in freedIndices. Empty string is reserved as the tombstone marker.`);r.stateToIndex.set(i,n)}}for(let n=0;n<t.rows.length;n+=1){let[i,a,l]=t.rows[n],h={total:a,toCounts:new Map};for(let c=0;c<l.length;c+=1){let[g,p]=l[c];h.toCounts.set(g,p)}r.rows.set(i,h)}return r}toBinary(){let t=new TextEncoder,e=3,r=new Array(this.indexToState.length);for(let a=0;a<this.indexToState.length;a+=1)r[a]=t.encode(this.indexToState[a]),e+=2+r[a].byteLength;e+=2+this.freedIndices.length*2,e+=2,this.rows.forEach(a=>{e+=8,e+=a.toCounts.size*6});let s=new Uint8Array(e),n=new DataView(s.buffer),i=0;n.setUint8(i,2),i+=1,n.setUint16(i,this.indexToState.length,!0),i+=2;for(let a=0;a<this.indexToState.length;a+=1){let l=r[a];n.setUint16(i,l.byteLength,!0),i+=2,s.set(l,i),i+=l.byteLength}n.setUint16(i,this.freedIndices.length,!0),i+=2;for(let a=0;a<this.freedIndices.length;a+=1)n.setUint16(i,this.freedIndices[a],!0),i+=2;return n.setUint16(i,this.rows.size,!0),i+=2,this.rows.forEach((a,l)=>{n.setUint16(i,l,!0),i+=2,n.setUint32(i,a.total,!0),i+=4,n.setUint16(i,a.toCounts.size,!0),i+=2,a.toCounts.forEach((h,c)=>{n.setUint16(i,c,!0),i+=2,n.setUint32(i,h,!0),i+=4})}),s}static fromBinary(t,e={}){let r=new o(e),s=new TextDecoder,n=new DataView(t.buffer,t.byteOffset,t.byteLength),i=0,a=n.getUint8(i);if(i+=1,a!==2)throw new Error(`Unsupported MarkovGraph binary version: 0x${a.toString(16).padStart(2,"0")}. Only version 0x02 is supported.`);let l=n.getUint16(i,!0);i+=2;let h=[];for(let m=0;m<l;m+=1){let d=n.getUint16(i,!0);i+=2,h.push(s.decode(t.subarray(i,i+d))),i+=d}let c=n.getUint16(i,!0);i+=2;let g=new Set;for(let m=0;m<c;m+=1)g.add(n.getUint16(i,!0)),i+=2;for(let m=0;m<h.length;m+=1){let d=h[m];if(r.indexToState.push(d),g.has(m)){if(d!=="")throw new Error(`MarkovGraph.fromBinary: slot ${m} is listed as freed but has non-empty label "${d}"`);r.freedIndices.push(m)}else{if(d==="")throw new Error(`MarkovGraph.fromBinary: slot ${m} has an empty-string label but is not listed in the freed-index section. Empty string is reserved as the tombstone marker.`);r.stateToIndex.set(d,m)}}let p=n.getUint16(i,!0);i+=2;for(let m=0;m<p;m+=1){let d=n.getUint16(i,!0);i+=2;let $=n.getUint32(i,!0);i+=4;let k=n.getUint16(i,!0);i+=2;let L=new Map;for(let b=0;b<k;b+=1){let q=n.getUint16(i,!0);i+=2;let J=n.getUint32(i,!0);i+=4,L.set(q,J)}r.rows.set(d,{total:$,toCounts:L})}return r}};function T(){return{count:0,totalMs:0,maxMs:0,samples:[]}}function ft(o,t,e){o.count+=1,o.totalMs+=t,t>o.maxMs&&(o.maxMs=t),o.samples.length<e?o.samples.push(t):e>0&&(o.samples[o.count%e]=t)}function at(o,t){if(o.length===0)return 0;let e=Math.max(0,Math.min(o.length-1,Math.ceil(t*o.length)-1));return o[e]}function S(o){if(o.count===0)return{count:0,avgMs:0,p95Ms:0,p99Ms:0,maxMs:0};let t=[...o.samples].sort((e,r)=>e-r);return{count:o.count,avgMs:o.totalMs/o.count,p95Ms:at(t,.95),p99Ms:at(t,.99),maxMs:o.maxMs}}var lt=typeof TextEncoder<"u"?new TextEncoder:null,E=class{constructor(t={}){this.enabled=t.enabled??!1,this.maxSamples=t.maxSamples??4096,this.stats={track:T(),bloomAdd:T(),bloomCheck:T(),incrementTransition:T(),entropyComputation:T(),divergenceComputation:T()}}now(){return this.enabled?performance.now():0}record(t,e){this.enabled&&ft(this.stats[t],performance.now()-e,this.maxSamples)}report(t){return{benchmarkEnabled:this.enabled,track:S(this.stats.track),bloomAdd:S(this.stats.bloomAdd),bloomCheck:S(this.stats.bloomCheck),incrementTransition:S(this.stats.incrementTransition),entropyComputation:S(this.stats.entropyComputation),divergenceComputation:S(this.stats.divergenceComputation),memoryFootprint:t}}serializedSizeBytes(t){let e=JSON.stringify(t);return lt?lt.encode(e).byteLength:e.length}};var P=class{getItem(t){if(typeof window>"u"||!window.localStorage)return null;try{return window.localStorage.getItem(t)}catch{return null}}setItem(t,e){typeof window>"u"||!window.localStorage||window.localStorage.setItem(t,e)}},D=class{setTimeout(t,e){return typeof globalThis.setTimeout!="function"?0:globalThis.setTimeout(t,e)}clearTimeout(t){typeof globalThis.clearTimeout=="function"&&globalThis.clearTimeout(t)}now(){return typeof globalThis.performance<"u"&&typeof globalThis.performance.now=="function"?globalThis.performance.now():Date.now()}},et=class{constructor(){this.store=new Map}getItem(t){return this.store.get(t)??null}setItem(t,e){this.store.set(t,e)}},f=class f{constructor(){this.pauseCallbacks=[];this.resumeCallbacks=[];this.interactionCallbacks=[];this.exitIntentCallbacks=[];this.interactionHandler=null;this.interactionLastFired=0;this.exitIntentHandler=null;this.handler=()=>{if(!(typeof document>"u"))if(document.hidden)for(let t of this.pauseCallbacks)t();else for(let t of this.resumeCallbacks)t()},typeof document<"u"&&document.addEventListener("visibilitychange",this.handler)}onPause(t){return this.pauseCallbacks.push(t),()=>{let e=this.pauseCallbacks.indexOf(t);e!==-1&&this.pauseCallbacks.splice(e,1)}}onResume(t){return this.resumeCallbacks.push(t),()=>{let e=this.resumeCallbacks.indexOf(t);e!==-1&&this.resumeCallbacks.splice(e,1)}}onInteraction(t){if(typeof window>"u"||typeof window.addEventListener!="function")return null;if(this.interactionCallbacks.push(t),this.interactionHandler===null&&typeof window<"u"&&typeof window.addEventListener=="function"){this.interactionHandler=()=>{let r=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();if(!(r-this.interactionLastFired<f.INTERACTION_THROTTLE_MS)){this.interactionLastFired=r;for(let s of this.interactionCallbacks)s()}};let e={passive:!0};for(let r of f.INTERACTION_EVENTS)window.addEventListener(r,this.interactionHandler,e)}return()=>{let e=this.interactionCallbacks.indexOf(t);e!==-1&&this.interactionCallbacks.splice(e,1),this.interactionCallbacks.length===0&&this.teardownInteractionListeners()}}teardownInteractionListeners(){if(this.interactionHandler!==null&&typeof window<"u"&&typeof window.removeEventListener=="function")for(let t of f.INTERACTION_EVENTS)window.removeEventListener(t,this.interactionHandler);this.interactionHandler=null}onExitIntent(t){if(this.exitIntentCallbacks.push(t),this.exitIntentHandler===null){let e=typeof document<"u"?document?.documentElement:null;e!=null&&(this.exitIntentHandler=r=>{if(r.clientY<=0)for(let s of this.exitIntentCallbacks)s()},e.addEventListener("mouseleave",this.exitIntentHandler))}return()=>{let e=this.exitIntentCallbacks.indexOf(t);e!==-1&&this.exitIntentCallbacks.splice(e,1),this.exitIntentCallbacks.length===0&&this.teardownExitIntentListener()}}teardownExitIntentListener(){if(this.exitIntentHandler!==null){let t=typeof document<"u"?document?.documentElement:null;t?.removeEventListener("mouseleave",this.exitIntentHandler)}this.exitIntentHandler=null}destroy(){typeof document<"u"&&document.removeEventListener("visibilitychange",this.handler),this.teardownInteractionListeners(),this.teardownExitIntentListener(),this.pauseCallbacks.length=0,this.resumeCallbacks.length=0,this.interactionCallbacks.length=0,this.exitIntentCallbacks.length=0}};f.INTERACTION_THROTTLE_MS=1e3,f.INTERACTION_EVENTS=["mousemove","scroll","touchstart","keydown"];var _=f;var bt=/[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/gi,vt=/\b[0-9a-f]{24}\b/gi,Tt=/\/\d{4,}(?=\/|$)/g;function R(o){let t=o.indexOf("?"),e=t!==-1?o.slice(0,t):o,r=e.indexOf("#");return r!==-1&&(e=e.slice(0,r)),e=e.replace(bt,":id").replace(vt,":id").replace(Tt,"/:id"),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}var w=18e5,rt=15e3,H=12e4,nt=5e3;function ht(o={}){let t=o.botProtection??!0,e=o.dwellTime?.enabled??!1,r=o.crossTabSync===!0,s=o.holdoutConfig?.percentage,n=Number.isFinite(s)?Math.min(100,Math.max(0,s)):s??0,i={...o.graph,baselineMeanLL:o.baselineMeanLL??o.graph?.baselineMeanLL,baselineStdLL:o.baselineStdLL??o.graph?.baselineStdLL,smoothingAlpha:o.smoothingAlpha??o.graph?.smoothingAlpha},a=i.smoothingEpsilon,l=typeof a=="number"&&Number.isFinite(a)&&a>0?a:.01,h=o.storageKey??"passive-intent",c=o.persistDebounceMs,g=Number.isFinite(c)&&c>=0?Math.floor(c):2e3,p=o.persistThrottleMs,m=Number.isFinite(p)&&p>=0?Math.floor(p):0,d=o.eventCooldownMs,$=Number.isFinite(d)&&d>=0?Math.floor(d):0,k=o.dwellTime?.minSamples,L=Number.isFinite(k)&&k>=1?Math.floor(k):10,b=o.dwellTime?.zScoreThreshold,q=Number.isFinite(b)&&b>0?b:2.5,J=o.enableBigrams??!1,Q=o.bigramFrequencyThreshold,ut=Number.isFinite(Q)&&Q>=1?Math.floor(Q):5,it=o.driftProtection?.maxAnomalyRate,pt=Number.isFinite(it)?Math.min(1,Math.max(0,it)):.4,Y=o.driftProtection?.evaluationWindowMs,yt=Number.isFinite(Y)&&Y>0?Math.floor(Y):3e5,tt=o.hesitationCorrelationWindowMs,gt=Number.isFinite(tt)&&tt>=0?Math.floor(tt):3e4;return{botProtection:t,dwellTimeEnabled:e,crossTabSync:r,holdoutPercent:n,graphConfig:i,trajectorySmoothingEpsilon:l,storageKey:h,persistDebounceMs:g,persistThrottleMs:m,eventCooldownMs:$,dwellTimeMinSamples:L,dwellTimeZScoreThreshold:q,enableBigrams:J,bigramFrequencyThreshold:ut,driftMaxAnomalyRate:pt,driftEvaluationWindowMs:yt,hesitationCorrelationWindowMs:gt}}var A=class{constructor(){this.listeners=new Map}on(t,e){let r=this.listeners.get(t)??new Set;return r.add(e),this.listeners.set(t,r),()=>{r.delete(e),r.size===0&&this.listeners.delete(t)}}emit(t,e){let r=this.listeners.get(t);r&&r.forEach(s=>s(e))}removeAll(){this.listeners.clear()}};var G=class{constructor(){this.isSuspectedBot=!1;this.trackTimestamps=new Array(10).fill(0);this.trackTimestampIndex=0;this.trackTimestampCount=0}record(t){this.trackTimestamps[this.trackTimestampIndex]=t,this.trackTimestampIndex=(this.trackTimestampIndex+1)%10,this.trackTimestampCount<10&&(this.trackTimestampCount+=1);let e=this.isSuspectedBot;return this.evaluate(),{suspected:this.isSuspectedBot,transitionedToBot:this.isSuspectedBot&&!e}}get suspected(){return this.isSuspectedBot}evaluate(){let t=this.trackTimestampCount;if(t<3)return;let e=0,r=[],s=t<10?0:this.trackTimestampIndex;for(let n=0;n<t-1;n+=1){let i=(s+n)%10,a=(s+n+1)%10,l=this.trackTimestamps[a]-this.trackTimestamps[i];r.push(l),l>=0&&l<50&&(e+=1)}if(r.length>=2){let n=0;for(let a=0;a<r.length;a+=1)n+=r[a];n/=r.length;let i=0;for(let a=0;a<r.length;a+=1){let l=r[a]-n;i+=l*l}i/=r.length,i<100&&(e+=1)}this.isSuspectedBot=e>=5}};function mt(o,t){let e=o?.count??0,r=o?.meanMs??0,s=o?.m2??0,n=e+1,i=t-r,a=r+i/n,l=t-a,h=s+i*l;return{count:n,meanMs:a,m2:h}}function ct(o){return o.count<2?0:Math.sqrt(o.m2/o.count)}function Et(o){throw new Error(`Unhandled AnomalyDecision kind: ${o.kind}`)}var M=class{constructor(t){this.lastEmittedAt={high_entropy:-1/0,trajectory_anomaly:-1/0,dwell_time_anomaly:-1/0};this.lastTrajectoryAnomalyAt=-1/0;this.lastTrajectoryAnomalyZScore=0;this.lastDwellAnomalyAt=-1/0;this.lastDwellAnomalyZScore=0;this.lastDwellAnomalyState="";this.anomaliesFiredInternal=0;this.emitter=t.emitter,this.timer=t.timer,this.assignmentGroup=t.assignmentGroup,this.eventCooldownMs=t.eventCooldownMs,this.hesitationCorrelationWindowMs=t.hesitationCorrelationWindowMs,this.driftPolicy=t.driftPolicy}get anomaliesFired(){return this.anomaliesFiredInternal}dispatch(t){if(t===null)return;t.kind==="trajectory_anomaly"&&this.driftPolicy.recordAnomaly();let e=this.timer.now();if(!(this.eventCooldownMs>0&&e-this.lastEmittedAt[t.kind]<this.eventCooldownMs)){if(this.lastEmittedAt[t.kind]=e,this.anomaliesFiredInternal+=1,this.assignmentGroup!=="control")switch(t.kind){case"high_entropy":this.emitter.emit("high_entropy",t.payload);break;case"trajectory_anomaly":this.emitter.emit("trajectory_anomaly",t.payload);break;case"dwell_time_anomaly":this.emitter.emit("dwell_time_anomaly",t.payload);break;default:Et(t)}t.kind==="trajectory_anomaly"?(this.lastTrajectoryAnomalyAt=e,this.lastTrajectoryAnomalyZScore=t.payload.zScore,this.maybeEmitHesitation(e)):t.kind==="dwell_time_anomaly"&&t.isPositiveZScore&&(this.lastDwellAnomalyAt=e,this.lastDwellAnomalyZScore=t.payload.zScore,this.lastDwellAnomalyState=t.payload.state,this.maybeEmitHesitation(e))}}maybeEmitHesitation(t){t-this.lastTrajectoryAnomalyAt<this.hesitationCorrelationWindowMs&&t-this.lastDwellAnomalyAt<this.hesitationCorrelationWindowMs&&(this.lastTrajectoryAnomalyAt=-1/0,this.lastDwellAnomalyAt=-1/0,this.assignmentGroup!=="control"&&this.emitter.emit("hesitation_detected",{state:this.lastDwellAnomalyState,trajectoryZScore:this.lastTrajectoryAnomalyZScore,dwellZScore:this.lastDwellAnomalyZScore}))}};var C=class{constructor(t){this.entropyGuard=new G;this.dwellStats=new Map;this.transitionsEvaluatedInternal=0;this.graph=t.graph,this.baseline=t.baseline,this.benchmark=t.benchmark,this.dwellTimeMinSamples=t.dwellTimeMinSamples,this.dwellTimeZScoreThreshold=t.dwellTimeZScoreThreshold,this.trajectorySmoothingEpsilon=t.trajectorySmoothingEpsilon,this.driftPolicy=t.driftPolicy,this.dispatcher=new M({emitter:t.emitter,timer:t.timer,assignmentGroup:t.assignmentGroup,eventCooldownMs:t.eventCooldownMs,hesitationCorrelationWindowMs:t.hesitationCorrelationWindowMs,driftPolicy:t.driftPolicy})}get suspected(){return this.entropyGuard.suspected}get transitionsEvaluated(){return this.transitionsEvaluatedInternal}get anomaliesFired(){return this.dispatcher.anomaliesFired}get isBaselineDrifted(){return this.driftPolicy.isDrifted}get baselineStatus(){return this.driftPolicy.baselineStatus}recordBotCheck(t){return this.entropyGuard.record(t)}recordTransition(t,e,r){this.transitionsEvaluatedInternal+=1}dispatch(t){this.dispatcher.dispatch(t)}evaluateEntropy(t){let e=this.benchmark.now();if(this.entropyGuard.suspected)return this.benchmark.record("entropyComputation",e),null;if(this.graph.rowTotal(t)<10)return this.benchmark.record("entropyComputation",e),null;let r=this.graph.entropyForState(t),s=this.graph.normalizedEntropyForState(t);return this.benchmark.record("entropyComputation",e),s>=this.graph.highEntropyThreshold?{kind:"high_entropy",payload:{state:t,entropy:r,normalizedEntropy:s}}:null}evaluateTrajectory(t,e,r){let s=this.benchmark.now();if(this.driftPolicy.isDrifted)return this.benchmark.record("divergenceComputation",s),null;if(this.entropyGuard.suspected)return this.benchmark.record("divergenceComputation",s),null;if(r.length<16)return this.benchmark.record("divergenceComputation",s),null;if(!this.baseline)return this.benchmark.record("divergenceComputation",s),null;let n=u.logLikelihoodTrajectory(this.graph,r,this.trajectorySmoothingEpsilon),i=u.logLikelihoodTrajectory(this.baseline,r,this.trajectorySmoothingEpsilon),a=Math.max(1,r.length-1),l=i/a,h=-Math.abs(this.graph.divergenceThreshold),c=typeof this.graph.baselineMeanLL=="number"&&typeof this.graph.baselineStdLL=="number"&&Number.isFinite(this.graph.baselineMeanLL)&&Number.isFinite(this.graph.baselineStdLL)&&this.graph.baselineStdLL>0,g=c?this.graph.baselineStdLL*Math.sqrt(32/a):0,p=c?(l-this.graph.baselineMeanLL)/g:l,m=c?p<=h:l<=h;return this.benchmark.record("divergenceComputation",s),m?{kind:"trajectory_anomaly",payload:{stateFrom:t,stateTo:e,realLogLikelihood:n,expectedBaselineLogLikelihood:i,zScore:p}}:null}evaluateDwellTime(t,e){if(e<=0)return null;let r=mt(this.dwellStats.get(t),e);if(this.dwellStats.set(t,r),r.count<this.dwellTimeMinSamples)return null;let s=ct(r);if(s<=0)return null;let n=(e-r.meanMs)/s;return Math.abs(n)>=this.dwellTimeZScoreThreshold?{kind:"dwell_time_anomaly",payload:{state:t,dwellMs:e,meanMs:r.meanMs,stdMs:s,zScore:n},isPositiveZScore:n>0}:null}};var j=class{constructor(t){this.ctx=t;this.lastPersistedAt=-1/0;this.throttleTimer=null;this.isClosedFlag=!1}serialize(){let t=this.ctx.getGraphAndBloom();if(!t)return null;let{graph:e,bloom:r}=t;this.ctx.setEngineHealth("pruning_active");try{e.prune()}finally{this.ctx.setEngineHealth("healthy")}let s;try{let n=e.toBinary();s=B(n)}catch(n){return this.ctx.reportError("SERIALIZE",n instanceof Error?n.message:String(n),n),null}return JSON.stringify({bloomBase64:r.toBase64(),graphBinary:s})}flushNow(){this.throttleTimer!==null&&(this.ctx.getTimer().clearTimeout(this.throttleTimer),this.throttleTimer=null),this.lastPersistedAt=-1/0,this.persist()}close(){this.isClosedFlag=!0,this.throttleTimer!==null&&(this.ctx.getTimer().clearTimeout(this.throttleTimer),this.throttleTimer=null)}checkThrottle(){let t=this.ctx.getThrottleMs();if(t>0&&!this.isClosedFlag){let r=this.ctx.getTimer().now()-this.lastPersistedAt;if(r<t){if(this.throttleTimer===null){let s=t-r;this.throttleTimer=this.ctx.getTimer().setTimeout(()=>{this.throttleTimer=null,this.persist()},s)}return!0}}return!1}},U=class extends j{persist(){if(!this.ctx.isDirty()||!this.ctx.getGraphAndBloom()||this.checkThrottle())return;let t=this.serialize();if(t)try{this.ctx.getStorage().setItem(this.ctx.getStorageKey(),t),this.ctx.clearDirty(),this.lastPersistedAt=this.ctx.getTimer().now(),this.ctx.setEngineHealth("healthy")}catch(e){let r=e instanceof Error&&(e.name==="QuotaExceededError"||e.message.toLowerCase().includes("quota"));r&&this.ctx.setEngineHealth("quota_exceeded"),this.ctx.reportError(r?"QUOTA_EXCEEDED":"STORAGE_WRITE",e instanceof Error?e.message:String(e),e)}}},F=class extends j{constructor(){super(...arguments);this.isAsyncWriting=!1;this.hasPendingAsyncPersist=!1;this.asyncWriteFailCount=0;this.retryTimer=null}persist(){if(!this.ctx.isDirty()||!this.ctx.getGraphAndBloom())return;if(this.isAsyncWriting){this.hasPendingAsyncPersist=!0;return}if(this.checkThrottle())return;let e=this.serialize();if(!e)return;this.isAsyncWriting=!0,this.hasPendingAsyncPersist=!1,this.ctx.clearDirty();let r=this.ctx.getAsyncStorage(),s;try{s=r.setItem(this.ctx.getStorageKey(),e)}catch(n){this.handleAsyncWriteError(n);return}s.then(()=>{this.isAsyncWriting=!1,this.asyncWriteFailCount=0,this.lastPersistedAt=this.ctx.getTimer().now(),this.ctx.setEngineHealth("healthy"),(this.hasPendingAsyncPersist||this.ctx.isDirty())&&(this.hasPendingAsyncPersist=!1,this.persist())}).catch(n=>{this.handleAsyncWriteError(n)})}handleAsyncWriteError(e){this.isAsyncWriting=!1,this.ctx.markDirty(),this.asyncWriteFailCount+=1;let r=e instanceof Error&&(e.name==="QuotaExceededError"||e.message.toLowerCase().includes("quota"));r&&this.ctx.setEngineHealth("quota_exceeded"),this.ctx.reportError(r?"QUOTA_EXCEEDED":"STORAGE_WRITE",e instanceof Error?e.message:String(e),e),this.hasPendingAsyncPersist=!1,!this.isClosedFlag&&this.asyncWriteFailCount===1&&this.schedulePersist()}schedulePersist(){this.isClosedFlag||(this.retryTimer!==null&&this.ctx.getTimer().clearTimeout(this.retryTimer),this.retryTimer=this.ctx.getTimer().setTimeout(()=>{this.retryTimer=null,this.persist()},this.ctx.getDebounceMs()))}flushNow(){this.retryTimer!==null&&(this.ctx.getTimer().clearTimeout(this.retryTimer),this.retryTimer=null),super.flushNow()}close(){super.close(),this.retryTimer!==null&&(this.ctx.getTimer().clearTimeout(this.retryTimer),this.retryTimer=null)}};var z=class{constructor(t){this.graphInstance=null;this.bloomInstance=null;this.isClosedFlag=!1;this.isDirtyFlag=!1;this.engineHealthInternal="healthy";this.storageKey=t.storageKey,this.persistDebounceMs=t.persistDebounceMs,this.persistThrottleMs=t.persistThrottleMs,this.storage=t.storage,this.asyncStorage=t.asyncStorage,this.timer=t.timer,this.onErrorCb=t.onError,this.asyncStorage?this.strategy=new F(this):this.strategy=new U(this)}markDirty(){this.isDirtyFlag=!0}getStorageKey(){return this.storageKey}getStorage(){return this.storage}getAsyncStorage(){return this.asyncStorage}getTimer(){return this.timer}getThrottleMs(){return this.persistThrottleMs}getDebounceMs(){return this.persistDebounceMs}getGraphAndBloom(){return!this.graphInstance||!this.bloomInstance?null:{graph:this.graphInstance,bloom:this.bloomInstance}}isClosed(){return this.isClosedFlag}isDirty(){return this.isDirtyFlag}clearDirty(){this.isDirtyFlag=!1}setEngineHealth(t){this.engineHealthInternal=t}reportError(t,e,r){this.onErrorCb&&this.onErrorCb({code:t,message:e,originalError:r})}get engineHealth(){return this.engineHealthInternal}attach(t,e){this.graphInstance=t,this.bloomInstance=e}restore(t){let e;try{e=this.storage.getItem(this.storageKey)}catch(r){return this.onErrorCb&&this.onErrorCb({code:"STORAGE_READ",message:r instanceof Error?r.message:String(r),originalError:r}),null}if(!e)return null;try{let r=JSON.parse(e),s;if(r.graphBinary){let i=N(r.graphBinary);s=u.fromBinary(i,t)}else if(r.graph)s=u.fromJSON(r.graph,t);else return null;return{bloom:r.bloomBase64?y.fromBase64(r.bloomBase64):new y,graph:s}}catch(r){if(this.onErrorCb){let s=typeof TextEncoder<"u"?new TextEncoder().encode(e).length:e.length;this.onErrorCb({code:"RESTORE_PARSE",message:r instanceof Error?r.message:String(r),originalError:{cause:r,payloadLength:s}})}return null}}persist(){this.strategy.persist()}flushNow(){this.strategy.flushNow()}close(){this.isClosedFlag=!0,this.strategy.close()}};var W=class{constructor(t){this.pauseUnsub=null;this.resumeUnsub=null;this.exitIntentUnsub=null;this.tabHiddenAt=null;this.idleStartedAt=0;this.isIdle=!1;this.idleCheckTimer=null;this.interactionUnsub=null;this.timer=t.timer,this.dwellTimeEnabled=t.dwellTimeEnabled,this.emitter=t.emitter,this.onAdjustBaseline=t.onAdjustBaseline,this.onResetBaseline=t.onResetBaseline,this.hasPreviousState=t.hasPreviousState,this.getPreviousState=t.getPreviousState,this.lastInteractionAt=this.timer.now(),this.onExitIntentCallback=t.onExitIntent,t.lifecycleAdapter!==void 0?(this.lifecycleAdapter=t.lifecycleAdapter,this.ownsLifecycleAdapter=!1):(this.lifecycleAdapter=typeof window<"u"?new _:null,this.ownsLifecycleAdapter=!0),this.bindAdapter(this.lifecycleAdapter)}bindAdapter(t){this.pauseUnsub?.(),this.pauseUnsub=null,this.resumeUnsub?.(),this.resumeUnsub=null,this.exitIntentUnsub?.(),this.exitIntentUnsub=null,this.stopIdleTracking(),t&&(this.pauseUnsub=t.onPause(()=>{this.tabHiddenAt=this.timer.now()}),this.resumeUnsub=t.onResume(()=>{if(this.tabHiddenAt===null)return;let e=this.timer.now()-this.tabHiddenAt;if(this.tabHiddenAt=null,e>=15e3){let r=this.getPreviousState();r!==null&&this.emitter.emit("attention_return",{state:r,hiddenDuration:e})}if(this.dwellTimeEnabled){if(e>18e5){this.hasPreviousState()&&(this.onResetBaseline(),this.emitter.emit("session_stale",{reason:"hidden_duration_exceeded",measuredMs:e,thresholdMs:18e5}));return}this.hasPreviousState()&&this.onAdjustBaseline(e)}}),this.startIdleTracking(t),this.onExitIntentCallback!==void 0&&typeof t.onExitIntent=="function"&&(this.exitIntentUnsub=t.onExitIntent(()=>{this.onExitIntentCallback()})))}setAdapterForTest(t,e){this.ownsLifecycleAdapter&&this.lifecycleAdapter?.destroy(),this.lifecycleAdapter=t,this.ownsLifecycleAdapter=e,this.tabHiddenAt=null,this.isIdle=!1,this.lastInteractionAt=this.timer.now(),this.exitIntentUnsub?.(),this.exitIntentUnsub=null,this.bindAdapter(t)}destroy(){this.stopIdleTracking(),this.pauseUnsub?.(),this.pauseUnsub=null,this.resumeUnsub?.(),this.resumeUnsub=null,this.exitIntentUnsub?.(),this.exitIntentUnsub=null,this.ownsLifecycleAdapter&&this.lifecycleAdapter?.destroy()}startIdleTracking(t){if(!t||typeof t.onInteraction!="function")return;let e=t.onInteraction(()=>{if(this.lastInteractionAt=this.timer.now(),this.isIdle){let r=this.timer.now()-this.idleStartedAt;this.isIdle=!1,this.dwellTimeEnabled&&this.hasPreviousState()&&this.onAdjustBaseline(r);let s=this.getPreviousState();s!==null&&this.emitter.emit("user_resumed",{state:s,idleMs:r})}});e&&(this.interactionUnsub=e,this.scheduleIdleCheck())}stopIdleTracking(){this.interactionUnsub?.(),this.interactionUnsub=null,this.idleCheckTimer!==null&&(this.timer.clearTimeout(this.idleCheckTimer),this.idleCheckTimer=null)}scheduleIdleCheck(){this.idleCheckTimer=this.timer.setTimeout(()=>{this.idleCheckTick()},5e3)}idleCheckTick(){this.idleCheckTimer=null;let t=this.timer.now();if(!this.isIdle&&this.hasPreviousState()&&t-this.lastInteractionAt>=12e4){this.isIdle=!0,this.idleStartedAt=this.lastInteractionAt+12e4;let e=this.getPreviousState();e!==null&&this.emitter.emit("user_idle",{state:e,idleMs:t-this.idleStartedAt})}this.interactionUnsub!==null&&this.scheduleIdleCheck()}};var K=class{constructor(t){this.isSuspected=t.isSuspected,this.evaluateDwellTime=t.evaluateDwellTime,this.getPreviousStateEnteredAt=t.getPreviousStateEnteredAt,this.emitter=t.emitter}onTrackContext(t){if(!t.from||this.isSuspected())return;let e=t.now-this.getPreviousStateEnteredAt();e>18e5?this.emitter.emit("session_stale",{reason:"dwell_exceeded",measuredMs:e,thresholdMs:18e5}):this.evaluateDwellTime(t.from,e)}};var Z=class{constructor(t,e){this.graph=t,this.bigramFrequencyThreshold=e}onTransition(t,e,r){if(r.length<3)return;let n=`${r[r.length-3]}\u2192${t}`,i=`${t}\u2192${e}`;this.graph.rowTotal(t)>=this.bigramFrequencyThreshold&&this.graph.incrementTransition(n,i)}};var I=class{constructor(t,e){this.drifted=!1;this.windowStart=0;this.windowTrackCount=0;this.windowAnomalyCount=0;this.maxAnomalyRate=t,this.evaluationWindowMs=e}onTrackStart(t){t-this.windowStart>=this.evaluationWindowMs&&(this.windowStart=t,this.windowTrackCount=0,this.windowAnomalyCount=0),this.windowTrackCount+=1}get isDrifted(){return this.drifted}get baselineStatus(){return this.drifted?"drifted":"active"}recordAnomaly(){this.windowAnomalyCount+=1,this.windowTrackCount>0&&this.windowAnomalyCount/this.windowTrackCount>this.maxAnomalyRate&&(this.drifted=!0)}};var dt=256;function At(o){return!(o.type!=="transition"||typeof o.from!="string"||typeof o.to!="string"||o.from.length===0||o.to.length===0||o.from.length>256||o.to.length>256)}function Mt(o){return!(o.type!=="counter"||typeof o.key!="string"||o.key.length===0||o.key.length>256||typeof o.by!="number"||!Number.isFinite(o.by))}var x=class{constructor(t,e,r,s=new Map){if(this.graph=e,this.bloom=r,this.counters=s,typeof BroadcastChannel>"u"){this.channel=null,this.isActive=!1;return}this.channel=new BroadcastChannel(t),this.isActive=!0,this.channel.onmessage=n=>{this.handleMessage(n.data)}}broadcast(t,e){if(!this.channel)return;let r={type:"transition",from:t,to:e};this.channel.postMessage(r)}broadcastCounter(t,e){if(!this.channel)return;let r={type:"counter",key:t,by:e};this.channel.postMessage(r)}applyRemote(t,e){this.bloom.add(t),this.bloom.add(e),this.graph.incrementTransition(t,e)}applyRemoteCounter(t,e){if(!this.counters.has(t)&&this.counters.size>=50)return;let r=this.counters.get(t)??0;this.counters.set(t,r+e)}close(){this.channel&&(this.channel.onmessage=null,this.channel.close())}handleMessage(t){if(typeof t!="object"||t===null)return;let e=t;if(e.type==="transition"){if(!At(e))return;this.applyRemote(e.from,e.to)}else if(e.type==="counter"){if(!Mt(e))return;this.applyRemoteCounter(e.key,e.by)}}};var X=class{constructor(t){this.broadcastSync=new x(t.channelName,t.graph,t.bloom,t.counters),this.isSuspected=t.isSuspected}onAfterEvaluation(t,e){this.isSuspected()||this.broadcastSync.broadcast(t,e)}onCounterIncrement(t,e){this.isSuspected()||this.broadcastSync.broadcastCounter(t,e)}destroy(){this.broadcastSync.close()}};var V=class o{constructor(t={}){this.emitter=new A;this.previousState=null;this.previousStateEnteredAt=0;this.recentTrajectory=[];this.counters=new Map;this.runBotProtectionStage=t=>{if(!this.botProtection)return;this.signalEngine.recordBotCheck(t.now).transitionedToBot&&this.emitter.emit("bot_detected",{state:t.state})};this.runBloomStage=t=>{t.isNewToBloom=!this.bloom.check(t.state);let e=this.benchmark.now();this.bloom.add(t.state),this.benchmark.record("bloomAdd",e)};this.runTransitionContextStage=t=>{t.from=this.previousState,this.previousState=t.state;for(let e=0;e<this.policies.length;e+=1)this.policies[e].onTrackContext?.(t);this.previousStateEnteredAt=t.now,this.recentTrajectory.push(t.state),this.recentTrajectory.length>32&&this.recentTrajectory.shift()};this.runGraphAndSignalStage=t=>{if(this.botProtection&&this.signalEngine.suspected){t.isNewToBloom&&this.persistenceCoordinator.markDirty();return}if(t.from){let e=this.benchmark.now();this.graph.incrementTransition(t.from,t.state),this.benchmark.record("incrementTransition",e),this.signalEngine.recordTransition(t.from,t.state,this.recentTrajectory);for(let r=0;r<this.policies.length;r+=1)this.policies[r].onTransition?.(t.from,t.state,this.recentTrajectory);this.persistenceCoordinator.markDirty(),this.signalEngine.dispatch(this.signalEngine.evaluateEntropy(t.state)),this.signalEngine.dispatch(this.signalEngine.evaluateTrajectory(t.from,t.state,this.recentTrajectory));for(let r=0;r<this.policies.length;r+=1)this.policies[r].onAfterEvaluation?.(t.from,t.state);return}t.isNewToBloom&&this.persistenceCoordinator.markDirty()};this.runEmitAndPersistStage=t=>{this.emitter.emit("state_change",{from:t.from,to:t.state}),this.persistenceCoordinator.persist()};let e=ht(t);this.benchmark=new E(t.benchmark),this.timer=t.timer??new D,this.onError=t.onError,this.botProtection=e.botProtection,this.stateNormalizer=t.stateNormalizer,this.sessionId=typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2),this.assignmentGroup=Math.random()*100<e.holdoutPercent?"control":"treatment";let r=new z({storageKey:e.storageKey,persistDebounceMs:e.persistDebounceMs,persistThrottleMs:e.persistThrottleMs,storage:t.storage??new P,asyncStorage:t.asyncStorage??null,timer:this.timer,onError:t.onError});this.persistenceCoordinator=r;let s=r.restore(e.graphConfig);this.bloom=s?.bloom??new y(t.bloom),this.graph=s?.graph??new u(e.graphConfig),this.baseline=t.baseline?u.fromJSON(t.baseline,e.graphConfig):null,r.attach(this.graph,this.bloom);let n=new I(e.driftMaxAnomalyRate,e.driftEvaluationWindowMs),i=[n];this.signalEngine=new C({graph:this.graph,baseline:this.baseline,timer:this.timer,benchmark:this.benchmark,emitter:this.emitter,assignmentGroup:this.assignmentGroup,eventCooldownMs:e.eventCooldownMs,dwellTimeMinSamples:e.dwellTimeMinSamples,dwellTimeZScoreThreshold:e.dwellTimeZScoreThreshold,hesitationCorrelationWindowMs:e.hesitationCorrelationWindowMs,trajectorySmoothingEpsilon:e.trajectorySmoothingEpsilon,driftPolicy:n}),e.dwellTimeEnabled&&i.push(new K({isSuspected:()=>this.signalEngine.suspected,evaluateDwellTime:(a,l)=>{this.signalEngine.dispatch(this.signalEngine.evaluateDwellTime(a,l))},getPreviousStateEnteredAt:()=>this.previousStateEnteredAt,emitter:this.emitter})),e.enableBigrams&&i.push(new Z(this.graph,e.bigramFrequencyThreshold)),e.crossTabSync&&i.push(new X({channelName:`passiveintent-sync:${e.storageKey}`,graph:this.graph,bloom:this.bloom,counters:this.counters,isSuspected:()=>this.signalEngine.suspected})),this.policies=i,this.lifecycleCoordinator=new W({lifecycleAdapter:t.lifecycleAdapter,timer:this.timer,dwellTimeEnabled:e.dwellTimeEnabled,emitter:this.emitter,onAdjustBaseline:a=>{this.previousStateEnteredAt+=a},onResetBaseline:()=>{this.previousStateEnteredAt=this.timer.now()},hasPreviousState:()=>this.previousState!==null,getPreviousState:()=>this.previousState,onExitIntent:()=>{if(this.previousState===null)return;let a=this.graph.getLikelyNextStates(this.previousState,.4);a.length!==0&&this.emitter.emit("exit_intent",{state:this.previousState,likelyNext:a[0].state})}}),this.trackStages=[this.runBotProtectionStage,this.runBloomStage,this.runTransitionContextStage,this.runGraphAndSignalStage,this.runEmitAndPersistStage]}on(t,e){return this.emitter.on(t,e)}static async createAsync(t){if(!t.asyncStorage)throw new Error("IntentManager.createAsync() requires config.asyncStorage");let e=t.storageKey??"passive-intent",r=await t.asyncStorage.getItem(e),s={getItem:()=>r,setItem:()=>{}},{storage:n,...i}=t;return new o({...i,storage:s})}track(t){if(t=R(t),this.stateNormalizer)try{let n=this.stateNormalizer(t),i=String(n);if(i==="")return;t=i}catch(n){this.onError&&this.onError({code:"VALIDATION",message:`IntentManager.track(): stateNormalizer threw: ${n instanceof Error?n.message:String(n)}`});return}if(t===""){this.onError&&this.onError({code:"VALIDATION",message:"IntentManager.track(): state label must not be an empty string"});return}let e=this.timer.now(),r=this.benchmark.now();for(let n=0;n<this.policies.length;n+=1)this.policies[n].onTrackStart?.(e);let s={state:t,now:e,trackStart:r,from:null,isNewToBloom:!1};for(let n=0;n<this.trackStages.length;n+=1)this.trackStages[n](s);this.benchmark.record("track",r)}get _previousStateEnteredAt(){return this.previousStateEnteredAt}hasSeen(t){let e=this.benchmark.now(),r=this.bloom.check(t);return this.benchmark.record("bloomCheck",e),r}resetSession(){this.recentTrajectory=[],this.previousState=null,this.previousStateEnteredAt=0}exportGraph(){return this.graph.toJSON()}predictNextStates(t=.3,e){if(this.previousState===null)return[];let r=this.graph.getLikelyNextStates(this.previousState,t);return e?r.filter(({state:s})=>e(s)):r}flushNow(){this.persistenceCoordinator.flushNow()}destroy(){this.persistenceCoordinator.flushNow(),this.persistenceCoordinator.close(),this.emitter.removeAll(),this.lifecycleCoordinator.destroy();for(let t=0;t<this.policies.length;t+=1)this.policies[t].destroy?.()}getTelemetry(){return{sessionId:this.sessionId,transitionsEvaluated:this.signalEngine.transitionsEvaluated,botStatus:this.signalEngine.suspected?"suspected_bot":"human",anomaliesFired:this.signalEngine.anomaliesFired,engineHealth:this.persistenceCoordinator.engineHealth,baselineStatus:this.signalEngine.baselineStatus,assignmentGroup:this.assignmentGroup}}trackConversion(t){this.emitter.emit("conversion",t)}incrementCounter(t,e=1){if(t==="")return this.onError&&this.onError({code:"VALIDATION",message:"IntentManager.incrementCounter(): key must not be an empty string"}),0;if(!Number.isFinite(e))return this.onError&&this.onError({code:"VALIDATION",message:`IntentManager.incrementCounter(): 'by' must be a finite number, got ${e}`}),this.counters.get(t)??0;if(!this.counters.has(t)&&this.counters.size>=50)return this.onError&&this.onError({code:"LIMIT_EXCEEDED",message:"IntentManager.incrementCounter(): max unique counter keys (50) reached"}),0;let r=(this.counters.get(t)??0)+e;this.counters.set(t,r);for(let s=0;s<this.policies.length;s+=1)this.policies[s].onCounterIncrement?.(t,e);return r}getCounter(t){return this.counters.get(t)??0}resetCounter(t){this.counters.delete(t)}getPerformanceReport(){let t=this.graph.toJSON();return this.benchmark.report({stateCount:this.graph.stateCount(),totalTransitions:this.graph.totalTransitions(),bloomBitsetBytes:this.bloom.getBitsetByteSize(),serializedGraphBytes:this.benchmark.serializedSizeBytes(t)})}};export{rt as ATTENTION_RETURN_THRESHOLD_MS,M as AnomalyDispatcher,E as BenchmarkRecorder,y as BloomFilter,x as BroadcastSync,_ as BrowserLifecycleAdapter,P as BrowserStorageAdapter,D as BrowserTimerAdapter,I as DriftProtectionPolicy,A as EventEmitter,nt as IDLE_CHECK_INTERVAL_MS,V as IntentManager,w as MAX_PLAUSIBLE_DWELL_MS,dt as MAX_STATE_LENGTH,u as MarkovGraph,et as MemoryStorageAdapter,C as SignalEngine,H as USER_IDLE_THRESHOLD_MS,st as computeBloomConfig,R as normalizeRouteState};
2
+ //# sourceMappingURL=index.js.map