ainamika-sdk 1.1.6 → 1.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -11,7 +11,9 @@
11
11
  - **Web Vitals & Performance Tracking**: Core Web Vitals (LCP, FCP, FID, CLS, TTFB) and page load metrics
12
12
  - **Engagement Analytics**: Scroll depth, rage clicks, time on page, active/idle time tracking
13
13
  - **API Response Tracking**: Track and analyze API calls with timing and response data
14
- - **Error Tracking**: Comprehensive error capture with stack traces, screenshots, and DOM snapshots
14
+ - **Error Tracking**: Comprehensive error capture with stack traces, screenshots, device info, and DOM snapshots
15
+ - **Page Context & Query Params**: Automatic capture of URL, path, query parameters, referrer with every event
16
+ - **Extra Config Support**: Pass custom data (userId, deviceId, appVersion) that's included in all events
15
17
  - **Smart Event Naming**: AI generates semantic event names like `game_launch_cubeform` instead of generic names
16
18
  - **User Journey Analysis**: Track complete user journeys for funnel optimization
17
19
  - **Sampling Support**: Server-side sampling to control data volume and costs
@@ -240,6 +242,14 @@ const analytics = new AInamikaSDK({
240
242
  batchInterval: 5000 // Batch interval in ms (default: 5000)
241
243
  },
242
244
 
245
+ // Extra Config - Custom data included with ALL events
246
+ extraConfig: {
247
+ appVersion: '2.0.0', // Your app version
248
+ environment: 'production', // Environment name
249
+ deviceId: 'device_abc123', // Custom device ID
250
+ buildNumber: '1234' // Any custom data you need
251
+ },
252
+
243
253
  // Advanced Tracking (NEW)
244
254
  advancedTracking: {
245
255
  enabled: true, // Master toggle (default: true)
@@ -275,6 +285,91 @@ const analytics = new AInamikaSDK({
275
285
  });
276
286
  ```
277
287
 
288
+ ## Extra Config & Page Context
289
+
290
+ Every event automatically includes **page context** (URL, path, query params, referrer) and any **extra config** you provide.
291
+
292
+ ### Page Context (Automatic)
293
+
294
+ All events include:
295
+
296
+ ```javascript
297
+ {
298
+ pageContext: {
299
+ url: "https://example.com/products?utm_source=google&campaign=summer",
300
+ path: "/products",
301
+ queryParams: {
302
+ utm_source: "google",
303
+ campaign: "summer"
304
+ },
305
+ referrer: "https://google.com",
306
+ title: "Products - My Store",
307
+ hash: "#featured" // if present
308
+ }
309
+ }
310
+ ```
311
+
312
+ ### Extra Config
313
+
314
+ Pass custom data that will be included with **every event**:
315
+
316
+ ```javascript
317
+ // Set during initialization
318
+ const analytics = new AInamikaSDK({
319
+ projectKey: 'proj_xxx',
320
+ extraConfig: {
321
+ appVersion: '2.0.0',
322
+ environment: 'production',
323
+ region: 'us-east'
324
+ }
325
+ });
326
+
327
+ // Update after user login (merges with existing)
328
+ analytics.setExtraConfig({
329
+ userId: 'user_12345',
330
+ plan: 'premium',
331
+ company: 'Acme Inc'
332
+ });
333
+
334
+ // Replace entire extraConfig (pass false to not merge)
335
+ analytics.setExtraConfig({ newKey: 'value' }, false);
336
+
337
+ // Get current extraConfig
338
+ const config = analytics.getExtraConfig();
339
+ ```
340
+
341
+ ### Event Data Structure
342
+
343
+ Every tracked event includes:
344
+
345
+ ```javascript
346
+ {
347
+ event: "button_click",
348
+ properties: { /* your event data */ },
349
+ timestamp: 1704067200000,
350
+ userId: "user_12345",
351
+ sessionId: "sess_abc123",
352
+ project_key: "proj_xxx",
353
+
354
+ // Automatic page context
355
+ pageContext: {
356
+ url: "https://example.com/checkout?ref=cart",
357
+ path: "/checkout",
358
+ queryParams: { ref: "cart" },
359
+ referrer: "https://example.com/cart",
360
+ title: "Checkout"
361
+ },
362
+
363
+ // Your custom extraConfig
364
+ extraConfig: {
365
+ appVersion: "2.0.0",
366
+ environment: "production",
367
+ userId: "user_12345",
368
+ plan: "premium"
369
+ }
370
+ }
371
+ ```
372
+
278
373
  ## Smart Event Naming
279
374
 
280
375
  The SDK uses AI to generate semantic event names from your DOM:
@@ -348,6 +443,8 @@ new AInamikaSDK(config: AnalyticsConfig)
348
443
  | `getPerformanceMetrics()` | Get Web Vitals metrics |
349
444
  | `getEngagementMetrics()` | Get engagement metrics |
350
445
  | `identifyUser(userId, properties?)` | Identify authenticated user |
446
+ | `setExtraConfig(config, merge?)` | Set/update extra config (included in all events) |
447
+ | `getExtraConfig()` | Get current extra config |
351
448
  | `captureException(error, context?)` | Manually capture exception |
352
449
  | `flushStoredErrors()` | Flush queued errors |
353
450
  | `getSamplingStatus()` | Get sampling decision |
@@ -1,2 +1,2 @@
1
- !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.AInamikaSDKPro=t():e.AInamikaSDKPro=t()}("undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:this,function(){return function(){"use strict";var e={d:function(t,r){for(var n in r)e.o(r,n)&&!e.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:r[n]})},o:function(e,t){return Object.prototype.hasOwnProperty.call(e,t)}},t={};e.d(t,{default:function(){return C}});var r=function(){return r=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},r.apply(this,arguments)},n=function(e,t,r,n){return new(r||(r=Promise))(function(o,i){function a(e){try{c(n.next(e))}catch(e){i(e)}}function s(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(a,s)}c((n=n.apply(e,t||[])).next())})},o=function(e,t){var r,n,o,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=s(0),a.throw=s(1),a.return=s(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(s){return function(c){return function(s){if(r)throw new TypeError("Generator is already executing.");for(;a&&(a=0,s[0]&&(i=0)),i;)try{if(r=1,n&&(o=2&s[0]?n.return:s[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,s[1])).done)return o;switch(n=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,n=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){i.label=s[1];break}if(6===s[0]&&i.label<o[1]){i.label=o[1],o=s;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(s);break}o[2]&&i.ops.pop(),i.trys.pop();continue}s=t.call(e,i)}catch(e){s=[6,e],n=0}finally{r=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}},i=function(e,t,r){if(r||2===arguments.length)for(var n,o=0,i=t.length;o<i;o++)!n&&o in t||(n||(n=Array.prototype.slice.call(t,0,o)),n[o]=t[o]);return e.concat(n||Array.prototype.slice.call(t))},a=function(){function e(e){this.breadcrumbs=[],this.errorCount=0,this.errorDebounceMap=new Map,this.html2canvasLoaded=!1,this.html2canvasLoading=null,this.isCapturingScreenshot=!1,this.config=r({captureScreenshots:!1,captureDomSnapshots:!1,maxStackTraceDepth:50,maxErrorsPerSession:100,debounceMs:1e3,enableNetworkTracking:!0,enableConsoleCapture:!0},e),this.authManager=e.authManager,this.sessionId=this.generateSessionId(),this.originalConsole=r({},console),this.initialize()}return e.prototype.loadHtml2Canvas=function(){return n(this,void 0,void 0,function(){var e=this;return o(this,function(t){return this.html2canvasLoaded||"function"==typeof window.html2canvas?(this.html2canvasLoaded=!0,[2,!0]):(this.html2canvasLoading||(this.html2canvasLoading=new Promise(function(t){var r=document.createElement("script");r.src="https://html2canvas.hertzen.com/dist/html2canvas.min.js",r.async=!0,r.onload=function(){console.log("[AInamika Error Tracker] html2canvas loaded successfully"),e.html2canvasLoaded=!0,t(!0)},r.onerror=function(){console.error("[AInamika Error Tracker] Failed to load html2canvas"),t(!1)},document.head.appendChild(r)})),[2,this.html2canvasLoading])})})},e.prototype.initialize=function(){var e=this;window.addEventListener("error",function(t){e.handleError({type:"javascript",message:t.message,filename:t.filename,line:t.lineno,column:t.colno,error:t.error})}),window.addEventListener("unhandledrejection",function(t){var r;e.handleError({type:"unhandled",message:(null===(r=t.reason)||void 0===r?void 0:r.message)||"Unhandled Promise Rejection",error:t.reason,promise:!0})}),this.config.enableNetworkTracking&&this.setupNetworkTracking(),this.config.enableConsoleCapture&&this.setupConsoleCapture(),this.setupNavigationTracking(),this.setupClickTracking(),this.config.captureScreenshots&&this.loadHtml2Canvas(),console.log("[AInamika Error Tracker] Initialized successfully")},e.prototype.generateSessionId=function(){return"session_".concat(Date.now(),"_").concat(Math.random().toString(36).substr(2,9))},e.prototype.addBreadcrumb=function(e){this.breadcrumbs.push(r(r({},e),{timestamp:Date.now()})),this.breadcrumbs.length>50&&(this.breadcrumbs=this.breadcrumbs.slice(-50))},e.prototype.handleError=function(e){if(this.errorCount>=this.config.maxErrorsPerSession)console.warn("[AInamika Error Tracker] Max errors per session reached");else{var t="".concat(e.message,"_").concat(e.filename,"_").concat(e.line),r=Date.now();if(this.errorDebounceMap.has(t)&&r-this.errorDebounceMap.get(t)<this.config.debounceMs)return;this.errorDebounceMap.set(t,r),this.errorCount++,this.captureError(e)}},e.prototype.captureError=function(e){return n(this,void 0,void 0,function(){var t,r,n;return o(this,function(o){switch(o.label){case 0:return o.trys.push([0,4,,5]),t={client_id:this.config.clientId,project_key:this.config.projectKey,error_type:e.type||"javascript",message:e.message||"Unknown error",stack_trace:this.extractStackTrace(e.error),url:window.location.href,user_agent:navigator.userAgent,timestamp:Date.now(),error_metadata:{line:e.line,column:e.column,filename:e.filename,userId:this.userId,sessionId:this.sessionId,breadcrumbs:i([],this.breadcrumbs,!0),networkInfo:this.getNetworkInfo(),performance:this.getPerformanceInfo(),deviceInfo:this.getDeviceInfo()},severity:this.assessSeverity(e),session_id:this.sessionId,user_id:this.userId},this.config.captureScreenshots?(r=t,[4,this.captureScreenshot()]):[3,2];case 1:r.screen_snapshot=o.sent(),o.label=2;case 2:return[4,this.sendError(t)];case 3:return o.sent(),this.addBreadcrumb({type:"error",message:"".concat(t.error_type,": ").concat(t.message),data:{severity:t.severity}}),[3,5];case 4:return n=o.sent(),console.error("[AInamika Error Tracker] Failed to capture error:",n),[3,5];case 5:return[2]}})})},e.prototype.extractStackTrace=function(e){if(!e||!e.stack)return"";var t=e.stack.split("\n"),r=this.config.maxStackTraceDepth;return t.slice(0,r).join("\n")},e.prototype.assessSeverity=function(e){var t,r=(null===(t=e.message)||void 0===t?void 0:t.toLowerCase())||"";return r.includes("out of memory")||r.includes("security")||r.includes("permission denied")||"unhandled"===e.type?"critical":r.includes("network")||r.includes("timeout")||r.includes("failed to fetch")||r.includes("cors")?"high":r.includes("undefined")||r.includes("null")||r.includes("cannot read property")?"medium":"low"},e.prototype.captureDomSnapshot=function(){try{var e={url:window.location.href,title:document.title,viewport:{width:window.innerWidth,height:window.innerHeight},elements:this.extractDomElements()};return JSON.stringify(e)}catch(e){return console.error("[AInamika Error Tracker] Failed to capture DOM snapshot:",e),""}},e.prototype.extractDomElements=function(){var e=this,t=[];return["body > *","[id]",'[class*="error"]','[class*="modal"]',"form","button",'input[type="submit"]'].forEach(function(r){try{var n=document.querySelectorAll(r);Array.from(n).slice(0,100-t.length).forEach(function(r){var n;t.push({tagName:r.tagName,id:r.id,className:r.className,textContent:null===(n=r.textContent)||void 0===n?void 0:n.substring(0,100),attributes:e.getElementAttributes(r)})})}catch(e){}}),t},e.prototype.getElementAttributes=function(e){var t={};return["id","class","type","name","value","href","src"].forEach(function(r){var n=e.getAttribute(r);n&&(t[r]=n)}),t},e.prototype.captureScreenshot=function(){return n(this,void 0,void 0,function(){var e;return o(this,function(t){switch(t.label){case 0:if(this.isCapturingScreenshot)return[2,""];this.isCapturingScreenshot=!0,t.label=1;case 1:return t.trys.push([1,5,6,7]),[4,this.loadHtml2Canvas()];case 2:return t.sent()?"function"!=typeof window.html2canvas?[3,4]:[4,window.html2canvas(document.body,{height:Math.min(window.innerHeight,1e3),width:Math.min(window.innerWidth,1e3),useCORS:!0,logging:!1})]:(console.warn("[AInamika Error Tracker] html2canvas not available, skipping screenshot"),[2,""]);case 3:return[2,t.sent().toDataURL("image/jpeg",.7)];case 4:return[2,""];case 5:return e=t.sent(),console.error("[AInamika Error Tracker] Failed to capture screenshot:",e),[2,""];case 6:return this.isCapturingScreenshot=!1,[7];case 7:return[2]}})})},e.prototype.getNetworkInfo=function(){var e=navigator.connection||navigator.mozConnection||navigator.webkitConnection;return e?{effectiveType:e.effectiveType,downlink:e.downlink,rtt:e.rtt,saveData:e.saveData}:{}},e.prototype.getPerformanceInfo=function(){var e={};if(performance.memory&&(e.memory={usedJSHeapSize:performance.memory.usedJSHeapSize,totalJSHeapSize:performance.memory.totalJSHeapSize,jsHeapSizeLimit:performance.memory.jsHeapSizeLimit}),performance.timing){var t=performance.timing;e.timing={domContentLoaded:t.domContentLoadedEventEnd-t.navigationStart,load:t.loadEventEnd-t.navigationStart},performance.getEntriesByType&&performance.getEntriesByType("paint").forEach(function(t){"first-paint"===t.name?e.timing.firstPaint=t.startTime:"first-contentful-paint"===t.name&&(e.timing.firstContentfulPaint=t.startTime)})}return e},e.prototype.getDeviceInfo=function(){var e=navigator.userAgent,t="desktop";/tablet|ipad|playbook|silk/i.test(e)?t="tablet":/mobile|iphone|ipod|android|blackberry|opera mini|iemobile/i.test(e)&&(t="mobile");var r="Unknown",n="";/windows/i.test(e)?(r="Windows",(a=e.match(/Windows NT (\d+\.\d+)/))&&(n=a[1])):/macintosh|mac os x/i.test(e)?(r="macOS",(a=e.match(/Mac OS X (\d+[._]\d+)/))&&(n=a[1].replace("_","."))):/android/i.test(e)?(r="Android",(a=e.match(/Android (\d+(\.\d+)?)/))&&(n=a[1])):/iphone|ipad|ipod/i.test(e)?(r="iOS",(a=e.match(/OS (\d+[._]\d+)/))&&(n=a[1].replace("_","."))):/linux/i.test(e)&&(r="Linux");var o="Unknown",i="";if(/edg/i.test(e))o="Edge",(a=e.match(/Edg\/(\d+(\.\d+)?)/))&&(i=a[1]);else if(/chrome/i.test(e)&&!/edg/i.test(e))o="Chrome",(a=e.match(/Chrome\/(\d+(\.\d+)?)/))&&(i=a[1]);else if(/safari/i.test(e)&&!/chrome/i.test(e))o="Safari",(a=e.match(/Version\/(\d+(\.\d+)?)/))&&(i=a[1]);else if(/firefox/i.test(e)){var a;o="Firefox",(a=e.match(/Firefox\/(\d+(\.\d+)?)/))&&(i=a[1])}return{deviceType:t,os:r,osVersion:n,browser:o,browserVersion:i,screenWidth:window.screen.width,screenHeight:window.screen.height,language:navigator.language||"",timezone:Intl.DateTimeFormat().resolvedOptions().timeZone||""}},e.prototype.setupNetworkTracking=function(){var e=this,t=window.fetch;window.fetch=function(){for(var r=[],i=0;i<arguments.length;i++)r[i]=arguments[i];return n(e,void 0,void 0,function(){var e,n,i,a;return o(this,function(o){switch(o.label){case 0:e=Date.now(),n=r[0]instanceof Request?r[0].url:String(r[0]),o.label=1;case 1:return o.trys.push([1,3,,4]),[4,t.apply(void 0,r)];case 2:return i=o.sent(),this.addBreadcrumb({type:"network",message:"Fetch ".concat(i.status," ").concat(n),data:{url:n,status:i.status,duration:Date.now()-e}}),i.ok||this.handleError({type:"network",message:"Network request failed: ".concat(i.status," ").concat(i.statusText),url:n,status:i.status}),[2,i];case 3:throw a=o.sent(),this.addBreadcrumb({type:"network",message:"Fetch failed ".concat(n),data:{url:n,error:(null==a?void 0:a.message)||"Unknown error"}}),this.handleError({type:"network",message:"Network request failed: ".concat((null==a?void 0:a.message)||"Unknown error"),url:n,error:a}),a;case 4:return[2]}})})};var r=XMLHttpRequest.prototype.open,a=XMLHttpRequest.prototype.send;XMLHttpRequest.prototype.open=function(e,t,n,o,i){return this._errorTracker={method:e,url:t,startTime:Date.now()},r.call(this,e,t,n||!0,o,i)},XMLHttpRequest.prototype.send=function(){for(var e=this,t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];var n=this._errorTracker;return this.addEventListener("loadend",function(){if(n){var t=Date.now()-n.startTime;e.status>=400&&e.dispatchEvent(new CustomEvent("networkerror",{detail:{type:"network",message:"XHR request failed: ".concat(e.status," ").concat(e.statusText),url:n.url,status:e.status}})),e.dispatchEvent(new CustomEvent("networkbreadcrumb",{detail:{type:"network",message:"XHR ".concat(e.status," ").concat(n.url),data:{method:n.method,url:n.url,status:e.status,duration:t}}}))}}),a.call.apply(a,i([this],t,!1))},document.addEventListener("networkerror",function(t){e.handleError(t.detail)}),document.addEventListener("networkbreadcrumb",function(t){e.addBreadcrumb(t.detail)})},e.prototype.setupConsoleCapture=function(){var e=this;["error","warn"].forEach(function(t){var r=e.originalConsole[t];console[t]=function(){for(var n=[],o=0;o<arguments.length;o++)n[o]=arguments[o];"function"==typeof r&&r.call.apply(r,i([console],n,!1)),"error"===t&&e.handleError({type:"console",message:n.map(function(e){return String(e)}).join(" "),consoleMethod:t}),e.addBreadcrumb({type:"console",message:"Console ".concat(t,": ").concat(n.map(function(e){return String(e)}).join(" ")),data:{level:t}})}})},e.prototype.setupNavigationTracking=function(){var e=this,t=window.location.href,r=function(){var r=window.location.href;r!==t&&(e.addBreadcrumb({type:"navigation",message:"Navigation from ".concat(t," to ").concat(r),data:{from:t,to:r}}),t=r)};window.addEventListener("popstate",r),window.addEventListener("hashchange",r);var n=history.pushState,o=history.replaceState;history.pushState=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];n.apply(this,e),setTimeout(r,0)},history.replaceState=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];o.apply(this,e),setTimeout(r,0)}},e.prototype.setupClickTracking=function(){var e=this;document.addEventListener("click",function(t){var r,n=t.target;if(n){var o=e.getElementSelector(n),i=(null===(r=n.textContent)||void 0===r?void 0:r.trim().substring(0,50))||"";e.addBreadcrumb({type:"click",message:"Clicked ".concat(o).concat(i?": ".concat(i):""),data:{selector:o,text:i,tagName:n.tagName,id:n.id,className:n.className}})}})},e.prototype.getElementSelector=function(e){if(e.id)return"#".concat(e.id);if(e.className){var t=e.className.split(" ").filter(function(e){return e}).slice(0,2);if(t.length)return".".concat(t.join("."))}return e.tagName.toLowerCase()},e.prototype.sendError=function(e){return n(this,void 0,void 0,function(){var t,n,i,a;return o(this,function(o){switch(o.label){case 0:return o.trys.push([0,5,,6]),t={"Content-Type":"application/json"},this.authManager?[4,this.authManager.getAuthHeaders()]:[3,2];case 1:return n=o.sent(),t=r(r({},t),n),[3,3];case 2:this.config.apiKey&&(t.Authorization="Bearer ".concat(this.config.apiKey)),o.label=3;case 3:return[4,fetch("".concat(this.config.endpoint,"/api/v1/errors"),{method:"POST",headers:t,body:JSON.stringify(e)})];case 4:if(!(i=o.sent()).ok)throw new Error("Failed to send error: ".concat(i.status," ").concat(i.statusText));return console.log("[AInamika Error Tracker] Error sent successfully"),[3,6];case 5:return a=o.sent(),console.error("[AInamika Error Tracker] Failed to send error:",a),this.storeErrorLocally(e),[3,6];case 6:return[2]}})})},e.prototype.storeErrorLocally=function(e){try{var t=localStorage.getItem("ainamika_errors")||"[]",r=JSON.parse(t);r.push(e),r.length>50&&r.splice(0,r.length-50),localStorage.setItem("ainamika_errors",JSON.stringify(r))}catch(e){console.error("[AInamika Error Tracker] Failed to store error locally:",e)}},e.prototype.captureException=function(e,t){this.handleError({type:"custom",message:e.message,error:e,context:t})},e.prototype.setUser=function(e){this.userId=e},e.prototype.addTag=function(e,t){this.config.clientId||(this.config.clientId+="_".concat(e,":").concat(t))},e.prototype.flushStoredErrors=function(){return n(this,void 0,void 0,function(){var e,t,r,n,i,a;return o(this,function(o){switch(o.label){case 0:if(o.trys.push([0,5,,6]),!(e=localStorage.getItem("ainamika_errors")))return[2];if(0===(t=JSON.parse(e)).length)return[2];console.log("[AInamika Error Tracker] Flushing ".concat(t.length," stored errors")),r=0,n=t,o.label=1;case 1:return r<n.length?(i=n[r],[4,this.sendError(i)]):[3,4];case 2:o.sent(),o.label=3;case 3:return r++,[3,1];case 4:return localStorage.removeItem("ainamika_errors"),[3,6];case 5:return a=o.sent(),console.error("[AInamika Error Tracker] Failed to flush stored errors:",a),[3,6];case 6:return[2]}})})},e}(),s="undefined"!=typeof window&&window.__AINAMIKA_CONFIG__?window.__AINAMIKA_CONFIG__:{API_BASE_URL:"https://ainamika-webhook-proxy-366651516847.asia-south1.run.app",APP_ENV:"production",DEBUG:!1},c={EVENTS:"".concat(s.API_BASE_URL,"/api/v1/events"),ERRORS:"".concat(s.API_BASE_URL,"/api/errors/report"),CONFIG:"".concat(s.API_BASE_URL,"/api/v1/sdk/config"),DEBUG_EVENTS:"".concat(s.API_BASE_URL,"/api/v1/debug/events"),PROJECTS_LOOKUP:"".concat(s.API_BASE_URL,"/api/v1/projects/lookup"),SAMPLING_CHECK:"".concat(s.API_BASE_URL,"/api/v1/projects/sampling/check")},u=function(){return u=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},u.apply(this,arguments)},l=function(e,t,r,n){return new(r||(r=Promise))(function(o,i){function a(e){try{c(n.next(e))}catch(e){i(e)}}function s(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(a,s)}c((n=n.apply(e,t||[])).next())})},h=function(e,t){var r,n,o,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=s(0),a.throw=s(1),a.return=s(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(s){return function(c){return function(s){if(r)throw new TypeError("Generator is already executing.");for(;a&&(a=0,s[0]&&(i=0)),i;)try{if(r=1,n&&(o=2&s[0]?n.return:s[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,s[1])).done)return o;switch(n=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,n=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){i.label=s[1];break}if(6===s[0]&&i.label<o[1]){i.label=o[1],o=s;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(s);break}o[2]&&i.ops.pop(),i.trys.pop();continue}s=t.call(e,i)}catch(e){s=[6,e],n=0}finally{r=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}},d=function(){function e(e){void 0===e&&(e={}),this.STORAGE_KEY="ainamika_error_queue",this.METADATA_KEY="ainamika_error_metadata",this.isProcessing=!1,this.config=u({maxStorageSize:5242880,maxRetries:5,retryInterval:3e4,compressionEnabled:!0,encryptionEnabled:!1},e),this.initialize()}return e.prototype.initialize=function(){var e=this;this.cleanupOldErrors(),this.startRetryTimer(),this.setupStorageListener(),setTimeout(function(){return e.processQueue()},1e3)},e.prototype.storeError=function(e){return l(this,void 0,void 0,function(){var t,r,n,o=this;return h(this,function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),t=this.generateErrorId(),r={id:t,errorData:this.config.compressionEnabled?this.compressData(e):e,timestamp:Date.now(),retryCount:0},[4,this.addToQueue(r)];case 1:return i.sent(),this.updateMetadata(),setTimeout(function(){return o.processQueue()},100),[2,t];case 2:throw n=i.sent(),console.error("[AInamika Error Storage] Failed to store error:",n),n;case 3:return[2]}})})},e.prototype.getStoredErrors=function(){var e=this;try{var t=localStorage.getItem(this.STORAGE_KEY);return t?JSON.parse(t).map(function(t){return u(u({},t),{errorData:e.config.compressionEnabled?e.decompressData(t.errorData):t.errorData})}):[]}catch(e){return console.error("[AInamika Error Storage] Failed to get stored errors:",e),[]}},e.prototype.removeError=function(e){try{var t=this.getQueueRaw(),r=t.filter(function(t){return t.id!==e});return r.length!==t.length&&(localStorage.setItem(this.STORAGE_KEY,JSON.stringify(r)),this.updateMetadata(),!0)}catch(e){return console.error("[AInamika Error Storage] Failed to remove error:",e),!1}},e.prototype.clearAll=function(){try{localStorage.removeItem(this.STORAGE_KEY),localStorage.removeItem(this.METADATA_KEY),console.log("[AInamika Error Storage] All errors cleared")}catch(e){console.error("[AInamika Error Storage] Failed to clear errors:",e)}},e.prototype.getStorageStats=function(){try{var e=this.getQueueRaw(),t=new Blob([localStorage.getItem(this.STORAGE_KEY)||""]).size,r=e.map(function(e){return e.timestamp}).sort();return{errorCount:e.length,totalSize:t,oldestError:r[0],newestError:r[r.length-1]}}catch(e){return console.error("[AInamika Error Storage] Failed to get storage stats:",e),{errorCount:0,totalSize:0}}},e.prototype.processQueue=function(){return l(this,void 0,void 0,function(){var e,t,r,n,o;return h(this,function(i){switch(i.label){case 0:if(this.isProcessing)return[2];this.isProcessing=!0,i.label=1;case 1:if(i.trys.push([1,,8,9]),0===(e=this.getQueueRaw()).length)return[2];console.log("[AInamika Error Storage] Processing ".concat(e.length," queued errors")),t=0,r=e,i.label=2;case 2:if(!(t<r.length))return[3,7];if((n=r[t]).retryCount>=this.config.maxRetries)return console.warn("[AInamika Error Storage] Max retries reached for error ".concat(n.id)),this.removeError(n.id),[3,6];if(n.lastRetry&&Date.now()-n.lastRetry<this.config.retryInterval)return[3,6];i.label=3;case 3:return i.trys.push([3,5,,6]),[4,this.sendError(n)];case 4:return i.sent()?(this.removeError(n.id),console.log("[AInamika Error Storage] Successfully sent error ".concat(n.id))):this.incrementRetryCount(n.id),[3,6];case 5:return o=i.sent(),console.error("[AInamika Error Storage] Failed to send error ".concat(n.id,":"),o),this.incrementRetryCount(n.id),[3,6];case 6:return t++,[3,2];case 7:return[3,9];case 8:return this.isProcessing=!1,[7];case 9:return[2]}})})},e.prototype.retryError=function(e){return l(this,void 0,void 0,function(){var t,r,n;return h(this,function(o){switch(o.label){case 0:if(t=this.getQueueRaw(),!(r=t.find(function(t){return t.id===e})))return[2,!1];o.label=1;case 1:return o.trys.push([1,3,,4]),[4,this.sendError(r)];case 2:return o.sent()?(this.removeError(e),[2,!0]):(this.incrementRetryCount(e),[2,!1]);case 3:return n=o.sent(),console.error("[AInamika Error Storage] Failed to retry error ".concat(e,":"),n),this.incrementRetryCount(e),[2,!1];case 4:return[2]}})})},e.prototype.addToQueue=function(e){return l(this,void 0,void 0,function(){var t,r;return h(this,function(n){if((t=this.getQueueRaw()).push(e),r=JSON.stringify(t),new Blob([r]).size>this.config.maxStorageSize)for(;t.length>0&&new Blob([JSON.stringify(t)]).size>this.config.maxStorageSize;)t.shift(),console.warn("[AInamika Error Storage] Removed old error due to size limit");return localStorage.setItem(this.STORAGE_KEY,JSON.stringify(t)),[2]})})},e.prototype.getQueueRaw=function(){try{var e=localStorage.getItem(this.STORAGE_KEY);return e?JSON.parse(e):[]}catch(e){return console.error("[AInamika Error Storage] Failed to parse stored errors:",e),[]}},e.prototype.incrementRetryCount=function(e){try{var t=this.getQueueRaw(),r=t.findIndex(function(t){return t.id===e});-1!==r&&(t[r].retryCount++,t[r].lastRetry=Date.now(),localStorage.setItem(this.STORAGE_KEY,JSON.stringify(t)))}catch(e){console.error("[AInamika Error Storage] Failed to increment retry count:",e)}},e.prototype.sendError=function(e){return l(this,void 0,void 0,function(){var t,r,n,o;return h(this,function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),t=this.config.compressionEnabled?this.decompressData(e.errorData):e.errorData,r=t.endpoint||c.ERRORS,n=t.apiKey||"",[4,fetch("".concat(r,"/api/v1/errors"),{method:"POST",headers:{"Content-Type":"application/json",Authorization:n?"Bearer ".concat(n):""},body:JSON.stringify(t)})];case 1:return[2,i.sent().ok];case 2:return o=i.sent(),console.error("[AInamika Error Storage] Network error sending stored error:",o),[2,!1];case 3:return[2]}})})},e.prototype.compressData=function(e){try{var t=JSON.stringify(e);return btoa(t)}catch(t){return console.warn("[AInamika Error Storage] Compression failed, storing uncompressed:",t),e}},e.prototype.decompressData=function(e){try{if("string"==typeof e&&e.length>0){var t=atob(e);return JSON.parse(t)}return e}catch(t){return console.warn("[AInamika Error Storage] Decompression failed, returning raw data:",t),e}},e.prototype.generateErrorId=function(){return"error_".concat(Date.now(),"_").concat(Math.random().toString(36).substr(2,9))},e.prototype.cleanupOldErrors=function(){try{var e=this.getQueueRaw(),t=Date.now()-6048e5,r=e.filter(function(e){return e.timestamp>t});r.length!==e.length&&(localStorage.setItem(this.STORAGE_KEY,JSON.stringify(r)),console.log("[AInamika Error Storage] Cleaned up ".concat(e.length-r.length," old errors")))}catch(e){console.error("[AInamika Error Storage] Failed to cleanup old errors:",e)}},e.prototype.startRetryTimer=function(){var e=this;this.retryTimer=window.setInterval(function(){e.processQueue()},this.config.retryInterval)},e.prototype.setupStorageListener=function(){var e=this;window.addEventListener("storage",function(t){t.key===e.STORAGE_KEY&&(console.log("[AInamika Error Storage] Storage updated from another tab"),setTimeout(function(){return e.processQueue()},1e3))}),window.addEventListener("online",function(){console.log("[AInamika Error Storage] Network back online, processing queue"),setTimeout(function(){return e.processQueue()},1e3)}),window.addEventListener("offline",function(){console.log("[AInamika Error Storage] Network offline, errors will be queued")})},e.prototype.updateMetadata=function(){try{var e=this.getStorageStats(),t=u({lastUpdate:Date.now()},e);localStorage.setItem(this.METADATA_KEY,JSON.stringify(t))}catch(e){console.error("[AInamika Error Storage] Failed to update metadata:",e)}},e.prototype.exportErrors=function(){try{var e=this.getStoredErrors(),t={timestamp:Date.now(),version:"1.0",stats:this.getStorageStats(),errors:e};return JSON.stringify(t,null,2)}catch(e){return console.error("[AInamika Error Storage] Failed to export errors:",e),"{}"}},e.prototype.importErrors=function(e){try{var t=JSON.parse(e);if(!t.errors||!Array.isArray(t.errors))throw new Error("Invalid export format");this.clearAll();for(var r=0,n=t.errors;r<n.length;r++){var o=n[r];this.storeError(o.errorData)}return console.log("[AInamika Error Storage] Imported ".concat(t.errors.length," errors")),!0}catch(e){return console.error("[AInamika Error Storage] Failed to import errors:",e),!1}},e.prototype.destroy=function(){this.retryTimer&&(clearInterval(this.retryTimer),this.retryTimer=void 0),this.processQueue(),console.log("[AInamika Error Storage] Storage instance destroyed")},e}(),f=(function(){function e(){}e.getAinamikaStorageUsage=function(){var e=0,t=0,r=0;for(var n in localStorage)if(localStorage.hasOwnProperty(n)){var o=new Blob([localStorage.getItem(n)||""]).size;e+=o,n.startsWith("ainamika_error")?t+=o:n.startsWith("ainamika_")&&(r+=o)}return{totalSize:e,errorSize:t,otherSize:r}},e.checkStorageSpace=function(e){try{var t="ainamika_storage_test",r="x".repeat(Math.min(e,1048576));return localStorage.setItem(t,r),localStorage.removeItem(t),!0}catch(e){return!1}},e.cleanupAllAinamikaStorage=function(){var e=[];for(var t in localStorage)t.startsWith("ainamika_")&&e.push(t);e.forEach(function(e){return localStorage.removeItem(e)}),console.log("[AInamika Storage Utils] Cleaned up ".concat(e.length," storage keys"))},e.generateStorageReport=function(){var t=new d;return{usage:e.getAinamikaStorageUsage(),errors:t.getStoredErrors(),metadata:t.getStorageStats()}}}(),function(){return f=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},f.apply(this,arguments)}),g=function(){function e(){this.userId=null,this.userProperties={},this.initializeUser()}return e.prototype.initializeUser=function(){this.userId=this.getOrCreateUserId()},e.prototype.getOrCreateUserId=function(){try{var e=localStorage.getItem("ainamika_user_id");return e||(e=this.generateAnonymousId(),localStorage.setItem("ainamika_user_id",e)),e}catch(e){return console.warn("[UserManager] localStorage not available, using session ID"),this.generateAnonymousId()}},e.prototype.generateAnonymousId=function(){return"anon_"+Math.random().toString(36).substr(2,9)+"_"+Date.now()},e.prototype.getUserId=function(){return this.userId||(this.userId=this.getOrCreateUserId()),this.userId},e.prototype.getUserProperties=function(){return f({},this.userProperties)},e.prototype.identifyUser=function(e,t){var r=this.getUserId();try{localStorage.setItem("ainamika_user_id",e),this.userId=e,t&&(this.userProperties=f(f({},this.userProperties),t)),console.log("[UserManager] User identified: ".concat(r," → ").concat(e))}catch(e){console.error("[UserManager] Error identifying user:",e)}},e.prototype.updateUserProperties=function(e){this.userProperties=f(f({},this.userProperties),e)},e.prototype.clearUser=function(){try{localStorage.removeItem("ainamika_user_id"),this.userId=null,this.userProperties={},this.initializeUser()}catch(e){console.error("[UserManager] Error clearing user:",e)}},e.prototype.getUserIdentificationEvent=function(e){return{event:"user_identified",previous_id:this.getUserId(),user_id:e,timestamp:Date.now(),properties:this.userProperties}},e.prototype.isAnonymousUser=function(){return this.getUserId().startsWith("anon_")},e.prototype.getUserType=function(){return this.isAnonymousUser()?"anonymous":"authenticated"},e}(),p=function(){return p=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},p.apply(this,arguments)},m=function(){function e(){this.userJourney=[],this.lastEventTime=0,this.sequenceIndex=0,this.maxJourneyLength=50,this.journeyAnalysisThreshold=5,this.journeyStartTime=Date.now()}return e.prototype.trackEvent=function(e,t){var r=Date.now(),n=this.lastEventTime?r-this.lastEventTime:0,o={eventName:e,timestamp:r,properties:p(p({},t),{timeSinceLastEvent:n,journeyPosition:this.sequenceIndex}),sequenceIndex:this.sequenceIndex++};this.userJourney.push(o),this.lastEventTime=r,this.userJourney.length>this.maxJourneyLength&&(this.userJourney=this.userJourney.slice(-this.maxJourneyLength)),console.log("[JourneyTracker] Event tracked: ".concat(e," (position: ").concat(o.sequenceIndex,")"))},e.prototype.getContext=function(){var e=Date.now();return{journeySequence:this.getJourneySequence(),eventCount:this.userJourney.length,lastEventTime:this.lastEventTime,journeyStartTime:this.journeyStartTime,timeSinceLastEvent:this.lastEventTime?e-this.lastEventTime:0}},e.prototype.getJourneySequence=function(){return this.userJourney.map(function(e){return e.eventName})},e.prototype.getJourneyData=function(){return function(e,t,r){if(r||2===arguments.length)for(var n,o=0,i=t.length;o<i;o++)!n&&o in t||(n||(n=Array.prototype.slice.call(t,0,o)),n[o]=t[o]);return e.concat(n||Array.prototype.slice.call(t))}([],this.userJourney,!0)},e.prototype.shouldAnalyzeJourney=function(){return this.userJourney.length>=this.journeyAnalysisThreshold&&this.userJourney.length%this.journeyAnalysisThreshold===0},e.prototype.getJourneyForAnalysis=function(){var e=Date.now()-this.journeyStartTime,t=this.calculateAverageTimeBetweenEvents();return{journey:this.userJourney.map(function(e){return{name:e.eventName,timestamp:e.timestamp,properties:e.properties}}),metadata:{journeyLength:this.userJourney.length,journeyDuration:e,avgTimeBetweenEvents:t,startTime:this.journeyStartTime,endTime:this.lastEventTime}}},e.prototype.calculateAverageTimeBetweenEvents=function(){if(this.userJourney.length<2)return 0;for(var e=0,t=1;t<this.userJourney.length;t++)e+=this.userJourney[t].timestamp-this.userJourney[t-1].timestamp;return Math.round(e/(this.userJourney.length-1))},e.prototype.findPatterns=function(){var e={};if(this.userJourney.length<3)return e;for(var t=0;t<=this.userJourney.length-3;t++){var r=this.userJourney.slice(t,t+3).map(function(e){return e.eventName}).join(" → ");e[r]=(e[r]||0)+1}return Object.fromEntries(Object.entries(e).filter(function(e){return e[0],e[1]>1}))},e.prototype.clearJourney=function(){this.userJourney=[],this.sequenceIndex=0,this.lastEventTime=0,this.journeyStartTime=Date.now()},e.prototype.getJourneySegment=function(e){return this.userJourney.slice(-e)},e.prototype.detectPotentialFunnel=function(){for(var e=this.getJourneySequence().slice(-5),t=0,r=Object.entries({signup_flow:["view_pricing","click_signup","enter_email"],purchase_flow:["view_product","add_to_cart","view_cart"],onboarding_flow:["user_signup","profile_setup","tutorial_start"]});t<r.length;t++){var n=r[t],o=n[0];if(n[1].filter(function(t){return e.includes(t)}).length>=2)return o}return null},e}(),v=function(e,t,r,n){return new(r||(r=Promise))(function(o,i){function a(e){try{c(n.next(e))}catch(e){i(e)}}function s(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(a,s)}c((n=n.apply(e,t||[])).next())})},y=function(e,t){var r,n,o,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=s(0),a.throw=s(1),a.return=s(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(s){return function(c){return function(s){if(r)throw new TypeError("Generator is already executing.");for(;a&&(a=0,s[0]&&(i=0)),i;)try{if(r=1,n&&(o=2&s[0]?n.return:s[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,s[1])).done)return o;switch(n=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,n=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){i.label=s[1];break}if(6===s[0]&&i.label<o[1]){i.label=o[1],o=s;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(s);break}o[2]&&i.ops.pop(),i.trys.pop();continue}s=t.call(e,i)}catch(e){s=[6,e],n=0}finally{r=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}},k=function(){function e(e,t,r){void 0===r&&(r=!1),this.accessToken=null,this.refreshToken=null,this.tokenExpiry=null,this.clientId=e,this.apiEndpoint=t,this.debug=r,this.loadTokens()}return e.prototype.initialize=function(){return v(this,void 0,void 0,function(){var e,t;return y(this,function(r){switch(r.label){case 0:return r.trys.push([0,4,,5]),this.isTokenValid()?(this.debugLog("Using existing valid token"),[2,!0]):this.refreshToken?[4,this.refreshAccessToken()]:[3,2];case 1:if(r.sent())return[2,!0];r.label=2;case 2:return[4,this.requestTokens()];case 3:return(e=r.sent())?(this.setTokens(e),[2,!0]):[2,!1];case 4:return t=r.sent(),this.debugLog("Authentication initialization failed:",t),[2,!1];case 5:return[2]}})})},e.prototype.requestTokens=function(){return v(this,void 0,void 0,function(){var e,t;return y(this,function(r){switch(r.label){case 0:return r.trys.push([0,3,,4]),[4,fetch("".concat(this.apiEndpoint,"/api/v1/auth/token"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:this.clientId})})];case 1:if(!(e=r.sent()).ok)throw new Error("Token request failed: ".concat(e.status));return[4,e.json()];case 2:return[2,r.sent()];case 3:return t=r.sent(),this.debugLog("Token request error:",t),[2,null];case 4:return[2]}})})},e.prototype.refreshAccessToken=function(){return v(this,void 0,void 0,function(){var e,t,r;return y(this,function(n){switch(n.label){case 0:if(!this.refreshToken)return[2,!1];n.label=1;case 1:return n.trys.push([1,4,,5]),[4,fetch("".concat(this.apiEndpoint,"/api/v1/auth/refresh"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refresh_token:this.refreshToken})})];case 2:return(e=n.sent()).ok?[4,e.json()]:(this.clearTokens(),[2,!1]);case 3:return t=n.sent(),this.setTokens(t),[2,!0];case 4:return r=n.sent(),this.debugLog("Token refresh error:",r),[2,!1];case 5:return[2]}})})},e.prototype.getAccessToken=function(){return v(this,void 0,void 0,function(){return y(this,function(e){switch(e.label){case 0:return this.shouldRefreshToken()?[4,this.refreshAccessToken()]:[3,2];case 1:e.sent(),e.label=2;case 2:return this.isTokenValid()?[3,4]:[4,this.initialize()];case 3:if(!e.sent())return[2,null];e.label=4;case 4:return[2,this.accessToken]}})})},e.prototype.getAuthHeaders=function(){return v(this,void 0,void 0,function(){var e;return y(this,function(t){switch(t.label){case 0:return[4,this.getAccessToken()];case 1:return(e=t.sent())?[2,{Authorization:"Bearer ".concat(e)}]:[2,{"X-Client-ID":this.clientId}]}})})},e.prototype.isTokenValid=function(){return!(!this.accessToken||!this.tokenExpiry)&&Date.now()<this.tokenExpiry},e.prototype.shouldRefreshToken=function(){return!(!this.tokenExpiry||!this.refreshToken)&&Date.now()>this.tokenExpiry-3e5},e.prototype.setTokens=function(e){this.accessToken=e.access_token,this.refreshToken=e.refresh_token||this.refreshToken,this.tokenExpiry=Date.now()+1e3*e.expires_in,this.saveTokens(),this.scheduleTokenRefresh(),this.debugLog("Tokens set successfully")},e.prototype.scheduleTokenRefresh=function(){var e=this;this.refreshTimer&&clearTimeout(this.refreshTimer);var t=Math.max(0,this.tokenExpiry-Date.now()-3e5);this.refreshTimer=setTimeout(function(){e.refreshAccessToken()},t)},e.prototype.saveTokens=function(){if("undefined"!=typeof window&&window.localStorage){var e={accessToken:this.accessToken,refreshToken:this.refreshToken,tokenExpiry:this.tokenExpiry};localStorage.setItem("ainamika_auth_".concat(this.clientId),JSON.stringify(e))}},e.prototype.loadTokens=function(){if("undefined"!=typeof window&&window.localStorage){var e=localStorage.getItem("ainamika_auth_".concat(this.clientId));if(e)try{var t=JSON.parse(e);this.accessToken=t.accessToken,this.refreshToken=t.refreshToken,this.tokenExpiry=t.tokenExpiry,this.isTokenValid()&&this.scheduleTokenRefresh()}catch(e){this.debugLog("Failed to load stored tokens:",e)}}},e.prototype.clearTokens=function(){this.accessToken=null,this.refreshToken=null,this.tokenExpiry=null,"undefined"!=typeof window&&window.localStorage&&localStorage.removeItem("ainamika_auth_".concat(this.clientId)),this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=void 0)},e.prototype.logout=function(){return v(this,void 0,void 0,function(){var e;return y(this,function(t){switch(t.label){case 0:return t.trys.push([0,3,4,5]),this.accessToken?[4,fetch("".concat(this.apiEndpoint,"/api/v1/auth/logout"),{method:"POST",headers:{Authorization:"Bearer ".concat(this.accessToken)}})]:[3,2];case 1:t.sent(),t.label=2;case 2:return[3,5];case 3:return e=t.sent(),this.debugLog("Logout error:",e),[3,5];case 4:return this.clearTokens(),[7];case 5:return[2]}})})},e.prototype.debugLog=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.debug&&console.log.apply(console,function(e,t,r){if(r||2===arguments.length)for(var n,o=0,i=t.length;o<i;o++)!n&&o in t||(n||(n=Array.prototype.slice.call(t,0,o)),n[o]=t[o]);return e.concat(n||Array.prototype.slice.call(t))}(["[Ainamika Auth]"],e,!1))},e}(),b=function(){return b=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},b.apply(this,arguments)},w=function(){function e(e,t){this.performanceMetrics={},this.scrollDepthReached=new Set,this.clickHistory=[],this.isPageVisible=!0,this.visibilityChangeCount=0,this.config=b({trackPerformance:!0,trackEngagement:!0,trackScrollDepth:!0,trackRageClicks:!0,trackTimeOnPage:!0,trackAPIResponses:!1,scrollDepthThresholds:[25,50,75,90,100],rageClickThreshold:3,rageClickWindow:1e3,apiTrackingPatterns:[]},e),this.onEvent=t,this.pageStartTime=Date.now(),this.lastActivityTime=Date.now(),this.originalFetch=window.fetch.bind(window),this.originalXHR=XMLHttpRequest.prototype.open,this.engagementMetrics={timeOnPage:0,scrollDepth:0,scrollDepthMilestones:[],rageClicks:0,totalClicks:0,activeTime:0,idleTime:0,pageVisibilityChanges:0},this.initialize()}return e.prototype.initialize=function(){var e=this;this.config.trackPerformance&&this.initPerformanceTracking(),this.config.trackEngagement&&this.initEngagementTracking(),this.config.trackScrollDepth&&this.initScrollTracking(),this.config.trackRageClicks&&this.initRageClickTracking(),this.config.trackTimeOnPage&&this.initTimeTracking(),this.config.trackAPIResponses&&this.initAPITracking(),window.addEventListener("beforeunload",function(){e.trackPageExit()}),console.log("[AInamika Advanced Tracker] Initialized")},e.prototype.initPerformanceTracking=function(){var e=this;if("PerformanceObserver"in window){try{new PerformanceObserver(function(t){var r,n=t.getEntries(),o=n[n.length-1];e.performanceMetrics.lcp=o.startTime,e.onEvent("performance_lcp",{value:o.startTime,element:null===(r=o.element)||void 0===r?void 0:r.tagName})}).observe({type:"largest-contentful-paint",buffered:!0})}catch(e){console.debug("[Advanced Tracker] LCP not supported")}try{new PerformanceObserver(function(t){var r=t.getEntries()[0];e.performanceMetrics.fid=r.processingStart-r.startTime,e.onEvent("performance_fid",{value:e.performanceMetrics.fid,eventType:r.name})}).observe({type:"first-input",buffered:!0})}catch(e){console.debug("[Advanced Tracker] FID not supported")}try{var t=0;new PerformanceObserver(function(r){for(var n=0,o=r.getEntries();n<o.length;n++){var i=o[n];i.hadRecentInput||(t+=i.value)}e.performanceMetrics.cls=t}).observe({type:"layout-shift",buffered:!0}),document.addEventListener("visibilitychange",function(){"hidden"===document.visibilityState&&e.onEvent("performance_cls",{value:t})})}catch(e){console.debug("[Advanced Tracker] CLS not supported")}try{new PerformanceObserver(function(t){var r=t.getEntries().find(function(e){return"first-contentful-paint"===e.name});r&&(e.performanceMetrics.fcp=r.startTime,e.onEvent("performance_fcp",{value:r.startTime}))}).observe({type:"paint",buffered:!0})}catch(e){console.debug("[Advanced Tracker] FCP not supported")}}window.addEventListener("load",function(){setTimeout(function(){var t=performance.timing;e.performanceMetrics.ttfb=t.responseStart-t.navigationStart,e.performanceMetrics.domContentLoaded=t.domContentLoadedEventEnd-t.navigationStart,e.performanceMetrics.pageLoad=t.loadEventEnd-t.navigationStart;var r=performance.getEntriesByType("resource");e.performanceMetrics.resourceCount=r.length,e.performanceMetrics.transferSize=r.reduce(function(e,t){return e+(t.transferSize||0)},0),e.onEvent("performance_page_load",{ttfb:e.performanceMetrics.ttfb,domContentLoaded:e.performanceMetrics.domContentLoaded,pageLoad:e.performanceMetrics.pageLoad,resourceCount:e.performanceMetrics.resourceCount,transferSizeKB:Math.round((e.performanceMetrics.transferSize||0)/1024)})},0)})},e.prototype.initEngagementTracking=function(){var e=this;document.addEventListener("visibilitychange",function(){e.isPageVisible="visible"===document.visibilityState,e.visibilityChangeCount++,e.engagementMetrics.pageVisibilityChanges=e.visibilityChangeCount,e.isPageVisible?e.lastActivityTime=Date.now():e.updateActiveTime()}),["mousemove","keydown","touchstart","scroll"].forEach(function(t){document.addEventListener(t,function(){e.lastActivityTime=Date.now()},{passive:!0})}),document.addEventListener("click",function(){e.engagementMetrics.totalClicks++})},e.prototype.initScrollTracking=function(){var e=this,t=!1,r=function(){var r=window.scrollY||document.documentElement.scrollTop,n=Math.max(document.body.scrollHeight,document.documentElement.scrollHeight)-window.innerHeight,o=n>0?Math.round(r/n*100):0;e.engagementMetrics.scrollDepth=Math.max(e.engagementMetrics.scrollDepth,o);for(var i=0,a=e.config.scrollDepthThresholds;i<a.length;i++){var s=a[i];o>=s&&!e.scrollDepthReached.has(s)&&(e.scrollDepthReached.add(s),e.engagementMetrics.scrollDepthMilestones.push(s),e.onEvent("engagement_scroll_depth",{depth:s,maxDepth:e.engagementMetrics.scrollDepth,timeToReach:Date.now()-e.pageStartTime}))}t=!1};window.addEventListener("scroll",function(){t||(requestAnimationFrame(r),t=!0)},{passive:!0})},e.prototype.initRageClickTracking=function(){var e=this;document.addEventListener("click",function(t){var r,n=Date.now();if(e.clickHistory.push(n),e.clickHistory=e.clickHistory.filter(function(t){return n-t<e.config.rageClickWindow}),e.clickHistory.length>=e.config.rageClickThreshold){e.engagementMetrics.rageClicks++;var o=t.target;e.onEvent("engagement_rage_click",{clickCount:e.clickHistory.length,element:{tagName:o.tagName,id:o.id,className:o.className,textContent:null===(r=o.textContent)||void 0===r?void 0:r.substring(0,50)},position:{x:t.clientX,y:t.clientY},totalRageClicks:e.engagementMetrics.rageClicks}),e.clickHistory=[]}})},e.prototype.initTimeTracking=function(){var e=this;setInterval(function(){e.updateActiveTime()},3e4)},e.prototype.updateActiveTime=function(){var e=Date.now(),t=e-this.lastActivityTime;this.engagementMetrics.timeOnPage=e-this.pageStartTime,t<3e4?this.engagementMetrics.activeTime+=Math.min(t,3e4):this.engagementMetrics.idleTime+=t},e.prototype.initAPITracking=function(){var e=this;window.fetch=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return n=e,o=void 0,a=function(){var e,r,n,o,i,a,s;return function(e,t){var r,n,o,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=s(0),a.throw=s(1),a.return=s(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(s){return function(c){return function(s){if(r)throw new TypeError("Generator is already executing.");for(;a&&(a=0,s[0]&&(i=0)),i;)try{if(r=1,n&&(o=2&s[0]?n.return:s[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,s[1])).done)return o;switch(n=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,n=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){i.label=s[1];break}if(6===s[0]&&i.label<o[1]){i.label=o[1],o=s;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(s);break}o[2]&&i.ops.pop(),i.trys.pop();continue}s=t.call(e,i)}catch(e){s=[6,e],n=0}finally{r=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}}(this,function(c){switch(c.label){case 0:if(e=Date.now(),r=t[0]instanceof Request?t[0].url:String(t[0]),n=(null===(s=t[1])||void 0===s?void 0:s.method)||"GET",!this.shouldTrackAPI(r))return[2,this.originalFetch.apply(this,t)];c.label=1;case 1:return c.trys.push([1,3,,4]),[4,this.originalFetch.apply(this,t)];case 2:return o=c.sent(),a=Date.now()-e,this.trackAPICall({url:r,method:n,status:o.status,duration:a,success:o.ok,timestamp:Date.now()}),[2,o];case 3:throw i=c.sent(),a=Date.now()-e,this.trackAPICall({url:r,method:n,status:0,duration:a,success:!1,error:(null==i?void 0:i.message)||"Network error",timestamp:Date.now()}),i;case 4:return[2]}})},new((i=void 0)||(i=Promise))(function(e,t){function r(e){try{c(a.next(e))}catch(e){t(e)}}function s(e){try{c(a.throw(e))}catch(e){t(e)}}function c(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(r,s)}c((a=a.apply(n,o||[])).next())});var n,o,i,a},console.log("[Advanced Tracker] API tracking initialized")},e.prototype.shouldTrackAPI=function(e){return!this.config.apiTrackingPatterns||0===this.config.apiTrackingPatterns.length||this.config.apiTrackingPatterns.some(function(t){try{return new RegExp(t).test(e)}catch(r){return e.includes(t)}})},e.prototype.trackAPICall=function(e){this.onEvent("api_call",{url:e.url,method:e.method,status:e.status,duration:e.duration,success:e.success,error:e.error})},e.prototype.trackAPI=function(e,t,r,n){this.onEvent("api_response_tracked",b({endpoint:e,method:t,responseType:typeof r,responseKeys:r&&"object"==typeof r?Object.keys(r):[],hasData:!!r,dataCount:Array.isArray(r)?r.length:void 0},n))},e.prototype.trackEngagement=function(e,t){this.onEvent("engagement_".concat(e),b(b({},t),{timeOnPage:Date.now()-this.pageStartTime,scrollDepth:this.engagementMetrics.scrollDepth}))},e.prototype.trackConversion=function(e,t,r){this.onEvent("conversion",b(b({goal:e,value:t},r),{timeToConvert:Date.now()-this.pageStartTime,scrollDepthAtConversion:this.engagementMetrics.scrollDepth,clicksBeforeConversion:this.engagementMetrics.totalClicks}))},e.prototype.getPerformanceMetrics=function(){return b({},this.performanceMetrics)},e.prototype.getEngagementMetrics=function(){return this.updateActiveTime(),b(b({},this.engagementMetrics),{timeOnPage:Date.now()-this.pageStartTime})},e.prototype.trackPageExit=function(){this.updateActiveTime(),this.onEvent("page_exit",{timeOnPage:Date.now()-this.pageStartTime,activeTime:this.engagementMetrics.activeTime,idleTime:this.engagementMetrics.idleTime,scrollDepth:this.engagementMetrics.scrollDepth,scrollMilestones:this.engagementMetrics.scrollDepthMilestones,totalClicks:this.engagementMetrics.totalClicks,rageClicks:this.engagementMetrics.rageClicks,visibilityChanges:this.engagementMetrics.pageVisibilityChanges,performance:this.performanceMetrics})},e}(),S=function(){return S=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},S.apply(this,arguments)},T=function(e,t,r,n){return new(r||(r=Promise))(function(o,i){function a(e){try{c(n.next(e))}catch(e){i(e)}}function s(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(a,s)}c((n=n.apply(e,t||[])).next())})},E=function(e,t){var r,n,o,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=s(0),a.throw=s(1),a.return=s(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(s){return function(c){return function(s){if(r)throw new TypeError("Generator is already executing.");for(;a&&(a=0,s[0]&&(i=0)),i;)try{if(r=1,n&&(o=2&s[0]?n.return:s[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,s[1])).done)return o;switch(n=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,n=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){i.label=s[1];break}if(6===s[0]&&i.label<o[1]){i.label=o[1],o=s;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(s);break}o[2]&&i.ops.pop(),i.trys.pop();continue}s=t.call(e,i)}catch(e){s=[6,e],n=0}finally{r=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}},_=function(e,t,r){if(r||2===arguments.length)for(var n,o=0,i=t.length;o<i;o++)!n&&o in t||(n||(n=Array.prototype.slice.call(t,0,o)),n[o]=t[o]);return e.concat(n||Array.prototype.slice.call(t))},I=function(){function e(e){if(this.eventQueue=[],this.isInitialized=!1,this.batchRetryCount=0,this.maxBatchRetries=5,this.domHashCache={},this.lastDomHash="",this.lastConfigHash="",this.mutationDebounceTimer=null,this.mutationDebounceMs=2e3,this.attachedListeners=new WeakMap,this.knownElementSelectors=new Set,this.mergedConfig={events_to_track:[]},this.MAX_CACHED_CONFIGS=15,!e.projectKey&&!e.clientId&&!e.apiKey)throw new Error("[AInamika SDK] Either projectKey or clientId is required for initialization");this.config=S({endpoint:s.API_BASE_URL,batchInterval:5e3,useWebWorker:!0,debug:s.DEBUG,errorTracking:{enabled:!0,captureScreenshots:!0,captureDomSnapshots:!0,maxStackTraceDepth:50,maxErrorsPerSession:100,debounceMs:1e3,enableNetworkTracking:!0,enableConsoleCapture:!0},advancedTracking:{enabled:!0,trackPerformance:!0,trackEngagement:!0,trackScrollDepth:!0,trackRageClicks:!0,trackTimeOnPage:!0,trackAPIResponses:!1,scrollDepthThresholds:[25,50,75,90,100]}},e),this.sessionId=this.generateSessionId(),this.userIdentifier=this.getOrCreateUserIdentifier(),this.userManager=new g,this.journeyTracker=new m,this.authManager=new k(this.config.clientId||this.config.apiKey||"",this.config.endpoint,this.config.debug);var t=new Blob(["\n self.eventQueue = [];\n self.config = {\n apiUrl: '',\n batchSize: 10,\n batchInterval: 5000,\n headers: { 'Content-Type': 'application/json' }\n };\n let batchTimer = null;\n function flushQueue() {\n self.postMessage({ status: 'debug', message: '[AInamika Worker] flushQueue called', eventQueue: self.eventQueue, config: self.config });\n if (self.eventQueue.length === 0) return;\n const batch = self.eventQueue.splice(0, self.config.batchSize);\n fetch(self.config.apiUrl, {\n method: 'POST',\n headers: self.config.headers,\n body: JSON.stringify({ events: batch })\n }).then(r => {\n if (r.ok) {\n self.postMessage({ status: 'success' });\n } else {\n self.postMessage({ status: 'error', error: r.statusText, failedEvents: batch });\n }\n }).catch(e => {\n self.postMessage({ status: 'error', error: e.message, failedEvents: batch });\n });\n }\n self.onmessage = function(e) {\n self.postMessage({ status: 'debug', message: '[AInamika Worker] onmessage', data: e.data });\n if (e.data.type === 'config') {\n self.config = { ...self.config, ...e.data.payload };\n if (batchTimer) clearInterval(batchTimer);\n batchTimer = setInterval(flushQueue, self.config.batchInterval);\n self.postMessage({ status: 'debug', message: '[AInamika Worker] config set', config: self.config });\n } else if (e.data.type === 'track') {\n self.eventQueue.push(e.data.payload);\n // Only send when timer triggers, not when batch size is reached\n // This ensures true batching behavior\n } else if (e.data.type === 'batch') {\n // Handle batch flush from main thread\n self.postMessage({ status: 'debug', message: '[AInamika Worker] Received batch from main thread', events: e.data.events });\n self.eventQueue.push(...e.data.events);\n flushQueue();\n } else if (e.data.type === 'initConfig') {\n // No-op for now, can be used for advanced config\n }\n };\n "],{type:"application/javascript"}),r=URL.createObjectURL(t);this.worker=new Worker(r),this.initialize()}return e.prototype.initialize=function(){return T(this,void 0,void 0,function(){var e,t,r,n,o;return E(this,function(i){switch(i.label){case 0:if(this.isInitialized)return[2];if(this.isInitialized=!0,!this.config.projectKey)return[3,5];i.label=1;case 1:return i.trys.push([1,4,,5]),[4,this.initializeProjectSettings()];case 2:return i.sent(),[4,this.initializeSamplingDecision()];case 3:return i.sent(),this.log("Project-based initialization complete",{projectKey:this.config.projectKey,projectSettings:this.projectSettings,samplingDecision:this.samplingDecision}),[3,5];case 4:return e=i.sent(),this.log("Project initialization failed:",e),console.warn("[AInamika SDK] Failed to initialize project settings. Some features may be limited."),[3,5];case 5:if(!this.config.clientId&&!this.config.apiKey)return[3,9];i.label=6;case 6:return i.trys.push([6,8,,9]),[4,this.authManager.initialize()];case 7:return i.sent(),this.log("Authentication initialized"),[3,9];case 8:return t=i.sent(),this.log("Authentication initialization failed:",t),this.config.debug||console.warn("[Ainamika] Running without authentication. Some features may be limited."),[3,9];case 9:return(null===(r=this.config.errorTracking)||void 0===r?void 0:r.enabled)&&this.shouldSampleErrors()?this.initializeErrorTracking():(null===(n=this.config.errorTracking)||void 0===n?void 0:n.enabled)&&!this.shouldSampleErrors()&&this.log("Error tracking disabled due to sampling decision"),(null===(o=this.config.advancedTracking)||void 0===o?void 0:o.enabled)&&this.initializeAdvancedTracking(),this.config.autoConfig?[4,this.setupAutoConfiguration()]:[3,11];case 10:i.sent(),i.label=11;case 11:return this.setupDynamicDomTracking(),this.config.useWebWorker&&"undefined"!=typeof Worker?[4,this.setupWebWorker()]:[3,13];case 12:return i.sent(),[3,14];case 13:this.startBatchTimer(),i.label=14;case 14:return this.log("AnalyticsPro SDK initialized",{config:this.config,projectKey:this.config.projectKey,sampling:this.samplingDecision}),[2]}})})},e.prototype.getOrCreateUserIdentifier=function(){var e="ainamika_user_identifier",t=localStorage.getItem(e);return t||(t="anon_"+Math.random().toString(36).substr(2,16)+Date.now().toString(36),localStorage.setItem(e,t),this.log("Created new user identifier:",t)),t},e.prototype.initializeProjectSettings=function(){return T(this,void 0,void 0,function(){var e,t,r;return E(this,function(n){switch(n.label){case 0:if(!this.config.projectKey)return[2];n.label=1;case 1:return n.trys.push([1,4,,5]),[4,fetch(c.PROJECTS_LOOKUP,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({project_key:this.config.projectKey})})];case 2:if(!(e=n.sent()).ok)throw new Error("Project lookup failed: ".concat(e.status));return t=this,[4,e.json()];case 3:return t.projectSettings=n.sent(),this.log("Project settings loaded:",this.projectSettings),[3,5];case 4:throw r=n.sent(),this.log("Failed to load project settings:",r),r;case 5:return[2]}})})},e.prototype.initializeSamplingDecision=function(){return T(this,void 0,void 0,function(){var e,t,r;return E(this,function(n){switch(n.label){case 0:if(!this.config.projectKey)return[2];n.label=1;case 1:return n.trys.push([1,4,,5]),[4,fetch(c.SAMPLING_CHECK,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({project_key:this.config.projectKey,user_identifier:this.userIdentifier})})];case 2:if(!(e=n.sent()).ok)throw new Error("Sampling check failed: ".concat(e.status));return t=this,[4,e.json()];case 3:return t.samplingDecision=n.sent(),this.log("Sampling decision received:",this.samplingDecision),this.cacheSamplingDecision(),[3,5];case 4:return r=n.sent(),this.log("Failed to get sampling decision, using cached or defaults:",r),this.loadCachedSamplingDecision(),[3,5];case 5:return[2]}})})},e.prototype.cacheSamplingDecision=function(){if(this.samplingDecision){var e="ainamika_sampling_".concat(this.config.projectKey);localStorage.setItem(e,JSON.stringify(this.samplingDecision))}},e.prototype.loadCachedSamplingDecision=function(){var e="ainamika_sampling_".concat(this.config.projectKey),t=localStorage.getItem(e);if(t)try{this.samplingDecision=JSON.parse(t),this.log("Loaded cached sampling decision:",this.samplingDecision)}catch(e){this.samplingDecision={should_sample:{events:!0,errors:!0,session_replay:!1},rates:{events:100,errors:100,session_replay:0},decision:"existing"}}else this.samplingDecision={should_sample:{events:!0,errors:!0,session_replay:!1},rates:{events:100,errors:100,session_replay:0},decision:"existing"}},e.prototype.shouldSampleEvents=function(){return!this.samplingDecision||this.samplingDecision.should_sample.events},e.prototype.shouldSampleErrors=function(){return!this.samplingDecision||this.samplingDecision.should_sample.errors},e.prototype.shouldSampleSessionReplay=function(){return!!this.samplingDecision&&this.samplingDecision.should_sample.session_replay},e.prototype.getSamplingStatus=function(){return this.samplingDecision||null},e.prototype.getProjectInfo=function(){return this.projectSettings||null},e.prototype.getTrackingStatus=function(){return{totalEvents:this.mergedConfig.events_to_track.length,knownSelectors:this.knownElementSelectors.size,mergedConfig:this.mergedConfig}},e.prototype.resetDomTracking=function(){this.knownElementSelectors.clear(),this.mergedConfig={events_to_track:[]},this.lastDomHash="",this.attachedListeners=new WeakMap,this.log("DOM tracking reset - will re-analyze on next mutation")},e.prototype.initializeErrorTracking=function(){var e,t,r,n,o,i,c,u,l,h,f,g,p,m;try{this.errorStorage=new d({maxStorageSize:5242880,maxRetries:5,retryInterval:3e4,compressionEnabled:!0,encryptionEnabled:!1});var v={endpoint:s.API_BASE_URL,clientId:this.config.clientId||"",apiKey:this.config.apiKey,authManager:this.authManager,projectKey:this.config.projectKey,captureScreenshots:null===(t=null===(e=this.config.errorTracking)||void 0===e?void 0:e.captureScreenshots)||void 0===t||t,captureDomSnapshots:null===(n=null===(r=this.config.errorTracking)||void 0===r?void 0:r.captureDomSnapshots)||void 0===n||n,maxStackTraceDepth:null!==(i=null===(o=this.config.errorTracking)||void 0===o?void 0:o.maxStackTraceDepth)&&void 0!==i?i:50,maxErrorsPerSession:null!==(u=null===(c=this.config.errorTracking)||void 0===c?void 0:c.maxErrorsPerSession)&&void 0!==u?u:100,debounceMs:null!==(h=null===(l=this.config.errorTracking)||void 0===l?void 0:l.debounceMs)&&void 0!==h?h:1e3,enableNetworkTracking:null===(g=null===(f=this.config.errorTracking)||void 0===f?void 0:f.enableNetworkTracking)||void 0===g||g,enableConsoleCapture:null===(m=null===(p=this.config.errorTracking)||void 0===p?void 0:p.enableConsoleCapture)||void 0===m||m};this.errorTracker=new a(v);var y=this.getUserId();y&&this.errorTracker&&this.errorTracker.setUser(y),this.log("Error tracking initialized successfully")}catch(e){console.error("[AInamika SDK] Failed to initialize error tracking:",e)}},e.prototype.captureException=function(e,t){this.errorTracker&&this.errorTracker.captureException(e,t)},e.prototype.setUser=function(e){console.warn("[AInamika SDK] setUser is deprecated. Please use identifyUser() instead."),this.identifyUser(e)},e.prototype.flushStoredErrors=function(){return T(this,void 0,void 0,function(){return E(this,function(e){switch(e.label){case 0:return this.errorStorage?[4,this.errorStorage.processQueue()]:[3,2];case 1:e.sent(),e.label=2;case 2:return this.errorTracker?[4,this.errorTracker.flushStoredErrors()]:[3,4];case 3:e.sent(),e.label=4;case 4:return[2]}})})},e.prototype.initializeAdvancedTracking=function(){var e,t,r,n,o,i,a,s,c,u,l,h,d,f,g=this;try{var p={trackPerformance:null===(t=null===(e=this.config.advancedTracking)||void 0===e?void 0:e.trackPerformance)||void 0===t||t,trackEngagement:null===(n=null===(r=this.config.advancedTracking)||void 0===r?void 0:r.trackEngagement)||void 0===n||n,trackScrollDepth:null===(i=null===(o=this.config.advancedTracking)||void 0===o?void 0:o.trackScrollDepth)||void 0===i||i,trackRageClicks:null===(s=null===(a=this.config.advancedTracking)||void 0===a?void 0:a.trackRageClicks)||void 0===s||s,trackTimeOnPage:null===(u=null===(c=this.config.advancedTracking)||void 0===c?void 0:c.trackTimeOnPage)||void 0===u||u,trackAPIResponses:null!==(h=null===(l=this.config.advancedTracking)||void 0===l?void 0:l.trackAPIResponses)&&void 0!==h&&h,scrollDepthThresholds:(null===(d=this.config.advancedTracking)||void 0===d?void 0:d.scrollDepthThresholds)||[25,50,75,90,100],apiTrackingPatterns:(null===(f=this.config.advancedTracking)||void 0===f?void 0:f.apiTrackingPatterns)||[]};this.advancedTracker=new w(p,function(e,t){g.sendToWorker(e,t)}),this.log("Advanced tracking initialized successfully")}catch(e){console.error("[AInamika SDK] Failed to initialize advanced tracking:",e)}},e.prototype.trackAPI=function(e,t,r,n){this.advancedTracker?this.advancedTracker.trackAPI(e,t,r,n):this.track("api_response_tracked",S({endpoint:e,method:t,responseType:typeof r,hasData:!!r},n))},e.prototype.trackEngagement=function(e,t){this.advancedTracker?this.advancedTracker.trackEngagement(e,t):this.track("engagement_".concat(e),t||{})},e.prototype.trackConversion=function(e,t,r){this.advancedTracker?this.advancedTracker.trackConversion(e,t,r):this.track("conversion",S({goal:e,value:t},r))},e.prototype.getPerformanceMetrics=function(){var e;return(null===(e=this.advancedTracker)||void 0===e?void 0:e.getPerformanceMetrics())||null},e.prototype.getEngagementMetrics=function(){var e;return(null===(e=this.advancedTracker)||void 0===e?void 0:e.getEngagementMetrics())||null},e.prototype.setupAutoConfiguration=function(){return T(this,void 0,void 0,function(){var e,t,r,n,o=this;return E(this,function(i){switch(i.label){case 0:return i.trys.push([0,7,,8]),this.log("Starting auto-configuration..."),[4,this.getDOMStructure()];case 1:return e=i.sent(),t=this.computeDomHash(e),this.lastDomHash=t,(e.elements||[]).forEach(function(e){e.selector&&o.knownElementSelectors.add(e.selector)}),this.log("Tracking ".concat(this.knownElementSelectors.size," initial element selectors")),(r=this.getCachedConfigForDomHash(t))?(this.log("Loaded analytics config from localStorage cache for DOM hash:",t),[3,4]):[3,2];case 2:return[4,this.loadConfigFromFile()];case 3:(r=i.sent())&&this.log("Loaded analytics config from file"),i.label=4;case 4:return r?[3,6]:(this.log("No cached config found, fetching from backend for DOM hash:",t),[4,this.fetchGeneratedConfig(e,t)]);case 5:(r=i.sent())&&r.events_to_track&&(this.saveConfigToFile(r),this.setCachedConfigForDomHash(t,r),this.lastConfigHash=r.config_hash||""),i.label=6;case 6:return r&&r.events_to_track?(this.mergedConfig={events_to_track:_([],r.events_to_track,!0),tracking_config:r.tracking_config},this.applyGeneratedConfig(r),this.config.useWebWorker&&"undefined"!=typeof Worker&&this.worker.postMessage({type:"initConfig",config:r}),this.log("Auto-configuration applied successfully",{eventsCount:r.events_to_track.length,knownSelectors:this.knownElementSelectors.size})):this.log("Auto-configuration failed: Invalid config received from backend.",r),[3,8];case 7:return n=i.sent(),this.log("Auto-configuration failed with error",n),[3,8];case 8:return[2]}})})},e.prototype.getDOMStructure=function(){return T(this,void 0,void 0,function(){var e,t,r,n,o;return E(this,function(i){switch(i.label){case 0:return e=function(e){if(e.id)return"#".concat(e.id);if(e.className){var t=e.className.split(" ").filter(function(e){return e.trim()}).join(".");return t?".".concat(t):e.tagName.toLowerCase()}return e.tagName.toLowerCase()},[4,new Promise(function(e){return setTimeout(e,500)})];case 1:return i.sent(),t=Array.from(document.body.querySelectorAll('\n button, a, input, select, textarea, form, img, h1, h2, h3, h4, h5, h6,\n [role=button], [role=link], [onclick], [tabindex], [data-analytics], [data-track],\n .card, .btn, .btn-primary, .btn-secondary, .card-title, .card-description, .card-price, .card-actions,\n [id*="card"], [class*="card"], [class*="btn"], [class*="price"], [class*="title"],\n div, span, p\n ')),r=t.filter(function(e){var t=window.getComputedStyle(e),r="none"!==t.display&&"hidden"!==t.visibility&&"0"!==t.opacity,n="button"===e.tagName.toLowerCase()||"a"===e.tagName.toLowerCase()||e.hasAttribute("onclick")||"button"===e.getAttribute("role")||e.classList.contains("btn")||e.classList.contains("card"),o="cardsContainer"===e.id||e.classList.contains("cards-grid")||e.classList.contains("card")||"img"===e.tagName.toLowerCase()||-1!==["h1","h2","h3"].indexOf(e.tagName.toLowerCase());return r&&(n||o)||"cardsContainer"===e.id}),n=new Set,o=r.map(function(t){var r,n,o={};return Array.from(t.attributes).forEach(function(e){-1===["style","data-timestamp","data-rendered"].indexOf(e.name)&&(o[e.name]=e.value.length>25?e.value.substring(0,25):e.value)}),{tagName:t.tagName.toLowerCase(),selector:e(t),id:t.id||"",className:t.className||"",textContent:(t.textContent||"").trim().substring(0,100),attributes:o,isInteractive:"button"===t.tagName.toLowerCase()||"a"===t.tagName.toLowerCase()||t.hasAttribute("onclick")||"button"===t.getAttribute("role")||t.classList.contains("btn"),hasChildren:t.children.length>0,childCount:t.children.length,parentTagName:(null===(r=t.parentElement)||void 0===r?void 0:r.tagName.toLowerCase())||"",index:Array.from((null===(n=t.parentElement)||void 0===n?void 0:n.children)||[]).indexOf(t)}}).filter(function(e){var t=e.tagName+"|"+e.selector+"|"+e.textContent.substring(0,20);return!n.has(t)&&(n.add(t),!0)}),this.log("DOM structure analyzed",{elementCount:o.length,elements:o}),[2,{elements:o}]}})})},e.prototype.fetchGeneratedConfig=function(e,t){return T(this,void 0,void 0,function(){var r,n,o,i,a;return E(this,function(s){switch(s.label){case 0:return s.trys.push([0,4,,5]),e&&e.elements&&0===e.elements.length?(this.log("No elements found in DOM structure, skipping config fetch."),[2,null]):(r={"Content-Type":"application/json"},[4,this.authManager.getAuthHeaders()]);case 1:return n=s.sent(),r=S(S({},r),n),o={structure:e},t&&(o.domHash=t,o.lastConfigHash=this.lastConfigHash),[4,fetch(c.CONFIG,{method:"POST",headers:r,body:JSON.stringify(o)})];case 2:if(!(i=s.sent()).ok)throw new Error("Backend returned ".concat(i.status));return[4,i.json()];case 3:return[2,s.sent()];case 4:return a=s.sent(),this.log("Error fetching generated config:",a),[2,null];case 5:return[2]}})})},e.prototype.applyGeneratedConfig=function(e){var t=this;e.tracking_config&&this.log("Applying tracking config:",e.tracking_config),e.events_to_track.forEach(function(e){try{var r=document.querySelectorAll(e.element_selector),n=e.metadata_rules||{extract_customdata:!0,extract_text:!0};r.length>0?r.forEach(function(r){var o=t.attachedListeners.get(r);o||(o=new Set,t.attachedListeners.set(r,o)),(Array.isArray(e.event_type)?e.event_type:[e.event_type]).forEach(function(i){o.has(i)||(o.add(i),"click"===i&&(r.addEventListener("click",function(r){var o=r.target,i=t.extractElementData(o,n);t.sendToWorker(e.event_name,{selector:e.element_selector,eventType:"click",category:e.category||"uncategorized",element:i,itemName:i.itemName,section:i.section,timestamp:(new Date).toISOString()})}),t.log('Attached click listener for "'.concat(e.event_name,'" on "').concat(e.element_selector,'" (category: ').concat(e.category||"uncategorized",")"))),"view"===i&&"IntersectionObserver"in window&&(new IntersectionObserver(function(r){r.forEach(function(r){if(r.isIntersecting){var o=r.target,i=t.extractElementData(o,n);t.sendToWorker(e.event_name,{selector:e.element_selector,eventType:"view",category:e.category||"uncategorized",element:i,itemName:i.itemName,section:i.section,intersectionRatio:r.intersectionRatio,timestamp:(new Date).toISOString()})}})},{threshold:[.1,.5,1]}).observe(r),t.log('Attached IntersectionObserver for "'.concat(e.event_name,'" on "').concat(e.element_selector,'"'))),"focus"!==i&&"blur"!==i||(r.addEventListener(i,function(){var o=r,a=t.extractElementData(o,n);t.sendToWorker(e.event_name,{selector:e.element_selector,eventType:i,category:e.category||"uncategorized",element:a,timestamp:(new Date).toISOString()})}),t.log("Attached ".concat(i,' listener for "').concat(e.event_name,'" on "').concat(e.element_selector,'"'))))})}):t.log('No elements found for selector: "'.concat(e.element_selector,'"'))}catch(r){t.log('Error applying selector "'.concat(e.element_selector,'":'),r)}}),e.observe_mutations&&"MutationObserver"in window&&(new MutationObserver(function(e){e.forEach(function(e){t.sendToWorker("dom_mutation",{type:e.type,target:e.target.outerHTML,timestamp:(new Date).toISOString()})})}).observe(document.body,{childList:!0,subtree:!0}),this.log("MutationObserver attached for DOM changes"))},e.prototype.extractElementData=function(e,t){var r=e.getBoundingClientRect(),n={tagName:e.tagName.toLowerCase(),id:e.id||"",className:e.className||"",textContent:(e.textContent||"").trim().substring(0,100),position:{x:Math.round(r.x),y:Math.round(r.y),width:Math.round(r.width),height:Math.round(r.height)},href:e.href||void 0,value:e.value||void 0};if(!1!==(null==t?void 0:t.extract_customdata)){var o=function(e){var t,r={},n=e.getAttribute("customdata")||e.dataset.customdata;if(n)try{var o=JSON.parse(n);r.customdata=o,o.name&&(r.itemName=o.name),o.displayedTitle&&(r.section=o.displayedTitle),o.title&&(r.title=o.title),o.category&&(r.category=o.category),o.id&&(r.itemId=o.id)}catch(e){var i=n.match(/"name"\s*:\s*"([^"]+)"/);i&&(r.itemName=i[1]);var a=n.match(/"(?:displayedTitle|title)"\s*:\s*"([^"]+)"/);a&&(r.section=a[1])}var s=e.id;if(s){r.elementId=s;var c=s.split("_");if(c.length>=2){var u=c.slice(1).join("_");!r.itemName&&u&&(r.itemName=u)}}var l=null===(t=e.textContent)||void 0===t?void 0:t.trim();l&&l.length<100&&(r.displayText=l);for(var h=e.dataset,d=0,f=Object.entries(h);d<f.length;d++){var g=f[d],p=g[0],m=g[1];!r[p]&&m&&(r["data_".concat(p)]=m)}return r}(e);Object.keys(o).length>0&&(n.enriched=o,o.itemName&&(n.itemName=o.itemName),o.section&&(n.section=o.section),o.category&&(n.category=o.category))}return this.config.debug&&(n.attributes=Array.from(e.attributes).reduce(function(e,t){return e[t.name]=t.value.length>100?t.value.substring(0,100)+"...":t.value,e},{})),n},e.prototype.sendToWorker=function(e,t){var r;if(this.shouldSampleEvents()){var n=new Date,o=this.getCommonEventData(),i=S({event:e,properties:t,timestamp:n.getTime(),created_at:n.toISOString(),userId:this.getUserId(),sessionId:this.sessionId,project_key:this.config.projectKey||void 0,client_id:this.config.clientId||this.config.apiKey||void 0,project_id:(null===(r=this.projectSettings)||void 0===r?void 0:r.project_id)||void 0},o);this.config.useWebWorker&&"undefined"!=typeof Worker?this.worker.postMessage({type:"track",payload:i}):this.eventQueue.push(i),this.log("Event tracked:",i)}else this.log("Event skipped due to sampling:",e)},e.prototype.setupWebWorker=function(){return T(this,void 0,void 0,function(){var e,t,r,n,o,i=this;return E(this,function(a){switch(a.label){case 0:return[4,this.authManager.getAuthHeaders()];case 1:return e=a.sent(),this.worker.postMessage({type:"config",payload:{apiUrl:(null===(t=this.config.apiDetails)||void 0===t?void 0:t.apiEndPoint)||"".concat(this.config.endpoint,"/api/v1/events"),batchSize:(null===(r=this.config.workerConfig)||void 0===r?void 0:r.batchSize)||10,batchInterval:(null===(n=this.config.workerConfig)||void 0===n?void 0:n.batchInterval)||5e3,headers:S(S({"Content-Type":"application/json"},e),(null===(o=this.config.apiDetails)||void 0===o?void 0:o.headers)||{})}}),this.worker.onmessage=function(e){var t;"success"===e.data.status?i.log("Batch sent successfully by worker"):"debug"===e.data.status?i.log(e.data.message,e.data):"error"===e.data.status&&(i.log("Worker failed to send batch",e.data.error),e.data.failedEvents&&e.data.failedEvents.length>0&&(t=i.eventQueue).unshift.apply(t,e.data.failedEvents))},this.log("Web worker setup complete."),[2]}})})},e.prototype.track=function(e,t){var r;if(void 0===t&&(t={}),this.shouldSampleEvents()){this.journeyTracker.trackEvent(e,t);var n=this.journeyTracker.getContext(),o=new Date,i=this.getCommonEventData(),a=S({event:e,properties:S(S({},t),{journeyContext:{sequenceIndex:n.eventCount-1,timeSinceLastEvent:n.timeSinceLastEvent,journeyDuration:Date.now()-n.journeyStartTime}}),timestamp:o.getTime(),created_at:o.toISOString(),userId:this.userManager.getUserId(),userType:this.userManager.getUserType(),sessionId:this.sessionId,project_key:this.config.projectKey||void 0,client_id:this.config.clientId||this.config.apiKey||void 0,project_id:(null===(r=this.projectSettings)||void 0===r?void 0:r.project_id)||void 0},i);this.journeyTracker.shouldAnalyzeJourney()&&this.sendJourneyForAnalysis(),this.config.useWebWorker&&"undefined"!=typeof Worker?this.worker.postMessage({type:"track",payload:a}):this.eventQueue.push(a),this.log("Event tracked public:",a)}else this.log("Event skipped due to sampling:",e)},e.prototype.startBatchTimer=function(){var e=this;this.batchTimer=window.setInterval(function(){e.flushQueue()},this.config.batchInterval)},e.prototype.flushQueue=function(){return T(this,void 0,void 0,function(){var e;return E(this,function(t){switch(t.label){case 0:return 0===this.eventQueue.length?[2]:(e=_([],this.eventQueue,!0),this.eventQueue=[],this.config.useWebWorker&&"undefined"!=typeof Worker?(this.worker.postMessage({type:"batch",events:e,endpoint:"".concat(this.config.endpoint,"/api/v1/events")}),[3,3]):[3,1]);case 1:return[4,this.sendBatchWithRetry(e)];case 2:t.sent(),t.label=3;case 3:return[2]}})})},e.prototype.sendBatchWithRetry=function(e){return T(this,void 0,void 0,function(){var t,r;return E(this,function(n){switch(n.label){case 0:if(this.batchRetryCount>=this.maxBatchRetries)return this.batchTimer&&(clearInterval(this.batchTimer),this.batchTimer=void 0,this.log("Max batch retries reached. BatchTimer cancelled.")),[2];n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this.sendBatch(e)];case 2:return n.sent(),this.batchRetryCount=0,[3,4];case 3:return t=n.sent(),this.batchRetryCount++,this.log("Batch send failed. Retry attempt ".concat(this.batchRetryCount," of ").concat(this.maxBatchRetries,"."),t),(r=this.eventQueue).unshift.apply(r,e),this.batchRetryCount>=this.maxBatchRetries&&this.batchTimer&&(clearInterval(this.batchTimer),this.batchTimer=void 0,this.log("Max batch retries reached. BatchTimer cancelled.")),[3,4];case 4:return[2]}})})},e.prototype.sendBatch=function(e){return T(this,void 0,void 0,function(){var t,r,n,o,i,a,s;return E(this,function(c){switch(c.label){case 0:return t="".concat(this.config.endpoint,"/api/v1/events"),r={"Content-Type":"application/json"},[4,this.authManager.getAuthHeaders()];case 1:n=c.sent(),r=S(S({},r),n),this.config.apiDetails&&this.config.apiDetails.apiEndPoint&&(t=this.config.apiDetails.apiEndPoint,this.config.apiDetails.headers&&(r=S(S({},r),this.config.apiDetails.headers))),o=this.config.clientId||"5288aa7d-1b7c-481e-958d-eb9b8e951f14",i=e.map(function(e){return S({event:e.event,userId:e.userId,client_id:o,timestamp:new Date(e.timestamp).toISOString()},e.properties||{})}),c.label=2;case 2:return c.trys.push([2,4,,5]),[4,fetch(t,{method:"POST",headers:r,body:JSON.stringify({events:i})})];case 3:if(!(a=c.sent()).ok)throw new Error("Failed to send batch: ".concat(a.status));return this.log("Batch sent successfully:",i),[3,5];case 4:throw s=c.sent(),this.log("Error sending batch:",s),s;case 5:return[2]}})})},e.prototype.generateSessionId=function(){return"sess_"+Math.random().toString(36).substr(2,9)},e.prototype.getPageContext=function(){var e=window.location.href,t=window.location.pathname,r=window.location.hash,n=document.referrer,o={};return new URLSearchParams(window.location.search).forEach(function(e,t){o[t]=e}),{url:e,path:t,hash:r||void 0,referrer:n||void 0,queryParams:Object.keys(o).length>0?o:void 0,title:document.title||void 0}},e.prototype.getCommonEventData=function(){return S({pageContext:this.getPageContext()},this.config.extraConfig?{extraConfig:this.config.extraConfig}:{})},e.prototype.getUserId=function(){return this.userManager.getUserId()},e.prototype.identifyUser=function(e,t){var r=this.userManager.getUserIdentificationEvent(e);this.userManager.identifyUser(e,t),this.track("user_identified",r),this.errorTracker&&this.errorTracker.setUser(e),this.log("User identified:",{userId:e,properties:t})},e.prototype.setExtraConfig=function(e,t){void 0===t&&(t=!0),t&&this.config.extraConfig?this.config.extraConfig=S(S({},this.config.extraConfig),e):this.config.extraConfig=e,this.log("Extra config updated:",this.config.extraConfig)},e.prototype.getExtraConfig=function(){return this.config.extraConfig},e.prototype.isAuthenticated=function(){return T(this,void 0,void 0,function(){return E(this,function(e){switch(e.label){case 0:return[4,this.authManager.getAccessToken()];case 1:return[2,null!==e.sent()]}})})},e.prototype.authenticate=function(){return T(this,void 0,void 0,function(){return E(this,function(e){switch(e.label){case 0:return[4,this.authManager.initialize()];case 1:return[2,e.sent()]}})})},e.prototype.logout=function(){return T(this,void 0,void 0,function(){return E(this,function(e){switch(e.label){case 0:return[4,this.authManager.logout()];case 1:return e.sent(),[2]}})})},e.prototype.sendJourneyForAnalysis=function(){return T(this,void 0,void 0,function(){var e,t,r,n,o;return E(this,function(i){switch(i.label){case 0:return i.trys.push([0,3,,4]),e=this.journeyTracker.getJourneyForAnalysis(),t="".concat(this.config.endpoint,"/api/v1/journeys/analyze"),[4,this.authManager.getAuthHeaders()];case 1:return r=i.sent(),[4,fetch(t,{method:"POST",headers:S({"Content-Type":"application/json"},r),body:JSON.stringify({client_id:this.config.clientId,user_id:this.userManager.getUserId(),session_id:this.sessionId,journey:e})})];case 2:return(n=i.sent()).ok||console.error("[AInamika SDK] Failed to send journey for analysis:",n.statusText),[3,4];case 3:return o=i.sent(),console.error("[AInamika SDK] Error sending journey for analysis:",o),[3,4];case 4:return[2]}})})},e.prototype.log=function(e,t){this.config.debug&&console.log("[AnalyticsPro SDK] ".concat(e),t||"")},e.prototype.saveConfigToFile=function(e){this.config.debug},e.prototype.loadConfigFromFile=function(){return T(this,void 0,void 0,function(){var e;return E(this,function(t){switch(t.label){case 0:return t.trys.push([0,3,,4]),[4,fetch("/AInamika_config.json",{cache:"reload"})];case 1:return(e=t.sent()).ok?[4,e.json()]:[2,null];case 2:return[2,t.sent()];case 3:return t.sent(),[2,null];case 4:return[2]}})})},e.prototype.setupDynamicDomTracking=function(){return T(this,void 0,void 0,function(){var e=this;return E(this,function(t){return"MutationObserver"in window&&(new MutationObserver(function(){e.mutationDebounceTimer&&clearTimeout(e.mutationDebounceTimer),e.mutationDebounceTimer=window.setTimeout(function(){e.handleDomMutation()},e.mutationDebounceMs)}).observe(document.body,{childList:!0,subtree:!0,attributes:!0}),this.log("Dynamic DOM MutationObserver attached")),[2]})})},e.prototype.computeDomHash=function(e){for(var t=JSON.stringify(e),r=2166136261,n=0;n<t.length;n++)r^=t.charCodeAt(n),r+=(r<<1)+(r<<4)+(r<<7)+(r<<8)+(r<<24);return(r>>>0).toString(16)},e.prototype.getCachedConfigForDomHash=function(e){try{var t=JSON.parse(localStorage.getItem("ainamika_dom_config_cache")||"{}"),r=t[e];return r?r.events_to_track?(t[e]={config:r,lastAccessed:Date.now(),createdAt:Date.now()},localStorage.setItem("ainamika_dom_config_cache",JSON.stringify(t)),r):(r.lastAccessed=Date.now(),localStorage.setItem("ainamika_dom_config_cache",JSON.stringify(t)),r.config):null}catch(e){return null}},e.prototype.setCachedConfigForDomHash=function(e,t){var r=this;try{var n=JSON.parse(localStorage.getItem("ainamika_dom_config_cache")||"{}");n[e]={config:t,lastAccessed:Date.now(),createdAt:Date.now()};var o=Object.keys(n);o.length>this.MAX_CACHED_CONFIGS&&o.sort(function(e,t){return(n[e].lastAccessed||n[e].createdAt||0)-(n[t].lastAccessed||n[t].createdAt||0)}).slice(0,o.length-this.MAX_CACHED_CONFIGS).forEach(function(e){delete n[e],r.log("Evicted old config cache: ".concat(e))}),localStorage.setItem("ainamika_dom_config_cache",JSON.stringify(n))}catch(e){this.log("Cache storage error, clearing old entries:",e),this.clearOldConfigCache()}},e.prototype.clearOldConfigCache=function(){try{var e=JSON.parse(localStorage.getItem("ainamika_dom_config_cache")||"{}"),t=Object.keys(e);if(0===t.length)return;var r=t.sort(function(t,r){var n=e[t].lastAccessed||e[t].createdAt||0;return(e[r].lastAccessed||e[r].createdAt||0)-n}),n={};r.slice(0,5).forEach(function(t){n[t]=e[t]}),localStorage.setItem("ainamika_dom_config_cache",JSON.stringify(n)),this.log("Cleared config cache, kept ".concat(Object.keys(n).length," entries"))}catch(e){localStorage.removeItem("ainamika_dom_config_cache")}},e.prototype.handleDomMutation=function(){return T(this,void 0,void 0,function(){var e,t,r,n,o,i,a,s=this;return E(this,function(c){switch(c.label){case 0:return[4,this.getDOMStructure()];case 1:return e=c.sent(),(t=this.computeDomHash(e))===this.lastDomHash?(this.log("DOM hash unchanged after mutation, skipping config fetch."),[2]):(this.log("DOM hash changed, detecting new elements...",{oldHash:this.lastDomHash,newHash:t}),this.lastDomHash=t,r=e.elements||[],0===(n=r.filter(function(e){var t=e.selector||"";return!(!t||s.knownElementSelectors.has(t))})).length?(this.log("No new elements detected, skipping config fetch."),[2]):(this.log("Found ".concat(n.length," new elements out of ").concat(r.length," total")),(o=this.getCachedConfigForDomHash(t))?(this.log("Reusing cached config for DOM hash",t),this.mergeAndApplyConfig(o),r.forEach(function(e){e.selector&&s.knownElementSelectors.add(e.selector)}),[2]):(i={elements:n},this.log("Fetching config for new elements only:",n.length),[4,this.fetchGeneratedConfig(i,t)])));case 2:return(a=c.sent())&&a.events_to_track?(this.mergeAndApplyConfig(a),this.setCachedConfigForDomHash(t,this.mergedConfig),this.lastConfigHash=a.config_hash||"",n.forEach(function(e){e.selector&&s.knownElementSelectors.add(e.selector)}),this.log("Fetched and merged config for new elements",{newEvents:a.events_to_track.length,totalEvents:this.mergedConfig.events_to_track.length})):this.log("No valid config returned for new elements"),[2]}})})},e.prototype.mergeAndApplyConfig=function(e){var t;if(e&&e.events_to_track){var r=new Set(this.mergedConfig.events_to_track.map(function(e){return e.element_selector})),n=e.events_to_track.filter(function(e){return!r.has(e.element_selector)});n.length>0&&((t=this.mergedConfig.events_to_track).push.apply(t,n),this.log("Merged ".concat(n.length," new events, total: ").concat(this.mergedConfig.events_to_track.length))),e.tracking_config&&(this.mergedConfig.tracking_config=S(S({},this.mergedConfig.tracking_config),e.tracking_config)),n.length>0&&this.applyGeneratedConfig({events_to_track:n,tracking_config:e.tracking_config})}},e}();"undefined"!=typeof window&&(window.AInamikaSDKPro=I);var C=I;return t.default}()});
1
+ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.AInamikaSDKPro=t():e.AInamikaSDKPro=t()}("undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:this,function(){return function(){"use strict";var e={d:function(t,r){for(var n in r)e.o(r,n)&&!e.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:r[n]})},o:function(e,t){return Object.prototype.hasOwnProperty.call(e,t)}},t={};e.d(t,{default:function(){return I}});var r=function(){return r=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var i in t=arguments[r])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},r.apply(this,arguments)},n=function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function a(e){try{c(n.next(e))}catch(e){o(e)}}function s(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(a,s)}c((n=n.apply(e,t||[])).next())})},i=function(e,t){var r,n,i,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=s(0),a.throw=s(1),a.return=s(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(s){return function(c){return function(s){if(r)throw new TypeError("Generator is already executing.");for(;a&&(a=0,s[0]&&(o=0)),o;)try{if(r=1,n&&(i=2&s[0]?n.return:s[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,s[1])).done)return i;switch(n=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,n=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((i=(i=o.trys).length>0&&i[i.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]<i[3])){o.label=s[1];break}if(6===s[0]&&o.label<i[1]){o.label=i[1],i=s;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(s);break}i[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],n=0}finally{r=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}},o=function(e,t,r){if(r||2===arguments.length)for(var n,i=0,o=t.length;i<o;i++)!n&&i in t||(n||(n=Array.prototype.slice.call(t,0,i)),n[i]=t[i]);return e.concat(n||Array.prototype.slice.call(t))},a=function(){function e(e){this.breadcrumbs=[],this.errorCount=0,this.errorDebounceMap=new Map,this.html2canvasLoaded=!1,this.html2canvasLoading=null,this.isCapturingScreenshot=!1,this.config=r({captureScreenshots:!1,captureDomSnapshots:!1,maxStackTraceDepth:50,maxErrorsPerSession:100,debounceMs:1e3,enableNetworkTracking:!0,enableConsoleCapture:!0},e),this.authManager=e.authManager,this.sessionId=this.generateSessionId(),this.originalConsole=r({},console),this.initialize()}return e.prototype.loadHtml2Canvas=function(){return n(this,void 0,void 0,function(){var e=this;return i(this,function(t){return this.html2canvasLoaded||"function"==typeof window.html2canvas?(this.html2canvasLoaded=!0,[2,!0]):(this.html2canvasLoading||(this.html2canvasLoading=new Promise(function(t){var r=document.createElement("script");r.src="https://html2canvas.hertzen.com/dist/html2canvas.min.js",r.async=!0,r.onload=function(){console.log("[AInamika Error Tracker] html2canvas loaded successfully"),e.html2canvasLoaded=!0,t(!0)},r.onerror=function(){console.error("[AInamika Error Tracker] Failed to load html2canvas"),t(!1)},document.head.appendChild(r)})),[2,this.html2canvasLoading])})})},e.prototype.initialize=function(){var e=this;window.addEventListener("error",function(t){e.handleError({type:"javascript",message:t.message,filename:t.filename,line:t.lineno,column:t.colno,error:t.error})}),window.addEventListener("unhandledrejection",function(t){var r;e.handleError({type:"unhandled",message:(null===(r=t.reason)||void 0===r?void 0:r.message)||"Unhandled Promise Rejection",error:t.reason,promise:!0})}),this.config.enableNetworkTracking&&this.setupNetworkTracking(),this.config.enableConsoleCapture&&this.setupConsoleCapture(),this.setupNavigationTracking(),this.setupClickTracking(),this.config.captureScreenshots&&this.loadHtml2Canvas(),console.log("[AInamika Error Tracker] Initialized successfully")},e.prototype.generateSessionId=function(){return"session_".concat(Date.now(),"_").concat(Math.random().toString(36).substr(2,9))},e.prototype.addBreadcrumb=function(e){this.breadcrumbs.push(r(r({},e),{timestamp:Date.now()})),this.breadcrumbs.length>50&&(this.breadcrumbs=this.breadcrumbs.slice(-50))},e.prototype.handleError=function(e){if(this.errorCount>=this.config.maxErrorsPerSession)console.warn("[AInamika Error Tracker] Max errors per session reached");else{var t="".concat(e.message,"_").concat(e.filename,"_").concat(e.line),r=Date.now();if(this.errorDebounceMap.has(t)&&r-this.errorDebounceMap.get(t)<this.config.debounceMs)return;this.errorDebounceMap.set(t,r),this.errorCount++,this.captureError(e)}},e.prototype.captureError=function(e){return n(this,void 0,void 0,function(){var t,r,n;return i(this,function(i){switch(i.label){case 0:return i.trys.push([0,4,,5]),t={client_id:this.config.clientId,project_key:this.config.projectKey,error_type:e.type||"javascript",message:e.message||"Unknown error",stack_trace:this.extractStackTrace(e.error),url:window.location.href,user_agent:navigator.userAgent,timestamp:Date.now(),error_metadata:{line:e.line,column:e.column,filename:e.filename,userId:this.userId,sessionId:this.sessionId,breadcrumbs:o([],this.breadcrumbs,!0),networkInfo:this.getNetworkInfo(),performance:this.getPerformanceInfo(),deviceInfo:this.getDeviceInfo()},severity:this.assessSeverity(e),session_id:this.sessionId,user_id:this.userId},this.config.captureScreenshots?(r=t,[4,this.captureScreenshot()]):[3,2];case 1:r.screen_snapshot=i.sent(),i.label=2;case 2:return[4,this.sendError(t)];case 3:return i.sent(),this.addBreadcrumb({type:"error",message:"".concat(t.error_type,": ").concat(t.message),data:{severity:t.severity}}),[3,5];case 4:return n=i.sent(),console.error("[AInamika Error Tracker] Failed to capture error:",n),[3,5];case 5:return[2]}})})},e.prototype.extractStackTrace=function(e){if(!e||!e.stack)return"";var t=e.stack.split("\n"),r=this.config.maxStackTraceDepth;return t.slice(0,r).join("\n")},e.prototype.assessSeverity=function(e){var t,r=(null===(t=e.message)||void 0===t?void 0:t.toLowerCase())||"";return r.includes("out of memory")||r.includes("security")||r.includes("permission denied")||"unhandled"===e.type?"critical":r.includes("network")||r.includes("timeout")||r.includes("failed to fetch")||r.includes("cors")?"high":r.includes("undefined")||r.includes("null")||r.includes("cannot read property")?"medium":"low"},e.prototype.captureDomSnapshot=function(){try{var e={url:window.location.href,title:document.title,viewport:{width:window.innerWidth,height:window.innerHeight},elements:this.extractDomElements()};return JSON.stringify(e)}catch(e){return console.error("[AInamika Error Tracker] Failed to capture DOM snapshot:",e),""}},e.prototype.extractDomElements=function(){var e=this,t=[];return["body > *","[id]",'[class*="error"]','[class*="modal"]',"form","button",'input[type="submit"]'].forEach(function(r){try{var n=document.querySelectorAll(r);Array.from(n).slice(0,100-t.length).forEach(function(r){var n;t.push({tagName:r.tagName,id:r.id,className:r.className,textContent:null===(n=r.textContent)||void 0===n?void 0:n.substring(0,100),attributes:e.getElementAttributes(r)})})}catch(e){}}),t},e.prototype.getElementAttributes=function(e){var t={};return["id","class","type","name","value","href","src"].forEach(function(r){var n=e.getAttribute(r);n&&(t[r]=n)}),t},e.prototype.captureScreenshot=function(){return n(this,void 0,void 0,function(){var e;return i(this,function(t){switch(t.label){case 0:if(this.isCapturingScreenshot)return[2,""];this.isCapturingScreenshot=!0,t.label=1;case 1:return t.trys.push([1,5,6,7]),[4,this.loadHtml2Canvas()];case 2:return t.sent()?"function"!=typeof window.html2canvas?[3,4]:[4,window.html2canvas(document.body,{height:Math.min(window.innerHeight,1e3),width:Math.min(window.innerWidth,1e3),useCORS:!0,logging:!1})]:(console.warn("[AInamika Error Tracker] html2canvas not available, skipping screenshot"),[2,""]);case 3:return[2,t.sent().toDataURL("image/jpeg",.7)];case 4:return[2,""];case 5:return e=t.sent(),console.error("[AInamika Error Tracker] Failed to capture screenshot:",e),[2,""];case 6:return this.isCapturingScreenshot=!1,[7];case 7:return[2]}})})},e.prototype.getNetworkInfo=function(){var e=navigator.connection||navigator.mozConnection||navigator.webkitConnection;return e?{effectiveType:e.effectiveType,downlink:e.downlink,rtt:e.rtt,saveData:e.saveData}:{}},e.prototype.getPerformanceInfo=function(){var e={};if(performance.memory&&(e.memory={usedJSHeapSize:performance.memory.usedJSHeapSize,totalJSHeapSize:performance.memory.totalJSHeapSize,jsHeapSizeLimit:performance.memory.jsHeapSizeLimit}),performance.timing){var t=performance.timing;e.timing={domContentLoaded:t.domContentLoadedEventEnd-t.navigationStart,load:t.loadEventEnd-t.navigationStart},performance.getEntriesByType&&performance.getEntriesByType("paint").forEach(function(t){"first-paint"===t.name?e.timing.firstPaint=t.startTime:"first-contentful-paint"===t.name&&(e.timing.firstContentfulPaint=t.startTime)})}return e},e.prototype.getDeviceInfo=function(){var e=navigator.userAgent,t="desktop";/tablet|ipad|playbook|silk/i.test(e)?t="tablet":/mobile|iphone|ipod|android|blackberry|opera mini|iemobile/i.test(e)&&(t="mobile");var r="Unknown",n="";/windows/i.test(e)?(r="Windows",(a=e.match(/Windows NT (\d+\.\d+)/))&&(n=a[1])):/macintosh|mac os x/i.test(e)?(r="macOS",(a=e.match(/Mac OS X (\d+[._]\d+)/))&&(n=a[1].replace("_","."))):/android/i.test(e)?(r="Android",(a=e.match(/Android (\d+(\.\d+)?)/))&&(n=a[1])):/iphone|ipad|ipod/i.test(e)?(r="iOS",(a=e.match(/OS (\d+[._]\d+)/))&&(n=a[1].replace("_","."))):/linux/i.test(e)&&(r="Linux");var i="Unknown",o="";if(/edg/i.test(e))i="Edge",(a=e.match(/Edg\/(\d+(\.\d+)?)/))&&(o=a[1]);else if(/chrome/i.test(e)&&!/edg/i.test(e))i="Chrome",(a=e.match(/Chrome\/(\d+(\.\d+)?)/))&&(o=a[1]);else if(/safari/i.test(e)&&!/chrome/i.test(e))i="Safari",(a=e.match(/Version\/(\d+(\.\d+)?)/))&&(o=a[1]);else if(/firefox/i.test(e)){var a;i="Firefox",(a=e.match(/Firefox\/(\d+(\.\d+)?)/))&&(o=a[1])}return{deviceType:t,os:r,osVersion:n,browser:i,browserVersion:o,screenWidth:window.screen.width,screenHeight:window.screen.height,language:navigator.language||"",timezone:Intl.DateTimeFormat().resolvedOptions().timeZone||""}},e.prototype.setupNetworkTracking=function(){var e=this,t=window.fetch;window.fetch=function(){for(var r=[],o=0;o<arguments.length;o++)r[o]=arguments[o];return n(e,void 0,void 0,function(){var e,n,o,a;return i(this,function(i){switch(i.label){case 0:e=Date.now(),n=r[0]instanceof Request?r[0].url:String(r[0]),i.label=1;case 1:return i.trys.push([1,3,,4]),[4,t.apply(void 0,r)];case 2:return o=i.sent(),this.addBreadcrumb({type:"network",message:"Fetch ".concat(o.status," ").concat(n),data:{url:n,status:o.status,duration:Date.now()-e}}),o.ok||this.handleError({type:"network",message:"Network request failed: ".concat(o.status," ").concat(o.statusText),url:n,status:o.status}),[2,o];case 3:throw a=i.sent(),this.addBreadcrumb({type:"network",message:"Fetch failed ".concat(n),data:{url:n,error:(null==a?void 0:a.message)||"Unknown error"}}),this.handleError({type:"network",message:"Network request failed: ".concat((null==a?void 0:a.message)||"Unknown error"),url:n,error:a}),a;case 4:return[2]}})})};var r=XMLHttpRequest.prototype.open,a=XMLHttpRequest.prototype.send;XMLHttpRequest.prototype.open=function(e,t,n,i,o){return this._errorTracker={method:e,url:t,startTime:Date.now()},r.call(this,e,t,n||!0,i,o)},XMLHttpRequest.prototype.send=function(){for(var e=this,t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];var n=this._errorTracker;return this.addEventListener("loadend",function(){if(n){var t=Date.now()-n.startTime;e.status>=400&&e.dispatchEvent(new CustomEvent("networkerror",{detail:{type:"network",message:"XHR request failed: ".concat(e.status," ").concat(e.statusText),url:n.url,status:e.status}})),e.dispatchEvent(new CustomEvent("networkbreadcrumb",{detail:{type:"network",message:"XHR ".concat(e.status," ").concat(n.url),data:{method:n.method,url:n.url,status:e.status,duration:t}}}))}}),a.call.apply(a,o([this],t,!1))},document.addEventListener("networkerror",function(t){e.handleError(t.detail)}),document.addEventListener("networkbreadcrumb",function(t){e.addBreadcrumb(t.detail)})},e.prototype.setupConsoleCapture=function(){var e=this;["error","warn"].forEach(function(t){var r=e.originalConsole[t];console[t]=function(){for(var n=[],i=0;i<arguments.length;i++)n[i]=arguments[i];"function"==typeof r&&r.call.apply(r,o([console],n,!1)),"error"===t&&e.handleError({type:"console",message:n.map(function(e){return String(e)}).join(" "),consoleMethod:t}),e.addBreadcrumb({type:"console",message:"Console ".concat(t,": ").concat(n.map(function(e){return String(e)}).join(" ")),data:{level:t}})}})},e.prototype.setupNavigationTracking=function(){var e=this,t=window.location.href,r=function(){var r=window.location.href;r!==t&&(e.addBreadcrumb({type:"navigation",message:"Navigation from ".concat(t," to ").concat(r),data:{from:t,to:r}}),t=r)};window.addEventListener("popstate",r),window.addEventListener("hashchange",r);var n=history.pushState,i=history.replaceState;history.pushState=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];n.apply(this,e),setTimeout(r,0)},history.replaceState=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];i.apply(this,e),setTimeout(r,0)}},e.prototype.setupClickTracking=function(){var e=this;document.addEventListener("click",function(t){var r,n=t.target;if(n){var i=e.getElementSelector(n),o=(null===(r=n.textContent)||void 0===r?void 0:r.trim().substring(0,50))||"";e.addBreadcrumb({type:"click",message:"Clicked ".concat(i).concat(o?": ".concat(o):""),data:{selector:i,text:o,tagName:n.tagName,id:n.id,className:n.className}})}})},e.prototype.getElementSelector=function(e){if(e.id)return"#".concat(e.id);if(e.className){var t=e.className.split(" ").filter(function(e){return e}).slice(0,2);if(t.length)return".".concat(t.join("."))}return e.tagName.toLowerCase()},e.prototype.sendError=function(e){return n(this,void 0,void 0,function(){var t,n,o,a;return i(this,function(i){switch(i.label){case 0:return i.trys.push([0,5,,6]),t={"Content-Type":"application/json"},this.authManager?[4,this.authManager.getAuthHeaders()]:[3,2];case 1:return n=i.sent(),t=r(r({},t),n),[3,3];case 2:this.config.apiKey&&(t.Authorization="Bearer ".concat(this.config.apiKey)),i.label=3;case 3:return[4,fetch("".concat(this.config.endpoint,"/api/v1/errors"),{method:"POST",headers:t,body:JSON.stringify(e)})];case 4:if(!(o=i.sent()).ok)throw new Error("Failed to send error: ".concat(o.status," ").concat(o.statusText));return console.log("[AInamika Error Tracker] Error sent successfully"),[3,6];case 5:return a=i.sent(),console.error("[AInamika Error Tracker] Failed to send error:",a),this.storeErrorLocally(e),[3,6];case 6:return[2]}})})},e.prototype.storeErrorLocally=function(e){try{var t=localStorage.getItem("ainamika_errors")||"[]",r=JSON.parse(t);r.push(e),r.length>50&&r.splice(0,r.length-50),localStorage.setItem("ainamika_errors",JSON.stringify(r))}catch(e){console.error("[AInamika Error Tracker] Failed to store error locally:",e)}},e.prototype.captureException=function(e,t){this.handleError({type:"custom",message:e.message,error:e,context:t})},e.prototype.setUser=function(e){this.userId=e},e.prototype.addTag=function(e,t){this.config.clientId||(this.config.clientId+="_".concat(e,":").concat(t))},e.prototype.flushStoredErrors=function(){return n(this,void 0,void 0,function(){var e,t,r,n,o,a;return i(this,function(i){switch(i.label){case 0:if(i.trys.push([0,5,,6]),!(e=localStorage.getItem("ainamika_errors")))return[2];if(0===(t=JSON.parse(e)).length)return[2];console.log("[AInamika Error Tracker] Flushing ".concat(t.length," stored errors")),r=0,n=t,i.label=1;case 1:return r<n.length?(o=n[r],[4,this.sendError(o)]):[3,4];case 2:i.sent(),i.label=3;case 3:return r++,[3,1];case 4:return localStorage.removeItem("ainamika_errors"),[3,6];case 5:return a=i.sent(),console.error("[AInamika Error Tracker] Failed to flush stored errors:",a),[3,6];case 6:return[2]}})})},e}(),s="undefined"!=typeof window&&window.__AINAMIKA_CONFIG__?window.__AINAMIKA_CONFIG__:{API_BASE_URL:"https://ainamika-webhook-proxy-366651516847.asia-south1.run.app",APP_ENV:"production",DEBUG:!1},c={EVENTS:"".concat(s.API_BASE_URL,"/api/v1/events"),ERRORS:"".concat(s.API_BASE_URL,"/api/errors/report"),CONFIG:"".concat(s.API_BASE_URL,"/api/v1/sdk/config"),DEBUG_EVENTS:"".concat(s.API_BASE_URL,"/api/v1/debug/events"),PROJECTS_LOOKUP:"".concat(s.API_BASE_URL,"/api/v1/projects/lookup"),SAMPLING_CHECK:"".concat(s.API_BASE_URL,"/api/v1/projects/sampling/check")},l=function(){return l=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var i in t=arguments[r])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},l.apply(this,arguments)},u=function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function a(e){try{c(n.next(e))}catch(e){o(e)}}function s(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(a,s)}c((n=n.apply(e,t||[])).next())})},h=function(e,t){var r,n,i,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=s(0),a.throw=s(1),a.return=s(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(s){return function(c){return function(s){if(r)throw new TypeError("Generator is already executing.");for(;a&&(a=0,s[0]&&(o=0)),o;)try{if(r=1,n&&(i=2&s[0]?n.return:s[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,s[1])).done)return i;switch(n=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,n=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((i=(i=o.trys).length>0&&i[i.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]<i[3])){o.label=s[1];break}if(6===s[0]&&o.label<i[1]){o.label=i[1],i=s;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(s);break}i[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],n=0}finally{r=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}},d=function(){function e(e){void 0===e&&(e={}),this.STORAGE_KEY="ainamika_error_queue",this.METADATA_KEY="ainamika_error_metadata",this.isProcessing=!1,this.config=l({maxStorageSize:5242880,maxRetries:5,retryInterval:3e4,compressionEnabled:!0,encryptionEnabled:!1},e),this.initialize()}return e.prototype.initialize=function(){var e=this;this.cleanupOldErrors(),this.startRetryTimer(),this.setupStorageListener(),setTimeout(function(){return e.processQueue()},1e3)},e.prototype.storeError=function(e){return u(this,void 0,void 0,function(){var t,r,n,i=this;return h(this,function(o){switch(o.label){case 0:return o.trys.push([0,2,,3]),t=this.generateErrorId(),r={id:t,errorData:this.config.compressionEnabled?this.compressData(e):e,timestamp:Date.now(),retryCount:0},[4,this.addToQueue(r)];case 1:return o.sent(),this.updateMetadata(),setTimeout(function(){return i.processQueue()},100),[2,t];case 2:throw n=o.sent(),console.error("[AInamika Error Storage] Failed to store error:",n),n;case 3:return[2]}})})},e.prototype.getStoredErrors=function(){var e=this;try{var t=localStorage.getItem(this.STORAGE_KEY);return t?JSON.parse(t).map(function(t){return l(l({},t),{errorData:e.config.compressionEnabled?e.decompressData(t.errorData):t.errorData})}):[]}catch(e){return console.error("[AInamika Error Storage] Failed to get stored errors:",e),[]}},e.prototype.removeError=function(e){try{var t=this.getQueueRaw(),r=t.filter(function(t){return t.id!==e});return r.length!==t.length&&(localStorage.setItem(this.STORAGE_KEY,JSON.stringify(r)),this.updateMetadata(),!0)}catch(e){return console.error("[AInamika Error Storage] Failed to remove error:",e),!1}},e.prototype.clearAll=function(){try{localStorage.removeItem(this.STORAGE_KEY),localStorage.removeItem(this.METADATA_KEY),console.log("[AInamika Error Storage] All errors cleared")}catch(e){console.error("[AInamika Error Storage] Failed to clear errors:",e)}},e.prototype.getStorageStats=function(){try{var e=this.getQueueRaw(),t=new Blob([localStorage.getItem(this.STORAGE_KEY)||""]).size,r=e.map(function(e){return e.timestamp}).sort();return{errorCount:e.length,totalSize:t,oldestError:r[0],newestError:r[r.length-1]}}catch(e){return console.error("[AInamika Error Storage] Failed to get storage stats:",e),{errorCount:0,totalSize:0}}},e.prototype.processQueue=function(){return u(this,void 0,void 0,function(){var e,t,r,n,i;return h(this,function(o){switch(o.label){case 0:if(this.isProcessing)return[2];this.isProcessing=!0,o.label=1;case 1:if(o.trys.push([1,,8,9]),0===(e=this.getQueueRaw()).length)return[2];console.log("[AInamika Error Storage] Processing ".concat(e.length," queued errors")),t=0,r=e,o.label=2;case 2:if(!(t<r.length))return[3,7];if((n=r[t]).retryCount>=this.config.maxRetries)return console.warn("[AInamika Error Storage] Max retries reached for error ".concat(n.id)),this.removeError(n.id),[3,6];if(n.lastRetry&&Date.now()-n.lastRetry<this.config.retryInterval)return[3,6];o.label=3;case 3:return o.trys.push([3,5,,6]),[4,this.sendError(n)];case 4:return o.sent()?(this.removeError(n.id),console.log("[AInamika Error Storage] Successfully sent error ".concat(n.id))):this.incrementRetryCount(n.id),[3,6];case 5:return i=o.sent(),console.error("[AInamika Error Storage] Failed to send error ".concat(n.id,":"),i),this.incrementRetryCount(n.id),[3,6];case 6:return t++,[3,2];case 7:return[3,9];case 8:return this.isProcessing=!1,[7];case 9:return[2]}})})},e.prototype.retryError=function(e){return u(this,void 0,void 0,function(){var t,r,n;return h(this,function(i){switch(i.label){case 0:if(t=this.getQueueRaw(),!(r=t.find(function(t){return t.id===e})))return[2,!1];i.label=1;case 1:return i.trys.push([1,3,,4]),[4,this.sendError(r)];case 2:return i.sent()?(this.removeError(e),[2,!0]):(this.incrementRetryCount(e),[2,!1]);case 3:return n=i.sent(),console.error("[AInamika Error Storage] Failed to retry error ".concat(e,":"),n),this.incrementRetryCount(e),[2,!1];case 4:return[2]}})})},e.prototype.addToQueue=function(e){return u(this,void 0,void 0,function(){var t,r;return h(this,function(n){if((t=this.getQueueRaw()).push(e),r=JSON.stringify(t),new Blob([r]).size>this.config.maxStorageSize)for(;t.length>0&&new Blob([JSON.stringify(t)]).size>this.config.maxStorageSize;)t.shift(),console.warn("[AInamika Error Storage] Removed old error due to size limit");return localStorage.setItem(this.STORAGE_KEY,JSON.stringify(t)),[2]})})},e.prototype.getQueueRaw=function(){try{var e=localStorage.getItem(this.STORAGE_KEY);return e?JSON.parse(e):[]}catch(e){return console.error("[AInamika Error Storage] Failed to parse stored errors:",e),[]}},e.prototype.incrementRetryCount=function(e){try{var t=this.getQueueRaw(),r=t.findIndex(function(t){return t.id===e});-1!==r&&(t[r].retryCount++,t[r].lastRetry=Date.now(),localStorage.setItem(this.STORAGE_KEY,JSON.stringify(t)))}catch(e){console.error("[AInamika Error Storage] Failed to increment retry count:",e)}},e.prototype.sendError=function(e){return u(this,void 0,void 0,function(){var t,r,n,i;return h(this,function(o){switch(o.label){case 0:return o.trys.push([0,2,,3]),t=this.config.compressionEnabled?this.decompressData(e.errorData):e.errorData,r=t.endpoint||c.ERRORS,n=t.apiKey||"",[4,fetch("".concat(r,"/api/v1/errors"),{method:"POST",headers:{"Content-Type":"application/json",Authorization:n?"Bearer ".concat(n):""},body:JSON.stringify(t)})];case 1:return[2,o.sent().ok];case 2:return i=o.sent(),console.error("[AInamika Error Storage] Network error sending stored error:",i),[2,!1];case 3:return[2]}})})},e.prototype.compressData=function(e){try{var t=JSON.stringify(e);return btoa(t)}catch(t){return console.warn("[AInamika Error Storage] Compression failed, storing uncompressed:",t),e}},e.prototype.decompressData=function(e){try{if("string"==typeof e&&e.length>0){var t=atob(e);return JSON.parse(t)}return e}catch(t){return console.warn("[AInamika Error Storage] Decompression failed, returning raw data:",t),e}},e.prototype.generateErrorId=function(){return"error_".concat(Date.now(),"_").concat(Math.random().toString(36).substr(2,9))},e.prototype.cleanupOldErrors=function(){try{var e=this.getQueueRaw(),t=Date.now()-6048e5,r=e.filter(function(e){return e.timestamp>t});r.length!==e.length&&(localStorage.setItem(this.STORAGE_KEY,JSON.stringify(r)),console.log("[AInamika Error Storage] Cleaned up ".concat(e.length-r.length," old errors")))}catch(e){console.error("[AInamika Error Storage] Failed to cleanup old errors:",e)}},e.prototype.startRetryTimer=function(){var e=this;this.retryTimer=window.setInterval(function(){e.processQueue()},this.config.retryInterval)},e.prototype.setupStorageListener=function(){var e=this;window.addEventListener("storage",function(t){t.key===e.STORAGE_KEY&&(console.log("[AInamika Error Storage] Storage updated from another tab"),setTimeout(function(){return e.processQueue()},1e3))}),window.addEventListener("online",function(){console.log("[AInamika Error Storage] Network back online, processing queue"),setTimeout(function(){return e.processQueue()},1e3)}),window.addEventListener("offline",function(){console.log("[AInamika Error Storage] Network offline, errors will be queued")})},e.prototype.updateMetadata=function(){try{var e=this.getStorageStats(),t=l({lastUpdate:Date.now()},e);localStorage.setItem(this.METADATA_KEY,JSON.stringify(t))}catch(e){console.error("[AInamika Error Storage] Failed to update metadata:",e)}},e.prototype.exportErrors=function(){try{var e=this.getStoredErrors(),t={timestamp:Date.now(),version:"1.0",stats:this.getStorageStats(),errors:e};return JSON.stringify(t,null,2)}catch(e){return console.error("[AInamika Error Storage] Failed to export errors:",e),"{}"}},e.prototype.importErrors=function(e){try{var t=JSON.parse(e);if(!t.errors||!Array.isArray(t.errors))throw new Error("Invalid export format");this.clearAll();for(var r=0,n=t.errors;r<n.length;r++){var i=n[r];this.storeError(i.errorData)}return console.log("[AInamika Error Storage] Imported ".concat(t.errors.length," errors")),!0}catch(e){return console.error("[AInamika Error Storage] Failed to import errors:",e),!1}},e.prototype.destroy=function(){this.retryTimer&&(clearInterval(this.retryTimer),this.retryTimer=void 0),this.processQueue(),console.log("[AInamika Error Storage] Storage instance destroyed")},e}(),g=(function(){function e(){}e.getAinamikaStorageUsage=function(){var e=0,t=0,r=0;for(var n in localStorage)if(localStorage.hasOwnProperty(n)){var i=new Blob([localStorage.getItem(n)||""]).size;e+=i,n.startsWith("ainamika_error")?t+=i:n.startsWith("ainamika_")&&(r+=i)}return{totalSize:e,errorSize:t,otherSize:r}},e.checkStorageSpace=function(e){try{var t="ainamika_storage_test",r="x".repeat(Math.min(e,1048576));return localStorage.setItem(t,r),localStorage.removeItem(t),!0}catch(e){return!1}},e.cleanupAllAinamikaStorage=function(){var e=[];for(var t in localStorage)t.startsWith("ainamika_")&&e.push(t);e.forEach(function(e){return localStorage.removeItem(e)}),console.log("[AInamika Storage Utils] Cleaned up ".concat(e.length," storage keys"))},e.generateStorageReport=function(){var t=new d;return{usage:e.getAinamikaStorageUsage(),errors:t.getStoredErrors(),metadata:t.getStorageStats()}}}(),function(){return g=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var i in t=arguments[r])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},g.apply(this,arguments)}),f=function(){function e(){this.userId=null,this.userProperties={},this.initializeUser()}return e.prototype.initializeUser=function(){this.userId=this.getOrCreateUserId()},e.prototype.getOrCreateUserId=function(){try{var e=localStorage.getItem("ainamika_user_id");return e||(e=this.generateAnonymousId(),localStorage.setItem("ainamika_user_id",e)),e}catch(e){return console.warn("[UserManager] localStorage not available, using session ID"),this.generateAnonymousId()}},e.prototype.generateAnonymousId=function(){return"anon_"+Math.random().toString(36).substr(2,9)+"_"+Date.now()},e.prototype.getUserId=function(){return this.userId||(this.userId=this.getOrCreateUserId()),this.userId},e.prototype.getUserProperties=function(){return g({},this.userProperties)},e.prototype.identifyUser=function(e,t){var r=this.getUserId();try{localStorage.setItem("ainamika_user_id",e),this.userId=e,t&&(this.userProperties=g(g({},this.userProperties),t)),console.log("[UserManager] User identified: ".concat(r," → ").concat(e))}catch(e){console.error("[UserManager] Error identifying user:",e)}},e.prototype.updateUserProperties=function(e){this.userProperties=g(g({},this.userProperties),e)},e.prototype.clearUser=function(){try{localStorage.removeItem("ainamika_user_id"),this.userId=null,this.userProperties={},this.initializeUser()}catch(e){console.error("[UserManager] Error clearing user:",e)}},e.prototype.getUserIdentificationEvent=function(e){return{event:"user_identified",previous_id:this.getUserId(),user_id:e,timestamp:Date.now(),properties:this.userProperties}},e.prototype.isAnonymousUser=function(){return this.getUserId().startsWith("anon_")},e.prototype.getUserType=function(){return this.isAnonymousUser()?"anonymous":"authenticated"},e}(),p=function(){return p=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var i in t=arguments[r])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},p.apply(this,arguments)},m=function(){function e(){this.userJourney=[],this.lastEventTime=0,this.sequenceIndex=0,this.maxJourneyLength=50,this.journeyAnalysisThreshold=5,this.journeyStartTime=Date.now()}return e.prototype.trackEvent=function(e,t){var r=Date.now(),n=this.lastEventTime?r-this.lastEventTime:0,i={eventName:e,timestamp:r,properties:p(p({},t),{timeSinceLastEvent:n,journeyPosition:this.sequenceIndex}),sequenceIndex:this.sequenceIndex++};this.userJourney.push(i),this.lastEventTime=r,this.userJourney.length>this.maxJourneyLength&&(this.userJourney=this.userJourney.slice(-this.maxJourneyLength)),console.log("[JourneyTracker] Event tracked: ".concat(e," (position: ").concat(i.sequenceIndex,")"))},e.prototype.getContext=function(){var e=Date.now();return{journeySequence:this.getJourneySequence(),eventCount:this.userJourney.length,lastEventTime:this.lastEventTime,journeyStartTime:this.journeyStartTime,timeSinceLastEvent:this.lastEventTime?e-this.lastEventTime:0}},e.prototype.getJourneySequence=function(){return this.userJourney.map(function(e){return e.eventName})},e.prototype.getJourneyData=function(){return function(e,t,r){if(r||2===arguments.length)for(var n,i=0,o=t.length;i<o;i++)!n&&i in t||(n||(n=Array.prototype.slice.call(t,0,i)),n[i]=t[i]);return e.concat(n||Array.prototype.slice.call(t))}([],this.userJourney,!0)},e.prototype.shouldAnalyzeJourney=function(){return this.userJourney.length>=this.journeyAnalysisThreshold&&this.userJourney.length%this.journeyAnalysisThreshold===0},e.prototype.getJourneyForAnalysis=function(){var e=Date.now()-this.journeyStartTime,t=this.calculateAverageTimeBetweenEvents();return{journey:this.userJourney.map(function(e){return{name:e.eventName,timestamp:e.timestamp,properties:e.properties}}),metadata:{journeyLength:this.userJourney.length,journeyDuration:e,avgTimeBetweenEvents:t,startTime:this.journeyStartTime,endTime:this.lastEventTime}}},e.prototype.calculateAverageTimeBetweenEvents=function(){if(this.userJourney.length<2)return 0;for(var e=0,t=1;t<this.userJourney.length;t++)e+=this.userJourney[t].timestamp-this.userJourney[t-1].timestamp;return Math.round(e/(this.userJourney.length-1))},e.prototype.findPatterns=function(){var e={};if(this.userJourney.length<3)return e;for(var t=0;t<=this.userJourney.length-3;t++){var r=this.userJourney.slice(t,t+3).map(function(e){return e.eventName}).join(" → ");e[r]=(e[r]||0)+1}return Object.fromEntries(Object.entries(e).filter(function(e){return e[0],e[1]>1}))},e.prototype.clearJourney=function(){this.userJourney=[],this.sequenceIndex=0,this.lastEventTime=0,this.journeyStartTime=Date.now()},e.prototype.getJourneySegment=function(e){return this.userJourney.slice(-e)},e.prototype.detectPotentialFunnel=function(){for(var e=this.getJourneySequence().slice(-5),t=0,r=Object.entries({signup_flow:["view_pricing","click_signup","enter_email"],purchase_flow:["view_product","add_to_cart","view_cart"],onboarding_flow:["user_signup","profile_setup","tutorial_start"]});t<r.length;t++){var n=r[t],i=n[0];if(n[1].filter(function(t){return e.includes(t)}).length>=2)return i}return null},e}(),v=function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function a(e){try{c(n.next(e))}catch(e){o(e)}}function s(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(a,s)}c((n=n.apply(e,t||[])).next())})},y=function(e,t){var r,n,i,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=s(0),a.throw=s(1),a.return=s(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(s){return function(c){return function(s){if(r)throw new TypeError("Generator is already executing.");for(;a&&(a=0,s[0]&&(o=0)),o;)try{if(r=1,n&&(i=2&s[0]?n.return:s[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,s[1])).done)return i;switch(n=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,n=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((i=(i=o.trys).length>0&&i[i.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]<i[3])){o.label=s[1];break}if(6===s[0]&&o.label<i[1]){o.label=i[1],i=s;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(s);break}i[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],n=0}finally{r=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}},k=function(){function e(e,t,r){void 0===r&&(r=!1),this.accessToken=null,this.refreshToken=null,this.tokenExpiry=null,this.clientId=e,this.apiEndpoint=t,this.debug=r,this.loadTokens()}return e.prototype.initialize=function(){return v(this,void 0,void 0,function(){var e,t;return y(this,function(r){switch(r.label){case 0:return r.trys.push([0,4,,5]),this.isTokenValid()?(this.debugLog("Using existing valid token"),[2,!0]):this.refreshToken?[4,this.refreshAccessToken()]:[3,2];case 1:if(r.sent())return[2,!0];r.label=2;case 2:return[4,this.requestTokens()];case 3:return(e=r.sent())?(this.setTokens(e),[2,!0]):[2,!1];case 4:return t=r.sent(),this.debugLog("Authentication initialization failed:",t),[2,!1];case 5:return[2]}})})},e.prototype.requestTokens=function(){return v(this,void 0,void 0,function(){var e,t;return y(this,function(r){switch(r.label){case 0:return r.trys.push([0,3,,4]),[4,fetch("".concat(this.apiEndpoint,"/api/v1/auth/token"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:this.clientId})})];case 1:if(!(e=r.sent()).ok)throw new Error("Token request failed: ".concat(e.status));return[4,e.json()];case 2:return[2,r.sent()];case 3:return t=r.sent(),this.debugLog("Token request error:",t),[2,null];case 4:return[2]}})})},e.prototype.refreshAccessToken=function(){return v(this,void 0,void 0,function(){var e,t,r;return y(this,function(n){switch(n.label){case 0:if(!this.refreshToken)return[2,!1];n.label=1;case 1:return n.trys.push([1,4,,5]),[4,fetch("".concat(this.apiEndpoint,"/api/v1/auth/refresh"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refresh_token:this.refreshToken})})];case 2:return(e=n.sent()).ok?[4,e.json()]:(this.clearTokens(),[2,!1]);case 3:return t=n.sent(),this.setTokens(t),[2,!0];case 4:return r=n.sent(),this.debugLog("Token refresh error:",r),[2,!1];case 5:return[2]}})})},e.prototype.getAccessToken=function(){return v(this,void 0,void 0,function(){return y(this,function(e){switch(e.label){case 0:return this.shouldRefreshToken()?[4,this.refreshAccessToken()]:[3,2];case 1:e.sent(),e.label=2;case 2:return this.isTokenValid()?[3,4]:[4,this.initialize()];case 3:if(!e.sent())return[2,null];e.label=4;case 4:return[2,this.accessToken]}})})},e.prototype.getAuthHeaders=function(){return v(this,void 0,void 0,function(){var e;return y(this,function(t){switch(t.label){case 0:return[4,this.getAccessToken()];case 1:return(e=t.sent())?[2,{Authorization:"Bearer ".concat(e)}]:[2,{"X-Client-ID":this.clientId}]}})})},e.prototype.isTokenValid=function(){return!(!this.accessToken||!this.tokenExpiry)&&Date.now()<this.tokenExpiry},e.prototype.shouldRefreshToken=function(){return!(!this.tokenExpiry||!this.refreshToken)&&Date.now()>this.tokenExpiry-3e5},e.prototype.setTokens=function(e){this.accessToken=e.access_token,this.refreshToken=e.refresh_token||this.refreshToken,this.tokenExpiry=Date.now()+1e3*e.expires_in,this.saveTokens(),this.scheduleTokenRefresh(),this.debugLog("Tokens set successfully")},e.prototype.scheduleTokenRefresh=function(){var e=this;this.refreshTimer&&clearTimeout(this.refreshTimer);var t=Math.max(0,this.tokenExpiry-Date.now()-3e5);this.refreshTimer=setTimeout(function(){e.refreshAccessToken()},t)},e.prototype.saveTokens=function(){if("undefined"!=typeof window&&window.localStorage){var e={accessToken:this.accessToken,refreshToken:this.refreshToken,tokenExpiry:this.tokenExpiry};localStorage.setItem("ainamika_auth_".concat(this.clientId),JSON.stringify(e))}},e.prototype.loadTokens=function(){if("undefined"!=typeof window&&window.localStorage){var e=localStorage.getItem("ainamika_auth_".concat(this.clientId));if(e)try{var t=JSON.parse(e);this.accessToken=t.accessToken,this.refreshToken=t.refreshToken,this.tokenExpiry=t.tokenExpiry,this.isTokenValid()&&this.scheduleTokenRefresh()}catch(e){this.debugLog("Failed to load stored tokens:",e)}}},e.prototype.clearTokens=function(){this.accessToken=null,this.refreshToken=null,this.tokenExpiry=null,"undefined"!=typeof window&&window.localStorage&&localStorage.removeItem("ainamika_auth_".concat(this.clientId)),this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=void 0)},e.prototype.logout=function(){return v(this,void 0,void 0,function(){var e;return y(this,function(t){switch(t.label){case 0:return t.trys.push([0,3,4,5]),this.accessToken?[4,fetch("".concat(this.apiEndpoint,"/api/v1/auth/logout"),{method:"POST",headers:{Authorization:"Bearer ".concat(this.accessToken)}})]:[3,2];case 1:t.sent(),t.label=2;case 2:return[3,5];case 3:return e=t.sent(),this.debugLog("Logout error:",e),[3,5];case 4:return this.clearTokens(),[7];case 5:return[2]}})})},e.prototype.debugLog=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.debug&&console.log.apply(console,function(e,t,r){if(r||2===arguments.length)for(var n,i=0,o=t.length;i<o;i++)!n&&i in t||(n||(n=Array.prototype.slice.call(t,0,i)),n[i]=t[i]);return e.concat(n||Array.prototype.slice.call(t))}(["[Ainamika Auth]"],e,!1))},e}(),b=function(){return b=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var i in t=arguments[r])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},b.apply(this,arguments)},w=function(){function e(e,t){this.performanceMetrics={},this.scrollDepthReached=new Set,this.clickHistory=[],this.isPageVisible=!0,this.visibilityChangeCount=0,this.config=b({trackPerformance:!0,trackEngagement:!0,trackScrollDepth:!0,trackRageClicks:!0,trackTimeOnPage:!0,trackAPIResponses:!1,scrollDepthThresholds:[25,50,75,90,100],rageClickThreshold:3,rageClickWindow:1e3,apiTrackingPatterns:[]},e),this.onEvent=t,this.pageStartTime=Date.now(),this.lastActivityTime=Date.now(),this.originalFetch=window.fetch.bind(window),this.originalXHR=XMLHttpRequest.prototype.open,this.engagementMetrics={timeOnPage:0,scrollDepth:0,scrollDepthMilestones:[],rageClicks:0,totalClicks:0,activeTime:0,idleTime:0,pageVisibilityChanges:0},this.initialize()}return e.prototype.initialize=function(){var e=this;this.config.trackPerformance&&this.initPerformanceTracking(),this.config.trackEngagement&&this.initEngagementTracking(),this.config.trackScrollDepth&&this.initScrollTracking(),this.config.trackRageClicks&&this.initRageClickTracking(),this.config.trackTimeOnPage&&this.initTimeTracking(),this.config.trackAPIResponses&&this.initAPITracking(),window.addEventListener("beforeunload",function(){e.trackPageExit()}),console.log("[AInamika Advanced Tracker] Initialized")},e.prototype.initPerformanceTracking=function(){var e=this;if("PerformanceObserver"in window){try{new PerformanceObserver(function(t){var r,n=t.getEntries(),i=n[n.length-1];e.performanceMetrics.lcp=i.startTime,e.onEvent("performance_lcp",{value:i.startTime,element:null===(r=i.element)||void 0===r?void 0:r.tagName})}).observe({type:"largest-contentful-paint",buffered:!0})}catch(e){console.debug("[Advanced Tracker] LCP not supported")}try{new PerformanceObserver(function(t){var r=t.getEntries()[0];e.performanceMetrics.fid=r.processingStart-r.startTime,e.onEvent("performance_fid",{value:e.performanceMetrics.fid,eventType:r.name})}).observe({type:"first-input",buffered:!0})}catch(e){console.debug("[Advanced Tracker] FID not supported")}try{var t=0;new PerformanceObserver(function(r){for(var n=0,i=r.getEntries();n<i.length;n++){var o=i[n];o.hadRecentInput||(t+=o.value)}e.performanceMetrics.cls=t}).observe({type:"layout-shift",buffered:!0}),document.addEventListener("visibilitychange",function(){"hidden"===document.visibilityState&&e.onEvent("performance_cls",{value:t})})}catch(e){console.debug("[Advanced Tracker] CLS not supported")}try{new PerformanceObserver(function(t){var r=t.getEntries().find(function(e){return"first-contentful-paint"===e.name});r&&(e.performanceMetrics.fcp=r.startTime,e.onEvent("performance_fcp",{value:r.startTime}))}).observe({type:"paint",buffered:!0})}catch(e){console.debug("[Advanced Tracker] FCP not supported")}}window.addEventListener("load",function(){setTimeout(function(){var t=performance.timing;e.performanceMetrics.ttfb=t.responseStart-t.navigationStart,e.performanceMetrics.domContentLoaded=t.domContentLoadedEventEnd-t.navigationStart,e.performanceMetrics.pageLoad=t.loadEventEnd-t.navigationStart;var r=performance.getEntriesByType("resource");e.performanceMetrics.resourceCount=r.length,e.performanceMetrics.transferSize=r.reduce(function(e,t){return e+(t.transferSize||0)},0),e.onEvent("performance_page_load",{ttfb:e.performanceMetrics.ttfb,domContentLoaded:e.performanceMetrics.domContentLoaded,pageLoad:e.performanceMetrics.pageLoad,resourceCount:e.performanceMetrics.resourceCount,transferSizeKB:Math.round((e.performanceMetrics.transferSize||0)/1024)})},0)})},e.prototype.initEngagementTracking=function(){var e=this;document.addEventListener("visibilitychange",function(){e.isPageVisible="visible"===document.visibilityState,e.visibilityChangeCount++,e.engagementMetrics.pageVisibilityChanges=e.visibilityChangeCount,e.isPageVisible?e.lastActivityTime=Date.now():e.updateActiveTime()}),["mousemove","keydown","touchstart","scroll"].forEach(function(t){document.addEventListener(t,function(){e.lastActivityTime=Date.now()},{passive:!0})}),document.addEventListener("click",function(){e.engagementMetrics.totalClicks++})},e.prototype.initScrollTracking=function(){var e=this,t=!1,r=function(){var r=window.scrollY||document.documentElement.scrollTop,n=Math.max(document.body.scrollHeight,document.documentElement.scrollHeight)-window.innerHeight,i=n>0?Math.round(r/n*100):0;e.engagementMetrics.scrollDepth=Math.max(e.engagementMetrics.scrollDepth,i);for(var o=0,a=e.config.scrollDepthThresholds;o<a.length;o++){var s=a[o];i>=s&&!e.scrollDepthReached.has(s)&&(e.scrollDepthReached.add(s),e.engagementMetrics.scrollDepthMilestones.push(s),e.onEvent("engagement_scroll_depth",{depth:s,maxDepth:e.engagementMetrics.scrollDepth,timeToReach:Date.now()-e.pageStartTime}))}t=!1};window.addEventListener("scroll",function(){t||(requestAnimationFrame(r),t=!0)},{passive:!0})},e.prototype.initRageClickTracking=function(){var e=this;document.addEventListener("click",function(t){var r,n=Date.now();if(e.clickHistory.push(n),e.clickHistory=e.clickHistory.filter(function(t){return n-t<e.config.rageClickWindow}),e.clickHistory.length>=e.config.rageClickThreshold){e.engagementMetrics.rageClicks++;var i=t.target;e.onEvent("engagement_rage_click",{clickCount:e.clickHistory.length,element:{tagName:i.tagName,id:i.id,className:i.className,textContent:null===(r=i.textContent)||void 0===r?void 0:r.substring(0,50)},position:{x:t.clientX,y:t.clientY},totalRageClicks:e.engagementMetrics.rageClicks}),e.clickHistory=[]}})},e.prototype.initTimeTracking=function(){var e=this;setInterval(function(){e.updateActiveTime()},3e4)},e.prototype.updateActiveTime=function(){var e=Date.now(),t=e-this.lastActivityTime;this.engagementMetrics.timeOnPage=e-this.pageStartTime,t<3e4?this.engagementMetrics.activeTime+=Math.min(t,3e4):this.engagementMetrics.idleTime+=t},e.prototype.initAPITracking=function(){var e=this;window.fetch=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return n=e,i=void 0,a=function(){var e,r,n,i,o,a,s;return function(e,t){var r,n,i,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=s(0),a.throw=s(1),a.return=s(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(s){return function(c){return function(s){if(r)throw new TypeError("Generator is already executing.");for(;a&&(a=0,s[0]&&(o=0)),o;)try{if(r=1,n&&(i=2&s[0]?n.return:s[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,s[1])).done)return i;switch(n=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,n=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((i=(i=o.trys).length>0&&i[i.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]<i[3])){o.label=s[1];break}if(6===s[0]&&o.label<i[1]){o.label=i[1],i=s;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(s);break}i[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],n=0}finally{r=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}}(this,function(c){switch(c.label){case 0:if(e=Date.now(),r=t[0]instanceof Request?t[0].url:String(t[0]),n=(null===(s=t[1])||void 0===s?void 0:s.method)||"GET",!this.shouldTrackAPI(r))return[2,this.originalFetch.apply(this,t)];c.label=1;case 1:return c.trys.push([1,3,,4]),[4,this.originalFetch.apply(this,t)];case 2:return i=c.sent(),a=Date.now()-e,this.trackAPICall({url:r,method:n,status:i.status,duration:a,success:i.ok,timestamp:Date.now()}),[2,i];case 3:throw o=c.sent(),a=Date.now()-e,this.trackAPICall({url:r,method:n,status:0,duration:a,success:!1,error:(null==o?void 0:o.message)||"Network error",timestamp:Date.now()}),o;case 4:return[2]}})},new((o=void 0)||(o=Promise))(function(e,t){function r(e){try{c(a.next(e))}catch(e){t(e)}}function s(e){try{c(a.throw(e))}catch(e){t(e)}}function c(t){var n;t.done?e(t.value):(n=t.value,n instanceof o?n:new o(function(e){e(n)})).then(r,s)}c((a=a.apply(n,i||[])).next())});var n,i,o,a},console.log("[Advanced Tracker] API tracking initialized")},e.prototype.shouldTrackAPI=function(e){return!this.config.apiTrackingPatterns||0===this.config.apiTrackingPatterns.length||this.config.apiTrackingPatterns.some(function(t){try{return new RegExp(t).test(e)}catch(r){return e.includes(t)}})},e.prototype.trackAPICall=function(e){this.onEvent("api_call",{url:e.url,method:e.method,status:e.status,duration:e.duration,success:e.success,error:e.error})},e.prototype.trackAPI=function(e,t,r,n){this.onEvent("api_response_tracked",b({endpoint:e,method:t,responseType:typeof r,responseKeys:r&&"object"==typeof r?Object.keys(r):[],hasData:!!r,dataCount:Array.isArray(r)?r.length:void 0},n))},e.prototype.trackEngagement=function(e,t){this.onEvent("engagement_".concat(e),b(b({},t),{timeOnPage:Date.now()-this.pageStartTime,scrollDepth:this.engagementMetrics.scrollDepth}))},e.prototype.trackConversion=function(e,t,r){this.onEvent("conversion",b(b({goal:e,value:t},r),{timeToConvert:Date.now()-this.pageStartTime,scrollDepthAtConversion:this.engagementMetrics.scrollDepth,clicksBeforeConversion:this.engagementMetrics.totalClicks}))},e.prototype.getPerformanceMetrics=function(){return b({},this.performanceMetrics)},e.prototype.getEngagementMetrics=function(){return this.updateActiveTime(),b(b({},this.engagementMetrics),{timeOnPage:Date.now()-this.pageStartTime})},e.prototype.trackPageExit=function(){this.updateActiveTime(),this.onEvent("page_exit",{timeOnPage:Date.now()-this.pageStartTime,activeTime:this.engagementMetrics.activeTime,idleTime:this.engagementMetrics.idleTime,scrollDepth:this.engagementMetrics.scrollDepth,scrollMilestones:this.engagementMetrics.scrollDepthMilestones,totalClicks:this.engagementMetrics.totalClicks,rageClicks:this.engagementMetrics.rageClicks,visibilityChanges:this.engagementMetrics.pageVisibilityChanges,performance:this.performanceMetrics})},e}(),S=function(){return S=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var i in t=arguments[r])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},S.apply(this,arguments)},T=function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function a(e){try{c(n.next(e))}catch(e){o(e)}}function s(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(a,s)}c((n=n.apply(e,t||[])).next())})},E=function(e,t){var r,n,i,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=s(0),a.throw=s(1),a.return=s(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(s){return function(c){return function(s){if(r)throw new TypeError("Generator is already executing.");for(;a&&(a=0,s[0]&&(o=0)),o;)try{if(r=1,n&&(i=2&s[0]?n.return:s[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,s[1])).done)return i;switch(n=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,n=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((i=(i=o.trys).length>0&&i[i.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]<i[3])){o.label=s[1];break}if(6===s[0]&&o.label<i[1]){o.label=i[1],i=s;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(s);break}i[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],n=0}finally{r=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}},_=function(e,t,r){if(r||2===arguments.length)for(var n,i=0,o=t.length;i<o;i++)!n&&i in t||(n||(n=Array.prototype.slice.call(t,0,i)),n[i]=t[i]);return e.concat(n||Array.prototype.slice.call(t))},C=function(){function e(e){if(this.eventQueue=[],this.isInitialized=!1,this.batchRetryCount=0,this.maxBatchRetries=5,this.lastDomHash="",this.lastConfigHash="",this.mutationDebounceTimer=null,this.mutationDebounceMs=2e3,this.attachedListeners=new WeakMap,this.knownElementSelectors=new Set,this.mergedConfig={events_to_track:[]},this.MAX_CACHED_CONFIGS=15,!e.projectKey&&!e.clientId&&!e.apiKey)throw new Error("[AInamika SDK] Either projectKey or clientId is required for initialization");this.config=S({endpoint:s.API_BASE_URL,batchInterval:5e3,useWebWorker:!0,debug:s.DEBUG,errorTracking:{enabled:!0,captureScreenshots:!0,captureDomSnapshots:!0,maxStackTraceDepth:50,maxErrorsPerSession:100,debounceMs:1e3,enableNetworkTracking:!0,enableConsoleCapture:!0},advancedTracking:{enabled:!0,trackPerformance:!0,trackEngagement:!0,trackScrollDepth:!0,trackRageClicks:!0,trackTimeOnPage:!0,trackAPIResponses:!1,scrollDepthThresholds:[25,50,75,90,100]}},e),this.sessionId=this.generateSessionId(),this.userIdentifier=this.getOrCreateUserIdentifier(),this.userManager=new f,this.journeyTracker=new m,this.authManager=new k(this.config.clientId||this.config.apiKey||"",this.config.endpoint,this.config.debug);var t=new Blob(["\n self.eventQueue = [];\n self.config = {\n apiUrl: '',\n batchSize: 10,\n batchInterval: 5000,\n headers: { 'Content-Type': 'application/json' }\n };\n let batchTimer = null;\n function flushQueue() {\n self.postMessage({ status: 'debug', message: '[AInamika Worker] flushQueue called', eventQueue: self.eventQueue, config: self.config });\n if (self.eventQueue.length === 0) return;\n const batch = self.eventQueue.splice(0, self.config.batchSize);\n fetch(self.config.apiUrl, {\n method: 'POST',\n headers: self.config.headers,\n body: JSON.stringify({ events: batch })\n }).then(r => {\n if (r.ok) {\n self.postMessage({ status: 'success' });\n } else {\n self.postMessage({ status: 'error', error: r.statusText, failedEvents: batch });\n }\n }).catch(e => {\n self.postMessage({ status: 'error', error: e.message, failedEvents: batch });\n });\n }\n self.onmessage = function(e) {\n self.postMessage({ status: 'debug', message: '[AInamika Worker] onmessage', data: e.data });\n if (e.data.type === 'config') {\n self.config = { ...self.config, ...e.data.payload };\n if (batchTimer) clearInterval(batchTimer);\n batchTimer = setInterval(flushQueue, self.config.batchInterval);\n self.postMessage({ status: 'debug', message: '[AInamika Worker] config set', config: self.config });\n } else if (e.data.type === 'track') {\n self.eventQueue.push(e.data.payload);\n // Only send when timer triggers, not when batch size is reached\n // This ensures true batching behavior\n } else if (e.data.type === 'batch') {\n // Handle batch flush from main thread\n self.postMessage({ status: 'debug', message: '[AInamika Worker] Received batch from main thread', events: e.data.events });\n self.eventQueue.push(...e.data.events);\n flushQueue();\n } else if (e.data.type === 'initConfig') {\n // No-op for now, can be used for advanced config\n }\n };\n "],{type:"application/javascript"}),r=URL.createObjectURL(t);this.worker=new Worker(r),this.initialize()}return e.prototype.initialize=function(){return T(this,void 0,void 0,function(){var e,t,r,n,i;return E(this,function(o){switch(o.label){case 0:if(this.isInitialized)return[2];if(this.isInitialized=!0,!this.config.projectKey)return[3,5];o.label=1;case 1:return o.trys.push([1,4,,5]),[4,this.initializeProjectSettings()];case 2:return o.sent(),[4,this.initializeSamplingDecision()];case 3:return o.sent(),this.log("Project-based initialization complete",{projectKey:this.config.projectKey,projectSettings:this.projectSettings,samplingDecision:this.samplingDecision}),[3,5];case 4:return e=o.sent(),this.log("Project initialization failed:",e),console.warn("[AInamika SDK] Failed to initialize project settings. Some features may be limited."),[3,5];case 5:if(!this.config.clientId&&!this.config.apiKey)return[3,9];o.label=6;case 6:return o.trys.push([6,8,,9]),[4,this.authManager.initialize()];case 7:return o.sent(),this.log("Authentication initialized"),[3,9];case 8:return t=o.sent(),this.log("Authentication initialization failed:",t),this.config.debug||console.warn("[Ainamika] Running without authentication. Some features may be limited."),[3,9];case 9:return(null===(r=this.config.errorTracking)||void 0===r?void 0:r.enabled)&&this.shouldSampleErrors()?this.initializeErrorTracking():(null===(n=this.config.errorTracking)||void 0===n?void 0:n.enabled)&&!this.shouldSampleErrors()&&this.log("Error tracking disabled due to sampling decision"),(null===(i=this.config.advancedTracking)||void 0===i?void 0:i.enabled)&&this.initializeAdvancedTracking(),this.config.autoConfig?[4,this.setupAutoConfiguration()]:[3,11];case 10:o.sent(),o.label=11;case 11:return this.setupDynamicDomTracking(),this.config.useWebWorker&&"undefined"!=typeof Worker?[4,this.setupWebWorker()]:[3,13];case 12:return o.sent(),[3,14];case 13:this.startBatchTimer(),o.label=14;case 14:return this.log("AnalyticsPro SDK initialized",{config:this.config,projectKey:this.config.projectKey,sampling:this.samplingDecision}),[2]}})})},e.prototype.getOrCreateUserIdentifier=function(){var e="ainamika_user_identifier",t=localStorage.getItem(e);return t||(t="anon_"+Math.random().toString(36).substr(2,16)+Date.now().toString(36),localStorage.setItem(e,t),this.log("Created new user identifier:",t)),t},e.prototype.initializeProjectSettings=function(){return T(this,void 0,void 0,function(){var e,t,r;return E(this,function(n){switch(n.label){case 0:if(!this.config.projectKey)return[2];n.label=1;case 1:return n.trys.push([1,4,,5]),[4,fetch(c.PROJECTS_LOOKUP,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({project_key:this.config.projectKey})})];case 2:if(!(e=n.sent()).ok)throw new Error("Project lookup failed: ".concat(e.status));return t=this,[4,e.json()];case 3:return t.projectSettings=n.sent(),this.log("Project settings loaded:",this.projectSettings),[3,5];case 4:throw r=n.sent(),this.log("Failed to load project settings:",r),r;case 5:return[2]}})})},e.prototype.initializeSamplingDecision=function(){return T(this,void 0,void 0,function(){var e,t,r;return E(this,function(n){switch(n.label){case 0:if(!this.config.projectKey)return[2];n.label=1;case 1:return n.trys.push([1,4,,5]),[4,fetch(c.SAMPLING_CHECK,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({project_key:this.config.projectKey,user_identifier:this.userIdentifier})})];case 2:if(!(e=n.sent()).ok)throw new Error("Sampling check failed: ".concat(e.status));return t=this,[4,e.json()];case 3:return t.samplingDecision=n.sent(),this.log("Sampling decision received:",this.samplingDecision),this.cacheSamplingDecision(),[3,5];case 4:return r=n.sent(),this.log("Failed to get sampling decision, using cached or defaults:",r),this.loadCachedSamplingDecision(),[3,5];case 5:return[2]}})})},e.prototype.cacheSamplingDecision=function(){if(this.samplingDecision){var e="ainamika_sampling_".concat(this.config.projectKey);localStorage.setItem(e,JSON.stringify(this.samplingDecision))}},e.prototype.loadCachedSamplingDecision=function(){var e="ainamika_sampling_".concat(this.config.projectKey),t=localStorage.getItem(e);if(t)try{this.samplingDecision=JSON.parse(t),this.log("Loaded cached sampling decision:",this.samplingDecision)}catch(e){this.samplingDecision={should_sample:{events:!0,errors:!0,session_replay:!1},rates:{events:100,errors:100,session_replay:0},decision:"existing"}}else this.samplingDecision={should_sample:{events:!0,errors:!0,session_replay:!1},rates:{events:100,errors:100,session_replay:0},decision:"existing"}},e.prototype.shouldSampleEvents=function(){return!this.samplingDecision||this.samplingDecision.should_sample.events},e.prototype.shouldSampleErrors=function(){return!this.samplingDecision||this.samplingDecision.should_sample.errors},e.prototype.shouldSampleSessionReplay=function(){return!!this.samplingDecision&&this.samplingDecision.should_sample.session_replay},e.prototype.getSamplingStatus=function(){return this.samplingDecision||null},e.prototype.getProjectInfo=function(){return this.projectSettings||null},e.prototype.getTrackingStatus=function(){return{totalEvents:this.mergedConfig.events_to_track.length,knownSelectors:this.knownElementSelectors.size,mergedConfig:this.mergedConfig}},e.prototype.resetDomTracking=function(){this.knownElementSelectors.clear(),this.mergedConfig={events_to_track:[]},this.lastDomHash="",this.attachedListeners=new WeakMap,this.log("DOM tracking reset - will re-analyze on next mutation")},e.prototype.clearAllCaches=function(e){void 0===e&&(e=!1);try{localStorage.removeItem("ainamika_dom_config_cache"),this.log("Cleared DOM config cache"),this.config.projectKey&&(localStorage.removeItem("ainamika_sampling_".concat(this.config.projectKey)),this.log("Cleared sampling decision cache")),e&&(localStorage.removeItem("ainamika_user_identifier"),this.log("Cleared user identifier")),this.resetDomTracking(),this.samplingDecision=void 0,this.log("All caches cleared successfully")}catch(e){console.error("[AInamika SDK] Error clearing caches:",e)}},e.prototype.getCacheStats=function(){try{var e=JSON.parse(localStorage.getItem("ainamika_dom_config_cache")||"{}"),t=Object.keys(e);return{domConfigCacheSize:t.length,cachedDomHashes:t,hasSamplingCache:!!localStorage.getItem("ainamika_sampling_".concat(this.config.projectKey)),hasUserIdentifier:!!localStorage.getItem("ainamika_user_identifier")}}catch(e){return{domConfigCacheSize:0,cachedDomHashes:[],hasSamplingCache:!1,hasUserIdentifier:!1}}},e.prototype.initializeErrorTracking=function(){var e,t,r,n,i,o,c,l,u,h,g,f,p,m;try{this.errorStorage=new d({maxStorageSize:5242880,maxRetries:5,retryInterval:3e4,compressionEnabled:!0,encryptionEnabled:!1});var v={endpoint:s.API_BASE_URL,clientId:this.config.clientId||"",apiKey:this.config.apiKey,authManager:this.authManager,projectKey:this.config.projectKey,captureScreenshots:null===(t=null===(e=this.config.errorTracking)||void 0===e?void 0:e.captureScreenshots)||void 0===t||t,captureDomSnapshots:null===(n=null===(r=this.config.errorTracking)||void 0===r?void 0:r.captureDomSnapshots)||void 0===n||n,maxStackTraceDepth:null!==(o=null===(i=this.config.errorTracking)||void 0===i?void 0:i.maxStackTraceDepth)&&void 0!==o?o:50,maxErrorsPerSession:null!==(l=null===(c=this.config.errorTracking)||void 0===c?void 0:c.maxErrorsPerSession)&&void 0!==l?l:100,debounceMs:null!==(h=null===(u=this.config.errorTracking)||void 0===u?void 0:u.debounceMs)&&void 0!==h?h:1e3,enableNetworkTracking:null===(f=null===(g=this.config.errorTracking)||void 0===g?void 0:g.enableNetworkTracking)||void 0===f||f,enableConsoleCapture:null===(m=null===(p=this.config.errorTracking)||void 0===p?void 0:p.enableConsoleCapture)||void 0===m||m};this.errorTracker=new a(v);var y=this.getUserId();y&&this.errorTracker&&this.errorTracker.setUser(y),this.log("Error tracking initialized successfully")}catch(e){console.error("[AInamika SDK] Failed to initialize error tracking:",e)}},e.prototype.captureException=function(e,t){this.errorTracker&&this.errorTracker.captureException(e,t)},e.prototype.setUser=function(e){console.warn("[AInamika SDK] setUser is deprecated. Please use identifyUser() instead."),this.identifyUser(e)},e.prototype.flushStoredErrors=function(){return T(this,void 0,void 0,function(){return E(this,function(e){switch(e.label){case 0:return this.errorStorage?[4,this.errorStorage.processQueue()]:[3,2];case 1:e.sent(),e.label=2;case 2:return this.errorTracker?[4,this.errorTracker.flushStoredErrors()]:[3,4];case 3:e.sent(),e.label=4;case 4:return[2]}})})},e.prototype.initializeAdvancedTracking=function(){var e,t,r,n,i,o,a,s,c,l,u,h,d,g,f=this;try{var p={trackPerformance:null===(t=null===(e=this.config.advancedTracking)||void 0===e?void 0:e.trackPerformance)||void 0===t||t,trackEngagement:null===(n=null===(r=this.config.advancedTracking)||void 0===r?void 0:r.trackEngagement)||void 0===n||n,trackScrollDepth:null===(o=null===(i=this.config.advancedTracking)||void 0===i?void 0:i.trackScrollDepth)||void 0===o||o,trackRageClicks:null===(s=null===(a=this.config.advancedTracking)||void 0===a?void 0:a.trackRageClicks)||void 0===s||s,trackTimeOnPage:null===(l=null===(c=this.config.advancedTracking)||void 0===c?void 0:c.trackTimeOnPage)||void 0===l||l,trackAPIResponses:null!==(h=null===(u=this.config.advancedTracking)||void 0===u?void 0:u.trackAPIResponses)&&void 0!==h&&h,scrollDepthThresholds:(null===(d=this.config.advancedTracking)||void 0===d?void 0:d.scrollDepthThresholds)||[25,50,75,90,100],apiTrackingPatterns:(null===(g=this.config.advancedTracking)||void 0===g?void 0:g.apiTrackingPatterns)||[]};this.advancedTracker=new w(p,function(e,t){f.sendToWorker(e,t)}),this.log("Advanced tracking initialized successfully")}catch(e){console.error("[AInamika SDK] Failed to initialize advanced tracking:",e)}},e.prototype.trackAPI=function(e,t,r,n){this.advancedTracker?this.advancedTracker.trackAPI(e,t,r,n):this.track("api_response_tracked",S({endpoint:e,method:t,responseType:typeof r,hasData:!!r},n))},e.prototype.trackEngagement=function(e,t){this.advancedTracker?this.advancedTracker.trackEngagement(e,t):this.track("engagement_".concat(e),t||{})},e.prototype.trackConversion=function(e,t,r){this.advancedTracker?this.advancedTracker.trackConversion(e,t,r):this.track("conversion",S({goal:e,value:t},r))},e.prototype.getPerformanceMetrics=function(){var e;return(null===(e=this.advancedTracker)||void 0===e?void 0:e.getPerformanceMetrics())||null},e.prototype.getEngagementMetrics=function(){var e;return(null===(e=this.advancedTracker)||void 0===e?void 0:e.getEngagementMetrics())||null},e.prototype.setupAutoConfiguration=function(){return T(this,void 0,void 0,function(){var e,t,r,n,i,o,a=this;return E(this,function(s){switch(s.label){case 0:return s.trys.push([0,5,,6]),this.log("Starting auto-configuration..."),[4,this.getDOMStructure()];case 1:return e=s.sent(),t=this.computeDomHash(e),this.lastDomHash=t,(e.elements||[]).forEach(function(e){e.selector&&a.knownElementSelectors.add(e.selector)}),this.log("Tracking ".concat(this.knownElementSelectors.size," initial element selectors")),r=this.getCachedConfigForDomHash(t),n=!1,r&&r.events_to_track?(this.log("Applying cached config immediately for DOM hash:",t),this.mergedConfig={events_to_track:_([],r.events_to_track,!0),tracking_config:r.tracking_config},this.applyGeneratedConfig(r),n=!0,this.config.useWebWorker&&"undefined"!=typeof Worker&&this.worker.postMessage({type:"initConfig",config:r}),this.log("Cached config applied, events ready for tracking",{eventsCount:r.events_to_track.length}),[3,4]):[3,2];case 2:return[4,this.loadConfigFromFile()];case 3:(i=s.sent())&&i.events_to_track&&(this.log("Applying config from file"),this.mergedConfig={events_to_track:_([],i.events_to_track,!0),tracking_config:i.tracking_config},this.applyGeneratedConfig(i),n=!0),s.label=4;case 4:return this.fetchAndMergeFreshConfig(e,t,n),[3,6];case 5:return o=s.sent(),this.log("Auto-configuration failed with error",o),[3,6];case 6:return[2]}})})},e.prototype.fetchAndMergeFreshConfig=function(e,t,r){return T(this,void 0,void 0,function(){var n,i,o,a,s;return E(this,function(c){switch(c.label){case 0:return c.trys.push([0,2,,3]),this.log("Fetching fresh config from backend (background)..."),[4,this.fetchGeneratedConfig(e,t)];case 1:return(n=c.sent())&&n.events_to_track?(r?(i=new Set(this.mergedConfig.events_to_track.map(function(e){return e.element_selector})),(o=n.events_to_track.filter(function(e){return!i.has(e.element_selector)})).length>0?(this.log("Found ".concat(o.length," new events from fresh config, merging...")),(s=this.mergedConfig.events_to_track).push.apply(s,o),this.applyGeneratedConfig({events_to_track:o,tracking_config:n.tracking_config})):this.log("Fresh config has no new events, cache was up-to-date"),n.tracking_config&&(this.mergedConfig.tracking_config=S(S({},this.mergedConfig.tracking_config),n.tracking_config))):(this.mergedConfig={events_to_track:_([],n.events_to_track,!0),tracking_config:n.tracking_config},this.applyGeneratedConfig(n),this.config.useWebWorker&&"undefined"!=typeof Worker&&this.worker.postMessage({type:"initConfig",config:n})),this.setCachedConfigForDomHash(t,this.mergedConfig),this.lastConfigHash=n.config_hash||"",this.log("Fresh config processed successfully",{totalEvents:this.mergedConfig.events_to_track.length,knownSelectors:this.knownElementSelectors.size}),[3,3]):(this.log("No valid config returned from API"),[2]);case 2:return a=c.sent(),this.log("Background config fetch failed:",a),[3,3];case 3:return[2]}})})},e.prototype.getDOMStructure=function(){return T(this,void 0,void 0,function(){var e,t,r,n,i,o=this;return E(this,function(a){switch(a.label){case 0:return e=function(e){if(e.id)return"#".concat(e.id);if(e.className){var t=e.className.split(" ").filter(function(e){return e.trim()}).join(".");return t?".".concat(t):e.tagName.toLowerCase()}return e.tagName.toLowerCase()},[4,new Promise(function(e){return setTimeout(e,500)})];case 1:return a.sent(),t=Array.from(document.body.querySelectorAll('\n button, a, input, select, textarea, form, img, h1, h2, h3, h4, h5, h6,\n [role=button], [role=link], [onclick], [tabindex], [data-analytics], [data-track],\n .card, .btn, .btn-primary, .btn-secondary, .card-title, .card-description, .card-price, .card-actions,\n [id*="card"], [class*="card"], [class*="btn"], [class*="price"], [class*="title"],\n div, span, p\n ')),r=t.filter(function(e){var t=window.getComputedStyle(e),r="none"!==t.display&&"hidden"!==t.visibility&&"0"!==t.opacity,n="button"===e.tagName.toLowerCase()||"a"===e.tagName.toLowerCase()||e.hasAttribute("onclick")||"button"===e.getAttribute("role")||e.classList.contains("btn")||e.classList.contains("card"),i="cardsContainer"===e.id||e.classList.contains("cards-grid")||e.classList.contains("card")||"img"===e.tagName.toLowerCase()||-1!==["h1","h2","h3"].indexOf(e.tagName.toLowerCase());return r&&(n||i)||"cardsContainer"===e.id}),n=new Set,i=r.map(function(t){var r,n,i={};Array.from(t.attributes).forEach(function(e){-1===["style","data-timestamp","data-rendered"].indexOf(e.name)&&(i[e.name]=e.value.length>25?e.value.substring(0,25):e.value)});var a=o.generateElementFingerprint(t);return{tagName:t.tagName.toLowerCase(),selector:e(t),fingerprint:a,id:t.id||"",className:t.className||"",textContent:(t.textContent||"").trim().substring(0,100),attributes:i,isInteractive:"button"===t.tagName.toLowerCase()||"a"===t.tagName.toLowerCase()||t.hasAttribute("onclick")||"button"===t.getAttribute("role")||t.classList.contains("btn"),hasChildren:t.children.length>0,childCount:t.children.length,parentTagName:(null===(r=t.parentElement)||void 0===r?void 0:r.tagName.toLowerCase())||"",index:Array.from((null===(n=t.parentElement)||void 0===n?void 0:n.children)||[]).indexOf(t)}}).filter(function(e){return!n.has(e.fingerprint)&&(n.add(e.fingerprint),!0)}),this.log("DOM structure analyzed",{elementCount:i.length,elements:i}),[2,{elements:i}]}})})},e.prototype.fetchGeneratedConfig=function(e,t){return T(this,void 0,void 0,function(){var r,n,i,o,a;return E(this,function(s){switch(s.label){case 0:return s.trys.push([0,4,,5]),e&&e.elements&&0===e.elements.length?(this.log("No elements found in DOM structure, skipping config fetch."),[2,null]):(r={"Content-Type":"application/json"},[4,this.authManager.getAuthHeaders()]);case 1:return n=s.sent(),r=S(S({},r),n),i={structure:e},t&&(i.domHash=t,i.lastConfigHash=this.lastConfigHash),[4,fetch(c.CONFIG,{method:"POST",headers:r,body:JSON.stringify(i)})];case 2:if(!(o=s.sent()).ok)throw new Error("Backend returned ".concat(o.status));return[4,o.json()];case 3:return[2,s.sent()];case 4:return a=s.sent(),this.log("Error fetching generated config:",a),[2,null];case 5:return[2]}})})},e.prototype.applyGeneratedConfig=function(e){var t=this;e.tracking_config&&this.log("Applying tracking config:",e.tracking_config),e.events_to_track.forEach(function(e){try{var r=document.querySelectorAll(e.element_selector),n=e.metadata_rules||{extract_customdata:!0,extract_text:!0};r.length>0?r.forEach(function(r){var i=t.attachedListeners.get(r);i||(i=new Set,t.attachedListeners.set(r,i)),(Array.isArray(e.event_type)?e.event_type:[e.event_type]).forEach(function(o){i.has(o)||(i.add(o),"click"===o&&(r.addEventListener("click",function(r){var i=r.target,o=t.extractElementData(i,n);t.sendToWorker(e.event_name,{selector:e.element_selector,eventType:"click",category:e.category||"uncategorized",element:o,itemName:o.itemName,section:o.section,timestamp:(new Date).toISOString()})}),t.log('Attached click listener for "'.concat(e.event_name,'" on "').concat(e.element_selector,'" (category: ').concat(e.category||"uncategorized",")"))),"view"===o&&"IntersectionObserver"in window&&(new IntersectionObserver(function(r){r.forEach(function(r){if(r.isIntersecting){var i=r.target,o=t.extractElementData(i,n);t.sendToWorker(e.event_name,{selector:e.element_selector,eventType:"view",category:e.category||"uncategorized",element:o,itemName:o.itemName,section:o.section,intersectionRatio:r.intersectionRatio,timestamp:(new Date).toISOString()})}})},{threshold:[.1,.5,1]}).observe(r),t.log('Attached IntersectionObserver for "'.concat(e.event_name,'" on "').concat(e.element_selector,'"'))),"focus"!==o&&"blur"!==o||(r.addEventListener(o,function(){var i=r,a=t.extractElementData(i,n);t.sendToWorker(e.event_name,{selector:e.element_selector,eventType:o,category:e.category||"uncategorized",element:a,timestamp:(new Date).toISOString()})}),t.log("Attached ".concat(o,' listener for "').concat(e.event_name,'" on "').concat(e.element_selector,'"'))))})}):t.log('No elements found for selector: "'.concat(e.element_selector,'"'))}catch(r){t.log('Error applying selector "'.concat(e.element_selector,'":'),r)}}),e.observe_mutations&&"MutationObserver"in window&&(new MutationObserver(function(e){e.forEach(function(e){t.sendToWorker("dom_mutation",{type:e.type,target:e.target.outerHTML,timestamp:(new Date).toISOString()})})}).observe(document.body,{childList:!0,subtree:!0}),this.log("MutationObserver attached for DOM changes"))},e.prototype.extractElementData=function(e,t){var r=e.getBoundingClientRect(),n={tagName:e.tagName.toLowerCase(),id:e.id||"",className:e.className||"",textContent:(e.textContent||"").trim().substring(0,100),position:{x:Math.round(r.x),y:Math.round(r.y),width:Math.round(r.width),height:Math.round(r.height)},href:e.href||void 0,value:e.value||void 0};if(!1!==(null==t?void 0:t.extract_customdata)){var i=function(e){var t,r={},n=e.getAttribute("customdata")||e.dataset.customdata;if(n)try{var i=JSON.parse(n);r.customdata=i,i.name&&(r.itemName=i.name),i.displayedTitle&&(r.section=i.displayedTitle),i.title&&(r.title=i.title),i.category&&(r.category=i.category),i.id&&(r.itemId=i.id)}catch(e){var o=n.match(/"name"\s*:\s*"([^"]+)"/);o&&(r.itemName=o[1]);var a=n.match(/"(?:displayedTitle|title)"\s*:\s*"([^"]+)"/);a&&(r.section=a[1])}var s=e.id;if(s){r.elementId=s;var c=s.split("_");if(c.length>=2){var l=c.slice(1).join("_");!r.itemName&&l&&(r.itemName=l)}}var u=null===(t=e.textContent)||void 0===t?void 0:t.trim();u&&u.length<100&&(r.displayText=u);for(var h=e.dataset,d=0,g=Object.entries(h);d<g.length;d++){var f=g[d],p=f[0],m=f[1];!r[p]&&m&&(r["data_".concat(p)]=m)}return r}(e);Object.keys(i).length>0&&(n.enriched=i,i.itemName&&(n.itemName=i.itemName),i.section&&(n.section=i.section),i.category&&(n.category=i.category))}return this.config.debug&&(n.attributes=Array.from(e.attributes).reduce(function(e,t){return e[t.name]=t.value.length>100?t.value.substring(0,100)+"...":t.value,e},{})),n},e.prototype.sendToWorker=function(e,t){var r;if(this.shouldSampleEvents()){var n=new Date,i=this.getCommonEventData(),o=S({event:e,properties:t,timestamp:n.getTime(),created_at:n.toISOString(),userId:this.getUserId(),sessionId:this.sessionId,project_key:this.config.projectKey||void 0,client_id:this.config.clientId||this.config.apiKey||void 0,project_id:(null===(r=this.projectSettings)||void 0===r?void 0:r.project_id)||void 0},i);this.config.useWebWorker&&"undefined"!=typeof Worker?this.worker.postMessage({type:"track",payload:o}):this.eventQueue.push(o),this.log("Event tracked:",o)}else this.log("Event skipped due to sampling:",e)},e.prototype.setupWebWorker=function(){return T(this,void 0,void 0,function(){var e,t,r,n,i,o=this;return E(this,function(a){switch(a.label){case 0:return[4,this.authManager.getAuthHeaders()];case 1:return e=a.sent(),this.worker.postMessage({type:"config",payload:{apiUrl:(null===(t=this.config.apiDetails)||void 0===t?void 0:t.apiEndPoint)||"".concat(this.config.endpoint,"/api/v1/events"),batchSize:(null===(r=this.config.workerConfig)||void 0===r?void 0:r.batchSize)||10,batchInterval:(null===(n=this.config.workerConfig)||void 0===n?void 0:n.batchInterval)||5e3,headers:S(S({"Content-Type":"application/json"},e),(null===(i=this.config.apiDetails)||void 0===i?void 0:i.headers)||{})}}),this.worker.onmessage=function(e){var t;"success"===e.data.status?o.log("Batch sent successfully by worker"):"debug"===e.data.status?o.log(e.data.message,e.data):"error"===e.data.status&&(o.log("Worker failed to send batch",e.data.error),e.data.failedEvents&&e.data.failedEvents.length>0&&(t=o.eventQueue).unshift.apply(t,e.data.failedEvents))},this.log("Web worker setup complete."),[2]}})})},e.prototype.track=function(e,t){var r;if(void 0===t&&(t={}),this.shouldSampleEvents()){this.journeyTracker.trackEvent(e,t);var n=this.journeyTracker.getContext(),i=new Date,o=this.getCommonEventData(),a=S({event:e,properties:S(S({},t),{journeyContext:{sequenceIndex:n.eventCount-1,timeSinceLastEvent:n.timeSinceLastEvent,journeyDuration:Date.now()-n.journeyStartTime}}),timestamp:i.getTime(),created_at:i.toISOString(),userId:this.userManager.getUserId(),userType:this.userManager.getUserType(),sessionId:this.sessionId,project_key:this.config.projectKey||void 0,client_id:this.config.clientId||this.config.apiKey||void 0,project_id:(null===(r=this.projectSettings)||void 0===r?void 0:r.project_id)||void 0},o);this.journeyTracker.shouldAnalyzeJourney()&&this.sendJourneyForAnalysis(),this.config.useWebWorker&&"undefined"!=typeof Worker?this.worker.postMessage({type:"track",payload:a}):this.eventQueue.push(a),this.log("Event tracked public:",a)}else this.log("Event skipped due to sampling:",e)},e.prototype.startBatchTimer=function(){var e=this;this.batchTimer=window.setInterval(function(){e.flushQueue()},this.config.batchInterval)},e.prototype.flushQueue=function(){return T(this,void 0,void 0,function(){var e;return E(this,function(t){switch(t.label){case 0:return 0===this.eventQueue.length?[2]:(e=_([],this.eventQueue,!0),this.eventQueue=[],this.config.useWebWorker&&"undefined"!=typeof Worker?(this.worker.postMessage({type:"batch",events:e,endpoint:"".concat(this.config.endpoint,"/api/v1/events")}),[3,3]):[3,1]);case 1:return[4,this.sendBatchWithRetry(e)];case 2:t.sent(),t.label=3;case 3:return[2]}})})},e.prototype.sendBatchWithRetry=function(e){return T(this,void 0,void 0,function(){var t,r;return E(this,function(n){switch(n.label){case 0:if(this.batchRetryCount>=this.maxBatchRetries)return this.batchTimer&&(clearInterval(this.batchTimer),this.batchTimer=void 0,this.log("Max batch retries reached. BatchTimer cancelled.")),[2];n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this.sendBatch(e)];case 2:return n.sent(),this.batchRetryCount=0,[3,4];case 3:return t=n.sent(),this.batchRetryCount++,this.log("Batch send failed. Retry attempt ".concat(this.batchRetryCount," of ").concat(this.maxBatchRetries,"."),t),(r=this.eventQueue).unshift.apply(r,e),this.batchRetryCount>=this.maxBatchRetries&&this.batchTimer&&(clearInterval(this.batchTimer),this.batchTimer=void 0,this.log("Max batch retries reached. BatchTimer cancelled.")),[3,4];case 4:return[2]}})})},e.prototype.sendBatch=function(e){return T(this,void 0,void 0,function(){var t,r,n,i,o,a,s;return E(this,function(c){switch(c.label){case 0:return t="".concat(this.config.endpoint,"/api/v1/events"),r={"Content-Type":"application/json"},[4,this.authManager.getAuthHeaders()];case 1:n=c.sent(),r=S(S({},r),n),this.config.apiDetails&&this.config.apiDetails.apiEndPoint&&(t=this.config.apiDetails.apiEndPoint,this.config.apiDetails.headers&&(r=S(S({},r),this.config.apiDetails.headers))),i=this.config.clientId||"5288aa7d-1b7c-481e-958d-eb9b8e951f14",o=e.map(function(e){return S({event:e.event,userId:e.userId,client_id:i,timestamp:new Date(e.timestamp).toISOString()},e.properties||{})}),c.label=2;case 2:return c.trys.push([2,4,,5]),[4,fetch(t,{method:"POST",headers:r,body:JSON.stringify({events:o})})];case 3:if(!(a=c.sent()).ok)throw new Error("Failed to send batch: ".concat(a.status));return this.log("Batch sent successfully:",o),[3,5];case 4:throw s=c.sent(),this.log("Error sending batch:",s),s;case 5:return[2]}})})},e.prototype.generateSessionId=function(){return"sess_"+Math.random().toString(36).substr(2,9)},e.prototype.getPageContext=function(){var e=window.location.href,t=window.location.pathname,r=window.location.hash,n=document.referrer,i={};return new URLSearchParams(window.location.search).forEach(function(e,t){i[t]=e}),{url:e,path:t,hash:r||void 0,referrer:n||void 0,queryParams:Object.keys(i).length>0?i:void 0,title:document.title||void 0}},e.prototype.getCommonEventData=function(){return S({pageContext:this.getPageContext()},this.config.extraConfig?{extraConfig:this.config.extraConfig}:{})},e.prototype.getUserId=function(){return this.userManager.getUserId()},e.prototype.identifyUser=function(e,t){var r=this.userManager.getUserIdentificationEvent(e);this.userManager.identifyUser(e,t),this.track("user_identified",r),this.errorTracker&&this.errorTracker.setUser(e),this.log("User identified:",{userId:e,properties:t})},e.prototype.setExtraConfig=function(e,t){void 0===t&&(t=!0),t&&this.config.extraConfig?this.config.extraConfig=S(S({},this.config.extraConfig),e):this.config.extraConfig=e,this.log("Extra config updated:",this.config.extraConfig)},e.prototype.getExtraConfig=function(){return this.config.extraConfig},e.prototype.isAuthenticated=function(){return T(this,void 0,void 0,function(){return E(this,function(e){switch(e.label){case 0:return[4,this.authManager.getAccessToken()];case 1:return[2,null!==e.sent()]}})})},e.prototype.authenticate=function(){return T(this,void 0,void 0,function(){return E(this,function(e){switch(e.label){case 0:return[4,this.authManager.initialize()];case 1:return[2,e.sent()]}})})},e.prototype.logout=function(){return T(this,void 0,void 0,function(){return E(this,function(e){switch(e.label){case 0:return[4,this.authManager.logout()];case 1:return e.sent(),[2]}})})},e.prototype.sendJourneyForAnalysis=function(){return T(this,void 0,void 0,function(){var e,t,r,n,i;return E(this,function(o){switch(o.label){case 0:return o.trys.push([0,3,,4]),e=this.journeyTracker.getJourneyForAnalysis(),t="".concat(this.config.endpoint,"/api/v1/journeys/analyze"),[4,this.authManager.getAuthHeaders()];case 1:return r=o.sent(),[4,fetch(t,{method:"POST",headers:S({"Content-Type":"application/json"},r),body:JSON.stringify({client_id:this.config.clientId,user_id:this.userManager.getUserId(),session_id:this.sessionId,journey:e})})];case 2:return(n=o.sent()).ok||console.error("[AInamika SDK] Failed to send journey for analysis:",n.statusText),[3,4];case 3:return i=o.sent(),console.error("[AInamika SDK] Error sending journey for analysis:",i),[3,4];case 4:return[2]}})})},e.prototype.log=function(e,t){this.config.debug&&console.log("[AnalyticsPro SDK] ".concat(e),t||"")},e.prototype.loadConfigFromFile=function(){return T(this,void 0,void 0,function(){var e;return E(this,function(t){switch(t.label){case 0:return t.trys.push([0,3,,4]),[4,fetch("/AInamika_config.json",{cache:"reload"})];case 1:return(e=t.sent()).ok?[4,e.json()]:[2,null];case 2:return[2,t.sent()];case 3:return t.sent(),[2,null];case 4:return[2]}})})},e.prototype.setupDynamicDomTracking=function(){return T(this,void 0,void 0,function(){var e=this;return E(this,function(t){return"MutationObserver"in window&&(new MutationObserver(function(){e.mutationDebounceTimer&&clearTimeout(e.mutationDebounceTimer),e.mutationDebounceTimer=window.setTimeout(function(){e.handleDomMutation()},e.mutationDebounceMs)}).observe(document.body,{childList:!0,subtree:!0,attributes:!0}),this.log("Dynamic DOM MutationObserver attached")),[2]})})},e.prototype.computeDomHash=function(e){for(var t=JSON.stringify(e),r=2166136261,n=0;n<t.length;n++)r^=t.charCodeAt(n),r+=(r<<1)+(r<<4)+(r<<7)+(r<<8)+(r<<24);return(r>>>0).toString(16)},e.prototype.generateElementFingerprint=function(e){var t=[],r=e.getAttribute("data-testid"),n=e.getAttribute("data-track"),i=e.getAttribute("data-analytics");r&&t.push("testid:".concat(r)),n&&t.push("track:".concat(n)),i&&t.push("analytics:".concat(i));var o=e.id;o&&!o.match(/^(jsc|css|ember|react|ng)-|^\d+$|^[a-f0-9]{8,}$/i)&&t.push("id:".concat(o));var a=e.getAttribute("name");a&&t.push("name:".concat(a));var s=e.getAttribute("aria-label");s&&t.push("aria:".concat(s.substring(0,50)));var c=e.tagName.toLowerCase(),l=e.getAttribute("role"),u=e.getAttribute("type");if(t.push("tag:".concat(c)),l&&t.push("role:".concat(l)),u&&t.push("type:".concat(u)),["button","a","span","div"].includes(c)){var h=(e.textContent||"").trim().substring(0,30).toLowerCase().replace(/\s+/g,"_");h&&t.push("text:".concat(h))}var d=e.getAttribute("customdata");if(d)try{var g=JSON.parse(d);g.name&&t.push("customname:".concat(g.name)),g.id&&t.push("customid:".concat(g.id))}catch(e){t.push("customdata:".concat(d.substring(0,30)))}var f=e.closest('[data-testid], [id]:not([id^="jsc-"]):not([id^="css-"])');if(f&&f!==e){var p=f.getAttribute("data-testid")||f.id;p&&t.push("parent:".concat(p))}if(e.className&&"string"==typeof e.className){var m=e.className.split(" ").filter(function(e){return e.trim()&&!e.match(/^(jsc|css|ember|react|ng|active|hover|focus|selected|open|closed)-|^[a-f0-9]{6,}$/i)}).slice(0,3).join(".");m&&t.push("class:".concat(m))}var v=t.join("|");return this.hashString(v)},e.prototype.hashString=function(e){for(var t=0,r=0;r<e.length;r++)t=(t<<5)-t+e.charCodeAt(r),t&=t;return Math.abs(t).toString(16).padStart(8,"0").substring(0,16)},e.prototype.getCachedConfigForDomHash=function(e){try{var t=JSON.parse(localStorage.getItem("ainamika_dom_config_cache")||"{}"),r=t[e];return r?r.events_to_track?(t[e]={config:r,lastAccessed:Date.now(),createdAt:Date.now()},localStorage.setItem("ainamika_dom_config_cache",JSON.stringify(t)),r):(r.lastAccessed=Date.now(),localStorage.setItem("ainamika_dom_config_cache",JSON.stringify(t)),r.config):null}catch(e){return null}},e.prototype.setCachedConfigForDomHash=function(e,t){var r=this;try{var n=JSON.parse(localStorage.getItem("ainamika_dom_config_cache")||"{}");n[e]={config:t,lastAccessed:Date.now(),createdAt:Date.now()};var i=Object.keys(n);i.length>this.MAX_CACHED_CONFIGS&&i.sort(function(e,t){return(n[e].lastAccessed||n[e].createdAt||0)-(n[t].lastAccessed||n[t].createdAt||0)}).slice(0,i.length-this.MAX_CACHED_CONFIGS).forEach(function(e){delete n[e],r.log("Evicted old config cache: ".concat(e))}),localStorage.setItem("ainamika_dom_config_cache",JSON.stringify(n))}catch(e){this.log("Cache storage error, clearing old entries:",e),this.clearOldConfigCache()}},e.prototype.clearOldConfigCache=function(){try{var e=JSON.parse(localStorage.getItem("ainamika_dom_config_cache")||"{}"),t=Object.keys(e);if(0===t.length)return;var r=t.sort(function(t,r){var n=e[t].lastAccessed||e[t].createdAt||0;return(e[r].lastAccessed||e[r].createdAt||0)-n}),n={};r.slice(0,5).forEach(function(t){n[t]=e[t]}),localStorage.setItem("ainamika_dom_config_cache",JSON.stringify(n)),this.log("Cleared config cache, kept ".concat(Object.keys(n).length," entries"))}catch(e){localStorage.removeItem("ainamika_dom_config_cache")}},e.prototype.handleDomMutation=function(){return T(this,void 0,void 0,function(){var e,t,r,n,i,o,a,s=this;return E(this,function(c){switch(c.label){case 0:return[4,this.getDOMStructure()];case 1:return e=c.sent(),(t=this.computeDomHash(e))===this.lastDomHash?(this.log("DOM hash unchanged after mutation, skipping config fetch."),[2]):(this.log("DOM hash changed, detecting new elements...",{oldHash:this.lastDomHash,newHash:t}),this.lastDomHash=t,r=e.elements||[],0===(n=r.filter(function(e){var t=e.selector||"";return!(!t||s.knownElementSelectors.has(t))})).length?(this.log("No new elements detected, skipping config fetch."),[2]):(this.log("Found ".concat(n.length," new elements out of ").concat(r.length," total")),(i=this.getCachedConfigForDomHash(t))?(this.log("Reusing cached config for DOM hash",t),this.mergeAndApplyConfig(i),r.forEach(function(e){e.selector&&s.knownElementSelectors.add(e.selector)}),[2]):(o={elements:n},this.log("Fetching config for new elements only:",n.length),[4,this.fetchGeneratedConfig(o,t)])));case 2:return(a=c.sent())&&a.events_to_track?(this.mergeAndApplyConfig(a),this.setCachedConfigForDomHash(t,this.mergedConfig),this.lastConfigHash=a.config_hash||"",n.forEach(function(e){e.selector&&s.knownElementSelectors.add(e.selector)}),this.log("Fetched and merged config for new elements",{newEvents:a.events_to_track.length,totalEvents:this.mergedConfig.events_to_track.length})):this.log("No valid config returned for new elements"),[2]}})})},e.prototype.mergeAndApplyConfig=function(e){var t;if(e&&e.events_to_track){var r=new Set(this.mergedConfig.events_to_track.map(function(e){return e.element_selector})),n=e.events_to_track.filter(function(e){return!r.has(e.element_selector)});n.length>0&&((t=this.mergedConfig.events_to_track).push.apply(t,n),this.log("Merged ".concat(n.length," new events, total: ").concat(this.mergedConfig.events_to_track.length))),e.tracking_config&&(this.mergedConfig.tracking_config=S(S({},this.mergedConfig.tracking_config),e.tracking_config)),n.length>0&&this.applyGeneratedConfig({events_to_track:n,tracking_config:e.tracking_config})}},e}();"undefined"!=typeof window&&(window.AInamikaSDKPro=C);var I=C;return t.default}()});
2
2
  //# sourceMappingURL=ainamika-sdk.js.map