@passiveintent/core 1.0.0 → 1.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1018 -711
- package/dist/factory.d.ts +142 -0
- package/dist/factory.d.ts.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +72 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/intent-sdk.d.ts +1 -0
- package/dist/intent-sdk.d.ts.map +1 -1
- package/package.json +99 -99
package/dist/index.d.ts
CHANGED
|
@@ -16,4 +16,76 @@ export type { IntentEventName, IntentEventMap, HighEntropyPayload, TrajectoryAno
|
|
|
16
16
|
export { BrowserStorageAdapter, BrowserTimerAdapter, MemoryStorageAdapter, BrowserLifecycleAdapter, } from './adapters.js';
|
|
17
17
|
export type { StorageAdapter, AsyncStorageAdapter, TimerAdapter, TimerHandle, LifecycleAdapter, } from './adapters.js';
|
|
18
18
|
export type { BenchmarkConfig, MemoryFootprintReport, OperationStats, PerformanceReport, } from './performance-instrumentation.js';
|
|
19
|
+
/**
|
|
20
|
+
* Raw IntentEngine class for enterprise / cross-platform use cases.
|
|
21
|
+
*
|
|
22
|
+
* Requires explicit injection of all four adapter interfaces.
|
|
23
|
+
* Use `createBrowserIntent()` instead for standard web applications.
|
|
24
|
+
*
|
|
25
|
+
* ```ts
|
|
26
|
+
* import { IntentEngine } from '@passiveintent/core';
|
|
27
|
+
*
|
|
28
|
+
* const engine = new IntentEngine({
|
|
29
|
+
* stateModel: myModel,
|
|
30
|
+
* persistence: myStorage,
|
|
31
|
+
* lifecycle: myLifecycle,
|
|
32
|
+
* input: myInput,
|
|
33
|
+
* });
|
|
34
|
+
* ```
|
|
35
|
+
*/
|
|
36
|
+
export { PropensityCalculator } from './engine/propensity-calculator.js';
|
|
37
|
+
export { IntentEngine } from './engine/intent-engine.js';
|
|
38
|
+
export type { IntentEngineConfig } from './types/microkernel.js';
|
|
39
|
+
/**
|
|
40
|
+
* `createBrowserIntent` — primary entry point for standard web applications.
|
|
41
|
+
*
|
|
42
|
+
* Automatically wires `ContinuousGraphModel`, `LocalStorageAdapter`,
|
|
43
|
+
* `BrowserLifecycleAdapter`, and `MouseKinematicsAdapter` into a new
|
|
44
|
+
* `IntentEngine` and returns it ready to use.
|
|
45
|
+
*
|
|
46
|
+
* ```ts
|
|
47
|
+
* import { createBrowserIntent } from '@passiveintent/core';
|
|
48
|
+
*
|
|
49
|
+
* const intent = createBrowserIntent({ storageKey: 'my-app' });
|
|
50
|
+
* intent.on('high_entropy', ({ state }) => showHelpWidget(state));
|
|
51
|
+
* intent.on('exit_intent', ({ likelyNext }) => prefetch(likelyNext));
|
|
52
|
+
* ```
|
|
53
|
+
*/
|
|
54
|
+
export { createBrowserIntent } from './factory.js';
|
|
55
|
+
export type { BrowserConfig } from './factory.js';
|
|
56
|
+
/**
|
|
57
|
+
* TypeScript contracts for building custom plugins against the IntentEngine
|
|
58
|
+
* microkernel. Import the namespace to implement your own adapters:
|
|
59
|
+
*
|
|
60
|
+
* ```ts
|
|
61
|
+
* import type { CoreInterfaces } from '@passiveintent/core';
|
|
62
|
+
*
|
|
63
|
+
* // React Native navigation adapter
|
|
64
|
+
* class ReactNativeInputAdapter implements CoreInterfaces.IInputAdapter {
|
|
65
|
+
* subscribe(onState: (state: string) => void): () => void {
|
|
66
|
+
* return navigation.addListener('state', (e) => onState(e.data.state.routes.at(-1)?.name ?? '/'));
|
|
67
|
+
* }
|
|
68
|
+
* destroy(): void {}
|
|
69
|
+
* }
|
|
70
|
+
*
|
|
71
|
+
* // Custom swipe-based input for dating / food-delivery apps
|
|
72
|
+
* class SwipeKinematicsAdapter implements CoreInterfaces.IInputAdapter {
|
|
73
|
+
* subscribe(onState: (state: string) => void): () => void {
|
|
74
|
+
* return swipeEmitter.on('swipe', ({ direction, cardId }) =>
|
|
75
|
+
* onState(`card:${cardId}:${direction}`));
|
|
76
|
+
* }
|
|
77
|
+
* destroy(): void {}
|
|
78
|
+
* }
|
|
79
|
+
* ```
|
|
80
|
+
*
|
|
81
|
+
* Available contracts:
|
|
82
|
+
* - `IInputAdapter` — push-based navigation/behavioral input
|
|
83
|
+
* - `ILifecycleAdapter` — platform pause / resume / exit-intent
|
|
84
|
+
* - `IStateModel` — Markov + Bloom state model
|
|
85
|
+
* - `IPersistenceAdapter` — synchronous key-value storage
|
|
86
|
+
* - `IntentEngineConfig` — full constructor config shape
|
|
87
|
+
* - `EntropyResult` — return type of `IStateModel.evaluateEntropy`
|
|
88
|
+
* - `TrajectoryResult` — return type of `IStateModel.evaluateTrajectory`
|
|
89
|
+
*/
|
|
90
|
+
export type * as CoreInterfaces from './types/microkernel.js';
|
|
19
91
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +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"}
|
|
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;AAM1C;;;;;;;;;;;;;;;;GAgBG;AACH,OAAO,EAAE,oBAAoB,EAAE,MAAM,mCAAmC,CAAC;AACzE,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AACzD,YAAY,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAMjE;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AACnD,YAAY,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAMlD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,YAAY,KAAK,cAAc,MAAM,wBAAwB,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -1,2 +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};
|
|
1
|
+
function T(s){let e=[];for(let r=0;r<s.length;r+=32768){let i=s.subarray(r,Math.min(r+32768,s.length));e.push(String.fromCharCode.apply(null,i))}return btoa(e.join(""))}function S(s){let t=atob(s),e=new Uint8Array(t.length);for(let r=0;r<t.length;r+=1)e[r]=t.charCodeAt(r);return e}function mt(s,t=2166136261){let e=t>>>0;for(let r=0;r<s.length;r+=1)e^=s.charCodeAt(r),e+=(e<<1)+(e<<4)+(e<<7)+(e<<8)+(e<<24);return e>>>0}var G=(()=>{let s=globalThis.__PFIE_WM__;return(typeof s=="number"?s:2343432205)>>>0})(),w=new Uint32Array(2),y=class s{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=w[0],r=w[1];for(let i=0;i<this.hashCount;i+=1){let n=(e+i*r>>>0)%this.bitSize;this.setBit(n)}}check(t){this.computeHashes(t);let e=w[0],r=w[1];for(let i=0;i<this.hashCount;i+=1){let n=(e+i*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,i=r*r,n=Math.ceil(-(t*Math.log(e))/i),o=Math.max(1,Math.round(n/t*r));return{bitSize:n,hashCount:o}}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 T(this.bits)}static fromBase64(t,e={}){return new s(e,S(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){w[0]=(mt(t,2166136261)^G^G)>>>0,w[1]=(mt(t,16777619)^G^G)>>>0}};function dt(s,t){s<=0&&(s=1),t<=0&&(t=1e-10),t>=1&&(t=.99);let e=Math.ceil(-(s*Math.log(t))/(Math.LN2*Math.LN2)),r=Math.max(1,Math.round(e/s*Math.log(2))),i=Math.exp(-(r*s)/e),n=Math.pow(1-i,r);return{bitSize:e,hashCount:r,estimatedFpRate:n}}var d=class s{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),i=this.ensureState(e),n=this.rows.get(r)??{total:0,toCounts:new Map},o=(n.toCounts.get(i)??0)+1;n.toCounts.set(i,o),n.total+=1,this.rows.set(r,n)}getProbability(t,e){let r=this.stateToIndex.get(t),i=this.stateToIndex.get(e);if(r===void 0||i===void 0)return 0;let n=this.rows.get(r);if(!n||n.total===0)return 0;let o=n.toCounts.get(i)??0;return this.smoothingAlpha===0?o/n.total:(o+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 i=0;if(this.smoothingAlpha===0)r.toCounts.forEach(n=>{let o=n/r.total;o>0&&(i-=o*Math.log(o))});else{let n=this.stateToIndex.size,o=r.total+this.smoothingAlpha*n;r.toCounts.forEach(l=>{let h=(l+this.smoothingAlpha)/o;i-=h*Math.log(h)});let a=n-r.toCounts.size;if(a>0){let l=this.smoothingAlpha/o;l>0&&(i-=a*l*Math.log(l))}}return i}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 i=Math.max(2,r.toCounts.size),n=Math.log(i);if(n<=0)return 0;let o=0;r.toCounts.forEach(l=>{let h=l/r.total;h>0&&(o-=h*Math.log(h))});let a=o/n;return Math.min(1,Math.max(0,a))}static logLikelihoodTrajectory(t,e,r=.01){if(e.length<2)return 0;let i=0;for(let n=0;n<e.length-1;n+=1){let o=t.getProbability(e[n],e[n+1]);i+=Math.log(o>0?o:r)}return i}getLikelyNextStates(t,e){let r=this.stateToIndex.get(t);if(r===void 0)return[];let i=this.rows.get(r);if(!i||i.total===0)return[];let n=[],o=this.smoothingAlpha===0?i.total:i.total+this.smoothingAlpha*this.stateToIndex.size;return i.toCounts.forEach((a,l)=>{let h=this.smoothingAlpha===0?a/o:(a+this.smoothingAlpha)/o;if(h>=e){let m=this.indexToState[l];m&&m!==""&&n.push({state:m,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 o=this.rows.get(n);e.push({index:n,total:o?.total??0})}),e.sort((n,o)=>n.total-o.total);let r=Math.max(1,Math.min(Math.ceil(t*.2),t-this.maxStates)),i=new Set;for(let n=0;n<r&&n<e.length;n+=1)i.add(e[n].index);i.forEach(n=>{this.rows.delete(n)}),this.rows.forEach(n=>{let o=0;i.forEach(a=>{let l=n.toCounts.get(a);l!==void 0&&(o+=l,n.toCounts.delete(a))}),n.total-=o}),i.forEach(n=>{let o=this.indexToState[n];o!==void 0&&o!==""&&this.stateToIndex.delete(o),this.freedIndices.push(n),this.indexToState[n]=""})}toJSON(){let t=[];return this.rows.forEach((e,r)=>{let i=[];e.toCounts.forEach((n,o)=>{i.push([o,n])}),t.push([r,e.total,i])}),{states:[...this.indexToState],rows:t,freedIndices:[...this.freedIndices]}}static fromJSON(t,e={}){let r=new s(e),i=new Set(t.freedIndices);for(let n=0;n<t.states.length;n+=1){let o=t.states[n];if(r.indexToState.push(o),i.has(n)){if(o!=="")throw new Error(`MarkovGraph.fromJSON: slot ${n} is listed in freedIndices but has non-empty label "${o}"`);r.freedIndices.push(n)}else{if(o==="")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(o,n)}}for(let n=0;n<t.rows.length;n+=1){let[o,a,l]=t.rows[n],h={total:a,toCounts:new Map};for(let m=0;m<l.length;m+=1){let[p,g]=l[m];h.toCounts.set(p,g)}r.rows.set(o,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 i=new Uint8Array(e),n=new DataView(i.buffer),o=0;n.setUint8(o,2),o+=1,n.setUint16(o,this.indexToState.length,!0),o+=2;for(let a=0;a<this.indexToState.length;a+=1){let l=r[a];n.setUint16(o,l.byteLength,!0),o+=2,i.set(l,o),o+=l.byteLength}n.setUint16(o,this.freedIndices.length,!0),o+=2;for(let a=0;a<this.freedIndices.length;a+=1)n.setUint16(o,this.freedIndices[a],!0),o+=2;return n.setUint16(o,this.rows.size,!0),o+=2,this.rows.forEach((a,l)=>{n.setUint16(o,l,!0),o+=2,n.setUint32(o,a.total,!0),o+=4,n.setUint16(o,a.toCounts.size,!0),o+=2,a.toCounts.forEach((h,m)=>{n.setUint16(o,m,!0),o+=2,n.setUint32(o,h,!0),o+=4})}),i}static fromBinary(t,e={}){let r=new s(e),i=new TextDecoder,n=new DataView(t.buffer,t.byteOffset,t.byteLength),o=0,a=n.getUint8(o);if(o+=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(o,!0);o+=2;let h=[];for(let c=0;c<l;c+=1){let u=n.getUint16(o,!0);o+=2,h.push(i.decode(t.subarray(o,o+u))),o+=u}let m=n.getUint16(o,!0);o+=2;let p=new Set;for(let c=0;c<m;c+=1)p.add(n.getUint16(o,!0)),o+=2;for(let c=0;c<h.length;c+=1){let u=h[c];if(r.indexToState.push(u),p.has(c)){if(u!=="")throw new Error(`MarkovGraph.fromBinary: slot ${c} is listed as freed but has non-empty label "${u}"`);r.freedIndices.push(c)}else{if(u==="")throw new Error(`MarkovGraph.fromBinary: slot ${c} 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(u,c)}}let g=n.getUint16(o,!0);o+=2;for(let c=0;c<g;c+=1){let u=n.getUint16(o,!0);o+=2;let D=n.getUint32(o,!0);o+=4;let rt=n.getUint16(o,!0);o+=2;let E=new Map;for(let j=0;j<rt;j+=1){let H=n.getUint16(o,!0);o+=2;let N=n.getUint32(o,!0);o+=4,E.set(H,N)}r.rows.set(u,{total:D,toCounts:E})}return r}};function M(){return{count:0,totalMs:0,maxMs:0,samples:[]}}function kt(s,t,e){s.count+=1,s.totalMs+=t,t>s.maxMs&&(s.maxMs=t),s.samples.length<e?s.samples.push(t):e>0&&(s.samples[s.count%e]=t)}function pt(s,t){if(s.length===0)return 0;let e=Math.max(0,Math.min(s.length-1,Math.ceil(t*s.length)-1));return s[e]}function A(s){if(s.count===0)return{count:0,avgMs:0,p95Ms:0,p99Ms:0,maxMs:0};let t=[...s.samples].sort((e,r)=>e-r);return{count:s.count,avgMs:s.totalMs/s.count,p95Ms:pt(t,.95),p99Ms:pt(t,.99),maxMs:s.maxMs}}var ut=typeof TextEncoder<"u"?new TextEncoder:null,I=class{constructor(t={}){this.enabled=t.enabled??!1,this.maxSamples=t.maxSamples??4096,this.stats={track:M(),bloomAdd:M(),bloomCheck:M(),incrementTransition:M(),entropyComputation:M(),divergenceComputation:M()}}now(){return this.enabled?performance.now():0}record(t,e){this.enabled&&kt(this.stats[t],performance.now()-e,this.maxSamples)}report(t){return{benchmarkEnabled:this.enabled,track:A(this.stats.track),bloomAdd:A(this.stats.bloomAdd),bloomCheck:A(this.stats.bloomCheck),incrementTransition:A(this.stats.incrementTransition),entropyComputation:A(this.stats.entropyComputation),divergenceComputation:A(this.stats.divergenceComputation),memoryFootprint:t}}serializedSizeBytes(t){let e=JSON.stringify(t);return ut?ut.encode(e).byteLength:e.length}};var B=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)}},R=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()}},st=class{constructor(){this.store=new Map}getItem(t){return this.store.get(t)??null}setItem(t,e){this.store.set(t,e)}},b=class b{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<b.INTERACTION_THROTTLE_MS)){this.interactionLastFired=r;for(let i of this.interactionCallbacks)i()}};let e={passive:!0};for(let r of b.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 b.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 i of this.exitIntentCallbacks)i()},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}};b.INTERACTION_THROTTLE_MS=1e3,b.INTERACTION_EVENTS=["mousemove","scroll","touchstart","keydown"];var v=b;var Pt=/[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/gi,Lt=/\b[0-9a-f]{24}\b/gi,_t=/\/\d{4,}(?=\/|$)/g;function C(s){let t=s.indexOf("?"),e=t!==-1?s.slice(0,t):s,r=e.indexOf("#");return r!==-1&&(e=e.slice(0,r)),e=e.replace(Pt,":id").replace(Lt,":id").replace(_t,"/:id"),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}var x=18e5,at=15e3,F=12e4,gt=5e3;function yt(s){if(!Number.isFinite(s))return NaN;let t=Math.min(.5,Math.max(.001,s)),e=Math.sqrt(-2*Math.log(t));return e-(2.515517+e*(.802853+e*.010328))/(1+e*(1.432788+e*(.189269+e*.001308)))}function ft(s={}){let t=s.botProtection??!0,e=s.dwellTime?.enabled??!1,r=s.crossTabSync===!0,i=s.holdoutConfig?.percentage,n=Number.isFinite(i)?Math.min(100,Math.max(0,i)):i??0,o=s.graph?.targetFPR,a={...s.graph,baselineMeanLL:s.baselineMeanLL??s.graph?.baselineMeanLL,baselineStdLL:s.baselineStdLL??s.graph?.baselineStdLL,smoothingAlpha:s.smoothingAlpha??s.graph?.smoothingAlpha,divergenceThreshold:Number.isFinite(o)?yt(o):s.graph?.divergenceThreshold},l=a.smoothingEpsilon,h=typeof l=="number"&&Number.isFinite(l)&&l>0?l:.01,m=s.storageKey??"passive-intent",p=s.persistDebounceMs,g=Number.isFinite(p)&&p>=0?Math.floor(p):2e3,c=s.persistThrottleMs,u=Number.isFinite(c)&&c>=0?Math.floor(c):0,D=s.eventCooldownMs,rt=Number.isFinite(D)&&D>=0?Math.floor(D):0,E=s.dwellTime?.minSamples,j=Number.isFinite(E)&&E>=1?Math.floor(E):10,H=s.dwellTime?.targetFPR,N=s.dwellTime?.zScoreThreshold,wt=Number.isFinite(H)?yt(H):Number.isFinite(N)&&N>0?N:2.5,Mt=s.enableBigrams??!1,nt=s.bigramFrequencyThreshold,At=Number.isFinite(nt)&&nt>=1?Math.floor(nt):5,ct=s.driftProtection?.maxAnomalyRate,It=Number.isFinite(ct)?Math.min(1,Math.max(0,ct)):.4,it=s.driftProtection?.evaluationWindowMs,Ct=Number.isFinite(it)&&it>0?Math.floor(it):3e5,ot=s.hesitationCorrelationWindowMs,xt=Number.isFinite(ot)&&ot>=0?Math.floor(ot):3e4;return{botProtection:t,dwellTimeEnabled:e,crossTabSync:r,holdoutPercent:n,graphConfig:a,trajectorySmoothingEpsilon:h,storageKey:m,persistDebounceMs:g,persistThrottleMs:u,eventCooldownMs:rt,dwellTimeMinSamples:j,dwellTimeZScoreThreshold:wt,enableBigrams:Mt,bigramFrequencyThreshold:At,driftMaxAnomalyRate:It,driftEvaluationWindowMs:Ct,hesitationCorrelationWindowMs:xt,plugins:s.plugins??[]}}var f=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(i=>i(e))}removeAll(){this.listeners.clear()}};var U=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=[],i=t<10?0:this.trackTimestampIndex;for(let n=0;n<t-1;n+=1){let o=(i+n)%10,a=(i+n+1)%10,l=this.trackTimestamps[a]-this.trackTimestamps[o];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 o=0;for(let a=0;a<r.length;a+=1){let l=r[a]-n;o+=l*l}o/=r.length,o<100&&(e+=1)}this.isSuspectedBot=e>=5}};function bt(s,t){let e=s?.count??0,r=s?.meanMs??0,i=s?.m2??0,n=e+1,o=t-r,a=r+o/n,l=t-a,h=i+o*l;return{count:n,meanMs:a,m2:h}}function vt(s){return s.count<2?0:Math.sqrt(s.m2/s.count)}function Dt(s){throw new Error(`Unhandled AnomalyDecision kind: ${s.kind}`)}var k=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:Dt(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}))}};function Et(s){return s<10?"low":s<30?"medium":"high"}var P=class{constructor(t){this.entropyGuard=new U;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 k({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),i=this.graph.normalizedEntropyForState(t);return this.benchmark.record("entropyComputation",e),i>=this.graph.highEntropyThreshold?{kind:"high_entropy",payload:{state:t,entropy:r,normalizedEntropy:i}}:null}evaluateTrajectory(t,e,r){let i=this.benchmark.now();if(this.driftPolicy.isDrifted)return this.benchmark.record("divergenceComputation",i),null;if(this.entropyGuard.suspected)return this.benchmark.record("divergenceComputation",i),null;if(r.length<16)return this.benchmark.record("divergenceComputation",i),null;if(!this.baseline)return this.benchmark.record("divergenceComputation",i),null;let n=d.logLikelihoodTrajectory(this.graph,r,this.trajectorySmoothingEpsilon),o=d.logLikelihoodTrajectory(this.baseline,r,this.trajectorySmoothingEpsilon),a=Math.max(1,r.length-1),l=o/a,h=-Math.abs(this.graph.divergenceThreshold),m=typeof this.graph.baselineMeanLL=="number"&&typeof this.graph.baselineStdLL=="number"&&Number.isFinite(this.graph.baselineMeanLL)&&Number.isFinite(this.graph.baselineStdLL)&&this.graph.baselineStdLL>0,p=m?this.graph.baselineStdLL*Math.sqrt(32/a):0,g=m?(l-this.graph.baselineMeanLL)/p:l,c=m?g<=h:l<=h;if(this.benchmark.record("divergenceComputation",i),c){let u=this.graph.rowTotal(t);return{kind:"trajectory_anomaly",payload:{stateFrom:t,stateTo:e,realLogLikelihood:n,expectedBaselineLogLikelihood:o,zScore:g,sampleSize:u,confidence:Et(u)}}}return null}evaluateDwellTime(t,e){if(e<=0)return null;let r=bt(this.dwellStats.get(t),e);if(this.dwellStats.set(t,r),r.count<this.dwellTimeMinSamples)return null;let i=vt(r);if(i<=0)return null;let n=(e-r.meanMs)/i;if(Math.abs(n)>=this.dwellTimeZScoreThreshold){let o=r.count;return{kind:"dwell_time_anomaly",payload:{state:t,dwellMs:e,meanMs:r.meanMs,stdMs:i,zScore:n,sampleSize:o,confidence:Et(o)},isPositiveZScore:n>0}}return null}};var z=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 i;try{let n=e.toBinary();i=T(n)}catch(n){return this.ctx.reportError("SERIALIZE",n instanceof Error?n.message:String(n),n),null}return JSON.stringify({bloomBase64:r.toBase64(),graphBinary:i})}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 i=t-r;this.throttleTimer=this.ctx.getTimer().setTimeout(()=>{this.throttleTimer=null,this.persist()},i)}return!0}}return!1}},W=class extends z{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)}}},K=class extends z{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(),i;try{i=r.setItem(this.ctx.getStorageKey(),e)}catch(n){this.handleAsyncWriteError(n);return}i.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 $=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 K(this):this.strategy=new W(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),i;if(r.graphBinary){let o=S(r.graphBinary);i=d.fromBinary(o,t)}else if(r.graph)i=d.fromJSON(r.graph,t);else return null;return{bloom:r.bloomBase64?y.fromBase64(r.bloomBase64):new y,graph:i}}catch(r){if(this.onErrorCb){let i=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:i}})}return null}}persist(){this.strategy.persist()}flushNow(){this.strategy.flushNow()}close(){this.isClosedFlag=!0,this.strategy.close()}};var V=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 v: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=()=>{this.idleCheckTimer!==null&&this.timer.clearTimeout(this.idleCheckTimer),this.idleCheckTimer=this.timer.setTimeout(()=>{if(this.idleCheckTimer=null,this.isIdle||!this.hasPreviousState())return;this.isIdle=!0,this.idleStartedAt=this.lastInteractionAt+12e4;let i=this.getPreviousState();i!==null&&this.emitter.emit("user_idle",{state:i,idleMs:this.timer.now()-this.idleStartedAt})},12e4)},r=t.onInteraction(()=>{if(this.lastInteractionAt=this.timer.now(),this.isIdle){let i=this.timer.now()-this.idleStartedAt;this.isIdle=!1,this.dwellTimeEnabled&&this.hasPreviousState()&&this.onAdjustBaseline(i);let n=this.getPreviousState();n!==null&&this.emitter.emit("user_resumed",{state:n,idleMs:i})}e()});r&&(this.interactionUnsub=r,e())}stopIdleTracking(){this.interactionUnsub?.(),this.interactionUnsub=null,this.idleCheckTimer!==null&&(this.timer.clearTimeout(this.idleCheckTimer),this.idleCheckTimer=null)}};var X=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}`,o=`${t}\u2192${e}`;this.graph.rowTotal(t)>=this.bigramFrequencyThreshold&&this.graph.incrementTransition(n,o)}};var L=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 St=256;function Rt(s){return!(s.type!=="transition"||typeof s.from!="string"||typeof s.to!="string"||s.from.length===0||s.to.length===0||s.from.length>256||s.to.length>256)}function Ot(s){return!(s.type!=="counter"||typeof s.key!="string"||s.key.length===0||s.key.length>256||typeof s.by!="number"||!Number.isFinite(s.by))}var _=class{constructor(t,e,r,i=new Map){if(this.graph=e,this.bloom=r,this.counters=i,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(!Rt(e))return;this.applyRemote(e.from,e.to)}else if(e.type==="counter"){if(!Ot(e))return;this.applyRemoteCounter(e.key,e.by)}}};var q=class{constructor(t){this.broadcastSync=new _(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 J=class s{constructor(t={}){this.emitter=new f;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.callPolicy(e,()=>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.callPolicy(r,()=>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.callPolicy(r,()=>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=ft(t);this.benchmark=new I(t.benchmark),this.timer=t.timer??new R,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 $({storageKey:e.storageKey,persistDebounceMs:e.persistDebounceMs,persistThrottleMs:e.persistThrottleMs,storage:t.storage??new B,asyncStorage:t.asyncStorage??null,timer:this.timer,onError:t.onError});this.persistenceCoordinator=r;let i=r.restore(e.graphConfig);this.bloom=i?.bloom??new y(t.bloom),this.graph=i?.graph??new d(e.graphConfig),this.baseline=t.baseline?d.fromJSON(t.baseline,e.graphConfig):null,r.attach(this.graph,this.bloom);let n=new L(e.driftMaxAnomalyRate,e.driftEvaluationWindowMs),o=[n];this.signalEngine=new P({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&&o.push(new X({isSuspected:()=>this.signalEngine.suspected,evaluateDwellTime:(a,l)=>{this.signalEngine.dispatch(this.signalEngine.evaluateDwellTime(a,l))},getPreviousStateEnteredAt:()=>this.previousStateEnteredAt,emitter:this.emitter})),e.enableBigrams&&o.push(new Z(this.graph,e.bigramFrequencyThreshold)),e.crossTabSync&&o.push(new q({channelName:`passiveintent-sync:${e.storageKey}`,graph:this.graph,bloom:this.bloom,counters:this.counters,isSuspected:()=>this.signalEngine.suspected})),this.pluginStartIndex=o.length,this.policies=[...o,...e.plugins],this.lifecycleCoordinator=new V({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]}callPolicy(t,e){if(t<this.pluginStartIndex)e();else try{e()}catch(r){this.onError&&this.onError({code:"VALIDATION",message:`IntentManager: plugin[${t-this.pluginStartIndex}] threw: ${r instanceof Error?r.message:String(r)}`,originalError:r})}}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),i={getItem:()=>r,setItem:()=>{}},{storage:n,...o}=t;return new s({...o,storage:i})}track(t){if(t=C(t),this.stateNormalizer)try{let n=this.stateNormalizer(t),o=String(n);if(o==="")return;t=o}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.callPolicy(n,()=>this.policies[n].onTrackStart?.(e));let i={state:t,now:e,trackStart:r,from:null,isNewToBloom:!1};for(let n=0;n<this.trackStages.length;n+=1)this.trackStages[n](i);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:i})=>e(i)):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.callPolicy(t,()=>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 i=0;i<this.policies.length;i+=1)this.callPolicy(i,()=>this.policies[i].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)})}};var ht=class{constructor(t=.2,e=500){this.alpha=Number.isFinite(t)&&t>=0?t:0,this.cachedBaseline=0,this.lastCalculationTime=-1/0,this.lastPropensity=0,this.THROTTLE_MS=Number.isFinite(e)&&e>=0?e:500}updateBaseline(t,e,r,i=3){let n=Number.isFinite(i)&&i>=1?Math.floor(i):3;if(e===r){this.cachedBaseline=1;return}let o=[{state:e,pathProb:1,depth:0,pathVisited:new Set([e])}],a=0;for(;o.length>0;){let l=o.shift(),h=t.getLikelyNext(l.state,0);for(let{state:m,probability:p}of h){if(l.pathVisited.has(m))continue;let g=l.pathProb*p;if(m===r)a+=g;else if(l.depth+1<n){let c=new Set(l.pathVisited);c.add(m),o.push({state:m,pathProb:g,depth:l.depth+1,pathVisited:c})}}}this.cachedBaseline=Math.min(1,a)}getRealTimePropensity(t){let e=performance.now();if(e-this.lastCalculationTime<this.THROTTLE_MS)return this.lastPropensity;if(this.cachedBaseline<=0)return this.lastCalculationTime=e,this.lastPropensity=0,0;let r=Number.isFinite(t)?t:0,i=Math.exp(-this.alpha*Math.max(0,r)),n=this.cachedBaseline*i;return this.lastPropensity=n,this.lastCalculationTime=e,n}};var jt=20,O=class{constructor(t){this.emitter=new f;this.teardowns=[];this.previousState=null;this.recentTrajectory=[];this.stateModel=t.stateModel,this.persistence=t.persistence,this.lifecycle=t.lifecycle,this.input=t.input,this.storageKey=t.storageKey??"passive-intent-engine",this.stateNormalizer=t.stateNormalizer,this.onError=t.onError;let e=null;try{e=this.persistence.load(this.storageKey)}catch(r){this.onError?.({code:"RESTORE_READ",message:`IntentEngine: failed to read persisted state: ${r instanceof Error?r.message:String(r)}`})}if(e!==null)try{this.stateModel.restore(e)}catch(r){this.onError?.({code:"RESTORE_PARSE",message:`IntentEngine: failed to restore persisted state: ${r instanceof Error?r.message:String(r)}`})}if(this.input)try{let r=this.input.subscribe(i=>this._processState(i));this.teardowns.push(r)}catch(r){this.onError?.({code:"ADAPTER_SETUP",message:`IntentEngine: input.subscribe() threw: ${r instanceof Error?r.message:String(r)}`})}try{this.teardowns.push(this.lifecycle.onPause(()=>{this._persist()}))}catch(r){this.onError?.({code:"ADAPTER_SETUP",message:`IntentEngine: lifecycle.onPause() threw: ${r instanceof Error?r.message:String(r)}`})}if(typeof this.lifecycle.onExitIntent=="function")try{this.teardowns.push(this.lifecycle.onExitIntent(()=>{if(this.previousState===null)return;let r=[];try{r=this.stateModel.getLikelyNext(this.previousState,.4)}catch(i){this.onError?.({code:"STATE_MODEL",message:`IntentEngine: stateModel.getLikelyNext() threw: ${i instanceof Error?i.message:String(i)}`})}r.length!==0&&this.emitter.emit("exit_intent",{state:this.previousState,likelyNext:r[0].state})}))}catch(r){this.onError?.({code:"ADAPTER_SETUP",message:`IntentEngine: lifecycle.onExitIntent() threw: ${r instanceof Error?r.message:String(r)}`})}}on(t,e){return this.emitter.on(t,e)}track(t){this._processState(t)}destroy(){this._persist();for(let t of this.teardowns)try{t()}catch(e){this.onError?.({code:"ADAPTER_TEARDOWN",message:`IntentEngine: teardown threw: ${e instanceof Error?e.message:String(e)}`})}try{this.lifecycle.destroy()}catch(t){this.onError?.({code:"ADAPTER_TEARDOWN",message:`IntentEngine: lifecycle.destroy() threw: ${t instanceof Error?t.message:String(t)}`})}if(this.input)try{this.input.destroy()}catch(t){this.onError?.({code:"ADAPTER_TEARDOWN",message:`IntentEngine: input.destroy() threw: ${t instanceof Error?t.message:String(t)}`})}this.emitter.removeAll()}_processState(t){let e=C(t);if(this.stateNormalizer)try{let i=this.stateNormalizer(e);if(typeof i!="string"){this.onError?.({code:"VALIDATION",message:`IntentEngine.track(): stateNormalizer must return a string, got ${typeof i}`});return}if(i==="")return;e=i}catch(i){this.onError?.({code:"VALIDATION",message:`IntentEngine.track(): stateNormalizer threw: ${i instanceof Error?i.message:String(i)}`});return}if(e===""){this.onError?.({code:"VALIDATION",message:"IntentEngine.track(): state label must not be an empty string"});return}let r=this.previousState;try{this.stateModel.markSeen(e)}catch(i){this.onError?.({code:"STATE_MODEL",message:`IntentEngine: stateModel.markSeen() threw: ${i instanceof Error?i.message:String(i)}`});return}if(r!==null)try{this.stateModel.recordTransition(r,e)}catch(i){this.onError?.({code:"STATE_MODEL",message:`IntentEngine: stateModel.recordTransition() threw: ${i instanceof Error?i.message:String(i)}`});return}if(this.previousState=e,this.recentTrajectory.push(e),this.recentTrajectory.length>jt&&this.recentTrajectory.shift(),r!==null){let i={entropy:0,normalizedEntropy:0,isHigh:!1};try{i=this.stateModel.evaluateEntropy(e)}catch(o){this.onError?.({code:"STATE_MODEL",message:`IntentEngine: stateModel.evaluateEntropy() threw: ${o instanceof Error?o.message:String(o)}`})}i.isHigh&&this.emitter.emit("high_entropy",{state:e,entropy:i.entropy,normalizedEntropy:i.normalizedEntropy});let n=null;try{n=this.stateModel.evaluateTrajectory(r,e,this.recentTrajectory)}catch(o){this.onError?.({code:"STATE_MODEL",message:`IntentEngine: stateModel.evaluateTrajectory() threw: ${o instanceof Error?o.message:String(o)}`})}if(n!==null&&n.isAnomalous){let o=n.sampleSize;this.emitter.emit("trajectory_anomaly",{stateFrom:r,stateTo:e,realLogLikelihood:n.logLikelihood,expectedBaselineLogLikelihood:n.baselineLogLikelihood,zScore:n.zScore,sampleSize:o,confidence:o<10?"low":o<30?"medium":"high"})}}this.emitter.emit("state_change",{from:r,to:e}),this._persist()}_persist(){try{this.persistence.save(this.storageKey,this.stateModel.serialize())}catch(t){this.onError?.({code:"STORAGE_WRITE",message:`IntentEngine: persistence.save() threw: ${t instanceof Error?t.message:String(t)}`})}}};var Y=class extends v{};var Ht=[25,50,75,100],Gt=.3,Ft=200,Ut=150,Q=class{constructor(){this.callback=null;this.cleanups=[];this.lastScrollPercent=-1;this.scrollDebounceTimer=null;this.lastMouseX=0;this.lastMouseY=0;this.lastMouseTime=0;this.lastVelocityZone=null;this.currentPath=""}subscribe(t){if(typeof window>"u")return()=>{};this.callback=t,this.currentPath=window.location.pathname,this.lastScrollPercent=-1,this.lastVelocityZone=null,queueMicrotask(()=>t(this.currentPath));let e=()=>this.handleNavigation(),r=()=>this.handleNavigation();window.addEventListener("popstate",e),window.addEventListener("hashchange",r),this.cleanups.push(()=>{window.removeEventListener("popstate",e),window.removeEventListener("hashchange",r)});let i=()=>this.scheduleScrollEvaluation();window.addEventListener("scroll",i,{passive:!0}),this.cleanups.push(()=>window.removeEventListener("scroll",i));let n=o=>this.sampleMouseVelocity(o);return window.addEventListener("mousemove",n,{passive:!0}),this.cleanups.push(()=>window.removeEventListener("mousemove",n)),()=>this.teardown()}destroy(){this.teardown()}handleNavigation(){typeof window>"u"||(this.currentPath=window.location.pathname,this.scrollDebounceTimer!==null&&(clearTimeout(this.scrollDebounceTimer),this.scrollDebounceTimer=null),this.lastScrollPercent=-1,this.lastVelocityZone=null,this.lastMouseTime=0,this.lastMouseX=0,this.lastMouseY=0,this.emit(this.currentPath))}scheduleScrollEvaluation(){this.scrollDebounceTimer!==null&&clearTimeout(this.scrollDebounceTimer),this.scrollDebounceTimer=setTimeout(()=>{this.scrollDebounceTimer=null,this.evaluateScrollDepth()},Ut)}evaluateScrollDepth(){if(typeof window>"u"||typeof document>"u")return;let t=window.scrollY,e=document.documentElement.scrollHeight-document.documentElement.clientHeight;if(e<=0)return;let r=Math.min(100,Math.round(t/e*100)),i=null;for(let n of Ht)r>=n&&n>this.lastScrollPercent&&(i=n);i!==null&&(this.lastScrollPercent=i,this.emit(`${this.currentPath}@scroll.${i}`))}sampleMouseVelocity(t){let e=typeof performance<"u"?performance.now():Date.now();if(this.lastMouseTime===0){this.lastMouseX=t.clientX,this.lastMouseY=t.clientY,this.lastMouseTime=e;return}let r=e-this.lastMouseTime;if(r<Ft)return;let i=t.clientX-this.lastMouseX,n=t.clientY-this.lastMouseY,a=Math.sqrt(i*i+n*n)/r;this.lastMouseX=t.clientX,this.lastMouseY=t.clientY,this.lastMouseTime=e;let l=a>=Gt?"scanning":"focused";l!==this.lastVelocityZone&&(this.lastVelocityZone=l,this.emit(`${this.currentPath}@velocity.${l}`))}emit(t){this.callback?.(t)}teardown(){for(let t of this.cleanups)t();this.cleanups.length=0,this.scrollDebounceTimer!==null&&(clearTimeout(this.scrollDebounceTimer),this.scrollDebounceTimer=null),this.callback=null}};var tt=class{constructor(t={}){this.graphConfig=t.graph??{},this.bloomConfig=t.bloom??{},this.graph=new d(this.graphConfig),this.bloom=new y(this.bloomConfig),this.baseline=t.baseline?d.fromJSON(t.baseline,this.graphConfig):null}markSeen(t){this.bloom.add(t)}hasSeen(t){return this.bloom.check(t)}recordTransition(t,e){this.graph.incrementTransition(t,e)}getLikelyNext(t,e){return this.graph.getLikelyNextStates(t,e)}evaluateEntropy(t){let e={entropy:0,normalizedEntropy:0,isHigh:!1};if(this.graph.rowTotal(t)<10)return e;let r=this.graph.entropyForState(t),i=this.graph.normalizedEntropyForState(t),n=i>=this.graph.highEntropyThreshold;return{entropy:r,normalizedEntropy:i,isHigh:n}}evaluateTrajectory(t,e,r){if(this.baseline===null||r.length<16)return null;let i=d.logLikelihoodTrajectory(this.graph,r,.01),n=d.logLikelihoodTrajectory(this.baseline,r,.01),o=Math.max(1,r.length-1),a=n/o,l=-Math.abs(this.graph.divergenceThreshold),h=typeof this.graph.baselineMeanLL=="number"&&typeof this.graph.baselineStdLL=="number"&&Number.isFinite(this.graph.baselineMeanLL)&&Number.isFinite(this.graph.baselineStdLL)&&this.graph.baselineStdLL>0,m=h?this.graph.baselineStdLL*Math.sqrt(32/o):0,p=h?(a-this.graph.baselineMeanLL)/m:a,g=h?p<=l:a<=l;return{zScore:p,isAnomalous:g,logLikelihood:i,baselineLogLikelihood:n,sampleSize:this.graph.rowTotal(t)}}serialize(){this.graph.prune();let t=T(this.graph.toBinary()),r={bloomBase64:this.bloom.toBase64(),graphBinary:t};return JSON.stringify(r)}restore(t){let e=JSON.parse(t);e.graphBinary&&(this.graph=d.fromBinary(S(e.graphBinary),this.graphConfig)),e.bloomBase64&&(this.bloom=y.fromBase64(e.bloomBase64,this.bloomConfig))}};var et=class{load(t){try{return typeof window>"u"||!window.localStorage?null:window.localStorage.getItem(t)}catch{return null}}save(t,e){try{if(typeof window>"u"||!window.localStorage)return;window.localStorage.setItem(t,e)}catch{}}};function zt(s={}){let t=new tt({graph:s.graph,bloom:s.bloom,baseline:s.baseline}),e=new et,r=new Y,i=new Q;return new O({stateModel:t,persistence:e,lifecycle:r,input:i,storageKey:s.storageKey,stateNormalizer:s.stateNormalizer,onError:s.onError})}export{at as ATTENTION_RETURN_THRESHOLD_MS,k as AnomalyDispatcher,I as BenchmarkRecorder,y as BloomFilter,_ as BroadcastSync,v as BrowserLifecycleAdapter,B as BrowserStorageAdapter,R as BrowserTimerAdapter,L as DriftProtectionPolicy,f as EventEmitter,gt as IDLE_CHECK_INTERVAL_MS,O as IntentEngine,J as IntentManager,x as MAX_PLAUSIBLE_DWELL_MS,St as MAX_STATE_LENGTH,d as MarkovGraph,st as MemoryStorageAdapter,ht as PropensityCalculator,P as SignalEngine,F as USER_IDLE_THRESHOLD_MS,dt as computeBloomConfig,zt as createBrowserIntent,C as normalizeRouteState};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|