humanbehavior-js 0.5.50 → 0.5.52
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/packages/browser/dist/cjs/index.js +8 -8
- package/packages/browser/dist/cjs/index.js.map +1 -1
- package/packages/browser/dist/esm/index.js +2 -2
- package/packages/browser/dist/esm/index.js.map +1 -1
- package/packages/browser/dist/index.min.js +1 -1
- package/packages/browser/dist/index.min.js.map +1 -1
- package/packages/core/dist/api.d.ts +1 -1
- package/packages/core/dist/api.d.ts.map +1 -1
- package/packages/core/dist/index.js +1 -1
- package/packages/core/dist/index.js.map +1 -1
- package/packages/core/dist/index.mjs +1 -1
- package/packages/core/dist/index.mjs.map +1 -1
- package/packages/core/dist/tracker.d.ts +23 -0
- package/packages/core/dist/tracker.d.ts.map +1 -1
- package/packages/react/dist/index.js +1 -1
- package/packages/react/dist/index.js.map +1 -1
- package/packages/react/dist/index.mjs +1 -1
- package/packages/react/dist/index.mjs.map +1 -1
- package/packages/wizard/dist/cli/ai-auto-install.js +34 -14
- package/packages/wizard/dist/cli/ai-auto-install.js.map +1 -1
- package/packages/wizard/dist/cli/auto-install.d.ts.map +1 -1
- package/packages/wizard/dist/cli/auto-install.js +45 -23
- package/packages/wizard/dist/cli/auto-install.js.map +1 -1
- package/packages/wizard/dist/core/install-wizard.d.ts.map +1 -1
- package/packages/wizard/dist/index.js +1 -1
- package/packages/wizard/dist/index.js.map +1 -1
- package/packages/wizard/dist/index.mjs +1 -1
- package/packages/wizard/dist/index.mjs.map +1 -1
package/package.json
CHANGED
|
@@ -12173,7 +12173,7 @@ function v1Bytes(rnds, msecs, nsecs, clockseq, node, buf, offset = 0) {
|
|
|
12173
12173
|
return buf;
|
|
12174
12174
|
}
|
|
12175
12175
|
|
|
12176
|
-
exports.LogLevel = void 0;!function(e){e[e.NONE=0]="NONE",e[e.ERROR=1]="ERROR",e[e.WARN=2]="WARN",e[e.INFO=3]="INFO",e[e.DEBUG=4]="DEBUG";}(exports.LogLevel||(exports.LogLevel={}));const s=new class{constructor(e){this.config={level:exports.LogLevel.ERROR,enableConsole:true,enableStorage:false},this.isBrowser="undefined"!=typeof window,e&&(this.config={...this.config,...e});}setConfig(e){this.config={...this.config,...e};}shouldLog(e){return e<=this.config.level}formatMessage(e,t,...i){return `[HumanBehavior ${e}] ${(new Date).toISOString()}: ${t}`}error(e,...t){if(!this.shouldLog(exports.LogLevel.ERROR))return;const s=this.formatMessage("ERROR",e);this.config.enableConsole&&console.error(s,...t),this.config.enableStorage&&this.isBrowser&&this.logToStorage(s,t);}warn(e,...t){if(!this.shouldLog(exports.LogLevel.WARN))return;const s=this.formatMessage("WARN",e);this.config.enableConsole&&console.warn(s,...t),this.config.enableStorage&&this.isBrowser&&this.logToStorage(s,t);}info(e,...t){if(!this.shouldLog(exports.LogLevel.INFO))return;const s=this.formatMessage("INFO",e);this.config.enableConsole&&console.log(s,...t),this.config.enableStorage&&this.isBrowser&&this.logToStorage(s,t);}debug(e,...t){if(!this.shouldLog(exports.LogLevel.DEBUG))return;const s=this.formatMessage("DEBUG",e);this.config.enableConsole&&console.log(s,...t),this.config.enableStorage&&this.isBrowser&&this.logToStorage(s,t);}logToStorage(e,t){try{const i=JSON.parse(localStorage.getItem("human_behavior_logs")||"[]"),s={message:e,args:t.length>0?t:void 0,timestamp:Date.now()};i.push(s),i.length>1e3&&i.splice(0,i.length-1e3),localStorage.setItem("human_behavior_logs",JSON.stringify(i));}catch(e){}}getLogs(){if(!this.isBrowser)return [];try{return JSON.parse(localStorage.getItem("human_behavior_logs")||"[]")}catch(e){return []}}clearLogs(){this.isBrowser&&localStorage.removeItem("human_behavior_logs");}},n=(e,...t)=>s.error(e,...t),r=(e,...t)=>s.warn(e,...t),a=(e,...t)=>s.info(e,...t),o=(e,...t)=>s.debug(e,...t),c=1048576;function l(e,t,i){return (new TextEncoder).encode(JSON.stringify({sessionId:i,events:[...e,t]})).length>c}function d(e,t){if(!e||"object"!=typeof e)return [];if((new TextEncoder).encode(JSON.stringify({sessionId:t,events:[e]})).length<=c)return [e];const i={...e},s=["screenshot","html","dom","fullText","innerHTML","outerHTML"];s.forEach(e=>{i[e]&&delete i[e];});if((new TextEncoder).encode(JSON.stringify({sessionId:t,events:[i]})).length<=c)return [i];return [{type:e.type,timestamp:e.timestamp,url:e.url,pathname:e.pathname,...Object.fromEntries(Object.entries(e).filter(([e,t])=>!s.includes(e)&&"object"!=typeof t&&"string"!=typeof t||"string"==typeof t&&t.length<1e3))}]}class h{constructor({apiKey:e,ingestionUrl:t}){this.monthlyLimitReached=false,this.apiKey=e,this.baseUrl=t;}checkMonthlyLimit(){return !this.monthlyLimitReached}async init(e,t){if(!this.checkMonthlyLimit())return {sessionId:e,endUserId:t};let i=null,s=null;"undefined"!=typeof window&&(i=window.location.href,s=document.referrer),a("API init called with:",{sessionId:e,userId:t,entryURL:i,referrer:s,baseUrl:this.baseUrl});try{const r=await fetch(`${this.baseUrl}/api/ingestion/init`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,Referer:s||""},body:JSON.stringify({sessionId:e,endUserId:t,entryURL:i,referrer:s})});if(a("API init response status:",r.status),!r.ok){if(429===r.status)return this.monthlyLimitReached=!0,{sessionId:e,endUserId:t};const i=await r.text();throw n("API init failed:",r.status,i),new Error(`Failed to initialize ingestion: ${r.statusText} - ${i}`)}const o=await r.json();return !0===o.monthlyLimitReached&&(this.monthlyLimitReached=!0,a("Monthly limit reached detected from server response")),a("API init success:",o),{sessionId:o.sessionId,endUserId:o.endUserId}}catch(e){throw n("API init error:",e),e}}async sendEvents(e,t,i){const s=e.filter(e=>e&&"object"==typeof e),n=await fetch(`${this.baseUrl}/api/ingestion/events`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({sessionId:t,events:s,endUserId:i})});if(!n.ok){if(429===n.status)throw this.monthlyLimitReached=true,new Error("429: Monthly video processing limit reached");throw new Error(`Failed to send events: ${n.statusText}`)} true===(await n.json()).monthlyLimitReached&&(this.monthlyLimitReached=true,a("Monthly limit reached detected from events response"));}async sendEventsChunked(e,t,i){if(!this.checkMonthlyLimit())return [];try{const s=[];let n=[];for(const r of e)if(r&&"object"==typeof r)if(l(n,r,t)){if(n.length>0){o(`[SDK] Sending chunk with ${n.length} events`);const e=await fetch(`${this.baseUrl}/api/ingestion/events`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({sessionId:t,events:n,endUserId:i})});if(!e.ok){if(429===e.status)return this.monthlyLimitReached=!0,s.flat();throw new Error(`Failed to send events: ${e.statusText}`)}const r=await e.json();!0===r.monthlyLimitReached&&(this.monthlyLimitReached=!0,a("Monthly limit reached detected from chunked events response")),s.push(r),n=[];}n=d(r,t);}else n.push(r);if(n.length>0){o(`[SDK] Sending final chunk with ${n.length} events`);const e=await fetch(`${this.baseUrl}/api/ingestion/events`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({sessionId:t,events:n,endUserId:i})});if(!e.ok){if(429===e.status)return this.monthlyLimitReached=!0,s.flat();throw new Error(`Failed to send events: ${e.statusText}`)}const r=await e.json();!0===r.monthlyLimitReached&&(this.monthlyLimitReached=!0,a("Monthly limit reached detected from final chunked events response")),s.push(r);}return s.flat()}catch(e){throw n("Error sending events:",e),e}}async sendUserData(e,t,i){try{const s={userId:e,userAttributes:t,sessionId:i,posthogName:t.email||t.name||null};o("Sending user data to server:",s);const n=await fetch(`${this.baseUrl}/api/ingestion/user`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(s)});if(!n.ok)throw new Error(`Failed to send user data: ${n.statusText} with API key: ${this.apiKey}`);const r=await n.json();return o("Server response:",r),r}catch(e){throw n("Error sending user data:",e),e}}async sendUserAuth(e,t,i,s){try{const n=await fetch(`${this.baseUrl}/api/ingestion/user/auth`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({userId:e,userAttributes:t,sessionId:i,authFields:s})});if(!n.ok)throw new Error(`Failed to authenticate user: ${n.statusText} with API key: ${this.apiKey}`);return await n.json()}catch(e){throw n("Error authenticating user:",e),e}}sendBeaconEvents(e,t){const i={sessionId:t,events:e,endUserId:null,apiKey:this.apiKey},s=new Blob([JSON.stringify(i)],{type:"application/json"});return navigator.sendBeacon(`${this.baseUrl}/api/ingestion/events`,s)}async sendCustomEvent(e,t,i,s){a("[SDK] Sending custom event",{sessionId:e,eventName:t,eventProperties:i,endUserId:s});try{const r=await fetch(`${this.baseUrl}/api/ingestion/customEvent`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({sessionId:e,eventName:t,eventProperties:i||{},endUserId:s||null})});if(a("[SDK] Custom event response",{status:r.status,statusText:r.statusText}),!r.ok){const e=await r.text();throw n("[SDK] Failed to send custom event",{status:r.status,statusText:r.statusText,errorText:e}),new Error(`Failed to send custom event: ${r.status} ${r.statusText} - ${e}`)}const c=await r.json();return o("[SDK] Custom event success",c),c}catch(s){throw n("[SDK] Error sending custom event",s,{sessionId:e,eventName:t,eventProperties:i}),s}}async sendCustomEventBatch(e,t,i){try{const s=await fetch(`${this.baseUrl}/api/ingestion/customEvent/batch`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({sessionId:e,events:t,endUserId:i||null})});if(!s.ok)throw new Error(`Failed to send custom event batch: ${s.statusText}`);return await s.json()}catch(e){throw n("Error sending custom event batch:",e),e}}}class u{constructor(e){if(this.redactedText="[REDACTED]",this.unredactedFields=new Set,this.redactedFields=new Set,this.redactionMode="privacy-first",this.excludeSelectors=['[data-no-redact="true"]',".human-behavior-no-redact"],e?.redactedText&&(this.redactedText=e.redactedText),e?.excludeSelectors&&(this.excludeSelectors=[...this.excludeSelectors,...e.excludeSelectors]),e?.redactionStrategy)if(this.redactionMode=e.redactionStrategy.mode,"privacy-first"===this.redactionMode)e.redactionStrategy.unredactFields&&this.setFieldsToUnredact(e.redactionStrategy.unredactFields);else {const t=['input[type="password"]','[data-hb-redact="true"]'],i=e.redactionStrategy.redactFields&&e.redactionStrategy.redactFields.length>0?e.redactionStrategy.redactFields:t;this.setFieldsToRedact(i);}e?.legacyRedactFields&&this.setFieldsToUnredact(e.legacyRedactFields),e?.userFields&&this.setFieldsToUnredact(e.userFields);}setFieldsToRedact(e){this.redactedFields.clear();['input[type="password"]','input[type="password" i]','[type="password"]','[type="password" i]',...e].forEach(e=>{this.redactedFields.add(e);}),this.redactedFields.size>0?o(`Redaction: Active for ${this.redactedFields.size} field(s):`,Array.from(this.redactedFields)):o("Redaction: No fields to redact"),this.applyRedactionClasses();}setFieldsToUnredact(e){this.unredactedFields.clear();const t=e.filter(e=>!this.isPasswordSelector(e)||(r(`Cannot unredact password field: ${e} - Password fields are always protected`),false));t.forEach(e=>this.unredactedFields.add(e)),t.length>0?o(`Unredaction: Active for ${t.length} field(s):`,t):o("Unredaction: No valid fields to unredact"),this.applyUnredactionClasses();}redactFields(e){e.forEach(e=>{this.unredactedFields.delete(e);}),this.unredactedFields.size>0?o(`Unredaction: Removed ${e.length} field(s), ${this.unredactedFields.size} remaining:`,Array.from(this.unredactedFields)):o("Unredaction: All fields redacted"),this.applyUnredactionClasses();}clearUnredactedFields(){this.unredactedFields.clear(),o("Unredaction: All fields cleared, everything redacted"),this.removeUnredactionClasses();}hasUnredactedFields(){return this.unredactedFields.size>0}getRedactionMode(){return this.redactionMode}getUnredactedFields(){return Array.from(this.unredactedFields)}getMaskTextSelector(){return "privacy-first"===this.redactionMode?0===this.unredactedFields.size?null:Array.from(this.unredactedFields).join(","):0===this.redactedFields.size?null:Array.from(this.redactedFields).join(",")}applyRedactionClasses(){0!==this.redactedFields.size&&("undefined"!=typeof document&&"loading"!==document.readyState?this.redactedFields.forEach(e=>{try{const t=document.querySelectorAll(e);t.forEach(e=>{e&&e.classList&&e.classList.add("rr-mask");}),o(`Added rr-mask class to ${t.length} element(s) for selector: ${e}`);}catch(t){r(`Invalid selector: ${e}`);}}):o("DOM not ready, deferring redaction class application"));}applyUnredactionClasses(){0!==this.unredactedFields.size&&("undefined"!=typeof document&&"loading"!==document.readyState?this.unredactedFields.forEach(e=>{try{const t=document.querySelectorAll(e);t.forEach(e=>{e&&e.classList&&e.classList.remove("rr-mask");}),o(`Removed rr-mask class from ${t.length} element(s) for selector: ${e}`);}catch(t){r(`Invalid selector: ${e}`);}}):o("DOM not ready, deferring unredaction class application"));}removeUnredactionClasses(){o("Unredaction classes removed");}isPasswordSelector(e){return ['input[type="password"]','input[type="password" i]','[type="password"]','[type="password" i]'].some(t=>e.toLowerCase().includes(t.toLowerCase().replace(/[\[\]]/g,"")))}getOriginalValue(e){if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement)return e.value}isElementUnredacted(e){return this.shouldUnredactElement(e)}shouldUnredactElement(e){if("privacy-first"===this.redactionMode){if(0===this.unredactedFields.size)return false;for(const t of this.unredactedFields)try{if(e.matches(t))return !0}catch(e){r(`Invalid selector: ${t}`);}return false}if(0===this.redactedFields.size)return true;for(const t of this.redactedFields)try{if(e.matches(t))return !1}catch(e){r(`Invalid selector: ${t}`);}return true}}new u;const p="undefined"!=typeof window;function m(){if(!p)return "unknown";const e=navigator.userAgent.toLowerCase(),t=window.screen.width,i=window.screen.height;return /mobile|android|iphone|ipad|ipod|blackberry|windows phone/i.test(e)?/ipad/i.test(e)||t>=768&&i>=1024?"tablet":"mobile":/windows|macintosh|linux/i.test(e)?"desktop":"unknown"}function g(e){try{return new URL(e).hostname}catch{return ""}}function f(){if(!p)return {device_type:"unknown",browser:"unknown",browser_version:"unknown",os:"unknown",os_version:"unknown",screen_resolution:"unknown",viewport_size:"unknown",color_depth:0,timezone:"unknown",language:"unknown",languages:[]};const{browser:e,browser_version:t}=function(){if(!p)return {browser:"unknown",browser_version:"unknown"};const e=navigator.userAgent;if(/chrome/i.test(e)&&!/edge/i.test(e)){const t=e.match(/chrome\/(\d+)/i);return {browser:"chrome",browser_version:t?t[1]:"unknown"}}if(/firefox/i.test(e)){const t=e.match(/firefox\/(\d+)/i);return {browser:"firefox",browser_version:t?t[1]:"unknown"}}if(/safari/i.test(e)&&!/chrome/i.test(e)){const t=e.match(/version\/(\d+)/i);return {browser:"safari",browser_version:t?t[1]:"unknown"}}if(/edge/i.test(e)){const t=e.match(/edge\/(\d+)/i);return {browser:"edge",browser_version:t?t[1]:"unknown"}}if(/msie|trident/i.test(e)){const t=e.match(/msie (\d+)/i)||e.match(/rv:(\d+)/i);return {browser:"ie",browser_version:t?t[1]:"unknown"}}return {browser:"unknown",browser_version:"unknown"}}(),{os:i,os_version:s}=function(){if(!p)return {os:"unknown",os_version:"unknown"};const e=navigator.userAgent;if(/windows/i.test(e)){const t=e.match(/windows nt (\d+\.\d+)/i);let i="unknown";if(t){const e=parseFloat(t[1]);i=10===e?"10":6.3===e?"8.1":6.2===e?"8":6.1===e?"7":t[1];}return {os:"windows",os_version:i}}if(/macintosh|mac os x/i.test(e)){const t=e.match(/mac os x (\d+[._]\d+)/i);return {os:"macos",os_version:t?t[1].replace("_","."):"unknown"}}if(/iphone|ipad|ipod/i.test(e)){const t=e.match(/os (\d+[._]\d+)/i);return {os:"ios",os_version:t?t[1].replace("_","."):"unknown"}}if(/android/i.test(e)){const t=e.match(/android (\d+\.\d+)/i);return {os:"android",os_version:t?t[1]:"unknown"}}return /linux/i.test(e)?{os:"linux",os_version:"unknown"}:{os:"unknown",os_version:"unknown"}}();return {device_type:m(),browser:e,browser_version:t,os:i,os_version:s,screen_resolution:`${window.screen.width}x${window.screen.height}`,viewport_size:`${window.innerWidth}x${window.innerHeight}`,color_depth:window.screen.colorDepth,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,language:navigator.language,languages:[...navigator.languages||[navigator.language]],raw_user_agent:navigator.userAgent}}function y(){if(!p)return {current_url:"",pathname:"",search:"",hash:"",title:"",referrer:"",referrer_domain:"",initial_referrer:"",initial_referrer_domain:""};const e=window.location.href,t=document.referrer,i=function(e){const t=new URL(e),i={};return ["utm_source","utm_medium","utm_campaign","utm_term","utm_content"].forEach(e=>{const s=t.searchParams.get(e);s&&(i[e]=s);}),i}(e);return {current_url:e,pathname:window.location.pathname,search:window.location.search,hash:window.location.hash,title:document.title,referrer:t,referrer_domain:g(t),initial_referrer:t,initial_referrer_domain:g(t),initial_host:window.location.hostname,...i}}function v(){return {...f(),...y()}}function w(){if(!p)return {};const e=y();return {initial_referrer:e.initial_referrer,initial_referrer_domain:e.initial_referrer_domain,initial_url:e.current_url,initial_pathname:e.pathname,initial_utm_source:e.utm_source,initial_utm_medium:e.utm_medium,initial_utm_campaign:e.utm_campaign,initial_utm_term:e.utm_term,initial_utm_content:e.utm_content}}function k(){if(!p)return {};const e=y();return {current_url:e.current_url,pathname:e.pathname,search:e.search,hash:e.hash,title:e.title,referrer:e.referrer,referrer_domain:e.referrer_domain,utm_source:e.utm_source,utm_medium:e.utm_medium,utm_campaign:e.utm_campaign,utm_term:e.utm_term,utm_content:e.utm_content}}class S{constructor(e={}){this.sessionProperties={},this.userProperties={},this.initialProperties={},this.isInitialized=false,this.config={enableAutomaticProperties:true,enableSessionProperties:true,enableUserProperties:true,propertyDenylist:[],...e},this.automaticProperties=v(),this.initialize();}initialize(){this.isInitialized||(this.initialProperties=w(),this.loadSessionProperties(),this.isInitialized=true);}getEventProperties(e={}){const t={...e};return this.config.enableAutomaticProperties&&Object.assign(t,this.getAutomaticProperties()),this.config.enableSessionProperties&&Object.assign(t,this.sessionProperties),this.config.enableUserProperties&&Object.assign(t,this.userProperties),this.sessionProperties.$initial_properties_captured||(Object.assign(t,this.initialProperties),this.setSessionProperty("$initial_properties_captured",true)),this.applyDenylist(t),t}getAutomaticProperties(){return {...this.automaticProperties,...k()}}getAutomaticPropertiesWithGeoIP(e={}){return {...this.automaticProperties,...k(),...e}}setSessionProperty(e,t){this.sessionProperties[e]=t,this.saveSessionProperties();}setSessionProperties(e){Object.assign(this.sessionProperties,e),this.saveSessionProperties();}getSessionProperty(e){return this.sessionProperties[e]}removeSessionProperty(e){delete this.sessionProperties[e],this.saveSessionProperties();}setUserProperty(e,t){this.userProperties[e]=t;}setUserProperties(e){Object.assign(this.userProperties,e);}getUserProperty(e){return this.userProperties[e]}removeUserProperty(e){delete this.userProperties[e];}setOnce(e,t,i="user"){"session"===i?e in this.sessionProperties||this.setSessionProperty(e,t):e in this.userProperties||this.setUserProperty(e,t);}clearSessionProperties(){this.sessionProperties={},this.saveSessionProperties();}clearUserProperties(){this.userProperties={};}reset(){this.clearSessionProperties(),this.clearUserProperties(),this.initialProperties={},this.isInitialized=false,this.initialize();}loadSessionProperties(){if("undefined"!=typeof sessionStorage)try{const e=sessionStorage.getItem("hb_session_properties");e&&(this.sessionProperties=JSON.parse(e));}catch(e){console.warn("Failed to load session properties:",e);}}saveSessionProperties(){if("undefined"!=typeof sessionStorage)try{sessionStorage.setItem("hb_session_properties",JSON.stringify(this.sessionProperties));}catch(e){console.warn("Failed to save session properties:",e);}}applyDenylist(e){this.config.propertyDenylist&&0!==this.config.propertyDenylist.length&&this.config.propertyDenylist.forEach(t=>{delete e[t];});}updateAutomaticProperties(){this.automaticProperties=v();}getAllProperties(){return {automatic:this.getAutomaticProperties(),session:{...this.sessionProperties},user:{...this.userProperties},initial:{...this.initialProperties}}}}const _="undefined"!=typeof window;class C{get isTrackerStarted(){return this.isStarted}setupDomReadyHandler(){if(_)if("complete"===document.readyState||"interactive"===document.readyState)this.onDomReady();else if(document.addEventListener){document.addEventListener("DOMContentLoaded",()=>this.onDomReady(),{capture:false});const e=setInterval(()=>{"interactive"!==document.readyState&&"complete"!==document.readyState||(clearInterval(e),this.onDomReady());},10);setTimeout(()=>clearInterval(e),5e3);}else this.onDomReady();else this.onDomReady();}onDomReady(){this.isDomReady||(this.isDomReady=true,o("🎯 DOM is ready, processing queued requests"),this.requestQueue.forEach(e=>{this.processRequest(e);}),this.requestQueue=[],this.domReadyHandlers.forEach(e=>e()),this.domReadyHandlers=[]);}queueRequest(e){this.isDomReady?this.processRequest(e):this.requestQueue.push(e);}async processRequest(e){switch(o("Processing queued request:",e),e.type){case "addEvent":await this.addEvent(e.event);break;case "identifyUser":await this.identifyUser(e.userProperties);break;case "trackPageView":this.trackPageView();break;default:r("Unknown request type:",e.type);}}registerDomReadyHandler(e){this.isDomReady?e():this.domReadyHandlers.push(e);}static init(e,t){if(_&&false!==t?.suppressConsoleErrors){const e=console.error;console.error=(...t)=>{const i=t.join(" ");i.includes("SecurityError: Failed to execute 'toDataURL'")||i.includes("Tainted canvases may not be exported")||i.includes("Cannot inline img src=")||i.includes("Cross-Origin")||i.includes("CORS")||i.includes("Access-Control-Allow-Origin")||i.includes("Failed to load resource")||i.includes("net::ERR_BLOCKED_BY_CLIENT")||i.includes("NetworkError when attempting to fetch resource")||i.includes("Failed to fetch")||i.includes("TypeError: NetworkError")||i.includes("HumanBehavior ERROR")||i.includes("Failed to track custom event")||i.includes("Error sending custom event")||e.apply(console,t);};const t=console.warn;console.warn=(...e)=>{const i=e.join(" ");i.includes("Cannot inline img src=")||i.includes("Cross-Origin")||i.includes("CORS")||i.includes("Access-Control-Allow-Origin")||i.includes("Failed to load resource")||i.includes("net::ERR_BLOCKED_BY_CLIENT")||i.includes("NetworkError when attempting to fetch resource")||i.includes("Failed to fetch")||i.includes("Custom event network error")||i.includes("Request blocked by ad blocker")||t.apply(console,e);},window.addEventListener("error",e=>{const t=e.message||"";if(t.includes("SecurityError")||t.includes("Tainted canvases")||t.includes("toDataURL")||t.includes("Cross-Origin")||t.includes("CORS")||t.includes("NetworkError")||t.includes("Failed to fetch"))return e.preventDefault(),false});}if(_&&window.__humanBehaviorGlobalTracker)return o("Tracker already initialized, returning existing instance"),window.__humanBehaviorGlobalTracker;t?.logLevel&&this.configureLogging({level:t.logLevel});const i=new C(e,t?.ingestionUrl,{enableAutomaticProperties:t?.enableAutomaticProperties,propertyDenylist:t?.propertyDenylist,redactionStrategy:t?.redactionStrategy,redactFields:t?.redactFields,maxQueueSize:t?.maxQueueSize});return i.recordCanvas=t?.recordCanvas??false,t?.redactFields&&i.setUnredactedFields(t.redactFields),false!==t?.enableAutomaticTracking&&i.setupAutomaticTracking(t?.automaticTrackingOptions),i.start(),i}constructor(e,i,s){if(this.eventQueue=[],this.userProperties={},this.isProcessing=false,this.flushInterval=null,this.FLUSH_INTERVAL_MS=3e3,this.endUserId=null,this.initialized=false,this.initializationPromise=null,this.monthlyLimitReached=false,this.isDomReady=false,this.requestQueue=[],this.domReadyHandlers=[],this.originalConsole=null,this.consoleTrackingEnabled=false,this.navigationTrackingEnabled=false,this.currentUrl="",this.previousUrl="",this.originalPushState=null,this.originalReplaceState=null,this.navigationListeners=[],this._connectionBlocked=false,this.recordInstance=null,this.sessionStartTime=Date.now(),this.rrwebRecord=null,this.fullSnapshotTimeout=null,this.recordCanvas=false,this.isStarted=false,this.rageClickTracker={clicks:[]},this.RAGE_CLICK_THRESHOLD_PX=30,this.RAGE_CLICK_TIMEOUT_MS=1e3,this.RAGE_CLICK_CLICK_COUNT=3,this.deadClickTracker={pendingClicks:new Map},this.DEAD_CLICK_SCROLL_THRESHOLD_MS=100,this.DEAD_CLICK_SELECTION_THRESHOLD_MS=100,this.DEAD_CLICK_MUTATION_THRESHOLD_MS=2e3,this.DEAD_CLICK_ABSOLUTE_TIMEOUT_MS=1400,!e)throw new Error("Human Behavior API Key is required");if(this.api=new h({apiKey:e,ingestionUrl:i||"https://ingest.humanbehavior.co"}),this.apiKey=e,this.MAX_QUEUE_SIZE=s?.maxQueueSize??1e3,this.redactionManager=new u({redactionStrategy:s?.redactionStrategy,legacyRedactFields:s?.redactFields}),this.propertyManager=new S({enableAutomaticProperties:false!==s?.enableAutomaticProperties,propertyDenylist:s?.propertyDenylist||[]}),_){const e=localStorage.getItem(`human_behavior_session_id_${this.apiKey}`),i=localStorage.getItem(`human_behavior_last_activity_${this.apiKey}`),s=Date.now()-9e5;e&&i&&parseInt(i)>s?(this.sessionId=e,o(`Reusing existing session: ${this.sessionId}`),localStorage.setItem(`human_behavior_last_activity_${this.apiKey}`,Date.now().toString())):(e&&(o(`Session expired, clearing old session: ${e}`),localStorage.removeItem(`human_behavior_session_id_${this.apiKey}`),localStorage.removeItem(`human_behavior_last_activity_${this.apiKey}`)),this.sessionId=v1(),o(`Creating new session: ${this.sessionId}`),localStorage.setItem(`human_behavior_session_id_${this.apiKey}`,this.sessionId),localStorage.setItem(`human_behavior_last_activity_${this.apiKey}`,Date.now().toString())),this.currentUrl=window.location.href,window.__humanBehaviorGlobalTracker=this;}else this.sessionId=v1();this.initializationPromise=this.init().catch(e=>{n("Background initialization failed:",e);});}async init(){try{const e=_?this.getCookie(`human_behavior_end_user_id_${this.apiKey}`):null;o(`Initializing with sessionId: ${this.sessionId}, userId: ${e}`);const t=this.propertyManager.getAutomaticProperties();_?(this.setupPageUnloadHandler(),this.setupNavigationTracking()):a("HumanBehaviorTracker initialized in server environment. Session tracking is disabled."),await this.initServerAsync(e,t),this.initialized=!0,a(`HumanBehaviorTracker initialized with sessionId: ${this.sessionId}`);}catch(e){n("Failed to initialize HumanBehaviorTracker:",e),this.initialized=true;}}async initServerAsync(e,t){try{o("🚀 Attempting to call /init endpoint..."),o("📡 URL:",`${this.api.baseUrl}/api/ingestion/init`),o("🔑 API Key:",this.apiKey);let i=null,s=null;_&&(i=window.location.href,s=document.referrer),o("📦 Payload:",{sessionId:this.sessionId,endUserId:e,entryURL:i,referrer:s,automaticProperties:t});const n=await fetch(`${this.api.baseUrl}/api/ingestion/init`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,Referer:s||""},body:JSON.stringify({sessionId:this.sessionId,endUserId:e,entryURL:i,referrer:s,automaticProperties:t})});if(!n.ok)throw new Error(`Failed to initialize: ${n.statusText}`);const{sessionId:r,endUserId:c}=await n.json();r!==this.sessionId&&(o(`Server returned different sessionId: ${r} (client had: ${this.sessionId})`),this.sessionId=r,_&&localStorage.setItem(`human_behavior_session_id_${this.apiKey}`,this.sessionId)),null!=c?(this.endUserId=c,this.setCookie(`human_behavior_end_user_id_${this.apiKey}`,c,365),a(`Server initialization completed with endUserId: ${c}`)):o(`Server returned null endUserId, preserving existing value: ${this.endUserId||"none"}`);}catch(e){n("❌ Server initialization failed:",e),n("🔍 Error details:",{message:e?.message||"Unknown error",stack:e?.stack||"No stack trace",type:e?.constructor?.name||"Unknown type"}),r("Server initialization failed, continuing with local session:",e);}}async ensureInitialized(){this.initializationPromise&&await this.initializationPromise;}setupNavigationTracking(){if(!_||this.navigationTrackingEnabled)return;this.navigationTrackingEnabled=true,o("Setting up navigation tracking"),this.originalPushState=history.pushState,this.originalReplaceState=history.replaceState,history.pushState=(...e)=>{this.previousUrl=this.currentUrl,this.currentUrl=window.location.href,this.originalPushState.apply(history,e),this.trackNavigationEvent("pushState",this.previousUrl,this.currentUrl),this.takeFullSnapshot();},history.replaceState=(...e)=>{this.previousUrl=this.currentUrl,this.currentUrl=window.location.href,this.originalReplaceState.apply(history,e),this.trackNavigationEvent("replaceState",this.previousUrl,this.currentUrl),this.takeFullSnapshot();};const e=()=>{this.previousUrl=this.currentUrl,this.currentUrl=window.location.href,this.trackNavigationEvent("popstate",this.previousUrl,this.currentUrl),this.takeFullSnapshot();};window.addEventListener("popstate",e),this.navigationListeners.push(()=>{window.removeEventListener("popstate",e);});const t=()=>{this.previousUrl=this.currentUrl,this.currentUrl=window.location.href,this.trackNavigationEvent("hashchange",this.previousUrl,this.currentUrl);};window.addEventListener("hashchange",t),this.navigationListeners.push(()=>{window.removeEventListener("hashchange",t);}),this.trackNavigationEvent("pageLoad","",this.currentUrl);}async trackNavigationEvent(e,t,i){if(this.initialized)try{const s={type:e,from:t,to:i,timestamp:(new Date).toISOString(),pathname:window.location.pathname,search:window.location.search,hash:window.location.hash,referrer:document.referrer};if(await this.addEvent({type:5,data:{payload:{eventType:"navigation",...s}},timestamp:Date.now()}),"pageLoad"===e||"pushState"===e||"replaceState"===e||"popstate"===e||"hashchange"===e){const i={url:window.location.href,fromUrl:t,navigationType:e,pathname:window.location.pathname,search:window.location.search,hash:window.location.hash,referrer:document.referrer,timestamp:Date.now()};await this.customEvent("$page_viewed",i);}o(`Navigation tracked: ${e} from ${t} to ${i}`);}catch(e){n("Failed to track navigation event:",e);}}async trackPageView(e){if(this.initialized){this.propertyManager.updateAutomaticProperties();try{const t={url:e||window.location.href,pathname:window.location.pathname,search:window.location.search,hash:window.location.hash,referrer:document.referrer,timestamp:(new Date).toISOString()},i=this.propertyManager.getEventProperties(t);await this.addEvent({type:5,data:{payload:{eventType:"pageview",...i}},timestamp:Date.now()}),o(`Pageview tracked: ${t.url}`);}catch(e){n("Failed to track pageview event:",e);}}}async customEvent(e,t){if(!this.initialized||!this.endUserId)return void o(`Waiting for initialization/endUserId before tracking custom event: ${e}. Initialized: ${this.initialized}, endUserId: ${this.endUserId?"available":"null"}`);const i=this.propertyManager.getEventProperties(t);try{await this.api.sendCustomEvent(this.sessionId,e,i,this.endUserId),o(`Custom event tracked: ${e}`,i);}catch(t){n("Failed to track custom event:",t),t.message?.includes("500")||t.message?.includes("Internal Server Error")||t.message?.includes("Failed to send custom event")?r("Custom event endpoint failed, using fallback"):t.message?.includes("ERR_BLOCKED_BY_CLIENT")?r("Custom event request blocked by ad blocker, using fallback"):t.message?.includes("Failed to fetch")&&r("Custom event network error, using fallback");try{const t={eventName:e,properties:i||{},timestamp:(new Date).toISOString(),url:window.location.href,pathname:window.location.pathname};await this.addEvent({type:5,data:{payload:{eventType:"custom",...t}},timestamp:Date.now()}),o(`Custom event added to event stream as fallback: ${e}`);}catch(e){n("Failed to add custom event to event stream as fallback:",e);}}}setupAutomaticTracking(e){if(!_)return;const t={trackButtons:false!==e?.trackButtons,trackLinks:false,trackForms:false!==e?.trackForms,includeText:false!==e?.includeText,includeClasses:e?.includeClasses||false};o("Setting up automatic tracking with config:",t),t.trackButtons&&this.setupAutomaticButtonTracking(t),t.trackForms&&this.setupAutomaticFormTracking(t),this.setupRageClickDetection(),this.setupDeadClickDetection();}setupAutomaticButtonTracking(e){document.addEventListener("click",async t=>{const i=t.target;if("BUTTON"===i.tagName||i.closest("button")){const t="BUTTON"===i.tagName?i:i.closest("button"),s={buttonId:t.id||null,buttonType:t.type||"button",page:window.location.pathname,timestamp:Date.now()};e.includeText&&(s.buttonText=t.textContent?.trim()||null),e.includeClasses&&(s.buttonClass=t.className||null),Object.keys(s).forEach(e=>{null===s[e]&&delete s[e];}),await this.customEvent("$button_clicked",s);}});}setupRageClickDetection(){_&&document.addEventListener("click",async e=>{const t=e.target,i=e.clientX,s=e.clientY,n=Date.now();if(this.isRageClick(i,s,n,t)){const e=t.closest('button, a, [role="button"], [role="link"]')||t,r={x:i,y:s,page:window.location.pathname,element:e.tagName.toLowerCase(),clickCount:this.RAGE_CLICK_CLICK_COUNT,timestamp:n};e.id&&(r.elementId=e.id),e.className&&(r.elementClass=e.className),e.textContent&&(r.elementText=e.textContent.trim().substring(0,100)),Object.keys(r).forEach(e=>{null!==r[e]&&void 0!==r[e]||delete r[e];}),await this.customEvent("$rageclick",r),this.rageClickTracker.clicks=[];}});}isRageClick(e,t,i,s){const n=this.rageClickTracker.clicks,r=n[n.length-1];if(r&&Math.abs(e-r.x)+Math.abs(t-r.y)<this.RAGE_CLICK_THRESHOLD_PX&&i-r.timestamp<this.RAGE_CLICK_TIMEOUT_MS){if(n.push({x:e,y:t,timestamp:i,element:s}),n.length>=this.RAGE_CLICK_CLICK_COUNT)return true}else this.rageClickTracker.clicks=[{x:e,y:t,timestamp:i,element:s}];return false}setupDeadClickDetection(){_&&(this.setupDeadClickMutationObserver(),this.setupDeadClickScrollObserver(),this.setupDeadClickSelectionObserver(),this.setupDeadClickNavigationTracking(),document.addEventListener("click",e=>{const t=e.target;if(!t)return;if(!this.isInteractiveElement(t))return;if(this.ignoreClickForDeadDetection(t))return;const i=Date.now()+Math.random(),s=Date.now(),n=this.deadClickTracker.lastMutationTime,r=this.DEAD_CLICK_ABSOLUTE_TIMEOUT_MS,a=window.setTimeout(()=>{this.handleDeadClickTimeout(i);},r);this.deadClickTracker.pendingClicks.set(i,{element:t,originalEvent:e,timestamp:s,timer:a,cancelled:false,lastMutationTimeAtClick:n});}));}setupDeadClickMutationObserver(){_&&(this.deadClickTracker.mutationObserver||(this.deadClickTracker.mutationObserver=new MutationObserver(()=>{const e=Date.now();this.deadClickTracker.lastMutationTime=e,this.deadClickTracker.pendingClicks.forEach((t,i)=>{if(t.cancelled)return;const s=e-t.timestamp,n=t.lastMutationTimeAtClick||0,r=e>n,a=s>=0&&s<this.DEAD_CLICK_MUTATION_THRESHOLD_MS,o=s<0&&Math.abs(s)<50;(a&&r||o)&&this.cancelPendingClick(i);});}),this.deadClickTracker.mutationObserver.observe(document,{attributes:true,characterData:true,childList:true,subtree:true})));}setupDeadClickScrollObserver(){_&&window.addEventListener("scroll",()=>{const e=Date.now();this.deadClickTracker.pendingClicks.forEach((t,i)=>{e-t.timestamp<this.DEAD_CLICK_SCROLL_THRESHOLD_MS&&this.cancelPendingClick(i);});},{capture:true,passive:true});}setupDeadClickSelectionObserver(){_&&document.addEventListener("selectionchange",()=>{const e=Date.now();this.deadClickTracker.lastSelectionChangedTime=e,this.deadClickTracker.pendingClicks.forEach((t,i)=>{e-t.timestamp<this.DEAD_CLICK_SELECTION_THRESHOLD_MS&&this.cancelPendingClick(i);});});}setupDeadClickNavigationTracking(){if(!_)return;let e=window.location.href;const t=this.trackNavigationEvent.bind(this);this.trackNavigationEvent=async(i,s,n)=>(this.cancelAllPendingClicks(),e=window.location.href,t(i,s,n));const i=()=>{const t=window.location.href;t!==e&&(this.cancelAllPendingClicks(),e=t);};window.addEventListener("popstate",i),window.addEventListener("hashchange",i),window.addEventListener("beforeunload",()=>{this.cancelAllPendingClicks();}),setInterval(()=>{i();},100);}isInteractiveElement(e){const t=e.tagName.toLowerCase();if("button"===t||"a"===t)return true;if(["input","select","textarea"].includes(t))return true;const i=e.getAttribute("role");if(i&&["button","link","tab","menuitem","checkbox","radio"].includes(i))return true;if(e.onclick||e.getAttribute("onclick"))return true;try{if("pointer"===window.getComputedStyle(e).cursor)return !0}catch(e){}return !!e.closest('button, a, [role="button"], [role="link"], [role="tab"], [role="menuitem"]')}ignoreClickForDeadDetection(e){if("html"===e.tagName.toLowerCase())return true;const t=Date.now();for(const i of this.deadClickTracker.pendingClicks.values())if(i.element===e&&Math.abs(t-i.timestamp)<1e3)return true;return false}cancelPendingClick(e){const t=this.deadClickTracker.pendingClicks.get(e);t&&!t.cancelled&&(clearTimeout(t.timer),t.cancelled=true,this.deadClickTracker.pendingClicks.delete(e));}cancelAllPendingClicks(){this.deadClickTracker.pendingClicks.forEach((e,t)=>{e.cancelled||(clearTimeout(e.timer),this.deadClickTracker.pendingClicks.delete(t));});}async handleDeadClickTimeout(e){const t=this.deadClickTracker.pendingClicks.get(e);if(!t||t.cancelled)return;const i=Date.now()-t.timestamp;let s;const n=t.lastMutationTimeAtClick||0,r=this.deadClickTracker.lastMutationTime||0,a=r>n&&r>=t.timestamp,o=n>0&&n<t.timestamp&&t.timestamp-n<50;let c;a?s=r-t.timestamp:o&&(s=0),this.deadClickTracker.lastSelectionChangedTime&&t.timestamp<=this.deadClickTracker.lastSelectionChangedTime&&(c=this.deadClickTracker.lastSelectionChangedTime-t.timestamp);const l=void 0!==s&&s<this.DEAD_CLICK_MUTATION_THRESHOLD_MS,d=void 0!==c&&c<this.DEAD_CLICK_SELECTION_THRESHOLD_MS;l||d||await this.fireDeadClickEvent(t,i,s,c),this.deadClickTracker.pendingClicks.delete(e);}async fireDeadClickEvent(e,t,i,s){const n=e.element.closest('button, a, [role="button"], [role="link"]')||e.element,r={x:e.originalEvent.clientX,y:e.originalEvent.clientY,page:window.location.pathname,element:n.tagName.toLowerCase(),absoluteDelayMs:t,timestamp:e.timestamp};void 0!==i&&(r.mutationDelayMs=i),void 0!==s&&(r.selectionChangedDelayMs=s),n.id&&(r.elementId=n.id),n.className&&(r.elementClass=n.className),n.textContent&&(r.elementText=n.textContent.trim().substring(0,100)),Object.keys(r).forEach(e=>{null!==r[e]&&void 0!==r[e]||delete r[e];}),await this.customEvent("$deadclick",r);}setupAutomaticLinkTracking(e){}setupAutomaticFormTracking(e){document.addEventListener("submit",async t=>{const i=t.target,s=new FormData(i),n={formId:i.id||null,formAction:i.action||null,formMethod:i.method||"get",fields:Array.from(s.keys()),page:window.location.pathname,timestamp:Date.now()};e.includeClasses&&(n.formClass=i.className||null),Object.keys(n).forEach(e=>{null===n[e]&&delete n[e];}),await this.customEvent("$form_submitted",n);});}cleanupNavigationTracking(){this.navigationTrackingEnabled&&(this.originalPushState&&(history.pushState=this.originalPushState),this.originalReplaceState&&(history.replaceState=this.originalReplaceState),this.navigationListeners.forEach(e=>e()),this.navigationListeners=[],this.navigationTrackingEnabled=false,o("Navigation tracking cleaned up"));}static logToStorage(e){a(e);}static configureLogging(e){s.setConfig({level:{none:0,error:1,warn:2,info:3,debug:4}[e.level||"error"],enableConsole:false!==e.enableConsole,enableStorage:e.enableStorage||false});}enableConsoleTracking(){_&&!this.consoleTrackingEnabled&&(this.originalConsole={log:console.log,warn:console.warn,error:console.error},console.log=(...e)=>{this.trackConsoleEvent("log",e),this.originalConsole.log(...e);},console.warn=(...e)=>{this.trackConsoleEvent("warn",e),this.originalConsole.warn(...e);},console.error=(...e)=>{this.trackConsoleEvent("error",e),this.originalConsole.error(...e);},this.consoleTrackingEnabled=true,o("Console tracking enabled"));}disableConsoleTracking(){_&&this.consoleTrackingEnabled&&(this.originalConsole&&(console.log=this.originalConsole.log,console.warn=this.originalConsole.warn,console.error=this.originalConsole.error),this.consoleTrackingEnabled=false,o("Console tracking disabled"));}trackConsoleEvent(e,t){if(this.initialized)try{const i={level:e,message:t.map(e=>"object"==typeof e?JSON.stringify(e):String(e)).join(" "),timestamp:(new Date).toISOString(),url:window.location.href};this.addEvent({type:5,data:{payload:{eventType:"console",...i}},timestamp:Date.now()}).catch(e=>{n("Failed to track console event:",e);});}catch(e){n("Error in trackConsoleEvent:",e);}}setupPageUnloadHandler(){if(!_)return;o("Setting up page unload handler"),window.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState&&(o("Page hidden - sending pending events"),this.flushEvents());}),window.addEventListener("beforeunload",()=>{this.flushEvents();});const e=()=>{localStorage.setItem(`human_behavior_last_activity_${this.apiKey}`,Date.now().toString());};window.addEventListener("click",e),window.addEventListener("keydown",e),window.addEventListener("scroll",e),window.addEventListener("mousemove",e);}viewLogs(){try{const e=s.getLogs();a("HumanBehavior Logs:",e),s.clearLogs();}catch(e){n("Failed to read logs:",e);}}async identifyUser({userProperties:e}){await this.ensureInitialized();const t=this.endUserId;this.userProperties=e,o("Identifying user:",{userProperties:e,originalEndUserId:t,sessionId:this.sessionId}),!_||this.propertyManager.getAutomaticProperties();const i=await this.api.sendUserData(t||"",e,this.sessionId);if(i.actualUserId||i.wasExistingUser){const e=i.actualUserId||t;if(e&&e!==t){const i=`human_behavior_end_user_id_${this.apiKey}`;if(this.setCookie(i,e,365),_)try{localStorage.setItem(i,e);}catch(e){o("Failed to set canonical endUserId in localStorage:",e);}o(`🔗 Preexisting user detected. Future sessions will use canonical ID: ${e} (current session stays: ${t})`);}}return t||""}getUserAttributes(){return {...this.userProperties}}async start(){if(await this.ensureInitialized(),!_)return;if(this.isStarted)return void o("HumanBehaviorTracker already started, skipping start() call.");this.isStarted=true,this.flushInterval=window.setInterval(()=>{this.flushEvents();},this.FLUSH_INTERVAL_MS);const t=()=>{if(this.recordInstance)return void o("🎯 Recording already started, skipping duplicate start");o("🎯 DOM ready, starting session recording"),this.rrwebRecord=record;const t=record({emit:e=>{this.addRecordingEvent(e),2===e.type&&o(`🎯 FullSnapshot generated at ${(new Date).toISOString()}`);},maskTextSelector:this.redactionManager.getMaskTextSelector()||void 0,maskTextFn:void 0,maskAllInputs:"privacy-first"===this.redactionManager.getRedactionMode(),maskInputOptions:{password:true,text:true,textarea:true,email:true,number:true,tel:true,url:true,search:true,date:true,time:true,month:true,week:true},maskInputFn:(e,t)=>{try{const i=this.redactionManager.getRedactionMode();if(!(t instanceof HTMLElement))return e;if("privacy-first"===i)return "*".repeat(e.length||1);const s=this.redactionManager.shouldUnredactElement(t);t.id,t.name,t.type;return s?e:"*".repeat(e.length||1)}catch{return e}},slimDOMOptions:{},collectFonts:false,inlineStylesheet:true,recordCrossOriginIframes:false,recordCanvas:this.recordCanvas,sampling:this.recordCanvas?{canvas:4}:void 0,dataURLOptions:this.recordCanvas?{type:"image/webp",quality:.4}:void 0,hooks:{input:e=>{try{if("privacy-first"===this.redactionManager.getRedactionMode())return;const t="undefined"!=typeof document?document.querySelector(`[data-rrweb-id="${e.id}"]`):null;if(t&&t instanceof HTMLElement){this.redactionManager.shouldUnredactElement(t)||(void 0!==e.text&&(e.text="*".repeat(e.text?.length||1)),void 0!==e.value&&(e.value="*".repeat(e.value?.length||1)));}}catch{}}}});this.recordInstance=t||null;};if(o(`🎯 DOM ready state: ${document.readyState}`),"complete"===document.readyState||"interactive"===document.readyState)o(`🎯 DOM ready (${document.readyState}), starting recording immediately`),t();else {o("🎯 DOM not ready, waiting for DOMContentLoaded event");const e=()=>("interactive"===document.readyState||"complete"===document.readyState)&&(o(`🎯 DOM ready (${document.readyState}), starting recording`),t(),true);if(e())return;document.addEventListener("DOMContentLoaded",()=>{o("🎯 DOMContentLoaded fired, starting recording"),t();},{once:true});const i=setInterval(()=>{e()&&clearInterval(i);},10);setTimeout(()=>clearInterval(i),5e3);}}takeFullSnapshot(){this.fullSnapshotTimeout&&clearTimeout(this.fullSnapshotTimeout),this.fullSnapshotTimeout=window.setTimeout(()=>{try{requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.rrwebRecord&&"function"==typeof this.rrwebRecord.takeFullSnapshot?(this.rrwebRecord.takeFullSnapshot(),o("✅ FullSnapshot taken for navigation (delayed for animations)")):r("⚠️ takeFullSnapshot not available on record function");});});}catch(e){n("❌ Failed to take FullSnapshot for navigation:",e);}},1e3);}async stop(){await this.ensureInitialized(),_&&(this.flushInterval&&(clearInterval(this.flushInterval),this.flushInterval=null),this.recordInstance&&(this.recordInstance(),this.recordInstance=null),this.fullSnapshotTimeout&&(clearTimeout(this.fullSnapshotTimeout),this.fullSnapshotTimeout=null),this.rrwebRecord=null,this.disableConsoleTracking(),this.cleanupNavigationTracking(),this.deadClickTracker.mutationObserver&&(this.deadClickTracker.mutationObserver.disconnect(),this.deadClickTracker.mutationObserver=void 0),this.deadClickTracker.pendingClicks.forEach((e,t)=>{e.cancelled||clearTimeout(e.timer);}),this.deadClickTracker.pendingClicks.clear());}async addEvent(e){if(await this.ensureInitialized(),e&&"object"==typeof e){if(2===e.type){const t=!!e.data,i=!(!e.data||!e.data.node);o(t&&i?`✅ Valid FullSnapshot: hasData=${t}, hasNode=${i}, dataType=${e.data?.node?.type}`:`⚠️ Empty FullSnapshot detected: hasData=${t}, hasNode=${i} - continuing session`);}this.eventQueue.length>=this.MAX_QUEUE_SIZE&&(this.eventQueue.shift(),o("Queue is full, the oldest event is dropped.")),this.eventQueue.push(e),2===e.type?(o("FullSnapshot added, triggering immediate flush"),this.flushEvents()):this.eventQueue.length>=.8*this.MAX_QUEUE_SIZE&&(o(`Queue at ${this.eventQueue.length}/${this.MAX_QUEUE_SIZE}, triggering immediate flush`),this.flushEvents());}else o("⚠️ Skipping invalid event:",e);}async flushEvents(){if(!this.isProcessing&&this.initialized&&!this.monthlyLimitReached){this.isProcessing=true;try{const e=this.eventQueue;if(this.eventQueue=[],e.length>0){o("Flushing events:",e);const t=e.filter(e=>2===e.type);t.length>0&&o(`[FIXED] Sending ${t.length} FullSnapshot(s) with valid data`);try{await this.api.sendEventsChunked(e,this.sessionId,this.endUserId);}catch(e){if(e.message?.includes("ERROR: Session already completed"))r("Session expired, events will be lost");else if(e.message?.includes("413")||e.message?.includes("Content Too Large"))r("Payload too large, events will be lost");else {if(!(e.message?.includes("ERR_BLOCKED_BY_CLIENT")||e.message?.includes("Failed to fetch")||e.message?.includes("NetworkError")))throw e;r("Request blocked by ad blocker or network issue, events will be lost");}}}}finally{this.isProcessing=false;}}}async addRecordingEvent(e){if(await this.ensureInitialized(),e&&"object"==typeof e){if(2===e.type){const t=!!e.data,i=!(!e.data||!e.data.node);o(t&&i?`✅ Valid FullSnapshot: hasData=${t}, hasNode=${i}, dataType=${e.data?.node?.type}`:`⚠️ Empty FullSnapshot detected: hasData=${t}, hasNode=${i} - continuing session`);}this.eventQueue.length>=this.MAX_QUEUE_SIZE&&(this.eventQueue.shift(),o("Queue is full, the oldest event is dropped.")),this.eventQueue.push(e),2===e.type?(o("FullSnapshot added, triggering immediate flush"),this.flushEvents()):this.eventQueue.length>=.8*this.MAX_QUEUE_SIZE&&(o(`Queue at ${this.eventQueue.length}/${this.MAX_QUEUE_SIZE}, triggering immediate flush`),this.flushEvents());}else o("⚠️ Skipping invalid recording event:",e);}setCookie(e,t,i){if(_)try{const s=new Date;s.setTime(s.getTime()+24*i*60*60*1e3);const n=`expires=${s.toUTCString()}`;document.cookie=`${e}=${t};${n};path=/;SameSite=Lax`,localStorage.setItem(e,t),o(`Set cookie and localStorage: ${e}`);}catch(i){try{localStorage.setItem(e,t),o(`Cookie blocked, using localStorage: ${e}`);}catch(e){n("Failed to store user ID in both cookie and localStorage:",e);}}}getCookie(e){if(!_)return null;try{const t=e+"=",i=document.cookie.split(";");for(let s=0;s<i.length;s++){let n=i[s];for(;" "===n.charAt(0);)n=n.substring(1,n.length);if(0===n.indexOf(t)){const i=n.substring(t.length,n.length);return o(`Found cookie: ${e}`),i}}const s=localStorage.getItem(e);return s?(o(`Cookie not found, using localStorage: ${e}`),s):null}catch(t){try{const t=localStorage.getItem(e);if(t)return o(`Cookie access failed, using localStorage: ${e}`),t}catch(e){n("Failed to access both cookie and localStorage:",e);}return null}}deleteCookie(e){if(_){try{document.cookie=`${e}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; SameSite=Lax`,o(`Deleted cookie: ${e}`);}catch(t){n(`Failed to delete cookie: ${e}`,t);}try{localStorage.removeItem(e),o(`Removed from localStorage: ${e}`);}catch(t){n(`Failed to remove from localStorage: ${e}`,t);}}}logout(){if(_)try{const e=`human_behavior_end_user_id_${this.apiKey}`;this.deleteCookie(e),localStorage.removeItem(`human_behavior_session_id_${this.apiKey}`),localStorage.removeItem(`human_behavior_last_activity_${this.apiKey}`),this.endUserId=null,this.userProperties={},this.sessionId=v1(),_&&(localStorage.setItem(`human_behavior_session_id_${this.apiKey}`,this.sessionId),localStorage.setItem(`human_behavior_last_activity_${this.apiKey}`,Date.now().toString())),a("User logged out - cleared all user data and started fresh session");}catch(e){n("Error during logout:",e);}}async redact(e){await this.ensureInitialized(),_?this.redactionManager=new u(e):r("Redaction is only available in browser environments");}setRedactedFields(e){this.redactionManager.setFieldsToRedact(e),this.recordInstance&&this.restartWithNewRedaction();}setUnredactedFields(e){this.redactionManager.setFieldsToUnredact(e),this.recordInstance&&this.restartWithNewRedaction();}restartWithNewRedaction(){this.recordInstance&&(this.recordInstance(),this.start());}hasUnredactedFields(){return this.redactionManager.hasUnredactedFields()}getUnredactedFields(){return this.redactionManager.getUnredactedFields()}redactFields(e){this.redactionManager.redactFields(e),this.recordInstance&&this.restartWithNewRedaction();}clearUnredactedFields(){this.redactionManager.clearUnredactedFields(),this.recordInstance&&this.restartWithNewRedaction();}getSessionId(){return this.sessionId}getCurrentUrl(){return this.currentUrl}getSnapshotFrequencyInfo(){return {sessionDuration:Date.now()-this.sessionStartTime,currentInterval:3e5,currentThreshold:1e3,phase:"configured"}}async testConnection(){try{return await this.api.init(this.sessionId,this.endUserId),{success:!0}}catch(e){return {success:false,error:e.message||"Unknown error"}}}getConnectionStatus(){const e=[];let t=false;return this.eventQueue.length>0&&(t=true,e.push("Some requests may be blocked by ad blockers")),this._connectionBlocked&&(t=true,e.push("Initial connection test failed - ad blocker may be active")),"undefined"==typeof window&&e.push("Not running in browser environment"),void 0===navigator.sendBeacon&&e.push("sendBeacon not available, using fetch fallback"),{blocked:t,recommendations:e}}isPreexistingUser(){if(!_)return false;const e=this.getCookie(`human_behavior_end_user_id_${this.apiKey}`);return null!==e&&e!==this.endUserId}getUserInfo(){return {endUserId:this.endUserId,sessionId:this.sessionId,isPreexistingUser:this.isPreexistingUser(),initialized:this.initialized}}setSessionProperty(e,t){this.propertyManager.setSessionProperty(e,t);}setSessionProperties(e){this.propertyManager.setSessionProperties(e);}getSessionProperty(e){return this.propertyManager.getSessionProperty(e)}removeSessionProperty(e){this.propertyManager.removeSessionProperty(e);}setUserProperty(e,t){this.propertyManager.setUserProperty(e,t);}setUserProperties(e){this.propertyManager.setUserProperties(e);}getUserProperty(e){return this.propertyManager.getUserProperty(e)}removeUserProperty(e){this.propertyManager.removeUserProperty(e);}setOnce(e,t,i="user"){this.propertyManager.setOnce(e,t,i);}clearSessionProperties(){this.propertyManager.clearSessionProperties();}clearUserProperties(){this.propertyManager.clearUserProperties();}getAllProperties(){return this.propertyManager.getAllProperties()}}function b(e){const t=globalThis.__humanBehaviorGlobalTracker;return t?.identifyUser?t.identifyUser({userProperties:e}):(console.warn("HumanBehavior tracker not found. Make sure the SDK is initialized."),null)}function E(e,t){const i=globalThis.__humanBehaviorGlobalTracker;return i?.track?i.track(e,t):(console.warn("HumanBehavior tracker not found. Make sure the SDK is initialized."),null)}function I(){const e=globalThis.__humanBehaviorGlobalTracker;return !!e?.identifyUser}_&&(window.HumanBehaviorTracker=C);
|
|
12176
|
+
exports.LogLevel = void 0;!function(e){e[e.NONE=0]="NONE",e[e.ERROR=1]="ERROR",e[e.WARN=2]="WARN",e[e.INFO=3]="INFO",e[e.DEBUG=4]="DEBUG";}(exports.LogLevel||(exports.LogLevel={}));const s=new class{constructor(e){this.config={level:exports.LogLevel.ERROR,enableConsole:true,enableStorage:false},this.isBrowser="undefined"!=typeof window,e&&(this.config={...this.config,...e});}setConfig(e){this.config={...this.config,...e};}shouldLog(e){return e<=this.config.level}formatMessage(e,t,...i){return `[HumanBehavior ${e}] ${(new Date).toISOString()}: ${t}`}error(e,...t){if(!this.shouldLog(exports.LogLevel.ERROR))return;const s=this.formatMessage("ERROR",e);this.config.enableConsole&&console.error(s,...t),this.config.enableStorage&&this.isBrowser&&this.logToStorage(s,t);}warn(e,...t){if(!this.shouldLog(exports.LogLevel.WARN))return;const s=this.formatMessage("WARN",e);this.config.enableConsole&&console.warn(s,...t),this.config.enableStorage&&this.isBrowser&&this.logToStorage(s,t);}info(e,...t){if(!this.shouldLog(exports.LogLevel.INFO))return;const s=this.formatMessage("INFO",e);this.config.enableConsole&&console.log(s,...t),this.config.enableStorage&&this.isBrowser&&this.logToStorage(s,t);}debug(e,...t){if(!this.shouldLog(exports.LogLevel.DEBUG))return;const s=this.formatMessage("DEBUG",e);this.config.enableConsole&&console.log(s,...t),this.config.enableStorage&&this.isBrowser&&this.logToStorage(s,t);}logToStorage(e,t){try{const i=JSON.parse(localStorage.getItem("human_behavior_logs")||"[]"),s={message:e,args:t.length>0?t:void 0,timestamp:Date.now()};i.push(s),i.length>1e3&&i.splice(0,i.length-1e3),localStorage.setItem("human_behavior_logs",JSON.stringify(i));}catch(e){}}getLogs(){if(!this.isBrowser)return [];try{return JSON.parse(localStorage.getItem("human_behavior_logs")||"[]")}catch(e){return []}}clearLogs(){this.isBrowser&&localStorage.removeItem("human_behavior_logs");}},n=(e,...t)=>s.error(e,...t),r=(e,...t)=>s.warn(e,...t),o=(e,...t)=>s.info(e,...t),a=(e,...t)=>s.debug(e,...t),c=1048576;function d(e,t,i){return (new TextEncoder).encode(JSON.stringify({sessionId:i,events:[...e,t]})).length>c}function l(e,t){if(!e||"object"!=typeof e)return [];if((new TextEncoder).encode(JSON.stringify({sessionId:t,events:[e]})).length<=c)return [e];const i={...e},s=["screenshot","html","dom","fullText","innerHTML","outerHTML"];s.forEach(e=>{i[e]&&delete i[e];});if((new TextEncoder).encode(JSON.stringify({sessionId:t,events:[i]})).length<=c)return [i];return [{type:e.type,timestamp:e.timestamp,url:e.url,pathname:e.pathname,...Object.fromEntries(Object.entries(e).filter(([e,t])=>!s.includes(e)&&"object"!=typeof t&&"string"!=typeof t||"string"==typeof t&&t.length<1e3))}]}class h{constructor({apiKey:e,ingestionUrl:t}){this.monthlyLimitReached=false,this.apiKey=e,this.baseUrl=t;}checkMonthlyLimit(){return !this.monthlyLimitReached}async init(e,t){if(!this.checkMonthlyLimit())return {sessionId:e,endUserId:t};let i=null,s=null;"undefined"!=typeof window&&(i=window.location.href,s=document.referrer),o("API init called with:",{sessionId:e,userId:t,entryURL:i,referrer:s,baseUrl:this.baseUrl});try{const r=await fetch(`${this.baseUrl}/api/ingestion/init`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,Referer:s||""},body:JSON.stringify({sessionId:e,endUserId:t,entryURL:i,referrer:s})});if(o("API init response status:",r.status),!r.ok){if(429===r.status)return this.monthlyLimitReached=!0,{sessionId:e,endUserId:t};const i=await r.text();throw n("API init failed:",r.status,i),new Error(`Failed to initialize ingestion: ${r.statusText} - ${i}`)}const a=await r.json();return !0===a.monthlyLimitReached&&(this.monthlyLimitReached=!0,o("Monthly limit reached detected from server response")),o("API init success:",a),{sessionId:a.sessionId,endUserId:a.endUserId}}catch(e){throw n("API init error:",e),e}}async sendEvents(e,t,i){const s=e.filter(e=>e&&"object"==typeof e),n=await fetch(`${this.baseUrl}/api/ingestion/events`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({sessionId:t,events:s,endUserId:i})});if(!n.ok){if(429===n.status)throw this.monthlyLimitReached=true,new Error("429: Monthly video processing limit reached");throw new Error(`Failed to send events: ${n.statusText}`)} true===(await n.json()).monthlyLimitReached&&(this.monthlyLimitReached=true,o("Monthly limit reached detected from events response"));}async sendEventsChunked(e,t,i,s,r){if(!this.checkMonthlyLimit())return [];try{const n=[];let c=[];for(const h of e)if(h&&"object"==typeof h)if(d(c,h,t)){if(c.length>0){a(`[SDK] Sending chunk with ${c.length} events`);const e=await fetch(`${this.baseUrl}/api/ingestion/events`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({sessionId:t,events:c,endUserId:i,windowId:s,automaticProperties:r})});if(!e.ok){if(429===e.status)return this.monthlyLimitReached=!0,n.flat();throw new Error(`Failed to send events: ${e.statusText}`)}const d=await e.json();!0===d.monthlyLimitReached&&(this.monthlyLimitReached=!0,o("Monthly limit reached detected from chunked events response")),n.push(d),c=[];}c=l(h,t);}else c.push(h);if(c.length>0){a(`[SDK] Sending final chunk with ${c.length} events`);const e=await fetch(`${this.baseUrl}/api/ingestion/events`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({sessionId:t,events:c,endUserId:i,windowId:s,automaticProperties:c[0]?.automaticProperties})});if(!e.ok){if(429===e.status)return this.monthlyLimitReached=!0,n.flat();throw new Error(`Failed to send events: ${e.statusText}`)}const r=await e.json();!0===r.monthlyLimitReached&&(this.monthlyLimitReached=!0,o("Monthly limit reached detected from final chunked events response")),n.push(r);}return n.flat()}catch(e){throw n("Error sending events:",e),e}}async sendUserData(e,t,i){try{const s={userId:e,userAttributes:t,sessionId:i,posthogName:t.email||t.name||null};a("Sending user data to server:",s);const n=await fetch(`${this.baseUrl}/api/ingestion/user`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(s)});if(!n.ok)throw new Error(`Failed to send user data: ${n.statusText} with API key: ${this.apiKey}`);const r=await n.json();return a("Server response:",r),r}catch(e){throw n("Error sending user data:",e),e}}async sendUserAuth(e,t,i,s){try{const n=await fetch(`${this.baseUrl}/api/ingestion/user/auth`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({userId:e,userAttributes:t,sessionId:i,authFields:s})});if(!n.ok)throw new Error(`Failed to authenticate user: ${n.statusText} with API key: ${this.apiKey}`);return await n.json()}catch(e){throw n("Error authenticating user:",e),e}}sendBeaconEvents(e,t){const i={sessionId:t,events:e,endUserId:null,apiKey:this.apiKey},s=new Blob([JSON.stringify(i)],{type:"application/json"});return navigator.sendBeacon(`${this.baseUrl}/api/ingestion/events`,s)}async sendCustomEvent(e,t,i,s){o("[SDK] Sending custom event",{sessionId:e,eventName:t,eventProperties:i,endUserId:s});try{const r=await fetch(`${this.baseUrl}/api/ingestion/customEvent`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({sessionId:e,eventName:t,eventProperties:i||{},endUserId:s||null})});if(o("[SDK] Custom event response",{status:r.status,statusText:r.statusText}),!r.ok){const e=await r.text();throw n("[SDK] Failed to send custom event",{status:r.status,statusText:r.statusText,errorText:e}),new Error(`Failed to send custom event: ${r.status} ${r.statusText} - ${e}`)}const c=await r.json();return a("[SDK] Custom event success",c),c}catch(s){throw n("[SDK] Error sending custom event",s,{sessionId:e,eventName:t,eventProperties:i}),s}}async sendCustomEventBatch(e,t,i){try{const s=await fetch(`${this.baseUrl}/api/ingestion/customEvent/batch`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({sessionId:e,events:t,endUserId:i||null})});if(!s.ok)throw new Error(`Failed to send custom event batch: ${s.statusText}`);return await s.json()}catch(e){throw n("Error sending custom event batch:",e),e}}}class u{constructor(e){if(this.redactedText="[REDACTED]",this.unredactedFields=new Set,this.redactedFields=new Set,this.redactionMode="privacy-first",this.excludeSelectors=['[data-no-redact="true"]',".human-behavior-no-redact"],e?.redactedText&&(this.redactedText=e.redactedText),e?.excludeSelectors&&(this.excludeSelectors=[...this.excludeSelectors,...e.excludeSelectors]),e?.redactionStrategy)if(this.redactionMode=e.redactionStrategy.mode,"privacy-first"===this.redactionMode)e.redactionStrategy.unredactFields&&this.setFieldsToUnredact(e.redactionStrategy.unredactFields);else {const t=['input[type="password"]','[data-hb-redact="true"]'],i=e.redactionStrategy.redactFields&&e.redactionStrategy.redactFields.length>0?e.redactionStrategy.redactFields:t;this.setFieldsToRedact(i);}e?.legacyRedactFields&&this.setFieldsToUnredact(e.legacyRedactFields),e?.userFields&&this.setFieldsToUnredact(e.userFields);}setFieldsToRedact(e){this.redactedFields.clear();['input[type="password"]','input[type="password" i]','[type="password"]','[type="password" i]',...e].forEach(e=>{this.redactedFields.add(e);}),this.redactedFields.size>0?a(`Redaction: Active for ${this.redactedFields.size} field(s):`,Array.from(this.redactedFields)):a("Redaction: No fields to redact"),this.applyRedactionClasses();}setFieldsToUnredact(e){this.unredactedFields.clear();const t=e.filter(e=>!this.isPasswordSelector(e)||(r(`Cannot unredact password field: ${e} - Password fields are always protected`),false));t.forEach(e=>this.unredactedFields.add(e)),t.length>0?a(`Unredaction: Active for ${t.length} field(s):`,t):a("Unredaction: No valid fields to unredact"),this.applyUnredactionClasses();}redactFields(e){e.forEach(e=>{this.unredactedFields.delete(e);}),this.unredactedFields.size>0?a(`Unredaction: Removed ${e.length} field(s), ${this.unredactedFields.size} remaining:`,Array.from(this.unredactedFields)):a("Unredaction: All fields redacted"),this.applyUnredactionClasses();}clearUnredactedFields(){this.unredactedFields.clear(),a("Unredaction: All fields cleared, everything redacted"),this.removeUnredactionClasses();}hasUnredactedFields(){return this.unredactedFields.size>0}getRedactionMode(){return this.redactionMode}getUnredactedFields(){return Array.from(this.unredactedFields)}getMaskTextSelector(){return "privacy-first"===this.redactionMode?0===this.unredactedFields.size?null:Array.from(this.unredactedFields).join(","):0===this.redactedFields.size?null:Array.from(this.redactedFields).join(",")}applyRedactionClasses(){0!==this.redactedFields.size&&("undefined"!=typeof document&&"loading"!==document.readyState?this.redactedFields.forEach(e=>{try{const t=document.querySelectorAll(e);t.forEach(e=>{e&&e.classList&&e.classList.add("rr-mask");}),a(`Added rr-mask class to ${t.length} element(s) for selector: ${e}`);}catch(t){r(`Invalid selector: ${e}`);}}):a("DOM not ready, deferring redaction class application"));}applyUnredactionClasses(){0!==this.unredactedFields.size&&("undefined"!=typeof document&&"loading"!==document.readyState?this.unredactedFields.forEach(e=>{try{const t=document.querySelectorAll(e);t.forEach(e=>{e&&e.classList&&e.classList.remove("rr-mask");}),a(`Removed rr-mask class from ${t.length} element(s) for selector: ${e}`);}catch(t){r(`Invalid selector: ${e}`);}}):a("DOM not ready, deferring unredaction class application"));}removeUnredactionClasses(){a("Unredaction classes removed");}isPasswordSelector(e){return ['input[type="password"]','input[type="password" i]','[type="password"]','[type="password" i]'].some(t=>e.toLowerCase().includes(t.toLowerCase().replace(/[\[\]]/g,"")))}getOriginalValue(e){if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement)return e.value}isElementUnredacted(e){return this.shouldUnredactElement(e)}shouldUnredactElement(e){if("privacy-first"===this.redactionMode){if(0===this.unredactedFields.size)return false;for(const t of this.unredactedFields)try{if(e.matches(t))return !0}catch(e){r(`Invalid selector: ${t}`);}return false}if(0===this.redactedFields.size)return true;for(const t of this.redactedFields)try{if(e.matches(t))return !1}catch(e){r(`Invalid selector: ${t}`);}return true}}new u;const m="undefined"!=typeof window;function p(){if(!m)return "unknown";const e=navigator.userAgent.toLowerCase(),t=window.screen.width,i=window.screen.height;return /mobile|android|iphone|ipad|ipod|blackberry|windows phone/i.test(e)?/ipad/i.test(e)||t>=768&&i>=1024?"tablet":"mobile":/windows|macintosh|linux/i.test(e)?"desktop":"unknown"}function g(e){try{return new URL(e).hostname}catch{return ""}}function f(){if(!m)return {device_type:"unknown",browser:"unknown",browser_version:"unknown",os:"unknown",os_version:"unknown",screen_resolution:"unknown",viewport_size:"unknown",color_depth:0,timezone:"unknown",language:"unknown",languages:[]};const{browser:e,browser_version:t}=function(){if(!m)return {browser:"unknown",browser_version:"unknown"};const e=navigator.userAgent;if(/chrome/i.test(e)&&!/edge/i.test(e)){const t=e.match(/chrome\/(\d+)/i);return {browser:"chrome",browser_version:t?t[1]:"unknown"}}if(/firefox/i.test(e)){const t=e.match(/firefox\/(\d+)/i);return {browser:"firefox",browser_version:t?t[1]:"unknown"}}if(/safari/i.test(e)&&!/chrome/i.test(e)){const t=e.match(/version\/(\d+)/i);return {browser:"safari",browser_version:t?t[1]:"unknown"}}if(/edge/i.test(e)){const t=e.match(/edge\/(\d+)/i);return {browser:"edge",browser_version:t?t[1]:"unknown"}}if(/msie|trident/i.test(e)){const t=e.match(/msie (\d+)/i)||e.match(/rv:(\d+)/i);return {browser:"ie",browser_version:t?t[1]:"unknown"}}return {browser:"unknown",browser_version:"unknown"}}(),{os:i,os_version:s}=function(){if(!m)return {os:"unknown",os_version:"unknown"};const e=navigator.userAgent;if(/windows/i.test(e)){const t=e.match(/windows nt (\d+\.\d+)/i);let i="unknown";if(t){const e=parseFloat(t[1]);i=10===e?"10":6.3===e?"8.1":6.2===e?"8":6.1===e?"7":t[1];}return {os:"windows",os_version:i}}if(/macintosh|mac os x/i.test(e)){const t=e.match(/mac os x (\d+[._]\d+)/i);return {os:"macos",os_version:t?t[1].replace("_","."):"unknown"}}if(/iphone|ipad|ipod/i.test(e)){const t=e.match(/os (\d+[._]\d+)/i);return {os:"ios",os_version:t?t[1].replace("_","."):"unknown"}}if(/android/i.test(e)){const t=e.match(/android (\d+\.\d+)/i);return {os:"android",os_version:t?t[1]:"unknown"}}return /linux/i.test(e)?{os:"linux",os_version:"unknown"}:{os:"unknown",os_version:"unknown"}}();return {device_type:p(),browser:e,browser_version:t,os:i,os_version:s,screen_resolution:`${window.screen.width}x${window.screen.height}`,viewport_size:`${window.innerWidth}x${window.innerHeight}`,color_depth:window.screen.colorDepth,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,language:navigator.language,languages:[...navigator.languages||[navigator.language]],raw_user_agent:navigator.userAgent}}function w(){if(!m)return {current_url:"",pathname:"",search:"",hash:"",title:"",referrer:"",referrer_domain:"",initial_referrer:"",initial_referrer_domain:""};const e=window.location.href,t=document.referrer,i=function(e){const t=new URL(e),i={};return ["utm_source","utm_medium","utm_campaign","utm_term","utm_content"].forEach(e=>{const s=t.searchParams.get(e);s&&(i[e]=s);}),i}(e);return {current_url:e,pathname:window.location.pathname,search:window.location.search,hash:window.location.hash,title:document.title,referrer:t,referrer_domain:g(t),initial_referrer:t,initial_referrer_domain:g(t),initial_host:window.location.hostname,...i}}function v(){return {...f(),...w()}}function y(){if(!m)return {};const e=w();return {initial_referrer:e.initial_referrer,initial_referrer_domain:e.initial_referrer_domain,initial_url:e.current_url,initial_pathname:e.pathname,initial_utm_source:e.utm_source,initial_utm_medium:e.utm_medium,initial_utm_campaign:e.utm_campaign,initial_utm_term:e.utm_term,initial_utm_content:e.utm_content}}function k(){if(!m)return {};const e=w();return {current_url:e.current_url,pathname:e.pathname,search:e.search,hash:e.hash,title:e.title,referrer:e.referrer,referrer_domain:e.referrer_domain,utm_source:e.utm_source,utm_medium:e.utm_medium,utm_campaign:e.utm_campaign,utm_term:e.utm_term,utm_content:e.utm_content}}class S{constructor(e={}){this.sessionProperties={},this.userProperties={},this.initialProperties={},this.isInitialized=false,this.config={enableAutomaticProperties:true,enableSessionProperties:true,enableUserProperties:true,propertyDenylist:[],...e},this.automaticProperties=v(),this.initialize();}initialize(){this.isInitialized||(this.initialProperties=y(),this.loadSessionProperties(),this.isInitialized=true);}getEventProperties(e={}){const t={...e};return this.config.enableAutomaticProperties&&Object.assign(t,this.getAutomaticProperties()),this.config.enableSessionProperties&&Object.assign(t,this.sessionProperties),this.config.enableUserProperties&&Object.assign(t,this.userProperties),this.sessionProperties.$initial_properties_captured||(Object.assign(t,this.initialProperties),this.setSessionProperty("$initial_properties_captured",true)),this.applyDenylist(t),t}getAutomaticProperties(){return {...this.automaticProperties,...k()}}getAutomaticPropertiesWithGeoIP(e={}){return {...this.automaticProperties,...k(),...e}}setSessionProperty(e,t){this.sessionProperties[e]=t,this.saveSessionProperties();}setSessionProperties(e){Object.assign(this.sessionProperties,e),this.saveSessionProperties();}getSessionProperty(e){return this.sessionProperties[e]}removeSessionProperty(e){delete this.sessionProperties[e],this.saveSessionProperties();}setUserProperty(e,t){this.userProperties[e]=t;}setUserProperties(e){Object.assign(this.userProperties,e);}getUserProperty(e){return this.userProperties[e]}removeUserProperty(e){delete this.userProperties[e];}setOnce(e,t,i="user"){"session"===i?e in this.sessionProperties||this.setSessionProperty(e,t):e in this.userProperties||this.setUserProperty(e,t);}clearSessionProperties(){this.sessionProperties={},this.saveSessionProperties();}clearUserProperties(){this.userProperties={};}reset(){this.clearSessionProperties(),this.clearUserProperties(),this.initialProperties={},this.isInitialized=false,this.initialize();}loadSessionProperties(){if("undefined"!=typeof sessionStorage)try{const e=sessionStorage.getItem("hb_session_properties");e&&(this.sessionProperties=JSON.parse(e));}catch(e){console.warn("Failed to load session properties:",e);}}saveSessionProperties(){if("undefined"!=typeof sessionStorage)try{sessionStorage.setItem("hb_session_properties",JSON.stringify(this.sessionProperties));}catch(e){console.warn("Failed to save session properties:",e);}}applyDenylist(e){this.config.propertyDenylist&&0!==this.config.propertyDenylist.length&&this.config.propertyDenylist.forEach(t=>{delete e[t];});}updateAutomaticProperties(){this.automaticProperties=v();}getAllProperties(){return {automatic:this.getAutomaticProperties(),session:{...this.sessionProperties},user:{...this.userProperties},initial:{...this.initialProperties}}}}const I="undefined"!=typeof window;class C{get isTrackerStarted(){return this.isStarted}setupDomReadyHandler(){if(I)if("complete"===document.readyState||"interactive"===document.readyState)this.onDomReady();else if(document.addEventListener){document.addEventListener("DOMContentLoaded",()=>this.onDomReady(),{capture:false});const e=setInterval(()=>{"interactive"!==document.readyState&&"complete"!==document.readyState||(clearInterval(e),this.onDomReady());},10);setTimeout(()=>clearInterval(e),5e3);}else this.onDomReady();else this.onDomReady();}onDomReady(){this.isDomReady||(this.isDomReady=true,a("🎯 DOM is ready, processing queued requests"),this.requestQueue.forEach(e=>{this.processRequest(e);}),this.requestQueue=[],this.domReadyHandlers.forEach(e=>e()),this.domReadyHandlers=[]);}queueRequest(e){this.isDomReady?this.processRequest(e):this.requestQueue.push(e);}async processRequest(e){switch(a("Processing queued request:",e),e.type){case "addEvent":await this.addEvent(e.event);break;case "identifyUser":await this.identifyUser(e.userProperties);break;case "trackPageView":this.trackPageView();break;default:r("Unknown request type:",e.type);}}registerDomReadyHandler(e){this.isDomReady?e():this.domReadyHandlers.push(e);}static init(e,t){if(I&&false!==t?.suppressConsoleErrors){const e=console.error;console.error=(...t)=>{const i=t.join(" ");i.includes("SecurityError: Failed to execute 'toDataURL'")||i.includes("Tainted canvases may not be exported")||i.includes("Cannot inline img src=")||i.includes("Cross-Origin")||i.includes("CORS")||i.includes("Access-Control-Allow-Origin")||i.includes("Failed to load resource")||i.includes("net::ERR_BLOCKED_BY_CLIENT")||i.includes("NetworkError when attempting to fetch resource")||i.includes("Failed to fetch")||i.includes("TypeError: NetworkError")||i.includes("HumanBehavior ERROR")||i.includes("Failed to track custom event")||i.includes("Error sending custom event")||e.apply(console,t);};const t=console.warn;console.warn=(...e)=>{const i=e.join(" ");i.includes("Cannot inline img src=")||i.includes("Cross-Origin")||i.includes("CORS")||i.includes("Access-Control-Allow-Origin")||i.includes("Failed to load resource")||i.includes("net::ERR_BLOCKED_BY_CLIENT")||i.includes("NetworkError when attempting to fetch resource")||i.includes("Failed to fetch")||i.includes("Custom event network error")||i.includes("Request blocked by ad blocker")||t.apply(console,e);},window.addEventListener("error",e=>{const t=e.message||"";if(t.includes("SecurityError")||t.includes("Tainted canvases")||t.includes("toDataURL")||t.includes("Cross-Origin")||t.includes("CORS")||t.includes("NetworkError")||t.includes("Failed to fetch"))return e.preventDefault(),false});}if(I&&window.__humanBehaviorGlobalTracker)return a("Tracker already initialized, returning existing instance"),window.__humanBehaviorGlobalTracker;t?.logLevel&&this.configureLogging({level:t.logLevel});const i=new C(e,t?.ingestionUrl,{enableAutomaticProperties:t?.enableAutomaticProperties,propertyDenylist:t?.propertyDenylist,redactionStrategy:t?.redactionStrategy,redactFields:t?.redactFields,maxQueueSize:t?.maxQueueSize});return i.recordCanvas=t?.recordCanvas??false,t?.redactFields&&i.setUnredactedFields(t.redactFields),false!==t?.enableAutomaticTracking&&i.setupAutomaticTracking(t?.automaticTrackingOptions),i.start(),i}constructor(e,i,s){if(this.eventQueue=[],this.userProperties={},this.isProcessing=false,this.flushInterval=null,this.FLUSH_INTERVAL_MS=3e3,this.endUserId=null,this.initialized=false,this.initializationPromise=null,this.monthlyLimitReached=false,this.isDomReady=false,this.requestQueue=[],this.domReadyHandlers=[],this.originalConsole=null,this.consoleTrackingEnabled=false,this.navigationTrackingEnabled=false,this.currentUrl="",this.previousUrl="",this.originalPushState=null,this.originalReplaceState=null,this.navigationListeners=[],this._connectionBlocked=false,this.recordInstance=null,this.sessionStartTime=Date.now(),this.rrwebRecord=null,this.fullSnapshotTimeout=null,this.recordCanvas=false,this.isStarted=false,this.rageClickTracker={clicks:[]},this.RAGE_CLICK_THRESHOLD_PX=30,this.RAGE_CLICK_TIMEOUT_MS=1e3,this.RAGE_CLICK_CLICK_COUNT=3,this.deadClickTracker={pendingClicks:new Map},this.DEAD_CLICK_SCROLL_THRESHOLD_MS=100,this.DEAD_CLICK_SELECTION_THRESHOLD_MS=100,this.DEAD_CLICK_MUTATION_THRESHOLD_MS=2e3,this.DEAD_CLICK_ABSOLUTE_TIMEOUT_MS=1400,!e)throw new Error("Human Behavior API Key is required");if(this.api=new h({apiKey:e,ingestionUrl:i||"https://ingest.humanbehavior.co"}),this.apiKey=e,this.MAX_QUEUE_SIZE=s?.maxQueueSize??1e3,this.redactionManager=new u({redactionStrategy:s?.redactionStrategy,legacyRedactFields:s?.redactFields}),this.propertyManager=new S({enableAutomaticProperties:false!==s?.enableAutomaticProperties,propertyDenylist:s?.propertyDenylist||[]}),I){const e=`human_behavior_end_user_id_${this.apiKey}`,i=this.getCookie(e);this.endUserId=i||v1(),i?(a(`Reusing existing endUserId: ${this.endUserId}`),console.log(`[HumanBehavior] ♻️ Reusing existing endUserId: ${this.endUserId}`)):(this.setCookie(e,this.endUserId,365),a(`Generated new endUserId: ${this.endUserId}`),console.log(`[HumanBehavior] 🆕 Generated new endUserId: ${this.endUserId}`));}else this.endUserId=v1();I?(this.sessionId=this.getOrCreateSessionId(),this.windowId=v1(),this.currentUrl=window.location.href,window.__humanBehaviorGlobalTracker=this,console.log(`[HumanBehavior] 📝 Session initialized - SessionId: ${this.sessionId}, WindowId: ${this.windowId}`)):(this.sessionId=v1(),this.windowId=v1()),this.initializationPromise=this.init().catch(e=>{n("Background initialization failed:",e);});}async init(){try{I?(this.setupPageUnloadHandler(),this.setupNavigationTracking()):o("HumanBehaviorTracker initialized in server environment. Session tracking is disabled.");const e=this.propertyManager.getAutomaticProperties();await this.initServerAsync(this.endUserId,e),this.initialized=!0,o(`HumanBehaviorTracker initialized with sessionId: ${this.sessionId}, endUserId: ${this.endUserId}`);}catch(e){n("Failed to initialize HumanBehaviorTracker:",e),this.initialized=true;}}async initServerAsync(e,t){try{a("🚀 Attempting to call /init endpoint..."),a("📡 URL:",`${this.api.baseUrl}/api/ingestion/init`),a("🔑 API Key:",this.apiKey);let i=null,s=null;I&&(i=window.location.href,s=document.referrer),a("📦 Payload:",{sessionId:this.sessionId,endUserId:e,entryURL:i,referrer:s,automaticProperties:t});const n=new AbortController,o=setTimeout(()=>n.abort(),500);try{const r=await fetch(`${this.api.baseUrl}/api/ingestion/init`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,Referer:s||""},body:JSON.stringify({sessionId:this.sessionId,endUserId:e||this.endUserId,entryURL:i,referrer:s,automaticProperties:t}),signal:n.signal});if(clearTimeout(o),!r.ok)throw new Error(`Failed to initialize: ${r.statusText}`);const{sessionId:c,endUserId:d}=await r.json();c&&c!==this.sessionId&&(a(`Server returned different sessionId: ${c} (client had: ${this.sessionId})`),this.sessionId=c,I&&localStorage.setItem(`human_behavior_session_id_${this.apiKey}`,this.sessionId)),d&&d!==this.endUserId&&(a(`Server returned different endUserId: ${d} (client had: ${this.endUserId})`),this.endUserId=d,this.endUserId&&this.setCookie(`human_behavior_end_user_id_${this.apiKey}`,this.endUserId,365));}catch(e){return clearTimeout(o),void("AbortError"===e.name?(r("Init request timeout (500ms), continuing with local IDs"),console.log("[HumanBehavior] ⚠️ Init request timeout (500ms), continuing with local IDs")):(r("Init request failed, continuing with local IDs:",e),console.log("[HumanBehavior] ⚠️ Init request failed, continuing with local IDs:",e.message)))}this.initialized=!0,console.log(`[HumanBehavior] ✅ Init completed (optional) - SessionId: ${this.sessionId}, EndUserId: ${this.endUserId}`);}catch(e){n("❌ Server initialization failed:",e),r("Server initialization failed, continuing with local IDs:",e),this.initialized=true;}}async ensureInitialized(){this.initializationPromise&&await this.initializationPromise;}setupNavigationTracking(){if(!I||this.navigationTrackingEnabled)return;this.navigationTrackingEnabled=true,a("Setting up navigation tracking"),this.originalPushState=history.pushState,this.originalReplaceState=history.replaceState,history.pushState=(...e)=>{this.previousUrl=this.currentUrl,this.currentUrl=window.location.href,this.originalPushState.apply(history,e),this.trackNavigationEvent("pushState",this.previousUrl,this.currentUrl),this.takeFullSnapshot();},history.replaceState=(...e)=>{this.previousUrl=this.currentUrl,this.currentUrl=window.location.href,this.originalReplaceState.apply(history,e),this.trackNavigationEvent("replaceState",this.previousUrl,this.currentUrl),this.takeFullSnapshot();};const e=()=>{this.previousUrl=this.currentUrl,this.currentUrl=window.location.href,this.trackNavigationEvent("popstate",this.previousUrl,this.currentUrl),this.takeFullSnapshot();};window.addEventListener("popstate",e),this.navigationListeners.push(()=>{window.removeEventListener("popstate",e);});const t=()=>{this.previousUrl=this.currentUrl,this.currentUrl=window.location.href,this.trackNavigationEvent("hashchange",this.previousUrl,this.currentUrl);};window.addEventListener("hashchange",t),this.navigationListeners.push(()=>{window.removeEventListener("hashchange",t);}),this.trackNavigationEvent("pageLoad","",this.currentUrl);}async trackNavigationEvent(e,t,i){if(this.initialized)try{const s={type:e,from:t,to:i,timestamp:(new Date).toISOString(),pathname:window.location.pathname,search:window.location.search,hash:window.location.hash,referrer:document.referrer};if(await this.addEvent({type:5,data:{payload:{eventType:"navigation",...s}},timestamp:Date.now()}),"pageLoad"===e||"pushState"===e||"replaceState"===e||"popstate"===e||"hashchange"===e){const i={url:window.location.href,fromUrl:t,navigationType:e,pathname:window.location.pathname,search:window.location.search,hash:window.location.hash,referrer:document.referrer,timestamp:Date.now()};await this.customEvent("$page_viewed",i);}a(`Navigation tracked: ${e} from ${t} to ${i}`);}catch(e){n("Failed to track navigation event:",e);}}async trackPageView(e){if(this.initialized){this.propertyManager.updateAutomaticProperties();try{const t={url:e||window.location.href,pathname:window.location.pathname,search:window.location.search,hash:window.location.hash,referrer:document.referrer,timestamp:(new Date).toISOString()},i=this.propertyManager.getEventProperties(t);await this.addEvent({type:5,data:{payload:{eventType:"pageview",...i}},timestamp:Date.now()}),a(`Pageview tracked: ${t.url}`);}catch(e){n("Failed to track pageview event:",e);}}}async customEvent(e,i){this.endUserId||(r(`endUserId not available, using anonymous ID for event: ${e}`),this.endUserId=v1()),I&&this.checkAndRefreshSession();const s=this.propertyManager.getEventProperties(i);try{await this.api.sendCustomEvent(this.sessionId,e,s,this.endUserId),a(`Custom event tracked: ${e}`,s);}catch(t){n("Failed to track custom event:",t),t.message?.includes("500")||t.message?.includes("Internal Server Error")||t.message?.includes("Failed to send custom event")?r("Custom event endpoint failed, using fallback"):t.message?.includes("ERR_BLOCKED_BY_CLIENT")?r("Custom event request blocked by ad blocker, using fallback"):t.message?.includes("Failed to fetch")&&r("Custom event network error, using fallback");try{const t={eventName:e,properties:s||{},timestamp:(new Date).toISOString(),url:window.location.href,pathname:window.location.pathname};await this.addEvent({type:5,data:{payload:{eventType:"custom",...t}},timestamp:Date.now()}),a(`Custom event added to event stream as fallback: ${e}`);}catch(e){n("Failed to add custom event to event stream as fallback:",e);}}}setupAutomaticTracking(e){if(!I)return;const t={trackButtons:false!==e?.trackButtons,trackLinks:false,trackForms:false!==e?.trackForms,includeText:false!==e?.includeText,includeClasses:e?.includeClasses||false};a("Setting up automatic tracking with config:",t),t.trackButtons&&this.setupAutomaticButtonTracking(t),t.trackForms&&this.setupAutomaticFormTracking(t),this.setupRageClickDetection(),this.setupDeadClickDetection();}setupAutomaticButtonTracking(e){document.addEventListener("click",async t=>{const i=t.target;if("BUTTON"===i.tagName||i.closest("button")){const t="BUTTON"===i.tagName?i:i.closest("button"),s={buttonId:t.id||null,buttonType:t.type||"button",page:window.location.pathname,timestamp:Date.now()};e.includeText&&(s.buttonText=t.textContent?.trim()||null),e.includeClasses&&(s.buttonClass=t.className||null),Object.keys(s).forEach(e=>{null===s[e]&&delete s[e];}),await this.customEvent("$button_clicked",s);}});}setupRageClickDetection(){I&&document.addEventListener("click",async e=>{const t=e.target,i=e.clientX,s=e.clientY,n=Date.now();if(this.isRageClick(i,s,n,t)){const e=t.closest('button, a, [role="button"], [role="link"]')||t,r={x:i,y:s,page:window.location.pathname,element:e.tagName.toLowerCase(),clickCount:this.RAGE_CLICK_CLICK_COUNT,timestamp:n};e.id&&(r.elementId=e.id),e.className&&(r.elementClass=e.className),e.textContent&&(r.elementText=e.textContent.trim().substring(0,100)),Object.keys(r).forEach(e=>{null!==r[e]&&void 0!==r[e]||delete r[e];}),await this.customEvent("$rageclick",r),this.rageClickTracker.clicks=[];}});}isRageClick(e,t,i,s){const n=this.rageClickTracker.clicks,r=n[n.length-1];if(r&&Math.abs(e-r.x)+Math.abs(t-r.y)<this.RAGE_CLICK_THRESHOLD_PX&&i-r.timestamp<this.RAGE_CLICK_TIMEOUT_MS){if(n.push({x:e,y:t,timestamp:i,element:s}),n.length>=this.RAGE_CLICK_CLICK_COUNT)return true}else this.rageClickTracker.clicks=[{x:e,y:t,timestamp:i,element:s}];return false}setupDeadClickDetection(){I&&(this.setupDeadClickMutationObserver(),this.setupDeadClickScrollObserver(),this.setupDeadClickSelectionObserver(),this.setupDeadClickNavigationTracking(),document.addEventListener("click",e=>{const t=e.target;if(!t)return;if(!this.isInteractiveElement(t))return;if(this.ignoreClickForDeadDetection(t))return;const i=Date.now()+Math.random(),s=Date.now(),n=this.deadClickTracker.lastMutationTime,r=this.DEAD_CLICK_ABSOLUTE_TIMEOUT_MS,o=window.setTimeout(()=>{this.handleDeadClickTimeout(i);},r);this.deadClickTracker.pendingClicks.set(i,{element:t,originalEvent:e,timestamp:s,timer:o,cancelled:false,lastMutationTimeAtClick:n});}));}setupDeadClickMutationObserver(){I&&(this.deadClickTracker.mutationObserver||(this.deadClickTracker.mutationObserver=new MutationObserver(()=>{const e=Date.now();this.deadClickTracker.lastMutationTime=e,this.deadClickTracker.pendingClicks.forEach((t,i)=>{if(t.cancelled)return;const s=e-t.timestamp,n=t.lastMutationTimeAtClick||0,r=e>n,o=s>=0&&s<this.DEAD_CLICK_MUTATION_THRESHOLD_MS,a=s<0&&Math.abs(s)<50;(o&&r||a)&&this.cancelPendingClick(i);});}),this.deadClickTracker.mutationObserver.observe(document,{attributes:true,characterData:true,childList:true,subtree:true})));}setupDeadClickScrollObserver(){I&&window.addEventListener("scroll",()=>{const e=Date.now();this.deadClickTracker.pendingClicks.forEach((t,i)=>{e-t.timestamp<this.DEAD_CLICK_SCROLL_THRESHOLD_MS&&this.cancelPendingClick(i);});},{capture:true,passive:true});}setupDeadClickSelectionObserver(){I&&document.addEventListener("selectionchange",()=>{const e=Date.now();this.deadClickTracker.lastSelectionChangedTime=e,this.deadClickTracker.pendingClicks.forEach((t,i)=>{e-t.timestamp<this.DEAD_CLICK_SELECTION_THRESHOLD_MS&&this.cancelPendingClick(i);});});}setupDeadClickNavigationTracking(){if(!I)return;let e=window.location.href;const t=this.trackNavigationEvent.bind(this);this.trackNavigationEvent=async(i,s,n)=>(this.cancelAllPendingClicks(),e=window.location.href,t(i,s,n));const i=()=>{const t=window.location.href;t!==e&&(this.cancelAllPendingClicks(),e=t);};window.addEventListener("popstate",i),window.addEventListener("hashchange",i),window.addEventListener("beforeunload",()=>{this.cancelAllPendingClicks();}),setInterval(()=>{i();},100);}isInteractiveElement(e){const t=e.tagName.toLowerCase();if("button"===t||"a"===t)return true;if(["input","select","textarea"].includes(t))return true;const i=e.getAttribute("role");if(i&&["button","link","tab","menuitem","checkbox","radio"].includes(i))return true;if(e.onclick||e.getAttribute("onclick"))return true;try{if("pointer"===window.getComputedStyle(e).cursor)return !0}catch(e){}return !!e.closest('button, a, [role="button"], [role="link"], [role="tab"], [role="menuitem"]')}ignoreClickForDeadDetection(e){if("html"===e.tagName.toLowerCase())return true;const t=Date.now();for(const i of this.deadClickTracker.pendingClicks.values())if(i.element===e&&Math.abs(t-i.timestamp)<1e3)return true;return false}cancelPendingClick(e){const t=this.deadClickTracker.pendingClicks.get(e);t&&!t.cancelled&&(clearTimeout(t.timer),t.cancelled=true,this.deadClickTracker.pendingClicks.delete(e));}cancelAllPendingClicks(){this.deadClickTracker.pendingClicks.forEach((e,t)=>{e.cancelled||(clearTimeout(e.timer),this.deadClickTracker.pendingClicks.delete(t));});}async handleDeadClickTimeout(e){const t=this.deadClickTracker.pendingClicks.get(e);if(!t||t.cancelled)return;const i=Date.now()-t.timestamp;let s;const n=t.lastMutationTimeAtClick||0,r=this.deadClickTracker.lastMutationTime||0,o=r>n&&r>=t.timestamp,a=n>0&&n<t.timestamp&&t.timestamp-n<50;let c;o?s=r-t.timestamp:a&&(s=0),this.deadClickTracker.lastSelectionChangedTime&&t.timestamp<=this.deadClickTracker.lastSelectionChangedTime&&(c=this.deadClickTracker.lastSelectionChangedTime-t.timestamp);const d=void 0!==s&&s<this.DEAD_CLICK_MUTATION_THRESHOLD_MS,l=void 0!==c&&c<this.DEAD_CLICK_SELECTION_THRESHOLD_MS;d||l||await this.fireDeadClickEvent(t,i,s,c),this.deadClickTracker.pendingClicks.delete(e);}async fireDeadClickEvent(e,t,i,s){const n=e.element.closest('button, a, [role="button"], [role="link"]')||e.element,r={x:e.originalEvent.clientX,y:e.originalEvent.clientY,page:window.location.pathname,element:n.tagName.toLowerCase(),absoluteDelayMs:t,timestamp:e.timestamp};void 0!==i&&(r.mutationDelayMs=i),void 0!==s&&(r.selectionChangedDelayMs=s),n.id&&(r.elementId=n.id),n.className&&(r.elementClass=n.className),n.textContent&&(r.elementText=n.textContent.trim().substring(0,100)),Object.keys(r).forEach(e=>{null!==r[e]&&void 0!==r[e]||delete r[e];}),await this.customEvent("$deadclick",r);}setupAutomaticLinkTracking(e){}setupAutomaticFormTracking(e){document.addEventListener("submit",async t=>{const i=t.target,s=new FormData(i),n={formId:i.id||null,formAction:i.action||null,formMethod:i.method||"get",fields:Array.from(s.keys()),page:window.location.pathname,timestamp:Date.now()};e.includeClasses&&(n.formClass=i.className||null),Object.keys(n).forEach(e=>{null===n[e]&&delete n[e];}),await this.customEvent("$form_submitted",n);});}cleanupNavigationTracking(){this.navigationTrackingEnabled&&(this.originalPushState&&(history.pushState=this.originalPushState),this.originalReplaceState&&(history.replaceState=this.originalReplaceState),this.navigationListeners.forEach(e=>e()),this.navigationListeners=[],this.navigationTrackingEnabled=false,a("Navigation tracking cleaned up"));}static logToStorage(e){o(e);}static configureLogging(e){s.setConfig({level:{none:0,error:1,warn:2,info:3,debug:4}[e.level||"error"],enableConsole:false!==e.enableConsole,enableStorage:e.enableStorage||false});}enableConsoleTracking(){I&&!this.consoleTrackingEnabled&&(this.originalConsole={log:console.log,warn:console.warn,error:console.error},console.log=(...e)=>{this.trackConsoleEvent("log",e),this.originalConsole.log(...e);},console.warn=(...e)=>{this.trackConsoleEvent("warn",e),this.originalConsole.warn(...e);},console.error=(...e)=>{this.trackConsoleEvent("error",e),this.originalConsole.error(...e);},this.consoleTrackingEnabled=true,a("Console tracking enabled"));}disableConsoleTracking(){I&&this.consoleTrackingEnabled&&(this.originalConsole&&(console.log=this.originalConsole.log,console.warn=this.originalConsole.warn,console.error=this.originalConsole.error),this.consoleTrackingEnabled=false,a("Console tracking disabled"));}trackConsoleEvent(e,t){if(this.initialized)try{const i={level:e,message:t.map(e=>"object"==typeof e?JSON.stringify(e):String(e)).join(" "),timestamp:(new Date).toISOString(),url:window.location.href};this.addEvent({type:5,data:{payload:{eventType:"console",...i}},timestamp:Date.now()}).catch(e=>{n("Failed to track console event:",e);});}catch(e){n("Error in trackConsoleEvent:",e);}}setupPageUnloadHandler(){if(!I)return;a("Setting up page unload handler"),window.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState&&(a("Page hidden - sending pending events"),this.flushEvents());}),window.addEventListener("beforeunload",()=>{this.flushEvents();});const e=()=>{localStorage.setItem(`human_behavior_last_activity_${this.apiKey}`,Date.now().toString());};window.addEventListener("click",e),window.addEventListener("keydown",e),window.addEventListener("scroll",e),window.addEventListener("mousemove",e);}viewLogs(){try{const e=s.getLogs();o("HumanBehavior Logs:",e),s.clearLogs();}catch(e){n("Failed to read logs:",e);}}async identifyUser({userProperties:e}){const t=this.endUserId;this.userProperties=e,a("Identifying user:",{userProperties:e,originalEndUserId:t,sessionId:this.sessionId}),!I||this.propertyManager.getAutomaticProperties();const i=await this.api.sendUserData(t||"",e,this.sessionId);if(i.actualUserId||i.wasExistingUser){const e=i.actualUserId||t;if(e&&e!==t){const i=`human_behavior_end_user_id_${this.apiKey}`;if(this.setCookie(i,e,365),I)try{localStorage.setItem(i,e);}catch(e){a("Failed to set canonical endUserId in localStorage:",e);}a(`🔗 Preexisting user detected. Future sessions will use canonical ID: ${e} (current session stays: ${t})`);}}return t||""}getUserAttributes(){return {...this.userProperties}}async start(){if(!I)return;if(this.isStarted)return void a("HumanBehaviorTracker already started, skipping start() call.");this.isStarted=true,this.flushInterval=window.setInterval(()=>{this.flushEvents();},this.FLUSH_INTERVAL_MS);const t=()=>{if(this.recordInstance)return void a("🎯 Recording already started, skipping duplicate start");a("🎯 DOM ready, starting session recording"),this.rrwebRecord=record;const t=record({emit:e=>{this.addRecordingEvent(e),2===e.type&&a(`🎯 FullSnapshot generated at ${(new Date).toISOString()}`);},maskTextSelector:this.redactionManager.getMaskTextSelector()||void 0,maskTextFn:void 0,maskAllInputs:"privacy-first"===this.redactionManager.getRedactionMode(),maskInputOptions:{password:true,text:true,textarea:true,email:true,number:true,tel:true,url:true,search:true,date:true,time:true,month:true,week:true},maskInputFn:(e,t)=>{try{const i=this.redactionManager.getRedactionMode();if(!(t instanceof HTMLElement))return e;if("privacy-first"===i)return "*".repeat(e.length||1);const s=this.redactionManager.shouldUnredactElement(t);t.id,t.name,t.type;return s?e:"*".repeat(e.length||1)}catch{return e}},slimDOMOptions:{},collectFonts:false,inlineStylesheet:true,recordCrossOriginIframes:false,recordCanvas:this.recordCanvas,sampling:this.recordCanvas?{canvas:4}:void 0,dataURLOptions:this.recordCanvas?{type:"image/webp",quality:.4}:void 0,hooks:{input:e=>{try{if("privacy-first"===this.redactionManager.getRedactionMode())return;const t="undefined"!=typeof document?document.querySelector(`[data-rrweb-id="${e.id}"]`):null;if(t&&t instanceof HTMLElement){this.redactionManager.shouldUnredactElement(t)||(void 0!==e.text&&(e.text="*".repeat(e.text?.length||1)),void 0!==e.value&&(e.value="*".repeat(e.value?.length||1)));}}catch{}}}});this.recordInstance=t||null;};if(a(`🎯 DOM ready state: ${document.readyState}`),"complete"===document.readyState||"interactive"===document.readyState)a(`🎯 DOM ready (${document.readyState}), starting recording immediately`),t();else {a("🎯 DOM not ready, waiting for DOMContentLoaded event");const e=()=>("interactive"===document.readyState||"complete"===document.readyState)&&(a(`🎯 DOM ready (${document.readyState}), starting recording`),t(),true);if(e())return;document.addEventListener("DOMContentLoaded",()=>{a("🎯 DOMContentLoaded fired, starting recording"),t();},{once:true});const i=setInterval(()=>{e()&&clearInterval(i);},10);setTimeout(()=>clearInterval(i),5e3);}}takeFullSnapshot(){this.fullSnapshotTimeout&&clearTimeout(this.fullSnapshotTimeout),this.fullSnapshotTimeout=window.setTimeout(()=>{try{requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.rrwebRecord&&"function"==typeof this.rrwebRecord.takeFullSnapshot?(this.rrwebRecord.takeFullSnapshot(),a("✅ FullSnapshot taken for navigation (delayed for animations)")):r("⚠️ takeFullSnapshot not available on record function");});});}catch(e){n("❌ Failed to take FullSnapshot for navigation:",e);}},1e3);}async stop(){await this.ensureInitialized(),I&&(this.flushInterval&&(clearInterval(this.flushInterval),this.flushInterval=null),this.recordInstance&&(this.recordInstance(),this.recordInstance=null),this.fullSnapshotTimeout&&(clearTimeout(this.fullSnapshotTimeout),this.fullSnapshotTimeout=null),this.rrwebRecord=null,this.disableConsoleTracking(),this.cleanupNavigationTracking(),this.deadClickTracker.mutationObserver&&(this.deadClickTracker.mutationObserver.disconnect(),this.deadClickTracker.mutationObserver=void 0),this.deadClickTracker.pendingClicks.forEach((e,t)=>{e.cancelled||clearTimeout(e.timer);}),this.deadClickTracker.pendingClicks.clear());}async addEvent(e){if(I&&this.checkAndRefreshSession(),e&&"object"==typeof e){if(2===e.type){const t=!!e.data,i=!(!e.data||!e.data.node);a(t&&i?`✅ Valid FullSnapshot: hasData=${t}, hasNode=${i}, dataType=${e.data?.node?.type}`:`⚠️ Empty FullSnapshot detected: hasData=${t}, hasNode=${i} - continuing session`);}this.eventQueue.length>=this.MAX_QUEUE_SIZE&&(this.eventQueue.shift(),a("Queue is full, the oldest event is dropped.")),this.eventQueue.push(e),2===e.type?(a("FullSnapshot added, triggering immediate flush"),this.flushEvents()):this.eventQueue.length>=.8*this.MAX_QUEUE_SIZE&&(a(`Queue at ${this.eventQueue.length}/${this.MAX_QUEUE_SIZE}, triggering immediate flush`),this.flushEvents());}else a("⚠️ Skipping invalid event:",e);}async flushEvents(){if(!this.isProcessing&&!this.monthlyLimitReached){this.isProcessing=true;try{const e=this.eventQueue;if(this.eventQueue=[],e.length>0){a("Flushing events:",e);const t=e.filter(e=>2===e.type);t.length>0&&a(`[FIXED] Sending ${t.length} FullSnapshot(s) with valid data`);try{const t=this.propertyManager.getAutomaticProperties();console.log(`[HumanBehavior] 📤 Sending ${e.length} events - SessionId: ${this.sessionId}, EndUserId: ${this.endUserId}, WindowId: ${this.windowId}`),await this.api.sendEventsChunked(e,this.sessionId,this.endUserId,this.windowId,t),console.log(`[HumanBehavior] ✅ Successfully sent ${e.length} events`);}catch(e){if(e.message?.includes("ERROR: Session already completed"))r("Session expired, events will be lost");else if(e.message?.includes("413")||e.message?.includes("Content Too Large"))r("Payload too large, events will be lost");else {if(!(e.message?.includes("ERR_BLOCKED_BY_CLIENT")||e.message?.includes("Failed to fetch")||e.message?.includes("NetworkError")))throw e;r("Request blocked by ad blocker or network issue, events will be lost");}}}}finally{this.isProcessing=false;}}}async addRecordingEvent(e){if(I&&this.checkAndRefreshSession(),e&&"object"==typeof e){if(2===e.type){const t=!!e.data,i=!(!e.data||!e.data.node);a(t&&i?`✅ Valid FullSnapshot: hasData=${t}, hasNode=${i}, dataType=${e.data?.node?.type}`:`⚠️ Empty FullSnapshot detected: hasData=${t}, hasNode=${i} - continuing session`);}this.eventQueue.length>=this.MAX_QUEUE_SIZE&&(this.eventQueue.shift(),a("Queue is full, the oldest event is dropped.")),this.eventQueue.push(e),2===e.type?(a("FullSnapshot added, triggering immediate flush"),this.flushEvents()):this.eventQueue.length>=.8*this.MAX_QUEUE_SIZE&&(a(`Queue at ${this.eventQueue.length}/${this.MAX_QUEUE_SIZE}, triggering immediate flush`),this.flushEvents());}else a("⚠️ Skipping invalid recording event:",e);}setCookie(e,t,i){if(I)try{const s=new Date;s.setTime(s.getTime()+24*i*60*60*1e3);const n=`expires=${s.toUTCString()}`;document.cookie=`${e}=${t};${n};path=/;SameSite=Lax`,localStorage.setItem(e,t),a(`Set cookie and localStorage: ${e}`);}catch(i){try{localStorage.setItem(e,t),a(`Cookie blocked, using localStorage: ${e}`);}catch(e){n("Failed to store user ID in both cookie and localStorage:",e);}}}getCookie(e){if(!I)return null;try{const t=e+"=",i=document.cookie.split(";");for(let s=0;s<i.length;s++){let n=i[s];for(;" "===n.charAt(0);)n=n.substring(1,n.length);if(0===n.indexOf(t)){const i=n.substring(t.length,n.length);return a(`Found cookie: ${e}`),i}}const s=localStorage.getItem(e);return s?(a(`Cookie not found, using localStorage: ${e}`),s):null}catch(t){try{const t=localStorage.getItem(e);if(t)return a(`Cookie access failed, using localStorage: ${e}`),t}catch(e){n("Failed to access both cookie and localStorage:",e);}return null}}deleteCookie(e){if(I){try{document.cookie=`${e}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; SameSite=Lax`,a(`Deleted cookie: ${e}`);}catch(t){n(`Failed to delete cookie: ${e}`,t);}try{localStorage.removeItem(e),a(`Removed from localStorage: ${e}`);}catch(t){n(`Failed to remove from localStorage: ${e}`,t);}}}logout(){if(I)try{const e=`human_behavior_end_user_id_${this.apiKey}`;this.deleteCookie(e);const i=`human_behavior_session_${this.apiKey}`;localStorage.removeItem(i),this.endUserId=null,this.userProperties={},this.endUserId=v1(),this.setCookie(`human_behavior_end_user_id_${this.apiKey}`,this.endUserId,365),this.sessionId=this.createNewSession(i),this.windowId=v1(),o("User logged out - cleared all user data and started fresh session");}catch(e){n("Error during logout:",e);}}async redact(e){await this.ensureInitialized(),I?this.redactionManager=new u(e):r("Redaction is only available in browser environments");}setRedactedFields(e){this.redactionManager.setFieldsToRedact(e),this.recordInstance&&this.restartWithNewRedaction();}setUnredactedFields(e){this.redactionManager.setFieldsToUnredact(e),this.recordInstance&&this.restartWithNewRedaction();}restartWithNewRedaction(){this.recordInstance&&(this.recordInstance(),this.start());}hasUnredactedFields(){return this.redactionManager.hasUnredactedFields()}getUnredactedFields(){return this.redactionManager.getUnredactedFields()}redactFields(e){this.redactionManager.redactFields(e),this.recordInstance&&this.restartWithNewRedaction();}clearUnredactedFields(){this.redactionManager.clearUnredactedFields(),this.recordInstance&&this.restartWithNewRedaction();}checkAndRefreshSession(){if(!I)return;const e=`human_behavior_session_${this.apiKey}`,i=this.getStoredSession(e),s=Date.now();if(!i)return this.sessionId=this.createNewSession(e),this.windowId=v1(),a(`Created new session (no stored session): ${this.sessionId}`),void console.log(`[HumanBehavior] 🆕 Created new session (no stored session): ${this.sessionId}`);const n=s-i.lastActivityTimestamp,r=s-i.sessionStartTimestamp,c=Math.round(n/1e3/60),d=Math.round(r/1e3/60/60);if(n>3e5||r>864e5){a(`Session expired: idle=${c}min, age=${d}hrs`);const i=this.sessionId;return this.sessionId=this.createNewSession(e),this.windowId=v1(),o(`🔄 Session timeout: Created new session ${this.sessionId} (previous: ${i})`),console.log(`[HumanBehavior] 🔄 Session expired! Created new session: ${this.sessionId} (previous: ${i})`),void console.log("[HumanBehavior] ⏱️ Timeout reason: "+(c>5?`Idle for ${c} minutes`:`Session age ${d} hours`))}i.sessionId!==this.sessionId&&(this.sessionId=i.sessionId,a(`Session ID synced from storage: ${this.sessionId}`),console.log(`[HumanBehavior] 🔄 Session ID synced from storage: ${this.sessionId}`)),this.updateSessionActivity(e,s,i.sessionId,i.sessionStartTimestamp),console.log(`[HumanBehavior] ✅ Session active - SessionId: ${this.sessionId}, Idle: ${c}min, Age: ${d}hrs`);}getOrCreateSessionId(){if(!I)return v1();const e=`human_behavior_session_${this.apiKey}`,i=this.getStoredSession(e),s=Date.now();if(!i)return this.createNewSession(e);const n=s-i.lastActivityTimestamp,r=s-i.sessionStartTimestamp;return n>3e5||r>864e5?(a(`Session expired: idle=${n}ms, age=${r}ms`),this.createNewSession(e)):(this.updateSessionActivity(e,s,i.sessionId,i.sessionStartTimestamp),i.sessionId)}getStoredSession(e){try{const t=localStorage.getItem(e);return t?JSON.parse(t):null}catch{return null}}createNewSession(e){const i=v1(),s=Date.now(),n={sessionId:i,lastActivityTimestamp:s,sessionStartTimestamp:s};return localStorage.setItem(e,JSON.stringify(n)),a(`Created new session: ${i}`),console.log(`[HumanBehavior] 🆕 Created new session: ${i} at ${new Date(s).toLocaleTimeString()}`),i}updateSessionActivity(e,t,i,s){const n={sessionId:i,lastActivityTimestamp:t,sessionStartTimestamp:s};localStorage.setItem(e,JSON.stringify(n));}getSessionId(){return this.sessionId}getCurrentUrl(){return this.currentUrl}getSnapshotFrequencyInfo(){return {sessionDuration:Date.now()-this.sessionStartTime,currentInterval:3e5,currentThreshold:1e3,phase:"configured"}}async testConnection(){try{return await this.api.init(this.sessionId,this.endUserId),{success:!0}}catch(e){return {success:false,error:e.message||"Unknown error"}}}getConnectionStatus(){const e=[];let t=false;return this.eventQueue.length>0&&(t=true,e.push("Some requests may be blocked by ad blockers")),this._connectionBlocked&&(t=true,e.push("Initial connection test failed - ad blocker may be active")),"undefined"==typeof window&&e.push("Not running in browser environment"),void 0===navigator.sendBeacon&&e.push("sendBeacon not available, using fetch fallback"),{blocked:t,recommendations:e}}isPreexistingUser(){if(!I)return false;const e=this.getCookie(`human_behavior_end_user_id_${this.apiKey}`);return null!==e&&e!==this.endUserId}getUserInfo(){return {endUserId:this.endUserId,sessionId:this.sessionId,isPreexistingUser:this.isPreexistingUser(),initialized:this.initialized}}setSessionProperty(e,t){this.propertyManager.setSessionProperty(e,t);}setSessionProperties(e){this.propertyManager.setSessionProperties(e);}getSessionProperty(e){return this.propertyManager.getSessionProperty(e)}removeSessionProperty(e){this.propertyManager.removeSessionProperty(e);}setUserProperty(e,t){this.propertyManager.setUserProperty(e,t);}setUserProperties(e){this.propertyManager.setUserProperties(e);}getUserProperty(e){return this.propertyManager.getUserProperty(e)}removeUserProperty(e){this.propertyManager.removeUserProperty(e);}setOnce(e,t,i="user"){this.propertyManager.setOnce(e,t,i);}clearSessionProperties(){this.propertyManager.clearSessionProperties();}clearUserProperties(){this.propertyManager.clearUserProperties();}getAllProperties(){return this.propertyManager.getAllProperties()}}function _(e){const t=globalThis.__humanBehaviorGlobalTracker;return t?.identifyUser?t.identifyUser({userProperties:e}):(console.warn("HumanBehavior tracker not found. Make sure the SDK is initialized."),null)}function T(e,t){const i=globalThis.__humanBehaviorGlobalTracker;return i?.track?i.track(e,t):(console.warn("HumanBehavior tracker not found. Make sure the SDK is initialized."),null)}function b(){const e=globalThis.__humanBehaviorGlobalTracker;return !!e?.identifyUser}I&&(window.HumanBehaviorTracker=C);
|
|
12177
12177
|
|
|
12178
12178
|
/**
|
|
12179
12179
|
* Main entry point for the HumanBehavior SDK
|
|
@@ -12196,15 +12196,15 @@ exports.RedactionManager = u;
|
|
|
12196
12196
|
exports.getAutomaticProperties = v;
|
|
12197
12197
|
exports.getCurrentPageProperties = k;
|
|
12198
12198
|
exports.getDeviceInfo = f;
|
|
12199
|
-
exports.getInitialProperties =
|
|
12200
|
-
exports.getLocationInfo =
|
|
12201
|
-
exports.identifyUserGlobally =
|
|
12199
|
+
exports.getInitialProperties = y;
|
|
12200
|
+
exports.getLocationInfo = w;
|
|
12201
|
+
exports.identifyUserGlobally = _;
|
|
12202
12202
|
exports.init = init;
|
|
12203
|
-
exports.isGlobalTrackerAvailable =
|
|
12204
|
-
exports.logDebug =
|
|
12203
|
+
exports.isGlobalTrackerAvailable = b;
|
|
12204
|
+
exports.logDebug = a;
|
|
12205
12205
|
exports.logError = n;
|
|
12206
|
-
exports.logInfo =
|
|
12206
|
+
exports.logInfo = o;
|
|
12207
12207
|
exports.logWarn = r;
|
|
12208
12208
|
exports.logger = s;
|
|
12209
|
-
exports.sendEventGlobally =
|
|
12209
|
+
exports.sendEventGlobally = T;
|
|
12210
12210
|
//# sourceMappingURL=index.js.map
|