@slopit/behavioral 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/collectors/clipboard.ts","../src/collectors/focus.ts","../src/collectors/input-duration.ts","../src/collectors/keystroke.ts","../src/collectors/mouse.ts","../src/collectors/scroll.ts","../src/metrics/focus-metrics.ts","../src/metrics/input-duration-metrics.ts","../src/metrics/keystroke-metrics.ts","../src/metrics/mouse-metrics.ts","../src/metrics/scroll-metrics.ts","../src/metrics/timing-metrics.ts","../src/capture.ts","../src/collectors/paste.ts","../src/detection/text-appearance.ts","../src/detection/extension.ts","../src/intervention/intervention-manager.ts","../src/intervention/challenges.ts","../src/wrappers/input-wrapper.ts"],"names":["simpleHash","hashText"],"mappings":";;;AAuCO,IAAM,qBAAN,MAAyB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAkB9B,WAAA,CACU,MAAA,EAGR,SAAA,EACQ,mBAAA,EACA,cACA,WAAA,EACR;AAPQ,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAIA,IAAA,IAAA,CAAA,mBAAA,GAAA,mBAAA;AACA,IAAA,IAAA,CAAA,YAAA,GAAA,YAAA;AACA,IAAA,IAAA,CAAA,WAAA,GAAA,WAAA;AAER,IAAA,IAAA,CAAK,SAAA,GAAY,SAAA;AACjB,IAAA,IAAA,CAAK,UAAA,GAAa,IAAA,CAAK,WAAA,CAAY,IAAA,CAAK,IAAI,CAAA;AAC5C,IAAA,IAAA,CAAK,SAAA,GAAY,IAAA,CAAK,UAAA,CAAW,IAAA,CAAK,IAAI,CAAA;AAC1C,IAAA,IAAA,CAAK,QAAA,GAAW,IAAA,CAAK,SAAA,CAAU,IAAA,CAAK,IAAI,CAAA;AAAA,EAC1C;AAAA,EA9BQ,cAA4B,EAAC;AAAA,EAC7B,aAAmC,EAAC;AAAA,EACpC,OAAA,GAAy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,IAAA,MAAM,IAAA,GAAO,IAAA,CAAK,OAAA,CAAQ,OAAA,EAAQ;AAClC,IAAA,MAAM,KAAA,GAAQ,IAAA,CAAK,OAAA,CAAQ,QAAA,EAAS;AAEpC,IAAA,IAAI,IAAA,CAAK,mBAAA,CAAoB,eAAA,CAAgB,IAAA,EAAM,KAAK,CAAA,EAAG;AACzD,MAAA,IAAA,CAAK,wBAAA,GAA2B,IAAA;AAEhC,MAAA,IAAI;AACF,QAAA,MAAM,SAAS,MAAM,IAAA,CAAK,mBAAA,CAAoB,SAAA,CAAU,MAAM,KAAK,CAAA;AACnE,QAAA,IAAA,CAAK,mBAAA,CAAoB,KAAK,MAAM,CAAA;AACpC,QAAA,IAAA,CAAK,IAAA,CAAK,gBAAgB,MAAM,CAAA;AAAA,MAClC,CAAA,SAAE;AACA,QAAA,IAAA,CAAK,wBAAA,GAA2B,KAAA;AAAA,MAClC;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQQ,IAAA,CAAK,OAAqB,IAAA,EAAqB;AACrD,IAAA,MAAM,QAAA,GAAW,IAAA,CAAK,SAAA,CAAU,GAAA,CAAI,KAAK,CAAA;AACzC,IAAA,IAAI,aAAa,MAAA,EAAW;AAC1B,MAAA;AAAA,IACF;AAEA,IAAA,KAAA,MAAW,WAAW,QAAA,EAAU;AAC9B,MAAA,OAAA,CAAQ,IAAI,CAAA;AAAA,IACd;AAAA,EACF;AACF;AAmBO,SAAS,mBAAmB,MAAA,EAA2C;AAC5E,EAAA,OAAO,IAAI,aAAa,MAAM,CAAA;AAChC","file":"index.js","sourcesContent":["/**\n * Clipboard collector for paste and copy/cut events.\n *\n * @module\n */\n\nimport { hashText, simpleHash } from \"@slopit/core\";\nimport type { ClipboardCopyEvent, PasteEvent } from \"@slopit/core\";\n\nimport type { ClipboardCaptureConfig } from \"../types.js\";\n\n/**\n * Collects clipboard events (paste, copy, cut) from DOM elements.\n *\n * This collector unifies paste event tracking with copy/cut event tracking,\n * capturing selection context for copy/cut operations.\n *\n * @example\n * ```typescript\n * const collector = new ClipboardCollector(\n * {\n * enabled: true,\n * capturePaste: true,\n * captureCopyCut: true,\n * prevent: false,\n * capturePreview: true,\n * previewLength: 100,\n * },\n * performance.now(),\n * () => keystrokeCollector.getRecentCount(2000),\n * );\n *\n * collector.attach(document);\n * // ... capture events\n * const pasteEvents = collector.getPasteEvents();\n * const copyEvents = collector.getCopyEvents();\n * collector.detach();\n * ```\n */\nexport class ClipboardCollector {\n private pasteEvents: PasteEvent[] = [];\n private copyEvents: ClipboardCopyEvent[] = [];\n private element: HTMLElement | Document | null = null;\n private startTime: number;\n private boundPaste: (e: ClipboardEvent) => void;\n private boundCopy: (e: ClipboardEvent) => void;\n private boundCut: (e: ClipboardEvent) => void;\n\n /**\n * Creates a new ClipboardCollector.\n *\n * @param config - Configuration options for clipboard capture\n * @param startTime - Reference time for event timestamps (typically performance.now())\n * @param getRecentKeystrokes - Function returning keystroke count in recent window\n * @param onPasteEvent - Optional callback invoked for each paste event\n * @param onCopyEvent - Optional callback invoked for each copy/cut event\n */\n constructor(\n private config: Required<Omit<ClipboardCaptureConfig, \"warnMessage\">> & {\n warnMessage?: string;\n },\n startTime: number,\n private getRecentKeystrokes: () => number,\n private onPasteEvent?: (event: PasteEvent) => void,\n private onCopyEvent?: (event: ClipboardCopyEvent) => void,\n ) {\n this.startTime = startTime;\n this.boundPaste = this.handlePaste.bind(this);\n this.boundCopy = this.handleCopy.bind(this);\n this.boundCut = this.handleCut.bind(this);\n }\n\n /**\n * Attach collector to an element.\n *\n * @param element - The DOM element or document to attach listeners to\n */\n attach(element: HTMLElement | Document): void {\n this.element = element;\n\n if (this.config.capturePaste) {\n element.addEventListener(\"paste\", this.boundPaste as EventListener);\n }\n\n if (this.config.captureCopyCut) {\n element.addEventListener(\"copy\", this.boundCopy as EventListener);\n element.addEventListener(\"cut\", this.boundCut as EventListener);\n }\n }\n\n /**\n * Detach collector from element.\n */\n detach(): void {\n if (this.element) {\n this.element.removeEventListener(\"paste\", this.boundPaste as EventListener);\n this.element.removeEventListener(\"copy\", this.boundCopy as EventListener);\n this.element.removeEventListener(\"cut\", this.boundCut as EventListener);\n this.element = null;\n }\n }\n\n /**\n * Reset collected data.\n *\n * @param newStartTime - Optional new reference time for timestamps\n */\n reset(newStartTime?: number): void {\n this.pasteEvents = [];\n this.copyEvents = [];\n if (newStartTime !== undefined) {\n this.startTime = newStartTime;\n }\n }\n\n /**\n * Get all collected paste events.\n *\n * @returns Copy of paste events array\n */\n getPasteEvents(): PasteEvent[] {\n return [...this.pasteEvents];\n }\n\n /**\n * Get all collected copy/cut events.\n *\n * @returns Copy of copy/cut events array\n */\n getCopyEvents(): ClipboardCopyEvent[] {\n return [...this.copyEvents];\n }\n\n /**\n * Get all clipboard events combined.\n *\n * @returns Array of all paste and copy/cut events, sorted by time\n */\n getAllEvents(): Array<PasteEvent | ClipboardCopyEvent> {\n const all: Array<PasteEvent | ClipboardCopyEvent> = [...this.pasteEvents, ...this.copyEvents];\n return all.sort((a, b) => a.time - b.time);\n }\n\n private handlePaste(e: ClipboardEvent): void {\n const text = e.clipboardData?.getData(\"text/plain\") ?? \"\";\n const time = performance.now() - this.startTime;\n const precedingKeystrokes = this.getRecentKeystrokes();\n\n // Optionally prevent paste\n if (this.config.prevent) {\n e.preventDefault();\n if (this.config.warnMessage) {\n alert(this.config.warnMessage);\n }\n }\n\n const event: PasteEvent = {\n time,\n textLength: text.length,\n precedingKeystrokes,\n blocked: this.config.prevent,\n ...(this.config.capturePreview\n ? { textPreview: text.slice(0, this.config.previewLength) }\n : {}),\n // Hash asynchronously but use sync hash for immediate event\n textHash: simpleHash(text),\n };\n\n this.pasteEvents.push(event);\n this.onPasteEvent?.(event);\n\n // Update with proper SHA-256 hash asynchronously\n if (text.length > 0) {\n hashText(text).then((hash) => {\n event.textHash = hash;\n });\n }\n }\n\n private handleCopy(e: ClipboardEvent): void {\n this.handleCopyCut(e, \"copy\");\n }\n\n private handleCut(e: ClipboardEvent): void {\n this.handleCopyCut(e, \"cut\");\n }\n\n private handleCopyCut(_e: ClipboardEvent, eventType: \"copy\" | \"cut\"): void {\n const time = performance.now() - this.startTime;\n const selection = window.getSelection();\n const text = selection?.toString() ?? \"\";\n\n // Get selection indices from active element if it's an input or textarea\n let selectionStart: number | undefined;\n let selectionEnd: number | undefined;\n const activeElement = document.activeElement;\n\n if (activeElement instanceof HTMLInputElement || activeElement instanceof HTMLTextAreaElement) {\n selectionStart = activeElement.selectionStart ?? undefined;\n selectionEnd = activeElement.selectionEnd ?? undefined;\n }\n\n const event: ClipboardCopyEvent = {\n time,\n event: eventType,\n textLength: text.length,\n ...(this.config.capturePreview\n ? { textPreview: text.slice(0, this.config.previewLength) }\n : {}),\n textHash: simpleHash(text),\n ...(selectionStart !== undefined ? { selectionStart } : {}),\n ...(selectionEnd !== undefined ? { selectionEnd } : {}),\n };\n\n this.copyEvents.push(event);\n this.onCopyEvent?.(event);\n\n // Update with proper SHA-256 hash asynchronously\n if (text.length > 0) {\n hashText(text).then((hash) => {\n event.textHash = hash;\n });\n }\n }\n}\n","import type { FocusEvent as SlopitFocusEvent } from \"@slopit/core\";\nimport type { FocusCaptureConfig } from \"../types.js\";\n\n/**\n * Collects focus and visibility events.\n */\nexport class FocusCollector {\n private events: SlopitFocusEvent[] = [];\n private startTime: number;\n private lastBlurTime: number | undefined;\n private lastHiddenTime: number | undefined;\n private boundFocus: () => void;\n private boundBlur: () => void;\n private boundVisibility: () => void;\n private attached = false;\n\n constructor(\n private config: Required<FocusCaptureConfig>,\n startTime: number,\n private onEvent?: (event: SlopitFocusEvent) => void,\n ) {\n this.startTime = startTime;\n this.boundFocus = this.handleFocus.bind(this);\n this.boundBlur = this.handleBlur.bind(this);\n this.boundVisibility = this.handleVisibilityChange.bind(this);\n }\n\n /**\n * Attach collector to document.\n */\n attach(_element: Document): void {\n if (this.attached) return;\n\n if (this.config.useBlurFocus) {\n window.addEventListener(\"focus\", this.boundFocus);\n window.addEventListener(\"blur\", this.boundBlur);\n }\n\n if (this.config.useVisibilityAPI) {\n document.addEventListener(\"visibilitychange\", this.boundVisibility);\n }\n\n this.attached = true;\n }\n\n /**\n * Detach collector.\n */\n detach(): void {\n if (!this.attached) return;\n\n window.removeEventListener(\"focus\", this.boundFocus);\n window.removeEventListener(\"blur\", this.boundBlur);\n document.removeEventListener(\"visibilitychange\", this.boundVisibility);\n\n // Calculate final blur duration if still blurred\n if (this.lastBlurTime !== undefined) {\n this.updateLastBlurDuration();\n }\n\n this.attached = false;\n }\n\n /**\n * Reset collected data.\n */\n reset(newStartTime?: number): void {\n this.events = [];\n this.lastBlurTime = undefined;\n this.lastHiddenTime = undefined;\n if (newStartTime !== undefined) {\n this.startTime = newStartTime;\n }\n }\n\n /**\n * Get all collected events.\n */\n getEvents(): SlopitFocusEvent[] {\n return [...this.events];\n }\n\n private handleFocus(): void {\n const time = performance.now() - this.startTime;\n\n // Update blur duration of previous blur event\n this.updateLastBlurDuration();\n\n const event: SlopitFocusEvent = {\n time,\n event: \"focus\",\n };\n\n this.events.push(event);\n this.onEvent?.(event);\n }\n\n private handleBlur(): void {\n const time = performance.now() - this.startTime;\n this.lastBlurTime = time;\n\n const event: SlopitFocusEvent = {\n time,\n event: \"blur\",\n };\n\n this.events.push(event);\n this.onEvent?.(event);\n }\n\n private handleVisibilityChange(): void {\n const time = performance.now() - this.startTime;\n const visibility = document.visibilityState as \"visible\" | \"hidden\";\n\n if (visibility === \"hidden\") {\n this.lastHiddenTime = time;\n }\n\n const event: SlopitFocusEvent = {\n time,\n event: \"visibilitychange\",\n visibility,\n };\n\n this.events.push(event);\n this.onEvent?.(event);\n }\n\n private updateLastBlurDuration(): void {\n if (this.lastBlurTime === undefined) return;\n\n const currentTime = performance.now() - this.startTime;\n const blurDuration = currentTime - this.lastBlurTime;\n\n // Find the last blur event and update its duration\n for (let i = this.events.length - 1; i >= 0; i--) {\n const evt = this.events[i];\n if (evt?.event === \"blur\" && evt.blurDuration === undefined) {\n evt.blurDuration = blurDuration;\n break;\n }\n }\n\n this.lastBlurTime = undefined;\n }\n}\n","import type { InputDurationEvent } from \"@slopit/core\";\nimport type { InputDurationCaptureConfig } from \"../types.js\";\n\n/**\n * Tracks focus and blur events on input elements to measure engagement duration.\n *\n * This collector monitors element-level focus (not document-level) and records\n * the duration of each focus session. It can optionally track keystrokes and\n * paste events that occur during each focus period.\n */\nexport class InputDurationCollector {\n private events: InputDurationEvent[] = [];\n private element: HTMLElement | null = null;\n private startTime: number;\n private currentFocusStart: number | null = null;\n private currentKeystrokeCount = 0;\n private currentPasteCount = 0;\n private boundFocus: (e: Event) => void;\n private boundBlur: (e: Event) => void;\n\n constructor(\n private config: Required<InputDurationCaptureConfig>,\n startTime: number,\n private onEvent?: (event: InputDurationEvent) => void,\n ) {\n this.startTime = startTime;\n this.boundFocus = this.handleFocus.bind(this);\n this.boundBlur = this.handleBlur.bind(this);\n }\n\n /**\n * Attach collector to an element.\n *\n * @param element - The element to monitor for focus events.\n */\n attach(element: HTMLElement | Document): void {\n // Input duration tracking requires an HTMLElement, not Document\n if (element instanceof Document) {\n return;\n }\n this.element = element;\n element.addEventListener(\"focus\", this.boundFocus);\n element.addEventListener(\"blur\", this.boundBlur);\n }\n\n /**\n * Detach collector from element.\n */\n detach(): void {\n if (this.element) {\n this.element.removeEventListener(\"focus\", this.boundFocus);\n this.element.removeEventListener(\"blur\", this.boundBlur);\n this.element = null;\n }\n // Finalize any ongoing focus session\n if (this.currentFocusStart !== null) {\n this.finalizeCurrentSession();\n }\n }\n\n /**\n * Reset collected data.\n *\n * @param newStartTime - Optional new start time for relative timing.\n */\n reset(newStartTime?: number): void {\n this.events = [];\n this.currentFocusStart = null;\n this.currentKeystrokeCount = 0;\n this.currentPasteCount = 0;\n if (newStartTime !== undefined) {\n this.startTime = newStartTime;\n }\n }\n\n /**\n * Get all collected events.\n *\n * @returns A copy of the collected input duration events.\n */\n getEvents(): InputDurationEvent[] {\n return [...this.events];\n }\n\n /**\n * Get the start time of the current focus session.\n *\n * @returns The focus start time relative to startTime, or null if not focused.\n */\n getCurrentFocusStart(): number | null {\n return this.currentFocusStart;\n }\n\n /**\n * Increment the keystroke count for the current focus session.\n *\n * This method is called externally by the orchestrator when a keystroke\n * occurs on the tracked element.\n */\n incrementKeystrokes(): void {\n if (this.config.trackKeystrokes && this.currentFocusStart !== null) {\n this.currentKeystrokeCount++;\n }\n }\n\n /**\n * Increment the paste count for the current focus session.\n *\n * This method is called externally by the orchestrator when a paste\n * event occurs on the tracked element.\n */\n incrementPastes(): void {\n if (this.config.trackPastes && this.currentFocusStart !== null) {\n this.currentPasteCount++;\n }\n }\n\n private handleFocus(_e: Event): void {\n if (this.currentFocusStart === null) {\n this.currentFocusStart = performance.now() - this.startTime;\n this.currentKeystrokeCount = 0;\n this.currentPasteCount = 0;\n }\n }\n\n private handleBlur(_e: Event): void {\n this.finalizeCurrentSession();\n }\n\n private finalizeCurrentSession(): void {\n if (this.currentFocusStart === null) {\n return;\n }\n\n const blurTime = performance.now() - this.startTime;\n const duration = blurTime - this.currentFocusStart;\n const elementId = this.getElementId();\n\n const event: InputDurationEvent = {\n focusTime: this.currentFocusStart,\n blurTime,\n duration,\n };\n\n if (elementId !== undefined) {\n event.elementId = elementId;\n }\n\n if (this.config.trackKeystrokes) {\n event.keystrokesDuringFocus = this.currentKeystrokeCount;\n }\n\n if (this.config.trackPastes) {\n event.pastesDuringFocus = this.currentPasteCount;\n }\n\n this.events.push(event);\n this.onEvent?.(event);\n\n this.currentFocusStart = null;\n this.currentKeystrokeCount = 0;\n this.currentPasteCount = 0;\n }\n\n private getElementId(): string | undefined {\n if (!this.element) {\n return undefined;\n }\n\n // Prefer id attribute, then fall back to name attribute\n if (this.element.id) {\n return this.element.id;\n }\n\n if (this.element instanceof HTMLInputElement || this.element instanceof HTMLTextAreaElement) {\n return this.element.name || undefined;\n }\n\n return undefined;\n }\n}\n","import type { KeystrokeEvent, ModifierState } from \"@slopit/core\";\nimport type { KeystrokeCaptureConfig } from \"../types.js\";\n\n/**\n * Collects keystroke events from DOM elements.\n */\nexport class KeystrokeCollector {\n private events: KeystrokeEvent[] = [];\n private element: HTMLElement | Document | null = null;\n private startTime: number;\n private firstKeystrokeTime: number | undefined;\n private boundKeydown: (e: KeyboardEvent) => void;\n private boundKeyup: (e: KeyboardEvent) => void;\n\n constructor(\n private config: Required<KeystrokeCaptureConfig>,\n startTime: number,\n private onEvent?: (event: KeystrokeEvent) => void,\n ) {\n this.startTime = startTime;\n this.boundKeydown = this.handleKeydown.bind(this);\n this.boundKeyup = this.handleKeyup.bind(this);\n }\n\n /**\n * Attach collector to an element.\n */\n attach(element: HTMLElement | Document): void {\n this.element = element;\n element.addEventListener(\"keydown\", this.boundKeydown as EventListener);\n if (this.config.captureKeyUp) {\n element.addEventListener(\"keyup\", this.boundKeyup as EventListener);\n }\n }\n\n /**\n * Detach collector from element.\n */\n detach(): void {\n if (this.element) {\n this.element.removeEventListener(\"keydown\", this.boundKeydown as EventListener);\n this.element.removeEventListener(\"keyup\", this.boundKeyup as EventListener);\n this.element = null;\n }\n }\n\n /**\n * Reset collected data.\n */\n reset(newStartTime?: number): void {\n this.events = [];\n this.firstKeystrokeTime = undefined;\n if (newStartTime !== undefined) {\n this.startTime = newStartTime;\n }\n }\n\n /**\n * Get all collected events.\n */\n getEvents(): KeystrokeEvent[] {\n return [...this.events];\n }\n\n /**\n * Get time of first keystroke.\n */\n getFirstKeystrokeTime(): number | undefined {\n return this.firstKeystrokeTime;\n }\n\n /**\n * Get count of keystrokes in the last N milliseconds.\n */\n getRecentCount(windowMs: number): number {\n const now = performance.now();\n const cutoff = now - this.startTime - windowMs;\n return this.events.filter((e) => e.time >= cutoff).length;\n }\n\n private handleKeydown(e: KeyboardEvent): void {\n this.recordEvent(e, \"keydown\");\n }\n\n private handleKeyup(e: KeyboardEvent): void {\n this.recordEvent(e, \"keyup\");\n }\n\n private recordEvent(e: KeyboardEvent, type: \"keydown\" | \"keyup\"): void {\n const time = performance.now() - this.startTime;\n\n if (this.firstKeystrokeTime === undefined && type === \"keydown\") {\n this.firstKeystrokeTime = time;\n }\n\n const textLength = this.getTextLength(e.target);\n\n const event: KeystrokeEvent = {\n time,\n key: e.key,\n code: e.code,\n event: type,\n ...(textLength !== undefined ? { textLength } : {}),\n ...(this.config.includeModifiers ? { modifiers: this.getModifiers(e) } : {}),\n };\n\n this.events.push(event);\n this.onEvent?.(event);\n }\n\n private getTextLength(target: EventTarget | null): number | undefined {\n if (target instanceof HTMLTextAreaElement || target instanceof HTMLInputElement) {\n return target.value.length;\n }\n if (target instanceof HTMLElement && target.isContentEditable) {\n return target.textContent?.length;\n }\n return undefined;\n }\n\n private getModifiers(e: KeyboardEvent): ModifierState {\n return {\n shift: e.shiftKey,\n ctrl: e.ctrlKey,\n alt: e.altKey,\n meta: e.metaKey,\n };\n }\n}\n","import type { MouseEvent } from \"@slopit/core\";\nimport type { MouseCaptureConfig } from \"../types.js\";\n\n/**\n * Represents a period of mouse inactivity.\n */\nexport interface IdlePeriod {\n /**\n * Start time relative to startTime in milliseconds.\n */\n start: number;\n\n /**\n * End time relative to startTime in milliseconds.\n */\n end: number;\n\n /**\n * Duration of idle period in milliseconds.\n */\n duration: number;\n}\n\n/**\n * Collects mouse events from DOM elements.\n *\n * Tracks mouse movement with configurable throttling, click events,\n * drag operations, and idle periods. Computes velocity and distance\n * for movement events.\n */\nexport class MouseCollector {\n private events: MouseEvent[] = [];\n private element: HTMLElement | Document | null = null;\n private startTime: number;\n private lastMoveTime: number | null = null;\n private lastX: number | null = null;\n private lastY: number | null = null;\n private isDragging = false;\n private idlePeriods: IdlePeriod[] = [];\n private idleStart: number | null = null;\n private idleCheckInterval: ReturnType<typeof setInterval> | null = null;\n\n private boundMousemove: (e: globalThis.MouseEvent) => void;\n private boundMousedown: (e: globalThis.MouseEvent) => void;\n private boundMouseup: (e: globalThis.MouseEvent) => void;\n private boundClick: (e: globalThis.MouseEvent) => void;\n\n private throttledMoveHandler: ((e: globalThis.MouseEvent) => void) | null = null;\n private lastThrottledCall = 0;\n\n constructor(\n private config: Required<MouseCaptureConfig>,\n startTime: number,\n private onEvent?: (event: MouseEvent) => void,\n ) {\n this.startTime = startTime;\n this.boundMousemove = this.handleMousemove.bind(this);\n this.boundMousedown = this.handleMousedown.bind(this);\n this.boundMouseup = this.handleMouseup.bind(this);\n this.boundClick = this.handleClick.bind(this);\n }\n\n /**\n * Attach collector to an element.\n *\n * @param element - The DOM element or document to attach listeners to\n */\n attach(element: HTMLElement | Document): void {\n this.element = element;\n\n if (this.config.captureMovement) {\n this.throttledMoveHandler = this.createThrottledHandler(\n this.boundMousemove,\n this.config.throttleMs,\n );\n element.addEventListener(\"mousemove\", this.throttledMoveHandler as EventListener);\n }\n\n if (this.config.captureClicks) {\n element.addEventListener(\"mousedown\", this.boundMousedown as EventListener);\n element.addEventListener(\"mouseup\", this.boundMouseup as EventListener);\n element.addEventListener(\"click\", this.boundClick as EventListener);\n }\n\n // Start idle detection\n this.startIdleDetection();\n }\n\n /**\n * Detach collector from element.\n */\n detach(): void {\n if (this.element) {\n if (this.throttledMoveHandler) {\n this.element.removeEventListener(\"mousemove\", this.throttledMoveHandler as EventListener);\n }\n this.element.removeEventListener(\"mousedown\", this.boundMousedown as EventListener);\n this.element.removeEventListener(\"mouseup\", this.boundMouseup as EventListener);\n this.element.removeEventListener(\"click\", this.boundClick as EventListener);\n this.element = null;\n }\n\n this.stopIdleDetection();\n\n // Close any open idle period\n if (this.idleStart !== null) {\n const now = performance.now() - this.startTime;\n this.idlePeriods.push({\n start: this.idleStart,\n end: now,\n duration: now - this.idleStart,\n });\n this.idleStart = null;\n }\n }\n\n /**\n * Reset collected data.\n *\n * @param newStartTime - Optional new start time to use for relative timestamps\n */\n reset(newStartTime?: number): void {\n this.events = [];\n this.idlePeriods = [];\n this.lastMoveTime = null;\n this.lastX = null;\n this.lastY = null;\n this.isDragging = false;\n this.idleStart = null;\n this.lastThrottledCall = 0;\n\n if (newStartTime !== undefined) {\n this.startTime = newStartTime;\n }\n }\n\n /**\n * Get all collected events.\n *\n * @returns A copy of the collected mouse events array\n */\n getEvents(): MouseEvent[] {\n return [...this.events];\n }\n\n /**\n * Get all detected idle periods.\n *\n * @returns A copy of the idle periods array\n */\n getIdlePeriods(): IdlePeriod[] {\n return [...this.idlePeriods];\n }\n\n /**\n * Get total idle time in milliseconds.\n *\n * @returns Sum of all idle period durations\n */\n getTotalIdleTime(): number {\n return this.idlePeriods.reduce((sum, period) => sum + period.duration, 0);\n }\n\n /**\n * Get total distance traveled by the cursor in pixels.\n *\n * @returns Sum of all distance values from mousemove events\n */\n getTotalDistance(): number {\n return this.events\n .filter((e) => e.event === \"mousemove\" && e.distance !== undefined)\n .reduce((sum, e) => sum + (e.distance ?? 0), 0);\n }\n\n private createThrottledHandler(\n handler: (e: globalThis.MouseEvent) => void,\n throttleMs: number,\n ): (e: globalThis.MouseEvent) => void {\n return (e: globalThis.MouseEvent) => {\n const now = performance.now();\n if (now - this.lastThrottledCall >= throttleMs) {\n this.lastThrottledCall = now;\n handler(e);\n }\n };\n }\n\n private handleMousemove(e: globalThis.MouseEvent): void {\n const time = performance.now() - this.startTime;\n const x = e.clientX;\n const y = e.clientY;\n\n let velocity: number | undefined;\n let distance: number | undefined;\n let deltaTime: number | undefined;\n\n if (this.lastX !== null && this.lastY !== null && this.lastMoveTime !== null) {\n const dx = x - this.lastX;\n const dy = y - this.lastY;\n distance = Math.sqrt(dx * dx + dy * dy);\n deltaTime = time - this.lastMoveTime;\n\n if (deltaTime > 0) {\n velocity = distance / deltaTime;\n }\n }\n\n const event: MouseEvent = {\n time,\n event: \"mousemove\",\n x,\n y,\n ...(velocity !== undefined ? { velocity } : {}),\n ...(distance !== undefined ? { distance } : {}),\n ...(deltaTime !== undefined ? { deltaTime } : {}),\n ...(this.isDragging ? { isDragging: true } : {}),\n };\n\n this.events.push(event);\n this.onEvent?.(event);\n\n this.lastX = x;\n this.lastY = y;\n this.lastMoveTime = time;\n\n // Reset idle tracking on movement\n this.recordActivity(time);\n }\n\n private handleMousedown(e: globalThis.MouseEvent): void {\n const time = performance.now() - this.startTime;\n this.isDragging = true;\n\n const event: MouseEvent = {\n time,\n event: \"mousedown\",\n x: e.clientX,\n y: e.clientY,\n };\n\n this.events.push(event);\n this.onEvent?.(event);\n\n this.recordActivity(time);\n }\n\n private handleMouseup(e: globalThis.MouseEvent): void {\n const time = performance.now() - this.startTime;\n const wasDragging = this.isDragging;\n this.isDragging = false;\n\n const event: MouseEvent = {\n time,\n event: \"mouseup\",\n x: e.clientX,\n y: e.clientY,\n ...(wasDragging ? { isDragging: true } : {}),\n };\n\n this.events.push(event);\n this.onEvent?.(event);\n\n this.recordActivity(time);\n }\n\n private handleClick(e: globalThis.MouseEvent): void {\n const time = performance.now() - this.startTime;\n\n const event: MouseEvent = {\n time,\n event: \"click\",\n x: e.clientX,\n y: e.clientY,\n };\n\n this.events.push(event);\n this.onEvent?.(event);\n\n this.recordActivity(time);\n }\n\n private recordActivity(time: number): void {\n // If we were idle, close the idle period\n if (this.idleStart !== null) {\n this.idlePeriods.push({\n start: this.idleStart,\n end: time,\n duration: time - this.idleStart,\n });\n this.idleStart = null;\n }\n }\n\n private startIdleDetection(): void {\n // Check for idle every second\n this.idleCheckInterval = setInterval(() => {\n const now = performance.now() - this.startTime;\n const lastEventTime = this.getLastEventTime();\n\n if (lastEventTime !== null) {\n const timeSinceLastEvent = now - lastEventTime;\n\n // Start idle period if threshold exceeded and not already idle\n if (timeSinceLastEvent >= this.config.idleThresholdMs && this.idleStart === null) {\n // Idle started at the last event time + threshold\n this.idleStart = lastEventTime + this.config.idleThresholdMs;\n }\n }\n }, 1000);\n }\n\n private stopIdleDetection(): void {\n if (this.idleCheckInterval !== null) {\n clearInterval(this.idleCheckInterval);\n this.idleCheckInterval = null;\n }\n }\n\n private getLastEventTime(): number | null {\n if (this.events.length === 0) {\n return null;\n }\n const lastEvent = this.events[this.events.length - 1];\n return lastEvent?.time ?? null;\n }\n}\n","import type { ScrollEvent } from \"@slopit/core\";\nimport type { ScrollCaptureConfig } from \"../types.js\";\n\n/**\n * Collects scroll events from DOM elements.\n *\n * Tracks scroll direction, position, and velocity to help distinguish\n * between composing and reading/reviewing behavior patterns.\n */\nexport class ScrollCollector {\n private events: ScrollEvent[] = [];\n private element: HTMLElement | Document | null = null;\n private startTime: number;\n private lastScrollTime: number | undefined;\n private lastScrollTop: number | undefined;\n private lastDirection: \"up\" | \"down\" | undefined;\n private directionChanges = 0;\n private throttleTimer: ReturnType<typeof setTimeout> | null = null;\n private boundScroll: (e: Event) => void;\n\n constructor(\n private config: Required<ScrollCaptureConfig>,\n startTime: number,\n private onEvent?: (event: ScrollEvent) => void,\n ) {\n this.startTime = startTime;\n this.boundScroll = this.handleScroll.bind(this);\n }\n\n /**\n * Attach collector to an element.\n *\n * @param element - The element to attach scroll listeners to.\n */\n attach(element: HTMLElement | Document): void {\n this.element = element;\n element.addEventListener(\"scroll\", this.boundScroll, { passive: true });\n }\n\n /**\n * Detach collector from element.\n */\n detach(): void {\n if (this.element) {\n this.element.removeEventListener(\"scroll\", this.boundScroll);\n this.element = null;\n }\n if (this.throttleTimer !== null) {\n clearTimeout(this.throttleTimer);\n this.throttleTimer = null;\n }\n }\n\n /**\n * Reset collected data.\n *\n * @param newStartTime - Optional new start time for timing calculations.\n */\n reset(newStartTime?: number): void {\n this.events = [];\n this.lastScrollTime = undefined;\n this.lastScrollTop = undefined;\n this.lastDirection = undefined;\n this.directionChanges = 0;\n if (newStartTime !== undefined) {\n this.startTime = newStartTime;\n }\n }\n\n /**\n * Get all collected events.\n *\n * @returns A copy of the collected scroll events.\n */\n getEvents(): ScrollEvent[] {\n return [...this.events];\n }\n\n /**\n * Get the number of scroll direction changes.\n *\n * Direction changes may indicate review behavior (scrolling up and down\n * to read previously written content) rather than linear composition.\n *\n * @returns The count of direction changes.\n */\n getDirectionChanges(): number {\n return this.directionChanges;\n }\n\n private handleScroll(e: Event): void {\n if (!this.config.enabled) {\n return;\n }\n\n // Throttle scroll events\n if (this.throttleTimer !== null) {\n return;\n }\n\n this.throttleTimer = setTimeout(() => {\n this.throttleTimer = null;\n }, this.config.throttleMs);\n\n this.recordEvent(e);\n }\n\n private recordEvent(e: Event): void {\n const time = performance.now() - this.startTime;\n const target = this.getScrollTarget(e);\n\n if (!target) {\n return;\n }\n\n const scrollTop = target.scrollTop;\n const scrollHeight = target.scrollHeight;\n const clientHeight = target.clientHeight;\n\n // Calculate delta and direction\n const deltaY = this.lastScrollTop !== undefined ? scrollTop - this.lastScrollTop : 0;\n const direction: \"up\" | \"down\" = deltaY >= 0 ? \"down\" : \"up\";\n\n // Track direction changes\n if (this.config.captureDirection && this.lastDirection !== undefined) {\n if (direction !== this.lastDirection) {\n this.directionChanges++;\n }\n }\n\n // Calculate velocity (pixels per millisecond)\n let velocity: number | undefined;\n if (this.lastScrollTime !== undefined && this.lastScrollTop !== undefined) {\n const timeDelta = time - this.lastScrollTime;\n if (timeDelta > 0) {\n velocity = Math.abs(deltaY) / timeDelta;\n }\n }\n\n const event: ScrollEvent = {\n time,\n direction,\n deltaY,\n scrollTop,\n scrollHeight,\n clientHeight,\n ...(velocity !== undefined ? { velocity } : {}),\n };\n\n this.events.push(event);\n this.onEvent?.(event);\n\n // Update state for next event\n this.lastScrollTime = time;\n this.lastScrollTop = scrollTop;\n this.lastDirection = direction;\n }\n\n private getScrollTarget(e: Event): {\n scrollTop: number;\n scrollHeight: number;\n clientHeight: number;\n } | null {\n const target = e.target;\n\n if (target instanceof Document) {\n const docEl = target.documentElement;\n return {\n scrollTop: docEl.scrollTop,\n scrollHeight: docEl.scrollHeight,\n clientHeight: docEl.clientHeight,\n };\n }\n\n if (target instanceof HTMLElement) {\n return {\n scrollTop: target.scrollTop,\n scrollHeight: target.scrollHeight,\n clientHeight: target.clientHeight,\n };\n }\n\n return null;\n }\n}\n","import type { FocusEvent, FocusMetrics } from \"@slopit/core\";\n\n/**\n * Compute metrics from focus events.\n *\n * @param focusEvents - Array of focus events\n * @returns Computed focus metrics\n */\nexport function computeFocusMetrics(focusEvents: FocusEvent[]): FocusMetrics {\n let blurCount = 0;\n let totalBlurDuration = 0;\n let hiddenCount = 0;\n let totalHiddenDuration = 0;\n let lastHiddenTime: number | undefined;\n\n for (const event of focusEvents) {\n switch (event.event) {\n case \"blur\":\n blurCount++;\n if (event.blurDuration !== undefined) {\n totalBlurDuration += event.blurDuration;\n }\n break;\n\n case \"visibilitychange\":\n if (event.visibility === \"hidden\") {\n hiddenCount++;\n lastHiddenTime = event.time;\n } else if (event.visibility === \"visible\" && lastHiddenTime !== undefined) {\n totalHiddenDuration += event.time - lastHiddenTime;\n lastHiddenTime = undefined;\n }\n break;\n }\n }\n\n return {\n blurCount,\n totalBlurDuration,\n hiddenCount,\n totalHiddenDuration,\n };\n}\n","import type { InputDurationEvent, InputDurationMetrics } from \"@slopit/core\";\n\n/**\n * Compute metrics from input duration events.\n *\n * @param events - Array of input duration events\n * @returns Computed input duration metrics\n */\nexport function computeInputDurationMetrics(events: InputDurationEvent[]): InputDurationMetrics {\n if (events.length === 0) {\n return {\n totalFocusDuration: 0,\n meanFocusDuration: 0,\n focusSessionCount: 0,\n maxFocusDuration: 0,\n };\n }\n\n const durations = events.map((e) => e.duration);\n const totalFocusDuration = durations.reduce((a, b) => a + b, 0);\n const meanFocusDuration = totalFocusDuration / events.length;\n const maxFocusDuration = Math.max(...durations);\n\n return {\n totalFocusDuration,\n meanFocusDuration,\n focusSessionCount: events.length,\n maxFocusDuration,\n };\n}\n","import type { KeystrokeEvent, KeystrokeMetrics } from \"@slopit/core\";\n\n/**\n * Default pause threshold in milliseconds.\n */\nconst DEFAULT_PAUSE_THRESHOLD = 2000;\n\n/**\n * Compute metrics from keystroke events.\n *\n * @param keystrokes - Array of keystroke events\n * @param pauseThreshold - Minimum IKI to count as a pause (default: 2000ms)\n * @returns Computed keystroke metrics\n */\nexport function computeKeystrokeMetrics(\n keystrokes: KeystrokeEvent[],\n pauseThreshold = DEFAULT_PAUSE_THRESHOLD,\n): KeystrokeMetrics {\n // Filter to keydown events only\n const keydowns = keystrokes.filter((k) => k.event === \"keydown\");\n\n if (keydowns.length === 0) {\n return {\n totalKeystrokes: 0,\n printableKeystrokes: 0,\n deletions: 0,\n meanIKI: 0,\n stdIKI: 0,\n medianIKI: 0,\n pauseCount: 0,\n productProcessRatio: 0,\n };\n }\n\n // Count keystroke types\n const printableKeystrokes = keydowns.filter((k) => k.key.length === 1).length;\n const deletions = keydowns.filter((k) => k.key === \"Backspace\" || k.key === \"Delete\").length;\n\n // Compute inter-keystroke intervals\n const ikis = computeIKIs(keydowns);\n\n // Compute IKI statistics\n const { mean, std, median } = computeIKIStats(ikis);\n\n // Count pauses\n const pauseCount = ikis.filter((iki) => iki > pauseThreshold).length;\n\n // Compute product-process ratio\n const lastEvent = keydowns[keydowns.length - 1];\n const finalLength = lastEvent?.textLength ?? 0;\n const productProcessRatio = keydowns.length > 0 ? finalLength / keydowns.length : 0;\n\n return {\n totalKeystrokes: keydowns.length,\n printableKeystrokes,\n deletions,\n meanIKI: mean,\n stdIKI: std,\n medianIKI: median,\n pauseCount,\n productProcessRatio,\n };\n}\n\n/**\n * Compute inter-keystroke intervals from keydown events.\n */\nfunction computeIKIs(keydowns: KeystrokeEvent[]): number[] {\n if (keydowns.length < 2) {\n return [];\n }\n\n const ikis: number[] = [];\n for (let i = 1; i < keydowns.length; i++) {\n const prev = keydowns[i - 1];\n const curr = keydowns[i];\n if (prev && curr) {\n ikis.push(curr.time - prev.time);\n }\n }\n\n return ikis;\n}\n\n/**\n * Compute mean, standard deviation, and median of IKIs.\n */\nfunction computeIKIStats(ikis: number[]): { mean: number; std: number; median: number } {\n if (ikis.length === 0) {\n return { mean: 0, std: 0, median: 0 };\n }\n\n // Mean\n const sum = ikis.reduce((a, b) => a + b, 0);\n const mean = sum / ikis.length;\n\n // Standard deviation\n const squaredDiffs = ikis.map((iki) => (iki - mean) ** 2);\n const variance = squaredDiffs.reduce((a, b) => a + b, 0) / ikis.length;\n const std = Math.sqrt(variance);\n\n // Median\n const sorted = [...ikis].sort((a, b) => a - b);\n const mid = Math.floor(sorted.length / 2);\n const median =\n sorted.length % 2 === 0\n ? ((sorted[mid - 1] ?? 0) + (sorted[mid] ?? 0)) / 2\n : (sorted[mid] ?? 0);\n\n return { mean, std, median };\n}\n","import type { MouseEvent, MouseMetrics } from \"@slopit/core\";\nimport type { IdlePeriod } from \"../collectors/mouse.js\";\n\n/**\n * Compute metrics from mouse events and idle periods.\n *\n * @param events - Array of mouse events\n * @param idlePeriods - Array of detected idle periods\n * @returns Computed mouse metrics\n */\nexport function computeMouseMetrics(events: MouseEvent[], idlePeriods: IdlePeriod[]): MouseMetrics {\n if (events.length === 0) {\n return {\n totalEvents: 0,\n clickCount: 0,\n meanVelocity: 0,\n totalDistance: 0,\n totalIdleTime: 0,\n idlePeriodCount: 0,\n };\n }\n\n const clickCount = events.filter((e) => e.event === \"click\").length;\n\n // Compute velocity statistics from mousemove events\n const moveEvents = events.filter((e) => e.event === \"mousemove\" && e.velocity !== undefined);\n const velocities = moveEvents.map((e) => e.velocity ?? 0);\n const meanVelocity =\n velocities.length > 0 ? velocities.reduce((a, b) => a + b, 0) / velocities.length : 0;\n\n // Compute total distance\n const totalDistance = events\n .filter((e) => e.event === \"mousemove\" && e.distance !== undefined)\n .reduce((sum, e) => sum + (e.distance ?? 0), 0);\n\n // Compute idle time statistics\n const totalIdleTime = idlePeriods.reduce((sum, p) => sum + p.duration, 0);\n\n return {\n totalEvents: events.length,\n clickCount,\n meanVelocity,\n totalDistance,\n totalIdleTime,\n idlePeriodCount: idlePeriods.length,\n };\n}\n","import type { ScrollEvent, ScrollMetrics } from \"@slopit/core\";\n\n/**\n * Compute metrics from scroll events.\n *\n * @param events - Array of scroll events\n * @param directionChanges - Number of direction changes from collector\n * @returns Computed scroll metrics\n */\nexport function computeScrollMetrics(\n events: ScrollEvent[],\n directionChanges: number,\n): ScrollMetrics {\n if (events.length === 0) {\n return {\n totalScrollEvents: 0,\n totalScrollDistance: 0,\n directionChanges: 0,\n meanScrollVelocity: 0,\n upDownRatio: 0,\n };\n }\n\n // Compute total scroll distance\n const totalScrollDistance = events.reduce((sum, e) => sum + Math.abs(e.deltaY), 0);\n\n // Compute velocity statistics\n const eventsWithVelocity = events.filter((e) => e.velocity !== undefined);\n const velocities = eventsWithVelocity.map((e) => e.velocity ?? 0);\n const meanScrollVelocity =\n velocities.length > 0 ? velocities.reduce((a, b) => a + b, 0) / velocities.length : 0;\n\n // Compute up/down ratio\n const upCount = events.filter((e) => e.direction === \"up\").length;\n const downCount = events.filter((e) => e.direction === \"down\").length;\n const upDownRatio = downCount > 0 ? upCount / downCount : upCount > 0 ? 1 : 0;\n\n return {\n totalScrollEvents: events.length,\n totalScrollDistance,\n directionChanges,\n meanScrollVelocity,\n upDownRatio,\n };\n}\n","import type { KeystrokeEvent, TimingMetrics } from \"@slopit/core\";\n\n/**\n * Compute timing metrics from keystroke events.\n *\n * @param keystrokes - Array of keystroke events\n * @param trialStartTime - Trial start time (for first keystroke latency)\n * @param totalResponseTime - Total response time in milliseconds\n * @returns Computed timing metrics\n */\nexport function computeTimingMetrics(\n keystrokes: KeystrokeEvent[],\n totalResponseTime: number,\n): TimingMetrics {\n const keydowns = keystrokes.filter((k) => k.event === \"keydown\");\n\n // First keystroke latency\n const firstKeystroke = keydowns[0];\n const firstKeystrokeLatency = firstKeystroke?.time;\n\n // Characters per minute (excluding deletions)\n const printableCount = keydowns.filter((k) => k.key.length === 1).length;\n const deletionCount = keydowns.filter((k) => k.key === \"Backspace\" || k.key === \"Delete\").length;\n const netCharacters = Math.max(0, printableCount - deletionCount);\n\n const minutes = totalResponseTime / 60000;\n const charactersPerMinute = minutes > 0 ? netCharacters / minutes : null;\n\n return {\n ...(firstKeystrokeLatency !== undefined ? { firstKeystrokeLatency } : {}),\n totalResponseTime,\n ...(charactersPerMinute !== null ? { charactersPerMinute } : {}),\n };\n}\n","import type { BehavioralData, BehavioralMetrics, CaptureFlag } from \"@slopit/core\";\nimport { ClipboardCollector } from \"./collectors/clipboard.js\";\nimport { FocusCollector } from \"./collectors/focus.js\";\nimport { InputDurationCollector } from \"./collectors/input-duration.js\";\nimport { KeystrokeCollector } from \"./collectors/keystroke.js\";\nimport { MouseCollector } from \"./collectors/mouse.js\";\nimport { ScrollCollector } from \"./collectors/scroll.js\";\nimport { computeFocusMetrics } from \"./metrics/focus-metrics.js\";\nimport { computeInputDurationMetrics } from \"./metrics/input-duration-metrics.js\";\nimport { computeKeystrokeMetrics } from \"./metrics/keystroke-metrics.js\";\nimport { computeMouseMetrics } from \"./metrics/mouse-metrics.js\";\nimport { computeScrollMetrics } from \"./metrics/scroll-metrics.js\";\nimport { computeTimingMetrics } from \"./metrics/timing-metrics.js\";\nimport type {\n BehavioralCaptureConfig,\n BehavioralCaptureEvents,\n NormalizedConfig,\n} from \"./types.js\";\n\n/**\n * Platform-agnostic behavioral data capture.\n *\n * Captures keystroke dynamics, focus events, and paste events\n * from DOM elements. Works with any experiment framework or\n * custom implementation.\n *\n * @example\n * ```typescript\n * const capture = createBehavioralCapture({\n * keystroke: { enabled: true },\n * focus: { enabled: true },\n * paste: { enabled: true, prevent: false },\n * });\n *\n * const textarea = document.getElementById(\"response\");\n * capture.attach(textarea);\n *\n * // Later, retrieve data\n * const data = capture.getData();\n * const metrics = capture.getMetrics();\n *\n * // Cleanup\n * capture.detach();\n * ```\n */\nexport class BehavioralCapture {\n private config: NormalizedConfig;\n private keystrokeCollector: KeystrokeCollector | null = null;\n private focusCollector: FocusCollector | null = null;\n private clipboardCollector: ClipboardCollector | null = null;\n private mouseCollector: MouseCollector | null = null;\n private scrollCollector: ScrollCollector | null = null;\n private inputDurationCollector: InputDurationCollector | null = null;\n private attachedElement: HTMLElement | null = null;\n private trialStartTime = 0;\n private listeners: Map<\n keyof BehavioralCaptureEvents,\n Set<BehavioralCaptureEvents[keyof BehavioralCaptureEvents]>\n > = new Map();\n\n constructor(config: BehavioralCaptureConfig) {\n this.config = this.normalizeConfig(config);\n }\n\n /**\n * Attach capture to a DOM element.\n *\n * For text input capture, attach to the input or textarea element.\n * For document-level focus tracking, attach to document.\n *\n * @param element - The element to attach to\n * @param startTime - Optional trial start time (defaults to now)\n */\n attach(element: HTMLElement | Document, startTime?: number): void {\n this.trialStartTime = startTime ?? performance.now();\n this.attachedElement = element instanceof Document ? document.body : element;\n\n // Initialize input duration collector first (needs to receive events from others)\n if (this.config.inputDuration.enabled) {\n this.inputDurationCollector = new InputDurationCollector(\n this.config.inputDuration,\n this.trialStartTime,\n (event) => this.emit(\"inputDuration\", event),\n );\n this.inputDurationCollector.attach(element);\n }\n\n if (this.config.keystroke.enabled) {\n this.keystrokeCollector = new KeystrokeCollector(\n this.config.keystroke,\n this.trialStartTime,\n (event) => {\n this.emit(\"keystroke\", event);\n // Notify input duration collector of keystroke\n this.inputDurationCollector?.incrementKeystrokes();\n },\n );\n this.keystrokeCollector.attach(element);\n }\n\n if (this.config.focus.enabled) {\n this.focusCollector = new FocusCollector(this.config.focus, this.trialStartTime, (event) =>\n this.emit(\"focus\", event),\n );\n this.focusCollector.attach(document);\n }\n\n if (this.config.clipboard.enabled) {\n this.clipboardCollector = new ClipboardCollector(\n this.config.clipboard,\n this.trialStartTime,\n () => this.keystrokeCollector?.getRecentCount(2000) ?? 0,\n (event) => {\n this.emit(\"paste\", event);\n // Notify input duration collector of paste\n this.inputDurationCollector?.incrementPastes();\n },\n (event) => this.emit(\"clipboard\", event),\n );\n this.clipboardCollector.attach(element);\n }\n\n if (this.config.mouse.enabled) {\n this.mouseCollector = new MouseCollector(this.config.mouse, this.trialStartTime, (event) =>\n this.emit(\"mouse\", event),\n );\n this.mouseCollector.attach(element);\n }\n\n if (this.config.scroll.enabled) {\n this.scrollCollector = new ScrollCollector(this.config.scroll, this.trialStartTime, (event) =>\n this.emit(\"scroll\", event),\n );\n this.scrollCollector.attach(element);\n }\n }\n\n /**\n * Detach capture and clean up event listeners.\n */\n detach(): void {\n this.keystrokeCollector?.detach();\n this.focusCollector?.detach();\n this.clipboardCollector?.detach();\n this.mouseCollector?.detach();\n this.scrollCollector?.detach();\n this.inputDurationCollector?.detach();\n\n this.keystrokeCollector = null;\n this.focusCollector = null;\n this.clipboardCollector = null;\n this.mouseCollector = null;\n this.scrollCollector = null;\n this.inputDurationCollector = null;\n this.attachedElement = null;\n }\n\n /**\n * Reset all collected data without detaching.\n *\n * @param newStartTime - Optional new start time\n */\n reset(newStartTime?: number): void {\n this.trialStartTime = newStartTime ?? performance.now();\n this.keystrokeCollector?.reset(this.trialStartTime);\n this.focusCollector?.reset(this.trialStartTime);\n this.clipboardCollector?.reset(this.trialStartTime);\n this.mouseCollector?.reset(this.trialStartTime);\n this.scrollCollector?.reset(this.trialStartTime);\n this.inputDurationCollector?.reset(this.trialStartTime);\n }\n\n /**\n * Get all collected behavioral data.\n */\n getData(): BehavioralData {\n return {\n keystrokes: this.keystrokeCollector?.getEvents() ?? [],\n focus: this.focusCollector?.getEvents() ?? [],\n paste: this.clipboardCollector?.getPasteEvents() ?? [],\n mouse: this.mouseCollector?.getEvents() ?? [],\n scroll: this.scrollCollector?.getEvents() ?? [],\n clipboard: this.clipboardCollector?.getCopyEvents() ?? [],\n inputDuration: this.inputDurationCollector?.getEvents() ?? [],\n metrics: this.getMetrics(),\n };\n }\n\n /**\n * Get computed metrics from collected data.\n */\n getMetrics(): BehavioralMetrics {\n const keystrokes = this.keystrokeCollector?.getEvents() ?? [];\n const focusEvents = this.focusCollector?.getEvents() ?? [];\n const mouseEvents = this.mouseCollector?.getEvents() ?? [];\n const mouseIdlePeriods = this.mouseCollector?.getIdlePeriods() ?? [];\n const scrollEvents = this.scrollCollector?.getEvents() ?? [];\n const scrollDirectionChanges = this.scrollCollector?.getDirectionChanges() ?? 0;\n const inputDurationEvents = this.inputDurationCollector?.getEvents() ?? [];\n const currentTime = performance.now();\n const totalResponseTime = currentTime - this.trialStartTime;\n\n const keystrokeMetrics = keystrokes.length > 0 ? computeKeystrokeMetrics(keystrokes) : null;\n const focusMetrics = focusEvents.length > 0 ? computeFocusMetrics(focusEvents) : null;\n const mouseMetrics =\n mouseEvents.length > 0 ? computeMouseMetrics(mouseEvents, mouseIdlePeriods) : null;\n const scrollMetrics =\n scrollEvents.length > 0 ? computeScrollMetrics(scrollEvents, scrollDirectionChanges) : null;\n const inputDurationMetrics =\n inputDurationEvents.length > 0 ? computeInputDurationMetrics(inputDurationEvents) : null;\n\n return {\n ...(keystrokeMetrics !== null ? { keystroke: keystrokeMetrics } : {}),\n ...(focusMetrics !== null ? { focus: focusMetrics } : {}),\n timing: computeTimingMetrics(keystrokes, totalResponseTime),\n ...(mouseMetrics !== null ? { mouse: mouseMetrics } : {}),\n ...(scrollMetrics !== null ? { scroll: scrollMetrics } : {}),\n ...(inputDurationMetrics !== null ? { inputDuration: inputDurationMetrics } : {}),\n };\n }\n\n /**\n * Get flags generated during capture.\n */\n getFlags(): CaptureFlag[] {\n const flags: CaptureFlag[] = [];\n\n // Check for paste events\n const pasteEvents = this.clipboardCollector?.getPasteEvents() ?? [];\n if (pasteEvents.length > 0) {\n flags.push({\n type: \"paste_detected\",\n severity: \"medium\",\n message: `${pasteEvents.length} paste event(s) detected`,\n timestamp: Date.now(),\n details: { count: pasteEvents.length },\n });\n }\n\n // Check for excessive blur events\n const focusEvents = this.focusCollector?.getEvents() ?? [];\n const blurCount = focusEvents.filter((e) => e.event === \"blur\").length;\n if (blurCount > 5) {\n flags.push({\n type: \"excessive_blur\",\n severity: \"low\",\n message: `${blurCount} window blur events detected`,\n timestamp: Date.now(),\n details: { count: blurCount },\n });\n }\n\n // Check for mouse idle anomalies (long periods without mouse activity)\n const mouseIdlePeriods = this.mouseCollector?.getIdlePeriods() ?? [];\n const longIdlePeriods = mouseIdlePeriods.filter((p) => p.duration > 30000); // 30 seconds\n if (longIdlePeriods.length > 0) {\n const totalIdleTime = longIdlePeriods.reduce((sum, p) => sum + p.duration, 0);\n flags.push({\n type: \"mouse_idle_anomaly\",\n severity: \"low\",\n message: `${longIdlePeriods.length} long mouse idle period(s) detected (${Math.round(totalIdleTime / 1000)}s total)`,\n timestamp: Date.now(),\n details: {\n count: longIdlePeriods.length,\n totalIdleMs: totalIdleTime,\n periods: longIdlePeriods,\n },\n });\n }\n\n // Check for sudden text appearance (copy events followed by paste without keystrokes)\n const copyEvents = this.clipboardCollector?.getCopyEvents() ?? [];\n for (const paste of pasteEvents) {\n // Find copy events that happened within 5 seconds before the paste\n const recentCopies = copyEvents.filter(\n (c) => c.time < paste.time && paste.time - c.time < 5000,\n );\n\n // If there was a recent copy and the paste had few preceding keystrokes,\n // this might indicate copy-paste from the same document (not external source)\n if (recentCopies.length > 0 && paste.precedingKeystrokes < 5) {\n flags.push({\n type: \"sudden_text_appearance\",\n severity: \"medium\",\n message:\n \"Text pasted shortly after internal copy with minimal typing, potential pre-composed content\",\n timestamp: Date.now(),\n details: {\n pasteTime: paste.time,\n pasteLength: paste.textLength,\n precedingKeystrokes: paste.precedingKeystrokes,\n recentCopyCount: recentCopies.length,\n },\n });\n }\n }\n\n return flags;\n }\n\n /**\n * Subscribe to capture events.\n */\n on<K extends keyof BehavioralCaptureEvents>(event: K, handler: BehavioralCaptureEvents[K]): void {\n if (!this.listeners.has(event)) {\n this.listeners.set(event, new Set());\n }\n this.listeners.get(event)?.add(handler);\n }\n\n /**\n * Unsubscribe from capture events.\n */\n off<K extends keyof BehavioralCaptureEvents>(\n event: K,\n handler: BehavioralCaptureEvents[K],\n ): void {\n this.listeners.get(event)?.delete(handler);\n }\n\n private emit<K extends keyof BehavioralCaptureEvents>(\n event: K,\n data: Parameters<BehavioralCaptureEvents[K]>[0],\n ): void {\n for (const handler of this.listeners.get(event) ?? []) {\n (handler as (data: unknown) => void)(data);\n }\n }\n\n private normalizeConfig(config: BehavioralCaptureConfig): NormalizedConfig {\n const pasteWarnMessage = config.paste?.warnMessage;\n const clipboardWarnMessage = config.clipboard?.warnMessage;\n\n return {\n keystroke: {\n enabled: config.keystroke?.enabled ?? true,\n captureKeyUp: config.keystroke?.captureKeyUp ?? true,\n includeModifiers: config.keystroke?.includeModifiers ?? true,\n },\n focus: {\n enabled: config.focus?.enabled ?? true,\n useVisibilityAPI: config.focus?.useVisibilityAPI ?? true,\n useBlurFocus: config.focus?.useBlurFocus ?? true,\n },\n paste: {\n enabled: config.paste?.enabled ?? true,\n prevent: config.paste?.prevent ?? false,\n capturePreview: config.paste?.capturePreview ?? true,\n previewLength: config.paste?.previewLength ?? 100,\n ...(pasteWarnMessage !== undefined ? { warnMessage: pasteWarnMessage } : {}),\n },\n inputDuration: {\n enabled: config.inputDuration?.enabled ?? true,\n trackKeystrokes: config.inputDuration?.trackKeystrokes ?? true,\n trackPastes: config.inputDuration?.trackPastes ?? true,\n },\n clipboard: {\n enabled: config.clipboard?.enabled ?? true,\n capturePaste: config.clipboard?.capturePaste ?? true,\n captureCopyCut: config.clipboard?.captureCopyCut ?? true,\n prevent: config.clipboard?.prevent ?? false,\n capturePreview: config.clipboard?.capturePreview ?? true,\n previewLength: config.clipboard?.previewLength ?? 100,\n ...(clipboardWarnMessage !== undefined ? { warnMessage: clipboardWarnMessage } : {}),\n },\n mouse: {\n enabled: config.mouse?.enabled ?? true,\n captureClicks: config.mouse?.captureClicks ?? true,\n captureMovement: config.mouse?.captureMovement ?? true,\n throttleMs: config.mouse?.throttleMs ?? 50,\n idleThresholdMs: config.mouse?.idleThresholdMs ?? 5000,\n },\n scroll: {\n enabled: config.scroll?.enabled ?? true,\n throttleMs: config.scroll?.throttleMs ?? 100,\n captureDirection: config.scroll?.captureDirection ?? true,\n },\n };\n }\n}\n\n/**\n * Factory function to create a BehavioralCapture instance.\n */\nexport function createBehavioralCapture(config: BehavioralCaptureConfig): BehavioralCapture {\n return new BehavioralCapture(config);\n}\n","import { hashText, simpleHash } from \"@slopit/core\";\nimport type { PasteEvent } from \"@slopit/core\";\nimport type { PasteCaptureConfig } from \"../types.js\";\n\n/**\n * Collects paste events from DOM elements.\n */\nexport class PasteCollector {\n private events: PasteEvent[] = [];\n private element: HTMLElement | Document | null = null;\n private startTime: number;\n private boundPaste: (e: ClipboardEvent) => void;\n\n constructor(\n private config: Required<Omit<PasteCaptureConfig, \"warnMessage\">> & { warnMessage?: string },\n startTime: number,\n private getRecentKeystrokes: () => number,\n private onEvent?: (event: PasteEvent) => void,\n ) {\n this.startTime = startTime;\n this.boundPaste = this.handlePaste.bind(this);\n }\n\n /**\n * Attach collector to an element.\n */\n attach(element: HTMLElement | Document): void {\n this.element = element;\n element.addEventListener(\"paste\", this.boundPaste as EventListener);\n }\n\n /**\n * Detach collector from element.\n */\n detach(): void {\n if (this.element) {\n this.element.removeEventListener(\"paste\", this.boundPaste as EventListener);\n this.element = null;\n }\n }\n\n /**\n * Reset collected data.\n */\n reset(newStartTime?: number): void {\n this.events = [];\n if (newStartTime !== undefined) {\n this.startTime = newStartTime;\n }\n }\n\n /**\n * Get all collected events.\n */\n getEvents(): PasteEvent[] {\n return [...this.events];\n }\n\n private handlePaste(e: ClipboardEvent): void {\n const text = e.clipboardData?.getData(\"text/plain\") ?? \"\";\n const time = performance.now() - this.startTime;\n const precedingKeystrokes = this.getRecentKeystrokes();\n\n // Optionally prevent paste\n if (this.config.prevent) {\n e.preventDefault();\n if (this.config.warnMessage) {\n alert(this.config.warnMessage);\n }\n }\n\n const event: PasteEvent = {\n time,\n textLength: text.length,\n precedingKeystrokes,\n blocked: this.config.prevent,\n ...(this.config.capturePreview\n ? { textPreview: text.slice(0, this.config.previewLength) }\n : {}),\n // Hash asynchronously but use sync hash for immediate event\n textHash: simpleHash(text),\n };\n\n this.events.push(event);\n this.onEvent?.(event);\n\n // Update with proper SHA-256 hash asynchronously\n if (text.length > 0) {\n hashText(text).then((hash) => {\n event.textHash = hash;\n });\n }\n }\n}\n","/**\n * Detector for sudden text appearance without keystroke or paste source.\n *\n * @module\n */\n\nimport type { DetectionIndicator, DetectionResult, Detector } from \"./types.js\";\n\n/**\n * Configuration for the text appearance detector.\n */\nexport interface TextAppearanceDetectorConfig {\n /**\n * Minimum character count to flag as suspicious.\n * @default 50\n */\n minTextLength?: number;\n\n /**\n * Time window in milliseconds to check for keystroke activity.\n * @default 2000\n */\n timeWindowMs?: number;\n}\n\n/**\n * Callbacks for checking keystroke and paste activity.\n */\nexport interface TextAppearanceCallbacks {\n /**\n * Returns the number of keystrokes in the recent time window.\n */\n getRecentKeystrokes?: () => number;\n\n /**\n * Returns whether a paste occurred in the recent time window.\n */\n hadRecentPaste?: () => boolean;\n}\n\n/**\n * Default configuration values.\n */\nconst DEFAULT_CONFIG: Required<TextAppearanceDetectorConfig> = {\n minTextLength: 50,\n timeWindowMs: 2000,\n};\n\n/**\n * Detects sudden text appearance without corresponding keystroke or paste events.\n *\n * This detector uses MutationObserver to watch for text changes in input fields,\n * textareas, and contenteditable elements. When text appears faster than possible\n * via normal typing (e.g., 50+ characters with no keystrokes), it flags the event\n * as suspicious.\n *\n * @example\n * ```typescript\n * const detector = new TextAppearanceDetector(\n * { minTextLength: 30, timeWindowMs: 1500 },\n * {\n * getRecentKeystrokes: () => keystrokeCollector.getRecentCount(1500),\n * hadRecentPaste: () => pasteCollector.hadRecentPaste(1500),\n * }\n * );\n *\n * detector.startMonitoring(document.getElementById(\"response\"));\n * // ... user interaction ...\n * const result = detector.detect();\n * detector.stopMonitoring();\n * ```\n */\nexport class TextAppearanceDetector implements Detector {\n readonly name = \"text_appearance\";\n\n private observer: MutationObserver | null = null;\n private indicators: DetectionIndicator[] = [];\n private lastTextLength: Map<Element, number> = new Map();\n private keystrokeCallback: (() => number) | undefined;\n private pasteCallback: (() => boolean) | undefined;\n private config: Required<TextAppearanceDetectorConfig>;\n private startTime: number;\n private monitoredElement: HTMLElement | null = null;\n private inputHandler: ((e: Event) => void) | null = null;\n\n /**\n * Creates a new TextAppearanceDetector.\n *\n * @param config - Configuration options\n * @param callbacks - Callbacks for checking keystroke and paste activity\n */\n constructor(config: TextAppearanceDetectorConfig = {}, callbacks?: TextAppearanceCallbacks) {\n this.config = { ...DEFAULT_CONFIG, ...config };\n this.keystrokeCallback = callbacks?.getRecentKeystrokes;\n this.pasteCallback = callbacks?.hadRecentPaste;\n this.startTime = performance.now();\n }\n\n /**\n * Returns detection results with all recorded indicators.\n *\n * @returns Detection result with indicators of sudden text appearance\n */\n detect(): DetectionResult {\n const detected = this.indicators.length > 0;\n const confidence = detected ? this.calculateConfidence() : 0;\n\n return {\n detected,\n confidence,\n message: detected\n ? `Detected ${this.indicators.length} instance(s) of sudden text appearance`\n : \"No sudden text appearance detected\",\n indicators: [...this.indicators],\n };\n }\n\n /**\n * Starts monitoring an element for sudden text appearance.\n *\n * Watches for text changes in input/textarea elements and content changes\n * in contenteditable elements via MutationObserver.\n *\n * @param element - The element to monitor\n */\n startMonitoring(element: HTMLElement): void {\n if (this.observer) {\n this.stopMonitoring();\n }\n\n this.monitoredElement = element;\n this.startTime = performance.now();\n this.initializeTextLengths(element);\n\n // Set up input event listener for input/textarea elements\n this.inputHandler = this.handleInputEvent.bind(this);\n element.addEventListener(\"input\", this.inputHandler, true);\n\n // Set up MutationObserver for contenteditable and other DOM changes\n this.observer = new MutationObserver(this.handleMutations.bind(this));\n this.observer.observe(element, {\n characterData: true,\n childList: true,\n subtree: true,\n characterDataOldValue: true,\n });\n }\n\n /**\n * Stops monitoring and cleans up resources.\n */\n stopMonitoring(): void {\n if (this.observer) {\n this.observer.disconnect();\n this.observer = null;\n }\n\n if (this.monitoredElement && this.inputHandler) {\n this.monitoredElement.removeEventListener(\"input\", this.inputHandler, true);\n this.inputHandler = null;\n }\n\n this.monitoredElement = null;\n this.lastTextLength.clear();\n }\n\n /**\n * Resets the detector state.\n *\n * @param newStartTime - Optional new start time for timing calculations\n */\n reset(newStartTime?: number): void {\n this.indicators = [];\n this.lastTextLength.clear();\n if (newStartTime !== undefined) {\n this.startTime = newStartTime;\n }\n }\n\n /**\n * Returns the current list of indicators.\n *\n * @returns Copy of the indicators array\n */\n getIndicators(): DetectionIndicator[] {\n return [...this.indicators];\n }\n\n private initializeTextLengths(element: HTMLElement): void {\n // Initialize lengths for input/textarea elements\n const inputs = element.querySelectorAll(\"input, textarea\");\n for (const input of inputs) {\n if (input instanceof HTMLInputElement || input instanceof HTMLTextAreaElement) {\n this.lastTextLength.set(input, input.value.length);\n }\n }\n\n // Initialize for contenteditable elements\n const editables = element.querySelectorAll(\"[contenteditable]\");\n for (const editable of editables) {\n this.lastTextLength.set(editable, editable.textContent?.length ?? 0);\n }\n\n // Check if the element itself is editable\n if (element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement) {\n this.lastTextLength.set(element, element.value.length);\n } else if (element.isContentEditable) {\n this.lastTextLength.set(element, element.textContent?.length ?? 0);\n }\n }\n\n private handleInputEvent(e: Event): void {\n const target = e.target;\n if (!target) {\n return;\n }\n\n if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) {\n this.checkTextChange(target, target.value.length);\n }\n }\n\n private handleMutations(mutations: MutationRecord[]): void {\n for (const mutation of mutations) {\n if (mutation.type === \"characterData\" && mutation.target.parentElement) {\n const parent = mutation.target.parentElement;\n if (parent.isContentEditable) {\n const newLength = parent.textContent?.length ?? 0;\n this.checkTextChange(parent, newLength);\n }\n } else if (mutation.type === \"childList\") {\n const target = mutation.target;\n if (target instanceof HTMLElement && target.isContentEditable) {\n const newLength = target.textContent?.length ?? 0;\n this.checkTextChange(target, newLength);\n }\n }\n }\n }\n\n private checkTextChange(element: Element, newLength: number): void {\n const previousLength = this.lastTextLength.get(element) ?? 0;\n const lengthChange = newLength - previousLength;\n\n this.lastTextLength.set(element, newLength);\n\n // Only check significant increases\n if (lengthChange < this.config.minTextLength) {\n return;\n }\n\n // Check for recent keystrokes\n const recentKeystrokes = this.keystrokeCallback?.() ?? 0;\n\n // Check for recent paste\n const hadPaste = this.pasteCallback?.() ?? false;\n\n // Flag if text appeared without sufficient keystroke or paste activity\n if (recentKeystrokes < lengthChange && !hadPaste) {\n const time = performance.now() - this.startTime;\n const selector = this.getSelector(element);\n\n this.indicators.push({\n type: \"sudden_text_appearance\",\n selector,\n details: {\n characterCount: lengthChange,\n previousLength,\n newLength,\n recentKeystrokes,\n hadPaste,\n time,\n },\n });\n }\n }\n\n private getSelector(element: Element): string {\n if (element.id) {\n return `#${element.id}`;\n }\n\n if (element.className && typeof element.className === \"string\") {\n const classes = element.className.trim().split(/\\s+/).join(\".\");\n if (classes) {\n return `${element.tagName.toLowerCase()}.${classes}`;\n }\n }\n\n return element.tagName.toLowerCase();\n }\n\n private calculateConfidence(): number {\n if (this.indicators.length === 0) {\n return 0;\n }\n\n // Higher confidence with more indicators and larger text amounts\n const totalCharacters = this.indicators.reduce((sum, ind) => {\n const count = (ind.details?.[\"characterCount\"] as number) ?? 0;\n return sum + count;\n }, 0);\n\n // Base confidence from having indicators\n let confidence = 0.5;\n\n // Increase confidence based on total suspicious characters\n if (totalCharacters > 100) {\n confidence += 0.2;\n }\n if (totalCharacters > 500) {\n confidence += 0.2;\n }\n\n // Increase confidence based on number of incidents\n confidence += Math.min(0.1 * this.indicators.length, 0.1);\n\n return Math.min(confidence, 1);\n }\n}\n","/**\n * Detector for AI assistant browser extension signatures.\n *\n * Scans the DOM and global window object for known patterns associated with\n * browser extensions like Grammarly, Copilot, Quillbot, and other AI assistants.\n *\n * @module\n */\n\nimport type { DetectionIndicator, DetectionResult, Detector } from \"./types.js\";\n\n/**\n * Known DOM selectors for AI assistant browser extensions.\n */\nconst KNOWN_DOM_SELECTORS = [\n \"[data-grammarly-shadow-root]\",\n '[class*=\"grammarly\"]',\n '[class*=\"ai-assistant\"]',\n '[class*=\"copilot\"]',\n '[class*=\"chatgpt\"]',\n \"#quillbot-extension-portal\",\n] as const;\n\n/**\n * Known global window variables injected by AI assistant extensions.\n */\nconst KNOWN_GLOBALS = [\"__GRAMMARLY__\", \"__COPILOT__\", \"__QUILLBOT__\"] as const;\n\n/**\n * Monitor configuration for MutationObserver settings.\n */\nexport interface MonitorConfig {\n /**\n * Whether to observe attribute changes.\n * @default true\n */\n attributes: boolean;\n\n /**\n * Whether to observe child node additions/removals.\n * @default true\n */\n childList: boolean;\n\n /**\n * Whether to observe the entire subtree.\n * @default true\n */\n subtree: boolean;\n}\n\n/**\n * Configuration for the ExtensionDetector.\n */\nexport interface ExtensionDetectorConfig {\n /**\n * Additional DOM selectors to scan for extension signatures.\n */\n customSelectors?: string[];\n\n /**\n * Additional global window properties to check.\n */\n customGlobals?: string[];\n\n /**\n * Configuration for continuous monitoring via MutationObserver.\n */\n monitor?: Partial<MonitorConfig>;\n}\n\n/**\n * Normalized (fully resolved) extension detector configuration.\n */\ninterface NormalizedExtensionDetectorConfig {\n customSelectors: string[];\n customGlobals: string[];\n monitor: MonitorConfig;\n}\n\n/**\n * Detects AI assistant browser extension signatures.\n *\n * Scans for:\n * - Known DOM elements injected by extensions (e.g., Grammarly shadow roots)\n * - Global variables set by extensions\n * - Custom patterns provided via configuration\n *\n * @example\n * ```typescript\n * const detector = new ExtensionDetector();\n * const result = detector.detect();\n *\n * if (result.detected) {\n * console.log(\"Extensions found:\", result.indicators);\n * }\n * ```\n *\n * @example\n * ```typescript\n * // With continuous monitoring\n * const detector = new ExtensionDetector({\n * customSelectors: ['[data-my-extension]'],\n * });\n *\n * detector.startMonitoring();\n * // ... later\n * detector.stopMonitoring();\n * ```\n */\nexport class ExtensionDetector implements Detector {\n readonly name = \"extension-detector\";\n\n private readonly config: NormalizedExtensionDetectorConfig;\n private readonly allSelectors: string[];\n private readonly allGlobals: string[];\n private observer: MutationObserver | null = null;\n private monitoredIndicators: DetectionIndicator[] = [];\n\n constructor(config: ExtensionDetectorConfig = {}) {\n this.config = {\n customSelectors: config.customSelectors ?? [],\n customGlobals: config.customGlobals ?? [],\n monitor: {\n attributes: config.monitor?.attributes ?? true,\n childList: config.monitor?.childList ?? true,\n subtree: config.monitor?.subtree ?? true,\n },\n };\n\n this.allSelectors = [...KNOWN_DOM_SELECTORS, ...this.config.customSelectors];\n this.allGlobals = [...KNOWN_GLOBALS, ...this.config.customGlobals];\n }\n\n /**\n * Performs a one-shot detection scan for extension signatures.\n *\n * @returns Detection result with found indicators\n */\n detect(): DetectionResult {\n const startTime = performance.now();\n const indicators: DetectionIndicator[] = [];\n\n // Scan DOM for known selectors\n for (const selector of this.allSelectors) {\n const elements = this.queryElements(selector);\n if (elements.length > 0) {\n indicators.push({\n type: \"dom_element\",\n selector,\n details: {\n matchCount: elements.length,\n isKnown: (KNOWN_DOM_SELECTORS as readonly string[]).includes(selector),\n },\n });\n }\n }\n\n // Check for global variables\n for (const globalName of this.allGlobals) {\n if (this.hasGlobal(globalName)) {\n indicators.push({\n type: \"global_variable\",\n selector: globalName,\n details: {\n isKnown: (KNOWN_GLOBALS as readonly string[]).includes(globalName),\n },\n });\n }\n }\n\n const _scanDurationMs = performance.now() - startTime;\n\n return {\n detected: indicators.length > 0,\n confidence: this.calculateConfidence(indicators),\n message: this.generateMessage(indicators),\n indicators,\n };\n }\n\n /**\n * Starts continuous monitoring for dynamically injected extension elements.\n *\n * Uses MutationObserver to watch for DOM changes that match extension patterns.\n */\n startMonitoring(): void {\n if (this.observer !== null) {\n return;\n }\n\n this.observer = new MutationObserver((mutations) => {\n this.handleMutations(mutations);\n });\n\n this.observer.observe(document.documentElement, {\n attributes: this.config.monitor.attributes,\n childList: this.config.monitor.childList,\n subtree: this.config.monitor.subtree,\n attributeFilter: [\"class\", \"data-grammarly-shadow-root\"],\n });\n }\n\n /**\n * Stops continuous monitoring and disconnects the MutationObserver.\n */\n stopMonitoring(): void {\n if (this.observer !== null) {\n this.observer.disconnect();\n this.observer = null;\n }\n }\n\n /**\n * Gets all indicators detected during monitoring.\n *\n * @returns Array of detection indicators found during monitoring\n */\n getMonitoredIndicators(): DetectionIndicator[] {\n return [...this.monitoredIndicators];\n }\n\n /**\n * Resets all collected monitoring data.\n */\n reset(): void {\n this.monitoredIndicators = [];\n }\n\n /**\n * Queries the DOM for elements matching a selector.\n */\n private queryElements(selector: string): Element[] {\n try {\n return Array.from(document.querySelectorAll(selector));\n } catch {\n // Invalid selector, return empty array\n return [];\n }\n }\n\n /**\n * Checks if a global variable exists on the window object.\n */\n private hasGlobal(name: string): boolean {\n try {\n return name in window;\n } catch {\n return false;\n }\n }\n\n /**\n * Handles mutation events from the MutationObserver.\n */\n private handleMutations(mutations: MutationRecord[]): void {\n for (const mutation of mutations) {\n if (mutation.type === \"childList\") {\n this.handleChildListMutation(mutation);\n } else if (mutation.type === \"attributes\") {\n this.handleAttributeMutation(mutation);\n }\n }\n }\n\n /**\n * Handles child list mutations, checking new nodes for extension patterns.\n */\n private handleChildListMutation(mutation: MutationRecord): void {\n for (const node of mutation.addedNodes) {\n if (node.nodeType !== Node.ELEMENT_NODE) {\n continue;\n }\n\n const element = node as Element;\n\n // Check if the added element itself matches any selector\n for (const selector of this.allSelectors) {\n if (this.elementMatchesSelector(element, selector)) {\n this.addMonitoredIndicator(\"dom_element\", selector, {\n trigger: \"added_node\",\n tagName: element.tagName.toLowerCase(),\n });\n }\n }\n\n // Check descendants of the added element\n for (const selector of this.allSelectors) {\n const matches = this.querySelectorSafe(element, selector);\n if (matches.length > 0) {\n this.addMonitoredIndicator(\"dom_element\", selector, {\n trigger: \"added_descendant\",\n matchCount: matches.length,\n });\n }\n }\n }\n }\n\n /**\n * Handles attribute mutations, checking if changes match extension patterns.\n */\n private handleAttributeMutation(mutation: MutationRecord): void {\n const element = mutation.target as Element;\n\n for (const selector of this.allSelectors) {\n if (this.elementMatchesSelector(element, selector)) {\n this.addMonitoredIndicator(\"dom_element\", selector, {\n trigger: \"attribute_change\",\n attribute: mutation.attributeName,\n tagName: element.tagName.toLowerCase(),\n });\n }\n }\n }\n\n /**\n * Safely checks if an element matches a selector.\n */\n private elementMatchesSelector(element: Element, selector: string): boolean {\n try {\n return element.matches(selector);\n } catch {\n return false;\n }\n }\n\n /**\n * Safely queries for elements within a parent.\n */\n private querySelectorSafe(parent: Element, selector: string): Element[] {\n try {\n return Array.from(parent.querySelectorAll(selector));\n } catch {\n return [];\n }\n }\n\n /**\n * Adds an indicator to the monitored indicators list.\n */\n private addMonitoredIndicator(\n type: string,\n selector: string,\n details: Record<string, unknown>,\n ): void {\n const indicator: DetectionIndicator = {\n type,\n selector,\n details: {\n ...details,\n timestamp: performance.now(),\n isKnown:\n type === \"dom_element\"\n ? (KNOWN_DOM_SELECTORS as readonly string[]).includes(selector)\n : (KNOWN_GLOBALS as readonly string[]).includes(selector),\n },\n };\n this.monitoredIndicators.push(indicator);\n }\n\n /**\n * Calculates a confidence score based on indicators.\n */\n private calculateConfidence(indicators: DetectionIndicator[]): number {\n if (indicators.length === 0) {\n return 0;\n }\n\n // Higher confidence for multiple indicators or known patterns\n const knownCount = indicators.filter((i) => i.details?.[\"isKnown\"] === true).length;\n const unknownCount = indicators.length - knownCount;\n\n // Known patterns contribute more to confidence\n const score = Math.min(1, knownCount * 0.3 + unknownCount * 0.15);\n return Math.round(score * 100) / 100;\n }\n\n /**\n * Generates a human-readable message from indicators.\n */\n private generateMessage(indicators: DetectionIndicator[]): string {\n if (indicators.length === 0) {\n return \"No AI assistant browser extensions detected\";\n }\n\n const domCount = indicators.filter((i) => i.type === \"dom_element\").length;\n const globalCount = indicators.filter((i) => i.type === \"global_variable\").length;\n\n const parts: string[] = [];\n if (domCount > 0) {\n parts.push(`${domCount} DOM element${domCount > 1 ? \"s\" : \"\"}`);\n }\n if (globalCount > 0) {\n parts.push(`${globalCount} global variable${globalCount > 1 ? \"s\" : \"\"}`);\n }\n\n return `AI assistant extension signatures detected: ${parts.join(\", \")}`;\n }\n}\n\n/**\n * Creates a new ExtensionDetector instance.\n *\n * @param config - Configuration options\n * @returns New ExtensionDetector instance\n *\n * @example\n * ```typescript\n * const detector = createExtensionDetector({\n * customSelectors: ['[data-custom-ai]'],\n * });\n * ```\n */\nexport function createExtensionDetector(config?: ExtensionDetectorConfig): ExtensionDetector {\n return new ExtensionDetector(config);\n}\n","/**\n * Manager for evaluating behavioral triggers and applying interventions.\n *\n * @module\n */\n\nimport type {\n BehavioralState,\n InterventionManagerConfig,\n InterventionResult,\n InterventionType,\n TriggerConfig,\n} from \"./types.js\";\n\n/**\n * Intervention levels in escalation order.\n */\nconst INTERVENTION_LEVELS: InterventionType[] = [\"warning\", \"friction\", \"challenge\", \"block\"];\n\n/**\n * Manages behavioral interventions based on configurable triggers.\n *\n * The InterventionManager evaluates behavioral state against configured triggers\n * and fires interventions when thresholds are exceeded. It supports callback\n * registration for each intervention type and optional escalation on repeated\n * triggers.\n *\n * @example\n * ```typescript\n * const manager = new InterventionManager({\n * triggers: [\n * {\n * type: \"paste\",\n * threshold: { paste: { minLength: 100, maxPrecedingKeystrokes: 5 } },\n * intervention: \"warning\",\n * },\n * ],\n * escalate: true,\n * });\n *\n * manager.onIntervention(\"warning\", (result) => {\n * console.log(\"Warning triggered:\", result.reason);\n * });\n *\n * const result = manager.evaluate({\n * pasteEvents: [{ textLength: 500, precedingKeystrokes: 2 }],\n * });\n *\n * if (result) {\n * console.log(\"Intervention fired:\", result.type);\n * }\n * ```\n */\nexport class InterventionManager {\n private readonly triggers: TriggerConfig[];\n private readonly escalate: boolean;\n private interventionHistory: InterventionResult[] = [];\n private callbacks: Map<InterventionType, ((result: InterventionResult) => void)[]> = new Map();\n private triggerCounts: Map<TriggerConfig, number> = new Map();\n\n /**\n * Creates a new InterventionManager.\n *\n * @param config - Configuration with triggers and escalation settings\n */\n constructor(config: InterventionManagerConfig) {\n this.triggers = config.triggers;\n this.escalate = config.escalate ?? false;\n\n // Initialize callback arrays for each intervention type\n for (const type of INTERVENTION_LEVELS) {\n this.callbacks.set(type, []);\n }\n\n // Initialize trigger counts for escalation\n for (const trigger of this.triggers) {\n this.triggerCounts.set(trigger, 0);\n }\n }\n\n /**\n * Evaluates triggers against the current behavioral state.\n *\n * Checks each configured trigger against the provided state and returns\n * an InterventionResult if any trigger fires. Only the first matching\n * trigger is returned.\n *\n * @param state - Current behavioral state to evaluate\n * @returns InterventionResult if a trigger fires, null otherwise\n *\n * @example\n * ```typescript\n * const result = manager.evaluate({\n * pasteEvents: [{ textLength: 500, precedingKeystrokes: 2 }],\n * blurCount: 5,\n * totalBlurDuration: 15000,\n * });\n * ```\n */\n evaluate(state: BehavioralState): InterventionResult | null {\n for (const trigger of this.triggers) {\n const result = this.evaluateTrigger(trigger, state);\n if (result !== null) {\n // Update trigger count for escalation\n const currentCount = this.triggerCounts.get(trigger) ?? 0;\n this.triggerCounts.set(trigger, currentCount + 1);\n\n // Apply escalation if enabled\n const finalResult = this.escalate ? this.applyEscalation(result, trigger) : result;\n\n this.interventionHistory.push(finalResult);\n this.fireCallbacks(finalResult);\n return finalResult;\n }\n }\n return null;\n }\n\n /**\n * Registers a callback for a specific intervention type.\n *\n * Callbacks are invoked whenever an intervention of the specified type\n * is triggered during evaluation.\n *\n * @param type - The intervention type to listen for\n * @param callback - Function to call when the intervention fires\n *\n * @example\n * ```typescript\n * manager.onIntervention(\"warning\", (result) => {\n * alert(result.reason);\n * });\n *\n * manager.onIntervention(\"block\", (result) => {\n * disableSubmitButton();\n * });\n * ```\n */\n onIntervention(type: InterventionType, callback: (result: InterventionResult) => void): void {\n const callbacks = this.callbacks.get(type);\n if (callbacks !== undefined) {\n callbacks.push(callback);\n }\n }\n\n /**\n * Returns the history of all triggered interventions.\n *\n * @returns Copy of the intervention history array\n *\n * @example\n * ```typescript\n * const history = manager.getHistory();\n * console.log(`Total interventions: ${history.length}`);\n * ```\n */\n getHistory(): InterventionResult[] {\n return [...this.interventionHistory];\n }\n\n /**\n * Resets the intervention history and trigger counts.\n *\n * Call this method to clear all recorded interventions and reset\n * escalation counters.\n *\n * @example\n * ```typescript\n * manager.reset();\n * // History is now empty and escalation counters are reset\n * ```\n */\n reset(): void {\n this.interventionHistory = [];\n for (const trigger of this.triggers) {\n this.triggerCounts.set(trigger, 0);\n }\n }\n\n /**\n * Evaluates a single trigger against the behavioral state.\n */\n private evaluateTrigger(\n trigger: TriggerConfig,\n state: BehavioralState,\n ): InterventionResult | null {\n switch (trigger.type) {\n case \"paste\":\n return this.evaluatePasteTrigger(trigger, state);\n case \"blur\":\n return this.evaluateBlurTrigger(trigger, state);\n case \"idle\":\n return this.evaluateIdleTrigger(trigger, state);\n case \"timing\":\n return this.evaluateTimingTrigger(trigger, state);\n case \"composite\":\n return this.evaluateCompositeTrigger(trigger, state);\n default:\n return null;\n }\n }\n\n /**\n * Evaluates a paste-based trigger.\n */\n private evaluatePasteTrigger(\n trigger: TriggerConfig,\n state: BehavioralState,\n ): InterventionResult | null {\n const threshold = trigger.threshold.paste;\n if (threshold === undefined || state.pasteEvents === undefined) {\n return null;\n }\n\n for (const event of state.pasteEvents) {\n if (\n event.textLength >= threshold.minLength &&\n event.precedingKeystrokes <= threshold.maxPrecedingKeystrokes\n ) {\n return this.createResult(\n trigger,\n `Large paste detected (${event.textLength} characters) with minimal preceding keystrokes (${event.precedingKeystrokes})`,\n );\n }\n }\n\n return null;\n }\n\n /**\n * Evaluates a blur-based trigger.\n */\n private evaluateBlurTrigger(\n trigger: TriggerConfig,\n state: BehavioralState,\n ): InterventionResult | null {\n const threshold = trigger.threshold.blur;\n if (threshold === undefined) {\n return null;\n }\n\n const blurCount = state.blurCount ?? 0;\n const totalBlurDuration = state.totalBlurDuration ?? 0;\n\n if (blurCount >= threshold.countThreshold || totalBlurDuration >= threshold.durationThreshold) {\n const reasons: string[] = [];\n if (blurCount >= threshold.countThreshold) {\n reasons.push(`blur count (${blurCount}) exceeded threshold (${threshold.countThreshold})`);\n }\n if (totalBlurDuration >= threshold.durationThreshold) {\n reasons.push(\n `blur duration (${totalBlurDuration}ms) exceeded threshold (${threshold.durationThreshold}ms)`,\n );\n }\n return this.createResult(trigger, `Focus loss detected: ${reasons.join(\"; \")}`);\n }\n\n return null;\n }\n\n /**\n * Evaluates an idle-based trigger.\n */\n private evaluateIdleTrigger(\n trigger: TriggerConfig,\n state: BehavioralState,\n ): InterventionResult | null {\n const threshold = trigger.threshold.idle;\n if (threshold === undefined || state.idleDuration === undefined) {\n return null;\n }\n\n if (state.idleDuration >= threshold.durationMs) {\n return this.createResult(\n trigger,\n `Idle period detected (${state.idleDuration}ms) exceeded threshold (${threshold.durationMs}ms)`,\n );\n }\n\n return null;\n }\n\n /**\n * Evaluates a timing-based trigger.\n */\n private evaluateTimingTrigger(\n trigger: TriggerConfig,\n state: BehavioralState,\n ): InterventionResult | null {\n const threshold = trigger.threshold.timing;\n if (threshold === undefined || state.charactersPerSecond === undefined) {\n return null;\n }\n\n if (state.charactersPerSecond > threshold.maxCharactersPerSecond) {\n return this.createResult(\n trigger,\n `Typing speed (${state.charactersPerSecond.toFixed(1)} chars/sec) exceeded threshold (${threshold.maxCharactersPerSecond} chars/sec)`,\n );\n }\n\n return null;\n }\n\n /**\n * Evaluates a composite trigger (combination of multiple factors).\n */\n private evaluateCompositeTrigger(\n trigger: TriggerConfig,\n state: BehavioralState,\n ): InterventionResult | null {\n const triggeredConditions: string[] = [];\n\n // Check paste condition\n if (trigger.threshold.paste !== undefined && state.pasteEvents !== undefined) {\n const threshold = trigger.threshold.paste;\n for (const event of state.pasteEvents) {\n if (\n event.textLength >= threshold.minLength &&\n event.precedingKeystrokes <= threshold.maxPrecedingKeystrokes\n ) {\n triggeredConditions.push(\"suspicious paste\");\n break;\n }\n }\n }\n\n // Check blur condition\n if (trigger.threshold.blur !== undefined) {\n const threshold = trigger.threshold.blur;\n const blurCount = state.blurCount ?? 0;\n const totalBlurDuration = state.totalBlurDuration ?? 0;\n if (\n blurCount >= threshold.countThreshold ||\n totalBlurDuration >= threshold.durationThreshold\n ) {\n triggeredConditions.push(\"excessive focus loss\");\n }\n }\n\n // Check idle condition\n if (trigger.threshold.idle !== undefined && state.idleDuration !== undefined) {\n if (state.idleDuration >= trigger.threshold.idle.durationMs) {\n triggeredConditions.push(\"extended idle period\");\n }\n }\n\n // Check timing condition\n if (trigger.threshold.timing !== undefined && state.charactersPerSecond !== undefined) {\n if (state.charactersPerSecond > trigger.threshold.timing.maxCharactersPerSecond) {\n triggeredConditions.push(\"abnormal typing speed\");\n }\n }\n\n // Composite trigger fires if multiple conditions are met\n if (triggeredConditions.length >= 2) {\n return this.createResult(\n trigger,\n `Multiple behavioral anomalies detected: ${triggeredConditions.join(\", \")}`,\n );\n }\n\n return null;\n }\n\n /**\n * Creates an InterventionResult from a trigger.\n */\n private createResult(trigger: TriggerConfig, reason: string): InterventionResult {\n return {\n type: trigger.intervention,\n triggered: true,\n reason,\n triggerConfig: trigger,\n timestamp: performance.now(),\n };\n }\n\n /**\n * Applies escalation to an intervention result based on trigger count.\n */\n private applyEscalation(result: InterventionResult, trigger: TriggerConfig): InterventionResult {\n const count = this.triggerCounts.get(trigger) ?? 0;\n const currentIndex = INTERVENTION_LEVELS.indexOf(result.type);\n\n if (currentIndex === -1) {\n return result;\n }\n\n // Escalate based on how many times this trigger has fired\n const escalationSteps = Math.floor(count / 2); // Escalate every 2 triggers\n const newIndex = Math.min(currentIndex + escalationSteps, INTERVENTION_LEVELS.length - 1);\n\n if (newIndex === currentIndex) {\n return result;\n }\n\n const escalatedType = INTERVENTION_LEVELS[newIndex];\n if (escalatedType === undefined) {\n return result;\n }\n\n return {\n ...result,\n type: escalatedType,\n reason: `${result.reason} (escalated from ${result.type} due to repeated triggers)`,\n };\n }\n\n /**\n * Fires callbacks for an intervention result.\n */\n private fireCallbacks(result: InterventionResult): void {\n const callbacks = this.callbacks.get(result.type);\n if (callbacks !== undefined) {\n for (const callback of callbacks) {\n callback(result);\n }\n }\n }\n}\n\n/**\n * Creates a new InterventionManager instance.\n *\n * @param config - Configuration with triggers and escalation settings\n * @returns New InterventionManager instance\n *\n * @example\n * ```typescript\n * const manager = createInterventionManager({\n * triggers: [\n * {\n * type: \"paste\",\n * threshold: { paste: { minLength: 100, maxPrecedingKeystrokes: 5 } },\n * intervention: \"warning\",\n * },\n * ],\n * });\n * ```\n */\nexport function createInterventionManager(config: InterventionManagerConfig): InterventionManager {\n return new InterventionManager(config);\n}\n","/**\n * Challenge system for verifying human presence during behavioral capture.\n *\n * Challenges are interactive tasks that collect behavioral data while\n * verifying participant engagement. Researchers can implement custom\n * challenge renderers or use the provided implementations.\n *\n * @module\n */\n\n/**\n * Available challenge types.\n *\n * - `audio_transcription`: User transcribes audio content\n * - `image_description`: User describes visual content\n * - `typing_test`: User types displayed text (captures natural rhythm)\n * - `memory_recall`: User answers questions about previously shown content\n * - `consistency_check`: User re-answers a previous question for comparison\n */\nexport type ChallengeType =\n | \"audio_transcription\"\n | \"image_description\"\n | \"typing_test\"\n | \"memory_recall\"\n | \"consistency_check\";\n\n/**\n * Configuration for a challenge.\n */\nexport interface ChallengeConfig {\n /**\n * Type of challenge to present.\n */\n type: ChallengeType;\n\n /**\n * Prompt or instructions to display to the participant.\n */\n prompt: string;\n\n /**\n * Keywords expected in a valid response.\n * Used for automatic verification of memory recall and description challenges.\n */\n expectedKeywords?: string[];\n\n /**\n * Time limit for completing the challenge in milliseconds.\n * When exceeded, the challenge should auto-submit with current response.\n */\n timeLimit?: number;\n\n /**\n * Type-specific configuration data.\n *\n * For `typing_test`: `{ text: string }` - the text to type\n * For `audio_transcription`: `{ audioUrl: string }` - URL of audio file\n * For `image_description`: `{ imageUrl: string }` - URL of image\n * For `memory_recall`: `{ question: string, context?: string }`\n * For `consistency_check`: `{ originalQuestion: string, originalAnswer: string }`\n */\n data?: Record<string, unknown>;\n}\n\n/**\n * Result from a completed challenge.\n */\nexport interface ChallengeResult {\n /**\n * Whether the challenge was successfully completed.\n * For typing tests, this indicates accuracy threshold was met.\n * For keyword-based challenges, this indicates required keywords were present.\n */\n passed: boolean;\n\n /**\n * The participant's response text.\n */\n response: string;\n\n /**\n * Time taken to complete the challenge in milliseconds.\n */\n completionTime: number;\n\n /**\n * Behavioral data captured during the challenge.\n * Contains keystroke events, timing patterns, and other captured signals.\n */\n behavioralData?: unknown;\n}\n\n/**\n * Interface for challenge renderers.\n *\n * Researchers implement this interface to customize how challenges\n * are presented to participants. The library provides default\n * implementations for common challenge types.\n *\n * @example\n * ```typescript\n * class CustomChallenge implements ChallengeRenderer {\n * private cleanup: (() => void) | null = null;\n *\n * async render(\n * config: ChallengeConfig,\n * container: HTMLElement\n * ): Promise<ChallengeResult> {\n * // Create and append UI elements to container\n * // Set up event listeners and capture\n * // Return result when participant submits\n * }\n *\n * cleanup(): void {\n * // Remove elements and event listeners\n * }\n * }\n * ```\n */\nexport interface ChallengeRenderer {\n /**\n * Render the challenge UI and wait for completion.\n *\n * @param config - Challenge configuration\n * @param container - DOM element to render the challenge into\n * @returns Promise that resolves with the challenge result when submitted\n */\n render(config: ChallengeConfig, container: HTMLElement): Promise<ChallengeResult>;\n\n /**\n * Clean up the challenge UI and release resources.\n * Called after the challenge completes or is cancelled.\n */\n cleanup(): void;\n}\n\n/**\n * Typing test challenge that captures natural typing rhythm.\n *\n * Displays text for the participant to type, capturing keystroke\n * timing patterns that can be compared against their regular typing\n * behavior. This helps verify the same person is responding throughout\n * the study.\n *\n * @example\n * ```typescript\n * const challenge = new TypingTestChallenge();\n * const result = await challenge.render(\n * {\n * type: \"typing_test\",\n * prompt: \"Please type the following text exactly as shown:\",\n * data: { text: \"The quick brown fox jumps over the lazy dog.\" },\n * timeLimit: 60000,\n * },\n * document.getElementById(\"challenge-container\")!\n * );\n * console.log(result.passed, result.behavioralData);\n * challenge.cleanup();\n * ```\n */\nexport class TypingTestChallenge implements ChallengeRenderer {\n private container: HTMLElement | null = null;\n private startTime = 0;\n private keystrokes: Array<{ key: string; time: number; event: \"keydown\" | \"keyup\" }> = [];\n private boundHandlers: {\n keydown: ((e: KeyboardEvent) => void) | null;\n keyup: ((e: KeyboardEvent) => void) | null;\n } = { keydown: null, keyup: null };\n\n /**\n * Render the typing test challenge.\n *\n * @param config - Challenge configuration with `data.text` containing the text to type\n * @param container - Container element for the challenge UI\n * @returns Promise resolving to challenge result with typing accuracy and keystroke data\n */\n async render(config: ChallengeConfig, container: HTMLElement): Promise<ChallengeResult> {\n this.container = container;\n this.keystrokes = [];\n\n const targetText = (config.data?.[\"text\"] as string | undefined) ?? \"\";\n\n return new Promise((resolve) => {\n // Create challenge UI\n const wrapper = document.createElement(\"div\");\n wrapper.className = \"slopit-typing-challenge\";\n\n const promptEl = document.createElement(\"p\");\n promptEl.className = \"slopit-challenge-prompt\";\n promptEl.textContent = config.prompt;\n wrapper.appendChild(promptEl);\n\n const targetEl = document.createElement(\"div\");\n targetEl.className = \"slopit-typing-target\";\n targetEl.textContent = targetText;\n wrapper.appendChild(targetEl);\n\n const inputEl = document.createElement(\"textarea\");\n inputEl.className = \"slopit-typing-input\";\n inputEl.placeholder = \"Type the text above...\";\n inputEl.rows = 3;\n wrapper.appendChild(inputEl);\n\n const submitBtn = document.createElement(\"button\");\n submitBtn.className = \"slopit-challenge-submit\";\n submitBtn.textContent = \"Submit\";\n submitBtn.type = \"button\";\n wrapper.appendChild(submitBtn);\n\n container.appendChild(wrapper);\n\n // Start timing\n this.startTime = performance.now();\n\n // Set up keystroke capture\n this.boundHandlers.keydown = (e: KeyboardEvent) => {\n this.keystrokes.push({\n key: e.key,\n time: performance.now() - this.startTime,\n event: \"keydown\",\n });\n };\n\n this.boundHandlers.keyup = (e: KeyboardEvent) => {\n this.keystrokes.push({\n key: e.key,\n time: performance.now() - this.startTime,\n event: \"keyup\",\n });\n };\n\n inputEl.addEventListener(\"keydown\", this.boundHandlers.keydown);\n inputEl.addEventListener(\"keyup\", this.boundHandlers.keyup);\n\n // Handle submission\n const submit = (): void => {\n const completionTime = performance.now() - this.startTime;\n const response = inputEl.value;\n\n // Calculate accuracy using Levenshtein distance\n const accuracy = this.calculateAccuracy(targetText, response);\n const passed = accuracy >= 0.9; // 90% accuracy threshold\n\n resolve({\n passed,\n response,\n completionTime,\n behavioralData: {\n keystrokes: [...this.keystrokes],\n targetText,\n accuracy,\n },\n });\n };\n\n submitBtn.addEventListener(\"click\", submit);\n\n // Handle time limit\n if (config.timeLimit !== undefined) {\n setTimeout(() => {\n submit();\n }, config.timeLimit);\n }\n\n // Focus the input\n inputEl.focus();\n });\n }\n\n /**\n * Clean up challenge UI and event listeners.\n */\n cleanup(): void {\n if (this.container) {\n const wrapper = this.container.querySelector(\".slopit-typing-challenge\");\n if (wrapper) {\n const input = wrapper.querySelector(\".slopit-typing-input\");\n if (input && this.boundHandlers.keydown) {\n input.removeEventListener(\"keydown\", this.boundHandlers.keydown as EventListener);\n }\n if (input && this.boundHandlers.keyup) {\n input.removeEventListener(\"keyup\", this.boundHandlers.keyup as EventListener);\n }\n wrapper.remove();\n }\n this.container = null;\n }\n this.boundHandlers = { keydown: null, keyup: null };\n this.keystrokes = [];\n }\n\n /**\n * Calculate typing accuracy as a ratio (0-1).\n * Uses a simple character-by-character comparison with length normalization.\n */\n private calculateAccuracy(target: string, actual: string): number {\n if (target.length === 0) {\n return actual.length === 0 ? 1 : 0;\n }\n\n const maxLen = Math.max(target.length, actual.length);\n let matches = 0;\n\n for (let i = 0; i < Math.min(target.length, actual.length); i++) {\n if (target[i] === actual[i]) {\n matches++;\n }\n }\n\n return matches / maxLen;\n }\n}\n\n/**\n * Memory recall challenge that verifies participant engagement.\n *\n * Presents a question about previously shown content and checks\n * if the response contains expected keywords. Captures typing\n * behavior during the response.\n *\n * @example\n * ```typescript\n * const challenge = new MemoryRecallChallenge();\n * const result = await challenge.render(\n * {\n * type: \"memory_recall\",\n * prompt: \"What color was the car in the image you saw earlier?\",\n * expectedKeywords: [\"red\", \"sedan\"],\n * timeLimit: 30000,\n * },\n * document.getElementById(\"challenge-container\")!\n * );\n * ```\n */\nexport class MemoryRecallChallenge implements ChallengeRenderer {\n private container: HTMLElement | null = null;\n private startTime = 0;\n private keystrokes: Array<{ key: string; time: number; event: \"keydown\" | \"keyup\" }> = [];\n private boundHandlers: {\n keydown: ((e: KeyboardEvent) => void) | null;\n keyup: ((e: KeyboardEvent) => void) | null;\n } = { keydown: null, keyup: null };\n\n /**\n * Render the memory recall challenge.\n *\n * @param config - Challenge configuration with optional `expectedKeywords`\n * @param container - Container element for the challenge UI\n * @returns Promise resolving to challenge result with keyword matching status\n */\n async render(config: ChallengeConfig, container: HTMLElement): Promise<ChallengeResult> {\n this.container = container;\n this.keystrokes = [];\n\n return new Promise((resolve) => {\n // Create challenge UI\n const wrapper = document.createElement(\"div\");\n wrapper.className = \"slopit-memory-challenge\";\n\n const promptEl = document.createElement(\"p\");\n promptEl.className = \"slopit-challenge-prompt\";\n promptEl.textContent = config.prompt;\n wrapper.appendChild(promptEl);\n\n const inputEl = document.createElement(\"textarea\");\n inputEl.className = \"slopit-memory-input\";\n inputEl.placeholder = \"Type your answer...\";\n inputEl.rows = 3;\n wrapper.appendChild(inputEl);\n\n const submitBtn = document.createElement(\"button\");\n submitBtn.className = \"slopit-challenge-submit\";\n submitBtn.textContent = \"Submit\";\n submitBtn.type = \"button\";\n wrapper.appendChild(submitBtn);\n\n container.appendChild(wrapper);\n\n // Start timing\n this.startTime = performance.now();\n\n // Set up keystroke capture\n this.boundHandlers.keydown = (e: KeyboardEvent) => {\n this.keystrokes.push({\n key: e.key,\n time: performance.now() - this.startTime,\n event: \"keydown\",\n });\n };\n\n this.boundHandlers.keyup = (e: KeyboardEvent) => {\n this.keystrokes.push({\n key: e.key,\n time: performance.now() - this.startTime,\n event: \"keyup\",\n });\n };\n\n inputEl.addEventListener(\"keydown\", this.boundHandlers.keydown);\n inputEl.addEventListener(\"keyup\", this.boundHandlers.keyup);\n\n // Handle submission\n const submit = (): void => {\n const completionTime = performance.now() - this.startTime;\n const response = inputEl.value;\n\n // Check for expected keywords (case-insensitive)\n const passed = this.checkKeywords(response, config.expectedKeywords ?? []);\n\n resolve({\n passed,\n response,\n completionTime,\n behavioralData: {\n keystrokes: [...this.keystrokes],\n expectedKeywords: config.expectedKeywords,\n matchedKeywords: this.getMatchedKeywords(response, config.expectedKeywords ?? []),\n },\n });\n };\n\n submitBtn.addEventListener(\"click\", submit);\n\n // Handle time limit\n if (config.timeLimit !== undefined) {\n setTimeout(() => {\n submit();\n }, config.timeLimit);\n }\n\n // Focus the input\n inputEl.focus();\n });\n }\n\n /**\n * Clean up challenge UI and event listeners.\n */\n cleanup(): void {\n if (this.container) {\n const wrapper = this.container.querySelector(\".slopit-memory-challenge\");\n if (wrapper) {\n const input = wrapper.querySelector(\".slopit-memory-input\");\n if (input && this.boundHandlers.keydown) {\n input.removeEventListener(\"keydown\", this.boundHandlers.keydown as EventListener);\n }\n if (input && this.boundHandlers.keyup) {\n input.removeEventListener(\"keyup\", this.boundHandlers.keyup as EventListener);\n }\n wrapper.remove();\n }\n this.container = null;\n }\n this.boundHandlers = { keydown: null, keyup: null };\n this.keystrokes = [];\n }\n\n /**\n * Check if response contains all expected keywords.\n */\n private checkKeywords(response: string, keywords: string[]): boolean {\n if (keywords.length === 0) {\n return true; // No keywords required\n }\n\n const lowerResponse = response.toLowerCase();\n return keywords.every((keyword) => lowerResponse.includes(keyword.toLowerCase()));\n }\n\n /**\n * Get list of keywords that were matched in the response.\n */\n private getMatchedKeywords(response: string, keywords: string[]): string[] {\n const lowerResponse = response.toLowerCase();\n return keywords.filter((keyword) => lowerResponse.includes(keyword.toLowerCase()));\n }\n}\n\n/**\n * Create a challenge renderer for the specified type.\n *\n * Returns a built-in renderer for supported types (typing_test, memory_recall),\n * or null for types that require custom implementation (audio_transcription,\n * image_description, consistency_check).\n *\n * @param type - The challenge type\n * @returns A challenge renderer instance, or null if type requires custom implementation\n *\n * @example\n * ```typescript\n * const challenge = createChallenge(\"typing_test\");\n * if (challenge) {\n * const result = await challenge.render(config, container);\n * challenge.cleanup();\n * }\n * ```\n */\nexport function createChallenge(type: ChallengeType): ChallengeRenderer | null {\n switch (type) {\n case \"typing_test\":\n return new TypingTestChallenge();\n case \"memory_recall\":\n return new MemoryRecallChallenge();\n case \"audio_transcription\":\n case \"image_description\":\n case \"consistency_check\":\n // These require custom implementation by the researcher\n return null;\n default: {\n // Exhaustive check\n const _exhaustive: never = type;\n return _exhaustive;\n }\n }\n}\n","/**\n * Generic wrapper for HTML input elements combining behavioral capture with interventions.\n *\n * @module\n */\n\nimport type { BehavioralData, CaptureFlag } from \"@slopit/core\";\nimport { BehavioralCapture } from \"../capture.js\";\nimport type { DetectionResult, Detector } from \"../detection/index.js\";\nimport type { BehavioralCaptureConfig } from \"../types.js\";\n\n/**\n * Result of an intervention action.\n */\nexport interface InterventionResult {\n /**\n * Unique identifier for the intervention.\n */\n id: string;\n\n /**\n * Timestamp when the intervention was triggered.\n */\n timestamp: number;\n\n /**\n * Type of intervention applied.\n */\n type: string;\n\n /**\n * Whether the intervention was shown to the user.\n */\n shown: boolean;\n\n /**\n * User's response to the intervention, if any.\n */\n userResponse?: string;\n\n /**\n * Duration the intervention was displayed in milliseconds.\n */\n displayDuration?: number;\n\n /**\n * Additional metadata about the intervention.\n */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Interface for managing interventions during behavioral capture.\n *\n * Implementations can provide various intervention strategies such as\n * warnings, confirmations, or educational prompts.\n */\nexport interface InterventionManager {\n /**\n * Unique name for this intervention manager.\n */\n readonly name: string;\n\n /**\n * Evaluates whether an intervention should be triggered.\n *\n * @param data - Current behavioral data\n * @param flags - Current capture flags\n * @returns Whether an intervention should be shown\n */\n shouldIntervene(data: BehavioralData, flags: CaptureFlag[]): boolean;\n\n /**\n * Executes the intervention and returns the result.\n *\n * @param data - Current behavioral data\n * @param flags - Current capture flags\n * @returns Promise resolving to the intervention result\n */\n intervene(data: BehavioralData, flags: CaptureFlag[]): Promise<InterventionResult>;\n\n /**\n * Resets the intervention manager state.\n */\n reset(): void;\n}\n\n/**\n * Event types emitted by the InputWrapper.\n */\nexport type WrapperEvent =\n | \"data\" // Data captured\n | \"flag\" // Flag generated\n | \"intervention\" // Intervention triggered\n | \"detection\"; // Detection result\n\n/**\n * Configuration for InputWrapper.\n */\nexport interface InputWrapperConfig {\n /**\n * Configuration for behavioral capture.\n */\n capture?: BehavioralCaptureConfig;\n\n /**\n * Optional intervention manager for handling detected behaviors.\n */\n interventionManager?: InterventionManager;\n\n /**\n * Array of detectors to run periodically.\n */\n detectors?: Detector[];\n\n /**\n * Interval in milliseconds between detector runs.\n * @default 5000\n */\n detectionInterval?: number;\n}\n\n/**\n * Extended behavioral data including flags, detection results, and interventions.\n */\nexport interface EnhancedBehavioralData extends BehavioralData {\n /**\n * Flags generated during capture.\n */\n flags: CaptureFlag[];\n\n /**\n * Results from all detector runs.\n */\n detectionResults: DetectionResult[];\n\n /**\n * Results from all interventions.\n */\n interventions: InterventionResult[];\n}\n\n/**\n * Event handler type for wrapper events.\n */\ntype WrapperEventHandler<T> = (data: T) => void;\n\n/**\n * Generic wrapper for HTML input elements combining behavioral capture with detection and intervention.\n *\n * The InputWrapper provides a unified interface for:\n * - Behavioral data capture via BehavioralCapture\n * - Periodic detection via configurable Detectors\n * - Intervention handling via InterventionManager\n * - Event-based notification of capture, detection, and intervention events\n *\n * @example\n * ```typescript\n * import { InputWrapper, createInputWrapper } from \"@slopit/behavioral\";\n *\n * // Create wrapper with default configuration\n * const wrapper = createInputWrapper({\n * capture: { keystroke: { enabled: true } },\n * detectionInterval: 3000,\n * });\n *\n * // Wrap an input element\n * const textarea = document.getElementById(\"response\") as HTMLTextAreaElement;\n * wrapper.wrap(textarea);\n *\n * // Subscribe to events\n * wrapper.on(\"detection\", (result) => {\n * console.log(\"Detection:\", result);\n * });\n *\n * // Later, get all captured data\n * const data = wrapper.getData();\n *\n * // Cleanup\n * wrapper.unwrap();\n * ```\n */\nexport class InputWrapper {\n private element: HTMLTextAreaElement | HTMLInputElement | null = null;\n private capture: BehavioralCapture;\n private interventionManager?: InterventionManager;\n private detectors: Detector[] = [];\n private detectionInterval: number;\n private detectionTimer?: ReturnType<typeof setInterval>;\n private detectionResults: DetectionResult[] = [];\n private interventionResults: InterventionResult[] = [];\n private listeners: Map<WrapperEvent, Set<WrapperEventHandler<unknown>>> = new Map();\n private isInterventionInProgress = false;\n\n /**\n * Creates a new InputWrapper instance.\n *\n * @param config - Configuration options for the wrapper\n */\n constructor(config: InputWrapperConfig = {}) {\n this.capture = new BehavioralCapture(config.capture ?? {});\n if (config.interventionManager !== undefined) {\n this.interventionManager = config.interventionManager;\n }\n this.detectors = config.detectors ?? [];\n this.detectionInterval = config.detectionInterval ?? 5000;\n }\n\n /**\n * Wraps an input element with behavioral capture.\n *\n * Attaches event listeners to the element and starts detection\n * if detectors are configured.\n *\n * @param element - The textarea or input element to wrap\n * @throws {Error} If the wrapper is already attached to an element\n *\n * @example\n * ```typescript\n * const wrapper = createInputWrapper();\n * const input = document.querySelector(\"textarea\");\n * wrapper.wrap(input);\n * ```\n */\n wrap(element: HTMLTextAreaElement | HTMLInputElement): void {\n if (this.element !== null) {\n throw new Error(\"InputWrapper already attached. Call unwrap() first.\");\n }\n\n this.element = element;\n this.capture.attach(element);\n\n if (this.detectors.length > 0) {\n this.startDetection();\n }\n\n if (this.interventionManager !== undefined) {\n this.setupInterventionChecks();\n }\n }\n\n /**\n * Unwraps the element and cleans up all resources.\n *\n * Stops detection, detaches capture, and clears all internal state.\n *\n * @example\n * ```typescript\n * wrapper.unwrap();\n * // Can now wrap a different element\n * wrapper.wrap(anotherElement);\n * ```\n */\n unwrap(): void {\n this.stopDetection();\n this.capture.detach();\n this.element = null;\n }\n\n /**\n * Resets all collected data without unwrapping.\n *\n * Clears captured data, detection results, and intervention results\n * while maintaining the element attachment.\n *\n * @param newStartTime - Optional new start time for capture timing\n */\n reset(newStartTime?: number): void {\n this.capture.reset(newStartTime);\n this.detectionResults = [];\n this.interventionResults = [];\n\n if (this.interventionManager !== undefined) {\n this.interventionManager.reset();\n }\n }\n\n /**\n * Gets all captured data including flags, detection results, and interventions.\n *\n * @returns Enhanced behavioral data with all capture information\n *\n * @example\n * ```typescript\n * const data = wrapper.getData();\n * console.log(\"Keystrokes:\", data.keystrokes?.length);\n * console.log(\"Flags:\", data.flags.length);\n * console.log(\"Detections:\", data.detectionResults.length);\n * ```\n */\n getData(): EnhancedBehavioralData {\n return {\n ...this.capture.getData(),\n flags: this.capture.getFlags(),\n detectionResults: [...this.detectionResults],\n interventions: [...this.interventionResults],\n };\n }\n\n /**\n * Gets flags generated during capture.\n *\n * @returns Array of capture flags\n */\n getFlags(): CaptureFlag[] {\n return this.capture.getFlags();\n }\n\n /**\n * Gets all detection results from detector runs.\n *\n * @returns Array of detection results\n */\n getDetectionResults(): DetectionResult[] {\n return [...this.detectionResults];\n }\n\n /**\n * Gets all intervention results.\n *\n * @returns Array of intervention results\n */\n getInterventionResults(): InterventionResult[] {\n return [...this.interventionResults];\n }\n\n /**\n * Manually triggers all detectors immediately.\n *\n * Useful for running detection on demand rather than waiting\n * for the next scheduled interval.\n *\n * @returns Array of detection results from this run\n */\n runDetection(): DetectionResult[] {\n const results: DetectionResult[] = [];\n\n for (const detector of this.detectors) {\n const result = detector.detect();\n results.push(result);\n this.detectionResults.push(result);\n this.emit(\"detection\", result);\n }\n\n return results;\n }\n\n /**\n * Subscribes to wrapper events.\n *\n * @param event - The event type to subscribe to\n * @param handler - The callback function to invoke\n *\n * @example\n * ```typescript\n * wrapper.on(\"flag\", (flag) => {\n * console.log(\"Flag generated:\", flag.type);\n * });\n *\n * wrapper.on(\"detection\", (result) => {\n * if (result.detected) {\n * console.log(\"Detected:\", result.message);\n * }\n * });\n * ```\n */\n on(event: WrapperEvent, handler: WrapperEventHandler<unknown>): void {\n if (!this.listeners.has(event)) {\n this.listeners.set(event, new Set());\n }\n this.listeners.get(event)?.add(handler);\n }\n\n /**\n * Unsubscribes from wrapper events.\n *\n * @param event - The event type to unsubscribe from\n * @param handler - The callback function to remove\n */\n off(event: WrapperEvent, handler: WrapperEventHandler<unknown>): void {\n this.listeners.get(event)?.delete(handler);\n }\n\n /**\n * Starts the detection timer for periodic detector runs.\n */\n private startDetection(): void {\n if (this.detectionTimer !== undefined) {\n return;\n }\n\n // Start monitoring for detectors that support it\n for (const detector of this.detectors) {\n if (detector.startMonitoring !== undefined && this.element !== null) {\n detector.startMonitoring(this.element);\n }\n }\n\n this.detectionTimer = setInterval(() => {\n this.runDetection();\n }, this.detectionInterval);\n }\n\n /**\n * Stops the detection timer and monitoring.\n */\n private stopDetection(): void {\n if (this.detectionTimer !== undefined) {\n clearInterval(this.detectionTimer);\n delete this.detectionTimer;\n }\n\n // Stop monitoring for detectors that support it\n for (const detector of this.detectors) {\n if (detector.stopMonitoring !== undefined) {\n detector.stopMonitoring();\n }\n }\n }\n\n /**\n * Sets up intervention checks on behavioral capture events.\n */\n private setupInterventionChecks(): void {\n if (this.interventionManager === undefined) {\n return;\n }\n\n // Check for intervention on keystroke events\n this.capture.on(\"keystroke\", () => {\n void this.checkIntervention();\n });\n\n // Check for intervention on paste events\n this.capture.on(\"paste\", () => {\n void this.checkIntervention();\n });\n\n // Check for intervention on focus events\n this.capture.on(\"focus\", () => {\n void this.checkIntervention();\n });\n }\n\n /**\n * Checks if an intervention should be triggered and executes it.\n */\n private async checkIntervention(): Promise<void> {\n if (this.interventionManager === undefined || this.isInterventionInProgress) {\n return;\n }\n\n const data = this.capture.getData();\n const flags = this.capture.getFlags();\n\n if (this.interventionManager.shouldIntervene(data, flags)) {\n this.isInterventionInProgress = true;\n\n try {\n const result = await this.interventionManager.intervene(data, flags);\n this.interventionResults.push(result);\n this.emit(\"intervention\", result);\n } finally {\n this.isInterventionInProgress = false;\n }\n }\n }\n\n /**\n * Emits an event to all subscribed handlers.\n *\n * @param event - The event type\n * @param data - The event data\n */\n private emit(event: WrapperEvent, data: unknown): void {\n const handlers = this.listeners.get(event);\n if (handlers === undefined) {\n return;\n }\n\n for (const handler of handlers) {\n handler(data);\n }\n }\n}\n\n/**\n * Factory function to create an InputWrapper instance.\n *\n * @param config - Optional configuration for the wrapper\n * @returns A new InputWrapper instance\n *\n * @example\n * ```typescript\n * const wrapper = createInputWrapper({\n * capture: {\n * keystroke: { enabled: true },\n * paste: { enabled: true, prevent: false },\n * },\n * detectionInterval: 3000,\n * });\n * ```\n */\nexport function createInputWrapper(config?: InputWrapperConfig): InputWrapper {\n return new InputWrapper(config);\n}\n"]}
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "@slopit/behavioral",
3
+ "version": "0.1.0",
4
+ "description": "Client-side behavioral capture for keystroke dynamics, focus events, and paste detection",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": {
8
+ "name": "Aaron Steven White",
9
+ "email": "aaron.white@rochester.edu",
10
+ "url": "https://aaronstevenwhite.io"
11
+ },
12
+ "homepage": "https://slopit.github.io",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/slopit/slopit.git",
16
+ "directory": "packages/behavioral"
17
+ },
18
+ "bugs": {
19
+ "url": "https://github.com/slopit/slopit/issues"
20
+ },
21
+ "publishConfig": {
22
+ "access": "public"
23
+ },
24
+ "keywords": [
25
+ "behavioral-capture",
26
+ "keystroke-dynamics",
27
+ "focus-tracking",
28
+ "paste-detection",
29
+ "ai-detection",
30
+ "crowdsourcing"
31
+ ],
32
+ "exports": {
33
+ ".": {
34
+ "import": "./dist/index.js",
35
+ "types": "./dist/index.d.ts"
36
+ }
37
+ },
38
+ "files": [
39
+ "dist"
40
+ ],
41
+ "dependencies": {
42
+ "@slopit/core": "0.1.0"
43
+ },
44
+ "devDependencies": {
45
+ "jsdom": "^25.0.1",
46
+ "tsup": "^8.3.5",
47
+ "typescript": "^5.7.2",
48
+ "vitest": "^2.1.8"
49
+ },
50
+ "scripts": {
51
+ "build": "tsup",
52
+ "typecheck": "tsc --noEmit",
53
+ "test": "vitest run",
54
+ "test:watch": "vitest",
55
+ "clean": "rm -rf dist"
56
+ }
57
+ }