!function(){"use strict"; /** * Serenity.js - User Interaction Recording Library * * Records all user interactions with the page including: * - Mouse events (click, dblclick, mousedown, mouseup, mousemove) * - Keyboard events (keydown, keyup, keypress) * - Scroll and wheel events * - Touch events (touchstart, touchmove, touchend) for swipe detection * - Drag events (drag, dragstart, dragend) * - Window resize events * * Features: * - Configurable debounce to reduce data * - Optional screenshot capture using html2canvas * - Works as standalone or React hook * * @version 1.0.0 * @license MIT */const t={debounceMs:1e3,captureScreenshots:!1,screenshotOnEvent:!1,captureTextContent:!1,maskInputs:!0,screenshotQuality:"LOW",outputFormat:"json",maxEvents:1e3,events:["click","dblclick","mousedown","mouseup","mousemove","keydown","keyup","keypress","scroll","wheel","touchstart","touchmove","touchend","dragstart","drag","dragend","resize"],debounceEvents:["mousemove","scroll","wheel","touchmove","drag","resize"],onEvent:null,target:null},e={LOW:{scale:.25,format:"jpeg",quality:.5},MEDIUM:{scale:.5,format:"jpeg",quality:.7},HIGH:{scale:1,format:"png",quality:1}},n={click:0,dblclick:1,mousedown:2,mouseup:3,mousemove:4,keydown:5,keyup:6,keypress:7,scroll:8,wheel:9,touchstart:10,touchmove:11,touchend:12,dragstart:13,drag:14,dragend:15,resize:16,swipe:17,swipeleft:18,swiperight:19,swipeup:20,swipedown:21,pinch:22,focus:23,blur:24,input:25,change:26,submit:27,pointerdown:28,pointerup:29,pointermove:30,pointercancel:31,init:32,unknown:255},i=Object.entries(n).reduce((t,[e,n])=>(t[n]=e,t),{});function r(t,e){let n;return function(...i){clearTimeout(n),n=setTimeout(()=>t.apply(this,i),e)}}function s(){return new Promise((t,e)=>{if(window.html2canvas)return void t(window.html2canvas);const n=document.createElement("script");n.src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js",n.onload=()=>t(window.html2canvas),n.onerror=()=>e(new Error("Failed to load html2canvas")),document.head.appendChild(n)})}class o{constructor(){this.buffer=[]}writeUint8(t){this.buffer.push(255&t)}writeUint16(t){this.buffer.push(t>>8&255),this.buffer.push(255&t)}writeUint32(t){this.buffer.push(t>>24&255),this.buffer.push(t>>16&255),this.buffer.push(t>>8&255),this.buffer.push(255&t)}writeUint64(t){const e=Math.floor(t/4294967296),n=t>>>0;this.writeUint32(e),this.writeUint32(n)}writeInt32(t){this.writeUint32(t>>>0)}writeFloat64(t){const e=new ArrayBuffer(8),n=new DataView(e);n.setFloat64(0,t,!1);for(let t=0;t<8;t++)this.buffer.push(n.getUint8(t))}writeBytes(t){for(const e of t)this.buffer.push(255&e)}writeString(t){const e=(new TextEncoder).encode(t||"");this.writeVarint(e.length),this.writeBytes(e)}writeVarint(t){for(;t>=128;)this.buffer.push(127&t|128),t>>>=7;this.buffer.push(127&t)}getBuffer(){return new Uint8Array(this.buffer).buffer}getBytes(){return new Uint8Array(this.buffer)}}class c{constructor(t){if(t instanceof ArrayBuffer)this.bytes=new Uint8Array(t);else{if(!(t instanceof Uint8Array))throw new Error("BinaryDecoder requires ArrayBuffer or Uint8Array");this.bytes=t}this.offset=0}readUint8(){if(this.offset>=this.bytes.length)throw new Error("Buffer underflow");return this.bytes[this.offset++]}readUint16(){return this.readUint8()<<8|this.readUint8()}readUint32(){return(this.readUint8()<<24|this.readUint8()<<16|this.readUint8()<<8|this.readUint8())>>>0}readUint64(){return 4294967296*this.readUint32()+this.readUint32()}readInt32(){return 0|this.readUint32()}readFloat64(){const t=this.readBytes(8),e=new ArrayBuffer(8),n=new DataView(e);for(let e=0;e<8;e++)n.setUint8(e,t[e]);return n.getFloat64(0,!1)}readBytes(t){if(this.offset+t>this.bytes.length)throw new Error("Buffer underflow");const e=this.bytes.slice(this.offset,this.offset+t);return this.offset+=t,e}readString(){const t=this.readVarint();if(0===t)return"";const e=this.readBytes(t);return(new TextDecoder).decode(e)}readVarint(){let t=0,e=0;for(;;){const n=this.readUint8();if(t|=(127&n)<>>0}}class a{constructor(e={}){this.config={...t,...e},this.events=[],this.isRecording=!1,this.isPaused=!1,this.boundHandlers={},this.debouncedHandlers={},this.html2canvasLoaded=!1,this.startTime=null,this.config.debounceEvents.forEach(t=>{this.debouncedHandlers[t]=r(e=>this._recordEvent(t,e,!0),this.config.debounceMs)})}_createEventData(t,e){const n=Date.now(),i={t:t,ts:n,rt:this.startTime?n-this.startTime:0,tg:{tag:e.target?.tagName||null,id:e.target?.id||null,cls:e.target?.className||null}};if(this.config.captureTextContent&&e.target?.textContent&&(i.tg.txt=e.target.textContent.substring(0,50)),["click","dblclick","mousedown","mouseup","mousemove"].includes(t)&&(i.pos={x:e.clientX,y:e.clientY,pX:e.pageX,pY:e.pageY},i.btn=e.button),["keydown","keyup","keypress"].includes(t)){const t=!1!==this.config.maskInputs&&this._isSensitiveInputElement(e.target);i.k=t?{key:"*",code:"*",kc:0,ctrl:!1,shift:!1,alt:!1,meta:!1}:{key:e.key,code:e.code,kc:e.keyCode,ctrl:e.ctrlKey,shift:e.shiftKey,alt:e.altKey,meta:e.metaKey}}return"scroll"===t&&(i.scr={x:window.scrollX,y:window.scrollY,top:document.documentElement.scrollTop||document.body.scrollTop,left:document.documentElement.scrollLeft||document.body.scrollLeft}),"wheel"===t&&(i.whl={dX:e.deltaX,dY:e.deltaY,dZ:e.deltaZ,mode:e.deltaMode}),["touchstart","touchmove","touchend"].includes(t)&&(i.tch=Array.from(e.touches||[]).map(t=>({id:t.identifier,x:t.clientX,y:t.clientY,pX:t.pageX,pY:t.pageY})),i.chTch=Array.from(e.changedTouches||[]).map(t=>({id:t.identifier,x:t.clientX,y:t.clientY,pX:t.pageX,pY:t.pageY}))),["drag","dragstart","dragend"].includes(t)&&(i.pos={x:e.clientX,y:e.clientY,pX:e.pageX,pY:e.pageY}),"resize"===t&&(i.win={iW:window.innerWidth,iH:window.innerHeight,oW:window.outerWidth,oH:window.outerHeight}),i}_isSensitiveInputElement(t){if(!t||"string"!=typeof t.tagName)return!1;const e=t.tagName.toUpperCase();return"INPUT"===e||"TEXTAREA"===e||"SELECT"===e||Boolean(t.isContentEditable)}_storeEvent(t){if(this.events.push(t),this.events.length>this.config.maxEvents&&(this.events=this.events.slice(-this.config.maxEvents)),"function"==typeof this.config.onEvent)if("binary"===this.config.outputFormat){const e=this._encodeSingleEventToBinary(t);this.config.onEvent(e)}else this.config.onEvent(t)}async _recordEvent(t,e,n=!1){if(!this.isRecording||this.isPaused)return;const i=this._createEventData(t,e);if(this.config.screenshotOnEvent&&n)try{i.img=await this.takeScreenshot()}catch(t){console.warn("[Serenity] Screenshot failed:",t)}this._storeEvent(i)}_encodeSingleEventToBinary(t){const e=new o;return this._encodeEvent(e,t),e.getBuffer()}_createHandler(t){return this.config.debounceEvents.includes(t)?this.debouncedHandlers[t]:e=>this._recordEvent(t,e,!1)}start(){if(this.isRecording)return this;this.isRecording=!0,this.isPaused=!1,this.startTime=Date.now();const t={t:"init",ts:this.startTime,rt:0,win:{iW:window.innerWidth,iH:window.innerHeight,oW:window.outerWidth,oH:window.outerHeight},doc:{w:document.body?.scrollWidth||document.documentElement.scrollWidth,h:document.body?.scrollHeight||document.documentElement.scrollHeight},scr:{w:window.screen?.width||0,h:window.screen?.height||0},url:window.location.href,ua:navigator.userAgent};this._storeEvent(t);const e=this.config.target||document;return this.config.events.forEach(t=>{const n=this._createHandler(t);this.boundHandlers[t]=n,"resize"===t?window.addEventListener("resize",n,{passive:!0}):"scroll"===t?window.addEventListener("scroll",n,{passive:!0}):e.addEventListener(t,n,{passive:!0})}),this.config.captureScreenshots&&!this.html2canvasLoaded&&s().then(()=>{this.html2canvasLoaded=!0}).catch(t=>console.warn("[Serenity] Could not preload html2canvas:",t)),console.info("[Serenity] Recording started"),this}stop(){if(!this.isRecording)return this;this.isRecording=!1,this.isPaused=!1;const t=this.config.target||document;return Object.keys(this.boundHandlers).forEach(e=>{const n=this.boundHandlers[e];"resize"===e?window.removeEventListener("resize",n):"scroll"===e?window.removeEventListener("scroll",n):t.removeEventListener(e,n)}),this.boundHandlers={},console.info("[Serenity] Recording stopped"),this}pause(){return this.isRecording?(this.isPaused=!0,console.info("[Serenity] Recording paused"),this):this}resume(){return this.isRecording?(this.isPaused=!1,console.info("[Serenity] Recording resumed"),this):this}getEvents(){return[...this.events]}getEventCount(){return this.events.length}clearEvents(){return this.events=[],console.info("[Serenity] Events cleared"),this}async takeScreenshot(t){this.html2canvasLoaded||(await s(),this.html2canvasLoaded=!0);const n=e[t||this.config.screenshotQuality]||e.LOW,i=await window.html2canvas(document.body,{useCORS:!0,allowTaint:!0,logging:!1,scale:n.scale});return"jpeg"===n.format?i.toDataURL("image/jpeg",n.quality):i.toDataURL("image/png")}exportJSON(){return JSON.stringify(this.events,null,2)}importJSON(t){try{const e=JSON.parse(t);Array.isArray(e)&&(this.events=e)}catch(t){console.error("[Serenity] Failed to import JSON:",t)}return this}exportBinary(){const t=new o;t.writeBytes([83,82,78,84]),t.writeUint8(1),t.writeUint8(0),t.writeUint32(this.events.length);for(const e of this.events)this._encodeEvent(t,e);return t.getBuffer()}importBinary(t){try{const e=new c(t),n=e.readBytes(4);if(83!==n[0]||82!==n[1]||78!==n[2]||84!==n[3])throw new Error("Invalid Serenity binary format");const i=e.readUint8(),r=e.readUint8();if(1!==i)throw new Error(`Unsupported version: ${i}.${r}`);const s=e.readUint32();this.events=[];for(let t=0;t{this.debouncedHandlers[t]=r(e=>this._recordEvent(t,e,!0),this.config.debounceMs)}),e&&this.start(),this}destroy(){this.stop(),this.clearEvents(),this.config.onEvent=null,console.info("[Serenity] Instance destroyed")}getStatus(){return{isRecording:this.isRecording,isPaused:this.isPaused,eventCount:this.events.length,startTime:this.startTime,config:{...this.config}}}}function d(t={}){if("undefined"!=typeof window&&window.React){const e=window.React,{useState:n,useEffect:i,useCallback:r,useRef:s}=e,o=s(null),[c,d]=n([]),[h,u]=n(!1),[l,w]=n(!1);i(()=>(o.current=new a({...t,onEvent:e=>{d(n=>[...n.slice(-((t.maxEvents||1e3)-1)),e]),t.onEvent&&t.onEvent(e)}}),()=>{o.current&&o.current.destroy()}),[]);return{events:c,isRecording:h,isPaused:l,start:r(()=>{o.current&&(o.current.start(),u(!0),w(!1))},[]),stop:r(()=>{o.current&&(o.current.stop(),u(!1),w(!1))},[]),pause:r(()=>{o.current&&(o.current.pause(),w(!0))},[]),resume:r(()=>{o.current&&(o.current.resume(),w(!1))},[]),clearEvents:r(()=>{o.current&&(o.current.clearEvents(),d([]))},[]),takeScreenshot:r(async()=>o.current?await o.current.takeScreenshot():null,[]),getEvents:r(()=>o.current?o.current.getEvents():[],[]),serenity:o.current}}return console.warn("[Serenity] useSerenity hook requires React. Use Serenity class directly instead."),null}function h(t={}){return new a(t)}try{"undefined"!=typeof module&&module.exports&&(module.exports={Serenity:a,useSerenity:d,createSerenity:h})}catch{}"undefined"!=typeof window&&(window.Serenity=a,window.useSerenity=d,window.createSerenity=h)}();