@newgenesis/vision
Version:
Professional bot and AI detection library with behavioral analysis, fingerprinting, and adaptive challenges
1,389 lines (1,362 loc) • 35.2 kB
TypeScript
/**
* Core type definitions for Vision library
* @package @newgenesis/vision
* @author NewGenesis <https://newgenesis.ai>
*/
/**
* Detection mode for Vision
* - 'detector': Passive detection without UI
* - 'checkbox': Display checkbox UI with detection
*/
type VisionMode = 'detector' | 'checkbox';
/**
* Action to take based on risk score
* - 'accept': User appears human, allow access
* - 'challenge': Show additional verification
* - 'block': High risk, deny access
*/
type VisionAction = 'accept' | 'challenge' | 'block';
/**
* Challenge type for suspicious activity
*/
type ChallengeType = 'invisible' | 'checkbox' | 'captcha' | 'pow' | 'webauthn';
/**
* Risk level classification
*/
type RiskLevel = 'low' | 'medium' | 'high' | 'critical';
/**
* Main configuration options for Vision
*/
interface VisionConfig {
/** Element ID where Vision will be mounted (for browser) */
elementId?: string;
/** Detection mode */
mode: VisionMode;
/** Callback when detection result is ready */
onResult?: (result: VisionResult) => void;
/** Custom thresholds for risk scoring */
thresholds?: RiskThresholds;
/** Enable/disable specific detection modules */
modules?: ModuleConfig;
/** API endpoint for server-side verification (optional) */
apiEndpoint?: string;
/** Debug mode for development */
debug?: boolean;
/** Custom challenge configuration */
challenges?: ChallengeConfig;
}
/**
* Risk score thresholds
*/
interface RiskThresholds {
/** Score below this = accept (0-1) */
accept: number;
/** Score between accept and block = challenge (0-1) */
challenge: number;
/** Score above this = block (0-1) */
block: number;
}
/**
* Module enable/disable configuration
*/
interface ModuleConfig {
behavioral?: boolean;
fingerprint?: boolean;
textAnalysis?: boolean;
network?: boolean;
}
/**
* Challenge system configuration
*/
interface ChallengeConfig {
/** Default challenge type */
defaultType: ChallengeType;
/** Enable progressive challenge escalation */
progressive?: boolean;
/** External CAPTCHA keys (hCaptcha, reCAPTCHA, etc.) */
captchaKeys?: {
siteKey: string;
provider: 'hcaptcha' | 'recaptcha' | 'turnstile';
};
/** Proof of Work difficulty (1-10) */
powDifficulty?: number;
}
/**
* Final detection result
*/
interface VisionResult {
/** Overall risk score (0-1, higher = more suspicious) */
score: number;
/** Recommended action */
action: VisionAction;
/** Risk level classification */
riskLevel: RiskLevel;
/** Individual module scores */
signals: SignalScores;
/** Detailed breakdown (only in debug mode) */
details?: DetectionDetails;
/** Session ID for tracking */
sessionId: string;
/** Timestamp of detection */
timestamp: number;
/** Whether user passed challenge (if applicable) */
challengePassed?: boolean;
/** Challenge details (if challenge was presented) */
challenge?: {
type: string;
passed: boolean;
metrics: any;
};
/** Optional message for user feedback */
message?: string;
}
/**
* Individual signal scores from each detection module
*/
interface SignalScores {
behavioral: number;
fingerprint: number;
textAnalysis?: number;
network: number;
/** Weighted combined score */
combined: number;
}
/**
* Detailed detection information (debug mode)
*/
interface DetectionDetails {
behavioral?: BehavioralDetails;
fingerprint?: FingerprintDetails;
textAnalysis?: TextAnalysisDetails;
network?: NetworkDetails;
keystroke?: {
humanScore?: number;
botProbability?: number;
aiProbability?: number;
averageInterval?: number;
skippedChallenge?: boolean;
};
email?: {
humanScore?: number;
valid?: boolean;
suspicious?: boolean;
};
advanced?: {
humanScore: number;
reasons: string[];
timeSpent: number;
};
/** Flags that triggered suspicion */
flags: string[];
/** Confidence level (0-1) */
confidence: number;
}
/**
* Behavioral analysis details
*/
interface BehavioralDetails {
mouseEvents: {
count: number;
variance: number;
velocity: number[];
humanLike: boolean;
};
keyboardEvents: {
count: number;
interKeyTiming: number[];
pasteDetected: boolean;
humanLike: boolean;
};
scrollEvents: {
count: number;
pattern: number[];
naturalScroll: boolean;
};
focusEvents: {
count: number;
blur: number;
pattern: string;
};
/** Overall behavioral score */
score: number;
}
/**
* Browser fingerprint details
*/
interface FingerprintDetails {
canvas: {
hash: string;
consistent: boolean;
};
webgl: {
vendor: string;
renderer: string;
hash: string;
};
navigator: {
userAgent: string;
platform: string;
languages: string[];
plugins: number;
mimeTypes: number;
webdriver: boolean;
};
screen: {
width: number;
height: number;
colorDepth: number;
pixelRatio: number;
};
hardware: {
deviceMemory?: number;
hardwareConcurrency: number;
maxTouchPoints: number;
};
headlessDetection: {
isHeadless: boolean;
indicators: string[];
};
/** Overall fingerprint score */
score: number;
}
/**
* Text analysis details (for AI detection)
*/
interface TextAnalysisDetails {
text: string;
nlp: {
lexicalRichness: number;
punctuationRate: number;
averageWordLength: number;
sentenceComplexity: number;
};
aiDetection: {
perplexity?: number;
transformerScore?: number;
embeddingDistance?: number;
isAiGenerated: boolean;
confidence: number;
};
stylometry: {
features: Record<string, number>;
similarity: number;
};
/** Overall text analysis score */
score: number;
}
/**
* Network analysis details
*/
interface NetworkDetails {
ip?: string;
timing: {
latency: number;
jitter: number;
pattern: string;
};
connection: {
type: string;
effectiveType: string;
downlink?: number;
rtt?: number;
};
proxy: {
detected: boolean;
indicators: string[];
};
tor: {
detected: boolean;
};
/** Overall network score */
score: number;
}
/**
* Event tracking data
*/
interface EventData {
type: string;
timestamp: number;
data: Record<string, any>;
}
/**
* Mouse event data
*/
interface MouseEventData extends EventData {
type: 'mousemove' | 'mousedown' | 'mouseup' | 'click';
data: {
x: number;
y: number;
buttons?: number;
movementX?: number;
movementY?: number;
};
}
/**
* Keyboard event data
*/
interface KeyboardEventData extends EventData {
type: 'keydown' | 'keyup' | 'keypress';
data: {
key: string;
code: string;
keyCode: number;
timeSinceLastKey?: number;
};
}
/**
* Scroll event data
*/
interface ScrollEventData extends EventData {
type: 'scroll';
data: {
x: number;
y: number;
deltaX?: number;
deltaY?: number;
};
}
/**
* Module interface that all detection modules must implement
*/
interface DetectionModule {
/** Module name */
name: string;
/** Initialize the module */
init(): Promise<void>;
/** Start collecting data */
start(): void;
/** Stop collecting data */
stop(): void;
/** Analyze collected data and return score */
analyze(): Promise<number>;
/** Get detailed results */
getDetails(): Promise<any>;
/** Reset module state */
reset(): void;
}
/**
* VisionCore - Main orchestration engine
* Coordinates all detection modules and manages the detection lifecycle
*
* @package @newgenesis/vision
* @author NewGenesis <https://newgenesis.ai>
*/
/**
* Core Vision class - orchestrates all detection modules
*/
declare class VisionCore {
private config;
private modules;
private sessionManager;
private scoringEngine;
private isInitialized;
private isRunning;
private securityMode;
private progressiveScorer;
private sessionId;
/**
* Constructor
*/
constructor(config: VisionConfig);
/**
* Initialize Vision and all modules
*/
init(): Promise<void>;
/**
* Initialize detection modules based on configuration
*/
private initializeModules;
/**
* Start detection - begin collecting signals
*/
start(): Promise<void>;
/**
* Stop detection
*/
stop(): void;
/**
* Analyze all signals and generate result
*/
analyze(): Promise<VisionResult>;
/**
* Collect scores from all active modules
*/
private collectModuleScores;
/**
* Determine action based on score and thresholds
*/
private determineAction;
private getDecisionTuning;
/**
* Determine risk level based on score
*/
private determineRiskLevel;
/**
* Collect detailed information from all modules (debug mode)
*/
private collectDetailedInfo;
/**
* Reset all modules and state
*/
reset(): void;
/**
* Get current session ID
*/
getSessionId(): string;
/**
* Get configuration
*/
getConfig(): Required<VisionConfig>;
/**
* Check if Vision is initialized
*/
isReady(): boolean;
/**
* Check if detection is running
*/
isActive(): boolean;
/**
* Register a custom detection module
*/
registerModule(module: DetectionModule): void;
/**
* Unregister a detection module
*/
unregisterModule(moduleName: string): boolean;
/**
* Destroy Vision and cleanup resources
*/
destroy(): void;
}
/**
* SessionManager - Manages user session data and detection history
*
* @package @newgenesis/vision
* @author NewGenesis <https://newgenesis.ai>
*/
/**
* Session data structure
*/
interface SessionData {
sessionId: string;
startTime: number;
lastActivity: number;
results: VisionResult[];
metadata: Record<string, any>;
}
/**
* SessionManager class
*/
declare class SessionManager {
private sessionId;
private sessionData;
private storageKey;
/**
* Constructor
*/
constructor(sessionId: string);
/**
* Initialize session manager
*/
init(): Promise<void>;
/**
* Load session data from local storage
*/
private loadFromStorage;
/**
* Save session data to local storage
*/
private saveToStorage;
/**
* Update last activity timestamp
*/
updateActivity(): void;
/**
* Add detection result to session history
*/
updateResult(result: VisionResult): void;
/**
* Get all results in session
*/
getResults(): VisionResult[];
/**
* Get latest result
*/
getLatestResult(): VisionResult | null;
/**
* Get session metadata
*/
getMetadata(): Record<string, any>;
/**
* Set session metadata
*/
setMetadata(key: string, value: any): void;
/**
* Get session statistics
*/
getStats(): {
totalDetections: number;
averageScore: number;
highestScore: number;
lowestScore: number;
actions: Record<string, number>;
riskLevels: Record<string, number>;
};
/**
* Check if session is expired
*/
isExpired(): boolean;
/**
* Get session duration
*/
getDuration(): number;
/**
* Reset session data
*/
reset(): void;
/**
* Destroy session and cleanup
*/
destroy(): void;
/**
* Get session ID
*/
getSessionId(): string;
/**
* Get full session data
*/
getData(): SessionData;
}
/**
* Vision Standalone - Vanilla JavaScript API
* For use without React/Next.js
*
* @package @newgenesis/vision
* @author NewGenesis <https://newgenesis.ai>
*/
/**
* Standalone Vision API for vanilla JavaScript
*/
declare class VisionStandalone {
private core;
private checkboxElement;
private config;
constructor(config: VisionConfig);
/**
* Initialize Vision
*/
init(): Promise<void>;
/**
* Trigger verification
*/
verify(): Promise<VisionResult | null>;
/**
* Handle result from core
*/
private handleResult;
/**
* Get core instance
*/
getCore(): VisionCore | null;
/**
* Destroy and cleanup
*/
destroy(): void;
}
/**
* Global Vision object for browser usage
*/
declare global {
interface Window {
Vision: {
init: (config: VisionConfig) => Promise<VisionStandalone>;
version: string;
VisionCore: typeof VisionCore;
};
}
}
/**
* Constants and default configurations for Vision
* @package @newgenesis/vision
* @author NewGenesis <https://newgenesis.ai>
*/
/**
* Default risk thresholds
*/
declare const DEFAULT_THRESHOLDS: RiskThresholds;
/**
* Default module configuration (all enabled)
*/
declare const DEFAULT_MODULES: ModuleConfig;
/**
* Default challenge configuration
*/
declare const DEFAULT_CHALLENGES: ChallengeConfig;
/**
* Module weights for combined scoring
* Must sum to 1.0
*/
declare const MODULE_WEIGHTS: {
behavioral: number;
fingerprint: number;
textAnalysis: number;
network: number;
};
/**
* Behavioral analysis thresholds
*/
declare const BEHAVIORAL_THRESHOLDS: {
MIN_MOUSE_EVENTS: number;
MIN_KEYBOARD_EVENTS: number;
MIN_SCROLL_EVENTS: number;
MIN_MOUSE_VARIANCE: number;
MAX_MOUSE_VARIANCE: number;
MIN_KEY_TIMING: number;
MAX_KEY_TIMING: number;
KEY_TIMING_VARIANCE_THRESHOLD: number;
MIN_MOUSE_VELOCITY: number;
MAX_MOUSE_VELOCITY: number;
MIN_FOCUS_EVENTS: number;
};
/**
* Fingerprint detection indicators
*/
declare const FINGERPRINT_FLAGS: {
WEBDRIVER_PRESENT: string;
CHROME_HEADLESS: string;
PHANTOM_JS: string;
SELENIUM: string;
CANVAS_NOISE_MISSING: string;
CANVAS_BLOCKED: string;
WEBGL_UNMASKED: string;
WEBGL_INCONSISTENT: string;
PLUGINS_EMPTY: string;
LANGUAGES_INCONSISTENT: string;
PLATFORM_MISMATCH: string;
};
/**
* Text analysis thresholds (AI detection)
*/
declare const TEXT_ANALYSIS_THRESHOLDS: {
MIN_TEXT_LENGTH: number;
MIN_LEXICAL_RICHNESS: number;
MAX_LEXICAL_RICHNESS: number;
AI_PERPLEXITY_THRESHOLD: number;
AI_CONFIDENCE_THRESHOLD: number;
MIN_PUNCTUATION_RATE: number;
MAX_PUNCTUATION_RATE: number;
};
/**
* Network analysis thresholds
*/
declare const NETWORK_THRESHOLDS: {
MAX_REQUEST_JITTER: number;
MIN_LATENCY: number;
SUSPICIOUS_RTT: number;
SUSPICIOUS_DOWNLINK: number;
};
/**
* Session configuration
*/
declare const SESSION_CONFIG: {
DURATION: number;
STORAGE_KEY: string;
};
/**
* Performance budgets (ms)
*/
declare const PERFORMANCE_BUDGETS: {
INIT: number;
ANALYSIS: number;
FINGERPRINT: number;
BEHAVIORAL: number;
TEXT_ANALYSIS: number;
};
/**
* API endpoints (for server-side verification)
*/
declare const API_ENDPOINTS: {
VERIFY: string;
CHALLENGE: string;
REPORT: string;
};
/**
* Library metadata
*/
declare const VISION_METADATA: {
NAME: string;
VERSION: string;
AUTHOR: string;
HOMEPAGE: string;
};
/**
* Debug mode settings
*/
declare const DEBUG_CONFIG: {
LOG_PREFIX: string;
VERBOSE: boolean;
PERFORMANCE_TRACKING: boolean;
};
declare const constants_API_ENDPOINTS: typeof API_ENDPOINTS;
declare const constants_BEHAVIORAL_THRESHOLDS: typeof BEHAVIORAL_THRESHOLDS;
declare const constants_DEBUG_CONFIG: typeof DEBUG_CONFIG;
declare const constants_DEFAULT_CHALLENGES: typeof DEFAULT_CHALLENGES;
declare const constants_DEFAULT_MODULES: typeof DEFAULT_MODULES;
declare const constants_DEFAULT_THRESHOLDS: typeof DEFAULT_THRESHOLDS;
declare const constants_FINGERPRINT_FLAGS: typeof FINGERPRINT_FLAGS;
declare const constants_MODULE_WEIGHTS: typeof MODULE_WEIGHTS;
declare const constants_NETWORK_THRESHOLDS: typeof NETWORK_THRESHOLDS;
declare const constants_PERFORMANCE_BUDGETS: typeof PERFORMANCE_BUDGETS;
declare const constants_SESSION_CONFIG: typeof SESSION_CONFIG;
declare const constants_TEXT_ANALYSIS_THRESHOLDS: typeof TEXT_ANALYSIS_THRESHOLDS;
declare const constants_VISION_METADATA: typeof VISION_METADATA;
declare namespace constants {
export { constants_API_ENDPOINTS as API_ENDPOINTS, constants_BEHAVIORAL_THRESHOLDS as BEHAVIORAL_THRESHOLDS, constants_DEBUG_CONFIG as DEBUG_CONFIG, constants_DEFAULT_CHALLENGES as DEFAULT_CHALLENGES, constants_DEFAULT_MODULES as DEFAULT_MODULES, constants_DEFAULT_THRESHOLDS as DEFAULT_THRESHOLDS, constants_FINGERPRINT_FLAGS as FINGERPRINT_FLAGS, constants_MODULE_WEIGHTS as MODULE_WEIGHTS, constants_NETWORK_THRESHOLDS as NETWORK_THRESHOLDS, constants_PERFORMANCE_BUDGETS as PERFORMANCE_BUDGETS, constants_SESSION_CONFIG as SESSION_CONFIG, constants_TEXT_ANALYSIS_THRESHOLDS as TEXT_ANALYSIS_THRESHOLDS, constants_VISION_METADATA as VISION_METADATA };
}
/**
* ScoringEngine - Multi-signal scoring and risk calculation
* Combines signals from all detection modules using weighted averages
*
* @package @newgenesis/vision
* @author NewGenesis <https://newgenesis.ai>
*/
/**
* ScoringEngine class
*/
declare class ScoringEngine {
private thresholds;
private customWeights;
/**
* Constructor
*/
constructor(thresholds: RiskThresholds);
/**
* Initialize scoring engine
*/
init(): Promise<void>;
/**
* Calculate combined score from all signal scores
*/
calculateCombinedScore(scores: SignalScores): number;
/**
* Set custom module weights
*/
setCustomWeights(weights: Partial<typeof MODULE_WEIGHTS>): void;
/**
* Validate that weights sum to approximately 1.0
*/
private validateWeights;
/**
* Calculate confidence level based on available signals
*/
calculateConfidence(scores: SignalScores): number;
/**
* Adjust score based on historical data (adaptive learning)
*/
adjustScoreWithHistory(currentScore: number, historicalScores: number[]): number;
/**
* Calculate score variance (consistency indicator)
*/
calculateScoreVariance(scores: number[]): number;
/**
* Detect anomalies in score pattern
*/
detectScoreAnomaly(currentScore: number, historicalScores: number[]): boolean;
/**
* Get recommended action based on score
*/
getRecommendedAction(score: number): {
action: 'accept' | 'challenge' | 'block';
confidence: number;
};
/**
* Reset scoring engine state
*/
reset(): void;
/**
* Get current thresholds
*/
getThresholds(): RiskThresholds;
/**
* Update thresholds
*/
setThresholds(thresholds: Partial<RiskThresholds>): void;
}
/**
* BaseModule - Abstract base class for all detection modules
* Provides common functionality and interface
*
* @package @newgenesis/vision
* @author NewGenesis <https://newgenesis.ai>
*/
/**
* Abstract base class for detection modules
*/
declare abstract class BaseModule implements DetectionModule {
readonly name: string;
protected isInitialized: boolean;
protected isActive: boolean;
protected startTime: number;
/**
* Constructor
*/
constructor(name: string);
/**
* Initialize the module (must be implemented by subclass)
*/
abstract init(): Promise<void>;
/**
* Start collecting data
*/
start(): void;
/**
* Stop collecting data
*/
stop(): void;
/**
* Analyze collected data and return risk score (0-1)
*/
abstract analyze(): Promise<number>;
/**
* Get detailed results
*/
abstract getDetails(): Promise<any>;
/**
* Reset module state
*/
reset(): void;
/**
* Hook called when module starts (override in subclass)
*/
protected onStart(): void;
/**
* Hook called when module stops (override in subclass)
*/
protected onStop(): void;
/**
* Hook called when module resets (override in subclass)
*/
protected onReset(): void;
/**
* Get elapsed time since start
*/
protected getElapsedTime(): number;
/**
* Check if module is ready
*/
isReady(): boolean;
/**
* Check if module is currently active
*/
isRunning(): boolean;
}
/**
* BehavioralModule - Analyzes user behavioral patterns
* Tracks mouse movements, keyboard input, scroll behavior, and focus events
* to detect automation and bot-like patterns
*
* @package @newgenesis/vision
* @author NewGenesis <https://newgenesis.ai>
*/
/**
* BehavioralModule class
*/
declare class BehavioralModule extends BaseModule {
private mouseEvents;
private keyboardEvents;
private scrollEvents;
private focusEvents;
private blurEvents;
private pasteDetected;
private eventListeners;
/**
* Constructor
*/
constructor();
/**
* Initialize behavioral module
*/
init(): Promise<void>;
/**
* Start tracking behavioral events
*/
protected onStart(): void;
/**
* Stop tracking behavioral events
*/
protected onStop(): void;
private setupMouseTracking;
/**
* Setup keyboard tracking
*/
private setupKeyboardTracking;
/**
* Setup scroll tracking
*/
private setupScrollTracking;
/**
* Setup focus/blur tracking
*/
private setupFocusTracking;
/**
* Remove all event listeners
*/
private removeEventListeners;
/**
* Analyze behavioral data and calculate risk score
*/
analyze(): Promise<number>;
/**
* Analyze mouse movement patterns
*/
private analyzeMouseBehavior;
/**
* Calculate ratio of straight line movements
*/
private calculateStraightLineRatio;
/**
* Analyze keyboard input patterns
*/
private analyzeKeyboardBehavior;
/**
* Analyze scroll behavior
*/
private analyzeScrollBehavior;
/**
* Analyze focus/blur patterns
*/
private analyzeFocusPatterns;
/**
* Get detailed behavioral analysis results
*/
getDetails(): Promise<BehavioralDetails>;
/**
* Reset behavioral tracking data
*/
protected onReset(): void;
}
/**
* FingerprintModule - Advanced browser fingerprinting
* Detects headless browsers, automation tools, and collects unique browser characteristics
* Uses Canvas, WebGL, Navigator API, and performance metrics
*
* @package @newgenesis/vision
* @author NewGenesis <https://newgenesis.ai>
*/
/**
* FingerprintModule class
*/
declare class FingerprintModule extends BaseModule {
private fingerprintData;
private suspicionFlags;
/**
* Constructor
*/
constructor();
/**
* Initialize fingerprint module
*/
init(): Promise<void>;
/**
* Start fingerprint collection
*/
protected onStart(): void;
/**
* Collect all browser fingerprints
*/
private collectFingerprints;
/**
* Collect Canvas fingerprint
*/
private collectCanvasFingerprint;
/**
* Check for natural canvas noise
*/
private checkCanvasNoise;
/**
* Collect WebGL fingerprint
*/
private collectWebGLFingerprint;
/**
* Collect Navigator information
*/
private collectNavigatorInfo;
/**
* Collect Screen information
*/
private collectScreenInfo;
/**
* Collect Hardware information
*/
private collectHardwareInfo;
/**
* Detect headless browsers and automation
*/
private detectHeadless;
/**
* Detect Chrome headless
*/
private detectChromeHeadless;
/**
* Detect PhantomJS
*/
private detectPhantomJS;
/**
* Detect Selenium
*/
private detectSelenium;
/**
* Detect automation frameworks
*/
private detectAutomationFrameworks;
/**
* Analyze fingerprint data and calculate risk score
*/
analyze(): Promise<number>;
/**
* Get detailed fingerprint results
*/
getDetails(): Promise<FingerprintDetails>;
/**
* Reset fingerprint data
*/
protected onReset(): void;
}
/**
* NetworkModule - Network analysis and proxy/VPN/Tor detection
* Analyzes connection patterns, timing, and network characteristics
*
* @package @newgenesis/vision
* @author NewGenesis <https://newgenesis.ai>
*/
/**
* NetworkModule class
*/
declare class NetworkModule extends BaseModule {
private timingData;
private connectionInfo;
private suspicionFlags;
/**
* Constructor
*/
constructor();
/**
* Initialize network module
*/
init(): Promise<void>;
/**
* Start network analysis
*/
protected onStart(): void;
/**
* Collect network connection information
*/
private collectNetworkInfo;
/**
* Analyze connection timing patterns
*/
private analyzeConnectionTiming;
/**
* Analyze resource loading timing patterns
*/
private analyzeResourceTiming;
/**
* Detect proxy/VPN usage (basic heuristics)
*/
private detectProxy;
/**
* Detect Tor browser (client-side indicators)
*/
private detectTor;
/**
* Analyze network data and calculate risk score
*/
analyze(): Promise<number>;
/**
* Get detailed network results
*/
getDetails(): Promise<NetworkDetails>;
/**
* Reset network data
*/
protected onReset(): void;
}
/**
* TextAnalysisModule - AI-generated content detection
* Uses NLP, perplexity analysis, and stylometry to detect AI-generated text
*
* @package @newgenesis/vision
* @author NewGenesis <https://newgenesis.ai>
*/
/**
* TextAnalysisModule class
*/
declare class TextAnalysisModule extends BaseModule {
private textContent;
private nlpAnalysis;
private aiDetectionResult;
private compromiseNlp;
/**
* Constructor
*/
constructor();
/**
* Initialize text analysis module
*/
init(): Promise<void>;
/**
* Set text content to analyze
*/
setText(text: string): void;
/**
* Start text analysis
*/
protected onStart(): void;
/**
* Analyze text with NLP
*/
private analyzeWithNLP;
/**
* Fallback analysis when compromise is not available
*/
private analyzeFallback;
/**
* Detect AI-generated content using heuristics
*/
private detectAIContent;
/**
* Calculate simplified perplexity score
* Real perplexity requires a language model, this is a heuristic approximation
*/
private calculateSimplePerplexity;
/**
* Perform stylometry analysis
*/
private analyzeStylometry;
/**
* Calculate ratio of linguistic feature
*/
private calculateFeatureRatio;
/**
* Analyze text and calculate risk score
*/
analyze(): Promise<number>;
/**
* Get detailed text analysis results
*/
getDetails(): Promise<TextAnalysisDetails>;
/**
* Reset text analysis
*/
protected onReset(): void;
/**
* Get current text content
*/
getText(): string;
}
/**
* Logger utility for Vision
* @package @newgenesis/vision
* @author NewGenesis <https://newgenesis.ai>
*/
/**
* Log levels
*/
declare enum LogLevel {
DEBUG = 0,
INFO = 1,
WARN = 2,
ERROR = 3
}
/**
* Logger class for consistent logging across Vision
*/
declare class Logger {
private static instance;
private debugMode;
private minLevel;
private constructor();
/**
* Get singleton instance
*/
static getInstance(): Logger;
/**
* Enable debug mode
*/
setDebug(enabled: boolean): void;
/**
* Set minimum log level
*/
setMinLevel(level: LogLevel): void;
/**
* Debug log
*/
debug(message: string, ...args: any[]): void;
/**
* Info log
*/
info(message: string, ...args: any[]): void;
/**
* Warning log
*/
warn(message: string, ...args: any[]): void;
/**
* Error log
*/
error(message: string, error?: Error, ...args: any[]): void;
/**
* Performance measurement
*/
performance(label: string, duration: number): void;
/**
* Group start
*/
groupStart(label: string): void;
/**
* Group end
*/
groupEnd(): void;
}
/**
* Export singleton instance
*/
declare const logger: Logger;
/**
* Helper utilities for Vision
* @package @newgenesis/vision
* @author NewGenesis <https://newgenesis.ai>
*/
/**
* Generate unique session ID
*/
declare function generateSessionId(): string;
/**
* Generate hash from string
*/
declare function generateHash(str: string): Promise<string>;
/**
* Calculate variance of number array
*/
declare function calculateVariance(values: number[]): number;
/**
* Calculate standard deviation
*/
declare function calculateStdDev(values: number[]): number;
/**
* Calculate mean of number array
*/
declare function calculateMean(values: number[]): number;
/**
* Calculate median of number array
*/
declare function calculateMedian(values: number[]): number;
/**
* Normalize score to 0-1 range
*/
declare function normalizeScore(value: number, min: number, max: number): number;
/**
* Calculate Euclidean distance between two points
*/
declare function euclideanDistance(x1: number, y1: number, x2: number, y2: number): number;
/**
* Calculate velocity between two points over time
*/
declare function calculateVelocity(x1: number, y1: number, x2: number, y2: number, timeDelta: number): number;
/**
* Debounce function
*/
declare function debounce<T extends (...args: any[]) => any>(func: T, wait: number): (...args: Parameters<T>) => void;
/**
* Throttle function
*/
declare function throttle<T extends (...args: any[]) => any>(func: T, limit: number): (...args: Parameters<T>) => void;
/**
* Check if code is running in browser
*/
declare function isBrowser(): boolean;
/**
* Check if code is running in Node.js
*/
declare function isNode(): boolean;
/**
* Safe JSON parse
*/
declare function safeJsonParse<T>(json: string, fallback: T): T;
/**
* Safe local storage get
* @deprecated Use Supabase services instead of localStorage
* @see UserPreferencesService, ConsentService, CacheService, OfflineResultsService
*/
declare function safeLocalStorageGet(key: string): string | null;
/**
* Safe local storage set
* @deprecated Use Supabase services instead of localStorage
* @see UserPreferencesService, ConsentService, CacheService, OfflineResultsService
*/
declare function safeLocalStorageSet(key: string, value: string): boolean;
/**
* Get current timestamp in milliseconds
*/
declare function getTimestamp(): number;
/**
* Format timestamp to ISO string
*/
declare function formatTimestamp(timestamp: number): string;
/**
* Deep clone object
*/
declare function deepClone<T>(obj: T): T;
/**
* Check if value is defined and not null
*/
declare function isDefined<T>(value: T | undefined | null): value is T;
/**
* Clamp value between min and max
*/
declare function clamp(value: number, min: number, max: number): number;
/**
* Calculate weighted average
*/
declare function weightedAverage(values: number[], weights: number[]): number;
declare const helpers_calculateMean: typeof calculateMean;
declare const helpers_calculateMedian: typeof calculateMedian;
declare const helpers_calculateStdDev: typeof calculateStdDev;
declare const helpers_calculateVariance: typeof calculateVariance;
declare const helpers_calculateVelocity: typeof calculateVelocity;
declare const helpers_clamp: typeof clamp;
declare const helpers_debounce: typeof debounce;
declare const helpers_deepClone: typeof deepClone;
declare const helpers_euclideanDistance: typeof euclideanDistance;
declare const helpers_formatTimestamp: typeof formatTimestamp;
declare const helpers_generateHash: typeof generateHash;
declare const helpers_generateSessionId: typeof generateSessionId;
declare const helpers_getTimestamp: typeof getTimestamp;
declare const helpers_isBrowser: typeof isBrowser;
declare const helpers_isDefined: typeof isDefined;
declare const helpers_isNode: typeof isNode;
declare const helpers_normalizeScore: typeof normalizeScore;
declare const helpers_safeJsonParse: typeof safeJsonParse;
declare const helpers_safeLocalStorageGet: typeof safeLocalStorageGet;
declare const helpers_safeLocalStorageSet: typeof safeLocalStorageSet;
declare const helpers_throttle: typeof throttle;
declare const helpers_weightedAverage: typeof weightedAverage;
declare namespace helpers {
export { helpers_calculateMean as calculateMean, helpers_calculateMedian as calculateMedian, helpers_calculateStdDev as calculateStdDev, helpers_calculateVariance as calculateVariance, helpers_calculateVelocity as calculateVelocity, helpers_clamp as clamp, helpers_debounce as debounce, helpers_deepClone as deepClone, helpers_euclideanDistance as euclideanDistance, helpers_formatTimestamp as formatTimestamp, helpers_generateHash as generateHash, helpers_generateSessionId as generateSessionId, helpers_getTimestamp as getTimestamp, helpers_isBrowser as isBrowser, helpers_isDefined as isDefined, helpers_isNode as isNode, helpers_normalizeScore as normalizeScore, helpers_safeJsonParse as safeJsonParse, helpers_safeLocalStorageGet as safeLocalStorageGet, helpers_safeLocalStorageSet as safeLocalStorageSet, helpers_throttle as throttle, helpers_weightedAverage as weightedAverage };
}
/**
* Vision namespace for browser usage
*/
declare const Vision: {
Core: typeof VisionCore;
/**
* Quick initialization function for browser
*/
init: (config: VisionConfig) => Promise<VisionCore>;
/**
* Version information
*/
version: string;
author: string;
homepage: string;
};
export { BaseModule, type BehavioralDetails, BehavioralModule, type ChallengeConfig, type ChallengeType, type DetectionDetails, type DetectionModule, type EventData, type FingerprintDetails, FingerprintModule, type KeyboardEventData, LogLevel, type ModuleConfig, type MouseEventData, type NetworkDetails, NetworkModule, type RiskLevel, type RiskThresholds, ScoringEngine, type ScrollEventData, SessionManager, type SignalScores, type TextAnalysisDetails, TextAnalysisModule, Vision, type VisionAction, type VisionConfig, VisionCore, type VisionMode, type VisionResult, VisionStandalone, constants, Vision as default, helpers, logger };