@sensorswave/js-sdk 1.1.8 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -56,6 +56,8 @@ SensorsWave.trackEvent('ButtonClick', {
56
56
  | crossSubdomainCookie | boolean | true | Whether to share cookies across subdomains |
57
57
  | enableAB | boolean | false | Whether to enable A/B testing feature |
58
58
  | abRefreshInterval | number | 600000 (10 minutes) | The interval in milliseconds for refreshing A/B test configuration |
59
+ | enableErrorTrack | boolean | false | Whether to automatically capture error-level exceptions (`$Exception`): uncaught JS errors, unhandled promise rejections and resource load failures. Independent of `autoCapture`. Effective in web environment |
60
+ | enableCrashTrack | boolean | false | Whether to enable app crash tracking (fatal level). Only effective in app host environments (iOS/Android/HarmonyOS WebView); NOT effective in this pure web SDK (the option is reserved to keep one unified config spec across SDKs) |
59
61
  | batchSend | boolean | false | Whether to use batch sending (sends events in batches up to 10 events every 5 seconds) |
60
62
  | anonId | string | '' | User-provided anonymous ID. When set, it overrides the SDK-generated anonymous ID and persists locally (cookie), so it is reused on subsequent visits even if not passed again |
61
63
 
@@ -114,6 +116,25 @@ SensorsWave.track({
114
116
  });
115
117
  ```
116
118
 
119
+ #### trackException
120
+
121
+ Manually report a caught exception as an `$Exception` event (level is fixed to `error`).
122
+
123
+ This method is NOT gated by `enableErrorTrack` / `enableCrashTrack`; it only respects the consent guard (SDK initialized and not opted out). The stack is normalized and truncated the same way as automatically captured exceptions.
124
+
125
+ **Parameters:**
126
+ - `error` (Error | string, required): The caught error (an `Error` instance or a string)
127
+ - `properties` (Object, optional): Additional properties to attach. Cannot override the reserved `$exception_*` properties
128
+
129
+ **Example:**
130
+ ```javascript
131
+ try {
132
+ doSomethingRisky();
133
+ } catch (err) {
134
+ SensorsWave.trackException(err, { order_id: '123' });
135
+ }
136
+ ```
137
+
117
138
  ### User Profile
118
139
 
119
140
  #### profileSet
@@ -433,6 +454,56 @@ async function initFeatureConfig() {
433
454
  }
434
455
  ```
435
456
 
457
+ ## Error Tracking
458
+
459
+ The SDK reports exceptions as `$Exception` events. Exceptions come from two paths:
460
+
461
+ 1. **Automatic capture** — enable it with `enableErrorTrack: true` in `init()`. The SDK installs global listeners (capture-phase `error` + `unhandledrejection`) and captures:
462
+ - Uncaught JS errors (with or without an `Error` object, including cross-origin `"Script error."`)
463
+ - Unhandled promise rejections
464
+ - Resource load failures (`<script>`, `<img>`, `<link>`, etc.)
465
+ 2. **Manual reporting** — call `trackException(error, properties?)` anywhere you already catch an error (see [trackException](#trackexception)). This is NOT gated by `enableErrorTrack` / `enableCrashTrack`.
466
+
467
+ ### `$Exception` Event Properties
468
+
469
+ Every `$Exception` event carries the following reserved `$exception_*` properties:
470
+
471
+ | Property | Type | Description |
472
+ |----------|------|-------------|
473
+ | $exception_level | string | Severity level. Always `error` in this SDK (the `fatal` crash level only exists in app-host SDKs) |
474
+ | $exception_type | string | Exception type. For an `Error` object: its `name` (e.g. `TypeError`, `RangeError`), falling back to the type inferred from the stack header, then `Error`. Special values: `UnhandledRejection` (non-`Error` promise rejection reason) and `ResourceLoadError` (resource load failure). Capped at 200 chars |
475
+ | $exception_message | string | Exception message: `error.message` for `Error` objects, the raw message for string-form errors, a stringified reason for rejections (JSON for objects), or `Failed to load <tag> from <url>` for resource failures. Capped at 1000 chars |
476
+ | $exception_frames | `ExceptionFrame[]` | Structured stack frames derived from parsing `error.stack` (see below). This is the input for server-side symbolication (sourcemap) and aggregation. Empty array `[]` when there is no stack source (resource load failures, non-`Error` rejections, string-form reports) |
477
+
478
+ Custom properties passed to `trackException()` are attached alongside these, but cannot override the reserved `$exception_*` properties.
479
+
480
+ ### Stack Parsing
481
+
482
+ Stacks are parsed (V8/Gecko formats) before reporting:
483
+
484
+ - At most 30 frames are kept
485
+ - The page origin prefix, query string and hash are stripped from each frame's path (same-origin scripts become relative paths)
486
+ - Consecutive repeated frames are kept individually rather than collapsed
487
+ - Parsed frames are reported as the structured `$exception_frames` array (see below)
488
+
489
+ ### Structured Frames (`$exception_frames`)
490
+
491
+ Each event carries the parsed stack as a structured frame array for server-side symbolication and aggregation. Field semantics follow PostHog's `StackFrame`:
492
+
493
+ | Field | Type | Description |
494
+ |-------|------|-------------|
495
+ | platform | string | Always `web:javascript` in this SDK |
496
+ | filename | string | Cleaned path (page-origin prefix, query string and hash stripped) — the symbolication and aggregation key |
497
+ | function | string | Original function name (minified in compressed builds); `?` for anonymous frames |
498
+ | lineno / colno | number | Line and column as numbers. Note V8 columns are 1-based — subtract 1 when indexing a sourcemap |
499
+ | abs_path | string | The original URL before cleaning (query/hash version hints preserved), capped at 1000 chars — `filename` cleaning is irreversible, this recovers the loss |
500
+ | module | string | Fully-qualified class name, only written by Java hosts — never set by this SDK |
501
+
502
+ Notes:
503
+
504
+ - No collapsing or char-length truncation — the 30-frame parse limit bounds the payload, each frame is kept individually
505
+ - Synthetic frames (no `Error` object, e.g. cross-origin `"Script error."` built from `filename:lineno:colno`) are also emitted as a single-element array
506
+
436
507
  ## Supported Event Types
437
508
 
438
509
  The SDK automatically captures the following event types when `autoCapture` is enabled:
@@ -442,6 +513,10 @@ The SDK automatically captures the following event types when `autoCapture` is e
442
513
  - **PageLeave**: Triggered when a user is about to leave a page
443
514
  - **WebClick**: Triggered on element clicks (only when `enableClickTrack` is true)
444
515
 
516
+ Additional automatic events:
517
+
518
+ - **Exception** (`$Exception`): Triggered when an error-level exception is captured — uncaught JS errors, unhandled promise rejections, and resource load failures (only when `enableErrorTrack` is true), or reported manually via `trackException()`
519
+
445
520
  Custom events can be tracked using the `trackEvent()` or `track()` methods.
446
521
 
447
522
  ## License
package/dist/index.cjs.js CHANGED
@@ -1 +1 @@
1
- "use strict";class e{constructor(){this.listeners={}}on(e,t,n=!1){if(e&&t){if(!s(t))throw new Error("listener must be a function");this.listeners[e]=this.listeners[e]||[],this.listeners[e].push({listener:t,once:n})}}off(e,t){const n=this.listeners[e];if(!n?.length)return;"number"==typeof t&&n.splice(t,1);const i=n.findIndex(e=>e.listener===t);-1!==i&&n.splice(i,1)}emit(e,...t){this.listeners[e]&&this.listeners[e].forEach((n,i)=>{n.listener.call(this,...t),n.listener.once&&this.off(e,i)})}once(e,t){this.on(e,t,!0)}removeAllListeners(e){e?this.listeners[e]=[]:this.listeners={}}}const t={get:function(e){const t=e+"=",n=document.cookie.split(";");for(let i=0,s=n.length;i<s;i++){let e=n[i];for(;" "==e.charAt(0);)e=e.substring(1,e.length);if(0==e.indexOf(t))return h(e.substring(t.length,e.length))}return null},set:function({name:e,value:t,expires:n,samesite:i,secure:s,domain:r}){let o="",a="",c="",l="";if(0!==(n=null==n||void 0===n?365:n)){const e=new Date;"s"===String(n).slice(-1)?e.setTime(e.getTime()+1e3*Number(String(n).slice(0,-1))):e.setTime(e.getTime()+24*n*60*60*1e3),o="; expires="+e.toUTCString()}function u(e){return e?e.replace(/\r\n/g,""):""}i&&(c="; SameSite="+i),s&&(a="; secure");const h=u(e),d=u(t),g=u(r);g&&(l="; domain="+g),h&&d&&(document.cookie=h+"="+encodeURIComponent(d)+o+"; path=/"+l+c+a)},remove:function(e){this.set({name:e,value:"",expires:-1})},isSupport:function({samesite:e,secure:t}={}){if(!navigator.cookieEnabled)return!1;const n="sensorswave_cookie_support_test";return this.set({name:n,value:"1",samesite:e,secure:t}),"1"===this.get(n)&&(this.remove(n),!0)}},n=Object.prototype.toString;function i(e){return"[object Object]"===n.call(e)}function s(e){const t=n.call(e);return"[object Function]"==t||"[object AsyncFunction]"==t}function r(e){return"[object Array]"==n.call(e)}function o(e){return"[object String]"==n.call(e)}function a(e){return void 0===e}const c=Object.prototype.hasOwnProperty;function l(e){if(i(e)){for(let t in e)if(c.call(e,t))return!1;return!0}return!1}function u(e){return!(!e||1!==e.nodeType)}function h(e){let t=e;try{t=decodeURIComponent(e)}catch(n){t=e}return t}function d(e){try{return JSON.parse(e)}catch(t){return""}}const g=function(){let e=Date.now();return function(t){return Math.ceil((e=(9301*e+49297)%233280,e/233280*t))}}();function p(){if("function"==typeof Uint32Array){let e;if("undefined"!=typeof crypto&&(e=crypto),e&&i(e)&&e.getRandomValues)return e.getRandomValues(new Uint32Array(1))[0]/Math.pow(2,32)}return g(1e19)/1e19}const f=function(){function e(e){return("0".repeat(e)+Date.now().toString(16)).slice(-e)}return function(){let t=String(screen.height*screen.width);t=t&&/\d{4,}/.test(t)?t.slice(-4):String(31242*p()).replace(".","").slice(0,4);return e(8)+"-"+p().toString(16).replace(".","").slice(-4)+"-"+function(){const e=navigator.userAgent;let t,n=[],i=0;function s(e,t){let i=0;for(let s=0;s<t.length;s++)i|=n[s]<<8*s;return(e^i)>>>0}for(let r=0;r<e.length;r++)t=e.charCodeAt(r),n.unshift(255&t),n.length>=4&&(i=s(i,n),n=[]);return n.length>0&&(i=s(i,n)),("0000"+i.toString(16)).slice(-4)}()+"-"+t+"-"+e(12)||(String(p())+String(p())+String(p())).slice(2,15)}}();function m(e,t){t&&"string"==typeof t||(t="");let n=null;try{n=new URL(e).hostname}catch(i){}return n||t}function E(e){let t=[];try{t=atob(e).split("").map(function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)})}catch(n){t=[]}try{return decodeURIComponent(t.join(""))}catch(n){return t.join("")}}function I(e){let t="";try{t=btoa(encodeURIComponent(e).replace(/%([0-9A-F]{2})/g,function(e,t){return String.fromCharCode(parseInt(t,16))}))}catch(n){t=e}return t}const S={get:function(e){return window.localStorage.getItem(e)},parse:function(e){let t;try{t=JSON.parse(S.get(e))||null}catch(n){console.warn(n)}return t},set:function(e,t){try{window.localStorage.setItem(e,t)}catch(n){console.warn(n)}},remove:function(e){window.localStorage.removeItem(e)},isSupport:function(){let e=!0;try{const t="__local_store_support__",n="testIsSupportStorage";S.set(t,n),S.get(t)!==n&&(e=!1),S.remove(t)}catch(t){e=!1}return e}};function w(e){return e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")}function _(e){if(!e||"string"!=typeof e)return"";try{return new URL(e,window.location.origin).pathname}catch(t){return""}}const O={},A="1.1.8",v="init-ready",R="spa-switch",T="ff-ready",b="$PageLeave";var y=(e=>(e[e.FEATURE_GATE=1]="FEATURE_GATE",e[e.FEATURE_CONFIG=2]="FEATURE_CONFIG",e[e.EXPERIMENT=3]="EXPERIMENT",e))(y||{});const N={crossSubdomain:!1,requests:[],_sessionState:{},_abData:[],_trace_id:"",commonProps:{},_state:{anon_id:"",login_id:"",identities:{}},getIdentityCookieID(){return this._state.identities?.$identity_cookie_id||""},getCommonProps:function(){return this.commonProps||{}},setCommonProps:function(e){this.commonProps=e},getAnonId(){return this._state.anon_id||this.getIdentityCookieID()||f()},getLoginId(){return this._state.login_id},getTraceId(){return this._trace_id||f()},set:function(e,t){this._state[e]=t,this.save()},getCookieName:function(){return"sensorswave2025jssdkcross"},getABLSName:function(){return"sensorswave2025jssdkablatest"},save:function(){let e=JSON.parse(JSON.stringify(this._state));e.identities&&(e.identities=I(JSON.stringify(e.identities)));const n=JSON.stringify(e);t.set({name:this.getCookieName(),value:n,expires:365})},init:function(e){let n,s;this.crossSubdomain=e,t.isSupport()&&(n=t.get(this.getCookieName()),s=d(n)),N._state={...s||{}},N._state.identities&&(N._state.identities=d(E(N._state.identities))),N._state.identities&&i(N._state.identities)&&!l(N._state.identities)||(N._state.identities={$identity_cookie_id:f()}),N.save()},setLoginId(e){"number"==typeof e&&(e=String(e)),void 0!==e&&e&&(N.set("login_id",e),N.save())},setAnonId(e){"number"==typeof e&&(e=String(e)),"string"==typeof e&&e?(N.set("anon_id",e),N.save()):console.warn("[SensorsWave store] Invalid anonId, ignored:",e)},saveABData(e){if(!e||l(e))return;this._abData=e;let t=JSON.parse(JSON.stringify(this._abData));t=I(JSON.stringify(t));try{localStorage.setItem(this.getABLSName(),JSON.stringify({time:Date.now(),data:t,anon_id:this.getAnonId(),login_id:this.getLoginId()}))}catch(n){console.warn("Failed to save abdata to localStorage",n)}},getABData(e=6e5){try{let t=localStorage.getItem(this.getABLSName());if(t){const{time:n,data:i,login_id:s,anon_id:r}=d(t)||{};if(n&&i&&Date.now()-n<e&&r===this.getAnonId()&&(!s||s===this.getLoginId())){const e=d(E(i));return this._abData=Array.isArray(e)?e:[],this._abData}localStorage.removeItem(this.getABLSName())}}catch(t){console.warn("Failed to load abdata from localStorage",t),this._abData=[]}return this._abData||[]}};function P(e){var t;if(e.data)return{contentType:"application/json",body:(t=e.data,JSON.stringify(t,(e,t)=>"bigint"==typeof t?t.toString():t,undefined))}}const C=[];function L(e){const t={...e};t.timeout=t.timeout||6e4;const n=t.transport??"fetch",i=C.find(e=>e.transport===n)?.method??C[0]?.method;if(!i)throw new Error("No available transport method for HTTP request");i(t)}function B(e){return o(e=e||document.referrer)&&(e=h(e=e.trim()))||""}function F(e){const t=m(e=e||B());if(!t)return"";const n={baidu:[/^.*\.baidu\.com$/],bing:[/^.*\.bing\.com$/],google:[/^www\.google\.com$/,/^www\.google\.com\.[a-z]{2}$/,/^www\.google\.[a-z]{2}$/],sm:[/^m\.sm\.cn$/],so:[/^.+\.so\.com$/],sogou:[/^.*\.sogou\.com$/],yahoo:[/^.*\.yahoo\.com$/],duckduckgo:[/^.*\.duckduckgo\.com$/]};for(let i of Object.keys(n)){let e=n[i];for(let n=0,s=e.length;n<s;n++)if(e[n].test(t))return i}return""}function M(e,t){return-1!==e.indexOf(t)}"function"==typeof fetch&&C.push({transport:"fetch",method:function(e){if("undefined"==typeof fetch)return void console.error("fetch API is not available");const t=P(e),n=new Headers;e.headers&&Object.keys(e.headers).forEach(t=>{n.append(t,e.headers[t])}),t?.contentType&&n.append("Content-Type",t.contentType),fetch(e.url,{method:e.method||"GET",headers:n,body:t?.body}).then(t=>t.text().then(n=>{const i={statusCode:t.status,text:n};if(200===t.status)try{i.json=JSON.parse(n)}catch(s){console.error("Failed to parse response:",s)}e.callback?.(i)})).catch(t=>{console.error("Request failed:",t),e.callback?.({statusCode:0,text:String(t)})})}}),"undefined"!=typeof XMLHttpRequest&&C.push({transport:"XHR",method:function(e){if("undefined"==typeof XMLHttpRequest)return void console.error("XMLHttpRequest is not available");const t=new XMLHttpRequest;t.open(e.method||"GET",e.url,!0);const n=P(e);e.headers&&Object.keys(e.headers).forEach(n=>{t.setRequestHeader(n,e.headers[n])}),n?.contentType&&t.setRequestHeader("Content-Type",n.contentType),t.timeout=e.timeout||6e4,t.withCredentials=!0,t.onreadystatechange=()=>{if(4===t.readyState){const i={statusCode:t.status,text:t.responseText};if(200===t.status)try{i.json=JSON.parse(t.responseText)}catch(n){console.error("Failed to parse JSON response:",n)}e.callback?.(i)}},t.send(n?.body)}});const $={FACEBOOK:"Facebook",MOBILE:"Mobile",IOS:"iOS",ANDROID:"Android",TABLET:"Tablet",ANDROID_TABLET:"Android Tablet",IPAD:"iPad",APPLE:"Apple",APPLE_WATCH:"Apple Watch",SAFARI:"Safari",BLACKBERRY:"BlackBerry",SAMSUNG_BROWSER:"SamsungBrowser",SAMSUNG_INTERNET:"Samsung Internet",CHROME:"Chrome",CHROME_OS:"Chrome OS",CHROME_IOS:"Chrome iOS",INTERNET_EXPLORER:"Internet Explorer",INTERNET_EXPLORER_MOBILE:"Internet Explorer Mobile",OPERA:"Opera",OPERA_MINI:"Opera Mini",EDGE:"Edge",MICROSOFT_EDGE:"Microsoft Edge",FIREFOX:"Firefox",FIREFOX_IOS:"Firefox iOS",NINTENDO:"Nintendo",PLAYSTATION:"PlayStation",XBOX:"Xbox",ANDROID_MOBILE:"Android Mobile",MOBILE_SAFARI:"Mobile Safari",WINDOWS:"Windows",WINDOWS_PHONE:"Windows Phone",NOKIA:"Nokia",OUYA:"Ouya",GENERIC_MOBILE:"Generic mobile",GENERIC_TABLET:"Generic tablet",KONQUEROR:"Konqueror",UC_BROWSER:"UC Browser",HUAWEI:"Huawei",XIAOMI:"Xiaomi",OPPO:"OPPO",VIVO:"vivo"},k="(\\d+(\\.\\d+)?)",D=new RegExp("Version/"+k),x=new RegExp($.XBOX,"i"),H=new RegExp($.PLAYSTATION+" \\w+","i"),U=new RegExp($.NINTENDO+" \\w+","i"),X=new RegExp($.BLACKBERRY+"|PlayBook|BB10","i"),q=new RegExp("(HUAWEI|honor|HONOR)","i"),W=new RegExp("(Xiaomi|Redmi)","i"),G=new RegExp("(OPPO|realme)","i"),j=new RegExp("(vivo|IQOO)","i"),z={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000",5.1:"XP",5.2:"XP","6.0":"Vista",6.1:"7",6.2:"8",6.3:"8.1",6.4:"10","10.0":"10"};function Y(e,t){return t=t||"",M(e," OPR/")&&M(e,"Mini")?$.OPERA_MINI:M(e," OPR/")?$.OPERA:X.test(e)?$.BLACKBERRY:M(e,"IE"+$.MOBILE)||M(e,"WPDesktop")?$.INTERNET_EXPLORER_MOBILE:M(e,$.SAMSUNG_BROWSER)?$.SAMSUNG_INTERNET:M(e,$.EDGE)||M(e,"Edg/")?$.MICROSOFT_EDGE:M(e,"FBIOS")?$.FACEBOOK+" "+$.MOBILE:M(e,"UCWEB")||M(e,"UCBrowser")?$.UC_BROWSER:M(e,"CriOS")?$.CHROME_IOS:M(e,"CrMo")||M(e,$.CHROME)?$.CHROME:M(e,$.ANDROID)&&M(e,$.SAFARI)?$.ANDROID_MOBILE:M(e,"FxiOS")?$.FIREFOX_IOS:M(e.toLowerCase(),$.KONQUEROR.toLowerCase())?$.KONQUEROR:function(e,t){return t&&M(t,$.APPLE)||M(n=e,$.SAFARI)&&!M(n,$.CHROME)&&!M(n,$.ANDROID);var n}(e,t)?M(e,$.MOBILE)?$.MOBILE_SAFARI:$.SAFARI:M(e,$.FIREFOX)?$.FIREFOX:M(e,"MSIE")||M(e,"Trident/")?$.INTERNET_EXPLORER:M(e,"Gecko")?$.FIREFOX:""}const K={[$.INTERNET_EXPLORER_MOBILE]:[new RegExp("rv:"+k)],[$.MICROSOFT_EDGE]:[new RegExp($.EDGE+"?\\/"+k)],[$.CHROME]:[new RegExp("("+$.CHROME+"|CrMo)\\/"+k)],[$.CHROME_IOS]:[new RegExp("CriOS\\/"+k)],[$.UC_BROWSER]:[new RegExp("(UCBrowser|UCWEB)\\/"+k)],[$.SAFARI]:[D],[$.MOBILE_SAFARI]:[D],[$.OPERA]:[new RegExp("("+$.OPERA+"|OPR)\\/"+k)],[$.FIREFOX]:[new RegExp($.FIREFOX+"\\/"+k)],[$.FIREFOX_IOS]:[new RegExp("FxiOS\\/"+k)],[$.KONQUEROR]:[new RegExp("Konqueror[:/]?"+k,"i")],[$.BLACKBERRY]:[new RegExp($.BLACKBERRY+" "+k),D],[$.ANDROID_MOBILE]:[new RegExp("android\\s"+k,"i")],[$.SAMSUNG_INTERNET]:[new RegExp($.SAMSUNG_BROWSER+"\\/"+k)],[$.INTERNET_EXPLORER]:[new RegExp("(rv:|MSIE )"+k)],Mozilla:[new RegExp("rv:"+k)]};function J(e,t){const n=Y(e,t),i=K[n];if(a(i))return null;for(let s=0;s<i.length;s++){const t=i[s],n=e.match(t);if(n)return parseFloat(n[n.length-2])}return null}const Z=[[new RegExp($.XBOX+"; "+$.XBOX+" (.*?)[);]","i"),e=>[$.XBOX,e&&e[1]||""]],[new RegExp($.NINTENDO,"i"),[$.NINTENDO,""]],[new RegExp($.PLAYSTATION,"i"),[$.PLAYSTATION,""]],[X,[$.BLACKBERRY,""]],[new RegExp($.WINDOWS,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[$.WINDOWS_PHONE,""];if(new RegExp($.MOBILE).test(t)&&!/IEMobile\b/.test(t))return[$.WINDOWS+" "+$.MOBILE,""];const n=/Windows NT ([0-9.]+)/i.exec(t);if(n&&n[1]){const e=n[1];let i=z[e]||"";return/arm/i.test(t)&&(i="RT"),[$.WINDOWS,i]}return[$.WINDOWS,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>{if(e&&e[3]){const t=[e[3],e[4],e[5]||"0"];return[$.IOS,t.join(".")]}return[$.IOS,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{let t="";return e&&e.length>=3&&(t=a(e[2])?e[3]:e[2]),["watchOS",t]}],[new RegExp("("+$.ANDROID+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+$.ANDROID+")","i"),e=>{if(e&&e[2]){const t=[e[2],e[3],e[4]||"0"];return[$.ANDROID,t.join(".")]}return[$.ANDROID,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,e=>{const t=["Mac OS X",""];if(e&&e[1]){const n=[e[1],e[2],e[3]||"0"];t[1]=n.join(".")}return t}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[$.CHROME_OS,""]],[/Linux|debian/i,["Linux",""]]];function Q(){const e=window.innerHeight||document.documentElement.clientHeight||document.body&&document.body.clientHeight||0,t=window.innerWidth||document.documentElement.clientWidth||document.body&&document.body.clientWidth||0,n=navigator.userAgent,i=function(e){for(let t=0;t<Z.length;t++){const[n,i]=Z[t],s=n.exec(e),r=s&&("function"==typeof i?i(s,e):i);if(r)return r}return["",""]}(n)||["",""];return{$browser:Y(n),$browser_version:J(n),$url:location?.href.substring(0,1e3),$host:location?.host,$viewport_height:e,$viewport_width:t,$lib:"webjs",$lib_version:A,$search_engine:F(),$referrer:B(),$referrer_host:m(r=r||B()),$title:document.title,$language:navigator.language,$model:(s=n,(U.test(s)?$.NINTENDO:H.test(s)?$.PLAYSTATION:x.test(s)?$.XBOX:new RegExp($.OUYA,"i").test(s)?$.OUYA:new RegExp("("+$.WINDOWS_PHONE+"|WPDesktop)","i").test(s)?$.WINDOWS_PHONE:/iPad/.test(s)?$.IPAD:/iPod/.test(s)?"iPod Touch":/iPhone/.test(s)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(s)?$.APPLE_WATCH:X.test(s)?$.BLACKBERRY:/(kobo)\s(ereader|touch)/i.test(s)?"Kobo":new RegExp($.NOKIA,"i").test(s)?$.NOKIA:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(s)||/(kf[a-z]+)( bui|\)).+silk\//i.test(s)?"Kindle Fire":q.test(s)?$.HUAWEI:W.test(s)?$.XIAOMI:G.test(s)?$.OPPO:j.test(s)?$.VIVO:/(Android|ZTE)/i.test(s)?!new RegExp($.MOBILE).test(s)||/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(s)?/pixel[\daxl ]{1,6}/i.test(s)&&!/pixel c/i.test(s)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(s)||/lmy47v/i.test(s)&&!/QTAQZ3/i.test(s)?$.ANDROID:$.ANDROID_TABLET:$.ANDROID:new RegExp("(pda|"+$.MOBILE+")","i").test(s)?$.GENERIC_MOBILE:new RegExp($.TABLET,"i").test(s)&&!new RegExp($.TABLET+" pc","i").test(s)?$.GENERIC_TABLET:"")||""),$os:i?.[0]||"",$os_version:i?.[1]||"",$pathname:location?.pathname,$screen_height:Number(screen.height)||0,$screen_width:Number(screen.width)||0,$timezone_offset:60*-(new Date).getTimezoneOffset()};var s,r}const V=new class{constructor(){this.STORAGE_KEY="sensorswave_unsent_events",this.MAX_QUEUE_SIZE=200,this.MAX_RETRY_COUNT=1,this.MAX_AGE_MS=6048e5,this.queue=[],this.loadFromStorage(),this.cleanupExpiredItems()}loadFromStorage(){try{const e=localStorage.getItem(this.STORAGE_KEY);e&&(this.queue=d(e)||[])}catch(e){console.warn("Failed to load queue from localStorage:",e),this.queue=[]}}cleanupExpiredItems(){const e=Date.now(),t=this.queue.filter(t=>e-t.timestamp<this.MAX_AGE_MS);t.length!==this.queue.length&&(this.queue=t,this.saveToStorage())}saveToStorage(){try{this.cleanupExpiredItems(),this.queue.length>this.MAX_QUEUE_SIZE&&(this.queue=this.queue.slice(-this.MAX_QUEUE_SIZE)),localStorage.setItem(this.STORAGE_KEY,JSON.stringify(this.queue))}catch(e){console.warn("Failed to save queue to localStorage:",e)}}enqueue(e,t,n,i=this.MAX_RETRY_COUNT){try{const s={id:f(),url:e,data:t,headers:n,timestamp:Date.now(),retryCount:0,maxRetries:i};return this.queue.push(s),this.saveToStorage(),s.id}catch(s){return console.warn("Failed to enqueue request:",s),""}}dequeue(e){try{this.queue=this.queue.filter(t=>t.id!==e),this.saveToStorage()}catch(t){console.warn("Failed to dequeue request:",t)}}getAll(){try{return this.cleanupExpiredItems(),[...this.queue]}catch(e){return console.warn("Failed to get queue items:",e),[]}}incrementRetryCount(e){const t=this.queue.find(t=>t.id===e);return!(!t||t.retryCount>=t.maxRetries||(t.retryCount++,this.saveToStorage(),0))}clear(){this.queue=[];try{localStorage.removeItem(this.STORAGE_KEY)}catch(e){console.warn("Failed to clear queue from localStorage:",e)}}getItemById(e){return this.queue.find(t=>t.id===e)}};class ee{constructor(e={}){this.flushTimer=null,this.isFlushing=!1,this.config={maxBatchSize:e.maxBatchSize||20,flushInterval:e.flushInterval||5e3},this.startFlushTimer()}add(){V.getAll().length>=this.config.maxBatchSize&&this.triggerFlush()}triggerFlush(){this.isFlushing||(this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.isFlushing=!0,this.flush())}flush(){const e=V.getAll();if(0===e.length)return this.isFlushing=!1,void this.startFlushTimer();const t=[],n=[];e.forEach(e=>{Array.isArray(e.data)?t.push(...e.data):t.push(e.data),n.push(e.id)});const i=t.slice(0,this.config.maxBatchSize),s=e[e.length-1],r=s.url,o=s.headers;O.instance.config.debug&&console.log(JSON.stringify(i,null,2)),L({url:r,method:"POST",data:i,headers:o,callback:e=>{200===e.statusCode?n.forEach(e=>{V.dequeue(e)}):console.error("Failed to send batch events:",e),this.isFlushing=!1,this.startFlushTimer()}})}startFlushTimer(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.flushTimer=setInterval(()=>{V.getAll().length>0&&this.triggerFlush()},this.config.flushInterval)}destroy(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.flush()}}let te=null;function ne(){const e=O.instance;return!(!e||!e.__innerInited)||(console.warn("[SensorsWave] SDK is not initialized. Please call init() first."),!1)}let ie=null;function se(){return S.isSupport()?(ie||(te||(te=new ee({maxBatchSize:20,flushInterval:5e3})),ie=te),ie):null}function re(e,t,n){return L({url:e,method:"POST",data:t.data,headers:t.headers,callback:e=>{if(200!==e.statusCode){if(n)if(V.incrementRetryCount(n)){const e=V.getItemById(n);if(e){const t=Math.min(1e3*Math.pow(2,e.retryCount),3e4);setTimeout(()=>{re(e.url,{data:e.data,headers:e.headers},e.id)},t)}}else console.warn("Max retries reached for request:",n)}else n&&V.dequeue(n),t.callback&&t.callback(e.json)}})}function oe(e){return`${e.apiHost}/in/track`}function ae(e){return`${e.apiHost}/ab/evalall`}function ce(e){return{"Content-Type":"application/json",SourceToken:e.sourceToken}}function le(e,t,n){O.instance.config.debug&&console.log(JSON.stringify(t.data,null,2));const i=V.enqueue(e,t.data,t.headers);return re(e,{...t,callback:void 0},i)}function ue(){try{const e=sessionStorage.getItem("sensorswave_utm");if(!e)return{};const t=JSON.parse(e),n={};return Object.entries(t).forEach(([e,t])=>{null!=t&&""!==t&&(n[`$${e}`]=t)}),n}catch(e){return{}}}function he(e){const t={};return Object.entries(e).forEach(([e,n])=>{if("function"==typeof n)try{const i=n();t[e]=i}catch(i){console.warn("[SensorsWave] Failed to resolve dynamic property:",e,i)}else t[e]=n}),t}function de(e={},t=!0){const n={...t?Q():{},...he(N.getCommonProps()),...e},i=ue();return Object.keys(i).length>0&&Object.assign(n,i),n}function ge(e,t,n=!0){if(!ne())return;const i={time:Date.now(),trace_id:N.getTraceId(),event:e.event,properties:de(e.properties,n)},s=ue();Object.keys(s).length>0&&(i.user_properties||(i.user_properties={}),i.user_properties.$set||(i.user_properties.$set={}),Object.assign(i.user_properties.$set,s)),e.user_properties&&(e.user_properties.$set&&(i.user_properties=i.user_properties||{},i.user_properties.$set={...i.user_properties.$set||{},...e.user_properties.$set},delete e.user_properties.$set),i.user_properties={...i.user_properties,...e.user_properties});const r=N.getLoginId(),o=N.getAnonId();r&&(i.login_id=r),o&&(i.anon_id=o);const a=oe(t),c=ce(t),l=!1!==t.batchSend&&se();l?(V.enqueue(a,[i],c),l.add()):le(a,{data:[i],headers:c})}function pe({userProps:e,opts:t}){if(!ne())return;const n=N.getLoginId(),i=N.getAnonId();if(!n&&!i)return;const s={time:Date.now(),trace_id:N.getTraceId(),event:"$UserSet",login_id:n,anon_id:i,user_properties:e,properties:de()},r=oe(t),o=ce(t),a=se();if(!a)return le(r,{data:[s],headers:o});V.enqueue(r,[s],o),a.add()}function fe(e){return e.typ===y.FEATURE_GATE||e.typ===y.FEATURE_CONFIG?`$feature_${e.id}`:e.typ===y.EXPERIMENT?`$exp_${e.id}`:""}function me(e){const t=e.typ;return[y.FEATURE_GATE,y.EXPERIMENT,y.FEATURE_CONFIG].includes(t)?{[fe(e)]:e.vid}:{}}function Ee(e){const t=e.typ;return t===y.FEATURE_GATE||t===y.FEATURE_CONFIG?{$feature_key:e.key,$feature_variant:e.vid}:t===y.EXPERIMENT?{$exp_key:e.key,$exp_variant:e.vid}:{}}function Ie({isUnset:e=!1,data:t,opts:n}){if(!ne())return;if(!t||l(t)||t.disable_impress)return;const i=N.getLoginId(),s=N.getAnonId();if(!i&&!s)return;const r=t.typ===y.EXPERIMENT?"$ExpImpress":"$FeatureImpress";let o={};return o=e?{$unset:{[fe(t)]:null}}:{$set:{...me(t)}},ge({event:r,properties:Ee(t),user_properties:o},n)}class Se{constructor({plugins:e,emitter:t,config:n,sdk:i}){this.plugins=[],this.pluginInsMap={},this.emitter=t,this.config=n,this.sdk=i,this.registerBuiltInPlugins(e),this.created(),this.emitter.on(v,()=>{this.init()})}registerBuiltInPlugins(e){for(let t=0,n=e.length;t<n;t++)this.registerPlugin(e[t])}registerPlugin(e){this.plugins.push(e)}getPlugins(){return this.plugins}getPlugin(e){return this.pluginInsMap[e]}created(){for(let e=0,t=this.plugins.length;e<t;e++){const t=this.plugins[e];if(!t.NAME)throw new Error('Plugin should be defined with "NAME"');const n=new t({emitter:this.emitter,config:this.config,sdk:this.sdk});this.pluginInsMap[t.NAME]=n}}init(){for(const e of Object.keys(this.pluginInsMap)){const t=this.pluginInsMap[e];t.init&&t.init()}}destroy(){for(const e of Object.keys(this.pluginInsMap)){const t=this.pluginInsMap[e];t.destroy&&"function"==typeof t.destroy&&t.destroy()}this.pluginInsMap={},this.plugins=[]}}const we=class{constructor({emitter:e,config:t}){this.boundSend=null,this.hashEvent=null,this.spaSwitchHandler=null,this.emitter=e,this.config=t}init(){const e=this.config;this.boundSend=()=>{ge({event:"$PageView",properties:{}},e)},setTimeout(()=>{this.boundSend()},0),e.isSinglePageApp&&this.addSinglePageListener()}addSinglePageListener(){this.spaSwitchHandler=e=>{e!==location.href&&this.boundSend()},this.emitter.on(R,this.spaSwitchHandler)}destroy(){this.spaSwitchHandler&&(this.emitter.off(R,this.spaSwitchHandler),this.spaSwitchHandler=null),this.hashEvent&&this.boundSend&&(window.removeEventListener(this.hashEvent,this.boundSend),this.hashEvent=null),this.boundSend=null}};we.NAME="pageview";let _e=we;const Oe=class{constructor({emitter:e,config:t}){this.startTime=Date.now(),this.pageShowStatus=!0,this.pageHiddenStatus=!1,this.timer=null,this.currentPageUrl=document.referrer,this.url=location.href,this.title=document.title||"",this.heartbeatIntervalTime=5e3,this.heartbeatIntervalTimer=null,this.pageId=null,this.storageName="sensorswavewebjssdkpageleave",this.maxDuration=432e3,this.eventListeners=[],this.emitter=e,this.config=t}init(){this.pageId=Number(String(p()).slice(2,5)+String(p()).slice(2,4)+String(Date.now()).slice(-4)),this.addEventListener(),!0===document.hidden?this.pageShowStatus=!1:this.addHeartBeatInterval()}log(e){console.log(e)}refreshPageEndTimer(){this.timer&&(clearTimeout(this.timer),this.timer=null),this.timer=setTimeout(()=>{this.pageHiddenStatus=!1},5e3)}hiddenStatusHandler(){this.timer&&clearTimeout(this.timer),this.timer=null,this.pageHiddenStatus=!1}pageStartHandler(){this.startTime=Date.now(),1==!document.hidden?this.pageShowStatus=!0:this.pageShowStatus=!1,this.url=location.href,this.title=document.title}pageEndHandler(){if(!0===this.pageHiddenStatus)return;const e=this.getPageLeaveProperties();!1===this.pageShowStatus&&delete e.$event_duration,this.pageShowStatus=!1,this.pageHiddenStatus=!0,ge({event:b,properties:e},this.config),this.refreshPageEndTimer(),this.delHeartBeatData()}addEventListener(){this.addPageStartListener(),this.addPageSwitchListener(),this.addSinglePageListener(),this.addPageEndListener()}addPageStartListener(){if("onpageshow"in window){const e=()=>{this.pageStartHandler(),this.hiddenStatusHandler()};window.addEventListener("pageshow",e),this.eventListeners.push({target:window,event:"pageshow",handler:e})}}addSinglePageListener(){this.config.isSinglePageApp&&this.emitter.on(R,e=>{e!==location.href&&(this.url=e,this.pageEndHandler(),this.stopHeartBeatInterval(),this.currentPageUrl=this.url,this.pageStartHandler(),this.hiddenStatusHandler(),this.addHeartBeatInterval())})}addPageEndListener(){["pagehide","beforeunload"].forEach(e=>{if(`on${e}`in window){const t=()=>{this.pageEndHandler(),this.stopHeartBeatInterval()};window.addEventListener(e,t),this.eventListeners.push({target:window,event:e,handler:t})}})}addPageSwitchListener(){const e=()=>{"visible"===document.visibilityState?(this.pageStartHandler(),this.hiddenStatusHandler(),this.addHeartBeatInterval()):(this.url=location.href,this.title=document.title,this.stopHeartBeatInterval())};document.addEventListener("visibilitychange",e),this.eventListeners.push({target:document,event:"visibilitychange",handler:e})}addHeartBeatInterval(){S.isSupport()&&this.startHeartBeatInterval()}startHeartBeatInterval(){this.heartbeatIntervalTimer&&this.stopHeartBeatInterval(),this.heartbeatIntervalTimer=setInterval(()=>{this.saveHeartBeatData()},this.heartbeatIntervalTime),this.saveHeartBeatData("is_first_heartbeat"),this.reissueHeartBeatData()}stopHeartBeatInterval(){this.heartbeatIntervalTimer&&clearInterval(this.heartbeatIntervalTimer),this.heartbeatIntervalTimer=null}saveHeartBeatData(e){const t=this.getPageLeaveProperties();t.$time=Date.now(),"is_first_heartbeat"===e&&(t.$event_duration=3);const n={type:"track",event:b,properties:t,time:t.$time};n.heartbeat_interval_time=this.heartbeatIntervalTime,S.isSupport()&&S.set(`${this.storageName}-${this.pageId}`,JSON.stringify(n))}delHeartBeatData(e){S.isSupport()&&S.remove(e||`${this.storageName}-${this.pageId}`)}reissueHeartBeatData(){for(let e=window.localStorage.length-1;e>=0;e--){const t=window.localStorage.key(e);if(t&&t!==`${this.storageName}-${this.pageId}`&&0===t.indexOf(`${this.storageName}-`)){const e=S.parse(t);i(e)&&Date.now()-e.time>e.heartbeat_interval_time+5e3&&(delete e.heartbeat_interval_time,e._flush_time=(new Date).getTime(),ge({event:b,properties:e?.properties},this.config),this.delHeartBeatData(t))}}}getPageLeaveProperties(){let e=(Date.now()-this.startTime)/1e3;(isNaN(e)||e<0||e>this.maxDuration)&&(e=0),e=Number(e.toFixed(3));const t={$title:this.title,$url:this.url?.substring(0,1e3),$pathname:_(this.url)};return 0!==e&&(t.$event_duration=e),t}destroy(){this.eventListeners.forEach(({target:e,event:t,handler:n})=>{e.removeEventListener(t,n)}),this.eventListeners=[],this.timer&&(clearTimeout(this.timer),this.timer=null),this.heartbeatIntervalTimer&&(clearInterval(this.heartbeatIntervalTimer),this.heartbeatIntervalTimer=null)}};Oe.NAME="pageleave";let Ae=Oe;const ve=class{constructor({emitter:e,config:t}){this.eventSended=!1,this.emitter=e,this.config=t}init(){const e=()=>{let t=0;const n={};if(window.performance){t=function(){let e=0;if("function"==typeof performance.getEntriesByType){const t=performance.getEntriesByType("navigation");t.length>0&&(e=t[0].domContentLoadedEventEnd||0)}return e}();const e=function(){if(performance.getEntries&&"function"==typeof performance.getEntries){const e=performance.getEntries();let t=0;for(const n of e)"transferSize"in n&&(t+=n.transferSize);if("number"==typeof t&&t>=0&&t<10737418240)return Number((t/1024).toFixed(3))}}();e&&(n.$page_resource_size=e)}else console.warn("Performance API is not supported.");t>0&&!Number.isFinite(t)&&(n.$event_duration=Number((t/1e3).toFixed(3))),this.eventSended||(this.eventSended=!0,ge({event:"$PageLoad",properties:n},this.config)),window.removeEventListener("load",e)};"complete"===document.readyState?e():window.addEventListener&&window.addEventListener("load",e)}};ve.NAME="pageload";let Re=ve;function Te(e,t){if(!u(e))return!1;const n=o(e.tagName)?e.tagName.toLowerCase():"",i={};i.$element_type=n,i.$element_name=e.getAttribute("name")||"",i.$element_id=e.getAttribute("id")||"",i.$element_class_name=o(e.className)?e.className:"",i.$element_target_url=e.getAttribute("href")||"",i.$element_content=function(e,t){return o(t)&&"input"===t.toLowerCase()?("button"===(n=e).type||"submit"===n.type)&&n.value||"":function(e,t){let n="",i="";return e.textContent?n=w(e.textContent):e.innerText&&(n=w(e.innerText)),n&&(n=n.replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)),i=n||"","input"!==t&&"INPUT"!==t||(i=e.value||""),i}(e,t);var n}(e,n)||"",i.$element_selector=be(e)||"",i.$element_path=function(e){let t=[];for(;e.parentNode&&u(e);){if(!o(e.tagName))return"";if(e.id&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(e.id)){t.unshift(e.tagName.toLowerCase()+"#"+e.id);break}if(e===document.body){t.unshift("body");break}t.unshift(e.tagName.toLowerCase()),e=e.parentNode}return t.join(" > ")}(e)||"";const s=function(e,t){const n=t.pageX||t.clientX+ye().scrollLeft||t.offsetX+Ne(e).targetEleX,i=t.pageY||t.clientY+ye().scrollTop||t.offsetY+Ne(e).targetEleY;return{$page_x:Pe(n),$page_y:Pe(i)}}(e,t);return i.$page_x=s.$page_x,i.$page_y=s.$page_y,i}function be(e,t=[]){if(!(e&&e.parentNode&&e.parentNode.children&&o(e.tagName)))return"";t=Array.isArray(t)?t:[];const n=e.nodeName.toLowerCase();return e&&"body"!==n&&1==e.nodeType?(t.unshift(function(e){if(!e||!u(e)||!o(e.tagName))return"";let t=e.parentNode&&9==e.parentNode.nodeType?-1:function(e){if(!e.parentNode)return-1;let t=0;const n=e.tagName,i=e.parentNode.children;for(let s=0,r=i.length;s<r;s++)if(i[s].tagName===n){if(e===i[s])return t;t++}return-1}(e);return e.getAttribute&&e.getAttribute("id")&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(e.getAttribute("id"))?"#"+e.getAttribute("id"):e.tagName.toLowerCase()+(~t?":nth-of-type("+(t+1)+")":"")}(e)),e.getAttribute&&e.getAttribute("id")&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(e.getAttribute("id"))?t.join(" > "):be(e.parentNode,t)):(t.unshift("body"),t.join(" > "))}function ye(){return{scrollLeft:document.body.scrollLeft||document.documentElement.scrollLeft||0,scrollTop:document.body.scrollTop||document.documentElement.scrollTop||0}}function Ne(e){if(document.documentElement.getBoundingClientRect){const t=e.getBoundingClientRect();return{targetEleX:t.left+ye().scrollLeft||0,targetEleY:t.top+ye().scrollTop||0}}return{targetEleX:0,targetEleY:0}}function Pe(e){return Number(Number(e).toFixed(3))}const Ce=class{constructor({emitter:e,config:t}){this.isInitialized=!1,this.boundHandleClick=null,this.emitter=e,this.config=t}init(){this.isInitialized||(this.boundHandleClick=this.handleClick.bind(this),document.addEventListener("click",this.boundHandleClick,!0),this.isInitialized=!0)}handleClick(e){const t=e.target;if(!t)return;if(!["A","INPUT","BUTTON","TEXTAREA"].includes(t.tagName))return;if("true"===t.getAttribute("sensorswave-disable"))return;ge({event:"$WebClick",properties:Te(t,e)||{}},this.config)}destroy(){this.boundHandleClick&&(document.removeEventListener("click",this.boundHandleClick,!0),this.boundHandleClick=null),this.isInitialized=!1}};Ce.NAME="webclick";let Le=Ce;const Be=class{constructor({emitter:e,config:t}){this.updateInterval=null,this.fetchingPromise=null,this.emitter=e,this.config=t}init(){const e=this.config;e.enableAB&&(this.fastFetch().then(()=>{this.emitter.emit(T)}),e.abRefreshInterval<3e4&&(e.abRefreshInterval=3e4),this.updateInterval=setInterval(()=>{this.fetchNewData().catch(console.warn)},e.abRefreshInterval))}async fastFetch(){const e=N.getABData(this.config.abRefreshInterval);return e&&e.length?(this.emitter.emit(T),Promise.resolve(e)):this.fetchNewData()}async fetchNewData(){return this.fetchingPromise||(this.fetchingPromise=new Promise(e=>{!function({opts:e,cb:t}){if(!ne())return void(t&&t({}));const n=N.getLoginId(),i=N.getAnonId();if(!n&&!i)return void(t&&t({}));const s={user:{login_id:n||"",anon_id:i||"",props:{...Q(),...he(N.getCommonProps())}},sdk:"webjs",sdk_version:A};L({url:ae(e),method:"POST",data:s,headers:ce(e),callback:e=>{200!==e.statusCode?(console.error("Failed to fetch feature flags"),t&&t({})):t&&t(e.json)}})}({opts:this.config,cb:t=>{N.saveABData(t?.data?.results||[]),e(t),this.fetchingPromise=null}})})),this.fetchingPromise}async getFeatureGate(e){return await this.fastFetch().catch(console.warn),N.getABData(this.config.abRefreshInterval).find(t=>t.typ===y.FEATURE_GATE&&t.key==e)}async checkFeatureGate(e){const t=await this.getFeatureGate(e);return!!t&&(!t.hasOwnProperty("vid")&&t.key?(Ie({isUnset:!0,data:t,opts:this.config}),!1):(Ie({data:t,opts:this.config}),"fail"!==t.vid))}async getExperiment(e){await this.fastFetch().catch(console.warn);const t=N.getABData(this.config.abRefreshInterval).find(t=>t.typ===y.EXPERIMENT&&t.key===e);return t?!t.hasOwnProperty("vid")&&t.key?(Ie({isUnset:!0,data:t,opts:this.config}),{}):(Ie({data:t,opts:this.config}),t?.value||{}):{}}async getFeatureConfig(e){await this.fastFetch().catch(console.warn);const t=N.getABData(this.config.abRefreshInterval).find(t=>t.typ===y.FEATURE_CONFIG&&t.key===e);if(!t)return{};if(!t.hasOwnProperty("vid")&&t.key)return Ie({isUnset:!0,data:t,opts:this.config}),{};Ie({data:t,opts:this.config});const n=t?.value;if(n){if(i(n))return n;try{return JSON.parse(n)}catch{return n}}return{}}destroy(){this.updateInterval&&(clearInterval(this.updateInterval),this.updateInterval=null),this.fetchingPromise=null}};Be.NAME="abtest";let Fe=Be;const Me=["utm_source","utm_medium","utm_campaign","utm_content","utm_term"],$e=class{constructor({sdk:e,emitter:t,config:n}){this.sdk=e,this.emitter=t,this.config=n}init(){const e=this.getUTMFromURL();this.saveToSessionStorage(e),setTimeout(()=>{this.sendInitialUTM(e)},0)}getUTMFromURL(){try{const e=new URLSearchParams(window.location.search),t={};return Me.forEach(n=>{const i=e.get(n);i&&(t[n]=i)}),t}catch(e){return this.getUTMFromURLFallback()}}getUTMFromURLFallback(){const e={};return window.location.search.substring(1).split("&").forEach(t=>{const[n,i]=t.split("="),s=decodeURIComponent(n),r=i?decodeURIComponent(i):"";Me.includes(s)&&(e[s]=r)}),e}saveToSessionStorage(e){try{sessionStorage.setItem("sensorswave_utm",JSON.stringify(e))}catch(t){this.config.debug&&console.warn("[SensorsWave UTM] Failed to save to sessionStorage:",t)}}sendInitialUTM(e){const t={};Me.forEach(n=>{t[`$initial_${n}`]=null!=e[n]?e[n]:""});try{this.sdk.profileSetOnce(t)}catch(n){this.config.debug&&console.warn("[SensorsWave UTM] Failed to send initial UTM:",n)}}destroy(){}};$e.NAME="UTM";let ke=$e;const De=[],xe={debug:!1,sourceToken:"",apiHost:"",autoCapture:!0,isSinglePageApp:!1,crossSubdomainCookie:!0,enableAB:!1,abRefreshInterval:6e5,enableClickTrack:!1,batchSend:!1},He=new class{constructor(){this.__innerInited=!1,this.inited=!1,this.config={},this.eventEmitter=new e,this.pluginCore={},this.commonProps={},this.spaCleanup=null,O.instance=this}init(e,t={}){if(this.inited)return this;t.sourceToken=e,this.mergeConfig(t),this.eventEmitter.emit("init-param",this.config),this.__innerInited=!0;const n=this.config;return N.init(n.crossSubdomainCookie),n.anonId&&N.setAnonId(n.anonId),window._swFailedRequestsInitialized||(window._swFailedRequestsInitialized=!0,function(){const e=V.getAll();if(0!==e.length)for(let t=0,n=e.length;t<n;t+=10){const n=e.slice(t,t+10),i=[],s=[];n.forEach(e=>{Array.isArray(e.data)?i.push(...e.data):i.push(e.data),s.push(e.id)});const r=n[n.length-1],o=r.url,a=r.headers;L({url:o,method:"POST",data:i,headers:a,callback:e=>{200!==e.statusCode?console.error("Failed to send batch stored requests:",e):s.forEach(e=>{V.dequeue(e)})}})}}()),De.push(ke),n.autoCapture&&this.autoTrack(),n.enableAB&&De.push(Fe),n.enableClickTrack&&De.push(Le),this.pluginCore=new Se({plugins:De,emitter:this.eventEmitter,config:n,sdk:this}),this.spaCleanup=function(e){let t=location.href;const n=window.history.pushState,i=window.history.replaceState,r=function(){e(t),t=location.href};return s(window.history.pushState)&&(window.history.pushState=function(...i){n.apply(window.history,i),e(t),t=location.href}),s(window.history.replaceState)&&(window.history.replaceState=function(...n){i.apply(window.history,n),e(t),t=location.href}),window.addEventListener("popstate",r),function(){s(window.history.pushState)&&(window.history.pushState=n),s(window.history.replaceState)&&(window.history.replaceState=i),window.removeEventListener("popstate",r)}}(e=>{this.eventEmitter.emit(R,e)}),this.eventEmitter.emit(v),this.inited=!0,this}mergeConfig(e){this.config={...xe,...e}}track(e){!function(e,t){if(!ne())return;const n={...e};n.time||(n.time=Date.now()),n.login_id||(n.login_id=N.getLoginId()),n.anon_id||(n.anon_id=N.getAnonId()),n.trace_id||(n.trace_id=N.getTraceId()),n.properties={...Q(),...he(N.getCommonProps()),...n.properties};const i=oe(t),s=ce(t),r=!1!==t.batchSend&&se();if(!r)return le(i,{data:[n],headers:s});V.enqueue(i,[n],s),r.add()}(e,this.config)}trackEvent(e,t){ge({event:e,properties:t},this.config)}autoTrack(){De.push(_e,Re,Ae)}profileSet(e){pe({userProps:{$set:e},opts:this.config})}profileSetOnce(e){pe({userProps:{$set_once:e},opts:this.config})}profileIncrement(e){pe({userProps:{$increment:e},opts:this.config})}profileAppend(e){pe({userProps:{$append:e},opts:this.config})}profileUnion(e){pe({userProps:{$union:e},opts:this.config})}profileUnset(e){const t={};r(e)?e.forEach(function(e){t[e]=null}):t[e]=null,pe({userProps:{$unset:t},opts:this.config})}profileDelete(){pe({userProps:{$delete:!0},opts:this.config})}registerCommonProperties(e){if(!i(e))return console.warn("Commmon Properties must be an object!");this.commonProps=e,N.setCommonProps(this.commonProps)}clearCommonProperties(e){if(!r(e))return console.warn("Commmon Properties to be cleared must be an array!");e.forEach(e=>{delete this.commonProps[e]}),N.setCommonProps(this.commonProps)}identify(e){N.setLoginId(e),function(e){if(!ne())return;const t=N.getLoginId(),n=N.getAnonId();if(!t||!n)return;const i={time:Date.now(),trace_id:N.getTraceId(),event:"$Identify",login_id:t,anon_id:n,properties:de()},s=oe(e),r=ce(e),o=se();if(!o)return le(s,{data:[i],headers:r});V.enqueue(s,[i],r),o.add()}(this.config)}setLoginId(e){N.setLoginId(e)}getAnonId(){return N.getAnonId()}setAnonId(e){N.setAnonId(e)}getLoginId(){return N.getLoginId()}checkFeatureGate(e){const t=this.pluginCore.getPlugin(Fe.NAME);return this.config.enableAB&&t?t.checkFeatureGate(e):Promise.reject("AB is disabled")}getExperiment(e){const t=this.pluginCore.getPlugin(Fe.NAME);return this.config.enableAB&&t?t.getExperiment(e):Promise.reject("AB is disabled")}getFeatureConfig(e){const t=this.pluginCore.getPlugin(Fe.NAME);return this.config.enableAB&&t?t.getFeatureConfig(e):Promise.reject("AB is disabled")}destroy(){ie&&(ie.destroy(),ie=null),this.inited=!1,this.__innerInited=!1,this.spaCleanup&&"function"==typeof this.spaCleanup&&(this.spaCleanup(),this.spaCleanup=null),this.pluginCore&&"function"==typeof this.pluginCore.destroy&&this.pluginCore.destroy(),this.eventEmitter&&this.eventEmitter.removeAllListeners(),O.instance===this&&(O.instance=null)}};module.exports=He;
1
+ "use strict";class t{constructor(){this.listeners={}}on(t,e,n=!1){if(t&&e){if(!s(e))throw new Error("listener must be a function");this.listeners[t]=this.listeners[t]||[],this.listeners[t].push({listener:e,once:n})}}off(t,e){const n=this.listeners[t];if(!n?.length)return;"number"==typeof e&&n.splice(e,1);const i=n.findIndex(t=>t.listener===e);-1!==i&&n.splice(i,1)}emit(t,...e){this.listeners[t]&&this.listeners[t].forEach((n,i)=>{n.listener.call(this,...e),n.listener.once&&this.off(t,i)})}once(t,e){this.on(t,e,!0)}removeAllListeners(t){t?this.listeners[t]=[]:this.listeners={}}}const e={get:function(t){const e=t+"=",n=document.cookie.split(";");for(let i=0,s=n.length;i<s;i++){let t=n[i];for(;" "==t.charAt(0);)t=t.substring(1,t.length);if(0==t.indexOf(e))return h(t.substring(e.length,t.length))}return null},set:function({name:t,value:e,expires:n,samesite:i,secure:s,domain:r}){let o="",a="",c="",u="";if(0!==(n=null==n||void 0===n?365:n)){const t=new Date;"s"===String(n).slice(-1)?t.setTime(t.getTime()+1e3*Number(String(n).slice(0,-1))):t.setTime(t.getTime()+24*n*60*60*1e3),o="; expires="+t.toUTCString()}function l(t){return t?t.replace(/\r\n/g,""):""}i&&(c="; SameSite="+i),s&&(a="; secure");const h=l(t),d=l(e),p=l(r);p&&(u="; domain="+p),h&&d&&(document.cookie=h+"="+encodeURIComponent(d)+o+"; path=/"+u+c+a)},remove:function(t){this.set({name:t,value:"",expires:-1})},isSupport:function({samesite:t,secure:e}={}){if(!navigator.cookieEnabled)return!1;const n="sensorswave_cookie_support_test";return this.set({name:n,value:"1",samesite:t,secure:e}),"1"===this.get(n)&&(this.remove(n),!0)}},n=Object.prototype.toString;function i(t){return"[object Object]"===n.call(t)}function s(t){const e=n.call(t);return"[object Function]"==e||"[object AsyncFunction]"==e}function r(t){return"[object Array]"==n.call(t)}function o(t){return"[object String]"==n.call(t)}function a(t){return void 0===t}const c=Object.prototype.hasOwnProperty;function u(t){if(i(t)){for(let e in t)if(c.call(t,e))return!1;return!0}return!1}function l(t){return!(!t||1!==t.nodeType)}function h(t){let e=t;try{e=decodeURIComponent(t)}catch(n){e=t}return e}function d(t){try{return JSON.parse(t)}catch(e){return""}}const p=function(){let t=Date.now();return function(e){return Math.ceil((t=(9301*t+49297)%233280,t/233280*e))}}();function g(){if("function"==typeof Uint32Array){let t;if("undefined"!=typeof crypto&&(t=crypto),t&&i(t)&&t.getRandomValues)return t.getRandomValues(new Uint32Array(1))[0]/Math.pow(2,32)}return p(1e19)/1e19}const f=function(){function t(t){return("0".repeat(t)+Date.now().toString(16)).slice(-t)}return function(){let e=String(screen.height*screen.width);e=e&&/\d{4,}/.test(e)?e.slice(-4):String(31242*g()).replace(".","").slice(0,4);return t(8)+"-"+g().toString(16).replace(".","").slice(-4)+"-"+function(){const t=navigator.userAgent;let e,n=[],i=0;function s(t,e){let i=0;for(let s=0;s<e.length;s++)i|=n[s]<<8*s;return(t^i)>>>0}for(let r=0;r<t.length;r++)e=t.charCodeAt(r),n.unshift(255&e),n.length>=4&&(i=s(i,n),n=[]);return n.length>0&&(i=s(i,n)),("0000"+i.toString(16)).slice(-4)}()+"-"+e+"-"+t(12)||(String(g())+String(g())+String(g())).slice(2,15)}}();function m(t,e){e&&"string"==typeof e||(e="");let n=null;try{n=new URL(t).hostname}catch(i){}return n||e}function E(t){let e=[];try{e=atob(t).split("").map(function(t){return"%"+("00"+t.charCodeAt(0).toString(16)).slice(-2)})}catch(n){e=[]}try{return decodeURIComponent(e.join(""))}catch(n){return e.join("")}}function _(t){let e="";try{e=btoa(encodeURIComponent(t).replace(/%([0-9A-F]{2})/g,function(t,e){return String.fromCharCode(parseInt(e,16))}))}catch(n){e=t}return e}const I={get:function(t){return window.localStorage.getItem(t)},parse:function(t){let e;try{e=JSON.parse(I.get(t))||null}catch(n){console.warn(n)}return e},set:function(t,e){try{window.localStorage.setItem(t,e)}catch(n){console.warn(n)}},remove:function(t){window.localStorage.removeItem(t)},isSupport:function(){let t=!0;try{const e="__local_store_support__",n="testIsSupportStorage";I.set(e,n),I.get(e)!==n&&(t=!1),I.remove(e)}catch(e){t=!1}return t}};function S(t){return t.trim()}function w(t){if(!t||"string"!=typeof t)return"";try{return new URL(t,window.location.origin).pathname}catch(e){return""}}const O={},v="1.3.0",b="init-ready",y="spa-switch",A="ff-ready",R="$PageLeave",T="$Exception";var C=(t=>(t[t.FEATURE_GATE=1]="FEATURE_GATE",t[t.FEATURE_CONFIG=2]="FEATURE_CONFIG",t[t.EXPERIMENT=3]="EXPERIMENT",t))(C||{});const N={crossSubdomain:!1,requests:[],_sessionState:{},_abData:[],_trace_id:"",commonProps:{},_state:{anon_id:"",login_id:"",identities:{}},getIdentityCookieID(){return this._state.identities?.$identity_cookie_id||""},getCommonProps:function(){return this.commonProps||{}},setCommonProps:function(t){this.commonProps=t},getAnonId(){return this._state.anon_id||this.getIdentityCookieID()||f()},getLoginId(){return this._state.login_id},getTraceId(){return this._trace_id||f()},set:function(t,e){this._state[t]=e,this.save()},getCookieName:function(){return"sensorswave2025jssdkcross"},getABLSName:function(){return"sensorswave2025jssdkablatest"},save:function(){let t=JSON.parse(JSON.stringify(this._state));t.identities&&(t.identities=_(JSON.stringify(t.identities)));const n=JSON.stringify(t);e.set({name:this.getCookieName(),value:n,expires:365})},init:function(t){let n,s;this.crossSubdomain=t,e.isSupport()&&(n=e.get(this.getCookieName()),s=d(n)),N._state={...s||{}},N._state.identities&&(N._state.identities=d(E(N._state.identities))),N._state.identities&&i(N._state.identities)&&!u(N._state.identities)||(N._state.identities={$identity_cookie_id:f()}),N.save()},setLoginId(t){"number"==typeof t&&(t=String(t)),void 0!==t&&t&&(N.set("login_id",t),N.save())},setAnonId(t){"number"==typeof t&&(t=String(t)),"string"==typeof t&&t?(N.set("anon_id",t),N.save()):console.warn("[SensorsWave store] Invalid anonId, ignored:",t)},saveABData(t){if(!t||u(t))return;this._abData=t;let e=JSON.parse(JSON.stringify(this._abData));e=_(JSON.stringify(e));try{localStorage.setItem(this.getABLSName(),JSON.stringify({time:Date.now(),data:e,anon_id:this.getAnonId(),login_id:this.getLoginId()}))}catch(n){console.warn("Failed to save abdata to localStorage",n)}},getABData(t=6e5){try{let e=localStorage.getItem(this.getABLSName());if(e){const{time:n,data:i,login_id:s,anon_id:r}=d(e)||{};if(n&&i&&Date.now()-n<t&&r===this.getAnonId()&&(!s||s===this.getLoginId())){const t=d(E(i));return this._abData=Array.isArray(t)?t:[],this._abData}localStorage.removeItem(this.getABLSName())}}catch(e){this._abData=[]}return this._abData||[]}};function P(t){return!(t>=400&&t<500)||408===t||429===t}function k(t){var e;if(t.data)return{contentType:"application/json",body:(e=t.data,JSON.stringify(e,(t,e)=>"bigint"==typeof e?e.toString():e,undefined))}}const L=[];function $(t){const e={...t};e.timeout=e.timeout||6e4;const n=e.transport??"fetch",i=L.find(t=>t.transport===n)?.method??L[0]?.method;if(!i)throw new Error("No available transport method for HTTP request");i(e)}function F(t){return o(t=t||document.referrer)&&(t=h(t=t.trim()))||""}function B(t){const e=m(t=t||F());if(!e)return"";const n={baidu:[/^.*\.baidu\.com$/],bing:[/^.*\.bing\.com$/],google:[/^www\.google\.com$/,/^www\.google\.com\.[a-z]{2}$/,/^www\.google\.[a-z]{2}$/],sm:[/^m\.sm\.cn$/],so:[/^.+\.so\.com$/],sogou:[/^.*\.sogou\.com$/],yahoo:[/^.*\.yahoo\.com$/],duckduckgo:[/^.*\.duckduckgo\.com$/]};for(let i of Object.keys(n)){let t=n[i];for(let n=0,s=t.length;n<s;n++)if(t[n].test(e))return i}return""}function x(t,e){return-1!==t.indexOf(e)}"function"==typeof fetch&&L.push({transport:"fetch",method:function(t){if("undefined"==typeof fetch)return void console.error("fetch API is not available");const e=k(t),n=new Headers;t.headers&&Object.keys(t.headers).forEach(e=>{n.append(e,t.headers[e])}),e?.contentType&&n.append("Content-Type",e.contentType),fetch(t.url,{method:t.method||"GET",headers:n,body:e?.body}).then(e=>e.text().then(n=>{const i={statusCode:e.status,text:n};if(200===e.status)try{i.json=JSON.parse(n)}catch(s){console.error("Failed to parse response:",s)}t.callback?.(i)})).catch(e=>{console.error("Request failed:",e),t.callback?.({statusCode:0,text:String(e)})})}}),"undefined"!=typeof XMLHttpRequest&&L.push({transport:"XHR",method:function(t){if("undefined"==typeof XMLHttpRequest)return void console.error("XMLHttpRequest is not available");const e=new XMLHttpRequest;e.open(t.method||"GET",t.url,!0);const n=k(t);t.headers&&Object.keys(t.headers).forEach(n=>{e.setRequestHeader(n,t.headers[n])}),n?.contentType&&e.setRequestHeader("Content-Type",n.contentType),e.timeout=t.timeout||6e4,e.withCredentials=!0,e.onreadystatechange=()=>{if(4===e.readyState){const i={statusCode:e.status,text:e.responseText};if(200===e.status)try{i.json=JSON.parse(e.responseText)}catch(n){console.error("Failed to parse JSON response:",n)}t.callback?.(i)}},e.send(n?.body)}});const M={FACEBOOK:"Facebook",MOBILE:"Mobile",IOS:"iOS",ANDROID:"Android",TABLET:"Tablet",ANDROID_TABLET:"Android Tablet",IPAD:"iPad",APPLE:"Apple",APPLE_WATCH:"Apple Watch",SAFARI:"Safari",BLACKBERRY:"BlackBerry",SAMSUNG_BROWSER:"SamsungBrowser",SAMSUNG_INTERNET:"Samsung Internet",CHROME:"Chrome",CHROME_OS:"Chrome OS",CHROME_IOS:"Chrome iOS",INTERNET_EXPLORER:"Internet Explorer",INTERNET_EXPLORER_MOBILE:"Internet Explorer Mobile",OPERA:"Opera",OPERA_MINI:"Opera Mini",EDGE:"Edge",MICROSOFT_EDGE:"Microsoft Edge",FIREFOX:"Firefox",FIREFOX_IOS:"Firefox iOS",NINTENDO:"Nintendo",PLAYSTATION:"PlayStation",XBOX:"Xbox",ANDROID_MOBILE:"Android Mobile",MOBILE_SAFARI:"Mobile Safari",WINDOWS:"Windows",WINDOWS_PHONE:"Windows Phone",NOKIA:"Nokia",OUYA:"Ouya",GENERIC_MOBILE:"Generic mobile",GENERIC_TABLET:"Generic tablet",KONQUEROR:"Konqueror",UC_BROWSER:"UC Browser",HUAWEI:"Huawei",XIAOMI:"Xiaomi",OPPO:"OPPO",VIVO:"vivo"},D="(\\d+(\\.\\d+)?)",H=new RegExp("Version/"+D),U=new RegExp(M.XBOX,"i"),X=new RegExp(M.PLAYSTATION+" \\w+","i"),j=new RegExp(M.NINTENDO+" \\w+","i"),q=new RegExp(M.BLACKBERRY+"|PlayBook|BB10","i"),W=new RegExp("(HUAWEI|honor|HONOR)","i"),G=new RegExp("(Xiaomi|Redmi)","i"),z=new RegExp("(OPPO|realme)","i"),Y=new RegExp("(vivo|IQOO)","i"),K={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000",5.1:"XP",5.2:"XP","6.0":"Vista",6.1:"7",6.2:"8",6.3:"8.1",6.4:"10","10.0":"10"};function J(t,e){return e=e||"",x(t," OPR/")&&x(t,"Mini")?M.OPERA_MINI:x(t," OPR/")?M.OPERA:q.test(t)?M.BLACKBERRY:x(t,"IE"+M.MOBILE)||x(t,"WPDesktop")?M.INTERNET_EXPLORER_MOBILE:x(t,M.SAMSUNG_BROWSER)?M.SAMSUNG_INTERNET:x(t,M.EDGE)||x(t,"Edg/")?M.MICROSOFT_EDGE:x(t,"FBIOS")?M.FACEBOOK+" "+M.MOBILE:x(t,"UCWEB")||x(t,"UCBrowser")?M.UC_BROWSER:x(t,"CriOS")?M.CHROME_IOS:x(t,"CrMo")||x(t,M.CHROME)?M.CHROME:x(t,M.ANDROID)&&x(t,M.SAFARI)?M.ANDROID_MOBILE:x(t,"FxiOS")?M.FIREFOX_IOS:x(t.toLowerCase(),M.KONQUEROR.toLowerCase())?M.KONQUEROR:function(t,e){return e&&x(e,M.APPLE)||x(n=t,M.SAFARI)&&!x(n,M.CHROME)&&!x(n,M.ANDROID);var n}(t,e)?x(t,M.MOBILE)?M.MOBILE_SAFARI:M.SAFARI:x(t,M.FIREFOX)?M.FIREFOX:x(t,"MSIE")||x(t,"Trident/")?M.INTERNET_EXPLORER:x(t,"Gecko")?M.FIREFOX:""}const Z={[M.INTERNET_EXPLORER_MOBILE]:[new RegExp("rv:"+D)],[M.MICROSOFT_EDGE]:[new RegExp(M.EDGE+"?\\/"+D)],[M.CHROME]:[new RegExp("("+M.CHROME+"|CrMo)\\/"+D)],[M.CHROME_IOS]:[new RegExp("CriOS\\/"+D)],[M.UC_BROWSER]:[new RegExp("(UCBrowser|UCWEB)\\/"+D)],[M.SAFARI]:[H],[M.MOBILE_SAFARI]:[H],[M.OPERA]:[new RegExp("("+M.OPERA+"|OPR)\\/"+D)],[M.FIREFOX]:[new RegExp(M.FIREFOX+"\\/"+D)],[M.FIREFOX_IOS]:[new RegExp("FxiOS\\/"+D)],[M.KONQUEROR]:[new RegExp("Konqueror[:/]?"+D,"i")],[M.BLACKBERRY]:[new RegExp(M.BLACKBERRY+" "+D),H],[M.ANDROID_MOBILE]:[new RegExp("android\\s"+D,"i")],[M.SAMSUNG_INTERNET]:[new RegExp(M.SAMSUNG_BROWSER+"\\/"+D)],[M.INTERNET_EXPLORER]:[new RegExp("(rv:|MSIE )"+D)],Mozilla:[new RegExp("rv:"+D)]};function Q(t,e){const n=J(t,e),i=Z[n];if(a(i))return null;for(let s=0;s<i.length;s++){const e=i[s],n=t.match(e);if(n)return parseFloat(n[n.length-2])}return null}const V=[[new RegExp(M.XBOX+"; "+M.XBOX+" (.*?)[);]","i"),t=>[M.XBOX,t&&t[1]||""]],[new RegExp(M.NINTENDO,"i"),[M.NINTENDO,""]],[new RegExp(M.PLAYSTATION,"i"),[M.PLAYSTATION,""]],[q,[M.BLACKBERRY,""]],[new RegExp(M.WINDOWS,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[M.WINDOWS_PHONE,""];if(new RegExp(M.MOBILE).test(e)&&!/IEMobile\b/.test(e))return[M.WINDOWS+" "+M.MOBILE,""];const n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){const t=n[1];let i=K[t]||"";return/arm/i.test(e)&&(i="RT"),[M.WINDOWS,i]}return[M.WINDOWS,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>{if(t&&t[3]){const e=[t[3],t[4],t[5]||"0"];return[M.IOS,e.join(".")]}return[M.IOS,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{let e="";return t&&t.length>=3&&(e=a(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+M.ANDROID+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+M.ANDROID+")","i"),t=>{if(t&&t[2]){const e=[t[2],t[3],t[4]||"0"];return[M.ANDROID,e.join(".")]}return[M.ANDROID,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{const e=["Mac OS X",""];if(t&&t[1]){const n=[t[1],t[2],t[3]||"0"];e[1]=n.join(".")}return e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[M.CHROME_OS,""]],[/Linux|debian/i,["Linux",""]]];function tt(){const t=window.innerHeight||document.documentElement.clientHeight||document.body&&document.body.clientHeight||0,e=window.innerWidth||document.documentElement.clientWidth||document.body&&document.body.clientWidth||0,n=navigator.userAgent,i=function(t){for(let e=0;e<V.length;e++){const[n,i]=V[e],s=n.exec(t),r=s&&("function"==typeof i?i(s,t):i);if(r)return r}return["",""]}(n)||["",""];return{$browser:J(n),$browser_version:Q(n),$url:location?.href.substring(0,1e3),$host:location?.host,$viewport_height:t,$viewport_width:e,$lib:"webjs",$lib_version:v,$search_engine:B(),$referrer:F(),$referrer_host:m(r=r||F()),$title:document.title,$language:navigator.language,$model:(s=n,(j.test(s)?M.NINTENDO:X.test(s)?M.PLAYSTATION:U.test(s)?M.XBOX:new RegExp(M.OUYA,"i").test(s)?M.OUYA:new RegExp("("+M.WINDOWS_PHONE+"|WPDesktop)","i").test(s)?M.WINDOWS_PHONE:/iPad/.test(s)?M.IPAD:/iPod/.test(s)?"iPod Touch":/iPhone/.test(s)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(s)?M.APPLE_WATCH:q.test(s)?M.BLACKBERRY:/(kobo)\s(ereader|touch)/i.test(s)?"Kobo":new RegExp(M.NOKIA,"i").test(s)?M.NOKIA:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(s)||/(kf[a-z]+)( bui|\)).+silk\//i.test(s)?"Kindle Fire":W.test(s)?M.HUAWEI:G.test(s)?M.XIAOMI:z.test(s)?M.OPPO:Y.test(s)?M.VIVO:/(Android|ZTE)/i.test(s)?!new RegExp(M.MOBILE).test(s)||/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(s)?/pixel[\daxl ]{1,6}/i.test(s)&&!/pixel c/i.test(s)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(s)||/lmy47v/i.test(s)&&!/QTAQZ3/i.test(s)?M.ANDROID:M.ANDROID_TABLET:M.ANDROID:new RegExp("(pda|"+M.MOBILE+")","i").test(s)?M.GENERIC_MOBILE:new RegExp(M.TABLET,"i").test(s)&&!new RegExp(M.TABLET+" pc","i").test(s)?M.GENERIC_TABLET:"")||""),$os:i?.[0]||"",$os_version:i?.[1]||"",$pathname:location?.pathname,$screen_height:Number(screen.height)||0,$screen_width:Number(screen.width)||0,$timezone_offset:60*-(new Date).getTimezoneOffset()};var s,r}const et=new class{constructor(){this.STORAGE_KEY="sensorswave_unsent_events",this.MAX_QUEUE_SIZE=200,this.MAX_RETRY_COUNT=1,this.MAX_AGE_MS=6048e5,this.queue=[],this.loadFromStorage(),this.cleanupExpiredItems()}loadFromStorage(){try{const t=localStorage.getItem(this.STORAGE_KEY);t&&(this.queue=d(t)||[])}catch(t){console.warn("Failed to load queue from localStorage:",t),this.queue=[]}}cleanupExpiredItems(){const t=Date.now(),e=this.queue.filter(e=>t-e.timestamp<this.MAX_AGE_MS);e.length!==this.queue.length&&(this.queue=e,this.saveToStorage())}saveToStorage(){try{this.cleanupExpiredItems(),this.queue.length>this.MAX_QUEUE_SIZE&&(this.queue=this.queue.slice(-this.MAX_QUEUE_SIZE)),localStorage.setItem(this.STORAGE_KEY,JSON.stringify(this.queue))}catch(t){console.warn("Failed to save queue to localStorage:",t)}}enqueue(t,e,n,i=this.MAX_RETRY_COUNT){try{const s={id:f(),url:t,data:e,headers:n,timestamp:Date.now(),retryCount:0,maxRetries:i};return this.queue.push(s),this.saveToStorage(),s.id}catch(s){return console.warn("Failed to enqueue request:",s),""}}dequeue(t){try{this.queue=this.queue.filter(e=>e.id!==t),this.saveToStorage()}catch(e){console.warn("Failed to dequeue request:",e)}}getAll(){try{return this.cleanupExpiredItems(),[...this.queue]}catch(t){return console.warn("Failed to get queue items:",t),[]}}incrementRetryCount(t){const e=this.queue.find(e=>e.id===t);return!(!e||e.retryCount>=e.maxRetries||(e.retryCount++,this.saveToStorage(),0))}clear(){this.queue=[];try{localStorage.removeItem(this.STORAGE_KEY)}catch(t){console.warn("Failed to clear queue from localStorage:",t)}}getItemById(t){return this.queue.find(e=>e.id===t)}};class nt{constructor(t={}){this.flushTimer=null,this.isFlushing=!1,this.paused=!1,this.destroyed=!1,this.config={maxBatchSize:t.maxBatchSize||20,flushInterval:t.flushInterval||5e3},this.startFlushTimer()}pause(){this.paused=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null)}resume(){this.paused&&(this.paused=!1,this.startFlushTimer())}isPaused(){return this.paused}add(){et.getAll().length>=this.config.maxBatchSize&&this.triggerFlush()}triggerFlush(){this.paused||this.isFlushing||(this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.isFlushing=!0,this.flush())}flush(){const t=et.getAll();if(0===t.length)return this.isFlushing=!1,void this.startFlushTimer();const e=t.slice(0,this.config.maxBatchSize),n=[],i=[];e.forEach(t=>{Array.isArray(t.data)?n.push(...t.data):n.push(t.data),i.push(t.id)});const s=e[e.length-1],r=s.url,o=s.headers;O.instance&&O.instance.config.debug&&console.log(JSON.stringify(n,null,2)),$({url:r,method:"POST",data:n,headers:o,callback:t=>{200===t.statusCode?i.forEach(t=>{et.dequeue(t)}):P(t.statusCode)?console.error("Failed to send batch events:",t):i.forEach(t=>{et.dequeue(t)}),this.isFlushing=!1,this.startFlushTimer()}})}startFlushTimer(){this.destroyed||(this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.flushTimer=setInterval(()=>{et.getAll().length>0&&this.triggerFlush()},this.config.flushInterval))}destroy(){this.destroyed=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.paused||this.flush()}}let it=null;function st(){const t=O.instance;return!(!t||!t.__innerInited)||(console.warn("[SensorsWave] SDK is not initialized. Please call init() first."),!1)}function rt(){const t=O.instance;return!t||"function"!=typeof t.hasOptedOutCapturing||!t.hasOptedOutCapturing()}let ot=null;function at(){return I.isSupport()?(ot||(it||(it=new nt({maxBatchSize:20,flushInterval:5e3})),ot=it),ot):null}function ct(t,e,n){if(rt())return $({url:t,method:"POST",data:e.data,headers:e.headers,callback:t=>{if(200!==t.statusCode){if(!P(t.statusCode))return void(n&&et.dequeue(n));if(n&&et.incrementRetryCount(n)){const t=et.getItemById(n);if(t){const e=Math.min(1e3*Math.pow(2,t.retryCount),3e4);setTimeout(()=>{ct(t.url,{data:t.data,headers:t.headers},t.id)},e)}}}else n&&et.dequeue(n),e.callback&&e.callback(t.json)}})}function ut(t){return`${t.apiHost}/in/track`}function lt(t){return`${t.apiHost}/ab/evalall`}function ht(t){return{"Content-Type":"application/json",SourceToken:t.sourceToken}}function dt(t,e,n){O.instance&&O.instance.config.debug&&console.log(JSON.stringify(e.data,null,2));const i=et.enqueue(t,e.data,e.headers);return ct(t,{...e,callback:void 0},i)}function pt(){try{const t=sessionStorage.getItem("sensorswave_utm");if(!t)return{};const e=JSON.parse(t),n={};return Object.entries(e).forEach(([t,e])=>{null!=e&&""!==e&&(n[`$${t}`]=e)}),n}catch(t){return{}}}function gt(t){const e={};return Object.entries(t).forEach(([t,n])=>{if("function"==typeof n)try{const i=n();e[t]=i}catch(i){console.warn("[SensorsWave] Failed to resolve dynamic property:",t,i)}else e[t]=n}),e}function ft(t={},e=!0){const n={...e?tt():{},...gt(N.getCommonProps()),...t},i=pt();return Object.keys(i).length>0&&Object.assign(n,i),n}function mt(t,e,n=!0){if(!st())return;if(!rt())return;const i={time:Date.now(),trace_id:N.getTraceId(),event:t.event,properties:ft(t.properties,n)},s=pt();Object.keys(s).length>0&&(i.user_properties||(i.user_properties={}),i.user_properties.$set||(i.user_properties.$set={}),Object.assign(i.user_properties.$set,s)),t.user_properties&&(t.user_properties.$set&&(i.user_properties=i.user_properties||{},i.user_properties.$set={...i.user_properties.$set||{},...t.user_properties.$set},delete t.user_properties.$set),i.user_properties={...i.user_properties,...t.user_properties});const r=N.getLoginId(),o=N.getAnonId();r&&(i.login_id=r),o&&(i.anon_id=o);const a=ut(e),c=ht(e),u=!1!==e.batchSend&&at();u?(et.enqueue(a,[i],c),u.add()):dt(a,{data:[i],headers:c})}function Et({userProps:t,opts:e}){if(!st())return;if(!rt())return;const n=N.getLoginId(),i=N.getAnonId();if(!n&&!i)return;const s={time:Date.now(),trace_id:N.getTraceId(),event:"$UserSet",login_id:n,anon_id:i,user_properties:t,properties:ft()},r=ut(e),o=ht(e),a=at();if(!a)return dt(r,{data:[s],headers:o});et.enqueue(r,[s],o),a.add()}function _t(t){return t.typ===C.FEATURE_GATE||t.typ===C.FEATURE_CONFIG?`$feature_${t.id}`:t.typ===C.EXPERIMENT?`$exp_${t.id}`:""}function It(t){const e=t.typ;return[C.FEATURE_GATE,C.EXPERIMENT,C.FEATURE_CONFIG].includes(e)?{[_t(t)]:t.vid}:{}}function St(t){const e=t.typ;return e===C.FEATURE_GATE||e===C.FEATURE_CONFIG?{$feature_key:t.key,$feature_variant:t.vid}:e===C.EXPERIMENT?{$exp_key:t.key,$exp_variant:t.vid}:{}}function wt({isUnset:t=!1,data:e,opts:n}){if(!st())return;if(!rt())return;if(!e||u(e)||e.disable_impress)return;const i=N.getLoginId(),s=N.getAnonId();if(!i&&!s)return;const r=e.typ===C.EXPERIMENT?"$ExpImpress":"$FeatureImpress";let o={};return o=t?{$unset:{[_t(e)]:null}}:{$set:{...It(e)}},mt({event:r,properties:St(e),user_properties:o},n)}const Ot="sensorswave_opt_out";class vt{constructor(t){this.persist=t}read(){if(this.persist)try{const t=I.get(Ot);return"0"===t||"1"!==t&&void 0}catch{return}}write(t){if(this.persist)try{I.set(Ot,t?"0":"1")}catch{}}}class bt{constructor({plugins:t,emitter:e,config:n,sdk:i}){this.plugins=[],this.pluginInsMap={},this.emitter=e,this.config=n,this.sdk=i,this.registerBuiltInPlugins(t),this.created(),this.emitter.on(b,()=>{this.init()})}registerBuiltInPlugins(t){for(let e=0,n=t.length;e<n;e++)this.registerPlugin(t[e])}registerPlugin(t){this.plugins.push(t)}getPlugins(){return this.plugins}getPlugin(t){return this.pluginInsMap[t]}created(){for(let t=0,e=this.plugins.length;t<e;t++){const e=this.plugins[t];if(!e.NAME)throw new Error('Plugin should be defined with "NAME"');const n=new e({emitter:this.emitter,config:this.config,sdk:this.sdk});this.pluginInsMap[e.NAME]=n}}init(){for(const t of Object.keys(this.pluginInsMap)){const e=this.pluginInsMap[t];e.init&&e.init()}}destroy(){for(const t of Object.keys(this.pluginInsMap)){const e=this.pluginInsMap[t];e.destroy&&"function"==typeof e.destroy&&e.destroy()}this.pluginInsMap={},this.plugins=[]}}const yt=class{constructor({emitter:t,config:e,sdk:n}){this.boundSend=null,this.hashEvent=null,this.spaSwitchHandler=null,this.emitter=t,this.config=e,this.sdk=n}init(){const t=this.config;this.boundSend=()=>{mt({event:"$PageView",properties:{}},t)},this.sdk&&!0===this.sdk._postConsentInit||setTimeout(()=>{this.boundSend()},0),t.isSinglePageApp&&this.addSinglePageListener()}addSinglePageListener(){this.spaSwitchHandler=t=>{t!==location.href&&this.boundSend()},this.emitter.on(y,this.spaSwitchHandler)}destroy(){this.spaSwitchHandler&&(this.emitter.off(y,this.spaSwitchHandler),this.spaSwitchHandler=null),this.hashEvent&&this.boundSend&&(window.removeEventListener(this.hashEvent,this.boundSend),this.hashEvent=null),this.boundSend=null}};yt.NAME="pageview";let At=yt;const Rt=class{constructor({emitter:t,config:e,sdk:n}){this.startTime=Date.now(),this.pageShowStatus=!0,this.pageHiddenStatus=!1,this.timer=null,this.currentPageUrl=document.referrer,this.url=location.href,this.title=document.title||"",this.heartbeatIntervalTime=5e3,this.heartbeatIntervalTimer=null,this.pageId=null,this.storageName="sensorswavewebjssdkpageleave",this.maxDuration=432e3,this.eventListeners=[],this._skipFirstPageEnd=!1,this.emitter=t,this.config=e,this.sdk=n}__canCapture(){return!this.sdk||"function"!=typeof this.sdk.hasOptedOutCapturing||!this.sdk.hasOptedOutCapturing()}init(){this.pageId=Number(String(g()).slice(2,5)+String(g()).slice(2,4)+String(Date.now()).slice(-4)),this.addEventListener(),this.sdk&&!0===this.sdk._postConsentInit&&(this._skipFirstPageEnd=!0),!0===document.hidden?this.pageShowStatus=!1:this.addHeartBeatInterval()}log(t){console.log(t)}refreshPageEndTimer(){this.timer&&(clearTimeout(this.timer),this.timer=null),this.timer=setTimeout(()=>{this.pageHiddenStatus=!1},5e3)}hiddenStatusHandler(){this.timer&&clearTimeout(this.timer),this.timer=null,this.pageHiddenStatus=!1}pageStartHandler(){this.startTime=Date.now(),1==!document.hidden?this.pageShowStatus=!0:this.pageShowStatus=!1,this.url=location.href,this.title=document.title,this._skipFirstPageEnd=!1}pageEndHandler(){if(!0===this.pageHiddenStatus)return;if(!this.__canCapture())return;const t=this.getPageLeaveProperties();!1===this.pageShowStatus&&delete t.$event_duration,this.pageShowStatus=!1,this.pageHiddenStatus=!0,mt({event:R,properties:t},this.config),this.refreshPageEndTimer(),this.delHeartBeatData()}addEventListener(){this.addPageStartListener(),this.addPageSwitchListener(),this.addSinglePageListener(),this.addPageEndListener()}addPageStartListener(){if("onpageshow"in window){const t=()=>{this.pageStartHandler(),this.hiddenStatusHandler()};window.addEventListener("pageshow",t),this.eventListeners.push({target:window,event:"pageshow",handler:t})}}addSinglePageListener(){this.config.isSinglePageApp&&this.emitter.on(y,t=>{t!==location.href&&(this.url=t,this.pageEndHandler(),this.stopHeartBeatInterval(),this.currentPageUrl=this.url,this.pageStartHandler(),this.hiddenStatusHandler(),this.addHeartBeatInterval())})}addPageEndListener(){["pagehide","beforeunload"].forEach(t=>{if(`on${t}`in window){const e=()=>{if(this._skipFirstPageEnd)return this._skipFirstPageEnd=!1,void this.stopHeartBeatInterval();this.pageEndHandler(),this.stopHeartBeatInterval()};window.addEventListener(t,e),this.eventListeners.push({target:window,event:t,handler:e})}})}addPageSwitchListener(){const t=()=>{"visible"===document.visibilityState?(this.pageStartHandler(),this.hiddenStatusHandler(),this.addHeartBeatInterval()):(this.url=location.href,this.title=document.title,this.stopHeartBeatInterval())};document.addEventListener("visibilitychange",t),this.eventListeners.push({target:document,event:"visibilitychange",handler:t})}addHeartBeatInterval(){I.isSupport()&&this.startHeartBeatInterval()}startHeartBeatInterval(){this.heartbeatIntervalTimer&&this.stopHeartBeatInterval(),this.sdk&&!0===this.sdk._postConsentInit&&!0===this._skipFirstPageEnd||(this.heartbeatIntervalTimer=setInterval(()=>{this.saveHeartBeatData()},this.heartbeatIntervalTime),this.saveHeartBeatData("is_first_heartbeat"),this.reissueHeartBeatData())}stopHeartBeatInterval(){this.heartbeatIntervalTimer&&clearInterval(this.heartbeatIntervalTimer),this.heartbeatIntervalTimer=null}saveHeartBeatData(t){if(!this.__canCapture())return;const e=this.getPageLeaveProperties();e.$time=Date.now(),"is_first_heartbeat"===t&&(e.$event_duration=3);const n={type:"track",event:R,properties:e,time:e.$time};n.heartbeat_interval_time=this.heartbeatIntervalTime,I.isSupport()&&I.set(`${this.storageName}-${this.pageId}`,JSON.stringify(n))}delHeartBeatData(t){I.isSupport()&&I.remove(t||`${this.storageName}-${this.pageId}`)}reissueHeartBeatData(){if(this.__canCapture())for(let t=window.localStorage.length-1;t>=0;t--){const e=window.localStorage.key(t);if(e&&e!==`${this.storageName}-${this.pageId}`&&0===e.indexOf(`${this.storageName}-`)){const t=I.parse(e);i(t)&&Date.now()-t.time>t.heartbeat_interval_time+5e3&&(delete t.heartbeat_interval_time,t._flush_time=(new Date).getTime(),mt({event:R,properties:t?.properties},this.config),this.delHeartBeatData(e))}}}getPageLeaveProperties(){let t=(Date.now()-this.startTime)/1e3;(isNaN(t)||t<0||t>this.maxDuration)&&(t=0),t=Number(t.toFixed(3));const e={$title:this.title,$url:this.url?.substring(0,1e3),$pathname:w(this.url)};return 0!==t&&(e.$event_duration=t),e}destroy(){this.eventListeners.forEach(({target:t,event:e,handler:n})=>{t.removeEventListener(e,n)}),this.eventListeners=[],this.timer&&(clearTimeout(this.timer),this.timer=null),this.heartbeatIntervalTimer&&(clearInterval(this.heartbeatIntervalTimer),this.heartbeatIntervalTimer=null)}};Rt.NAME="pageleave";let Tt=Rt;const Ct=class{constructor({emitter:t,config:e,sdk:n}){this.eventSended=!1,this.emitter=t,this.config=e,this.sdk=n}init(){if(this.sdk&&!0===this.sdk._postConsentInit)return;const t=()=>{let e=0;const n={};if(window.performance){e=function(){let t=0;if("function"==typeof performance.getEntriesByType){const e=performance.getEntriesByType("navigation");e.length>0&&(t=e[0].domContentLoadedEventEnd||0)}return t}();const t=function(){if(performance.getEntries&&"function"==typeof performance.getEntries){const t=performance.getEntries();let e=0;for(const n of t)"transferSize"in n&&(e+=n.transferSize);if("number"==typeof e&&e>=0&&e<10737418240)return Number((e/1024).toFixed(3))}}();t&&(n.$page_resource_size=t)}else console.warn("Performance API is not supported.");e>0&&!Number.isFinite(e)&&(n.$event_duration=Number((e/1e3).toFixed(3))),this.eventSended||(this.eventSended=!0,mt({event:"$PageLoad",properties:n},this.config)),window.removeEventListener("load",t)};"complete"===document.readyState?t():window.addEventListener&&window.addEventListener("load",t)}};Ct.NAME="pageload";let Nt=Ct;function Pt(t,e){if(!l(t))return!1;const n=o(t.tagName)?t.tagName.toLowerCase():"",i={};i.$element_type=n,i.$element_name=t.getAttribute("name")||"",i.$element_id=t.getAttribute("id")||"",i.$element_class_name=o(t.className)?t.className:"",i.$element_target_url=t.getAttribute("href")||"",i.$element_content=function(t,e){return o(e)&&"input"===e.toLowerCase()?("button"===(n=t).type||"submit"===n.type)&&n.value||"":function(t,e){let n="",i="";return t.textContent?n=S(t.textContent):t.innerText&&(n=S(t.innerText)),n&&(n=n.replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)),i=n||"","input"!==e&&"INPUT"!==e||(i=t.value||""),i}(t,e);var n}(t,n)||"",i.$element_selector=kt(t)||"",i.$element_path=function(t){let e=[];for(;t.parentNode&&l(t);){if(!o(t.tagName))return"";if(t.id&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(t.id)){e.unshift(t.tagName.toLowerCase()+"#"+t.id);break}if(t===document.body){e.unshift("body");break}e.unshift(t.tagName.toLowerCase()),t=t.parentNode}return e.join(" > ")}(t)||"";const s=function(t,e){const n=e.pageX||e.clientX+Lt().scrollLeft||e.offsetX+$t(t).targetEleX,i=e.pageY||e.clientY+Lt().scrollTop||e.offsetY+$t(t).targetEleY;return{$page_x:Ft(n),$page_y:Ft(i)}}(t,e);return i.$page_x=s.$page_x,i.$page_y=s.$page_y,i}function kt(t,e=[]){if(!(t&&t.parentNode&&t.parentNode.children&&o(t.tagName)))return"";e=Array.isArray(e)?e:[];const n=t.nodeName.toLowerCase();return t&&"body"!==n&&1==t.nodeType?(e.unshift(function(t){if(!t||!l(t)||!o(t.tagName))return"";let e=t.parentNode&&9==t.parentNode.nodeType?-1:function(t){if(!t.parentNode)return-1;let e=0;const n=t.tagName,i=t.parentNode.children;for(let s=0,r=i.length;s<r;s++)if(i[s].tagName===n){if(t===i[s])return e;e++}return-1}(t);return t.getAttribute&&t.getAttribute("id")&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(t.getAttribute("id"))?"#"+t.getAttribute("id"):t.tagName.toLowerCase()+(~e?":nth-of-type("+(e+1)+")":"")}(t)),t.getAttribute&&t.getAttribute("id")&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(t.getAttribute("id"))?e.join(" > "):kt(t.parentNode,e)):(e.unshift("body"),e.join(" > "))}function Lt(){return{scrollLeft:document.body.scrollLeft||document.documentElement.scrollLeft||0,scrollTop:document.body.scrollTop||document.documentElement.scrollTop||0}}function $t(t){if(document.documentElement.getBoundingClientRect){const e=t.getBoundingClientRect();return{targetEleX:e.left+Lt().scrollLeft||0,targetEleY:e.top+Lt().scrollTop||0}}return{targetEleX:0,targetEleY:0}}function Ft(t){return Number(Number(t).toFixed(3))}const Bt=class{constructor({emitter:t,config:e}){this.isInitialized=!1,this.boundHandleClick=null,this.emitter=t,this.config=e}init(){this.isInitialized||(this.boundHandleClick=this.handleClick.bind(this),document.addEventListener("click",this.boundHandleClick,!0),this.isInitialized=!0)}handleClick(t){const e=t.target;if(!e)return;if(!["A","INPUT","BUTTON","TEXTAREA"].includes(e.tagName))return;if("true"===e.getAttribute("sensorswave-disable"))return;mt({event:"$WebClick",properties:Pt(e,t)||{}},this.config)}destroy(){this.boundHandleClick&&(document.removeEventListener("click",this.boundHandleClick,!0),this.boundHandleClick=null),this.isInitialized=!1}};Bt.NAME="webclick";let xt=Bt;const Mt=class{constructor({emitter:t,config:e,sdk:n}){this.updateInterval=null,this.fetchingPromise=null,this.emitter=t,this.config=e,this.sdk=n}init(){const t=this.config;if(t.enableAB){if(this.sdk&&"function"==typeof this.sdk.hasOptedOutCapturing&&this.sdk.hasOptedOutCapturing())return;this.fastFetch().then(()=>{this.emitter.emit(A)}),t.abRefreshInterval<3e4&&(t.abRefreshInterval=3e4),this.updateInterval=setInterval(()=>{this.fetchNewData().catch(console.warn)},t.abRefreshInterval)}}async fastFetch(){const t=N.getABData(this.config.abRefreshInterval);return t&&t.length?(this.emitter.emit(A),Promise.resolve(t)):this.fetchNewData()}async fetchNewData(){return this.fetchingPromise||(this.fetchingPromise=new Promise(t=>{!function({opts:t,cb:e}){if(!st())return void(e&&e({}));if(!rt())return void(e&&e({}));const n=N.getLoginId(),i=N.getAnonId();if(!n&&!i)return void(e&&e({}));const s={user:{login_id:n||"",anon_id:i||"",props:{...tt(),...gt(N.getCommonProps())}},sdk:"webjs",sdk_version:v};$({url:lt(t),method:"POST",data:s,headers:ht(t),callback:t=>{200!==t.statusCode?(console.error("Failed to fetch feature flags"),e&&e({})):e&&e(t.json)}})}({opts:this.config,cb:e=>{N.saveABData(e?.data?.results||[]),t(e),this.fetchingPromise=null}})})),this.fetchingPromise}async getFeatureGate(t){return await this.fastFetch().catch(console.warn),N.getABData(this.config.abRefreshInterval).find(e=>e.typ===C.FEATURE_GATE&&e.key==t)}async checkFeatureGate(t){const e=await this.getFeatureGate(t);return!!e&&(!e.hasOwnProperty("vid")&&e.key?(wt({isUnset:!0,data:e,opts:this.config}),!1):(wt({data:e,opts:this.config}),"fail"!==e.vid))}async getExperiment(t){await this.fastFetch().catch(console.warn);const e=N.getABData(this.config.abRefreshInterval).find(e=>e.typ===C.EXPERIMENT&&e.key===t);return e?!e.hasOwnProperty("vid")&&e.key?(wt({isUnset:!0,data:e,opts:this.config}),{}):(wt({data:e,opts:this.config}),e?.value||{}):{}}async getFeatureConfig(t){await this.fastFetch().catch(console.warn);const e=N.getABData(this.config.abRefreshInterval).find(e=>e.typ===C.FEATURE_CONFIG&&e.key===t);if(!e)return{};if(!e.hasOwnProperty("vid")&&e.key)return wt({isUnset:!0,data:e,opts:this.config}),{};wt({data:e,opts:this.config});const n=e?.value;if(n){if(i(n))return n;try{return JSON.parse(n)}catch{return n}}return{}}destroy(){this.updateInterval&&(clearInterval(this.updateInterval),this.updateInterval=null),this.fetchingPromise=null}};Mt.NAME="abtest";let Dt=Mt;const Ht=["utm_source","utm_medium","utm_campaign","utm_content","utm_term"],Ut="sensorswave_utm",Xt=class t{constructor({sdk:t,emitter:e,config:n}){this.sdk=t,this.emitter=e,this.config=n}init(){if(this.sdk&&!0===this.sdk._postConsentInit){let e=t.readFromSessionStorage();return e&&0!==Object.keys(e).length||(e=t.captureAndStore(this.config?.debug)),void this.scheduleInitialUTM(e)}const e=t.getUTMFromURL();t.saveToSessionStorage(e,this.config?.debug),this.scheduleInitialUTM(e)}scheduleInitialUTM(t){setTimeout(()=>{this.sendInitialUTM(t)},0)}static getUTMFromURL(){try{const t=new URLSearchParams(window.location.search),e={};return Ht.forEach(n=>{const i=t.get(n);i&&(e[n]=i)}),e}catch(e){return t.getUTMFromURLFallback()}}static getUTMFromURLFallback(){const t={};return window.location.search.substring(1).split("&").forEach(e=>{const[n,i]=e.split("="),s=decodeURIComponent(n),r=i?decodeURIComponent(i):"";Ht.includes(s)&&(t[s]=r)}),t}static readFromSessionStorage(){try{const t=sessionStorage.getItem(Ut);if(!t)return{};const e=JSON.parse(t);return e&&"object"==typeof e?e:{}}catch(t){return{}}}static saveToSessionStorage(t,e=!1){try{sessionStorage.setItem(Ut,JSON.stringify(t))}catch(n){e&&console.warn("[SensorsWave UTM] Failed to save to sessionStorage:",n)}}static captureAndStore(e=!1){const n=t.getUTMFromURL();return t.saveToSessionStorage(n,e),n}sendInitialUTM(t){const e={};Ht.forEach(n=>{e[`$initial_${n}`]=null!=t[n]?t[n]:""});try{this.sdk.profileSetOnce(e)}catch(n){this.config.debug&&console.warn("[SensorsWave UTM] Failed to send initial UTM:",n)}}destroy(){}};Xt.NAME="UTM";let jt=Xt;const qt=1e3,Wt=/^\s*(?:async\s+)?at\s+(?:(.+)\s+\()?(.+?):(\d+):(\d+)\)?$/,Gt=/^(?:(.*)@)?(.+?):(\d+):(\d+)$/;function zt(t){let e=t;try{const t=location.origin;t&&0===e.indexOf(t)&&(e=e.substring(t.length))}catch(s){}const n=e.indexOf("?");n>-1&&(e=e.substring(0,n));const i=e.indexOf("#");return i>-1&&(e=e.substring(0,i)),e}function Yt(t){return t.map(t=>({platform:"web:javascript",filename:zt(t.file),function:t.fn||"?",lineno:Number(t.line),colno:Number(t.col),abs_path:Kt(t.file,1e3)}))}function Kt(t,e){return t.length>e?t.substring(0,e):t}function Jt(t){let e;if("string"==typeof t)e=t;else if(null!==t&&"object"==typeof t){try{e=JSON.stringify(t)}catch(n){e=Object.prototype.toString.call(t)}e||(e=Object.prototype.toString.call(t))}else e=String(t);return Kt(e,qt)}function Zt(t){const{frames:e,headerType:n}=function(t){const e=[];let n="";if(!t||"string"!=typeof t)return{frames:e,headerType:n};const i=t.split(/\r?\n/);for(let s=0;s<i.length;s++){const t=i[s];if(!t||t.length>1024)continue;const r=t.match(Wt),o=r?null:t.match(Gt),a=r||o;if(a)e.push({fn:a[1]||"?",file:a[2],line:a[3],col:a[4]});else if(0===s){const e=t.indexOf(":");e>0&&(n=t.substring(0,e).trim())}if(e.length>=30)break}return{frames:e,headerType:n}}(t&&t.stack);let i=t&&t.name||n||"Error";return i=Kt(String(i),200),{$exception_level:"error",$exception_type:i,$exception_message:Kt(String(t&&t.message||""),qt),$exception_frames:Yt(e)}}function Qt(t,e,n,i){let s=[];return e&&(s=[{platform:"web:javascript",filename:zt(e),function:"?",lineno:n||0,colno:i||0,abs_path:Kt(e,1e3)}]),{$exception_level:"error",$exception_type:"Error",$exception_message:Kt(String(t||""),qt),$exception_frames:s}}class Vt{constructor(t=10,e=1,n=1e4){this.buckets=new Map,this.bucketSize=t,this.refillRate=e,this.refillInterval=n}allow(t){const e=Date.now();let n=this.buckets.get(t);if(n){if(e>n.lastRefill){const t=Math.floor((e-n.lastRefill)/this.refillInterval)*this.refillRate;t>0&&(n.tokens=Math.min(this.bucketSize,n.tokens+t),n.lastRefill+=t/this.refillRate*this.refillInterval)}}else n={tokens:this.bucketSize,lastRefill:e},this.buckets.set(t,n);return n.tokens>=1&&(n.tokens-=1,!0)}reset(){this.buckets.clear()}}const te=class{constructor({emitter:t,config:e}){this.isInitialized=!1,this.boundHandleError=null,this.boundHandleRejection=null,this.rateLimiter=new Vt,this.emitter=t,this.config=e}init(){this.isInitialized||(this.boundHandleError=this.handleError.bind(this),this.boundHandleRejection=this.handleRejection.bind(this),window.addEventListener("error",this.boundHandleError,!0),window.addEventListener("unhandledrejection",this.boundHandleRejection),this.isInitialized=!0)}handleError(t){try{const e=t.target;let n;if(e&&e!==window&&e.tagName)n=function(t){const e=t,n=(e.tagName||"").toLowerCase(),i=Kt(String(e.src||e.href||""),qt);return{$exception_level:"error",$exception_type:"ResourceLoadError",$exception_message:`Failed to load <${n}>${i?` from ${i}`:""}`,$exception_frames:[]}}(e);else{const e=t;n=e.error instanceof Error?Zt(e.error):Qt(String(e.message||""),e.filename,e.lineno,e.colno)}this.send(n)}catch(e){}}handleRejection(t){try{const e=t.reason;this.send(function(t){return t instanceof Error?Zt(t):{$exception_level:"error",$exception_type:"UnhandledRejection",$exception_message:Jt(t),$exception_frames:[]}}(e))}catch(e){}}send(t){t.$exception_message&&this.rateLimiter.allow(t.$exception_type)&&mt({event:T,properties:t},this.config)}destroy(){this.boundHandleError&&(window.removeEventListener("error",this.boundHandleError,!0),this.boundHandleError=null),this.boundHandleRejection&&(window.removeEventListener("unhandledrejection",this.boundHandleRejection),this.boundHandleRejection=null),this.rateLimiter.reset(),this.isInitialized=!1}};te.NAME="exception";let ee=te;const ne=[],ie={debug:!1,sourceToken:"",apiHost:"",autoCapture:!0,isSinglePageApp:!1,crossSubdomainCookie:!0,enableAB:!1,abRefreshInterval:6e5,enableClickTrack:!1,batchSend:!1,enableErrorTrack:!1,enableCrashTrack:!1,optOutCapturing:!1,persistOptOut:!1},se=new class{constructor(){this.__innerInited=!1,this.inited=!1,this.config={},this.eventEmitter=new t,this.pluginCore={},this.commonProps={},this.spaCleanup=null,this._optOutCapturing=!1,this.consentStorage=new vt(!1),this._setupAfterConsentDone=!1,this._postConsentInit=!1,O.instance=this}init(t,e={}){return this.inited?this:(O.instance=this,e.sourceToken=t,this.mergeConfig(e),this.consentStorage=new vt(!0===this.config.persistOptOut),this._optOutCapturing?this.consentStorage.write(!0):!0===this.config.optOutCapturing?(this._optOutCapturing=!0,this.consentStorage.write(!0)):!0===this.consentStorage.read()&&(this._optOutCapturing=!0),this.eventEmitter.emit("init-param",this.config),this.__innerInited=!0,this._optOutCapturing?(jt.captureAndStore(this.config.debug),this.eventEmitter.emit(b),this.inited=!0,this):(this.__setupAfterConsent(),this.eventEmitter.emit(b),this.inited=!0,this))}__setupAfterConsent(){if(this._setupAfterConsentDone)return;this._setupAfterConsentDone=!0;const t=this.config;ne.length=0,N.init(t.crossSubdomainCookie),t.anonId&&N.setAnonId(t.anonId),function(){if(window._swFailedRequestsInitialized)return;window._swFailedRequestsInitialized=!0;const t=O.instance;t&&"function"==typeof t.hasOptedOutCapturing&&t.hasOptedOutCapturing()||t&&!0===t._postConsentInit||function(){const t=et.getAll();if(0!==t.length)for(let e=0,n=t.length;e<n;e+=10){const n=t.slice(e,e+10),i=[],s=[];n.forEach(t=>{Array.isArray(t.data)?i.push(...t.data):i.push(t.data),s.push(t.id)});const r=n[n.length-1],o=r.url,a=r.headers;$({url:o,method:"POST",data:i,headers:a,callback:t=>{200!==t.statusCode?(console.error("Failed to send batch stored requests:",t),P(t.statusCode)||s.forEach(t=>{et.dequeue(t)})):s.forEach(t=>{et.dequeue(t)})}})}}()}(),ne.push(jt),t.autoCapture&&this.autoTrack(),t.enableAB&&ne.push(Dt),t.enableClickTrack&&ne.push(xt),t.enableCrashTrack&&t.debug&&console.warn("[SensorsWave] enableCrashTrack 仅在 app 宿主环境生效,当前 Web 环境不采集 crash"),t.enableErrorTrack&&ne.push(ee),this.pluginCore=new bt({plugins:ne,emitter:this.eventEmitter,config:t,sdk:this}),this.spaCleanup=function(t){let e=location.href;const n=window.history.pushState,i=window.history.replaceState,r=function(){t(e),e=location.href};return s(window.history.pushState)&&(window.history.pushState=function(...i){n.apply(window.history,i),t(e),e=location.href}),s(window.history.replaceState)&&(window.history.replaceState=function(...n){i.apply(window.history,n),t(e),e=location.href}),window.addEventListener("popstate",r),function(){s(window.history.pushState)&&(window.history.pushState=n),s(window.history.replaceState)&&(window.history.replaceState=i),window.removeEventListener("popstate",r)}}(t=>{this.eventEmitter.emit(y,t)})}mergeConfig(t){this.config={...ie,...t}}__canCapture(){return this.inited&&!this._optOutCapturing}track(t){this.__canCapture()&&function(t,e){if(!st())return;if(!rt())return;const n={...t};n.time||(n.time=Date.now()),n.login_id||(n.login_id=N.getLoginId()),n.anon_id||(n.anon_id=N.getAnonId()),n.trace_id||(n.trace_id=N.getTraceId()),n.properties={...tt(),...gt(N.getCommonProps()),...n.properties};const i=ut(e),s=ht(e),r=!1!==e.batchSend&&at();if(!r)return dt(i,{data:[n],headers:s});et.enqueue(i,[n],s),r.add()}(t,this.config)}trackEvent(t,e){this.__canCapture()&&mt({event:t,properties:e},this.config)}trackException(t,e){if(!this.__canCapture())return;const n={...e||{},...t instanceof Error?Zt(t):Qt(String(t))};mt({event:T,properties:n},this.config)}autoTrack(){ne.push(At,Nt,Tt)}profileSet(t){this.__canCapture()&&Et({userProps:{$set:t},opts:this.config})}profileSetOnce(t){this.__canCapture()&&Et({userProps:{$set_once:t},opts:this.config})}profileIncrement(t){this.__canCapture()&&Et({userProps:{$increment:t},opts:this.config})}profileAppend(t){this.__canCapture()&&Et({userProps:{$append:t},opts:this.config})}profileUnion(t){this.__canCapture()&&Et({userProps:{$union:t},opts:this.config})}profileUnset(t){if(!this.__canCapture())return;const e={};r(t)?t.forEach(function(t){e[t]=null}):e[t]=null,Et({userProps:{$unset:e},opts:this.config})}profileDelete(){this.__canCapture()&&Et({userProps:{$delete:!0},opts:this.config})}registerCommonProperties(t){if(!i(t))return console.warn("Commmon Properties must be an object!");this.commonProps=t,N.setCommonProps(this.commonProps)}clearCommonProperties(t){if(!r(t))return console.warn("Commmon Properties to be cleared must be an array!");t.forEach(t=>{delete this.commonProps[t]}),N.setCommonProps(this.commonProps)}identify(t){this.__canCapture()&&(N.setLoginId(t),function(t){if(!st())return;if(!rt())return;const e=N.getLoginId(),n=N.getAnonId();if(!e||!n)return;const i={time:Date.now(),trace_id:N.getTraceId(),event:"$Identify",login_id:e,anon_id:n,properties:ft()},s=ut(t),r=ht(t),o=at();if(!o)return dt(s,{data:[i],headers:r});et.enqueue(s,[i],r),o.add()}(this.config))}setLoginId(t){this.__canCapture()&&N.setLoginId(t)}getAnonId(){return this.__canCapture()?N.getAnonId():""}setAnonId(t){this.__canCapture()&&N.setAnonId(t)}getLoginId(){return this.__canCapture()?N.getLoginId():""}checkFeatureGate(t){if(!this.__canCapture())return Promise.resolve(!1);const e=this.pluginCore.getPlugin(Dt.NAME);return this.config.enableAB&&e?e.checkFeatureGate(t):Promise.reject("AB is disabled")}getExperiment(t){if(!this.__canCapture())return Promise.resolve({});const e=this.pluginCore.getPlugin(Dt.NAME);return this.config.enableAB&&e?e.getExperiment(t):Promise.reject("AB is disabled")}getFeatureConfig(t){if(!this.__canCapture())return Promise.resolve({});const e=this.pluginCore.getPlugin(Dt.NAME);return this.config.enableAB&&e?e.getFeatureConfig(t):Promise.reject("AB is disabled")}optOutCapturing(){this._optOutCapturing=!0,this.consentStorage.write(!0),ot&&ot.pause()}optInCapturing(){if(this._optOutCapturing=!1,this.consentStorage.write(!1),ot&&ot.resume(),this.inited&&!this._setupAfterConsentDone){this._postConsentInit=!0;try{this.__setupAfterConsent(),this.eventEmitter.emit(b)}finally{this._postConsentInit=!1}}}hasOptedOutCapturing(){return this._optOutCapturing}destroy(){ot&&(ot.destroy(),ot=null),"undefined"!=typeof window&&(window._swFailedRequestsInitialized=!1),this.inited=!1,this.__innerInited=!1,this.spaCleanup&&"function"==typeof this.spaCleanup&&(this.spaCleanup(),this.spaCleanup=null),this.pluginCore&&"function"==typeof this.pluginCore.destroy&&this.pluginCore.destroy(),this.pluginCore={},this.eventEmitter&&this.eventEmitter.removeAllListeners(),this.consentStorage=new vt(!0===this.config?.persistOptOut),this._optOutCapturing=!1,this._setupAfterConsentDone=!1,this._postConsentInit=!1,O.instance===this&&(O.instance=null)}};module.exports=se;
package/dist/index.es.js CHANGED
@@ -1 +1 @@
1
- class e{constructor(){this.listeners={}}on(e,t,n=!1){if(e&&t){if(!s(t))throw new Error("listener must be a function");this.listeners[e]=this.listeners[e]||[],this.listeners[e].push({listener:t,once:n})}}off(e,t){const n=this.listeners[e];if(!n?.length)return;"number"==typeof t&&n.splice(t,1);const i=n.findIndex(e=>e.listener===t);-1!==i&&n.splice(i,1)}emit(e,...t){this.listeners[e]&&this.listeners[e].forEach((n,i)=>{n.listener.call(this,...t),n.listener.once&&this.off(e,i)})}once(e,t){this.on(e,t,!0)}removeAllListeners(e){e?this.listeners[e]=[]:this.listeners={}}}const t={get:function(e){const t=e+"=",n=document.cookie.split(";");for(let i=0,s=n.length;i<s;i++){let e=n[i];for(;" "==e.charAt(0);)e=e.substring(1,e.length);if(0==e.indexOf(t))return h(e.substring(t.length,e.length))}return null},set:function({name:e,value:t,expires:n,samesite:i,secure:s,domain:r}){let o="",a="",c="",l="";if(0!==(n=null==n||void 0===n?365:n)){const e=/* @__PURE__ */new Date;"s"===String(n).slice(-1)?e.setTime(e.getTime()+1e3*Number(String(n).slice(0,-1))):e.setTime(e.getTime()+24*n*60*60*1e3),o="; expires="+e.toUTCString()}function u(e){return e?e.replace(/\r\n/g,""):""}i&&(c="; SameSite="+i),s&&(a="; secure");const h=u(e),d=u(t),g=u(r);g&&(l="; domain="+g),h&&d&&(document.cookie=h+"="+encodeURIComponent(d)+o+"; path=/"+l+c+a)},remove:function(e){this.set({name:e,value:"",expires:-1})},isSupport:function({samesite:e,secure:t}={}){if(!navigator.cookieEnabled)return!1;const n="sensorswave_cookie_support_test";return this.set({name:n,value:"1",samesite:e,secure:t}),"1"===this.get(n)&&(this.remove(n),!0)}},n=Object.prototype.toString;function i(e){return"[object Object]"===n.call(e)}function s(e){const t=n.call(e);return"[object Function]"==t||"[object AsyncFunction]"==t}function r(e){return"[object Array]"==n.call(e)}function o(e){return"[object String]"==n.call(e)}function a(e){return void 0===e}const c=Object.prototype.hasOwnProperty;function l(e){if(i(e)){for(let t in e)if(c.call(e,t))return!1;return!0}return!1}function u(e){return!(!e||1!==e.nodeType)}function h(e){let t=e;try{t=decodeURIComponent(e)}catch(n){t=e}return t}function d(e){try{return JSON.parse(e)}catch(t){return""}}const g=function(){let e=Date.now();return function(t){return Math.ceil((e=(9301*e+49297)%233280,e/233280*t))}}();function p(){if("function"==typeof Uint32Array){let e;if("undefined"!=typeof crypto&&(e=crypto),e&&i(e)&&e.getRandomValues)return e.getRandomValues(new Uint32Array(1))[0]/Math.pow(2,32)}return g(1e19)/1e19}const f=/* @__PURE__ */function(){function e(e){return("0".repeat(e)+Date.now().toString(16)).slice(-e)}return function(){let t=String(screen.height*screen.width);t=t&&/\d{4,}/.test(t)?t.slice(-4):String(31242*p()).replace(".","").slice(0,4);return e(8)+"-"+p().toString(16).replace(".","").slice(-4)+"-"+function(){const e=navigator.userAgent;let t,n=[],i=0;function s(e,t){let i=0;for(let s=0;s<t.length;s++)i|=n[s]<<8*s;return(e^i)>>>0}for(let r=0;r<e.length;r++)t=e.charCodeAt(r),n.unshift(255&t),n.length>=4&&(i=s(i,n),n=[]);return n.length>0&&(i=s(i,n)),("0000"+i.toString(16)).slice(-4)}()+"-"+t+"-"+e(12)||(String(p())+String(p())+String(p())).slice(2,15)}}();function m(e,t){t&&"string"==typeof t||(t="");let n=null;try{n=new URL(e).hostname}catch(i){}return n||t}function E(e){let t=[];try{t=atob(e).split("").map(function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)})}catch(n){t=[]}try{return decodeURIComponent(t.join(""))}catch(n){return t.join("")}}function I(e){let t="";try{t=btoa(encodeURIComponent(e).replace(/%([0-9A-F]{2})/g,function(e,t){return String.fromCharCode(parseInt(t,16))}))}catch(n){t=e}return t}const S={get:function(e){return window.localStorage.getItem(e)},parse:function(e){let t;try{t=JSON.parse(S.get(e))||null}catch(n){console.warn(n)}return t},set:function(e,t){try{window.localStorage.setItem(e,t)}catch(n){console.warn(n)}},remove:function(e){window.localStorage.removeItem(e)},isSupport:function(){let e=!0;try{const t="__local_store_support__",n="testIsSupportStorage";S.set(t,n),S.get(t)!==n&&(e=!1),S.remove(t)}catch(t){e=!1}return e}};function w(e){return e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")}function _(e){if(!e||"string"!=typeof e)return"";try{return new URL(e,window.location.origin).pathname}catch(t){return""}}const O={},A="1.1.8",v="init-ready",R="spa-switch",T="ff-ready",b="$PageLeave";var y=/* @__PURE__ */(e=>(e[e.FEATURE_GATE=1]="FEATURE_GATE",e[e.FEATURE_CONFIG=2]="FEATURE_CONFIG",e[e.EXPERIMENT=3]="EXPERIMENT",e))(y||{});const N={crossSubdomain:!1,requests:[],_sessionState:{},_abData:[],_trace_id:"",commonProps:{},_state:{anon_id:"",login_id:"",identities:{}},getIdentityCookieID(){return this._state.identities?.$identity_cookie_id||""},getCommonProps:function(){return this.commonProps||{}},setCommonProps:function(e){this.commonProps=e},getAnonId(){return this._state.anon_id||this.getIdentityCookieID()||f()},getLoginId(){return this._state.login_id},getTraceId(){return this._trace_id||f()},set:function(e,t){this._state[e]=t,this.save()},getCookieName:function(){return"sensorswave2025jssdkcross"},getABLSName:function(){return"sensorswave2025jssdkablatest"},save:function(){let e=JSON.parse(JSON.stringify(this._state));e.identities&&(e.identities=I(JSON.stringify(e.identities)));const n=JSON.stringify(e);t.set({name:this.getCookieName(),value:n,expires:365})},init:function(e){let n,s;this.crossSubdomain=e,t.isSupport()&&(n=t.get(this.getCookieName()),s=d(n)),N._state={...s||{}},N._state.identities&&(N._state.identities=d(E(N._state.identities))),N._state.identities&&i(N._state.identities)&&!l(N._state.identities)||(N._state.identities={$identity_cookie_id:f()}),N.save()},setLoginId(e){"number"==typeof e&&(e=String(e)),void 0!==e&&e&&(N.set("login_id",e),N.save())},setAnonId(e){"number"==typeof e&&(e=String(e)),"string"==typeof e&&e?(N.set("anon_id",e),N.save()):console.warn("[SensorsWave store] Invalid anonId, ignored:",e)},saveABData(e){if(!e||l(e))return;this._abData=e;let t=JSON.parse(JSON.stringify(this._abData));t=I(JSON.stringify(t));try{localStorage.setItem(this.getABLSName(),JSON.stringify({time:Date.now(),data:t,anon_id:this.getAnonId(),login_id:this.getLoginId()}))}catch(n){console.warn("Failed to save abdata to localStorage",n)}},getABData(e=6e5){try{let t=localStorage.getItem(this.getABLSName());if(t){const{time:n,data:i,login_id:s,anon_id:r}=d(t)||{};if(n&&i&&Date.now()-n<e&&r===this.getAnonId()&&(!s||s===this.getLoginId())){const e=d(E(i));return this._abData=Array.isArray(e)?e:[],this._abData}localStorage.removeItem(this.getABLSName())}}catch(t){console.warn("Failed to load abdata from localStorage",t),this._abData=[]}return this._abData||[]}};function P(e){var t;if(e.data)return{contentType:"application/json",body:(t=e.data,JSON.stringify(t,(e,t)=>"bigint"==typeof t?t.toString():t,undefined))}}const C=[];function L(e){const t={...e};t.timeout=t.timeout||6e4;const n=t.transport??"fetch",i=C.find(e=>e.transport===n)?.method??C[0]?.method;if(!i)throw new Error("No available transport method for HTTP request");i(t)}function B(e){return o(e=e||document.referrer)&&(e=h(e=e.trim()))||""}function F(e){const t=m(e=e||B());if(!t)return"";const n={baidu:[/^.*\.baidu\.com$/],bing:[/^.*\.bing\.com$/],google:[/^www\.google\.com$/,/^www\.google\.com\.[a-z]{2}$/,/^www\.google\.[a-z]{2}$/],sm:[/^m\.sm\.cn$/],so:[/^.+\.so\.com$/],sogou:[/^.*\.sogou\.com$/],yahoo:[/^.*\.yahoo\.com$/],duckduckgo:[/^.*\.duckduckgo\.com$/]};for(let i of Object.keys(n)){let e=n[i];for(let n=0,s=e.length;n<s;n++)if(e[n].test(t))return i}return""}function M(e,t){return-1!==e.indexOf(t)}"function"==typeof fetch&&C.push({transport:"fetch",method:function(e){if("undefined"==typeof fetch)return void console.error("fetch API is not available");const t=P(e),n=new Headers;e.headers&&Object.keys(e.headers).forEach(t=>{n.append(t,e.headers[t])}),t?.contentType&&n.append("Content-Type",t.contentType),fetch(e.url,{method:e.method||"GET",headers:n,body:t?.body}).then(t=>t.text().then(n=>{const i={statusCode:t.status,text:n};if(200===t.status)try{i.json=JSON.parse(n)}catch(s){console.error("Failed to parse response:",s)}e.callback?.(i)})).catch(t=>{console.error("Request failed:",t),e.callback?.({statusCode:0,text:String(t)})})}}),"undefined"!=typeof XMLHttpRequest&&C.push({transport:"XHR",method:function(e){if("undefined"==typeof XMLHttpRequest)return void console.error("XMLHttpRequest is not available");const t=new XMLHttpRequest;t.open(e.method||"GET",e.url,!0);const n=P(e);e.headers&&Object.keys(e.headers).forEach(n=>{t.setRequestHeader(n,e.headers[n])}),n?.contentType&&t.setRequestHeader("Content-Type",n.contentType),t.timeout=e.timeout||6e4,t.withCredentials=!0,t.onreadystatechange=()=>{if(4===t.readyState){const i={statusCode:t.status,text:t.responseText};if(200===t.status)try{i.json=JSON.parse(t.responseText)}catch(n){console.error("Failed to parse JSON response:",n)}e.callback?.(i)}},t.send(n?.body)}});const $={FACEBOOK:"Facebook",MOBILE:"Mobile",IOS:"iOS",ANDROID:"Android",TABLET:"Tablet",ANDROID_TABLET:"Android Tablet",IPAD:"iPad",APPLE:"Apple",APPLE_WATCH:"Apple Watch",SAFARI:"Safari",BLACKBERRY:"BlackBerry",SAMSUNG_BROWSER:"SamsungBrowser",SAMSUNG_INTERNET:"Samsung Internet",CHROME:"Chrome",CHROME_OS:"Chrome OS",CHROME_IOS:"Chrome iOS",INTERNET_EXPLORER:"Internet Explorer",INTERNET_EXPLORER_MOBILE:"Internet Explorer Mobile",OPERA:"Opera",OPERA_MINI:"Opera Mini",EDGE:"Edge",MICROSOFT_EDGE:"Microsoft Edge",FIREFOX:"Firefox",FIREFOX_IOS:"Firefox iOS",NINTENDO:"Nintendo",PLAYSTATION:"PlayStation",XBOX:"Xbox",ANDROID_MOBILE:"Android Mobile",MOBILE_SAFARI:"Mobile Safari",WINDOWS:"Windows",WINDOWS_PHONE:"Windows Phone",NOKIA:"Nokia",OUYA:"Ouya",GENERIC_MOBILE:"Generic mobile",GENERIC_TABLET:"Generic tablet",KONQUEROR:"Konqueror",UC_BROWSER:"UC Browser",HUAWEI:"Huawei",XIAOMI:"Xiaomi",OPPO:"OPPO",VIVO:"vivo"},k="(\\d+(\\.\\d+)?)",D=new RegExp("Version/"+k),x=new RegExp($.XBOX,"i"),H=new RegExp($.PLAYSTATION+" \\w+","i"),U=new RegExp($.NINTENDO+" \\w+","i"),X=new RegExp($.BLACKBERRY+"|PlayBook|BB10","i"),q=new RegExp("(HUAWEI|honor|HONOR)","i"),W=new RegExp("(Xiaomi|Redmi)","i"),G=new RegExp("(OPPO|realme)","i"),j=new RegExp("(vivo|IQOO)","i"),z={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000",5.1:"XP",5.2:"XP","6.0":"Vista",6.1:"7",6.2:"8",6.3:"8.1",6.4:"10","10.0":"10"};function Y(e,t){return t=t||"",M(e," OPR/")&&M(e,"Mini")?$.OPERA_MINI:M(e," OPR/")?$.OPERA:X.test(e)?$.BLACKBERRY:M(e,"IE"+$.MOBILE)||M(e,"WPDesktop")?$.INTERNET_EXPLORER_MOBILE:M(e,$.SAMSUNG_BROWSER)?$.SAMSUNG_INTERNET:M(e,$.EDGE)||M(e,"Edg/")?$.MICROSOFT_EDGE:M(e,"FBIOS")?$.FACEBOOK+" "+$.MOBILE:M(e,"UCWEB")||M(e,"UCBrowser")?$.UC_BROWSER:M(e,"CriOS")?$.CHROME_IOS:M(e,"CrMo")||M(e,$.CHROME)?$.CHROME:M(e,$.ANDROID)&&M(e,$.SAFARI)?$.ANDROID_MOBILE:M(e,"FxiOS")?$.FIREFOX_IOS:M(e.toLowerCase(),$.KONQUEROR.toLowerCase())?$.KONQUEROR:function(e,t){return t&&M(t,$.APPLE)||M(n=e,$.SAFARI)&&!M(n,$.CHROME)&&!M(n,$.ANDROID);var n}(e,t)?M(e,$.MOBILE)?$.MOBILE_SAFARI:$.SAFARI:M(e,$.FIREFOX)?$.FIREFOX:M(e,"MSIE")||M(e,"Trident/")?$.INTERNET_EXPLORER:M(e,"Gecko")?$.FIREFOX:""}const K={[$.INTERNET_EXPLORER_MOBILE]:[new RegExp("rv:"+k)],[$.MICROSOFT_EDGE]:[new RegExp($.EDGE+"?\\/"+k)],[$.CHROME]:[new RegExp("("+$.CHROME+"|CrMo)\\/"+k)],[$.CHROME_IOS]:[new RegExp("CriOS\\/"+k)],[$.UC_BROWSER]:[new RegExp("(UCBrowser|UCWEB)\\/"+k)],[$.SAFARI]:[D],[$.MOBILE_SAFARI]:[D],[$.OPERA]:[new RegExp("("+$.OPERA+"|OPR)\\/"+k)],[$.FIREFOX]:[new RegExp($.FIREFOX+"\\/"+k)],[$.FIREFOX_IOS]:[new RegExp("FxiOS\\/"+k)],[$.KONQUEROR]:[new RegExp("Konqueror[:/]?"+k,"i")],[$.BLACKBERRY]:[new RegExp($.BLACKBERRY+" "+k),D],[$.ANDROID_MOBILE]:[new RegExp("android\\s"+k,"i")],[$.SAMSUNG_INTERNET]:[new RegExp($.SAMSUNG_BROWSER+"\\/"+k)],[$.INTERNET_EXPLORER]:[new RegExp("(rv:|MSIE )"+k)],Mozilla:[new RegExp("rv:"+k)]};function J(e,t){const n=Y(e,t),i=K[n];if(a(i))return null;for(let s=0;s<i.length;s++){const t=i[s],n=e.match(t);if(n)return parseFloat(n[n.length-2])}return null}const Z=[[new RegExp($.XBOX+"; "+$.XBOX+" (.*?)[);]","i"),e=>[$.XBOX,e&&e[1]||""]],[new RegExp($.NINTENDO,"i"),[$.NINTENDO,""]],[new RegExp($.PLAYSTATION,"i"),[$.PLAYSTATION,""]],[X,[$.BLACKBERRY,""]],[new RegExp($.WINDOWS,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[$.WINDOWS_PHONE,""];if(new RegExp($.MOBILE).test(t)&&!/IEMobile\b/.test(t))return[$.WINDOWS+" "+$.MOBILE,""];const n=/Windows NT ([0-9.]+)/i.exec(t);if(n&&n[1]){const e=n[1];let i=z[e]||"";return/arm/i.test(t)&&(i="RT"),[$.WINDOWS,i]}return[$.WINDOWS,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>{if(e&&e[3]){const t=[e[3],e[4],e[5]||"0"];return[$.IOS,t.join(".")]}return[$.IOS,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{let t="";return e&&e.length>=3&&(t=a(e[2])?e[3]:e[2]),["watchOS",t]}],[new RegExp("("+$.ANDROID+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+$.ANDROID+")","i"),e=>{if(e&&e[2]){const t=[e[2],e[3],e[4]||"0"];return[$.ANDROID,t.join(".")]}return[$.ANDROID,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,e=>{const t=["Mac OS X",""];if(e&&e[1]){const n=[e[1],e[2],e[3]||"0"];t[1]=n.join(".")}return t}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[$.CHROME_OS,""]],[/Linux|debian/i,["Linux",""]]];function Q(){const e=window.innerHeight||document.documentElement.clientHeight||document.body&&document.body.clientHeight||0,t=window.innerWidth||document.documentElement.clientWidth||document.body&&document.body.clientWidth||0,n=navigator.userAgent,i=function(e){for(let t=0;t<Z.length;t++){const[n,i]=Z[t],s=n.exec(e),r=s&&("function"==typeof i?i(s,e):i);if(r)return r}return["",""]}(n)||["",""];return{$browser:Y(n),$browser_version:J(n),$url:location?.href.substring(0,1e3),$host:location?.host,$viewport_height:e,$viewport_width:t,$lib:"webjs",$lib_version:A,$search_engine:F(),$referrer:B(),$referrer_host:m(r=r||B()),$title:document.title,$language:navigator.language,$model:(s=n,(U.test(s)?$.NINTENDO:H.test(s)?$.PLAYSTATION:x.test(s)?$.XBOX:new RegExp($.OUYA,"i").test(s)?$.OUYA:new RegExp("("+$.WINDOWS_PHONE+"|WPDesktop)","i").test(s)?$.WINDOWS_PHONE:/iPad/.test(s)?$.IPAD:/iPod/.test(s)?"iPod Touch":/iPhone/.test(s)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(s)?$.APPLE_WATCH:X.test(s)?$.BLACKBERRY:/(kobo)\s(ereader|touch)/i.test(s)?"Kobo":new RegExp($.NOKIA,"i").test(s)?$.NOKIA:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(s)||/(kf[a-z]+)( bui|\)).+silk\//i.test(s)?"Kindle Fire":q.test(s)?$.HUAWEI:W.test(s)?$.XIAOMI:G.test(s)?$.OPPO:j.test(s)?$.VIVO:/(Android|ZTE)/i.test(s)?!new RegExp($.MOBILE).test(s)||/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(s)?/pixel[\daxl ]{1,6}/i.test(s)&&!/pixel c/i.test(s)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(s)||/lmy47v/i.test(s)&&!/QTAQZ3/i.test(s)?$.ANDROID:$.ANDROID_TABLET:$.ANDROID:new RegExp("(pda|"+$.MOBILE+")","i").test(s)?$.GENERIC_MOBILE:new RegExp($.TABLET,"i").test(s)&&!new RegExp($.TABLET+" pc","i").test(s)?$.GENERIC_TABLET:"")||""),$os:i?.[0]||"",$os_version:i?.[1]||"",$pathname:location?.pathname,$screen_height:Number(screen.height)||0,$screen_width:Number(screen.width)||0,$timezone_offset:60*-/* @__PURE__ */(new Date).getTimezoneOffset()};var s,r}const V=new class{constructor(){this.STORAGE_KEY="sensorswave_unsent_events",this.MAX_QUEUE_SIZE=200,this.MAX_RETRY_COUNT=1,this.MAX_AGE_MS=6048e5,this.queue=[],this.loadFromStorage(),this.cleanupExpiredItems()}loadFromStorage(){try{const e=localStorage.getItem(this.STORAGE_KEY);e&&(this.queue=d(e)||[])}catch(e){console.warn("Failed to load queue from localStorage:",e),this.queue=[]}}cleanupExpiredItems(){const e=Date.now(),t=this.queue.filter(t=>e-t.timestamp<this.MAX_AGE_MS);t.length!==this.queue.length&&(this.queue=t,this.saveToStorage())}saveToStorage(){try{this.cleanupExpiredItems(),this.queue.length>this.MAX_QUEUE_SIZE&&(this.queue=this.queue.slice(-this.MAX_QUEUE_SIZE)),localStorage.setItem(this.STORAGE_KEY,JSON.stringify(this.queue))}catch(e){console.warn("Failed to save queue to localStorage:",e)}}enqueue(e,t,n,i=this.MAX_RETRY_COUNT){try{const s={id:f(),url:e,data:t,headers:n,timestamp:Date.now(),retryCount:0,maxRetries:i};return this.queue.push(s),this.saveToStorage(),s.id}catch(s){return console.warn("Failed to enqueue request:",s),""}}dequeue(e){try{this.queue=this.queue.filter(t=>t.id!==e),this.saveToStorage()}catch(t){console.warn("Failed to dequeue request:",t)}}getAll(){try{return this.cleanupExpiredItems(),[...this.queue]}catch(e){return console.warn("Failed to get queue items:",e),[]}}incrementRetryCount(e){const t=this.queue.find(t=>t.id===e);return!(!t||t.retryCount>=t.maxRetries||(t.retryCount++,this.saveToStorage(),0))}clear(){this.queue=[];try{localStorage.removeItem(this.STORAGE_KEY)}catch(e){console.warn("Failed to clear queue from localStorage:",e)}}getItemById(e){return this.queue.find(t=>t.id===e)}};class ee{constructor(e={}){this.flushTimer=null,this.isFlushing=!1,this.config={maxBatchSize:e.maxBatchSize||20,flushInterval:e.flushInterval||5e3},this.startFlushTimer()}add(){V.getAll().length>=this.config.maxBatchSize&&this.triggerFlush()}triggerFlush(){this.isFlushing||(this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.isFlushing=!0,this.flush())}flush(){const e=V.getAll();if(0===e.length)return this.isFlushing=!1,void this.startFlushTimer();const t=[],n=[];e.forEach(e=>{Array.isArray(e.data)?t.push(...e.data):t.push(e.data),n.push(e.id)});const i=t.slice(0,this.config.maxBatchSize),s=e[e.length-1],r=s.url,o=s.headers;O.instance.config.debug&&console.log(JSON.stringify(i,null,2)),L({url:r,method:"POST",data:i,headers:o,callback:e=>{200===e.statusCode?n.forEach(e=>{V.dequeue(e)}):console.error("Failed to send batch events:",e),this.isFlushing=!1,this.startFlushTimer()}})}startFlushTimer(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.flushTimer=setInterval(()=>{V.getAll().length>0&&this.triggerFlush()},this.config.flushInterval)}destroy(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.flush()}}let te=null;function ne(){const e=O.instance;return!(!e||!e.__innerInited)||(console.warn("[SensorsWave] SDK is not initialized. Please call init() first."),!1)}let ie=null;function se(){return S.isSupport()?(ie||(te||(te=new ee({maxBatchSize:20,flushInterval:5e3})),ie=te),ie):null}function re(e,t,n){return L({url:e,method:"POST",data:t.data,headers:t.headers,callback:e=>{if(200!==e.statusCode){if(n)if(V.incrementRetryCount(n)){const e=V.getItemById(n);if(e){const t=Math.min(1e3*Math.pow(2,e.retryCount),3e4);setTimeout(()=>{re(e.url,{data:e.data,headers:e.headers},e.id)},t)}}else console.warn("Max retries reached for request:",n)}else n&&V.dequeue(n),t.callback&&t.callback(e.json)}})}function oe(e){return`${e.apiHost}/in/track`}function ae(e){return`${e.apiHost}/ab/evalall`}function ce(e){return{"Content-Type":"application/json",SourceToken:e.sourceToken}}function le(e,t,n){O.instance.config.debug&&console.log(JSON.stringify(t.data,null,2));const i=V.enqueue(e,t.data,t.headers);return re(e,{...t,callback:void 0},i)}function ue(){try{const e=sessionStorage.getItem("sensorswave_utm");if(!e)return{};const t=JSON.parse(e),n={};return Object.entries(t).forEach(([e,t])=>{null!=t&&""!==t&&(n[`$${e}`]=t)}),n}catch(e){return{}}}function he(e){const t={};return Object.entries(e).forEach(([e,n])=>{if("function"==typeof n)try{const i=n();t[e]=i}catch(i){console.warn("[SensorsWave] Failed to resolve dynamic property:",e,i)}else t[e]=n}),t}function de(e={},t=!0){const n={...t?Q():{},...he(N.getCommonProps()),...e},i=ue();return Object.keys(i).length>0&&Object.assign(n,i),n}function ge(e,t,n=!0){if(!ne())return;const i={time:Date.now(),trace_id:N.getTraceId(),event:e.event,properties:de(e.properties,n)},s=ue();Object.keys(s).length>0&&(i.user_properties||(i.user_properties={}),i.user_properties.$set||(i.user_properties.$set={}),Object.assign(i.user_properties.$set,s)),e.user_properties&&(e.user_properties.$set&&(i.user_properties=i.user_properties||{},i.user_properties.$set={...i.user_properties.$set||{},...e.user_properties.$set},delete e.user_properties.$set),i.user_properties={...i.user_properties,...e.user_properties});const r=N.getLoginId(),o=N.getAnonId();r&&(i.login_id=r),o&&(i.anon_id=o);const a=oe(t),c=ce(t),l=!1!==t.batchSend&&se();l?(V.enqueue(a,[i],c),l.add()):le(a,{data:[i],headers:c})}function pe({userProps:e,opts:t}){if(!ne())return;const n=N.getLoginId(),i=N.getAnonId();if(!n&&!i)return;const s={time:Date.now(),trace_id:N.getTraceId(),event:"$UserSet",login_id:n,anon_id:i,user_properties:e,properties:de()},r=oe(t),o=ce(t),a=se();if(!a)return le(r,{data:[s],headers:o});V.enqueue(r,[s],o),a.add()}function fe(e){return e.typ===y.FEATURE_GATE||e.typ===y.FEATURE_CONFIG?`$feature_${e.id}`:e.typ===y.EXPERIMENT?`$exp_${e.id}`:""}function me(e){const t=e.typ;return[y.FEATURE_GATE,y.EXPERIMENT,y.FEATURE_CONFIG].includes(t)?{[fe(e)]:e.vid}:{}}function Ee(e){const t=e.typ;return t===y.FEATURE_GATE||t===y.FEATURE_CONFIG?{$feature_key:e.key,$feature_variant:e.vid}:t===y.EXPERIMENT?{$exp_key:e.key,$exp_variant:e.vid}:{}}function Ie({isUnset:e=!1,data:t,opts:n}){if(!ne())return;if(!t||l(t)||t.disable_impress)return;const i=N.getLoginId(),s=N.getAnonId();if(!i&&!s)return;const r=t.typ===y.EXPERIMENT?"$ExpImpress":"$FeatureImpress";let o={};return o=e?{$unset:{[fe(t)]:null}}:{$set:{...me(t)}},ge({event:r,properties:Ee(t),user_properties:o},n)}class Se{constructor({plugins:e,emitter:t,config:n,sdk:i}){this.plugins=[],this.pluginInsMap={},this.emitter=t,this.config=n,this.sdk=i,this.registerBuiltInPlugins(e),this.created(),this.emitter.on(v,()=>{this.init()})}registerBuiltInPlugins(e){for(let t=0,n=e.length;t<n;t++)this.registerPlugin(e[t])}registerPlugin(e){this.plugins.push(e)}getPlugins(){return this.plugins}getPlugin(e){return this.pluginInsMap[e]}created(){for(let e=0,t=this.plugins.length;e<t;e++){const t=this.plugins[e];if(!t.NAME)throw new Error('Plugin should be defined with "NAME"');const n=new t({emitter:this.emitter,config:this.config,sdk:this.sdk});this.pluginInsMap[t.NAME]=n}}init(){for(const e of Object.keys(this.pluginInsMap)){const t=this.pluginInsMap[e];t.init&&t.init()}}destroy(){for(const e of Object.keys(this.pluginInsMap)){const t=this.pluginInsMap[e];t.destroy&&"function"==typeof t.destroy&&t.destroy()}this.pluginInsMap={},this.plugins=[]}}const we=class{constructor({emitter:e,config:t}){this.boundSend=null,this.hashEvent=null,this.spaSwitchHandler=null,this.emitter=e,this.config=t}init(){const e=this.config;this.boundSend=()=>{ge({event:"$PageView",properties:{}},e)},setTimeout(()=>{this.boundSend()},0),e.isSinglePageApp&&this.addSinglePageListener()}addSinglePageListener(){this.spaSwitchHandler=e=>{e!==location.href&&this.boundSend()},this.emitter.on(R,this.spaSwitchHandler)}destroy(){this.spaSwitchHandler&&(this.emitter.off(R,this.spaSwitchHandler),this.spaSwitchHandler=null),this.hashEvent&&this.boundSend&&(window.removeEventListener(this.hashEvent,this.boundSend),this.hashEvent=null),this.boundSend=null}};we.NAME="pageview";let _e=we;const Oe=class{constructor({emitter:e,config:t}){this.startTime=Date.now(),this.pageShowStatus=!0,this.pageHiddenStatus=!1,this.timer=null,this.currentPageUrl=document.referrer,this.url=location.href,this.title=document.title||"",this.heartbeatIntervalTime=5e3,this.heartbeatIntervalTimer=null,this.pageId=null,this.storageName="sensorswavewebjssdkpageleave",this.maxDuration=432e3,this.eventListeners=[],this.emitter=e,this.config=t}init(){this.pageId=Number(String(p()).slice(2,5)+String(p()).slice(2,4)+String(Date.now()).slice(-4)),this.addEventListener(),!0===document.hidden?this.pageShowStatus=!1:this.addHeartBeatInterval()}log(e){console.log(e)}refreshPageEndTimer(){this.timer&&(clearTimeout(this.timer),this.timer=null),this.timer=setTimeout(()=>{this.pageHiddenStatus=!1},5e3)}hiddenStatusHandler(){this.timer&&clearTimeout(this.timer),this.timer=null,this.pageHiddenStatus=!1}pageStartHandler(){this.startTime=Date.now(),1==!document.hidden?this.pageShowStatus=!0:this.pageShowStatus=!1,this.url=location.href,this.title=document.title}pageEndHandler(){if(!0===this.pageHiddenStatus)return;const e=this.getPageLeaveProperties();!1===this.pageShowStatus&&delete e.$event_duration,this.pageShowStatus=!1,this.pageHiddenStatus=!0,ge({event:b,properties:e},this.config),this.refreshPageEndTimer(),this.delHeartBeatData()}addEventListener(){this.addPageStartListener(),this.addPageSwitchListener(),this.addSinglePageListener(),this.addPageEndListener()}addPageStartListener(){if("onpageshow"in window){const e=()=>{this.pageStartHandler(),this.hiddenStatusHandler()};window.addEventListener("pageshow",e),this.eventListeners.push({target:window,event:"pageshow",handler:e})}}addSinglePageListener(){this.config.isSinglePageApp&&this.emitter.on(R,e=>{e!==location.href&&(this.url=e,this.pageEndHandler(),this.stopHeartBeatInterval(),this.currentPageUrl=this.url,this.pageStartHandler(),this.hiddenStatusHandler(),this.addHeartBeatInterval())})}addPageEndListener(){["pagehide","beforeunload"].forEach(e=>{if(`on${e}`in window){const t=()=>{this.pageEndHandler(),this.stopHeartBeatInterval()};window.addEventListener(e,t),this.eventListeners.push({target:window,event:e,handler:t})}})}addPageSwitchListener(){const e=()=>{"visible"===document.visibilityState?(this.pageStartHandler(),this.hiddenStatusHandler(),this.addHeartBeatInterval()):(this.url=location.href,this.title=document.title,this.stopHeartBeatInterval())};document.addEventListener("visibilitychange",e),this.eventListeners.push({target:document,event:"visibilitychange",handler:e})}addHeartBeatInterval(){S.isSupport()&&this.startHeartBeatInterval()}startHeartBeatInterval(){this.heartbeatIntervalTimer&&this.stopHeartBeatInterval(),this.heartbeatIntervalTimer=setInterval(()=>{this.saveHeartBeatData()},this.heartbeatIntervalTime),this.saveHeartBeatData("is_first_heartbeat"),this.reissueHeartBeatData()}stopHeartBeatInterval(){this.heartbeatIntervalTimer&&clearInterval(this.heartbeatIntervalTimer),this.heartbeatIntervalTimer=null}saveHeartBeatData(e){const t=this.getPageLeaveProperties();t.$time=Date.now(),"is_first_heartbeat"===e&&(t.$event_duration=3);const n={type:"track",event:b,properties:t,time:t.$time};n.heartbeat_interval_time=this.heartbeatIntervalTime,S.isSupport()&&S.set(`${this.storageName}-${this.pageId}`,JSON.stringify(n))}delHeartBeatData(e){S.isSupport()&&S.remove(e||`${this.storageName}-${this.pageId}`)}reissueHeartBeatData(){for(let e=window.localStorage.length-1;e>=0;e--){const t=window.localStorage.key(e);if(t&&t!==`${this.storageName}-${this.pageId}`&&0===t.indexOf(`${this.storageName}-`)){const e=S.parse(t);i(e)&&Date.now()-e.time>e.heartbeat_interval_time+5e3&&(delete e.heartbeat_interval_time,e._flush_time=/* @__PURE__ */(new Date).getTime(),ge({event:b,properties:e?.properties},this.config),this.delHeartBeatData(t))}}}getPageLeaveProperties(){let e=(Date.now()-this.startTime)/1e3;(isNaN(e)||e<0||e>this.maxDuration)&&(e=0),e=Number(e.toFixed(3));const t={$title:this.title,$url:this.url?.substring(0,1e3),$pathname:_(this.url)};return 0!==e&&(t.$event_duration=e),t}destroy(){this.eventListeners.forEach(({target:e,event:t,handler:n})=>{e.removeEventListener(t,n)}),this.eventListeners=[],this.timer&&(clearTimeout(this.timer),this.timer=null),this.heartbeatIntervalTimer&&(clearInterval(this.heartbeatIntervalTimer),this.heartbeatIntervalTimer=null)}};Oe.NAME="pageleave";let Ae=Oe;const ve=class{constructor({emitter:e,config:t}){this.eventSended=!1,this.emitter=e,this.config=t}init(){const e=()=>{let t=0;const n={};if(window.performance){t=function(){let e=0;if("function"==typeof performance.getEntriesByType){const t=performance.getEntriesByType("navigation");t.length>0&&(e=t[0].domContentLoadedEventEnd||0)}return e}();const e=function(){if(performance.getEntries&&"function"==typeof performance.getEntries){const e=performance.getEntries();let t=0;for(const n of e)"transferSize"in n&&(t+=n.transferSize);if("number"==typeof t&&t>=0&&t<10737418240)return Number((t/1024).toFixed(3))}}();e&&(n.$page_resource_size=e)}else console.warn("Performance API is not supported.");t>0&&!Number.isFinite(t)&&(n.$event_duration=Number((t/1e3).toFixed(3))),this.eventSended||(this.eventSended=!0,ge({event:"$PageLoad",properties:n},this.config)),window.removeEventListener("load",e)};"complete"===document.readyState?e():window.addEventListener&&window.addEventListener("load",e)}};ve.NAME="pageload";let Re=ve;function Te(e,t){if(!u(e))return!1;const n=o(e.tagName)?e.tagName.toLowerCase():"",i={};i.$element_type=n,i.$element_name=e.getAttribute("name")||"",i.$element_id=e.getAttribute("id")||"",i.$element_class_name=o(e.className)?e.className:"",i.$element_target_url=e.getAttribute("href")||"",i.$element_content=function(e,t){return o(t)&&"input"===t.toLowerCase()?("button"===(n=e).type||"submit"===n.type)&&n.value||"":function(e,t){let n="",i="";return e.textContent?n=w(e.textContent):e.innerText&&(n=w(e.innerText)),n&&(n=n.replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)),i=n||"","input"!==t&&"INPUT"!==t||(i=e.value||""),i}(e,t);var n}(e,n)||"",i.$element_selector=be(e)||"",i.$element_path=function(e){let t=[];for(;e.parentNode&&u(e);){if(!o(e.tagName))return"";if(e.id&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(e.id)){t.unshift(e.tagName.toLowerCase()+"#"+e.id);break}if(e===document.body){t.unshift("body");break}t.unshift(e.tagName.toLowerCase()),e=e.parentNode}return t.join(" > ")}(e)||"";const s=function(e,t){const n=t.pageX||t.clientX+ye().scrollLeft||t.offsetX+Ne(e).targetEleX,i=t.pageY||t.clientY+ye().scrollTop||t.offsetY+Ne(e).targetEleY;return{$page_x:Pe(n),$page_y:Pe(i)}}(e,t);return i.$page_x=s.$page_x,i.$page_y=s.$page_y,i}function be(e,t=[]){if(!(e&&e.parentNode&&e.parentNode.children&&o(e.tagName)))return"";t=Array.isArray(t)?t:[];const n=e.nodeName.toLowerCase();return e&&"body"!==n&&1==e.nodeType?(t.unshift(function(e){if(!e||!u(e)||!o(e.tagName))return"";let t=e.parentNode&&9==e.parentNode.nodeType?-1:function(e){if(!e.parentNode)return-1;let t=0;const n=e.tagName,i=e.parentNode.children;for(let s=0,r=i.length;s<r;s++)if(i[s].tagName===n){if(e===i[s])return t;t++}return-1}(e);return e.getAttribute&&e.getAttribute("id")&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(e.getAttribute("id"))?"#"+e.getAttribute("id"):e.tagName.toLowerCase()+(~t?":nth-of-type("+(t+1)+")":"")}(e)),e.getAttribute&&e.getAttribute("id")&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(e.getAttribute("id"))?t.join(" > "):be(e.parentNode,t)):(t.unshift("body"),t.join(" > "))}function ye(){return{scrollLeft:document.body.scrollLeft||document.documentElement.scrollLeft||0,scrollTop:document.body.scrollTop||document.documentElement.scrollTop||0}}function Ne(e){if(document.documentElement.getBoundingClientRect){const t=e.getBoundingClientRect();return{targetEleX:t.left+ye().scrollLeft||0,targetEleY:t.top+ye().scrollTop||0}}return{targetEleX:0,targetEleY:0}}function Pe(e){return Number(Number(e).toFixed(3))}const Ce=class{constructor({emitter:e,config:t}){this.isInitialized=!1,this.boundHandleClick=null,this.emitter=e,this.config=t}init(){this.isInitialized||(this.boundHandleClick=this.handleClick.bind(this),document.addEventListener("click",this.boundHandleClick,!0),this.isInitialized=!0)}handleClick(e){const t=e.target;if(!t)return;if(!["A","INPUT","BUTTON","TEXTAREA"].includes(t.tagName))return;if("true"===t.getAttribute("sensorswave-disable"))return;ge({event:"$WebClick",properties:Te(t,e)||{}},this.config)}destroy(){this.boundHandleClick&&(document.removeEventListener("click",this.boundHandleClick,!0),this.boundHandleClick=null),this.isInitialized=!1}};Ce.NAME="webclick";let Le=Ce;const Be=class{constructor({emitter:e,config:t}){this.updateInterval=null,this.fetchingPromise=null,this.emitter=e,this.config=t}init(){const e=this.config;e.enableAB&&(this.fastFetch().then(()=>{this.emitter.emit(T)}),e.abRefreshInterval<3e4&&(e.abRefreshInterval=3e4),this.updateInterval=setInterval(()=>{this.fetchNewData().catch(console.warn)},e.abRefreshInterval))}async fastFetch(){const e=N.getABData(this.config.abRefreshInterval);return e&&e.length?(this.emitter.emit(T),Promise.resolve(e)):this.fetchNewData()}async fetchNewData(){return this.fetchingPromise||(this.fetchingPromise=new Promise(e=>{!function({opts:e,cb:t}){if(!ne())return void(t&&t({}));const n=N.getLoginId(),i=N.getAnonId();if(!n&&!i)return void(t&&t({}));const s={user:{login_id:n||"",anon_id:i||"",props:{...Q(),...he(N.getCommonProps())}},sdk:"webjs",sdk_version:A};L({url:ae(e),method:"POST",data:s,headers:ce(e),callback:e=>{200!==e.statusCode?(console.error("Failed to fetch feature flags"),t&&t({})):t&&t(e.json)}})}({opts:this.config,cb:t=>{N.saveABData(t?.data?.results||[]),e(t),this.fetchingPromise=null}})})),this.fetchingPromise}async getFeatureGate(e){return await this.fastFetch().catch(console.warn),N.getABData(this.config.abRefreshInterval).find(t=>t.typ===y.FEATURE_GATE&&t.key==e)}async checkFeatureGate(e){const t=await this.getFeatureGate(e);return!!t&&(!t.hasOwnProperty("vid")&&t.key?(Ie({isUnset:!0,data:t,opts:this.config}),!1):(Ie({data:t,opts:this.config}),"fail"!==t.vid))}async getExperiment(e){await this.fastFetch().catch(console.warn);const t=N.getABData(this.config.abRefreshInterval).find(t=>t.typ===y.EXPERIMENT&&t.key===e);return t?!t.hasOwnProperty("vid")&&t.key?(Ie({isUnset:!0,data:t,opts:this.config}),{}):(Ie({data:t,opts:this.config}),t?.value||{}):{}}async getFeatureConfig(e){await this.fastFetch().catch(console.warn);const t=N.getABData(this.config.abRefreshInterval).find(t=>t.typ===y.FEATURE_CONFIG&&t.key===e);if(!t)return{};if(!t.hasOwnProperty("vid")&&t.key)return Ie({isUnset:!0,data:t,opts:this.config}),{};Ie({data:t,opts:this.config});const n=t?.value;if(n){if(i(n))return n;try{return JSON.parse(n)}catch{return n}}return{}}destroy(){this.updateInterval&&(clearInterval(this.updateInterval),this.updateInterval=null),this.fetchingPromise=null}};Be.NAME="abtest";let Fe=Be;const Me=["utm_source","utm_medium","utm_campaign","utm_content","utm_term"],$e=class{constructor({sdk:e,emitter:t,config:n}){this.sdk=e,this.emitter=t,this.config=n}init(){const e=this.getUTMFromURL();this.saveToSessionStorage(e),setTimeout(()=>{this.sendInitialUTM(e)},0)}getUTMFromURL(){try{const e=new URLSearchParams(window.location.search),t={};return Me.forEach(n=>{const i=e.get(n);i&&(t[n]=i)}),t}catch(e){return this.getUTMFromURLFallback()}}getUTMFromURLFallback(){const e={};return window.location.search.substring(1).split("&").forEach(t=>{const[n,i]=t.split("="),s=decodeURIComponent(n),r=i?decodeURIComponent(i):"";Me.includes(s)&&(e[s]=r)}),e}saveToSessionStorage(e){try{sessionStorage.setItem("sensorswave_utm",JSON.stringify(e))}catch(t){this.config.debug&&console.warn("[SensorsWave UTM] Failed to save to sessionStorage:",t)}}sendInitialUTM(e){const t={};Me.forEach(n=>{t[`$initial_${n}`]=null!=e[n]?e[n]:""});try{this.sdk.profileSetOnce(t)}catch(n){this.config.debug&&console.warn("[SensorsWave UTM] Failed to send initial UTM:",n)}}destroy(){}};$e.NAME="UTM";let ke=$e;const De=[],xe={debug:!1,sourceToken:"",apiHost:"",autoCapture:!0,isSinglePageApp:!1,crossSubdomainCookie:!0,enableAB:!1,abRefreshInterval:6e5,enableClickTrack:!1,batchSend:!1},He=new class{constructor(){this.__innerInited=!1,this.inited=!1,this.config={},this.eventEmitter=new e,this.pluginCore={},this.commonProps={},this.spaCleanup=null,O.instance=this}init(e,t={}){if(this.inited)return this;t.sourceToken=e,this.mergeConfig(t),this.eventEmitter.emit("init-param",this.config),this.__innerInited=!0;const n=this.config;return N.init(n.crossSubdomainCookie),n.anonId&&N.setAnonId(n.anonId),window._swFailedRequestsInitialized||(window._swFailedRequestsInitialized=!0,function(){const e=V.getAll();if(0!==e.length)for(let t=0,n=e.length;t<n;t+=10){const n=e.slice(t,t+10),i=[],s=[];n.forEach(e=>{Array.isArray(e.data)?i.push(...e.data):i.push(e.data),s.push(e.id)});const r=n[n.length-1],o=r.url,a=r.headers;L({url:o,method:"POST",data:i,headers:a,callback:e=>{200!==e.statusCode?console.error("Failed to send batch stored requests:",e):s.forEach(e=>{V.dequeue(e)})}})}}()),De.push(ke),n.autoCapture&&this.autoTrack(),n.enableAB&&De.push(Fe),n.enableClickTrack&&De.push(Le),this.pluginCore=new Se({plugins:De,emitter:this.eventEmitter,config:n,sdk:this}),this.spaCleanup=function(e){let t=location.href;const n=window.history.pushState,i=window.history.replaceState,r=function(){e(t),t=location.href};return s(window.history.pushState)&&(window.history.pushState=function(...i){n.apply(window.history,i),e(t),t=location.href}),s(window.history.replaceState)&&(window.history.replaceState=function(...n){i.apply(window.history,n),e(t),t=location.href}),window.addEventListener("popstate",r),function(){s(window.history.pushState)&&(window.history.pushState=n),s(window.history.replaceState)&&(window.history.replaceState=i),window.removeEventListener("popstate",r)}}(e=>{this.eventEmitter.emit(R,e)}),this.eventEmitter.emit(v),this.inited=!0,this}mergeConfig(e){this.config={...xe,...e}}track(e){!function(e,t){if(!ne())return;const n={...e};n.time||(n.time=Date.now()),n.login_id||(n.login_id=N.getLoginId()),n.anon_id||(n.anon_id=N.getAnonId()),n.trace_id||(n.trace_id=N.getTraceId()),n.properties={...Q(),...he(N.getCommonProps()),...n.properties};const i=oe(t),s=ce(t),r=!1!==t.batchSend&&se();if(!r)return le(i,{data:[n],headers:s});V.enqueue(i,[n],s),r.add()}(e,this.config)}trackEvent(e,t){ge({event:e,properties:t},this.config)}autoTrack(){De.push(_e,Re,Ae)}profileSet(e){pe({userProps:{$set:e},opts:this.config})}profileSetOnce(e){pe({userProps:{$set_once:e},opts:this.config})}profileIncrement(e){pe({userProps:{$increment:e},opts:this.config})}profileAppend(e){pe({userProps:{$append:e},opts:this.config})}profileUnion(e){pe({userProps:{$union:e},opts:this.config})}profileUnset(e){const t={};r(e)?e.forEach(function(e){t[e]=null}):t[e]=null,pe({userProps:{$unset:t},opts:this.config})}profileDelete(){pe({userProps:{$delete:!0},opts:this.config})}registerCommonProperties(e){if(!i(e))return console.warn("Commmon Properties must be an object!");this.commonProps=e,N.setCommonProps(this.commonProps)}clearCommonProperties(e){if(!r(e))return console.warn("Commmon Properties to be cleared must be an array!");e.forEach(e=>{delete this.commonProps[e]}),N.setCommonProps(this.commonProps)}identify(e){N.setLoginId(e),function(e){if(!ne())return;const t=N.getLoginId(),n=N.getAnonId();if(!t||!n)return;const i={time:Date.now(),trace_id:N.getTraceId(),event:"$Identify",login_id:t,anon_id:n,properties:de()},s=oe(e),r=ce(e),o=se();if(!o)return le(s,{data:[i],headers:r});V.enqueue(s,[i],r),o.add()}(this.config)}setLoginId(e){N.setLoginId(e)}getAnonId(){return N.getAnonId()}setAnonId(e){N.setAnonId(e)}getLoginId(){return N.getLoginId()}checkFeatureGate(e){const t=this.pluginCore.getPlugin(Fe.NAME);return this.config.enableAB&&t?t.checkFeatureGate(e):Promise.reject("AB is disabled")}getExperiment(e){const t=this.pluginCore.getPlugin(Fe.NAME);return this.config.enableAB&&t?t.getExperiment(e):Promise.reject("AB is disabled")}getFeatureConfig(e){const t=this.pluginCore.getPlugin(Fe.NAME);return this.config.enableAB&&t?t.getFeatureConfig(e):Promise.reject("AB is disabled")}destroy(){ie&&(ie.destroy(),ie=null),this.inited=!1,this.__innerInited=!1,this.spaCleanup&&"function"==typeof this.spaCleanup&&(this.spaCleanup(),this.spaCleanup=null),this.pluginCore&&"function"==typeof this.pluginCore.destroy&&this.pluginCore.destroy(),this.eventEmitter&&this.eventEmitter.removeAllListeners(),O.instance===this&&(O.instance=null)}};export{He as default};
1
+ class t{constructor(){this.listeners={}}on(t,e,n=!1){if(t&&e){if(!s(e))throw new Error("listener must be a function");this.listeners[t]=this.listeners[t]||[],this.listeners[t].push({listener:e,once:n})}}off(t,e){const n=this.listeners[t];if(!n?.length)return;"number"==typeof e&&n.splice(e,1);const i=n.findIndex(t=>t.listener===e);-1!==i&&n.splice(i,1)}emit(t,...e){this.listeners[t]&&this.listeners[t].forEach((n,i)=>{n.listener.call(this,...e),n.listener.once&&this.off(t,i)})}once(t,e){this.on(t,e,!0)}removeAllListeners(t){t?this.listeners[t]=[]:this.listeners={}}}const e={get:function(t){const e=t+"=",n=document.cookie.split(";");for(let i=0,s=n.length;i<s;i++){let t=n[i];for(;" "==t.charAt(0);)t=t.substring(1,t.length);if(0==t.indexOf(e))return h(t.substring(e.length,t.length))}return null},set:function({name:t,value:e,expires:n,samesite:i,secure:s,domain:r}){let o="",a="",c="",u="";if(0!==(n=null==n||void 0===n?365:n)){const t=/* @__PURE__ */new Date;"s"===String(n).slice(-1)?t.setTime(t.getTime()+1e3*Number(String(n).slice(0,-1))):t.setTime(t.getTime()+24*n*60*60*1e3),o="; expires="+t.toUTCString()}function l(t){return t?t.replace(/\r\n/g,""):""}i&&(c="; SameSite="+i),s&&(a="; secure");const h=l(t),d=l(e),p=l(r);p&&(u="; domain="+p),h&&d&&(document.cookie=h+"="+encodeURIComponent(d)+o+"; path=/"+u+c+a)},remove:function(t){this.set({name:t,value:"",expires:-1})},isSupport:function({samesite:t,secure:e}={}){if(!navigator.cookieEnabled)return!1;const n="sensorswave_cookie_support_test";return this.set({name:n,value:"1",samesite:t,secure:e}),"1"===this.get(n)&&(this.remove(n),!0)}},n=Object.prototype.toString;function i(t){return"[object Object]"===n.call(t)}function s(t){const e=n.call(t);return"[object Function]"==e||"[object AsyncFunction]"==e}function r(t){return"[object Array]"==n.call(t)}function o(t){return"[object String]"==n.call(t)}function a(t){return void 0===t}const c=Object.prototype.hasOwnProperty;function u(t){if(i(t)){for(let e in t)if(c.call(t,e))return!1;return!0}return!1}function l(t){return!(!t||1!==t.nodeType)}function h(t){let e=t;try{e=decodeURIComponent(t)}catch(n){e=t}return e}function d(t){try{return JSON.parse(t)}catch(e){return""}}const p=function(){let t=Date.now();return function(e){return Math.ceil((t=(9301*t+49297)%233280,t/233280*e))}}();function g(){if("function"==typeof Uint32Array){let t;if("undefined"!=typeof crypto&&(t=crypto),t&&i(t)&&t.getRandomValues)return t.getRandomValues(new Uint32Array(1))[0]/Math.pow(2,32)}return p(1e19)/1e19}const f=/* @__PURE__ */function(){function t(t){return("0".repeat(t)+Date.now().toString(16)).slice(-t)}return function(){let e=String(screen.height*screen.width);e=e&&/\d{4,}/.test(e)?e.slice(-4):String(31242*g()).replace(".","").slice(0,4);return t(8)+"-"+g().toString(16).replace(".","").slice(-4)+"-"+function(){const t=navigator.userAgent;let e,n=[],i=0;function s(t,e){let i=0;for(let s=0;s<e.length;s++)i|=n[s]<<8*s;return(t^i)>>>0}for(let r=0;r<t.length;r++)e=t.charCodeAt(r),n.unshift(255&e),n.length>=4&&(i=s(i,n),n=[]);return n.length>0&&(i=s(i,n)),("0000"+i.toString(16)).slice(-4)}()+"-"+e+"-"+t(12)||(String(g())+String(g())+String(g())).slice(2,15)}}();function m(t,e){e&&"string"==typeof e||(e="");let n=null;try{n=new URL(t).hostname}catch(i){}return n||e}function E(t){let e=[];try{e=atob(t).split("").map(function(t){return"%"+("00"+t.charCodeAt(0).toString(16)).slice(-2)})}catch(n){e=[]}try{return decodeURIComponent(e.join(""))}catch(n){return e.join("")}}function _(t){let e="";try{e=btoa(encodeURIComponent(t).replace(/%([0-9A-F]{2})/g,function(t,e){return String.fromCharCode(parseInt(e,16))}))}catch(n){e=t}return e}const I={get:function(t){return window.localStorage.getItem(t)},parse:function(t){let e;try{e=JSON.parse(I.get(t))||null}catch(n){console.warn(n)}return e},set:function(t,e){try{window.localStorage.setItem(t,e)}catch(n){console.warn(n)}},remove:function(t){window.localStorage.removeItem(t)},isSupport:function(){let t=!0;try{const e="__local_store_support__",n="testIsSupportStorage";I.set(e,n),I.get(e)!==n&&(t=!1),I.remove(e)}catch(e){t=!1}return t}};function S(t){return t.trim()}function w(t){if(!t||"string"!=typeof t)return"";try{return new URL(t,window.location.origin).pathname}catch(e){return""}}const O={},v="1.3.0",b="init-ready",y="spa-switch",A="ff-ready",R="$PageLeave",T="$Exception";var C=/* @__PURE__ */(t=>(t[t.FEATURE_GATE=1]="FEATURE_GATE",t[t.FEATURE_CONFIG=2]="FEATURE_CONFIG",t[t.EXPERIMENT=3]="EXPERIMENT",t))(C||{});const N={crossSubdomain:!1,requests:[],_sessionState:{},_abData:[],_trace_id:"",commonProps:{},_state:{anon_id:"",login_id:"",identities:{}},getIdentityCookieID(){return this._state.identities?.$identity_cookie_id||""},getCommonProps:function(){return this.commonProps||{}},setCommonProps:function(t){this.commonProps=t},getAnonId(){return this._state.anon_id||this.getIdentityCookieID()||f()},getLoginId(){return this._state.login_id},getTraceId(){return this._trace_id||f()},set:function(t,e){this._state[t]=e,this.save()},getCookieName:function(){return"sensorswave2025jssdkcross"},getABLSName:function(){return"sensorswave2025jssdkablatest"},save:function(){let t=JSON.parse(JSON.stringify(this._state));t.identities&&(t.identities=_(JSON.stringify(t.identities)));const n=JSON.stringify(t);e.set({name:this.getCookieName(),value:n,expires:365})},init:function(t){let n,s;this.crossSubdomain=t,e.isSupport()&&(n=e.get(this.getCookieName()),s=d(n)),N._state={...s||{}},N._state.identities&&(N._state.identities=d(E(N._state.identities))),N._state.identities&&i(N._state.identities)&&!u(N._state.identities)||(N._state.identities={$identity_cookie_id:f()}),N.save()},setLoginId(t){"number"==typeof t&&(t=String(t)),void 0!==t&&t&&(N.set("login_id",t),N.save())},setAnonId(t){"number"==typeof t&&(t=String(t)),"string"==typeof t&&t?(N.set("anon_id",t),N.save()):console.warn("[SensorsWave store] Invalid anonId, ignored:",t)},saveABData(t){if(!t||u(t))return;this._abData=t;let e=JSON.parse(JSON.stringify(this._abData));e=_(JSON.stringify(e));try{localStorage.setItem(this.getABLSName(),JSON.stringify({time:Date.now(),data:e,anon_id:this.getAnonId(),login_id:this.getLoginId()}))}catch(n){console.warn("Failed to save abdata to localStorage",n)}},getABData(t=6e5){try{let e=localStorage.getItem(this.getABLSName());if(e){const{time:n,data:i,login_id:s,anon_id:r}=d(e)||{};if(n&&i&&Date.now()-n<t&&r===this.getAnonId()&&(!s||s===this.getLoginId())){const t=d(E(i));return this._abData=Array.isArray(t)?t:[],this._abData}localStorage.removeItem(this.getABLSName())}}catch(e){this._abData=[]}return this._abData||[]}};function P(t){return!(t>=400&&t<500)||408===t||429===t}function k(t){var e;if(t.data)return{contentType:"application/json",body:(e=t.data,JSON.stringify(e,(t,e)=>"bigint"==typeof e?e.toString():e,undefined))}}const L=[];function $(t){const e={...t};e.timeout=e.timeout||6e4;const n=e.transport??"fetch",i=L.find(t=>t.transport===n)?.method??L[0]?.method;if(!i)throw new Error("No available transport method for HTTP request");i(e)}function F(t){return o(t=t||document.referrer)&&(t=h(t=t.trim()))||""}function B(t){const e=m(t=t||F());if(!e)return"";const n={baidu:[/^.*\.baidu\.com$/],bing:[/^.*\.bing\.com$/],google:[/^www\.google\.com$/,/^www\.google\.com\.[a-z]{2}$/,/^www\.google\.[a-z]{2}$/],sm:[/^m\.sm\.cn$/],so:[/^.+\.so\.com$/],sogou:[/^.*\.sogou\.com$/],yahoo:[/^.*\.yahoo\.com$/],duckduckgo:[/^.*\.duckduckgo\.com$/]};for(let i of Object.keys(n)){let t=n[i];for(let n=0,s=t.length;n<s;n++)if(t[n].test(e))return i}return""}function x(t,e){return-1!==t.indexOf(e)}"function"==typeof fetch&&L.push({transport:"fetch",method:function(t){if("undefined"==typeof fetch)return void console.error("fetch API is not available");const e=k(t),n=new Headers;t.headers&&Object.keys(t.headers).forEach(e=>{n.append(e,t.headers[e])}),e?.contentType&&n.append("Content-Type",e.contentType),fetch(t.url,{method:t.method||"GET",headers:n,body:e?.body}).then(e=>e.text().then(n=>{const i={statusCode:e.status,text:n};if(200===e.status)try{i.json=JSON.parse(n)}catch(s){console.error("Failed to parse response:",s)}t.callback?.(i)})).catch(e=>{console.error("Request failed:",e),t.callback?.({statusCode:0,text:String(e)})})}}),"undefined"!=typeof XMLHttpRequest&&L.push({transport:"XHR",method:function(t){if("undefined"==typeof XMLHttpRequest)return void console.error("XMLHttpRequest is not available");const e=new XMLHttpRequest;e.open(t.method||"GET",t.url,!0);const n=k(t);t.headers&&Object.keys(t.headers).forEach(n=>{e.setRequestHeader(n,t.headers[n])}),n?.contentType&&e.setRequestHeader("Content-Type",n.contentType),e.timeout=t.timeout||6e4,e.withCredentials=!0,e.onreadystatechange=()=>{if(4===e.readyState){const i={statusCode:e.status,text:e.responseText};if(200===e.status)try{i.json=JSON.parse(e.responseText)}catch(n){console.error("Failed to parse JSON response:",n)}t.callback?.(i)}},e.send(n?.body)}});const M={FACEBOOK:"Facebook",MOBILE:"Mobile",IOS:"iOS",ANDROID:"Android",TABLET:"Tablet",ANDROID_TABLET:"Android Tablet",IPAD:"iPad",APPLE:"Apple",APPLE_WATCH:"Apple Watch",SAFARI:"Safari",BLACKBERRY:"BlackBerry",SAMSUNG_BROWSER:"SamsungBrowser",SAMSUNG_INTERNET:"Samsung Internet",CHROME:"Chrome",CHROME_OS:"Chrome OS",CHROME_IOS:"Chrome iOS",INTERNET_EXPLORER:"Internet Explorer",INTERNET_EXPLORER_MOBILE:"Internet Explorer Mobile",OPERA:"Opera",OPERA_MINI:"Opera Mini",EDGE:"Edge",MICROSOFT_EDGE:"Microsoft Edge",FIREFOX:"Firefox",FIREFOX_IOS:"Firefox iOS",NINTENDO:"Nintendo",PLAYSTATION:"PlayStation",XBOX:"Xbox",ANDROID_MOBILE:"Android Mobile",MOBILE_SAFARI:"Mobile Safari",WINDOWS:"Windows",WINDOWS_PHONE:"Windows Phone",NOKIA:"Nokia",OUYA:"Ouya",GENERIC_MOBILE:"Generic mobile",GENERIC_TABLET:"Generic tablet",KONQUEROR:"Konqueror",UC_BROWSER:"UC Browser",HUAWEI:"Huawei",XIAOMI:"Xiaomi",OPPO:"OPPO",VIVO:"vivo"},D="(\\d+(\\.\\d+)?)",H=new RegExp("Version/"+D),U=new RegExp(M.XBOX,"i"),X=new RegExp(M.PLAYSTATION+" \\w+","i"),j=new RegExp(M.NINTENDO+" \\w+","i"),q=new RegExp(M.BLACKBERRY+"|PlayBook|BB10","i"),W=new RegExp("(HUAWEI|honor|HONOR)","i"),G=new RegExp("(Xiaomi|Redmi)","i"),z=new RegExp("(OPPO|realme)","i"),Y=new RegExp("(vivo|IQOO)","i"),K={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000",5.1:"XP",5.2:"XP","6.0":"Vista",6.1:"7",6.2:"8",6.3:"8.1",6.4:"10","10.0":"10"};function J(t,e){return e=e||"",x(t," OPR/")&&x(t,"Mini")?M.OPERA_MINI:x(t," OPR/")?M.OPERA:q.test(t)?M.BLACKBERRY:x(t,"IE"+M.MOBILE)||x(t,"WPDesktop")?M.INTERNET_EXPLORER_MOBILE:x(t,M.SAMSUNG_BROWSER)?M.SAMSUNG_INTERNET:x(t,M.EDGE)||x(t,"Edg/")?M.MICROSOFT_EDGE:x(t,"FBIOS")?M.FACEBOOK+" "+M.MOBILE:x(t,"UCWEB")||x(t,"UCBrowser")?M.UC_BROWSER:x(t,"CriOS")?M.CHROME_IOS:x(t,"CrMo")||x(t,M.CHROME)?M.CHROME:x(t,M.ANDROID)&&x(t,M.SAFARI)?M.ANDROID_MOBILE:x(t,"FxiOS")?M.FIREFOX_IOS:x(t.toLowerCase(),M.KONQUEROR.toLowerCase())?M.KONQUEROR:function(t,e){return e&&x(e,M.APPLE)||x(n=t,M.SAFARI)&&!x(n,M.CHROME)&&!x(n,M.ANDROID);var n}(t,e)?x(t,M.MOBILE)?M.MOBILE_SAFARI:M.SAFARI:x(t,M.FIREFOX)?M.FIREFOX:x(t,"MSIE")||x(t,"Trident/")?M.INTERNET_EXPLORER:x(t,"Gecko")?M.FIREFOX:""}const Z={[M.INTERNET_EXPLORER_MOBILE]:[new RegExp("rv:"+D)],[M.MICROSOFT_EDGE]:[new RegExp(M.EDGE+"?\\/"+D)],[M.CHROME]:[new RegExp("("+M.CHROME+"|CrMo)\\/"+D)],[M.CHROME_IOS]:[new RegExp("CriOS\\/"+D)],[M.UC_BROWSER]:[new RegExp("(UCBrowser|UCWEB)\\/"+D)],[M.SAFARI]:[H],[M.MOBILE_SAFARI]:[H],[M.OPERA]:[new RegExp("("+M.OPERA+"|OPR)\\/"+D)],[M.FIREFOX]:[new RegExp(M.FIREFOX+"\\/"+D)],[M.FIREFOX_IOS]:[new RegExp("FxiOS\\/"+D)],[M.KONQUEROR]:[new RegExp("Konqueror[:/]?"+D,"i")],[M.BLACKBERRY]:[new RegExp(M.BLACKBERRY+" "+D),H],[M.ANDROID_MOBILE]:[new RegExp("android\\s"+D,"i")],[M.SAMSUNG_INTERNET]:[new RegExp(M.SAMSUNG_BROWSER+"\\/"+D)],[M.INTERNET_EXPLORER]:[new RegExp("(rv:|MSIE )"+D)],Mozilla:[new RegExp("rv:"+D)]};function Q(t,e){const n=J(t,e),i=Z[n];if(a(i))return null;for(let s=0;s<i.length;s++){const e=i[s],n=t.match(e);if(n)return parseFloat(n[n.length-2])}return null}const V=[[new RegExp(M.XBOX+"; "+M.XBOX+" (.*?)[);]","i"),t=>[M.XBOX,t&&t[1]||""]],[new RegExp(M.NINTENDO,"i"),[M.NINTENDO,""]],[new RegExp(M.PLAYSTATION,"i"),[M.PLAYSTATION,""]],[q,[M.BLACKBERRY,""]],[new RegExp(M.WINDOWS,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[M.WINDOWS_PHONE,""];if(new RegExp(M.MOBILE).test(e)&&!/IEMobile\b/.test(e))return[M.WINDOWS+" "+M.MOBILE,""];const n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){const t=n[1];let i=K[t]||"";return/arm/i.test(e)&&(i="RT"),[M.WINDOWS,i]}return[M.WINDOWS,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>{if(t&&t[3]){const e=[t[3],t[4],t[5]||"0"];return[M.IOS,e.join(".")]}return[M.IOS,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{let e="";return t&&t.length>=3&&(e=a(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+M.ANDROID+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+M.ANDROID+")","i"),t=>{if(t&&t[2]){const e=[t[2],t[3],t[4]||"0"];return[M.ANDROID,e.join(".")]}return[M.ANDROID,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{const e=["Mac OS X",""];if(t&&t[1]){const n=[t[1],t[2],t[3]||"0"];e[1]=n.join(".")}return e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[M.CHROME_OS,""]],[/Linux|debian/i,["Linux",""]]];function tt(){const t=window.innerHeight||document.documentElement.clientHeight||document.body&&document.body.clientHeight||0,e=window.innerWidth||document.documentElement.clientWidth||document.body&&document.body.clientWidth||0,n=navigator.userAgent,i=function(t){for(let e=0;e<V.length;e++){const[n,i]=V[e],s=n.exec(t),r=s&&("function"==typeof i?i(s,t):i);if(r)return r}return["",""]}(n)||["",""];return{$browser:J(n),$browser_version:Q(n),$url:location?.href.substring(0,1e3),$host:location?.host,$viewport_height:t,$viewport_width:e,$lib:"webjs",$lib_version:v,$search_engine:B(),$referrer:F(),$referrer_host:m(r=r||F()),$title:document.title,$language:navigator.language,$model:(s=n,(j.test(s)?M.NINTENDO:X.test(s)?M.PLAYSTATION:U.test(s)?M.XBOX:new RegExp(M.OUYA,"i").test(s)?M.OUYA:new RegExp("("+M.WINDOWS_PHONE+"|WPDesktop)","i").test(s)?M.WINDOWS_PHONE:/iPad/.test(s)?M.IPAD:/iPod/.test(s)?"iPod Touch":/iPhone/.test(s)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(s)?M.APPLE_WATCH:q.test(s)?M.BLACKBERRY:/(kobo)\s(ereader|touch)/i.test(s)?"Kobo":new RegExp(M.NOKIA,"i").test(s)?M.NOKIA:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(s)||/(kf[a-z]+)( bui|\)).+silk\//i.test(s)?"Kindle Fire":W.test(s)?M.HUAWEI:G.test(s)?M.XIAOMI:z.test(s)?M.OPPO:Y.test(s)?M.VIVO:/(Android|ZTE)/i.test(s)?!new RegExp(M.MOBILE).test(s)||/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(s)?/pixel[\daxl ]{1,6}/i.test(s)&&!/pixel c/i.test(s)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(s)||/lmy47v/i.test(s)&&!/QTAQZ3/i.test(s)?M.ANDROID:M.ANDROID_TABLET:M.ANDROID:new RegExp("(pda|"+M.MOBILE+")","i").test(s)?M.GENERIC_MOBILE:new RegExp(M.TABLET,"i").test(s)&&!new RegExp(M.TABLET+" pc","i").test(s)?M.GENERIC_TABLET:"")||""),$os:i?.[0]||"",$os_version:i?.[1]||"",$pathname:location?.pathname,$screen_height:Number(screen.height)||0,$screen_width:Number(screen.width)||0,$timezone_offset:60*-/* @__PURE__ */(new Date).getTimezoneOffset()};var s,r}const et=new class{constructor(){this.STORAGE_KEY="sensorswave_unsent_events",this.MAX_QUEUE_SIZE=200,this.MAX_RETRY_COUNT=1,this.MAX_AGE_MS=6048e5,this.queue=[],this.loadFromStorage(),this.cleanupExpiredItems()}loadFromStorage(){try{const t=localStorage.getItem(this.STORAGE_KEY);t&&(this.queue=d(t)||[])}catch(t){console.warn("Failed to load queue from localStorage:",t),this.queue=[]}}cleanupExpiredItems(){const t=Date.now(),e=this.queue.filter(e=>t-e.timestamp<this.MAX_AGE_MS);e.length!==this.queue.length&&(this.queue=e,this.saveToStorage())}saveToStorage(){try{this.cleanupExpiredItems(),this.queue.length>this.MAX_QUEUE_SIZE&&(this.queue=this.queue.slice(-this.MAX_QUEUE_SIZE)),localStorage.setItem(this.STORAGE_KEY,JSON.stringify(this.queue))}catch(t){console.warn("Failed to save queue to localStorage:",t)}}enqueue(t,e,n,i=this.MAX_RETRY_COUNT){try{const s={id:f(),url:t,data:e,headers:n,timestamp:Date.now(),retryCount:0,maxRetries:i};return this.queue.push(s),this.saveToStorage(),s.id}catch(s){return console.warn("Failed to enqueue request:",s),""}}dequeue(t){try{this.queue=this.queue.filter(e=>e.id!==t),this.saveToStorage()}catch(e){console.warn("Failed to dequeue request:",e)}}getAll(){try{return this.cleanupExpiredItems(),[...this.queue]}catch(t){return console.warn("Failed to get queue items:",t),[]}}incrementRetryCount(t){const e=this.queue.find(e=>e.id===t);return!(!e||e.retryCount>=e.maxRetries||(e.retryCount++,this.saveToStorage(),0))}clear(){this.queue=[];try{localStorage.removeItem(this.STORAGE_KEY)}catch(t){console.warn("Failed to clear queue from localStorage:",t)}}getItemById(t){return this.queue.find(e=>e.id===t)}};class nt{constructor(t={}){this.flushTimer=null,this.isFlushing=!1,this.paused=!1,this.destroyed=!1,this.config={maxBatchSize:t.maxBatchSize||20,flushInterval:t.flushInterval||5e3},this.startFlushTimer()}pause(){this.paused=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null)}resume(){this.paused&&(this.paused=!1,this.startFlushTimer())}isPaused(){return this.paused}add(){et.getAll().length>=this.config.maxBatchSize&&this.triggerFlush()}triggerFlush(){this.paused||this.isFlushing||(this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.isFlushing=!0,this.flush())}flush(){const t=et.getAll();if(0===t.length)return this.isFlushing=!1,void this.startFlushTimer();const e=t.slice(0,this.config.maxBatchSize),n=[],i=[];e.forEach(t=>{Array.isArray(t.data)?n.push(...t.data):n.push(t.data),i.push(t.id)});const s=e[e.length-1],r=s.url,o=s.headers;O.instance&&O.instance.config.debug&&console.log(JSON.stringify(n,null,2)),$({url:r,method:"POST",data:n,headers:o,callback:t=>{200===t.statusCode?i.forEach(t=>{et.dequeue(t)}):P(t.statusCode)?console.error("Failed to send batch events:",t):i.forEach(t=>{et.dequeue(t)}),this.isFlushing=!1,this.startFlushTimer()}})}startFlushTimer(){this.destroyed||(this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.flushTimer=setInterval(()=>{et.getAll().length>0&&this.triggerFlush()},this.config.flushInterval))}destroy(){this.destroyed=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.paused||this.flush()}}let it=null;function st(){const t=O.instance;return!(!t||!t.__innerInited)||(console.warn("[SensorsWave] SDK is not initialized. Please call init() first."),!1)}function rt(){const t=O.instance;return!t||"function"!=typeof t.hasOptedOutCapturing||!t.hasOptedOutCapturing()}let ot=null;function at(){return I.isSupport()?(ot||(it||(it=new nt({maxBatchSize:20,flushInterval:5e3})),ot=it),ot):null}function ct(t,e,n){if(rt())return $({url:t,method:"POST",data:e.data,headers:e.headers,callback:t=>{if(200!==t.statusCode){if(!P(t.statusCode))return void(n&&et.dequeue(n));if(n&&et.incrementRetryCount(n)){const t=et.getItemById(n);if(t){const e=Math.min(1e3*Math.pow(2,t.retryCount),3e4);setTimeout(()=>{ct(t.url,{data:t.data,headers:t.headers},t.id)},e)}}}else n&&et.dequeue(n),e.callback&&e.callback(t.json)}})}function ut(t){return`${t.apiHost}/in/track`}function lt(t){return`${t.apiHost}/ab/evalall`}function ht(t){return{"Content-Type":"application/json",SourceToken:t.sourceToken}}function dt(t,e,n){O.instance&&O.instance.config.debug&&console.log(JSON.stringify(e.data,null,2));const i=et.enqueue(t,e.data,e.headers);return ct(t,{...e,callback:void 0},i)}function pt(){try{const t=sessionStorage.getItem("sensorswave_utm");if(!t)return{};const e=JSON.parse(t),n={};return Object.entries(e).forEach(([t,e])=>{null!=e&&""!==e&&(n[`$${t}`]=e)}),n}catch(t){return{}}}function gt(t){const e={};return Object.entries(t).forEach(([t,n])=>{if("function"==typeof n)try{const i=n();e[t]=i}catch(i){console.warn("[SensorsWave] Failed to resolve dynamic property:",t,i)}else e[t]=n}),e}function ft(t={},e=!0){const n={...e?tt():{},...gt(N.getCommonProps()),...t},i=pt();return Object.keys(i).length>0&&Object.assign(n,i),n}function mt(t,e,n=!0){if(!st())return;if(!rt())return;const i={time:Date.now(),trace_id:N.getTraceId(),event:t.event,properties:ft(t.properties,n)},s=pt();Object.keys(s).length>0&&(i.user_properties||(i.user_properties={}),i.user_properties.$set||(i.user_properties.$set={}),Object.assign(i.user_properties.$set,s)),t.user_properties&&(t.user_properties.$set&&(i.user_properties=i.user_properties||{},i.user_properties.$set={...i.user_properties.$set||{},...t.user_properties.$set},delete t.user_properties.$set),i.user_properties={...i.user_properties,...t.user_properties});const r=N.getLoginId(),o=N.getAnonId();r&&(i.login_id=r),o&&(i.anon_id=o);const a=ut(e),c=ht(e),u=!1!==e.batchSend&&at();u?(et.enqueue(a,[i],c),u.add()):dt(a,{data:[i],headers:c})}function Et({userProps:t,opts:e}){if(!st())return;if(!rt())return;const n=N.getLoginId(),i=N.getAnonId();if(!n&&!i)return;const s={time:Date.now(),trace_id:N.getTraceId(),event:"$UserSet",login_id:n,anon_id:i,user_properties:t,properties:ft()},r=ut(e),o=ht(e),a=at();if(!a)return dt(r,{data:[s],headers:o});et.enqueue(r,[s],o),a.add()}function _t(t){return t.typ===C.FEATURE_GATE||t.typ===C.FEATURE_CONFIG?`$feature_${t.id}`:t.typ===C.EXPERIMENT?`$exp_${t.id}`:""}function It(t){const e=t.typ;return[C.FEATURE_GATE,C.EXPERIMENT,C.FEATURE_CONFIG].includes(e)?{[_t(t)]:t.vid}:{}}function St(t){const e=t.typ;return e===C.FEATURE_GATE||e===C.FEATURE_CONFIG?{$feature_key:t.key,$feature_variant:t.vid}:e===C.EXPERIMENT?{$exp_key:t.key,$exp_variant:t.vid}:{}}function wt({isUnset:t=!1,data:e,opts:n}){if(!st())return;if(!rt())return;if(!e||u(e)||e.disable_impress)return;const i=N.getLoginId(),s=N.getAnonId();if(!i&&!s)return;const r=e.typ===C.EXPERIMENT?"$ExpImpress":"$FeatureImpress";let o={};return o=t?{$unset:{[_t(e)]:null}}:{$set:{...It(e)}},mt({event:r,properties:St(e),user_properties:o},n)}const Ot="sensorswave_opt_out";class vt{constructor(t){this.persist=t}read(){if(this.persist)try{const t=I.get(Ot);return"0"===t||"1"!==t&&void 0}catch{return}}write(t){if(this.persist)try{I.set(Ot,t?"0":"1")}catch{}}}class bt{constructor({plugins:t,emitter:e,config:n,sdk:i}){this.plugins=[],this.pluginInsMap={},this.emitter=e,this.config=n,this.sdk=i,this.registerBuiltInPlugins(t),this.created(),this.emitter.on(b,()=>{this.init()})}registerBuiltInPlugins(t){for(let e=0,n=t.length;e<n;e++)this.registerPlugin(t[e])}registerPlugin(t){this.plugins.push(t)}getPlugins(){return this.plugins}getPlugin(t){return this.pluginInsMap[t]}created(){for(let t=0,e=this.plugins.length;t<e;t++){const e=this.plugins[t];if(!e.NAME)throw new Error('Plugin should be defined with "NAME"');const n=new e({emitter:this.emitter,config:this.config,sdk:this.sdk});this.pluginInsMap[e.NAME]=n}}init(){for(const t of Object.keys(this.pluginInsMap)){const e=this.pluginInsMap[t];e.init&&e.init()}}destroy(){for(const t of Object.keys(this.pluginInsMap)){const e=this.pluginInsMap[t];e.destroy&&"function"==typeof e.destroy&&e.destroy()}this.pluginInsMap={},this.plugins=[]}}const yt=class{constructor({emitter:t,config:e,sdk:n}){this.boundSend=null,this.hashEvent=null,this.spaSwitchHandler=null,this.emitter=t,this.config=e,this.sdk=n}init(){const t=this.config;this.boundSend=()=>{mt({event:"$PageView",properties:{}},t)},this.sdk&&!0===this.sdk._postConsentInit||setTimeout(()=>{this.boundSend()},0),t.isSinglePageApp&&this.addSinglePageListener()}addSinglePageListener(){this.spaSwitchHandler=t=>{t!==location.href&&this.boundSend()},this.emitter.on(y,this.spaSwitchHandler)}destroy(){this.spaSwitchHandler&&(this.emitter.off(y,this.spaSwitchHandler),this.spaSwitchHandler=null),this.hashEvent&&this.boundSend&&(window.removeEventListener(this.hashEvent,this.boundSend),this.hashEvent=null),this.boundSend=null}};yt.NAME="pageview";let At=yt;const Rt=class{constructor({emitter:t,config:e,sdk:n}){this.startTime=Date.now(),this.pageShowStatus=!0,this.pageHiddenStatus=!1,this.timer=null,this.currentPageUrl=document.referrer,this.url=location.href,this.title=document.title||"",this.heartbeatIntervalTime=5e3,this.heartbeatIntervalTimer=null,this.pageId=null,this.storageName="sensorswavewebjssdkpageleave",this.maxDuration=432e3,this.eventListeners=[],this._skipFirstPageEnd=!1,this.emitter=t,this.config=e,this.sdk=n}__canCapture(){return!this.sdk||"function"!=typeof this.sdk.hasOptedOutCapturing||!this.sdk.hasOptedOutCapturing()}init(){this.pageId=Number(String(g()).slice(2,5)+String(g()).slice(2,4)+String(Date.now()).slice(-4)),this.addEventListener(),this.sdk&&!0===this.sdk._postConsentInit&&(this._skipFirstPageEnd=!0),!0===document.hidden?this.pageShowStatus=!1:this.addHeartBeatInterval()}log(t){console.log(t)}refreshPageEndTimer(){this.timer&&(clearTimeout(this.timer),this.timer=null),this.timer=setTimeout(()=>{this.pageHiddenStatus=!1},5e3)}hiddenStatusHandler(){this.timer&&clearTimeout(this.timer),this.timer=null,this.pageHiddenStatus=!1}pageStartHandler(){this.startTime=Date.now(),1==!document.hidden?this.pageShowStatus=!0:this.pageShowStatus=!1,this.url=location.href,this.title=document.title,this._skipFirstPageEnd=!1}pageEndHandler(){if(!0===this.pageHiddenStatus)return;if(!this.__canCapture())return;const t=this.getPageLeaveProperties();!1===this.pageShowStatus&&delete t.$event_duration,this.pageShowStatus=!1,this.pageHiddenStatus=!0,mt({event:R,properties:t},this.config),this.refreshPageEndTimer(),this.delHeartBeatData()}addEventListener(){this.addPageStartListener(),this.addPageSwitchListener(),this.addSinglePageListener(),this.addPageEndListener()}addPageStartListener(){if("onpageshow"in window){const t=()=>{this.pageStartHandler(),this.hiddenStatusHandler()};window.addEventListener("pageshow",t),this.eventListeners.push({target:window,event:"pageshow",handler:t})}}addSinglePageListener(){this.config.isSinglePageApp&&this.emitter.on(y,t=>{t!==location.href&&(this.url=t,this.pageEndHandler(),this.stopHeartBeatInterval(),this.currentPageUrl=this.url,this.pageStartHandler(),this.hiddenStatusHandler(),this.addHeartBeatInterval())})}addPageEndListener(){["pagehide","beforeunload"].forEach(t=>{if(`on${t}`in window){const e=()=>{if(this._skipFirstPageEnd)return this._skipFirstPageEnd=!1,void this.stopHeartBeatInterval();this.pageEndHandler(),this.stopHeartBeatInterval()};window.addEventListener(t,e),this.eventListeners.push({target:window,event:t,handler:e})}})}addPageSwitchListener(){const t=()=>{"visible"===document.visibilityState?(this.pageStartHandler(),this.hiddenStatusHandler(),this.addHeartBeatInterval()):(this.url=location.href,this.title=document.title,this.stopHeartBeatInterval())};document.addEventListener("visibilitychange",t),this.eventListeners.push({target:document,event:"visibilitychange",handler:t})}addHeartBeatInterval(){I.isSupport()&&this.startHeartBeatInterval()}startHeartBeatInterval(){this.heartbeatIntervalTimer&&this.stopHeartBeatInterval(),this.sdk&&!0===this.sdk._postConsentInit&&!0===this._skipFirstPageEnd||(this.heartbeatIntervalTimer=setInterval(()=>{this.saveHeartBeatData()},this.heartbeatIntervalTime),this.saveHeartBeatData("is_first_heartbeat"),this.reissueHeartBeatData())}stopHeartBeatInterval(){this.heartbeatIntervalTimer&&clearInterval(this.heartbeatIntervalTimer),this.heartbeatIntervalTimer=null}saveHeartBeatData(t){if(!this.__canCapture())return;const e=this.getPageLeaveProperties();e.$time=Date.now(),"is_first_heartbeat"===t&&(e.$event_duration=3);const n={type:"track",event:R,properties:e,time:e.$time};n.heartbeat_interval_time=this.heartbeatIntervalTime,I.isSupport()&&I.set(`${this.storageName}-${this.pageId}`,JSON.stringify(n))}delHeartBeatData(t){I.isSupport()&&I.remove(t||`${this.storageName}-${this.pageId}`)}reissueHeartBeatData(){if(this.__canCapture())for(let t=window.localStorage.length-1;t>=0;t--){const e=window.localStorage.key(t);if(e&&e!==`${this.storageName}-${this.pageId}`&&0===e.indexOf(`${this.storageName}-`)){const t=I.parse(e);i(t)&&Date.now()-t.time>t.heartbeat_interval_time+5e3&&(delete t.heartbeat_interval_time,t._flush_time=/* @__PURE__ */(new Date).getTime(),mt({event:R,properties:t?.properties},this.config),this.delHeartBeatData(e))}}}getPageLeaveProperties(){let t=(Date.now()-this.startTime)/1e3;(isNaN(t)||t<0||t>this.maxDuration)&&(t=0),t=Number(t.toFixed(3));const e={$title:this.title,$url:this.url?.substring(0,1e3),$pathname:w(this.url)};return 0!==t&&(e.$event_duration=t),e}destroy(){this.eventListeners.forEach(({target:t,event:e,handler:n})=>{t.removeEventListener(e,n)}),this.eventListeners=[],this.timer&&(clearTimeout(this.timer),this.timer=null),this.heartbeatIntervalTimer&&(clearInterval(this.heartbeatIntervalTimer),this.heartbeatIntervalTimer=null)}};Rt.NAME="pageleave";let Tt=Rt;const Ct=class{constructor({emitter:t,config:e,sdk:n}){this.eventSended=!1,this.emitter=t,this.config=e,this.sdk=n}init(){if(this.sdk&&!0===this.sdk._postConsentInit)return;const t=()=>{let e=0;const n={};if(window.performance){e=function(){let t=0;if("function"==typeof performance.getEntriesByType){const e=performance.getEntriesByType("navigation");e.length>0&&(t=e[0].domContentLoadedEventEnd||0)}return t}();const t=function(){if(performance.getEntries&&"function"==typeof performance.getEntries){const t=performance.getEntries();let e=0;for(const n of t)"transferSize"in n&&(e+=n.transferSize);if("number"==typeof e&&e>=0&&e<10737418240)return Number((e/1024).toFixed(3))}}();t&&(n.$page_resource_size=t)}else console.warn("Performance API is not supported.");e>0&&!Number.isFinite(e)&&(n.$event_duration=Number((e/1e3).toFixed(3))),this.eventSended||(this.eventSended=!0,mt({event:"$PageLoad",properties:n},this.config)),window.removeEventListener("load",t)};"complete"===document.readyState?t():window.addEventListener&&window.addEventListener("load",t)}};Ct.NAME="pageload";let Nt=Ct;function Pt(t,e){if(!l(t))return!1;const n=o(t.tagName)?t.tagName.toLowerCase():"",i={};i.$element_type=n,i.$element_name=t.getAttribute("name")||"",i.$element_id=t.getAttribute("id")||"",i.$element_class_name=o(t.className)?t.className:"",i.$element_target_url=t.getAttribute("href")||"",i.$element_content=function(t,e){return o(e)&&"input"===e.toLowerCase()?("button"===(n=t).type||"submit"===n.type)&&n.value||"":function(t,e){let n="",i="";return t.textContent?n=S(t.textContent):t.innerText&&(n=S(t.innerText)),n&&(n=n.replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)),i=n||"","input"!==e&&"INPUT"!==e||(i=t.value||""),i}(t,e);var n}(t,n)||"",i.$element_selector=kt(t)||"",i.$element_path=function(t){let e=[];for(;t.parentNode&&l(t);){if(!o(t.tagName))return"";if(t.id&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(t.id)){e.unshift(t.tagName.toLowerCase()+"#"+t.id);break}if(t===document.body){e.unshift("body");break}e.unshift(t.tagName.toLowerCase()),t=t.parentNode}return e.join(" > ")}(t)||"";const s=function(t,e){const n=e.pageX||e.clientX+Lt().scrollLeft||e.offsetX+$t(t).targetEleX,i=e.pageY||e.clientY+Lt().scrollTop||e.offsetY+$t(t).targetEleY;return{$page_x:Ft(n),$page_y:Ft(i)}}(t,e);return i.$page_x=s.$page_x,i.$page_y=s.$page_y,i}function kt(t,e=[]){if(!(t&&t.parentNode&&t.parentNode.children&&o(t.tagName)))return"";e=Array.isArray(e)?e:[];const n=t.nodeName.toLowerCase();return t&&"body"!==n&&1==t.nodeType?(e.unshift(function(t){if(!t||!l(t)||!o(t.tagName))return"";let e=t.parentNode&&9==t.parentNode.nodeType?-1:function(t){if(!t.parentNode)return-1;let e=0;const n=t.tagName,i=t.parentNode.children;for(let s=0,r=i.length;s<r;s++)if(i[s].tagName===n){if(t===i[s])return e;e++}return-1}(t);return t.getAttribute&&t.getAttribute("id")&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(t.getAttribute("id"))?"#"+t.getAttribute("id"):t.tagName.toLowerCase()+(~e?":nth-of-type("+(e+1)+")":"")}(t)),t.getAttribute&&t.getAttribute("id")&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(t.getAttribute("id"))?e.join(" > "):kt(t.parentNode,e)):(e.unshift("body"),e.join(" > "))}function Lt(){return{scrollLeft:document.body.scrollLeft||document.documentElement.scrollLeft||0,scrollTop:document.body.scrollTop||document.documentElement.scrollTop||0}}function $t(t){if(document.documentElement.getBoundingClientRect){const e=t.getBoundingClientRect();return{targetEleX:e.left+Lt().scrollLeft||0,targetEleY:e.top+Lt().scrollTop||0}}return{targetEleX:0,targetEleY:0}}function Ft(t){return Number(Number(t).toFixed(3))}const Bt=class{constructor({emitter:t,config:e}){this.isInitialized=!1,this.boundHandleClick=null,this.emitter=t,this.config=e}init(){this.isInitialized||(this.boundHandleClick=this.handleClick.bind(this),document.addEventListener("click",this.boundHandleClick,!0),this.isInitialized=!0)}handleClick(t){const e=t.target;if(!e)return;if(!["A","INPUT","BUTTON","TEXTAREA"].includes(e.tagName))return;if("true"===e.getAttribute("sensorswave-disable"))return;mt({event:"$WebClick",properties:Pt(e,t)||{}},this.config)}destroy(){this.boundHandleClick&&(document.removeEventListener("click",this.boundHandleClick,!0),this.boundHandleClick=null),this.isInitialized=!1}};Bt.NAME="webclick";let xt=Bt;const Mt=class{constructor({emitter:t,config:e,sdk:n}){this.updateInterval=null,this.fetchingPromise=null,this.emitter=t,this.config=e,this.sdk=n}init(){const t=this.config;if(t.enableAB){if(this.sdk&&"function"==typeof this.sdk.hasOptedOutCapturing&&this.sdk.hasOptedOutCapturing())return;this.fastFetch().then(()=>{this.emitter.emit(A)}),t.abRefreshInterval<3e4&&(t.abRefreshInterval=3e4),this.updateInterval=setInterval(()=>{this.fetchNewData().catch(console.warn)},t.abRefreshInterval)}}async fastFetch(){const t=N.getABData(this.config.abRefreshInterval);return t&&t.length?(this.emitter.emit(A),Promise.resolve(t)):this.fetchNewData()}async fetchNewData(){return this.fetchingPromise||(this.fetchingPromise=new Promise(t=>{!function({opts:t,cb:e}){if(!st())return void(e&&e({}));if(!rt())return void(e&&e({}));const n=N.getLoginId(),i=N.getAnonId();if(!n&&!i)return void(e&&e({}));const s={user:{login_id:n||"",anon_id:i||"",props:{...tt(),...gt(N.getCommonProps())}},sdk:"webjs",sdk_version:v};$({url:lt(t),method:"POST",data:s,headers:ht(t),callback:t=>{200!==t.statusCode?(console.error("Failed to fetch feature flags"),e&&e({})):e&&e(t.json)}})}({opts:this.config,cb:e=>{N.saveABData(e?.data?.results||[]),t(e),this.fetchingPromise=null}})})),this.fetchingPromise}async getFeatureGate(t){return await this.fastFetch().catch(console.warn),N.getABData(this.config.abRefreshInterval).find(e=>e.typ===C.FEATURE_GATE&&e.key==t)}async checkFeatureGate(t){const e=await this.getFeatureGate(t);return!!e&&(!e.hasOwnProperty("vid")&&e.key?(wt({isUnset:!0,data:e,opts:this.config}),!1):(wt({data:e,opts:this.config}),"fail"!==e.vid))}async getExperiment(t){await this.fastFetch().catch(console.warn);const e=N.getABData(this.config.abRefreshInterval).find(e=>e.typ===C.EXPERIMENT&&e.key===t);return e?!e.hasOwnProperty("vid")&&e.key?(wt({isUnset:!0,data:e,opts:this.config}),{}):(wt({data:e,opts:this.config}),e?.value||{}):{}}async getFeatureConfig(t){await this.fastFetch().catch(console.warn);const e=N.getABData(this.config.abRefreshInterval).find(e=>e.typ===C.FEATURE_CONFIG&&e.key===t);if(!e)return{};if(!e.hasOwnProperty("vid")&&e.key)return wt({isUnset:!0,data:e,opts:this.config}),{};wt({data:e,opts:this.config});const n=e?.value;if(n){if(i(n))return n;try{return JSON.parse(n)}catch{return n}}return{}}destroy(){this.updateInterval&&(clearInterval(this.updateInterval),this.updateInterval=null),this.fetchingPromise=null}};Mt.NAME="abtest";let Dt=Mt;const Ht=["utm_source","utm_medium","utm_campaign","utm_content","utm_term"],Ut="sensorswave_utm",Xt=class t{constructor({sdk:t,emitter:e,config:n}){this.sdk=t,this.emitter=e,this.config=n}init(){if(this.sdk&&!0===this.sdk._postConsentInit){let e=t.readFromSessionStorage();return e&&0!==Object.keys(e).length||(e=t.captureAndStore(this.config?.debug)),void this.scheduleInitialUTM(e)}const e=t.getUTMFromURL();t.saveToSessionStorage(e,this.config?.debug),this.scheduleInitialUTM(e)}scheduleInitialUTM(t){setTimeout(()=>{this.sendInitialUTM(t)},0)}static getUTMFromURL(){try{const t=new URLSearchParams(window.location.search),e={};return Ht.forEach(n=>{const i=t.get(n);i&&(e[n]=i)}),e}catch(e){return t.getUTMFromURLFallback()}}static getUTMFromURLFallback(){const t={};return window.location.search.substring(1).split("&").forEach(e=>{const[n,i]=e.split("="),s=decodeURIComponent(n),r=i?decodeURIComponent(i):"";Ht.includes(s)&&(t[s]=r)}),t}static readFromSessionStorage(){try{const t=sessionStorage.getItem(Ut);if(!t)return{};const e=JSON.parse(t);return e&&"object"==typeof e?e:{}}catch(t){return{}}}static saveToSessionStorage(t,e=!1){try{sessionStorage.setItem(Ut,JSON.stringify(t))}catch(n){e&&console.warn("[SensorsWave UTM] Failed to save to sessionStorage:",n)}}static captureAndStore(e=!1){const n=t.getUTMFromURL();return t.saveToSessionStorage(n,e),n}sendInitialUTM(t){const e={};Ht.forEach(n=>{e[`$initial_${n}`]=null!=t[n]?t[n]:""});try{this.sdk.profileSetOnce(e)}catch(n){this.config.debug&&console.warn("[SensorsWave UTM] Failed to send initial UTM:",n)}}destroy(){}};Xt.NAME="UTM";let jt=Xt;const qt=1e3,Wt=/^\s*(?:async\s+)?at\s+(?:(.+)\s+\()?(.+?):(\d+):(\d+)\)?$/,Gt=/^(?:(.*)@)?(.+?):(\d+):(\d+)$/;function zt(t){let e=t;try{const t=location.origin;t&&0===e.indexOf(t)&&(e=e.substring(t.length))}catch(s){}const n=e.indexOf("?");n>-1&&(e=e.substring(0,n));const i=e.indexOf("#");return i>-1&&(e=e.substring(0,i)),e}function Yt(t){return t.map(t=>({platform:"web:javascript",filename:zt(t.file),function:t.fn||"?",lineno:Number(t.line),colno:Number(t.col),abs_path:Kt(t.file,1e3)}))}function Kt(t,e){return t.length>e?t.substring(0,e):t}function Jt(t){let e;if("string"==typeof t)e=t;else if(null!==t&&"object"==typeof t){try{e=JSON.stringify(t)}catch(n){e=Object.prototype.toString.call(t)}e||(e=Object.prototype.toString.call(t))}else e=String(t);return Kt(e,qt)}function Zt(t){const{frames:e,headerType:n}=function(t){const e=[];let n="";if(!t||"string"!=typeof t)return{frames:e,headerType:n};const i=t.split(/\r?\n/);for(let s=0;s<i.length;s++){const t=i[s];if(!t||t.length>1024)continue;const r=t.match(Wt),o=r?null:t.match(Gt),a=r||o;if(a)e.push({fn:a[1]||"?",file:a[2],line:a[3],col:a[4]});else if(0===s){const e=t.indexOf(":");e>0&&(n=t.substring(0,e).trim())}if(e.length>=30)break}return{frames:e,headerType:n}}(t&&t.stack);let i=t&&t.name||n||"Error";return i=Kt(String(i),200),{$exception_level:"error",$exception_type:i,$exception_message:Kt(String(t&&t.message||""),qt),$exception_frames:Yt(e)}}function Qt(t,e,n,i){let s=[];return e&&(s=[{platform:"web:javascript",filename:zt(e),function:"?",lineno:n||0,colno:i||0,abs_path:Kt(e,1e3)}]),{$exception_level:"error",$exception_type:"Error",$exception_message:Kt(String(t||""),qt),$exception_frames:s}}class Vt{constructor(t=10,e=1,n=1e4){this.buckets=/* @__PURE__ */new Map,this.bucketSize=t,this.refillRate=e,this.refillInterval=n}allow(t){const e=Date.now();let n=this.buckets.get(t);if(n){if(e>n.lastRefill){const t=Math.floor((e-n.lastRefill)/this.refillInterval)*this.refillRate;t>0&&(n.tokens=Math.min(this.bucketSize,n.tokens+t),n.lastRefill+=t/this.refillRate*this.refillInterval)}}else n={tokens:this.bucketSize,lastRefill:e},this.buckets.set(t,n);return n.tokens>=1&&(n.tokens-=1,!0)}reset(){this.buckets.clear()}}const te=class{constructor({emitter:t,config:e}){this.isInitialized=!1,this.boundHandleError=null,this.boundHandleRejection=null,this.rateLimiter=new Vt,this.emitter=t,this.config=e}init(){this.isInitialized||(this.boundHandleError=this.handleError.bind(this),this.boundHandleRejection=this.handleRejection.bind(this),window.addEventListener("error",this.boundHandleError,!0),window.addEventListener("unhandledrejection",this.boundHandleRejection),this.isInitialized=!0)}handleError(t){try{const e=t.target;let n;if(e&&e!==window&&e.tagName)n=function(t){const e=t,n=(e.tagName||"").toLowerCase(),i=Kt(String(e.src||e.href||""),qt);return{$exception_level:"error",$exception_type:"ResourceLoadError",$exception_message:`Failed to load <${n}>${i?` from ${i}`:""}`,$exception_frames:[]}}(e);else{const e=t;n=e.error instanceof Error?Zt(e.error):Qt(String(e.message||""),e.filename,e.lineno,e.colno)}this.send(n)}catch(e){}}handleRejection(t){try{const e=t.reason;this.send(function(t){return t instanceof Error?Zt(t):{$exception_level:"error",$exception_type:"UnhandledRejection",$exception_message:Jt(t),$exception_frames:[]}}(e))}catch(e){}}send(t){t.$exception_message&&this.rateLimiter.allow(t.$exception_type)&&mt({event:T,properties:t},this.config)}destroy(){this.boundHandleError&&(window.removeEventListener("error",this.boundHandleError,!0),this.boundHandleError=null),this.boundHandleRejection&&(window.removeEventListener("unhandledrejection",this.boundHandleRejection),this.boundHandleRejection=null),this.rateLimiter.reset(),this.isInitialized=!1}};te.NAME="exception";let ee=te;const ne=[],ie={debug:!1,sourceToken:"",apiHost:"",autoCapture:!0,isSinglePageApp:!1,crossSubdomainCookie:!0,enableAB:!1,abRefreshInterval:6e5,enableClickTrack:!1,batchSend:!1,enableErrorTrack:!1,enableCrashTrack:!1,optOutCapturing:!1,persistOptOut:!1},se=new class{constructor(){this.__innerInited=!1,this.inited=!1,this.config={},this.eventEmitter=new t,this.pluginCore={},this.commonProps={},this.spaCleanup=null,this._optOutCapturing=!1,this.consentStorage=new vt(!1),this._setupAfterConsentDone=!1,this._postConsentInit=!1,O.instance=this}init(t,e={}){return this.inited?this:(O.instance=this,e.sourceToken=t,this.mergeConfig(e),this.consentStorage=new vt(!0===this.config.persistOptOut),this._optOutCapturing?this.consentStorage.write(!0):!0===this.config.optOutCapturing?(this._optOutCapturing=!0,this.consentStorage.write(!0)):!0===this.consentStorage.read()&&(this._optOutCapturing=!0),this.eventEmitter.emit("init-param",this.config),this.__innerInited=!0,this._optOutCapturing?(jt.captureAndStore(this.config.debug),this.eventEmitter.emit(b),this.inited=!0,this):(this.__setupAfterConsent(),this.eventEmitter.emit(b),this.inited=!0,this))}__setupAfterConsent(){if(this._setupAfterConsentDone)return;this._setupAfterConsentDone=!0;const t=this.config;ne.length=0,N.init(t.crossSubdomainCookie),t.anonId&&N.setAnonId(t.anonId),function(){if(window._swFailedRequestsInitialized)return;window._swFailedRequestsInitialized=!0;const t=O.instance;t&&"function"==typeof t.hasOptedOutCapturing&&t.hasOptedOutCapturing()||t&&!0===t._postConsentInit||function(){const t=et.getAll();if(0!==t.length)for(let e=0,n=t.length;e<n;e+=10){const n=t.slice(e,e+10),i=[],s=[];n.forEach(t=>{Array.isArray(t.data)?i.push(...t.data):i.push(t.data),s.push(t.id)});const r=n[n.length-1],o=r.url,a=r.headers;$({url:o,method:"POST",data:i,headers:a,callback:t=>{200!==t.statusCode?(console.error("Failed to send batch stored requests:",t),P(t.statusCode)||s.forEach(t=>{et.dequeue(t)})):s.forEach(t=>{et.dequeue(t)})}})}}()}(),ne.push(jt),t.autoCapture&&this.autoTrack(),t.enableAB&&ne.push(Dt),t.enableClickTrack&&ne.push(xt),t.enableCrashTrack&&t.debug&&console.warn("[SensorsWave] enableCrashTrack 仅在 app 宿主环境生效,当前 Web 环境不采集 crash"),t.enableErrorTrack&&ne.push(ee),this.pluginCore=new bt({plugins:ne,emitter:this.eventEmitter,config:t,sdk:this}),this.spaCleanup=function(t){let e=location.href;const n=window.history.pushState,i=window.history.replaceState,r=function(){t(e),e=location.href};return s(window.history.pushState)&&(window.history.pushState=function(...i){n.apply(window.history,i),t(e),e=location.href}),s(window.history.replaceState)&&(window.history.replaceState=function(...n){i.apply(window.history,n),t(e),e=location.href}),window.addEventListener("popstate",r),function(){s(window.history.pushState)&&(window.history.pushState=n),s(window.history.replaceState)&&(window.history.replaceState=i),window.removeEventListener("popstate",r)}}(t=>{this.eventEmitter.emit(y,t)})}mergeConfig(t){this.config={...ie,...t}}__canCapture(){return this.inited&&!this._optOutCapturing}track(t){this.__canCapture()&&function(t,e){if(!st())return;if(!rt())return;const n={...t};n.time||(n.time=Date.now()),n.login_id||(n.login_id=N.getLoginId()),n.anon_id||(n.anon_id=N.getAnonId()),n.trace_id||(n.trace_id=N.getTraceId()),n.properties={...tt(),...gt(N.getCommonProps()),...n.properties};const i=ut(e),s=ht(e),r=!1!==e.batchSend&&at();if(!r)return dt(i,{data:[n],headers:s});et.enqueue(i,[n],s),r.add()}(t,this.config)}trackEvent(t,e){this.__canCapture()&&mt({event:t,properties:e},this.config)}trackException(t,e){if(!this.__canCapture())return;const n={...e||{},...t instanceof Error?Zt(t):Qt(String(t))};mt({event:T,properties:n},this.config)}autoTrack(){ne.push(At,Nt,Tt)}profileSet(t){this.__canCapture()&&Et({userProps:{$set:t},opts:this.config})}profileSetOnce(t){this.__canCapture()&&Et({userProps:{$set_once:t},opts:this.config})}profileIncrement(t){this.__canCapture()&&Et({userProps:{$increment:t},opts:this.config})}profileAppend(t){this.__canCapture()&&Et({userProps:{$append:t},opts:this.config})}profileUnion(t){this.__canCapture()&&Et({userProps:{$union:t},opts:this.config})}profileUnset(t){if(!this.__canCapture())return;const e={};r(t)?t.forEach(function(t){e[t]=null}):e[t]=null,Et({userProps:{$unset:e},opts:this.config})}profileDelete(){this.__canCapture()&&Et({userProps:{$delete:!0},opts:this.config})}registerCommonProperties(t){if(!i(t))return console.warn("Commmon Properties must be an object!");this.commonProps=t,N.setCommonProps(this.commonProps)}clearCommonProperties(t){if(!r(t))return console.warn("Commmon Properties to be cleared must be an array!");t.forEach(t=>{delete this.commonProps[t]}),N.setCommonProps(this.commonProps)}identify(t){this.__canCapture()&&(N.setLoginId(t),function(t){if(!st())return;if(!rt())return;const e=N.getLoginId(),n=N.getAnonId();if(!e||!n)return;const i={time:Date.now(),trace_id:N.getTraceId(),event:"$Identify",login_id:e,anon_id:n,properties:ft()},s=ut(t),r=ht(t),o=at();if(!o)return dt(s,{data:[i],headers:r});et.enqueue(s,[i],r),o.add()}(this.config))}setLoginId(t){this.__canCapture()&&N.setLoginId(t)}getAnonId(){return this.__canCapture()?N.getAnonId():""}setAnonId(t){this.__canCapture()&&N.setAnonId(t)}getLoginId(){return this.__canCapture()?N.getLoginId():""}checkFeatureGate(t){if(!this.__canCapture())return Promise.resolve(!1);const e=this.pluginCore.getPlugin(Dt.NAME);return this.config.enableAB&&e?e.checkFeatureGate(t):Promise.reject("AB is disabled")}getExperiment(t){if(!this.__canCapture())return Promise.resolve({});const e=this.pluginCore.getPlugin(Dt.NAME);return this.config.enableAB&&e?e.getExperiment(t):Promise.reject("AB is disabled")}getFeatureConfig(t){if(!this.__canCapture())return Promise.resolve({});const e=this.pluginCore.getPlugin(Dt.NAME);return this.config.enableAB&&e?e.getFeatureConfig(t):Promise.reject("AB is disabled")}optOutCapturing(){this._optOutCapturing=!0,this.consentStorage.write(!0),ot&&ot.pause()}optInCapturing(){if(this._optOutCapturing=!1,this.consentStorage.write(!1),ot&&ot.resume(),this.inited&&!this._setupAfterConsentDone){this._postConsentInit=!0;try{this.__setupAfterConsent(),this.eventEmitter.emit(b)}finally{this._postConsentInit=!1}}}hasOptedOutCapturing(){return this._optOutCapturing}destroy(){ot&&(ot.destroy(),ot=null),"undefined"!=typeof window&&(window._swFailedRequestsInitialized=!1),this.inited=!1,this.__innerInited=!1,this.spaCleanup&&"function"==typeof this.spaCleanup&&(this.spaCleanup(),this.spaCleanup=null),this.pluginCore&&"function"==typeof this.pluginCore.destroy&&this.pluginCore.destroy(),this.pluginCore={},this.eventEmitter&&this.eventEmitter.removeAllListeners(),this.consentStorage=new vt(!0===this.config?.persistOptOut),this._optOutCapturing=!1,this._setupAfterConsentDone=!1,this._postConsentInit=!1,O.instance===this&&(O.instance=null)}};export{se as default};
package/dist/index.umd.js CHANGED
@@ -1 +1 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).SensorsWave=t()}(this,function(){"use strict";class e{constructor(){this.listeners={}}on(e,t,n=!1){if(e&&t){if(!s(t))throw new Error("listener must be a function");this.listeners[e]=this.listeners[e]||[],this.listeners[e].push({listener:t,once:n})}}off(e,t){const n=this.listeners[e];if(!n?.length)return;"number"==typeof t&&n.splice(t,1);const i=n.findIndex(e=>e.listener===t);-1!==i&&n.splice(i,1)}emit(e,...t){this.listeners[e]&&this.listeners[e].forEach((n,i)=>{n.listener.call(this,...t),n.listener.once&&this.off(e,i)})}once(e,t){this.on(e,t,!0)}removeAllListeners(e){e?this.listeners[e]=[]:this.listeners={}}}const t={get:function(e){const t=e+"=",n=document.cookie.split(";");for(let i=0,s=n.length;i<s;i++){let e=n[i];for(;" "==e.charAt(0);)e=e.substring(1,e.length);if(0==e.indexOf(t))return h(e.substring(t.length,e.length))}return null},set:function({name:e,value:t,expires:n,samesite:i,secure:s,domain:r}){let o="",a="",c="",l="";if(0!==(n=null==n||void 0===n?365:n)){const e=new Date;"s"===String(n).slice(-1)?e.setTime(e.getTime()+1e3*Number(String(n).slice(0,-1))):e.setTime(e.getTime()+24*n*60*60*1e3),o="; expires="+e.toUTCString()}function u(e){return e?e.replace(/\r\n/g,""):""}i&&(c="; SameSite="+i),s&&(a="; secure");const h=u(e),d=u(t),g=u(r);g&&(l="; domain="+g),h&&d&&(document.cookie=h+"="+encodeURIComponent(d)+o+"; path=/"+l+c+a)},remove:function(e){this.set({name:e,value:"",expires:-1})},isSupport:function({samesite:e,secure:t}={}){if(!navigator.cookieEnabled)return!1;const n="sensorswave_cookie_support_test";return this.set({name:n,value:"1",samesite:e,secure:t}),"1"===this.get(n)&&(this.remove(n),!0)}},n=Object.prototype.toString;function i(e){return"[object Object]"===n.call(e)}function s(e){const t=n.call(e);return"[object Function]"==t||"[object AsyncFunction]"==t}function r(e){return"[object Array]"==n.call(e)}function o(e){return"[object String]"==n.call(e)}function a(e){return void 0===e}const c=Object.prototype.hasOwnProperty;function l(e){if(i(e)){for(let t in e)if(c.call(e,t))return!1;return!0}return!1}function u(e){return!(!e||1!==e.nodeType)}function h(e){let t=e;try{t=decodeURIComponent(e)}catch(n){t=e}return t}function d(e){try{return JSON.parse(e)}catch(t){return""}}const g=function(){let e=Date.now();return function(t){return Math.ceil((e=(9301*e+49297)%233280,e/233280*t))}}();function p(){if("function"==typeof Uint32Array){let e;if("undefined"!=typeof crypto&&(e=crypto),e&&i(e)&&e.getRandomValues)return e.getRandomValues(new Uint32Array(1))[0]/Math.pow(2,32)}return g(1e19)/1e19}const f=function(){function e(e){return("0".repeat(e)+Date.now().toString(16)).slice(-e)}return function(){let t=String(screen.height*screen.width);t=t&&/\d{4,}/.test(t)?t.slice(-4):String(31242*p()).replace(".","").slice(0,4);return e(8)+"-"+p().toString(16).replace(".","").slice(-4)+"-"+function(){const e=navigator.userAgent;let t,n=[],i=0;function s(e,t){let i=0;for(let s=0;s<t.length;s++)i|=n[s]<<8*s;return(e^i)>>>0}for(let r=0;r<e.length;r++)t=e.charCodeAt(r),n.unshift(255&t),n.length>=4&&(i=s(i,n),n=[]);return n.length>0&&(i=s(i,n)),("0000"+i.toString(16)).slice(-4)}()+"-"+t+"-"+e(12)||(String(p())+String(p())+String(p())).slice(2,15)}}();function m(e,t){t&&"string"==typeof t||(t="");let n=null;try{n=new URL(e).hostname}catch(i){}return n||t}function E(e){let t=[];try{t=atob(e).split("").map(function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)})}catch(n){t=[]}try{return decodeURIComponent(t.join(""))}catch(n){return t.join("")}}function I(e){let t="";try{t=btoa(encodeURIComponent(e).replace(/%([0-9A-F]{2})/g,function(e,t){return String.fromCharCode(parseInt(t,16))}))}catch(n){t=e}return t}const S={get:function(e){return window.localStorage.getItem(e)},parse:function(e){let t;try{t=JSON.parse(S.get(e))||null}catch(n){console.warn(n)}return t},set:function(e,t){try{window.localStorage.setItem(e,t)}catch(n){console.warn(n)}},remove:function(e){window.localStorage.removeItem(e)},isSupport:function(){let e=!0;try{const t="__local_store_support__",n="testIsSupportStorage";S.set(t,n),S.get(t)!==n&&(e=!1),S.remove(t)}catch(t){e=!1}return e}};function w(e){return e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")}function _(e){if(!e||"string"!=typeof e)return"";try{return new URL(e,window.location.origin).pathname}catch(t){return""}}const O={},A="1.1.8",v="init-ready",R="spa-switch",T="ff-ready",y="$PageLeave";var b=(e=>(e[e.FEATURE_GATE=1]="FEATURE_GATE",e[e.FEATURE_CONFIG=2]="FEATURE_CONFIG",e[e.EXPERIMENT=3]="EXPERIMENT",e))(b||{});const N={crossSubdomain:!1,requests:[],_sessionState:{},_abData:[],_trace_id:"",commonProps:{},_state:{anon_id:"",login_id:"",identities:{}},getIdentityCookieID(){return this._state.identities?.$identity_cookie_id||""},getCommonProps:function(){return this.commonProps||{}},setCommonProps:function(e){this.commonProps=e},getAnonId(){return this._state.anon_id||this.getIdentityCookieID()||f()},getLoginId(){return this._state.login_id},getTraceId(){return this._trace_id||f()},set:function(e,t){this._state[e]=t,this.save()},getCookieName:function(){return"sensorswave2025jssdkcross"},getABLSName:function(){return"sensorswave2025jssdkablatest"},save:function(){let e=JSON.parse(JSON.stringify(this._state));e.identities&&(e.identities=I(JSON.stringify(e.identities)));const n=JSON.stringify(e);t.set({name:this.getCookieName(),value:n,expires:365})},init:function(e){let n,s;this.crossSubdomain=e,t.isSupport()&&(n=t.get(this.getCookieName()),s=d(n)),N._state={...s||{}},N._state.identities&&(N._state.identities=d(E(N._state.identities))),N._state.identities&&i(N._state.identities)&&!l(N._state.identities)||(N._state.identities={$identity_cookie_id:f()}),N.save()},setLoginId(e){"number"==typeof e&&(e=String(e)),void 0!==e&&e&&(N.set("login_id",e),N.save())},setAnonId(e){"number"==typeof e&&(e=String(e)),"string"==typeof e&&e?(N.set("anon_id",e),N.save()):console.warn("[SensorsWave store] Invalid anonId, ignored:",e)},saveABData(e){if(!e||l(e))return;this._abData=e;let t=JSON.parse(JSON.stringify(this._abData));t=I(JSON.stringify(t));try{localStorage.setItem(this.getABLSName(),JSON.stringify({time:Date.now(),data:t,anon_id:this.getAnonId(),login_id:this.getLoginId()}))}catch(n){console.warn("Failed to save abdata to localStorage",n)}},getABData(e=6e5){try{let t=localStorage.getItem(this.getABLSName());if(t){const{time:n,data:i,login_id:s,anon_id:r}=d(t)||{};if(n&&i&&Date.now()-n<e&&r===this.getAnonId()&&(!s||s===this.getLoginId())){const e=d(E(i));return this._abData=Array.isArray(e)?e:[],this._abData}localStorage.removeItem(this.getABLSName())}}catch(t){console.warn("Failed to load abdata from localStorage",t),this._abData=[]}return this._abData||[]}};function P(e){var t;if(e.data)return{contentType:"application/json",body:(t=e.data,JSON.stringify(t,(e,t)=>"bigint"==typeof t?t.toString():t,undefined))}}const C=[];function L(e){const t={...e};t.timeout=t.timeout||6e4;const n=t.transport??"fetch",i=C.find(e=>e.transport===n)?.method??C[0]?.method;if(!i)throw new Error("No available transport method for HTTP request");i(t)}function B(e){return o(e=e||document.referrer)&&(e=h(e=e.trim()))||""}function F(e){const t=m(e=e||B());if(!t)return"";const n={baidu:[/^.*\.baidu\.com$/],bing:[/^.*\.bing\.com$/],google:[/^www\.google\.com$/,/^www\.google\.com\.[a-z]{2}$/,/^www\.google\.[a-z]{2}$/],sm:[/^m\.sm\.cn$/],so:[/^.+\.so\.com$/],sogou:[/^.*\.sogou\.com$/],yahoo:[/^.*\.yahoo\.com$/],duckduckgo:[/^.*\.duckduckgo\.com$/]};for(let i of Object.keys(n)){let e=n[i];for(let n=0,s=e.length;n<s;n++)if(e[n].test(t))return i}return""}function M(e,t){return-1!==e.indexOf(t)}"function"==typeof fetch&&C.push({transport:"fetch",method:function(e){if("undefined"==typeof fetch)return void console.error("fetch API is not available");const t=P(e),n=new Headers;e.headers&&Object.keys(e.headers).forEach(t=>{n.append(t,e.headers[t])}),t?.contentType&&n.append("Content-Type",t.contentType),fetch(e.url,{method:e.method||"GET",headers:n,body:t?.body}).then(t=>t.text().then(n=>{const i={statusCode:t.status,text:n};if(200===t.status)try{i.json=JSON.parse(n)}catch(s){console.error("Failed to parse response:",s)}e.callback?.(i)})).catch(t=>{console.error("Request failed:",t),e.callback?.({statusCode:0,text:String(t)})})}}),"undefined"!=typeof XMLHttpRequest&&C.push({transport:"XHR",method:function(e){if("undefined"==typeof XMLHttpRequest)return void console.error("XMLHttpRequest is not available");const t=new XMLHttpRequest;t.open(e.method||"GET",e.url,!0);const n=P(e);e.headers&&Object.keys(e.headers).forEach(n=>{t.setRequestHeader(n,e.headers[n])}),n?.contentType&&t.setRequestHeader("Content-Type",n.contentType),t.timeout=e.timeout||6e4,t.withCredentials=!0,t.onreadystatechange=()=>{if(4===t.readyState){const i={statusCode:t.status,text:t.responseText};if(200===t.status)try{i.json=JSON.parse(t.responseText)}catch(n){console.error("Failed to parse JSON response:",n)}e.callback?.(i)}},t.send(n?.body)}});const $={FACEBOOK:"Facebook",MOBILE:"Mobile",IOS:"iOS",ANDROID:"Android",TABLET:"Tablet",ANDROID_TABLET:"Android Tablet",IPAD:"iPad",APPLE:"Apple",APPLE_WATCH:"Apple Watch",SAFARI:"Safari",BLACKBERRY:"BlackBerry",SAMSUNG_BROWSER:"SamsungBrowser",SAMSUNG_INTERNET:"Samsung Internet",CHROME:"Chrome",CHROME_OS:"Chrome OS",CHROME_IOS:"Chrome iOS",INTERNET_EXPLORER:"Internet Explorer",INTERNET_EXPLORER_MOBILE:"Internet Explorer Mobile",OPERA:"Opera",OPERA_MINI:"Opera Mini",EDGE:"Edge",MICROSOFT_EDGE:"Microsoft Edge",FIREFOX:"Firefox",FIREFOX_IOS:"Firefox iOS",NINTENDO:"Nintendo",PLAYSTATION:"PlayStation",XBOX:"Xbox",ANDROID_MOBILE:"Android Mobile",MOBILE_SAFARI:"Mobile Safari",WINDOWS:"Windows",WINDOWS_PHONE:"Windows Phone",NOKIA:"Nokia",OUYA:"Ouya",GENERIC_MOBILE:"Generic mobile",GENERIC_TABLET:"Generic tablet",KONQUEROR:"Konqueror",UC_BROWSER:"UC Browser",HUAWEI:"Huawei",XIAOMI:"Xiaomi",OPPO:"OPPO",VIVO:"vivo"},k="(\\d+(\\.\\d+)?)",D=new RegExp("Version/"+k),x=new RegExp($.XBOX,"i"),H=new RegExp($.PLAYSTATION+" \\w+","i"),U=new RegExp($.NINTENDO+" \\w+","i"),X=new RegExp($.BLACKBERRY+"|PlayBook|BB10","i"),q=new RegExp("(HUAWEI|honor|HONOR)","i"),W=new RegExp("(Xiaomi|Redmi)","i"),G=new RegExp("(OPPO|realme)","i"),j=new RegExp("(vivo|IQOO)","i"),z={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000",5.1:"XP",5.2:"XP","6.0":"Vista",6.1:"7",6.2:"8",6.3:"8.1",6.4:"10","10.0":"10"};function Y(e,t){return t=t||"",M(e," OPR/")&&M(e,"Mini")?$.OPERA_MINI:M(e," OPR/")?$.OPERA:X.test(e)?$.BLACKBERRY:M(e,"IE"+$.MOBILE)||M(e,"WPDesktop")?$.INTERNET_EXPLORER_MOBILE:M(e,$.SAMSUNG_BROWSER)?$.SAMSUNG_INTERNET:M(e,$.EDGE)||M(e,"Edg/")?$.MICROSOFT_EDGE:M(e,"FBIOS")?$.FACEBOOK+" "+$.MOBILE:M(e,"UCWEB")||M(e,"UCBrowser")?$.UC_BROWSER:M(e,"CriOS")?$.CHROME_IOS:M(e,"CrMo")||M(e,$.CHROME)?$.CHROME:M(e,$.ANDROID)&&M(e,$.SAFARI)?$.ANDROID_MOBILE:M(e,"FxiOS")?$.FIREFOX_IOS:M(e.toLowerCase(),$.KONQUEROR.toLowerCase())?$.KONQUEROR:function(e,t){return t&&M(t,$.APPLE)||M(n=e,$.SAFARI)&&!M(n,$.CHROME)&&!M(n,$.ANDROID);var n}(e,t)?M(e,$.MOBILE)?$.MOBILE_SAFARI:$.SAFARI:M(e,$.FIREFOX)?$.FIREFOX:M(e,"MSIE")||M(e,"Trident/")?$.INTERNET_EXPLORER:M(e,"Gecko")?$.FIREFOX:""}const K={[$.INTERNET_EXPLORER_MOBILE]:[new RegExp("rv:"+k)],[$.MICROSOFT_EDGE]:[new RegExp($.EDGE+"?\\/"+k)],[$.CHROME]:[new RegExp("("+$.CHROME+"|CrMo)\\/"+k)],[$.CHROME_IOS]:[new RegExp("CriOS\\/"+k)],[$.UC_BROWSER]:[new RegExp("(UCBrowser|UCWEB)\\/"+k)],[$.SAFARI]:[D],[$.MOBILE_SAFARI]:[D],[$.OPERA]:[new RegExp("("+$.OPERA+"|OPR)\\/"+k)],[$.FIREFOX]:[new RegExp($.FIREFOX+"\\/"+k)],[$.FIREFOX_IOS]:[new RegExp("FxiOS\\/"+k)],[$.KONQUEROR]:[new RegExp("Konqueror[:/]?"+k,"i")],[$.BLACKBERRY]:[new RegExp($.BLACKBERRY+" "+k),D],[$.ANDROID_MOBILE]:[new RegExp("android\\s"+k,"i")],[$.SAMSUNG_INTERNET]:[new RegExp($.SAMSUNG_BROWSER+"\\/"+k)],[$.INTERNET_EXPLORER]:[new RegExp("(rv:|MSIE )"+k)],Mozilla:[new RegExp("rv:"+k)]};function J(e,t){const n=Y(e,t),i=K[n];if(a(i))return null;for(let s=0;s<i.length;s++){const t=i[s],n=e.match(t);if(n)return parseFloat(n[n.length-2])}return null}const Z=[[new RegExp($.XBOX+"; "+$.XBOX+" (.*?)[);]","i"),e=>[$.XBOX,e&&e[1]||""]],[new RegExp($.NINTENDO,"i"),[$.NINTENDO,""]],[new RegExp($.PLAYSTATION,"i"),[$.PLAYSTATION,""]],[X,[$.BLACKBERRY,""]],[new RegExp($.WINDOWS,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[$.WINDOWS_PHONE,""];if(new RegExp($.MOBILE).test(t)&&!/IEMobile\b/.test(t))return[$.WINDOWS+" "+$.MOBILE,""];const n=/Windows NT ([0-9.]+)/i.exec(t);if(n&&n[1]){const e=n[1];let i=z[e]||"";return/arm/i.test(t)&&(i="RT"),[$.WINDOWS,i]}return[$.WINDOWS,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>{if(e&&e[3]){const t=[e[3],e[4],e[5]||"0"];return[$.IOS,t.join(".")]}return[$.IOS,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{let t="";return e&&e.length>=3&&(t=a(e[2])?e[3]:e[2]),["watchOS",t]}],[new RegExp("("+$.ANDROID+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+$.ANDROID+")","i"),e=>{if(e&&e[2]){const t=[e[2],e[3],e[4]||"0"];return[$.ANDROID,t.join(".")]}return[$.ANDROID,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,e=>{const t=["Mac OS X",""];if(e&&e[1]){const n=[e[1],e[2],e[3]||"0"];t[1]=n.join(".")}return t}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[$.CHROME_OS,""]],[/Linux|debian/i,["Linux",""]]];function Q(){const e=window.innerHeight||document.documentElement.clientHeight||document.body&&document.body.clientHeight||0,t=window.innerWidth||document.documentElement.clientWidth||document.body&&document.body.clientWidth||0,n=navigator.userAgent,i=function(e){for(let t=0;t<Z.length;t++){const[n,i]=Z[t],s=n.exec(e),r=s&&("function"==typeof i?i(s,e):i);if(r)return r}return["",""]}(n)||["",""];return{$browser:Y(n),$browser_version:J(n),$url:location?.href.substring(0,1e3),$host:location?.host,$viewport_height:e,$viewport_width:t,$lib:"webjs",$lib_version:A,$search_engine:F(),$referrer:B(),$referrer_host:m(r=r||B()),$title:document.title,$language:navigator.language,$model:(s=n,(U.test(s)?$.NINTENDO:H.test(s)?$.PLAYSTATION:x.test(s)?$.XBOX:new RegExp($.OUYA,"i").test(s)?$.OUYA:new RegExp("("+$.WINDOWS_PHONE+"|WPDesktop)","i").test(s)?$.WINDOWS_PHONE:/iPad/.test(s)?$.IPAD:/iPod/.test(s)?"iPod Touch":/iPhone/.test(s)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(s)?$.APPLE_WATCH:X.test(s)?$.BLACKBERRY:/(kobo)\s(ereader|touch)/i.test(s)?"Kobo":new RegExp($.NOKIA,"i").test(s)?$.NOKIA:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(s)||/(kf[a-z]+)( bui|\)).+silk\//i.test(s)?"Kindle Fire":q.test(s)?$.HUAWEI:W.test(s)?$.XIAOMI:G.test(s)?$.OPPO:j.test(s)?$.VIVO:/(Android|ZTE)/i.test(s)?!new RegExp($.MOBILE).test(s)||/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(s)?/pixel[\daxl ]{1,6}/i.test(s)&&!/pixel c/i.test(s)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(s)||/lmy47v/i.test(s)&&!/QTAQZ3/i.test(s)?$.ANDROID:$.ANDROID_TABLET:$.ANDROID:new RegExp("(pda|"+$.MOBILE+")","i").test(s)?$.GENERIC_MOBILE:new RegExp($.TABLET,"i").test(s)&&!new RegExp($.TABLET+" pc","i").test(s)?$.GENERIC_TABLET:"")||""),$os:i?.[0]||"",$os_version:i?.[1]||"",$pathname:location?.pathname,$screen_height:Number(screen.height)||0,$screen_width:Number(screen.width)||0,$timezone_offset:60*-(new Date).getTimezoneOffset()};var s,r}const V=new class{constructor(){this.STORAGE_KEY="sensorswave_unsent_events",this.MAX_QUEUE_SIZE=200,this.MAX_RETRY_COUNT=1,this.MAX_AGE_MS=6048e5,this.queue=[],this.loadFromStorage(),this.cleanupExpiredItems()}loadFromStorage(){try{const e=localStorage.getItem(this.STORAGE_KEY);e&&(this.queue=d(e)||[])}catch(e){console.warn("Failed to load queue from localStorage:",e),this.queue=[]}}cleanupExpiredItems(){const e=Date.now(),t=this.queue.filter(t=>e-t.timestamp<this.MAX_AGE_MS);t.length!==this.queue.length&&(this.queue=t,this.saveToStorage())}saveToStorage(){try{this.cleanupExpiredItems(),this.queue.length>this.MAX_QUEUE_SIZE&&(this.queue=this.queue.slice(-this.MAX_QUEUE_SIZE)),localStorage.setItem(this.STORAGE_KEY,JSON.stringify(this.queue))}catch(e){console.warn("Failed to save queue to localStorage:",e)}}enqueue(e,t,n,i=this.MAX_RETRY_COUNT){try{const s={id:f(),url:e,data:t,headers:n,timestamp:Date.now(),retryCount:0,maxRetries:i};return this.queue.push(s),this.saveToStorage(),s.id}catch(s){return console.warn("Failed to enqueue request:",s),""}}dequeue(e){try{this.queue=this.queue.filter(t=>t.id!==e),this.saveToStorage()}catch(t){console.warn("Failed to dequeue request:",t)}}getAll(){try{return this.cleanupExpiredItems(),[...this.queue]}catch(e){return console.warn("Failed to get queue items:",e),[]}}incrementRetryCount(e){const t=this.queue.find(t=>t.id===e);return!(!t||t.retryCount>=t.maxRetries||(t.retryCount++,this.saveToStorage(),0))}clear(){this.queue=[];try{localStorage.removeItem(this.STORAGE_KEY)}catch(e){console.warn("Failed to clear queue from localStorage:",e)}}getItemById(e){return this.queue.find(t=>t.id===e)}};class ee{constructor(e={}){this.flushTimer=null,this.isFlushing=!1,this.config={maxBatchSize:e.maxBatchSize||20,flushInterval:e.flushInterval||5e3},this.startFlushTimer()}add(){V.getAll().length>=this.config.maxBatchSize&&this.triggerFlush()}triggerFlush(){this.isFlushing||(this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.isFlushing=!0,this.flush())}flush(){const e=V.getAll();if(0===e.length)return this.isFlushing=!1,void this.startFlushTimer();const t=[],n=[];e.forEach(e=>{Array.isArray(e.data)?t.push(...e.data):t.push(e.data),n.push(e.id)});const i=t.slice(0,this.config.maxBatchSize),s=e[e.length-1],r=s.url,o=s.headers;O.instance.config.debug&&console.log(JSON.stringify(i,null,2)),L({url:r,method:"POST",data:i,headers:o,callback:e=>{200===e.statusCode?n.forEach(e=>{V.dequeue(e)}):console.error("Failed to send batch events:",e),this.isFlushing=!1,this.startFlushTimer()}})}startFlushTimer(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.flushTimer=setInterval(()=>{V.getAll().length>0&&this.triggerFlush()},this.config.flushInterval)}destroy(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.flush()}}let te=null;function ne(){const e=O.instance;return!(!e||!e.__innerInited)||(console.warn("[SensorsWave] SDK is not initialized. Please call init() first."),!1)}let ie=null;function se(){return S.isSupport()?(ie||(te||(te=new ee({maxBatchSize:20,flushInterval:5e3})),ie=te),ie):null}function re(e,t,n){return L({url:e,method:"POST",data:t.data,headers:t.headers,callback:e=>{if(200!==e.statusCode){if(n)if(V.incrementRetryCount(n)){const e=V.getItemById(n);if(e){const t=Math.min(1e3*Math.pow(2,e.retryCount),3e4);setTimeout(()=>{re(e.url,{data:e.data,headers:e.headers},e.id)},t)}}else console.warn("Max retries reached for request:",n)}else n&&V.dequeue(n),t.callback&&t.callback(e.json)}})}function oe(e){return`${e.apiHost}/in/track`}function ae(e){return`${e.apiHost}/ab/evalall`}function ce(e){return{"Content-Type":"application/json",SourceToken:e.sourceToken}}function le(e,t,n){O.instance.config.debug&&console.log(JSON.stringify(t.data,null,2));const i=V.enqueue(e,t.data,t.headers);return re(e,{...t,callback:void 0},i)}function ue(){try{const e=sessionStorage.getItem("sensorswave_utm");if(!e)return{};const t=JSON.parse(e),n={};return Object.entries(t).forEach(([e,t])=>{null!=t&&""!==t&&(n[`$${e}`]=t)}),n}catch(e){return{}}}function he(e){const t={};return Object.entries(e).forEach(([e,n])=>{if("function"==typeof n)try{const i=n();t[e]=i}catch(i){console.warn("[SensorsWave] Failed to resolve dynamic property:",e,i)}else t[e]=n}),t}function de(e={},t=!0){const n={...t?Q():{},...he(N.getCommonProps()),...e},i=ue();return Object.keys(i).length>0&&Object.assign(n,i),n}function ge(e,t,n=!0){if(!ne())return;const i={time:Date.now(),trace_id:N.getTraceId(),event:e.event,properties:de(e.properties,n)},s=ue();Object.keys(s).length>0&&(i.user_properties||(i.user_properties={}),i.user_properties.$set||(i.user_properties.$set={}),Object.assign(i.user_properties.$set,s)),e.user_properties&&(e.user_properties.$set&&(i.user_properties=i.user_properties||{},i.user_properties.$set={...i.user_properties.$set||{},...e.user_properties.$set},delete e.user_properties.$set),i.user_properties={...i.user_properties,...e.user_properties});const r=N.getLoginId(),o=N.getAnonId();r&&(i.login_id=r),o&&(i.anon_id=o);const a=oe(t),c=ce(t),l=!1!==t.batchSend&&se();l?(V.enqueue(a,[i],c),l.add()):le(a,{data:[i],headers:c})}function pe({userProps:e,opts:t}){if(!ne())return;const n=N.getLoginId(),i=N.getAnonId();if(!n&&!i)return;const s={time:Date.now(),trace_id:N.getTraceId(),event:"$UserSet",login_id:n,anon_id:i,user_properties:e,properties:de()},r=oe(t),o=ce(t),a=se();if(!a)return le(r,{data:[s],headers:o});V.enqueue(r,[s],o),a.add()}function fe(e){return e.typ===b.FEATURE_GATE||e.typ===b.FEATURE_CONFIG?`$feature_${e.id}`:e.typ===b.EXPERIMENT?`$exp_${e.id}`:""}function me(e){const t=e.typ;return[b.FEATURE_GATE,b.EXPERIMENT,b.FEATURE_CONFIG].includes(t)?{[fe(e)]:e.vid}:{}}function Ee(e){const t=e.typ;return t===b.FEATURE_GATE||t===b.FEATURE_CONFIG?{$feature_key:e.key,$feature_variant:e.vid}:t===b.EXPERIMENT?{$exp_key:e.key,$exp_variant:e.vid}:{}}function Ie({isUnset:e=!1,data:t,opts:n}){if(!ne())return;if(!t||l(t)||t.disable_impress)return;const i=N.getLoginId(),s=N.getAnonId();if(!i&&!s)return;const r=t.typ===b.EXPERIMENT?"$ExpImpress":"$FeatureImpress";let o={};return o=e?{$unset:{[fe(t)]:null}}:{$set:{...me(t)}},ge({event:r,properties:Ee(t),user_properties:o},n)}class Se{constructor({plugins:e,emitter:t,config:n,sdk:i}){this.plugins=[],this.pluginInsMap={},this.emitter=t,this.config=n,this.sdk=i,this.registerBuiltInPlugins(e),this.created(),this.emitter.on(v,()=>{this.init()})}registerBuiltInPlugins(e){for(let t=0,n=e.length;t<n;t++)this.registerPlugin(e[t])}registerPlugin(e){this.plugins.push(e)}getPlugins(){return this.plugins}getPlugin(e){return this.pluginInsMap[e]}created(){for(let e=0,t=this.plugins.length;e<t;e++){const t=this.plugins[e];if(!t.NAME)throw new Error('Plugin should be defined with "NAME"');const n=new t({emitter:this.emitter,config:this.config,sdk:this.sdk});this.pluginInsMap[t.NAME]=n}}init(){for(const e of Object.keys(this.pluginInsMap)){const t=this.pluginInsMap[e];t.init&&t.init()}}destroy(){for(const e of Object.keys(this.pluginInsMap)){const t=this.pluginInsMap[e];t.destroy&&"function"==typeof t.destroy&&t.destroy()}this.pluginInsMap={},this.plugins=[]}}const we=class{constructor({emitter:e,config:t}){this.boundSend=null,this.hashEvent=null,this.spaSwitchHandler=null,this.emitter=e,this.config=t}init(){const e=this.config;this.boundSend=()=>{ge({event:"$PageView",properties:{}},e)},setTimeout(()=>{this.boundSend()},0),e.isSinglePageApp&&this.addSinglePageListener()}addSinglePageListener(){this.spaSwitchHandler=e=>{e!==location.href&&this.boundSend()},this.emitter.on(R,this.spaSwitchHandler)}destroy(){this.spaSwitchHandler&&(this.emitter.off(R,this.spaSwitchHandler),this.spaSwitchHandler=null),this.hashEvent&&this.boundSend&&(window.removeEventListener(this.hashEvent,this.boundSend),this.hashEvent=null),this.boundSend=null}};we.NAME="pageview";let _e=we;const Oe=class{constructor({emitter:e,config:t}){this.startTime=Date.now(),this.pageShowStatus=!0,this.pageHiddenStatus=!1,this.timer=null,this.currentPageUrl=document.referrer,this.url=location.href,this.title=document.title||"",this.heartbeatIntervalTime=5e3,this.heartbeatIntervalTimer=null,this.pageId=null,this.storageName="sensorswavewebjssdkpageleave",this.maxDuration=432e3,this.eventListeners=[],this.emitter=e,this.config=t}init(){this.pageId=Number(String(p()).slice(2,5)+String(p()).slice(2,4)+String(Date.now()).slice(-4)),this.addEventListener(),!0===document.hidden?this.pageShowStatus=!1:this.addHeartBeatInterval()}log(e){console.log(e)}refreshPageEndTimer(){this.timer&&(clearTimeout(this.timer),this.timer=null),this.timer=setTimeout(()=>{this.pageHiddenStatus=!1},5e3)}hiddenStatusHandler(){this.timer&&clearTimeout(this.timer),this.timer=null,this.pageHiddenStatus=!1}pageStartHandler(){this.startTime=Date.now(),1==!document.hidden?this.pageShowStatus=!0:this.pageShowStatus=!1,this.url=location.href,this.title=document.title}pageEndHandler(){if(!0===this.pageHiddenStatus)return;const e=this.getPageLeaveProperties();!1===this.pageShowStatus&&delete e.$event_duration,this.pageShowStatus=!1,this.pageHiddenStatus=!0,ge({event:y,properties:e},this.config),this.refreshPageEndTimer(),this.delHeartBeatData()}addEventListener(){this.addPageStartListener(),this.addPageSwitchListener(),this.addSinglePageListener(),this.addPageEndListener()}addPageStartListener(){if("onpageshow"in window){const e=()=>{this.pageStartHandler(),this.hiddenStatusHandler()};window.addEventListener("pageshow",e),this.eventListeners.push({target:window,event:"pageshow",handler:e})}}addSinglePageListener(){this.config.isSinglePageApp&&this.emitter.on(R,e=>{e!==location.href&&(this.url=e,this.pageEndHandler(),this.stopHeartBeatInterval(),this.currentPageUrl=this.url,this.pageStartHandler(),this.hiddenStatusHandler(),this.addHeartBeatInterval())})}addPageEndListener(){["pagehide","beforeunload"].forEach(e=>{if(`on${e}`in window){const t=()=>{this.pageEndHandler(),this.stopHeartBeatInterval()};window.addEventListener(e,t),this.eventListeners.push({target:window,event:e,handler:t})}})}addPageSwitchListener(){const e=()=>{"visible"===document.visibilityState?(this.pageStartHandler(),this.hiddenStatusHandler(),this.addHeartBeatInterval()):(this.url=location.href,this.title=document.title,this.stopHeartBeatInterval())};document.addEventListener("visibilitychange",e),this.eventListeners.push({target:document,event:"visibilitychange",handler:e})}addHeartBeatInterval(){S.isSupport()&&this.startHeartBeatInterval()}startHeartBeatInterval(){this.heartbeatIntervalTimer&&this.stopHeartBeatInterval(),this.heartbeatIntervalTimer=setInterval(()=>{this.saveHeartBeatData()},this.heartbeatIntervalTime),this.saveHeartBeatData("is_first_heartbeat"),this.reissueHeartBeatData()}stopHeartBeatInterval(){this.heartbeatIntervalTimer&&clearInterval(this.heartbeatIntervalTimer),this.heartbeatIntervalTimer=null}saveHeartBeatData(e){const t=this.getPageLeaveProperties();t.$time=Date.now(),"is_first_heartbeat"===e&&(t.$event_duration=3);const n={type:"track",event:y,properties:t,time:t.$time};n.heartbeat_interval_time=this.heartbeatIntervalTime,S.isSupport()&&S.set(`${this.storageName}-${this.pageId}`,JSON.stringify(n))}delHeartBeatData(e){S.isSupport()&&S.remove(e||`${this.storageName}-${this.pageId}`)}reissueHeartBeatData(){for(let e=window.localStorage.length-1;e>=0;e--){const t=window.localStorage.key(e);if(t&&t!==`${this.storageName}-${this.pageId}`&&0===t.indexOf(`${this.storageName}-`)){const e=S.parse(t);i(e)&&Date.now()-e.time>e.heartbeat_interval_time+5e3&&(delete e.heartbeat_interval_time,e._flush_time=(new Date).getTime(),ge({event:y,properties:e?.properties},this.config),this.delHeartBeatData(t))}}}getPageLeaveProperties(){let e=(Date.now()-this.startTime)/1e3;(isNaN(e)||e<0||e>this.maxDuration)&&(e=0),e=Number(e.toFixed(3));const t={$title:this.title,$url:this.url?.substring(0,1e3),$pathname:_(this.url)};return 0!==e&&(t.$event_duration=e),t}destroy(){this.eventListeners.forEach(({target:e,event:t,handler:n})=>{e.removeEventListener(t,n)}),this.eventListeners=[],this.timer&&(clearTimeout(this.timer),this.timer=null),this.heartbeatIntervalTimer&&(clearInterval(this.heartbeatIntervalTimer),this.heartbeatIntervalTimer=null)}};Oe.NAME="pageleave";let Ae=Oe;const ve=class{constructor({emitter:e,config:t}){this.eventSended=!1,this.emitter=e,this.config=t}init(){const e=()=>{let t=0;const n={};if(window.performance){t=function(){let e=0;if("function"==typeof performance.getEntriesByType){const t=performance.getEntriesByType("navigation");t.length>0&&(e=t[0].domContentLoadedEventEnd||0)}return e}();const e=function(){if(performance.getEntries&&"function"==typeof performance.getEntries){const e=performance.getEntries();let t=0;for(const n of e)"transferSize"in n&&(t+=n.transferSize);if("number"==typeof t&&t>=0&&t<10737418240)return Number((t/1024).toFixed(3))}}();e&&(n.$page_resource_size=e)}else console.warn("Performance API is not supported.");t>0&&!Number.isFinite(t)&&(n.$event_duration=Number((t/1e3).toFixed(3))),this.eventSended||(this.eventSended=!0,ge({event:"$PageLoad",properties:n},this.config)),window.removeEventListener("load",e)};"complete"===document.readyState?e():window.addEventListener&&window.addEventListener("load",e)}};ve.NAME="pageload";let Re=ve;function Te(e,t){if(!u(e))return!1;const n=o(e.tagName)?e.tagName.toLowerCase():"",i={};i.$element_type=n,i.$element_name=e.getAttribute("name")||"",i.$element_id=e.getAttribute("id")||"",i.$element_class_name=o(e.className)?e.className:"",i.$element_target_url=e.getAttribute("href")||"",i.$element_content=function(e,t){return o(t)&&"input"===t.toLowerCase()?("button"===(n=e).type||"submit"===n.type)&&n.value||"":function(e,t){let n="",i="";return e.textContent?n=w(e.textContent):e.innerText&&(n=w(e.innerText)),n&&(n=n.replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)),i=n||"","input"!==t&&"INPUT"!==t||(i=e.value||""),i}(e,t);var n}(e,n)||"",i.$element_selector=ye(e)||"",i.$element_path=function(e){let t=[];for(;e.parentNode&&u(e);){if(!o(e.tagName))return"";if(e.id&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(e.id)){t.unshift(e.tagName.toLowerCase()+"#"+e.id);break}if(e===document.body){t.unshift("body");break}t.unshift(e.tagName.toLowerCase()),e=e.parentNode}return t.join(" > ")}(e)||"";const s=function(e,t){const n=t.pageX||t.clientX+be().scrollLeft||t.offsetX+Ne(e).targetEleX,i=t.pageY||t.clientY+be().scrollTop||t.offsetY+Ne(e).targetEleY;return{$page_x:Pe(n),$page_y:Pe(i)}}(e,t);return i.$page_x=s.$page_x,i.$page_y=s.$page_y,i}function ye(e,t=[]){if(!(e&&e.parentNode&&e.parentNode.children&&o(e.tagName)))return"";t=Array.isArray(t)?t:[];const n=e.nodeName.toLowerCase();return e&&"body"!==n&&1==e.nodeType?(t.unshift(function(e){if(!e||!u(e)||!o(e.tagName))return"";let t=e.parentNode&&9==e.parentNode.nodeType?-1:function(e){if(!e.parentNode)return-1;let t=0;const n=e.tagName,i=e.parentNode.children;for(let s=0,r=i.length;s<r;s++)if(i[s].tagName===n){if(e===i[s])return t;t++}return-1}(e);return e.getAttribute&&e.getAttribute("id")&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(e.getAttribute("id"))?"#"+e.getAttribute("id"):e.tagName.toLowerCase()+(~t?":nth-of-type("+(t+1)+")":"")}(e)),e.getAttribute&&e.getAttribute("id")&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(e.getAttribute("id"))?t.join(" > "):ye(e.parentNode,t)):(t.unshift("body"),t.join(" > "))}function be(){return{scrollLeft:document.body.scrollLeft||document.documentElement.scrollLeft||0,scrollTop:document.body.scrollTop||document.documentElement.scrollTop||0}}function Ne(e){if(document.documentElement.getBoundingClientRect){const t=e.getBoundingClientRect();return{targetEleX:t.left+be().scrollLeft||0,targetEleY:t.top+be().scrollTop||0}}return{targetEleX:0,targetEleY:0}}function Pe(e){return Number(Number(e).toFixed(3))}const Ce=class{constructor({emitter:e,config:t}){this.isInitialized=!1,this.boundHandleClick=null,this.emitter=e,this.config=t}init(){this.isInitialized||(this.boundHandleClick=this.handleClick.bind(this),document.addEventListener("click",this.boundHandleClick,!0),this.isInitialized=!0)}handleClick(e){const t=e.target;if(!t)return;if(!["A","INPUT","BUTTON","TEXTAREA"].includes(t.tagName))return;if("true"===t.getAttribute("sensorswave-disable"))return;ge({event:"$WebClick",properties:Te(t,e)||{}},this.config)}destroy(){this.boundHandleClick&&(document.removeEventListener("click",this.boundHandleClick,!0),this.boundHandleClick=null),this.isInitialized=!1}};Ce.NAME="webclick";let Le=Ce;const Be=class{constructor({emitter:e,config:t}){this.updateInterval=null,this.fetchingPromise=null,this.emitter=e,this.config=t}init(){const e=this.config;e.enableAB&&(this.fastFetch().then(()=>{this.emitter.emit(T)}),e.abRefreshInterval<3e4&&(e.abRefreshInterval=3e4),this.updateInterval=setInterval(()=>{this.fetchNewData().catch(console.warn)},e.abRefreshInterval))}async fastFetch(){const e=N.getABData(this.config.abRefreshInterval);return e&&e.length?(this.emitter.emit(T),Promise.resolve(e)):this.fetchNewData()}async fetchNewData(){return this.fetchingPromise||(this.fetchingPromise=new Promise(e=>{!function({opts:e,cb:t}){if(!ne())return void(t&&t({}));const n=N.getLoginId(),i=N.getAnonId();if(!n&&!i)return void(t&&t({}));const s={user:{login_id:n||"",anon_id:i||"",props:{...Q(),...he(N.getCommonProps())}},sdk:"webjs",sdk_version:A};L({url:ae(e),method:"POST",data:s,headers:ce(e),callback:e=>{200!==e.statusCode?(console.error("Failed to fetch feature flags"),t&&t({})):t&&t(e.json)}})}({opts:this.config,cb:t=>{N.saveABData(t?.data?.results||[]),e(t),this.fetchingPromise=null}})})),this.fetchingPromise}async getFeatureGate(e){return await this.fastFetch().catch(console.warn),N.getABData(this.config.abRefreshInterval).find(t=>t.typ===b.FEATURE_GATE&&t.key==e)}async checkFeatureGate(e){const t=await this.getFeatureGate(e);return!!t&&(!t.hasOwnProperty("vid")&&t.key?(Ie({isUnset:!0,data:t,opts:this.config}),!1):(Ie({data:t,opts:this.config}),"fail"!==t.vid))}async getExperiment(e){await this.fastFetch().catch(console.warn);const t=N.getABData(this.config.abRefreshInterval).find(t=>t.typ===b.EXPERIMENT&&t.key===e);return t?!t.hasOwnProperty("vid")&&t.key?(Ie({isUnset:!0,data:t,opts:this.config}),{}):(Ie({data:t,opts:this.config}),t?.value||{}):{}}async getFeatureConfig(e){await this.fastFetch().catch(console.warn);const t=N.getABData(this.config.abRefreshInterval).find(t=>t.typ===b.FEATURE_CONFIG&&t.key===e);if(!t)return{};if(!t.hasOwnProperty("vid")&&t.key)return Ie({isUnset:!0,data:t,opts:this.config}),{};Ie({data:t,opts:this.config});const n=t?.value;if(n){if(i(n))return n;try{return JSON.parse(n)}catch{return n}}return{}}destroy(){this.updateInterval&&(clearInterval(this.updateInterval),this.updateInterval=null),this.fetchingPromise=null}};Be.NAME="abtest";let Fe=Be;const Me=["utm_source","utm_medium","utm_campaign","utm_content","utm_term"],$e=class{constructor({sdk:e,emitter:t,config:n}){this.sdk=e,this.emitter=t,this.config=n}init(){const e=this.getUTMFromURL();this.saveToSessionStorage(e),setTimeout(()=>{this.sendInitialUTM(e)},0)}getUTMFromURL(){try{const e=new URLSearchParams(window.location.search),t={};return Me.forEach(n=>{const i=e.get(n);i&&(t[n]=i)}),t}catch(e){return this.getUTMFromURLFallback()}}getUTMFromURLFallback(){const e={};return window.location.search.substring(1).split("&").forEach(t=>{const[n,i]=t.split("="),s=decodeURIComponent(n),r=i?decodeURIComponent(i):"";Me.includes(s)&&(e[s]=r)}),e}saveToSessionStorage(e){try{sessionStorage.setItem("sensorswave_utm",JSON.stringify(e))}catch(t){this.config.debug&&console.warn("[SensorsWave UTM] Failed to save to sessionStorage:",t)}}sendInitialUTM(e){const t={};Me.forEach(n=>{t[`$initial_${n}`]=null!=e[n]?e[n]:""});try{this.sdk.profileSetOnce(t)}catch(n){this.config.debug&&console.warn("[SensorsWave UTM] Failed to send initial UTM:",n)}}destroy(){}};$e.NAME="UTM";let ke=$e;const De=[],xe={debug:!1,sourceToken:"",apiHost:"",autoCapture:!0,isSinglePageApp:!1,crossSubdomainCookie:!0,enableAB:!1,abRefreshInterval:6e5,enableClickTrack:!1,batchSend:!1};return new class{constructor(){this.__innerInited=!1,this.inited=!1,this.config={},this.eventEmitter=new e,this.pluginCore={},this.commonProps={},this.spaCleanup=null,O.instance=this}init(e,t={}){if(this.inited)return this;t.sourceToken=e,this.mergeConfig(t),this.eventEmitter.emit("init-param",this.config),this.__innerInited=!0;const n=this.config;return N.init(n.crossSubdomainCookie),n.anonId&&N.setAnonId(n.anonId),window._swFailedRequestsInitialized||(window._swFailedRequestsInitialized=!0,function(){const e=V.getAll();if(0!==e.length)for(let t=0,n=e.length;t<n;t+=10){const n=e.slice(t,t+10),i=[],s=[];n.forEach(e=>{Array.isArray(e.data)?i.push(...e.data):i.push(e.data),s.push(e.id)});const r=n[n.length-1],o=r.url,a=r.headers;L({url:o,method:"POST",data:i,headers:a,callback:e=>{200!==e.statusCode?console.error("Failed to send batch stored requests:",e):s.forEach(e=>{V.dequeue(e)})}})}}()),De.push(ke),n.autoCapture&&this.autoTrack(),n.enableAB&&De.push(Fe),n.enableClickTrack&&De.push(Le),this.pluginCore=new Se({plugins:De,emitter:this.eventEmitter,config:n,sdk:this}),this.spaCleanup=function(e){let t=location.href;const n=window.history.pushState,i=window.history.replaceState,r=function(){e(t),t=location.href};return s(window.history.pushState)&&(window.history.pushState=function(...i){n.apply(window.history,i),e(t),t=location.href}),s(window.history.replaceState)&&(window.history.replaceState=function(...n){i.apply(window.history,n),e(t),t=location.href}),window.addEventListener("popstate",r),function(){s(window.history.pushState)&&(window.history.pushState=n),s(window.history.replaceState)&&(window.history.replaceState=i),window.removeEventListener("popstate",r)}}(e=>{this.eventEmitter.emit(R,e)}),this.eventEmitter.emit(v),this.inited=!0,this}mergeConfig(e){this.config={...xe,...e}}track(e){!function(e,t){if(!ne())return;const n={...e};n.time||(n.time=Date.now()),n.login_id||(n.login_id=N.getLoginId()),n.anon_id||(n.anon_id=N.getAnonId()),n.trace_id||(n.trace_id=N.getTraceId()),n.properties={...Q(),...he(N.getCommonProps()),...n.properties};const i=oe(t),s=ce(t),r=!1!==t.batchSend&&se();if(!r)return le(i,{data:[n],headers:s});V.enqueue(i,[n],s),r.add()}(e,this.config)}trackEvent(e,t){ge({event:e,properties:t},this.config)}autoTrack(){De.push(_e,Re,Ae)}profileSet(e){pe({userProps:{$set:e},opts:this.config})}profileSetOnce(e){pe({userProps:{$set_once:e},opts:this.config})}profileIncrement(e){pe({userProps:{$increment:e},opts:this.config})}profileAppend(e){pe({userProps:{$append:e},opts:this.config})}profileUnion(e){pe({userProps:{$union:e},opts:this.config})}profileUnset(e){const t={};r(e)?e.forEach(function(e){t[e]=null}):t[e]=null,pe({userProps:{$unset:t},opts:this.config})}profileDelete(){pe({userProps:{$delete:!0},opts:this.config})}registerCommonProperties(e){if(!i(e))return console.warn("Commmon Properties must be an object!");this.commonProps=e,N.setCommonProps(this.commonProps)}clearCommonProperties(e){if(!r(e))return console.warn("Commmon Properties to be cleared must be an array!");e.forEach(e=>{delete this.commonProps[e]}),N.setCommonProps(this.commonProps)}identify(e){N.setLoginId(e),function(e){if(!ne())return;const t=N.getLoginId(),n=N.getAnonId();if(!t||!n)return;const i={time:Date.now(),trace_id:N.getTraceId(),event:"$Identify",login_id:t,anon_id:n,properties:de()},s=oe(e),r=ce(e),o=se();if(!o)return le(s,{data:[i],headers:r});V.enqueue(s,[i],r),o.add()}(this.config)}setLoginId(e){N.setLoginId(e)}getAnonId(){return N.getAnonId()}setAnonId(e){N.setAnonId(e)}getLoginId(){return N.getLoginId()}checkFeatureGate(e){const t=this.pluginCore.getPlugin(Fe.NAME);return this.config.enableAB&&t?t.checkFeatureGate(e):Promise.reject("AB is disabled")}getExperiment(e){const t=this.pluginCore.getPlugin(Fe.NAME);return this.config.enableAB&&t?t.getExperiment(e):Promise.reject("AB is disabled")}getFeatureConfig(e){const t=this.pluginCore.getPlugin(Fe.NAME);return this.config.enableAB&&t?t.getFeatureConfig(e):Promise.reject("AB is disabled")}destroy(){ie&&(ie.destroy(),ie=null),this.inited=!1,this.__innerInited=!1,this.spaCleanup&&"function"==typeof this.spaCleanup&&(this.spaCleanup(),this.spaCleanup=null),this.pluginCore&&"function"==typeof this.pluginCore.destroy&&this.pluginCore.destroy(),this.eventEmitter&&this.eventEmitter.removeAllListeners(),O.instance===this&&(O.instance=null)}}});
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).SensorsWave=e()}(this,function(){"use strict";class t{constructor(){this.listeners={}}on(t,e,n=!1){if(t&&e){if(!s(e))throw new Error("listener must be a function");this.listeners[t]=this.listeners[t]||[],this.listeners[t].push({listener:e,once:n})}}off(t,e){const n=this.listeners[t];if(!n?.length)return;"number"==typeof e&&n.splice(e,1);const i=n.findIndex(t=>t.listener===e);-1!==i&&n.splice(i,1)}emit(t,...e){this.listeners[t]&&this.listeners[t].forEach((n,i)=>{n.listener.call(this,...e),n.listener.once&&this.off(t,i)})}once(t,e){this.on(t,e,!0)}removeAllListeners(t){t?this.listeners[t]=[]:this.listeners={}}}const e={get:function(t){const e=t+"=",n=document.cookie.split(";");for(let i=0,s=n.length;i<s;i++){let t=n[i];for(;" "==t.charAt(0);)t=t.substring(1,t.length);if(0==t.indexOf(e))return h(t.substring(e.length,t.length))}return null},set:function({name:t,value:e,expires:n,samesite:i,secure:s,domain:r}){let o="",a="",c="",u="";if(0!==(n=null==n||void 0===n?365:n)){const t=new Date;"s"===String(n).slice(-1)?t.setTime(t.getTime()+1e3*Number(String(n).slice(0,-1))):t.setTime(t.getTime()+24*n*60*60*1e3),o="; expires="+t.toUTCString()}function l(t){return t?t.replace(/\r\n/g,""):""}i&&(c="; SameSite="+i),s&&(a="; secure");const h=l(t),d=l(e),p=l(r);p&&(u="; domain="+p),h&&d&&(document.cookie=h+"="+encodeURIComponent(d)+o+"; path=/"+u+c+a)},remove:function(t){this.set({name:t,value:"",expires:-1})},isSupport:function({samesite:t,secure:e}={}){if(!navigator.cookieEnabled)return!1;const n="sensorswave_cookie_support_test";return this.set({name:n,value:"1",samesite:t,secure:e}),"1"===this.get(n)&&(this.remove(n),!0)}},n=Object.prototype.toString;function i(t){return"[object Object]"===n.call(t)}function s(t){const e=n.call(t);return"[object Function]"==e||"[object AsyncFunction]"==e}function r(t){return"[object Array]"==n.call(t)}function o(t){return"[object String]"==n.call(t)}function a(t){return void 0===t}const c=Object.prototype.hasOwnProperty;function u(t){if(i(t)){for(let e in t)if(c.call(t,e))return!1;return!0}return!1}function l(t){return!(!t||1!==t.nodeType)}function h(t){let e=t;try{e=decodeURIComponent(t)}catch(n){e=t}return e}function d(t){try{return JSON.parse(t)}catch(e){return""}}const p=function(){let t=Date.now();return function(e){return Math.ceil((t=(9301*t+49297)%233280,t/233280*e))}}();function g(){if("function"==typeof Uint32Array){let t;if("undefined"!=typeof crypto&&(t=crypto),t&&i(t)&&t.getRandomValues)return t.getRandomValues(new Uint32Array(1))[0]/Math.pow(2,32)}return p(1e19)/1e19}const f=function(){function t(t){return("0".repeat(t)+Date.now().toString(16)).slice(-t)}return function(){let e=String(screen.height*screen.width);e=e&&/\d{4,}/.test(e)?e.slice(-4):String(31242*g()).replace(".","").slice(0,4);return t(8)+"-"+g().toString(16).replace(".","").slice(-4)+"-"+function(){const t=navigator.userAgent;let e,n=[],i=0;function s(t,e){let i=0;for(let s=0;s<e.length;s++)i|=n[s]<<8*s;return(t^i)>>>0}for(let r=0;r<t.length;r++)e=t.charCodeAt(r),n.unshift(255&e),n.length>=4&&(i=s(i,n),n=[]);return n.length>0&&(i=s(i,n)),("0000"+i.toString(16)).slice(-4)}()+"-"+e+"-"+t(12)||(String(g())+String(g())+String(g())).slice(2,15)}}();function m(t,e){e&&"string"==typeof e||(e="");let n=null;try{n=new URL(t).hostname}catch(i){}return n||e}function E(t){let e=[];try{e=atob(t).split("").map(function(t){return"%"+("00"+t.charCodeAt(0).toString(16)).slice(-2)})}catch(n){e=[]}try{return decodeURIComponent(e.join(""))}catch(n){return e.join("")}}function _(t){let e="";try{e=btoa(encodeURIComponent(t).replace(/%([0-9A-F]{2})/g,function(t,e){return String.fromCharCode(parseInt(e,16))}))}catch(n){e=t}return e}const I={get:function(t){return window.localStorage.getItem(t)},parse:function(t){let e;try{e=JSON.parse(I.get(t))||null}catch(n){console.warn(n)}return e},set:function(t,e){try{window.localStorage.setItem(t,e)}catch(n){console.warn(n)}},remove:function(t){window.localStorage.removeItem(t)},isSupport:function(){let t=!0;try{const e="__local_store_support__",n="testIsSupportStorage";I.set(e,n),I.get(e)!==n&&(t=!1),I.remove(e)}catch(e){t=!1}return t}};function S(t){return t.trim()}function w(t){if(!t||"string"!=typeof t)return"";try{return new URL(t,window.location.origin).pathname}catch(e){return""}}const O={},v="1.3.0",b="init-ready",y="spa-switch",A="ff-ready",R="$PageLeave",T="$Exception";var C=(t=>(t[t.FEATURE_GATE=1]="FEATURE_GATE",t[t.FEATURE_CONFIG=2]="FEATURE_CONFIG",t[t.EXPERIMENT=3]="EXPERIMENT",t))(C||{});const N={crossSubdomain:!1,requests:[],_sessionState:{},_abData:[],_trace_id:"",commonProps:{},_state:{anon_id:"",login_id:"",identities:{}},getIdentityCookieID(){return this._state.identities?.$identity_cookie_id||""},getCommonProps:function(){return this.commonProps||{}},setCommonProps:function(t){this.commonProps=t},getAnonId(){return this._state.anon_id||this.getIdentityCookieID()||f()},getLoginId(){return this._state.login_id},getTraceId(){return this._trace_id||f()},set:function(t,e){this._state[t]=e,this.save()},getCookieName:function(){return"sensorswave2025jssdkcross"},getABLSName:function(){return"sensorswave2025jssdkablatest"},save:function(){let t=JSON.parse(JSON.stringify(this._state));t.identities&&(t.identities=_(JSON.stringify(t.identities)));const n=JSON.stringify(t);e.set({name:this.getCookieName(),value:n,expires:365})},init:function(t){let n,s;this.crossSubdomain=t,e.isSupport()&&(n=e.get(this.getCookieName()),s=d(n)),N._state={...s||{}},N._state.identities&&(N._state.identities=d(E(N._state.identities))),N._state.identities&&i(N._state.identities)&&!u(N._state.identities)||(N._state.identities={$identity_cookie_id:f()}),N.save()},setLoginId(t){"number"==typeof t&&(t=String(t)),void 0!==t&&t&&(N.set("login_id",t),N.save())},setAnonId(t){"number"==typeof t&&(t=String(t)),"string"==typeof t&&t?(N.set("anon_id",t),N.save()):console.warn("[SensorsWave store] Invalid anonId, ignored:",t)},saveABData(t){if(!t||u(t))return;this._abData=t;let e=JSON.parse(JSON.stringify(this._abData));e=_(JSON.stringify(e));try{localStorage.setItem(this.getABLSName(),JSON.stringify({time:Date.now(),data:e,anon_id:this.getAnonId(),login_id:this.getLoginId()}))}catch(n){console.warn("Failed to save abdata to localStorage",n)}},getABData(t=6e5){try{let e=localStorage.getItem(this.getABLSName());if(e){const{time:n,data:i,login_id:s,anon_id:r}=d(e)||{};if(n&&i&&Date.now()-n<t&&r===this.getAnonId()&&(!s||s===this.getLoginId())){const t=d(E(i));return this._abData=Array.isArray(t)?t:[],this._abData}localStorage.removeItem(this.getABLSName())}}catch(e){this._abData=[]}return this._abData||[]}};function P(t){return!(t>=400&&t<500)||408===t||429===t}function k(t){var e;if(t.data)return{contentType:"application/json",body:(e=t.data,JSON.stringify(e,(t,e)=>"bigint"==typeof e?e.toString():e,undefined))}}const L=[];function $(t){const e={...t};e.timeout=e.timeout||6e4;const n=e.transport??"fetch",i=L.find(t=>t.transport===n)?.method??L[0]?.method;if(!i)throw new Error("No available transport method for HTTP request");i(e)}function F(t){return o(t=t||document.referrer)&&(t=h(t=t.trim()))||""}function x(t){const e=m(t=t||F());if(!e)return"";const n={baidu:[/^.*\.baidu\.com$/],bing:[/^.*\.bing\.com$/],google:[/^www\.google\.com$/,/^www\.google\.com\.[a-z]{2}$/,/^www\.google\.[a-z]{2}$/],sm:[/^m\.sm\.cn$/],so:[/^.+\.so\.com$/],sogou:[/^.*\.sogou\.com$/],yahoo:[/^.*\.yahoo\.com$/],duckduckgo:[/^.*\.duckduckgo\.com$/]};for(let i of Object.keys(n)){let t=n[i];for(let n=0,s=t.length;n<s;n++)if(t[n].test(e))return i}return""}function B(t,e){return-1!==t.indexOf(e)}"function"==typeof fetch&&L.push({transport:"fetch",method:function(t){if("undefined"==typeof fetch)return void console.error("fetch API is not available");const e=k(t),n=new Headers;t.headers&&Object.keys(t.headers).forEach(e=>{n.append(e,t.headers[e])}),e?.contentType&&n.append("Content-Type",e.contentType),fetch(t.url,{method:t.method||"GET",headers:n,body:e?.body}).then(e=>e.text().then(n=>{const i={statusCode:e.status,text:n};if(200===e.status)try{i.json=JSON.parse(n)}catch(s){console.error("Failed to parse response:",s)}t.callback?.(i)})).catch(e=>{console.error("Request failed:",e),t.callback?.({statusCode:0,text:String(e)})})}}),"undefined"!=typeof XMLHttpRequest&&L.push({transport:"XHR",method:function(t){if("undefined"==typeof XMLHttpRequest)return void console.error("XMLHttpRequest is not available");const e=new XMLHttpRequest;e.open(t.method||"GET",t.url,!0);const n=k(t);t.headers&&Object.keys(t.headers).forEach(n=>{e.setRequestHeader(n,t.headers[n])}),n?.contentType&&e.setRequestHeader("Content-Type",n.contentType),e.timeout=t.timeout||6e4,e.withCredentials=!0,e.onreadystatechange=()=>{if(4===e.readyState){const i={statusCode:e.status,text:e.responseText};if(200===e.status)try{i.json=JSON.parse(e.responseText)}catch(n){console.error("Failed to parse JSON response:",n)}t.callback?.(i)}},e.send(n?.body)}});const M={FACEBOOK:"Facebook",MOBILE:"Mobile",IOS:"iOS",ANDROID:"Android",TABLET:"Tablet",ANDROID_TABLET:"Android Tablet",IPAD:"iPad",APPLE:"Apple",APPLE_WATCH:"Apple Watch",SAFARI:"Safari",BLACKBERRY:"BlackBerry",SAMSUNG_BROWSER:"SamsungBrowser",SAMSUNG_INTERNET:"Samsung Internet",CHROME:"Chrome",CHROME_OS:"Chrome OS",CHROME_IOS:"Chrome iOS",INTERNET_EXPLORER:"Internet Explorer",INTERNET_EXPLORER_MOBILE:"Internet Explorer Mobile",OPERA:"Opera",OPERA_MINI:"Opera Mini",EDGE:"Edge",MICROSOFT_EDGE:"Microsoft Edge",FIREFOX:"Firefox",FIREFOX_IOS:"Firefox iOS",NINTENDO:"Nintendo",PLAYSTATION:"PlayStation",XBOX:"Xbox",ANDROID_MOBILE:"Android Mobile",MOBILE_SAFARI:"Mobile Safari",WINDOWS:"Windows",WINDOWS_PHONE:"Windows Phone",NOKIA:"Nokia",OUYA:"Ouya",GENERIC_MOBILE:"Generic mobile",GENERIC_TABLET:"Generic tablet",KONQUEROR:"Konqueror",UC_BROWSER:"UC Browser",HUAWEI:"Huawei",XIAOMI:"Xiaomi",OPPO:"OPPO",VIVO:"vivo"},D="(\\d+(\\.\\d+)?)",H=new RegExp("Version/"+D),U=new RegExp(M.XBOX,"i"),X=new RegExp(M.PLAYSTATION+" \\w+","i"),j=new RegExp(M.NINTENDO+" \\w+","i"),q=new RegExp(M.BLACKBERRY+"|PlayBook|BB10","i"),W=new RegExp("(HUAWEI|honor|HONOR)","i"),G=new RegExp("(Xiaomi|Redmi)","i"),z=new RegExp("(OPPO|realme)","i"),Y=new RegExp("(vivo|IQOO)","i"),K={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000",5.1:"XP",5.2:"XP","6.0":"Vista",6.1:"7",6.2:"8",6.3:"8.1",6.4:"10","10.0":"10"};function J(t,e){return e=e||"",B(t," OPR/")&&B(t,"Mini")?M.OPERA_MINI:B(t," OPR/")?M.OPERA:q.test(t)?M.BLACKBERRY:B(t,"IE"+M.MOBILE)||B(t,"WPDesktop")?M.INTERNET_EXPLORER_MOBILE:B(t,M.SAMSUNG_BROWSER)?M.SAMSUNG_INTERNET:B(t,M.EDGE)||B(t,"Edg/")?M.MICROSOFT_EDGE:B(t,"FBIOS")?M.FACEBOOK+" "+M.MOBILE:B(t,"UCWEB")||B(t,"UCBrowser")?M.UC_BROWSER:B(t,"CriOS")?M.CHROME_IOS:B(t,"CrMo")||B(t,M.CHROME)?M.CHROME:B(t,M.ANDROID)&&B(t,M.SAFARI)?M.ANDROID_MOBILE:B(t,"FxiOS")?M.FIREFOX_IOS:B(t.toLowerCase(),M.KONQUEROR.toLowerCase())?M.KONQUEROR:function(t,e){return e&&B(e,M.APPLE)||B(n=t,M.SAFARI)&&!B(n,M.CHROME)&&!B(n,M.ANDROID);var n}(t,e)?B(t,M.MOBILE)?M.MOBILE_SAFARI:M.SAFARI:B(t,M.FIREFOX)?M.FIREFOX:B(t,"MSIE")||B(t,"Trident/")?M.INTERNET_EXPLORER:B(t,"Gecko")?M.FIREFOX:""}const Z={[M.INTERNET_EXPLORER_MOBILE]:[new RegExp("rv:"+D)],[M.MICROSOFT_EDGE]:[new RegExp(M.EDGE+"?\\/"+D)],[M.CHROME]:[new RegExp("("+M.CHROME+"|CrMo)\\/"+D)],[M.CHROME_IOS]:[new RegExp("CriOS\\/"+D)],[M.UC_BROWSER]:[new RegExp("(UCBrowser|UCWEB)\\/"+D)],[M.SAFARI]:[H],[M.MOBILE_SAFARI]:[H],[M.OPERA]:[new RegExp("("+M.OPERA+"|OPR)\\/"+D)],[M.FIREFOX]:[new RegExp(M.FIREFOX+"\\/"+D)],[M.FIREFOX_IOS]:[new RegExp("FxiOS\\/"+D)],[M.KONQUEROR]:[new RegExp("Konqueror[:/]?"+D,"i")],[M.BLACKBERRY]:[new RegExp(M.BLACKBERRY+" "+D),H],[M.ANDROID_MOBILE]:[new RegExp("android\\s"+D,"i")],[M.SAMSUNG_INTERNET]:[new RegExp(M.SAMSUNG_BROWSER+"\\/"+D)],[M.INTERNET_EXPLORER]:[new RegExp("(rv:|MSIE )"+D)],Mozilla:[new RegExp("rv:"+D)]};function Q(t,e){const n=J(t,e),i=Z[n];if(a(i))return null;for(let s=0;s<i.length;s++){const e=i[s],n=t.match(e);if(n)return parseFloat(n[n.length-2])}return null}const V=[[new RegExp(M.XBOX+"; "+M.XBOX+" (.*?)[);]","i"),t=>[M.XBOX,t&&t[1]||""]],[new RegExp(M.NINTENDO,"i"),[M.NINTENDO,""]],[new RegExp(M.PLAYSTATION,"i"),[M.PLAYSTATION,""]],[q,[M.BLACKBERRY,""]],[new RegExp(M.WINDOWS,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[M.WINDOWS_PHONE,""];if(new RegExp(M.MOBILE).test(e)&&!/IEMobile\b/.test(e))return[M.WINDOWS+" "+M.MOBILE,""];const n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){const t=n[1];let i=K[t]||"";return/arm/i.test(e)&&(i="RT"),[M.WINDOWS,i]}return[M.WINDOWS,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>{if(t&&t[3]){const e=[t[3],t[4],t[5]||"0"];return[M.IOS,e.join(".")]}return[M.IOS,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{let e="";return t&&t.length>=3&&(e=a(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+M.ANDROID+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+M.ANDROID+")","i"),t=>{if(t&&t[2]){const e=[t[2],t[3],t[4]||"0"];return[M.ANDROID,e.join(".")]}return[M.ANDROID,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{const e=["Mac OS X",""];if(t&&t[1]){const n=[t[1],t[2],t[3]||"0"];e[1]=n.join(".")}return e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[M.CHROME_OS,""]],[/Linux|debian/i,["Linux",""]]];function tt(){const t=window.innerHeight||document.documentElement.clientHeight||document.body&&document.body.clientHeight||0,e=window.innerWidth||document.documentElement.clientWidth||document.body&&document.body.clientWidth||0,n=navigator.userAgent,i=function(t){for(let e=0;e<V.length;e++){const[n,i]=V[e],s=n.exec(t),r=s&&("function"==typeof i?i(s,t):i);if(r)return r}return["",""]}(n)||["",""];return{$browser:J(n),$browser_version:Q(n),$url:location?.href.substring(0,1e3),$host:location?.host,$viewport_height:t,$viewport_width:e,$lib:"webjs",$lib_version:v,$search_engine:x(),$referrer:F(),$referrer_host:m(r=r||F()),$title:document.title,$language:navigator.language,$model:(s=n,(j.test(s)?M.NINTENDO:X.test(s)?M.PLAYSTATION:U.test(s)?M.XBOX:new RegExp(M.OUYA,"i").test(s)?M.OUYA:new RegExp("("+M.WINDOWS_PHONE+"|WPDesktop)","i").test(s)?M.WINDOWS_PHONE:/iPad/.test(s)?M.IPAD:/iPod/.test(s)?"iPod Touch":/iPhone/.test(s)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(s)?M.APPLE_WATCH:q.test(s)?M.BLACKBERRY:/(kobo)\s(ereader|touch)/i.test(s)?"Kobo":new RegExp(M.NOKIA,"i").test(s)?M.NOKIA:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(s)||/(kf[a-z]+)( bui|\)).+silk\//i.test(s)?"Kindle Fire":W.test(s)?M.HUAWEI:G.test(s)?M.XIAOMI:z.test(s)?M.OPPO:Y.test(s)?M.VIVO:/(Android|ZTE)/i.test(s)?!new RegExp(M.MOBILE).test(s)||/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(s)?/pixel[\daxl ]{1,6}/i.test(s)&&!/pixel c/i.test(s)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(s)||/lmy47v/i.test(s)&&!/QTAQZ3/i.test(s)?M.ANDROID:M.ANDROID_TABLET:M.ANDROID:new RegExp("(pda|"+M.MOBILE+")","i").test(s)?M.GENERIC_MOBILE:new RegExp(M.TABLET,"i").test(s)&&!new RegExp(M.TABLET+" pc","i").test(s)?M.GENERIC_TABLET:"")||""),$os:i?.[0]||"",$os_version:i?.[1]||"",$pathname:location?.pathname,$screen_height:Number(screen.height)||0,$screen_width:Number(screen.width)||0,$timezone_offset:60*-(new Date).getTimezoneOffset()};var s,r}const et=new class{constructor(){this.STORAGE_KEY="sensorswave_unsent_events",this.MAX_QUEUE_SIZE=200,this.MAX_RETRY_COUNT=1,this.MAX_AGE_MS=6048e5,this.queue=[],this.loadFromStorage(),this.cleanupExpiredItems()}loadFromStorage(){try{const t=localStorage.getItem(this.STORAGE_KEY);t&&(this.queue=d(t)||[])}catch(t){console.warn("Failed to load queue from localStorage:",t),this.queue=[]}}cleanupExpiredItems(){const t=Date.now(),e=this.queue.filter(e=>t-e.timestamp<this.MAX_AGE_MS);e.length!==this.queue.length&&(this.queue=e,this.saveToStorage())}saveToStorage(){try{this.cleanupExpiredItems(),this.queue.length>this.MAX_QUEUE_SIZE&&(this.queue=this.queue.slice(-this.MAX_QUEUE_SIZE)),localStorage.setItem(this.STORAGE_KEY,JSON.stringify(this.queue))}catch(t){console.warn("Failed to save queue to localStorage:",t)}}enqueue(t,e,n,i=this.MAX_RETRY_COUNT){try{const s={id:f(),url:t,data:e,headers:n,timestamp:Date.now(),retryCount:0,maxRetries:i};return this.queue.push(s),this.saveToStorage(),s.id}catch(s){return console.warn("Failed to enqueue request:",s),""}}dequeue(t){try{this.queue=this.queue.filter(e=>e.id!==t),this.saveToStorage()}catch(e){console.warn("Failed to dequeue request:",e)}}getAll(){try{return this.cleanupExpiredItems(),[...this.queue]}catch(t){return console.warn("Failed to get queue items:",t),[]}}incrementRetryCount(t){const e=this.queue.find(e=>e.id===t);return!(!e||e.retryCount>=e.maxRetries||(e.retryCount++,this.saveToStorage(),0))}clear(){this.queue=[];try{localStorage.removeItem(this.STORAGE_KEY)}catch(t){console.warn("Failed to clear queue from localStorage:",t)}}getItemById(t){return this.queue.find(e=>e.id===t)}};class nt{constructor(t={}){this.flushTimer=null,this.isFlushing=!1,this.paused=!1,this.destroyed=!1,this.config={maxBatchSize:t.maxBatchSize||20,flushInterval:t.flushInterval||5e3},this.startFlushTimer()}pause(){this.paused=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null)}resume(){this.paused&&(this.paused=!1,this.startFlushTimer())}isPaused(){return this.paused}add(){et.getAll().length>=this.config.maxBatchSize&&this.triggerFlush()}triggerFlush(){this.paused||this.isFlushing||(this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.isFlushing=!0,this.flush())}flush(){const t=et.getAll();if(0===t.length)return this.isFlushing=!1,void this.startFlushTimer();const e=t.slice(0,this.config.maxBatchSize),n=[],i=[];e.forEach(t=>{Array.isArray(t.data)?n.push(...t.data):n.push(t.data),i.push(t.id)});const s=e[e.length-1],r=s.url,o=s.headers;O.instance&&O.instance.config.debug&&console.log(JSON.stringify(n,null,2)),$({url:r,method:"POST",data:n,headers:o,callback:t=>{200===t.statusCode?i.forEach(t=>{et.dequeue(t)}):P(t.statusCode)?console.error("Failed to send batch events:",t):i.forEach(t=>{et.dequeue(t)}),this.isFlushing=!1,this.startFlushTimer()}})}startFlushTimer(){this.destroyed||(this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.flushTimer=setInterval(()=>{et.getAll().length>0&&this.triggerFlush()},this.config.flushInterval))}destroy(){this.destroyed=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.paused||this.flush()}}let it=null;function st(){const t=O.instance;return!(!t||!t.__innerInited)||(console.warn("[SensorsWave] SDK is not initialized. Please call init() first."),!1)}function rt(){const t=O.instance;return!t||"function"!=typeof t.hasOptedOutCapturing||!t.hasOptedOutCapturing()}let ot=null;function at(){return I.isSupport()?(ot||(it||(it=new nt({maxBatchSize:20,flushInterval:5e3})),ot=it),ot):null}function ct(t,e,n){if(rt())return $({url:t,method:"POST",data:e.data,headers:e.headers,callback:t=>{if(200!==t.statusCode){if(!P(t.statusCode))return void(n&&et.dequeue(n));if(n&&et.incrementRetryCount(n)){const t=et.getItemById(n);if(t){const e=Math.min(1e3*Math.pow(2,t.retryCount),3e4);setTimeout(()=>{ct(t.url,{data:t.data,headers:t.headers},t.id)},e)}}}else n&&et.dequeue(n),e.callback&&e.callback(t.json)}})}function ut(t){return`${t.apiHost}/in/track`}function lt(t){return`${t.apiHost}/ab/evalall`}function ht(t){return{"Content-Type":"application/json",SourceToken:t.sourceToken}}function dt(t,e,n){O.instance&&O.instance.config.debug&&console.log(JSON.stringify(e.data,null,2));const i=et.enqueue(t,e.data,e.headers);return ct(t,{...e,callback:void 0},i)}function pt(){try{const t=sessionStorage.getItem("sensorswave_utm");if(!t)return{};const e=JSON.parse(t),n={};return Object.entries(e).forEach(([t,e])=>{null!=e&&""!==e&&(n[`$${t}`]=e)}),n}catch(t){return{}}}function gt(t){const e={};return Object.entries(t).forEach(([t,n])=>{if("function"==typeof n)try{const i=n();e[t]=i}catch(i){console.warn("[SensorsWave] Failed to resolve dynamic property:",t,i)}else e[t]=n}),e}function ft(t={},e=!0){const n={...e?tt():{},...gt(N.getCommonProps()),...t},i=pt();return Object.keys(i).length>0&&Object.assign(n,i),n}function mt(t,e,n=!0){if(!st())return;if(!rt())return;const i={time:Date.now(),trace_id:N.getTraceId(),event:t.event,properties:ft(t.properties,n)},s=pt();Object.keys(s).length>0&&(i.user_properties||(i.user_properties={}),i.user_properties.$set||(i.user_properties.$set={}),Object.assign(i.user_properties.$set,s)),t.user_properties&&(t.user_properties.$set&&(i.user_properties=i.user_properties||{},i.user_properties.$set={...i.user_properties.$set||{},...t.user_properties.$set},delete t.user_properties.$set),i.user_properties={...i.user_properties,...t.user_properties});const r=N.getLoginId(),o=N.getAnonId();r&&(i.login_id=r),o&&(i.anon_id=o);const a=ut(e),c=ht(e),u=!1!==e.batchSend&&at();u?(et.enqueue(a,[i],c),u.add()):dt(a,{data:[i],headers:c})}function Et({userProps:t,opts:e}){if(!st())return;if(!rt())return;const n=N.getLoginId(),i=N.getAnonId();if(!n&&!i)return;const s={time:Date.now(),trace_id:N.getTraceId(),event:"$UserSet",login_id:n,anon_id:i,user_properties:t,properties:ft()},r=ut(e),o=ht(e),a=at();if(!a)return dt(r,{data:[s],headers:o});et.enqueue(r,[s],o),a.add()}function _t(t){return t.typ===C.FEATURE_GATE||t.typ===C.FEATURE_CONFIG?`$feature_${t.id}`:t.typ===C.EXPERIMENT?`$exp_${t.id}`:""}function It(t){const e=t.typ;return[C.FEATURE_GATE,C.EXPERIMENT,C.FEATURE_CONFIG].includes(e)?{[_t(t)]:t.vid}:{}}function St(t){const e=t.typ;return e===C.FEATURE_GATE||e===C.FEATURE_CONFIG?{$feature_key:t.key,$feature_variant:t.vid}:e===C.EXPERIMENT?{$exp_key:t.key,$exp_variant:t.vid}:{}}function wt({isUnset:t=!1,data:e,opts:n}){if(!st())return;if(!rt())return;if(!e||u(e)||e.disable_impress)return;const i=N.getLoginId(),s=N.getAnonId();if(!i&&!s)return;const r=e.typ===C.EXPERIMENT?"$ExpImpress":"$FeatureImpress";let o={};return o=t?{$unset:{[_t(e)]:null}}:{$set:{...It(e)}},mt({event:r,properties:St(e),user_properties:o},n)}const Ot="sensorswave_opt_out";class vt{constructor(t){this.persist=t}read(){if(this.persist)try{const t=I.get(Ot);return"0"===t||"1"!==t&&void 0}catch{return}}write(t){if(this.persist)try{I.set(Ot,t?"0":"1")}catch{}}}class bt{constructor({plugins:t,emitter:e,config:n,sdk:i}){this.plugins=[],this.pluginInsMap={},this.emitter=e,this.config=n,this.sdk=i,this.registerBuiltInPlugins(t),this.created(),this.emitter.on(b,()=>{this.init()})}registerBuiltInPlugins(t){for(let e=0,n=t.length;e<n;e++)this.registerPlugin(t[e])}registerPlugin(t){this.plugins.push(t)}getPlugins(){return this.plugins}getPlugin(t){return this.pluginInsMap[t]}created(){for(let t=0,e=this.plugins.length;t<e;t++){const e=this.plugins[t];if(!e.NAME)throw new Error('Plugin should be defined with "NAME"');const n=new e({emitter:this.emitter,config:this.config,sdk:this.sdk});this.pluginInsMap[e.NAME]=n}}init(){for(const t of Object.keys(this.pluginInsMap)){const e=this.pluginInsMap[t];e.init&&e.init()}}destroy(){for(const t of Object.keys(this.pluginInsMap)){const e=this.pluginInsMap[t];e.destroy&&"function"==typeof e.destroy&&e.destroy()}this.pluginInsMap={},this.plugins=[]}}const yt=class{constructor({emitter:t,config:e,sdk:n}){this.boundSend=null,this.hashEvent=null,this.spaSwitchHandler=null,this.emitter=t,this.config=e,this.sdk=n}init(){const t=this.config;this.boundSend=()=>{mt({event:"$PageView",properties:{}},t)},this.sdk&&!0===this.sdk._postConsentInit||setTimeout(()=>{this.boundSend()},0),t.isSinglePageApp&&this.addSinglePageListener()}addSinglePageListener(){this.spaSwitchHandler=t=>{t!==location.href&&this.boundSend()},this.emitter.on(y,this.spaSwitchHandler)}destroy(){this.spaSwitchHandler&&(this.emitter.off(y,this.spaSwitchHandler),this.spaSwitchHandler=null),this.hashEvent&&this.boundSend&&(window.removeEventListener(this.hashEvent,this.boundSend),this.hashEvent=null),this.boundSend=null}};yt.NAME="pageview";let At=yt;const Rt=class{constructor({emitter:t,config:e,sdk:n}){this.startTime=Date.now(),this.pageShowStatus=!0,this.pageHiddenStatus=!1,this.timer=null,this.currentPageUrl=document.referrer,this.url=location.href,this.title=document.title||"",this.heartbeatIntervalTime=5e3,this.heartbeatIntervalTimer=null,this.pageId=null,this.storageName="sensorswavewebjssdkpageleave",this.maxDuration=432e3,this.eventListeners=[],this._skipFirstPageEnd=!1,this.emitter=t,this.config=e,this.sdk=n}__canCapture(){return!this.sdk||"function"!=typeof this.sdk.hasOptedOutCapturing||!this.sdk.hasOptedOutCapturing()}init(){this.pageId=Number(String(g()).slice(2,5)+String(g()).slice(2,4)+String(Date.now()).slice(-4)),this.addEventListener(),this.sdk&&!0===this.sdk._postConsentInit&&(this._skipFirstPageEnd=!0),!0===document.hidden?this.pageShowStatus=!1:this.addHeartBeatInterval()}log(t){console.log(t)}refreshPageEndTimer(){this.timer&&(clearTimeout(this.timer),this.timer=null),this.timer=setTimeout(()=>{this.pageHiddenStatus=!1},5e3)}hiddenStatusHandler(){this.timer&&clearTimeout(this.timer),this.timer=null,this.pageHiddenStatus=!1}pageStartHandler(){this.startTime=Date.now(),1==!document.hidden?this.pageShowStatus=!0:this.pageShowStatus=!1,this.url=location.href,this.title=document.title,this._skipFirstPageEnd=!1}pageEndHandler(){if(!0===this.pageHiddenStatus)return;if(!this.__canCapture())return;const t=this.getPageLeaveProperties();!1===this.pageShowStatus&&delete t.$event_duration,this.pageShowStatus=!1,this.pageHiddenStatus=!0,mt({event:R,properties:t},this.config),this.refreshPageEndTimer(),this.delHeartBeatData()}addEventListener(){this.addPageStartListener(),this.addPageSwitchListener(),this.addSinglePageListener(),this.addPageEndListener()}addPageStartListener(){if("onpageshow"in window){const t=()=>{this.pageStartHandler(),this.hiddenStatusHandler()};window.addEventListener("pageshow",t),this.eventListeners.push({target:window,event:"pageshow",handler:t})}}addSinglePageListener(){this.config.isSinglePageApp&&this.emitter.on(y,t=>{t!==location.href&&(this.url=t,this.pageEndHandler(),this.stopHeartBeatInterval(),this.currentPageUrl=this.url,this.pageStartHandler(),this.hiddenStatusHandler(),this.addHeartBeatInterval())})}addPageEndListener(){["pagehide","beforeunload"].forEach(t=>{if(`on${t}`in window){const e=()=>{if(this._skipFirstPageEnd)return this._skipFirstPageEnd=!1,void this.stopHeartBeatInterval();this.pageEndHandler(),this.stopHeartBeatInterval()};window.addEventListener(t,e),this.eventListeners.push({target:window,event:t,handler:e})}})}addPageSwitchListener(){const t=()=>{"visible"===document.visibilityState?(this.pageStartHandler(),this.hiddenStatusHandler(),this.addHeartBeatInterval()):(this.url=location.href,this.title=document.title,this.stopHeartBeatInterval())};document.addEventListener("visibilitychange",t),this.eventListeners.push({target:document,event:"visibilitychange",handler:t})}addHeartBeatInterval(){I.isSupport()&&this.startHeartBeatInterval()}startHeartBeatInterval(){this.heartbeatIntervalTimer&&this.stopHeartBeatInterval(),this.sdk&&!0===this.sdk._postConsentInit&&!0===this._skipFirstPageEnd||(this.heartbeatIntervalTimer=setInterval(()=>{this.saveHeartBeatData()},this.heartbeatIntervalTime),this.saveHeartBeatData("is_first_heartbeat"),this.reissueHeartBeatData())}stopHeartBeatInterval(){this.heartbeatIntervalTimer&&clearInterval(this.heartbeatIntervalTimer),this.heartbeatIntervalTimer=null}saveHeartBeatData(t){if(!this.__canCapture())return;const e=this.getPageLeaveProperties();e.$time=Date.now(),"is_first_heartbeat"===t&&(e.$event_duration=3);const n={type:"track",event:R,properties:e,time:e.$time};n.heartbeat_interval_time=this.heartbeatIntervalTime,I.isSupport()&&I.set(`${this.storageName}-${this.pageId}`,JSON.stringify(n))}delHeartBeatData(t){I.isSupport()&&I.remove(t||`${this.storageName}-${this.pageId}`)}reissueHeartBeatData(){if(this.__canCapture())for(let t=window.localStorage.length-1;t>=0;t--){const e=window.localStorage.key(t);if(e&&e!==`${this.storageName}-${this.pageId}`&&0===e.indexOf(`${this.storageName}-`)){const t=I.parse(e);i(t)&&Date.now()-t.time>t.heartbeat_interval_time+5e3&&(delete t.heartbeat_interval_time,t._flush_time=(new Date).getTime(),mt({event:R,properties:t?.properties},this.config),this.delHeartBeatData(e))}}}getPageLeaveProperties(){let t=(Date.now()-this.startTime)/1e3;(isNaN(t)||t<0||t>this.maxDuration)&&(t=0),t=Number(t.toFixed(3));const e={$title:this.title,$url:this.url?.substring(0,1e3),$pathname:w(this.url)};return 0!==t&&(e.$event_duration=t),e}destroy(){this.eventListeners.forEach(({target:t,event:e,handler:n})=>{t.removeEventListener(e,n)}),this.eventListeners=[],this.timer&&(clearTimeout(this.timer),this.timer=null),this.heartbeatIntervalTimer&&(clearInterval(this.heartbeatIntervalTimer),this.heartbeatIntervalTimer=null)}};Rt.NAME="pageleave";let Tt=Rt;const Ct=class{constructor({emitter:t,config:e,sdk:n}){this.eventSended=!1,this.emitter=t,this.config=e,this.sdk=n}init(){if(this.sdk&&!0===this.sdk._postConsentInit)return;const t=()=>{let e=0;const n={};if(window.performance){e=function(){let t=0;if("function"==typeof performance.getEntriesByType){const e=performance.getEntriesByType("navigation");e.length>0&&(t=e[0].domContentLoadedEventEnd||0)}return t}();const t=function(){if(performance.getEntries&&"function"==typeof performance.getEntries){const t=performance.getEntries();let e=0;for(const n of t)"transferSize"in n&&(e+=n.transferSize);if("number"==typeof e&&e>=0&&e<10737418240)return Number((e/1024).toFixed(3))}}();t&&(n.$page_resource_size=t)}else console.warn("Performance API is not supported.");e>0&&!Number.isFinite(e)&&(n.$event_duration=Number((e/1e3).toFixed(3))),this.eventSended||(this.eventSended=!0,mt({event:"$PageLoad",properties:n},this.config)),window.removeEventListener("load",t)};"complete"===document.readyState?t():window.addEventListener&&window.addEventListener("load",t)}};Ct.NAME="pageload";let Nt=Ct;function Pt(t,e){if(!l(t))return!1;const n=o(t.tagName)?t.tagName.toLowerCase():"",i={};i.$element_type=n,i.$element_name=t.getAttribute("name")||"",i.$element_id=t.getAttribute("id")||"",i.$element_class_name=o(t.className)?t.className:"",i.$element_target_url=t.getAttribute("href")||"",i.$element_content=function(t,e){return o(e)&&"input"===e.toLowerCase()?("button"===(n=t).type||"submit"===n.type)&&n.value||"":function(t,e){let n="",i="";return t.textContent?n=S(t.textContent):t.innerText&&(n=S(t.innerText)),n&&(n=n.replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)),i=n||"","input"!==e&&"INPUT"!==e||(i=t.value||""),i}(t,e);var n}(t,n)||"",i.$element_selector=kt(t)||"",i.$element_path=function(t){let e=[];for(;t.parentNode&&l(t);){if(!o(t.tagName))return"";if(t.id&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(t.id)){e.unshift(t.tagName.toLowerCase()+"#"+t.id);break}if(t===document.body){e.unshift("body");break}e.unshift(t.tagName.toLowerCase()),t=t.parentNode}return e.join(" > ")}(t)||"";const s=function(t,e){const n=e.pageX||e.clientX+Lt().scrollLeft||e.offsetX+$t(t).targetEleX,i=e.pageY||e.clientY+Lt().scrollTop||e.offsetY+$t(t).targetEleY;return{$page_x:Ft(n),$page_y:Ft(i)}}(t,e);return i.$page_x=s.$page_x,i.$page_y=s.$page_y,i}function kt(t,e=[]){if(!(t&&t.parentNode&&t.parentNode.children&&o(t.tagName)))return"";e=Array.isArray(e)?e:[];const n=t.nodeName.toLowerCase();return t&&"body"!==n&&1==t.nodeType?(e.unshift(function(t){if(!t||!l(t)||!o(t.tagName))return"";let e=t.parentNode&&9==t.parentNode.nodeType?-1:function(t){if(!t.parentNode)return-1;let e=0;const n=t.tagName,i=t.parentNode.children;for(let s=0,r=i.length;s<r;s++)if(i[s].tagName===n){if(t===i[s])return e;e++}return-1}(t);return t.getAttribute&&t.getAttribute("id")&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(t.getAttribute("id"))?"#"+t.getAttribute("id"):t.tagName.toLowerCase()+(~e?":nth-of-type("+(e+1)+")":"")}(t)),t.getAttribute&&t.getAttribute("id")&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(t.getAttribute("id"))?e.join(" > "):kt(t.parentNode,e)):(e.unshift("body"),e.join(" > "))}function Lt(){return{scrollLeft:document.body.scrollLeft||document.documentElement.scrollLeft||0,scrollTop:document.body.scrollTop||document.documentElement.scrollTop||0}}function $t(t){if(document.documentElement.getBoundingClientRect){const e=t.getBoundingClientRect();return{targetEleX:e.left+Lt().scrollLeft||0,targetEleY:e.top+Lt().scrollTop||0}}return{targetEleX:0,targetEleY:0}}function Ft(t){return Number(Number(t).toFixed(3))}const xt=class{constructor({emitter:t,config:e}){this.isInitialized=!1,this.boundHandleClick=null,this.emitter=t,this.config=e}init(){this.isInitialized||(this.boundHandleClick=this.handleClick.bind(this),document.addEventListener("click",this.boundHandleClick,!0),this.isInitialized=!0)}handleClick(t){const e=t.target;if(!e)return;if(!["A","INPUT","BUTTON","TEXTAREA"].includes(e.tagName))return;if("true"===e.getAttribute("sensorswave-disable"))return;mt({event:"$WebClick",properties:Pt(e,t)||{}},this.config)}destroy(){this.boundHandleClick&&(document.removeEventListener("click",this.boundHandleClick,!0),this.boundHandleClick=null),this.isInitialized=!1}};xt.NAME="webclick";let Bt=xt;const Mt=class{constructor({emitter:t,config:e,sdk:n}){this.updateInterval=null,this.fetchingPromise=null,this.emitter=t,this.config=e,this.sdk=n}init(){const t=this.config;if(t.enableAB){if(this.sdk&&"function"==typeof this.sdk.hasOptedOutCapturing&&this.sdk.hasOptedOutCapturing())return;this.fastFetch().then(()=>{this.emitter.emit(A)}),t.abRefreshInterval<3e4&&(t.abRefreshInterval=3e4),this.updateInterval=setInterval(()=>{this.fetchNewData().catch(console.warn)},t.abRefreshInterval)}}async fastFetch(){const t=N.getABData(this.config.abRefreshInterval);return t&&t.length?(this.emitter.emit(A),Promise.resolve(t)):this.fetchNewData()}async fetchNewData(){return this.fetchingPromise||(this.fetchingPromise=new Promise(t=>{!function({opts:t,cb:e}){if(!st())return void(e&&e({}));if(!rt())return void(e&&e({}));const n=N.getLoginId(),i=N.getAnonId();if(!n&&!i)return void(e&&e({}));const s={user:{login_id:n||"",anon_id:i||"",props:{...tt(),...gt(N.getCommonProps())}},sdk:"webjs",sdk_version:v};$({url:lt(t),method:"POST",data:s,headers:ht(t),callback:t=>{200!==t.statusCode?(console.error("Failed to fetch feature flags"),e&&e({})):e&&e(t.json)}})}({opts:this.config,cb:e=>{N.saveABData(e?.data?.results||[]),t(e),this.fetchingPromise=null}})})),this.fetchingPromise}async getFeatureGate(t){return await this.fastFetch().catch(console.warn),N.getABData(this.config.abRefreshInterval).find(e=>e.typ===C.FEATURE_GATE&&e.key==t)}async checkFeatureGate(t){const e=await this.getFeatureGate(t);return!!e&&(!e.hasOwnProperty("vid")&&e.key?(wt({isUnset:!0,data:e,opts:this.config}),!1):(wt({data:e,opts:this.config}),"fail"!==e.vid))}async getExperiment(t){await this.fastFetch().catch(console.warn);const e=N.getABData(this.config.abRefreshInterval).find(e=>e.typ===C.EXPERIMENT&&e.key===t);return e?!e.hasOwnProperty("vid")&&e.key?(wt({isUnset:!0,data:e,opts:this.config}),{}):(wt({data:e,opts:this.config}),e?.value||{}):{}}async getFeatureConfig(t){await this.fastFetch().catch(console.warn);const e=N.getABData(this.config.abRefreshInterval).find(e=>e.typ===C.FEATURE_CONFIG&&e.key===t);if(!e)return{};if(!e.hasOwnProperty("vid")&&e.key)return wt({isUnset:!0,data:e,opts:this.config}),{};wt({data:e,opts:this.config});const n=e?.value;if(n){if(i(n))return n;try{return JSON.parse(n)}catch{return n}}return{}}destroy(){this.updateInterval&&(clearInterval(this.updateInterval),this.updateInterval=null),this.fetchingPromise=null}};Mt.NAME="abtest";let Dt=Mt;const Ht=["utm_source","utm_medium","utm_campaign","utm_content","utm_term"],Ut="sensorswave_utm",Xt=class t{constructor({sdk:t,emitter:e,config:n}){this.sdk=t,this.emitter=e,this.config=n}init(){if(this.sdk&&!0===this.sdk._postConsentInit){let e=t.readFromSessionStorage();return e&&0!==Object.keys(e).length||(e=t.captureAndStore(this.config?.debug)),void this.scheduleInitialUTM(e)}const e=t.getUTMFromURL();t.saveToSessionStorage(e,this.config?.debug),this.scheduleInitialUTM(e)}scheduleInitialUTM(t){setTimeout(()=>{this.sendInitialUTM(t)},0)}static getUTMFromURL(){try{const t=new URLSearchParams(window.location.search),e={};return Ht.forEach(n=>{const i=t.get(n);i&&(e[n]=i)}),e}catch(e){return t.getUTMFromURLFallback()}}static getUTMFromURLFallback(){const t={};return window.location.search.substring(1).split("&").forEach(e=>{const[n,i]=e.split("="),s=decodeURIComponent(n),r=i?decodeURIComponent(i):"";Ht.includes(s)&&(t[s]=r)}),t}static readFromSessionStorage(){try{const t=sessionStorage.getItem(Ut);if(!t)return{};const e=JSON.parse(t);return e&&"object"==typeof e?e:{}}catch(t){return{}}}static saveToSessionStorage(t,e=!1){try{sessionStorage.setItem(Ut,JSON.stringify(t))}catch(n){e&&console.warn("[SensorsWave UTM] Failed to save to sessionStorage:",n)}}static captureAndStore(e=!1){const n=t.getUTMFromURL();return t.saveToSessionStorage(n,e),n}sendInitialUTM(t){const e={};Ht.forEach(n=>{e[`$initial_${n}`]=null!=t[n]?t[n]:""});try{this.sdk.profileSetOnce(e)}catch(n){this.config.debug&&console.warn("[SensorsWave UTM] Failed to send initial UTM:",n)}}destroy(){}};Xt.NAME="UTM";let jt=Xt;const qt=1e3,Wt=/^\s*(?:async\s+)?at\s+(?:(.+)\s+\()?(.+?):(\d+):(\d+)\)?$/,Gt=/^(?:(.*)@)?(.+?):(\d+):(\d+)$/;function zt(t){let e=t;try{const t=location.origin;t&&0===e.indexOf(t)&&(e=e.substring(t.length))}catch(s){}const n=e.indexOf("?");n>-1&&(e=e.substring(0,n));const i=e.indexOf("#");return i>-1&&(e=e.substring(0,i)),e}function Yt(t){return t.map(t=>({platform:"web:javascript",filename:zt(t.file),function:t.fn||"?",lineno:Number(t.line),colno:Number(t.col),abs_path:Kt(t.file,1e3)}))}function Kt(t,e){return t.length>e?t.substring(0,e):t}function Jt(t){let e;if("string"==typeof t)e=t;else if(null!==t&&"object"==typeof t){try{e=JSON.stringify(t)}catch(n){e=Object.prototype.toString.call(t)}e||(e=Object.prototype.toString.call(t))}else e=String(t);return Kt(e,qt)}function Zt(t){const{frames:e,headerType:n}=function(t){const e=[];let n="";if(!t||"string"!=typeof t)return{frames:e,headerType:n};const i=t.split(/\r?\n/);for(let s=0;s<i.length;s++){const t=i[s];if(!t||t.length>1024)continue;const r=t.match(Wt),o=r?null:t.match(Gt),a=r||o;if(a)e.push({fn:a[1]||"?",file:a[2],line:a[3],col:a[4]});else if(0===s){const e=t.indexOf(":");e>0&&(n=t.substring(0,e).trim())}if(e.length>=30)break}return{frames:e,headerType:n}}(t&&t.stack);let i=t&&t.name||n||"Error";return i=Kt(String(i),200),{$exception_level:"error",$exception_type:i,$exception_message:Kt(String(t&&t.message||""),qt),$exception_frames:Yt(e)}}function Qt(t,e,n,i){let s=[];return e&&(s=[{platform:"web:javascript",filename:zt(e),function:"?",lineno:n||0,colno:i||0,abs_path:Kt(e,1e3)}]),{$exception_level:"error",$exception_type:"Error",$exception_message:Kt(String(t||""),qt),$exception_frames:s}}class Vt{constructor(t=10,e=1,n=1e4){this.buckets=new Map,this.bucketSize=t,this.refillRate=e,this.refillInterval=n}allow(t){const e=Date.now();let n=this.buckets.get(t);if(n){if(e>n.lastRefill){const t=Math.floor((e-n.lastRefill)/this.refillInterval)*this.refillRate;t>0&&(n.tokens=Math.min(this.bucketSize,n.tokens+t),n.lastRefill+=t/this.refillRate*this.refillInterval)}}else n={tokens:this.bucketSize,lastRefill:e},this.buckets.set(t,n);return n.tokens>=1&&(n.tokens-=1,!0)}reset(){this.buckets.clear()}}const te=class{constructor({emitter:t,config:e}){this.isInitialized=!1,this.boundHandleError=null,this.boundHandleRejection=null,this.rateLimiter=new Vt,this.emitter=t,this.config=e}init(){this.isInitialized||(this.boundHandleError=this.handleError.bind(this),this.boundHandleRejection=this.handleRejection.bind(this),window.addEventListener("error",this.boundHandleError,!0),window.addEventListener("unhandledrejection",this.boundHandleRejection),this.isInitialized=!0)}handleError(t){try{const e=t.target;let n;if(e&&e!==window&&e.tagName)n=function(t){const e=t,n=(e.tagName||"").toLowerCase(),i=Kt(String(e.src||e.href||""),qt);return{$exception_level:"error",$exception_type:"ResourceLoadError",$exception_message:`Failed to load <${n}>${i?` from ${i}`:""}`,$exception_frames:[]}}(e);else{const e=t;n=e.error instanceof Error?Zt(e.error):Qt(String(e.message||""),e.filename,e.lineno,e.colno)}this.send(n)}catch(e){}}handleRejection(t){try{const e=t.reason;this.send(function(t){return t instanceof Error?Zt(t):{$exception_level:"error",$exception_type:"UnhandledRejection",$exception_message:Jt(t),$exception_frames:[]}}(e))}catch(e){}}send(t){t.$exception_message&&this.rateLimiter.allow(t.$exception_type)&&mt({event:T,properties:t},this.config)}destroy(){this.boundHandleError&&(window.removeEventListener("error",this.boundHandleError,!0),this.boundHandleError=null),this.boundHandleRejection&&(window.removeEventListener("unhandledrejection",this.boundHandleRejection),this.boundHandleRejection=null),this.rateLimiter.reset(),this.isInitialized=!1}};te.NAME="exception";let ee=te;const ne=[],ie={debug:!1,sourceToken:"",apiHost:"",autoCapture:!0,isSinglePageApp:!1,crossSubdomainCookie:!0,enableAB:!1,abRefreshInterval:6e5,enableClickTrack:!1,batchSend:!1,enableErrorTrack:!1,enableCrashTrack:!1,optOutCapturing:!1,persistOptOut:!1};return new class{constructor(){this.__innerInited=!1,this.inited=!1,this.config={},this.eventEmitter=new t,this.pluginCore={},this.commonProps={},this.spaCleanup=null,this._optOutCapturing=!1,this.consentStorage=new vt(!1),this._setupAfterConsentDone=!1,this._postConsentInit=!1,O.instance=this}init(t,e={}){return this.inited?this:(O.instance=this,e.sourceToken=t,this.mergeConfig(e),this.consentStorage=new vt(!0===this.config.persistOptOut),this._optOutCapturing?this.consentStorage.write(!0):!0===this.config.optOutCapturing?(this._optOutCapturing=!0,this.consentStorage.write(!0)):!0===this.consentStorage.read()&&(this._optOutCapturing=!0),this.eventEmitter.emit("init-param",this.config),this.__innerInited=!0,this._optOutCapturing?(jt.captureAndStore(this.config.debug),this.eventEmitter.emit(b),this.inited=!0,this):(this.__setupAfterConsent(),this.eventEmitter.emit(b),this.inited=!0,this))}__setupAfterConsent(){if(this._setupAfterConsentDone)return;this._setupAfterConsentDone=!0;const t=this.config;ne.length=0,N.init(t.crossSubdomainCookie),t.anonId&&N.setAnonId(t.anonId),function(){if(window._swFailedRequestsInitialized)return;window._swFailedRequestsInitialized=!0;const t=O.instance;t&&"function"==typeof t.hasOptedOutCapturing&&t.hasOptedOutCapturing()||t&&!0===t._postConsentInit||function(){const t=et.getAll();if(0!==t.length)for(let e=0,n=t.length;e<n;e+=10){const n=t.slice(e,e+10),i=[],s=[];n.forEach(t=>{Array.isArray(t.data)?i.push(...t.data):i.push(t.data),s.push(t.id)});const r=n[n.length-1],o=r.url,a=r.headers;$({url:o,method:"POST",data:i,headers:a,callback:t=>{200!==t.statusCode?(console.error("Failed to send batch stored requests:",t),P(t.statusCode)||s.forEach(t=>{et.dequeue(t)})):s.forEach(t=>{et.dequeue(t)})}})}}()}(),ne.push(jt),t.autoCapture&&this.autoTrack(),t.enableAB&&ne.push(Dt),t.enableClickTrack&&ne.push(Bt),t.enableCrashTrack&&t.debug&&console.warn("[SensorsWave] enableCrashTrack 仅在 app 宿主环境生效,当前 Web 环境不采集 crash"),t.enableErrorTrack&&ne.push(ee),this.pluginCore=new bt({plugins:ne,emitter:this.eventEmitter,config:t,sdk:this}),this.spaCleanup=function(t){let e=location.href;const n=window.history.pushState,i=window.history.replaceState,r=function(){t(e),e=location.href};return s(window.history.pushState)&&(window.history.pushState=function(...i){n.apply(window.history,i),t(e),e=location.href}),s(window.history.replaceState)&&(window.history.replaceState=function(...n){i.apply(window.history,n),t(e),e=location.href}),window.addEventListener("popstate",r),function(){s(window.history.pushState)&&(window.history.pushState=n),s(window.history.replaceState)&&(window.history.replaceState=i),window.removeEventListener("popstate",r)}}(t=>{this.eventEmitter.emit(y,t)})}mergeConfig(t){this.config={...ie,...t}}__canCapture(){return this.inited&&!this._optOutCapturing}track(t){this.__canCapture()&&function(t,e){if(!st())return;if(!rt())return;const n={...t};n.time||(n.time=Date.now()),n.login_id||(n.login_id=N.getLoginId()),n.anon_id||(n.anon_id=N.getAnonId()),n.trace_id||(n.trace_id=N.getTraceId()),n.properties={...tt(),...gt(N.getCommonProps()),...n.properties};const i=ut(e),s=ht(e),r=!1!==e.batchSend&&at();if(!r)return dt(i,{data:[n],headers:s});et.enqueue(i,[n],s),r.add()}(t,this.config)}trackEvent(t,e){this.__canCapture()&&mt({event:t,properties:e},this.config)}trackException(t,e){if(!this.__canCapture())return;const n={...e||{},...t instanceof Error?Zt(t):Qt(String(t))};mt({event:T,properties:n},this.config)}autoTrack(){ne.push(At,Nt,Tt)}profileSet(t){this.__canCapture()&&Et({userProps:{$set:t},opts:this.config})}profileSetOnce(t){this.__canCapture()&&Et({userProps:{$set_once:t},opts:this.config})}profileIncrement(t){this.__canCapture()&&Et({userProps:{$increment:t},opts:this.config})}profileAppend(t){this.__canCapture()&&Et({userProps:{$append:t},opts:this.config})}profileUnion(t){this.__canCapture()&&Et({userProps:{$union:t},opts:this.config})}profileUnset(t){if(!this.__canCapture())return;const e={};r(t)?t.forEach(function(t){e[t]=null}):e[t]=null,Et({userProps:{$unset:e},opts:this.config})}profileDelete(){this.__canCapture()&&Et({userProps:{$delete:!0},opts:this.config})}registerCommonProperties(t){if(!i(t))return console.warn("Commmon Properties must be an object!");this.commonProps=t,N.setCommonProps(this.commonProps)}clearCommonProperties(t){if(!r(t))return console.warn("Commmon Properties to be cleared must be an array!");t.forEach(t=>{delete this.commonProps[t]}),N.setCommonProps(this.commonProps)}identify(t){this.__canCapture()&&(N.setLoginId(t),function(t){if(!st())return;if(!rt())return;const e=N.getLoginId(),n=N.getAnonId();if(!e||!n)return;const i={time:Date.now(),trace_id:N.getTraceId(),event:"$Identify",login_id:e,anon_id:n,properties:ft()},s=ut(t),r=ht(t),o=at();if(!o)return dt(s,{data:[i],headers:r});et.enqueue(s,[i],r),o.add()}(this.config))}setLoginId(t){this.__canCapture()&&N.setLoginId(t)}getAnonId(){return this.__canCapture()?N.getAnonId():""}setAnonId(t){this.__canCapture()&&N.setAnonId(t)}getLoginId(){return this.__canCapture()?N.getLoginId():""}checkFeatureGate(t){if(!this.__canCapture())return Promise.resolve(!1);const e=this.pluginCore.getPlugin(Dt.NAME);return this.config.enableAB&&e?e.checkFeatureGate(t):Promise.reject("AB is disabled")}getExperiment(t){if(!this.__canCapture())return Promise.resolve({});const e=this.pluginCore.getPlugin(Dt.NAME);return this.config.enableAB&&e?e.getExperiment(t):Promise.reject("AB is disabled")}getFeatureConfig(t){if(!this.__canCapture())return Promise.resolve({});const e=this.pluginCore.getPlugin(Dt.NAME);return this.config.enableAB&&e?e.getFeatureConfig(t):Promise.reject("AB is disabled")}optOutCapturing(){this._optOutCapturing=!0,this.consentStorage.write(!0),ot&&ot.pause()}optInCapturing(){if(this._optOutCapturing=!1,this.consentStorage.write(!1),ot&&ot.resume(),this.inited&&!this._setupAfterConsentDone){this._postConsentInit=!0;try{this.__setupAfterConsent(),this.eventEmitter.emit(b)}finally{this._postConsentInit=!1}}}hasOptedOutCapturing(){return this._optOutCapturing}destroy(){ot&&(ot.destroy(),ot=null),"undefined"!=typeof window&&(window._swFailedRequestsInitialized=!1),this.inited=!1,this.__innerInited=!1,this.spaCleanup&&"function"==typeof this.spaCleanup&&(this.spaCleanup(),this.spaCleanup=null),this.pluginCore&&"function"==typeof this.pluginCore.destroy&&this.pluginCore.destroy(),this.pluginCore={},this.eventEmitter&&this.eventEmitter.removeAllListeners(),this.consentStorage=new vt(!0===this.config?.persistOptOut),this._optOutCapturing=!1,this._setupAfterConsentDone=!1,this._postConsentInit=!1,O.instance===this&&(O.instance=null)}}});
@@ -46,12 +46,17 @@ export interface SensorsWaveConfig {
46
46
  abRefreshInterval?: number;
47
47
  enableClickTrack?: boolean;
48
48
  batchSend?: boolean;
49
+ enableErrorTrack?: boolean;
50
+ enableCrashTrack?: boolean;
49
51
  anonId?: string;
52
+ optOutCapturing?: boolean;
53
+ persistOptOut?: boolean;
50
54
  [key: string]: any;
51
55
  }
52
56
  interface SensorsWaveInterface {
53
57
  trackEvent(e: string, p?: Object): void;
54
58
  track(e: AdvanceEvent): void;
59
+ trackException(error: Error | string, properties?: Record<string, any>): void;
55
60
  profileSet(p: Object): void;
56
61
  profileSetOnce(p: Object): void;
57
62
  profileIncrement(p: Object): void;
@@ -67,4 +72,7 @@ interface SensorsWaveInterface {
67
72
  checkFeatureGate(key: string): Promise<boolean>;
68
73
  getExperiment(key: string): Promise<Object>;
69
74
  getFeatureConfig(key: string): Promise<Object>;
75
+ optOutCapturing(): void;
76
+ optInCapturing(): void;
77
+ hasOptedOutCapturing(): boolean;
70
78
  }
@@ -6,7 +6,12 @@ export declare class BatchSender {
6
6
  private flushTimer;
7
7
  private config;
8
8
  private isFlushing;
9
+ private paused;
10
+ private destroyed;
9
11
  constructor(config?: Partial<BatchSenderConfig>);
12
+ pause(): void;
13
+ resume(): void;
14
+ isPaused(): boolean;
10
15
  add(): void;
11
16
  private triggerFlush;
12
17
  private flush;
@@ -0,0 +1,6 @@
1
+ export declare class ConsentStorage {
2
+ private persist;
3
+ constructor(persist: boolean);
4
+ read(): boolean | undefined;
5
+ write(isOptedOut: boolean): void;
6
+ }
@@ -2,6 +2,8 @@ import { HttpRequestOptions } from '../utils/request';
2
2
  import { SensorsWaveEvent, SensorsWaveSendEvent, SensorsWaveConfig, FFUser, ABData } from '../../types/Api';
3
3
  export declare function initFailedRequestsSenderWrapper(): void;
4
4
  export declare function cleanupBatchSender(): void;
5
+ export declare function pauseBatchSender(): void;
6
+ export declare function resumeBatchSender(): void;
5
7
  export declare function send(url: string, opts: Partial<HttpRequestOptions>, cb?: Function): void;
6
8
  export declare function sendEvent(data: SensorsWaveEvent, opts: SensorsWaveConfig, usePresetEventProps?: boolean): void;
7
9
  export declare function sendSWEvent(e: SensorsWaveSendEvent, opts: SensorsWaveConfig): void;
@@ -14,6 +14,7 @@ declare const PRESET_EVENTS: {
14
14
  USER_SET: string;
15
15
  AB_FEATURE_IMPRESS: string;
16
16
  AB_EXP_IMPRESS: string;
17
+ EXCEPTION: string;
17
18
  };
18
19
  declare enum ABType {
19
20
  FEATURE_GATE = 1,
@@ -10,11 +10,18 @@ declare class SensorsWave {
10
10
  private pluginCore;
11
11
  private commonProps;
12
12
  private spaCleanup;
13
+ private _optOutCapturing;
14
+ private consentStorage;
15
+ private _setupAfterConsentDone;
16
+ private _postConsentInit;
13
17
  constructor();
14
18
  init(sourceToken: string, config?: SensorsWaveConfig): this;
19
+ private __setupAfterConsent;
15
20
  private mergeConfig;
21
+ private __canCapture;
16
22
  track(e: SensorsWaveSendEvent): void;
17
23
  trackEvent(event: string, properties: Record<string, any>): void;
24
+ trackException(error: Error | string, properties?: Record<string, any>): void;
18
25
  private autoTrack;
19
26
  profileSet(p: Object): void;
20
27
  profileSetOnce(p: Object): void;
@@ -33,6 +40,9 @@ declare class SensorsWave {
33
40
  checkFeatureGate(key: string): any;
34
41
  getExperiment(key: string): any;
35
42
  getFeatureConfig(key: string): any;
43
+ optOutCapturing(): void;
44
+ optInCapturing(): void;
45
+ hasOptedOutCapturing(): boolean;
36
46
  destroy(): void;
37
47
  }
38
48
  declare const _default: SensorsWave;
@@ -4,11 +4,13 @@ export declare class AbTest {
4
4
  static NAME: string;
5
5
  private emitter;
6
6
  private config;
7
+ private sdk;
7
8
  private updateInterval;
8
9
  private fetchingPromise;
9
- constructor({ emitter, config }: {
10
+ constructor({ emitter, config, sdk }: {
10
11
  emitter: EventEmitter;
11
12
  config: SensorsWaveConfig;
13
+ sdk?: any;
12
14
  });
13
15
  init(): void;
14
16
  fastFetch(): Promise<any>;
@@ -0,0 +1,20 @@
1
+ import { EventEmitter } from '../../../core';
2
+ import { SensorsWaveConfig } from '../../types/Api';
3
+ export declare class Exception {
4
+ static NAME: string;
5
+ private emitter;
6
+ private config;
7
+ private isInitialized;
8
+ private boundHandleError;
9
+ private boundHandleRejection;
10
+ private rateLimiter;
11
+ constructor({ emitter, config }: {
12
+ emitter: EventEmitter;
13
+ config: SensorsWaveConfig;
14
+ });
15
+ init(): void;
16
+ private handleError;
17
+ private handleRejection;
18
+ private send;
19
+ destroy(): void;
20
+ }
@@ -4,6 +4,7 @@ export declare class PageLeave {
4
4
  static NAME: string;
5
5
  private emitter;
6
6
  private config;
7
+ private sdk;
7
8
  private startTime;
8
9
  private pageShowStatus;
9
10
  private pageHiddenStatus;
@@ -17,10 +18,13 @@ export declare class PageLeave {
17
18
  private storageName;
18
19
  private maxDuration;
19
20
  private eventListeners;
20
- constructor({ emitter, config }: {
21
+ private _skipFirstPageEnd;
22
+ constructor({ emitter, config, sdk }: {
21
23
  emitter: EventEmitter;
22
24
  config: SensorsWaveConfig;
25
+ sdk?: any;
23
26
  });
27
+ private __canCapture;
24
28
  init(): void;
25
29
  log(message: string): void;
26
30
  refreshPageEndTimer(): void;
@@ -4,10 +4,12 @@ export declare class PageLoad {
4
4
  static NAME: string;
5
5
  private emitter;
6
6
  private config;
7
+ private sdk;
7
8
  private eventSended;
8
- constructor({ emitter, config }: {
9
+ constructor({ emitter, config, sdk }: {
9
10
  emitter: EventEmitter;
10
11
  config: SensorsWaveConfig;
12
+ sdk?: any;
11
13
  });
12
14
  init(): void;
13
15
  }
@@ -4,12 +4,14 @@ export declare class PageView {
4
4
  static NAME: string;
5
5
  private emitter;
6
6
  private config;
7
+ private sdk;
7
8
  private boundSend;
8
9
  private hashEvent;
9
10
  private spaSwitchHandler;
10
- constructor({ emitter, config }: {
11
+ constructor({ emitter, config, sdk }: {
11
12
  emitter: EventEmitter;
12
13
  config: SensorsWaveConfig;
14
+ sdk?: any;
13
15
  });
14
16
  init(): void;
15
17
  addSinglePageListener(): void;
@@ -10,9 +10,12 @@ export declare class UTM {
10
10
  config: any;
11
11
  });
12
12
  init(): void;
13
- private getUTMFromURL;
14
- private getUTMFromURLFallback;
15
- private saveToSessionStorage;
13
+ private scheduleInitialUTM;
14
+ static getUTMFromURL(): Record<string, string>;
15
+ private static getUTMFromURLFallback;
16
+ static readFromSessionStorage(): Record<string, string>;
17
+ static saveToSessionStorage(utmParams: Record<string, string>, debug?: boolean): void;
18
+ static captureAndStore(debug?: boolean): Record<string, string>;
16
19
  private sendInitialUTM;
17
20
  destroy(): void;
18
21
  }
@@ -0,0 +1,41 @@
1
+ type StackFrame = {
2
+ fn: string;
3
+ file: string;
4
+ line: string;
5
+ col: string;
6
+ };
7
+ export type ExceptionPlatform = 'web:javascript' | 'java' | 'dart' | 'hermes' | 'ios';
8
+ export type ExceptionFrame = {
9
+ platform: ExceptionPlatform;
10
+ filename?: string;
11
+ function?: string;
12
+ lineno?: number;
13
+ colno?: number;
14
+ abs_path?: string;
15
+ module?: string;
16
+ };
17
+ export type ExceptionProps = {
18
+ $exception_level: string;
19
+ $exception_type: string;
20
+ $exception_message: string;
21
+ $exception_frames: ExceptionFrame[];
22
+ };
23
+ export declare function parseStack(stack?: string): {
24
+ frames: StackFrame[];
25
+ headerType: string;
26
+ };
27
+ export declare function toExceptionFrames(frames: StackFrame[]): ExceptionFrame[];
28
+ export declare function buildErrorProps(err: Error): ExceptionProps;
29
+ export declare function buildStringProps(message: string, filename?: string, lineno?: number, colno?: number): ExceptionProps;
30
+ export declare function buildRejectionProps(reason: unknown): ExceptionProps;
31
+ export declare function buildResourceProps(target: Element): ExceptionProps;
32
+ export declare class ExceptionRateLimiter {
33
+ private bucketSize;
34
+ private refillRate;
35
+ private refillInterval;
36
+ private buckets;
37
+ constructor(bucketSize?: number, refillRate?: number, refillInterval?: number);
38
+ allow(key: string): boolean;
39
+ reset(): void;
40
+ }
41
+ export {};
@@ -20,6 +20,7 @@ interface RequestContent {
20
20
  body: string | BlobPart;
21
21
  }
22
22
  export declare function appendUrlParameters(url: string, params: Record<string, any>): string;
23
+ export declare function isRetryableStatusCode(statusCode: number): boolean;
23
24
  export declare function serializeJson(data: any, space?: string | number): string;
24
25
  export declare function prepareRequestBody(options: HttpRequestOptions): RequestContent | undefined;
25
26
  export declare function request(_options: HttpRequestOptions): void;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "type": "module",
3
3
  "name": "@sensorswave/js-sdk",
4
- "version": "1.1.8",
4
+ "version": "1.3.0",
5
5
  "description": "Sensors Wave JS SDK for web analytics",
6
6
  "main": "dist/index.cjs.js",
7
7
  "module": "dist/index.es.js",