@passiveintent/core 1.1.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 +105 -34
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +99 -99
package/README.md
CHANGED
|
@@ -466,40 +466,41 @@ new IntentManager({
|
|
|
466
466
|
|
|
467
467
|
All fields are optional. Pass them to `new IntentManager(config)` or `IntentManager.createAsync(config)`.
|
|
468
468
|
|
|
469
|
-
| Field | Type | Default | Description
|
|
470
|
-
| ------------------------------- | -------------------------------------------------------- | ----------------------------------------------------- |
|
|
471
|
-
| `storageKey` | `string` | `'passive-intent'` | `localStorage` key used to persist the Bloom filter and Markov graph.
|
|
472
|
-
| `storage` | `StorageAdapter` | `BrowserStorageAdapter` | Synchronous storage backend. Override for custom persistence or tests.
|
|
473
|
-
| `asyncStorage` | `AsyncStorageAdapter` | — | Async storage backend (React Native, IndexedDB, etc.). Use with `IntentManager.createAsync()`. Takes precedence over `storage` for writes.
|
|
474
|
-
| `timer` | `TimerAdapter` | `BrowserTimerAdapter` | Timer backend. Override for deterministic tests.
|
|
475
|
-
| `lifecycleAdapter` | `LifecycleAdapter` | `BrowserLifecycleAdapter` | Page-visibility adapter. Override for React Native, Electron, or SSR environments.
|
|
476
|
-
| `bloom` | `BloomFilterConfig` | — | Bloom filter sizing: `{ bitSize?: number, hashCount?: number }`. Defaults to 2048 bits / 4 hashes.
|
|
477
|
-
| `graph` | `MarkovGraphConfig` | — | Markov graph tuning (see sub-fields below).
|
|
478
|
-
| `graph.highEntropyThreshold` | `number` | `0.75` | Normalized entropy threshold `[0, 1]` above which `high_entropy` fires.
|
|
479
|
-
| `graph.divergenceThreshold` | `number` | `3.5` | Z-score magnitude for `trajectory_anomaly`. Decrease for more sensitivity.
|
|
480
|
-
| `graph.targetFPR` | `number` | — | Target false-positive rate (`0.001`–`0.5`) for trajectory anomaly detection. Converted to a Z-score via the inverse-normal CDF and **overrides** `graph.divergenceThreshold` when set. Follows the same precedence rules as `dwellTime.targetFPR`.
|
|
481
|
-
| `graph.baselineMeanLL` | `number` | — | Pre-computed mean of average per-step log-likelihood for normal sessions. Enables Z-score calibration. Also available as top-level `baselineMeanLL` (takes precedence).
|
|
482
|
-
| `graph.baselineStdLL` | `number` | — | Pre-computed std of average per-step log-likelihood. Pair with `baselineMeanLL`. Also available as top-level `baselineStdLL` (takes precedence).
|
|
483
|
-
| `graph.smoothingEpsilon` | `number` | `0.01` | Laplace smoothing probability for unseen transitions.
|
|
484
|
-
| `graph.smoothingAlpha` | `number` | `0.1` | Dirichlet pseudo-count for cold-start regularization. `0` = pure frequentist math. Also available as top-level `smoothingAlpha` (takes precedence).
|
|
485
|
-
| `graph.maxStates` | `number` | `500` | Maximum live states before LFU pruning triggers.
|
|
486
|
-
| `baselineMeanLL` | `number` | — | Top-level alias for `graph.baselineMeanLL`. Takes precedence when both are set.
|
|
487
|
-
| `baselineStdLL` | `number` | — | Top-level alias for `graph.baselineStdLL`. Takes precedence when both are set.
|
|
488
|
-
| `smoothingAlpha` | `number` | `0.1` | Top-level alias for `graph.smoothingAlpha`. Takes precedence when both are set.
|
|
489
|
-
| `baseline` | `SerializedMarkovGraph` | — | Pre-trained baseline graph (from `MarkovGraph.toJSON()`). Required for `trajectory_anomaly` detection.
|
|
490
|
-
| `botProtection` | `boolean` | `true` | Enable EntropyGuard heuristic bot detection. Set `false` in E2E/CI environments.
|
|
491
|
-
| `dwellTime` | `DwellTimeConfig` | — | Dwell-time anomaly settings: `{ enabled?: boolean, minSamples?: number, zScoreThreshold?: number, targetFPR?: number }`. `targetFPR` (float `0.001`–`0.5`) converts a false-positive rate to a Z-score and overrides `zScoreThreshold` when set.
|
|
492
|
-
| `enableBigrams` | `boolean` | `false` | Record second-order (bigram) Markov transitions for more discriminative modeling.
|
|
493
|
-
| `bigramFrequencyThreshold` | `number` | `5` | Minimum outgoing transitions a unigram state must have before bigram edges are recorded.
|
|
494
|
-
| `crossTabSync` | `boolean` | `false` | Broadcast verified transitions to other tabs via `BroadcastChannel`. No-op in SSR / unsupported environments.
|
|
495
|
-
| `
|
|
496
|
-
| `
|
|
497
|
-
| `
|
|
498
|
-
| `
|
|
499
|
-
| `
|
|
500
|
-
| `
|
|
501
|
-
| `
|
|
502
|
-
| `
|
|
469
|
+
| Field | Type | Default | Description |
|
|
470
|
+
| ------------------------------- | -------------------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
471
|
+
| `storageKey` | `string` | `'passive-intent'` | `localStorage` key used to persist the Bloom filter and Markov graph. |
|
|
472
|
+
| `storage` | `StorageAdapter` | `BrowserStorageAdapter` | Synchronous storage backend. Override for custom persistence or tests. |
|
|
473
|
+
| `asyncStorage` | `AsyncStorageAdapter` | — | Async storage backend (React Native, IndexedDB, etc.). Use with `IntentManager.createAsync()`. Takes precedence over `storage` for writes. |
|
|
474
|
+
| `timer` | `TimerAdapter` | `BrowserTimerAdapter` | Timer backend. Override for deterministic tests. |
|
|
475
|
+
| `lifecycleAdapter` | `LifecycleAdapter` | `BrowserLifecycleAdapter` | Page-visibility adapter. Override for React Native, Electron, or SSR environments. |
|
|
476
|
+
| `bloom` | `BloomFilterConfig` | — | Bloom filter sizing: `{ bitSize?: number, hashCount?: number }`. Defaults to 2048 bits / 4 hashes. |
|
|
477
|
+
| `graph` | `MarkovGraphConfig` | — | Markov graph tuning (see sub-fields below). |
|
|
478
|
+
| `graph.highEntropyThreshold` | `number` | `0.75` | Normalized entropy threshold `[0, 1]` above which `high_entropy` fires. |
|
|
479
|
+
| `graph.divergenceThreshold` | `number` | `3.5` | Z-score magnitude for `trajectory_anomaly`. Decrease for more sensitivity. |
|
|
480
|
+
| `graph.targetFPR` | `number` | — | Target false-positive rate (`0.001`–`0.5`) for trajectory anomaly detection. Converted to a Z-score via the inverse-normal CDF and **overrides** `graph.divergenceThreshold` when set. Follows the same precedence rules as `dwellTime.targetFPR`. |
|
|
481
|
+
| `graph.baselineMeanLL` | `number` | — | Pre-computed mean of average per-step log-likelihood for normal sessions. Enables Z-score calibration. Also available as top-level `baselineMeanLL` (takes precedence). |
|
|
482
|
+
| `graph.baselineStdLL` | `number` | — | Pre-computed std of average per-step log-likelihood. Pair with `baselineMeanLL`. Also available as top-level `baselineStdLL` (takes precedence). |
|
|
483
|
+
| `graph.smoothingEpsilon` | `number` | `0.01` | Laplace smoothing probability for unseen transitions. |
|
|
484
|
+
| `graph.smoothingAlpha` | `number` | `0.1` | Dirichlet pseudo-count for cold-start regularization. `0` = pure frequentist math. Also available as top-level `smoothingAlpha` (takes precedence). |
|
|
485
|
+
| `graph.maxStates` | `number` | `500` | Maximum live states before LFU pruning triggers. |
|
|
486
|
+
| `baselineMeanLL` | `number` | — | Top-level alias for `graph.baselineMeanLL`. Takes precedence when both are set. |
|
|
487
|
+
| `baselineStdLL` | `number` | — | Top-level alias for `graph.baselineStdLL`. Takes precedence when both are set. |
|
|
488
|
+
| `smoothingAlpha` | `number` | `0.1` | Top-level alias for `graph.smoothingAlpha`. Takes precedence when both are set. |
|
|
489
|
+
| `baseline` | `SerializedMarkovGraph` | — | Pre-trained baseline graph (from `MarkovGraph.toJSON()`). Required for `trajectory_anomaly` detection. |
|
|
490
|
+
| `botProtection` | `boolean` | `true` | Enable EntropyGuard heuristic bot detection. Set `false` in E2E/CI environments. |
|
|
491
|
+
| `dwellTime` | `DwellTimeConfig` | — | Dwell-time anomaly settings: `{ enabled?: boolean, minSamples?: number, zScoreThreshold?: number, targetFPR?: number }`. `targetFPR` (float `0.001`–`0.5`) converts a false-positive rate to a Z-score and overrides `zScoreThreshold` when set. |
|
|
492
|
+
| `enableBigrams` | `boolean` | `false` | Record second-order (bigram) Markov transitions for more discriminative modeling. |
|
|
493
|
+
| `bigramFrequencyThreshold` | `number` | `5` | Minimum outgoing transitions a unigram state must have before bigram edges are recorded. |
|
|
494
|
+
| `crossTabSync` | `boolean` | `false` | Broadcast verified transitions to other tabs via `BroadcastChannel`. No-op in SSR / unsupported environments. |
|
|
495
|
+
| `plugins` | `EnginePolicy[]` | `[]` | External policy plugins appended to the built-in pipeline. Built-in policies (Drift, Dwell, Bigram, CrossTab) always run first; plugins execute in array order after them. Each plugin hook is wrapped in a `try/catch` — a throwing plugin forwards to `onError` and never propagates to the caller. |
|
|
496
|
+
| `persistThrottleMs` | `number` | `0` | Max write frequency for the prune+serialize pipeline. `0` = sync write on every `track()` (full crash-safety). `200–500` recommended for typical graphs. |
|
|
497
|
+
| `persistDebounceMs` | `number` | `2000` | Delay for the async-error retry path and `flushNow()` timer cancellation only. Does not control write frequency for normal `track()` flow. |
|
|
498
|
+
| `eventCooldownMs` | `number` | `0` | Minimum ms between consecutive emissions of the same cooldown-gated event (`high_entropy`, `trajectory_anomaly`, `dwell_time_anomaly`). `0` disables throttling. |
|
|
499
|
+
| `hesitationCorrelationWindowMs` | `number` | `30000` | Max gap (ms) between a `trajectory_anomaly` and a `dwell_time_anomaly` for them to combine into a `hesitation_detected` event. |
|
|
500
|
+
| `driftProtection` | `{ maxAnomalyRate: number; evaluationWindowMs: number }` | `{ maxAnomalyRate: 0.4, evaluationWindowMs: 300000 }` | Killswitch: disables trajectory evaluation when anomaly rate exceeds `maxAnomalyRate` within the rolling window. Set `maxAnomalyRate: 1` to disable. |
|
|
501
|
+
| `holdoutConfig` | `{ percentage: number }` | — | Local A/B holdout: `percentage` (0–100) chance of routing a session to the `'control'` group, which suppresses anomaly events. Visible via `getTelemetry().assignmentGroup`. |
|
|
502
|
+
| `benchmark` | `BenchmarkConfig` | — | Enable op-latency instrumentation: `{ enabled?: boolean, maxSamples?: number }`. Read results via `getPerformanceReport()`. |
|
|
503
|
+
| `onError` | `(error: PassiveIntentError) => void` | — | Non-fatal error callback for storage errors, quota exhaustion, parse failures, and validation errors. The engine never throws to the host. |
|
|
503
504
|
|
|
504
505
|
### Adapters
|
|
505
506
|
|
|
@@ -752,6 +753,76 @@ All four interfaces, plus `EntropyResult`, `TrajectoryResult`, and
|
|
|
752
753
|
|
|
753
754
|
---
|
|
754
755
|
|
|
756
|
+
## The Mathematics of PassiveIntent
|
|
757
|
+
|
|
758
|
+
PassiveIntent does not use black-box neural networks, cloud embeddings, or third-party ML APIs. It is a deterministic, locally executed mathematical engine.
|
|
759
|
+
|
|
760
|
+
By combining physical kinematics with probabilistic state mapping, the engine calculates a real-time propensity-to-convert score in < 2ms with zero data egress.
|
|
761
|
+
|
|
762
|
+
Here are the foundational formulas powering the engine:
|
|
763
|
+
|
|
764
|
+
---
|
|
765
|
+
|
|
766
|
+
### 1. Kinematic Friction (Welford's Online Algorithm)
|
|
767
|
+
|
|
768
|
+
To detect user hesitation without storing heavy arrays of mouse/swipe coordinates, we use Welford’s online algorithm to calculate running variance in $O(1)$ time and $O(1)$ memory.
|
|
769
|
+
|
|
770
|
+
For each new input interaction $x_k$ (e.g., dwell time or swipe velocity), we update the running mean $\mu_k$ and the sum of squared differences $M_k$:
|
|
771
|
+
|
|
772
|
+
$$
|
|
773
|
+
\mu_k = \mu_{k-1} + \frac{x_k - \mu_{k-1}}{k}
|
|
774
|
+
$$
|
|
775
|
+
|
|
776
|
+
$$
|
|
777
|
+
M_k = M_{k-1} + (x_k - \mu_{k-1})(x_k - \mu_k)
|
|
778
|
+
$$
|
|
779
|
+
|
|
780
|
+
The sample variance is then cleanly derived as:
|
|
781
|
+
|
|
782
|
+
$$
|
|
783
|
+
\sigma^2_k = \frac{M_k}{k-1}
|
|
784
|
+
$$
|
|
785
|
+
|
|
786
|
+
---
|
|
787
|
+
|
|
788
|
+
### 2. Anomaly Detection (Z-Score Normalization)
|
|
789
|
+
|
|
790
|
+
Generic thresholds fail because user behavior on a media site differs completely from a B2B SaaS dashboard. PassiveIntent normalizes hesitation against the site's unique baseline using a standard Z-score:
|
|
791
|
+
|
|
792
|
+
$$
|
|
793
|
+
Z = \frac{x - \mu_{\text{baseline}}}{\sigma_{\text{baseline}}}
|
|
794
|
+
$$
|
|
795
|
+
|
|
796
|
+
A threshold such as $Z > 2.0$ indicates statistically unusual hesitation (under near-normal assumptions) and can trigger the configured dwell-time or trajectory anomaly handlers.
|
|
797
|
+
|
|
798
|
+
---
|
|
799
|
+
|
|
800
|
+
### 3. Journey Prediction (Laplace-Smoothed Markov Chains)
|
|
801
|
+
|
|
802
|
+
We map the user's path to purchase using a continuous 1st-order and 2nd-order (bigram) Markov graph. To prevent the "Cold Start" problem (where unvisited pages break the probability matrix), we apply Dirichlet prior / Laplace smoothing.
|
|
803
|
+
|
|
804
|
+
The probability $P$ of a user moving to state $j$ given their current state $i$ is:
|
|
805
|
+
|
|
806
|
+
$$
|
|
807
|
+
P(s_{t+1}=j \mid s_t=i) = \frac{c(i \to j) + \alpha}{\sum_k c(i \to k) + \alpha K}
|
|
808
|
+
$$
|
|
809
|
+
|
|
810
|
+
Where $c$ is the transition count, $\alpha$ is the smoothing parameter, and $K$ is the total number of known states.
|
|
811
|
+
|
|
812
|
+
---
|
|
813
|
+
|
|
814
|
+
### 4. Real-Time Propensity Scoring
|
|
815
|
+
|
|
816
|
+
To predict if a user will churn before they actually click away, we penalize their historical Markov probability of reaching the target state $H(S_c, S_t)$ using an exponential decay function tied directly to their real-time kinematic friction $Z$:
|
|
817
|
+
|
|
818
|
+
$$
|
|
819
|
+
P_{rt} = H(S_c, S_t) \cdot e^{-\lambda \cdot \max(0, Z)}
|
|
820
|
+
$$
|
|
821
|
+
|
|
822
|
+
If the user stays on the optimal path (low entropy), $P_{rt}$ remains high. The exact millisecond their physical input exhibits anomalous variance ($Z > 0$), the propensity score decays exponentially, allowing UI layers to trigger targeted discounts or support chats precisely at the moment of maximum indecision.
|
|
823
|
+
|
|
824
|
+
---
|
|
825
|
+
|
|
755
826
|
## Design decisions (brief)
|
|
756
827
|
|
|
757
828
|
- **Isomorphic adapters**: direct `window`/`localStorage` usage is avoided in core flow to keep SSR safe.
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var ht=Object.defineProperty;var Lt=Object.getOwnPropertyDescriptor;var _t=Object.getOwnPropertyNames;var Dt=Object.prototype.hasOwnProperty;var Nt=(s,t)=>{for(var e in t)ht(s,e,{get:t[e],enumerable:!0})},Bt=(s,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of _t(t))!Dt.call(s,i)&&i!==e&&ht(s,i,{get:()=>t[i],enumerable:!(r=Lt(t,i))||r.enumerable});return s};var Rt=s=>Bt(ht({},"__esModule",{value:!0}),s);var Jt={};Nt(Jt,{ATTENTION_RETURN_THRESHOLD_MS:()=>W,AnomalyDispatcher:()=>w,BenchmarkRecorder:()=>v,BloomFilter:()=>y,BroadcastSync:()=>I,BrowserLifecycleAdapter:()=>b,BrowserStorageAdapter:()=>D,BrowserTimerAdapter:()=>N,DriftProtectionPolicy:()=>A,EventEmitter:()=>f,IDLE_CHECK_INTERVAL_MS:()=>mt,IntentEngine:()=>B,IntentManager:()=>H,MAX_PLAUSIBLE_DWELL_MS:()=>S,MAX_STATE_LENGTH:()=>pt,MarkovGraph:()=>d,MemoryStorageAdapter:()=>z,PropensityCalculator:()=>tt,SignalEngine:()=>M,USER_IDLE_THRESHOLD_MS:()=>j,computeBloomConfig:()=>ct,createBrowserIntent:()=>Mt,normalizeRouteState:()=>T});module.exports=Rt(Jt);function x(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 k(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 gt(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 U=(()=>{let s=globalThis.__PFIE_WM__;return(typeof s=="number"?s:2343432205)>>>0})(),P=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=P[0],r=P[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=P[0],r=P[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 x(this.bits)}static fromBase64(t,e={}){return new s(e,k(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){P[0]=(gt(t,2166136261)^U^U)>>>0,P[1]=(gt(t,16777619)^U^U)>>>0}};function ct(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 R=n.getUint32(o,!0);o+=4;let ot=n.getUint16(o,!0);o+=2;let C=new Map;for(let G=0;G<ot;G+=1){let F=n.getUint16(o,!0);o+=2;let O=n.getUint32(o,!0);o+=4,C.set(F,O)}r.rows.set(u,{total:R,toCounts:C})}return r}};function L(){return{count:0,totalMs:0,maxMs:0,samples:[]}}function Ot(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 yt(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 _(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:yt(t,.95),p99Ms:yt(t,.99),maxMs:s.maxMs}}var ft=typeof TextEncoder<"u"?new TextEncoder:null,v=class{constructor(t={}){this.enabled=t.enabled??!1,this.maxSamples=t.maxSamples??4096,this.stats={track:L(),bloomAdd:L(),bloomCheck:L(),incrementTransition:L(),entropyComputation:L(),divergenceComputation:L()}}now(){return this.enabled?performance.now():0}record(t,e){this.enabled&&Ot(this.stats[t],performance.now()-e,this.maxSamples)}report(t){return{benchmarkEnabled:this.enabled,track:_(this.stats.track),bloomAdd:_(this.stats.bloomAdd),bloomCheck:_(this.stats.bloomCheck),incrementTransition:_(this.stats.incrementTransition),entropyComputation:_(this.stats.entropyComputation),divergenceComputation:_(this.stats.divergenceComputation),memoryFootprint:t}}serializedSizeBytes(t){let e=JSON.stringify(t);return ft?ft.encode(e).byteLength:e.length}};var D=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)}},N=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()}},z=class{constructor(){this.store=new Map}getItem(t){return this.store.get(t)??null}setItem(t,e){this.store.set(t,e)}},E=class E{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<E.INTERACTION_THROTTLE_MS)){this.interactionLastFired=r;for(let i of this.interactionCallbacks)i()}};let e={passive:!0};for(let r of E.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 E.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}};E.INTERACTION_THROTTLE_MS=1e3,E.INTERACTION_EVENTS=["mousemove","scroll","touchstart","keydown"];var b=E;var jt=/[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/gi,Ht=/\b[0-9a-f]{24}\b/gi,Gt=/\/\d{4,}(?=\/|$)/g;function T(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(jt,":id").replace(Ht,":id").replace(Gt,"/:id"),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}var S=18e5,W=15e3,j=12e4,mt=5e3;function bt(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 vt(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)?bt(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,R=s.eventCooldownMs,ot=Number.isFinite(R)&&R>=0?Math.floor(R):0,C=s.dwellTime?.minSamples,G=Number.isFinite(C)&&C>=1?Math.floor(C):10,F=s.dwellTime?.targetFPR,O=s.dwellTime?.zScoreThreshold,At=Number.isFinite(F)?bt(F):Number.isFinite(O)&&O>0?O:2.5,It=s.enableBigrams??!1,st=s.bigramFrequencyThreshold,Ct=Number.isFinite(st)&&st>=1?Math.floor(st):5,ut=s.driftProtection?.maxAnomalyRate,xt=Number.isFinite(ut)?Math.min(1,Math.max(0,ut)):.4,at=s.driftProtection?.evaluationWindowMs,kt=Number.isFinite(at)&&at>0?Math.floor(at):3e5,lt=s.hesitationCorrelationWindowMs,Pt=Number.isFinite(lt)&<>=0?Math.floor(lt):3e4;return{botProtection:t,dwellTimeEnabled:e,crossTabSync:r,holdoutPercent:n,graphConfig:a,trajectorySmoothingEpsilon:h,storageKey:m,persistDebounceMs:g,persistThrottleMs:u,eventCooldownMs:ot,dwellTimeMinSamples:G,dwellTimeZScoreThreshold:At,enableBigrams:It,bigramFrequencyThreshold:Ct,driftMaxAnomalyRate:xt,driftEvaluationWindowMs:kt,hesitationCorrelationWindowMs:Pt}}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 K=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 Et(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 Tt(s){return s.count<2?0:Math.sqrt(s.m2/s.count)}function Ft(s){throw new Error(`Unhandled AnomalyDecision kind: ${s.kind}`)}var w=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:Ft(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 St(s){return s<10?"low":s<30?"medium":"high"}var M=class{constructor(t){this.entropyGuard=new K;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 w({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:St(u)}}}return null}evaluateDwellTime(t,e){if(e<=0)return null;let r=Et(this.dwellStats.get(t),e);if(this.dwellStats.set(t,r),r.count<this.dwellTimeMinSamples)return null;let i=Tt(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:St(o)},isPositiveZScore:n>0}}return null}};var $=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=x(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}},V=class extends ${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)}}},X=class extends ${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 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 X(this):this.strategy=new V(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=k(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 q=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 b: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 J=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 Y=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 A=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 pt=256;function Wt(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 Kt(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 I=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(!Wt(e))return;this.applyRemote(e.from,e.to)}else if(e.type==="counter"){if(!Kt(e))return;this.applyRemoteCounter(e.key,e.by)}}};var Q=class{constructor(t){this.broadcastSync=new I(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 H=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.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=vt(t);this.benchmark=new v(t.benchmark),this.timer=t.timer??new N,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 D,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 A(e.driftMaxAnomalyRate,e.driftEvaluationWindowMs),o=[n];this.signalEngine=new M({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 J({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 Y(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.policies=o,this.lifecycleCoordinator=new q({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),i={getItem:()=>r,setItem:()=>{}},{storage:n,...o}=t;return new s({...o,storage:i})}track(t){if(t=T(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.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.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.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 tt=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 $t=20,B=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=T(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>$t&&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 et=class extends b{};var Vt=[25,50,75,100],Xt=.3,Zt=200,qt=150,rt=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()},qt)}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 Vt)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<Zt)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>=Xt?"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 nt=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=x(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(k(e.graphBinary),this.graphConfig)),e.bloomBase64&&(this.bloom=y.fromBase64(e.bloomBase64,this.bloomConfig))}};var it=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 Mt(s={}){let t=new nt({graph:s.graph,bloom:s.bloom,baseline:s.baseline}),e=new it,r=new et,i=new rt;return new B({stateModel:t,persistence:e,lifecycle:r,input:i,storageKey:s.storageKey,stateNormalizer:s.stateNormalizer,onError:s.onError})}0&&(module.exports={ATTENTION_RETURN_THRESHOLD_MS,AnomalyDispatcher,BenchmarkRecorder,BloomFilter,BroadcastSync,BrowserLifecycleAdapter,BrowserStorageAdapter,BrowserTimerAdapter,DriftProtectionPolicy,EventEmitter,IDLE_CHECK_INTERVAL_MS,IntentEngine,IntentManager,MAX_PLAUSIBLE_DWELL_MS,MAX_STATE_LENGTH,MarkovGraph,MemoryStorageAdapter,PropensityCalculator,SignalEngine,USER_IDLE_THRESHOLD_MS,computeBloomConfig,createBrowserIntent,normalizeRouteState});
|
|
1
|
+
"use strict";var ht=Object.defineProperty;var Lt=Object.getOwnPropertyDescriptor;var _t=Object.getOwnPropertyNames;var Dt=Object.prototype.hasOwnProperty;var Nt=(s,t)=>{for(var e in t)ht(s,e,{get:t[e],enumerable:!0})},Bt=(s,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of _t(t))!Dt.call(s,i)&&i!==e&&ht(s,i,{get:()=>t[i],enumerable:!(r=Lt(t,i))||r.enumerable});return s};var Rt=s=>Bt(ht({},"__esModule",{value:!0}),s);var Jt={};Nt(Jt,{ATTENTION_RETURN_THRESHOLD_MS:()=>W,AnomalyDispatcher:()=>w,BenchmarkRecorder:()=>v,BloomFilter:()=>y,BroadcastSync:()=>I,BrowserLifecycleAdapter:()=>b,BrowserStorageAdapter:()=>D,BrowserTimerAdapter:()=>N,DriftProtectionPolicy:()=>A,EventEmitter:()=>f,IDLE_CHECK_INTERVAL_MS:()=>mt,IntentEngine:()=>B,IntentManager:()=>H,MAX_PLAUSIBLE_DWELL_MS:()=>S,MAX_STATE_LENGTH:()=>pt,MarkovGraph:()=>d,MemoryStorageAdapter:()=>z,PropensityCalculator:()=>tt,SignalEngine:()=>M,USER_IDLE_THRESHOLD_MS:()=>j,computeBloomConfig:()=>ct,createBrowserIntent:()=>Mt,normalizeRouteState:()=>T});module.exports=Rt(Jt);function x(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 k(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 gt(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 U=(()=>{let s=globalThis.__PFIE_WM__;return(typeof s=="number"?s:2343432205)>>>0})(),P=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=P[0],r=P[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=P[0],r=P[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 x(this.bits)}static fromBase64(t,e={}){return new s(e,k(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){P[0]=(gt(t,2166136261)^U^U)>>>0,P[1]=(gt(t,16777619)^U^U)>>>0}};function ct(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 R=n.getUint32(o,!0);o+=4;let ot=n.getUint16(o,!0);o+=2;let C=new Map;for(let G=0;G<ot;G+=1){let F=n.getUint16(o,!0);o+=2;let O=n.getUint32(o,!0);o+=4,C.set(F,O)}r.rows.set(u,{total:R,toCounts:C})}return r}};function L(){return{count:0,totalMs:0,maxMs:0,samples:[]}}function Ot(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 yt(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 _(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:yt(t,.95),p99Ms:yt(t,.99),maxMs:s.maxMs}}var ft=typeof TextEncoder<"u"?new TextEncoder:null,v=class{constructor(t={}){this.enabled=t.enabled??!1,this.maxSamples=t.maxSamples??4096,this.stats={track:L(),bloomAdd:L(),bloomCheck:L(),incrementTransition:L(),entropyComputation:L(),divergenceComputation:L()}}now(){return this.enabled?performance.now():0}record(t,e){this.enabled&&Ot(this.stats[t],performance.now()-e,this.maxSamples)}report(t){return{benchmarkEnabled:this.enabled,track:_(this.stats.track),bloomAdd:_(this.stats.bloomAdd),bloomCheck:_(this.stats.bloomCheck),incrementTransition:_(this.stats.incrementTransition),entropyComputation:_(this.stats.entropyComputation),divergenceComputation:_(this.stats.divergenceComputation),memoryFootprint:t}}serializedSizeBytes(t){let e=JSON.stringify(t);return ft?ft.encode(e).byteLength:e.length}};var D=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)}},N=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()}},z=class{constructor(){this.store=new Map}getItem(t){return this.store.get(t)??null}setItem(t,e){this.store.set(t,e)}},E=class E{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<E.INTERACTION_THROTTLE_MS)){this.interactionLastFired=r;for(let i of this.interactionCallbacks)i()}};let e={passive:!0};for(let r of E.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 E.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}};E.INTERACTION_THROTTLE_MS=1e3,E.INTERACTION_EVENTS=["mousemove","scroll","touchstart","keydown"];var b=E;var jt=/[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/gi,Ht=/\b[0-9a-f]{24}\b/gi,Gt=/\/\d{4,}(?=\/|$)/g;function T(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(jt,":id").replace(Ht,":id").replace(Gt,"/:id"),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}var S=18e5,W=15e3,j=12e4,mt=5e3;function bt(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 vt(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)?bt(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,R=s.eventCooldownMs,ot=Number.isFinite(R)&&R>=0?Math.floor(R):0,C=s.dwellTime?.minSamples,G=Number.isFinite(C)&&C>=1?Math.floor(C):10,F=s.dwellTime?.targetFPR,O=s.dwellTime?.zScoreThreshold,At=Number.isFinite(F)?bt(F):Number.isFinite(O)&&O>0?O:2.5,It=s.enableBigrams??!1,st=s.bigramFrequencyThreshold,Ct=Number.isFinite(st)&&st>=1?Math.floor(st):5,ut=s.driftProtection?.maxAnomalyRate,xt=Number.isFinite(ut)?Math.min(1,Math.max(0,ut)):.4,at=s.driftProtection?.evaluationWindowMs,kt=Number.isFinite(at)&&at>0?Math.floor(at):3e5,lt=s.hesitationCorrelationWindowMs,Pt=Number.isFinite(lt)&<>=0?Math.floor(lt):3e4;return{botProtection:t,dwellTimeEnabled:e,crossTabSync:r,holdoutPercent:n,graphConfig:a,trajectorySmoothingEpsilon:h,storageKey:m,persistDebounceMs:g,persistThrottleMs:u,eventCooldownMs:ot,dwellTimeMinSamples:G,dwellTimeZScoreThreshold:At,enableBigrams:It,bigramFrequencyThreshold:Ct,driftMaxAnomalyRate:xt,driftEvaluationWindowMs:kt,hesitationCorrelationWindowMs:Pt,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 K=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 Et(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 Tt(s){return s.count<2?0:Math.sqrt(s.m2/s.count)}function Ft(s){throw new Error(`Unhandled AnomalyDecision kind: ${s.kind}`)}var w=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:Ft(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 St(s){return s<10?"low":s<30?"medium":"high"}var M=class{constructor(t){this.entropyGuard=new K;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 w({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:St(u)}}}return null}evaluateDwellTime(t,e){if(e<=0)return null;let r=Et(this.dwellStats.get(t),e);if(this.dwellStats.set(t,r),r.count<this.dwellTimeMinSamples)return null;let i=Tt(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:St(o)},isPositiveZScore:n>0}}return null}};var $=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=x(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}},V=class extends ${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)}}},X=class extends ${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 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 X(this):this.strategy=new V(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=k(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 q=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 b: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 J=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 Y=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 A=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 pt=256;function Wt(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 Kt(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 I=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(!Wt(e))return;this.applyRemote(e.from,e.to)}else if(e.type==="counter"){if(!Kt(e))return;this.applyRemoteCounter(e.key,e.by)}}};var Q=class{constructor(t){this.broadcastSync=new I(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 H=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=vt(t);this.benchmark=new v(t.benchmark),this.timer=t.timer??new N,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 D,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 A(e.driftMaxAnomalyRate,e.driftEvaluationWindowMs),o=[n];this.signalEngine=new M({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 J({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 Y(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 q({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=T(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 tt=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 $t=20,B=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=T(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>$t&&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 et=class extends b{};var Vt=[25,50,75,100],Xt=.3,Zt=200,qt=150,rt=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()},qt)}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 Vt)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<Zt)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>=Xt?"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 nt=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=x(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(k(e.graphBinary),this.graphConfig)),e.bloomBase64&&(this.bloom=y.fromBase64(e.bloomBase64,this.bloomConfig))}};var it=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 Mt(s={}){let t=new nt({graph:s.graph,bloom:s.bloom,baseline:s.baseline}),e=new it,r=new et,i=new rt;return new B({stateModel:t,persistence:e,lifecycle:r,input:i,storageKey:s.storageKey,stateNormalizer:s.stateNormalizer,onError:s.onError})}0&&(module.exports={ATTENTION_RETURN_THRESHOLD_MS,AnomalyDispatcher,BenchmarkRecorder,BloomFilter,BroadcastSync,BrowserLifecycleAdapter,BrowserStorageAdapter,BrowserTimerAdapter,DriftProtectionPolicy,EventEmitter,IDLE_CHECK_INTERVAL_MS,IntentEngine,IntentManager,MAX_PLAUSIBLE_DWELL_MS,MAX_STATE_LENGTH,MarkovGraph,MemoryStorageAdapter,PropensityCalculator,SignalEngine,USER_IDLE_THRESHOLD_MS,computeBloomConfig,createBrowserIntent,normalizeRouteState});
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|