@bluenath/engage 2.0.10 → 2.0.11

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
@@ -1,34 +1,20 @@
1
1
  # @bluenath/engage
2
2
 
3
- The official analytics and attribution SDK for [EngagePro](https://engagepro.bluenath.com). Production-ready event capture for campaign ROI measurement and creator attribution.
4
-
5
- Developed by the [Bluenath](https://bluenath.com) team.
6
-
7
- ---
8
-
9
- ## Overview
10
-
11
- `@bluenath/engage` is a high-performance analytics SDK designed to bridge the gap between user interactions and campaign attribution. It captures critical web events, enriches intent signals, and securely transmits batched payloads to EngagePro's ingestion servers for real-time ROI analysis.
12
-
13
- ## Key Features
14
-
15
- - **Automated Event Capture**: Seamlessly tracks high-value interactions including page views, commerce events, form submissions, and friction signals (e.g., rage-clicks).
16
- - **Manual Business Events**: Flexible API for tracking custom conversions with support for value, currency, and campaign metadata.
17
- - **Resilient Delivery**: Robust offline queueing mechanism with exponential backoff and retry logic.
18
- - **Framework Integration**: Includes a lightweight React Provider and custom hooks for modern web architectures.
19
- - **Data Security**: Built-in protection for sensitive input fields and secure handling of attribution identifiers.
3
+ The official event tracking SDK for EngagePro.
20
4
 
21
5
  ## Installation
22
6
 
23
- Install the package via your preferred package manager:
7
+ Install the package using your preferred package manager:
24
8
 
25
9
  ```bash
26
10
  npm install @bluenath/engage
27
11
  ```
28
12
 
29
- ## Quick Start (React)
13
+ ## Quick Start
30
14
 
31
- Initialize the SDK at the root of your application using the `EngageProProvider`.
15
+ ### React Application
16
+
17
+ Initialize the SDK at the root of your application using the `EngageProProvider`:
32
18
 
33
19
  ```tsx
34
20
  import React from "react";
@@ -38,7 +24,7 @@ import App from "./App";
38
24
 
39
25
  ReactDOM.createRoot(document.getElementById("root")!).render(
40
26
  <EngageProProvider
41
- writeKey="YOUR_PUBLIC_WRITE_KEY"
27
+ apiKey="YOUR_PUBLIC_API_KEY"
42
28
  tracking={{
43
29
  autoTrack: true,
44
30
  useCookies: true,
@@ -50,16 +36,36 @@ ReactDOM.createRoot(document.getElementById("root")!).render(
50
36
  );
51
37
  ```
52
38
 
53
- ## Quick Start (Plain JavaScript / Non-React)
39
+ To track events or identify users in a component, use the `useAnalytics` hook:
40
+
41
+ ```tsx
42
+ import { useAnalytics } from "@bluenath/engage";
43
+
44
+ export function ExampleComponent() {
45
+ const analytics = useAnalytics();
46
+
47
+ const handlePurchase = () => {
48
+ analytics.track("PURCHASE", {
49
+ amount: 4999,
50
+ currency: "INR",
51
+ ref: "camp_CAMPAIGN_ID_cr_CREATOR_ID",
52
+ });
53
+ };
54
+
55
+ return <button onClick={handlePurchase}>Complete Purchase</button>;
56
+ }
57
+ ```
58
+
59
+ ### Plain JavaScript / Non-React Application
54
60
 
55
- For non-React applications, you can import and initialize the core `Engage` instance directly.
61
+ Import and initialize the core `engage` instance:
56
62
 
57
63
  ```javascript
58
64
  import { engage } from "@bluenath/engage";
59
65
 
60
- // Initialize once at the entry point of your app
66
+ // Initialize once at the entry point of your application
61
67
  engage.init({
62
- writeKey: "YOUR_PUBLIC_WRITE_KEY",
68
+ apiKey: "YOUR_PUBLIC_API_KEY",
63
69
  tracking: {
64
70
  autoTrack: true,
65
71
  useCookies: true,
@@ -71,67 +77,23 @@ engage.init({
71
77
  engage.track("PURCHASE", {
72
78
  amount: 2999,
73
79
  currency: "INR",
74
- orderId: "ORD-9981"
80
+ ref: "camp_CAMPAIGN_ID_cr_CREATOR_ID"
75
81
  });
76
82
  ```
77
83
 
78
- ## Manual Event Tracking
79
-
80
- Use the `track` method (or `useAnalytics` hook in React) to capture specific business outcomes.
81
-
82
- ```tsx
83
- // React Example
84
- import { useAnalytics } from "@bluenath/engage";
85
-
86
- export function PurchaseConfirmation() {
87
- const analytics = useAnalytics();
88
-
89
- const handlePurchase = () => {
90
- analytics.track("PURCHASE", {
91
- orderId: "ORD-1029",
92
- amount: 4999,
93
- currency: "INR",
94
- ref: "camp_<campaignId>_cr_<creatorId>",
95
- });
96
- };
97
-
98
- return <button onClick={handlePurchase}>Confirm Payout</button>;
99
- }
100
- ```
101
-
102
- ### Attribution Reference Format
103
-
104
- For accurate campaign attribution, ensure the `ref` field follows the standard EngagePro format:
105
- `camp_<campaignId>_cr_<creatorId>`
106
-
107
- ## API Reference
108
-
109
- ### Configuration Options
84
+ ## Configuration Options
110
85
 
111
86
  | Property | Type | Required | Description |
112
87
  | :--- | :--- | :--- | :--- |
113
- | `writeKey` | `string` | **Yes** | Your public brand write key from the [EngagePro Dashboard](https://engagepro.bluenath.com/app/integration). |
114
- | `apiHost` | `string` | No | Local development override (restricted to `localhost` or `127.0.0.1`). |
115
- | `tracking.autoTrack` | `boolean` | **Yes** | Enables automated DOM interaction capture. |
116
- | `tracking.useCookies`| `boolean` | **Yes** | Persists anonymous identifiers across sessions. |
117
- | `tracking.fingerprint`| `boolean` | **Yes** | Includes device context for fraud prevention and unique visit tracking. |
88
+ | `apiKey` | `string` | Yes | Your public brand API key from the EngagePro Dashboard. |
89
+ | `tracking.autoTrack` | `boolean` | Yes | Enables automated DOM interaction capture. |
90
+ | `tracking.useCookies`| `boolean` | Yes | Persists anonymous identifiers across sessions. |
91
+ | `tracking.fingerprint`| `boolean` | Yes | Includes device context for fraud prevention and unique visit tracking. |
118
92
  | `debug` | `boolean` | No | Enables console logging for integration testing. |
119
93
 
120
- ## Network & Security Policies
121
-
122
- - **Endpoint Isolation**: Production data is exclusively routed to EngagePro's managed infrastructure.
123
- - **Local Development**: The `apiHost` parameter is strictly limited to local environments for testing. External host overrides are rejected for security compliance.
124
- - **Security Best Practices**:
125
- - Never expose internal service keys in client-side code.
126
- - Rotate write keys immediately if leakage is suspected.
127
- - Use hashed or anonymous identifiers; do not transmit raw PII (Personally Identifiable Information).
128
-
129
- ## Resources
130
-
131
- - [Official Documentation](https://engagepro.bluenath.com/docs)
132
- - [EngagePro Platform](https://engagepro.bluenath.com)
133
- - [Bluenath Creator OS](https://bluenath.com)
94
+ ## Documentation and Resources
134
95
 
135
- ## License
96
+ For detailed API references and integration guides, please visit our website and documentation:
136
97
 
137
- This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details.
98
+ - [EngagePro Website](https://engagepro.bluenath.com)
99
+ - [EngagePro Documentation](https://engagepro.bluenath.com/docs)
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var e=Object.defineProperty,t=(t,i,a)=>((t,i,a)=>i in t?e(t,i,{enumerable:!0,configurable:!0,writable:!0,value:a}):t[i]=a)(t,"symbol"!=typeof i?i+"":i,a);Object.defineProperties(exports,{t:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const i=require("react/jsx-runtime"),a=require("react");let n;const r=new Uint8Array(16);function o(){if(!n&&(n="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!n))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return n(r)}const s=[];for(let U=0;U<256;++U)s.push((U+256).toString(16).slice(1));const c={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function d(e,t,i){if(c.randomUUID&&!e)return c.randomUUID();const a=(e=e||{}).random||(e.rng||o)();return a[6]=15&a[6]|64,a[8]=63&a[8]|128,function(e,t=0){return s[e[t+0]]+s[e[t+1]]+s[e[t+2]]+s[e[t+3]]+"-"+s[e[t+4]]+s[e[t+5]]+"-"+s[e[t+6]]+s[e[t+7]]+"-"+s[e[t+8]]+s[e[t+9]]+"-"+s[e[t+10]]+s[e[t+11]]+s[e[t+12]]+s[e[t+13]]+s[e[t+14]]+s[e[t+15]]}(a)}const u=e=>{let t=2166136261;const i=e.length;for(let a=0;a<i;a++)t^=e.charCodeAt(a),t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24);return("0000000"+(t>>>0).toString(16)).substr(-8)},h=()=>{try{const e=document.createElement("canvas");e.width=200,e.height=50;const t=e.getContext("2d");return t?(t.textBaseline="top",t.font="14px 'Arial'",t.textBaseline="alphabetic",t.fillStyle="#f60",t.fillRect(125,1,62,20),t.fillStyle="#069",t.fillText("EngagePro, 😃",2,15),t.fillStyle="rgba(102, 204, 0, 0.7)",t.fillText("EngagePro, 😃",4,17),u(e.toDataURL())):""}catch(e){return""}};class l{constructor(e="local"){t(this,"memoryStore",{}),t(this,"keyPrefix","engage_"),t(this,"domain"),this.type=e,this.domain=this.getCookieDomain()}getItem(e){const t=this.keyPrefix+e;if(this.memoryStore.hasOwnProperty(t))return this.memoryStore[t];try{if("local"===this.type&&this.isBrowser())return window.localStorage.getItem(t);if("cookie"===this.type&&this.isBrowser())return this.getCookie(t)}catch(i){return null}return null}setItem(e,t){const i=this.keyPrefix+e;this.memoryStore[i]=t;try{"local"===this.type&&this.isBrowser()?window.localStorage.setItem(i,t):"cookie"===this.type&&this.isBrowser()&&this.setCookie(i,t,365)}catch(a){this.isQuotaError(a)&&(this.type="memory")}}removeItem(e){const t=this.keyPrefix+e;delete this.memoryStore[t];try{"local"===this.type&&this.isBrowser()?window.localStorage.removeItem(t):"cookie"===this.type&&this.isBrowser()&&this.setCookie(t,"",-1)}catch(i){}}getCookie(e){const t=e+"=",i=document.cookie.split(";");for(let a=0;a<i.length;a++){let e=i[a];for(;" "===e.charAt(0);)e=e.substring(1,e.length);if(0===e.indexOf(t))return decodeURIComponent(e.substring(t.length,e.length))}return null}setCookie(e,t,i){let a="";if(i){const e=new Date;e.setTime(e.getTime()+24*i*60*60*1e3),a="; expires="+e.toUTCString()}document.cookie=`${e}=${encodeURIComponent(t)}${a}; path=/; domain=${this.domain}; SameSite=Lax; Secure`}getCookieDomain(){if(!this.isBrowser())return"";const e=window.location.hostname,t=e.split(".");return 1===t.length||"localhost"===e?"":t.length>2?"."+t.slice(-2).join("."):"."+e}isBrowser(){try{return"undefined"!=typeof window&&void 0!==window.document}catch(e){return!1}}isQuotaError(e){return e instanceof DOMException&&(22===e.code||1014===e.code||"QuotaExceededError"===e.name||"NS_ERROR_DOM_QUOTA_REACHED"===e.name)}}class A{constructor(e){t(this,"storage"),t(this,"SESSION_TIMEOUT",18e5),t(this,"deviceId"),t(this,"sessionId"),t(this,"userId",null),t(this,"currentUrl"),t(this,"referrer"),this.storage=new l(e.persistence),this.deviceId=this.getOrSetDeviceId(),this.sessionId="",this.manageSession(),"undefined"!=typeof window?(this.currentUrl=window.location.href,this.referrer=document.referrer,this.listenToHistory()):(this.currentUrl="",this.referrer="")}getOrSetDeviceId(){const e=this.storage.getItem("device_id");if(e)return e;const t=(()=>{if("undefined"==typeof window)return"server-side-id";const e=navigator,t=window.screen,i=(()=>{try{const e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");if(!t)return{vendor:"",renderer:""};const i=t.getExtension("WEBGL_debug_renderer_info");return i?{vendor:t.getParameter(i.UNMASKED_VENDOR_WEBGL),renderer:t.getParameter(i.UNMASKED_RENDERER_WEBGL)}:{vendor:"",renderer:""}}catch(e){return{vendor:"",renderer:""}}})(),a={userAgent:e.userAgent||"",screenRes:`${t.width}x${t.height}`,colorDepth:t.colorDepth||0,timezone:(new Date).getTimezoneOffset(),language:e.language||"en-US",platform:e.platform||"unknown",hardwareConcurrency:e.hardwareConcurrency||1,deviceMemory:e.deviceMemory||0,canvasFingerprint:h(),webglVendor:i.vendor,webglRenderer:i.renderer},n=[a.platform,a.language,a.screenRes,a.colorDepth,a.timezone,a.hardwareConcurrency,a.deviceMemory,a.canvasFingerprint,a.webglVendor,a.webglRenderer].join("|");return`${u(n)}-${u(a.userAgent)}`})();return this.storage.setItem("device_id",t),t}manageSession(){const e=Date.now(),t=this.storage.getItem("session_id"),i=parseInt(this.storage.getItem("last_activity")||"0");if(!t||e-i>this.SESSION_TIMEOUT?(this.sessionId=`sess_${e}_${Math.random().toString(36).substr(2,9)}`,this.storage.setItem("session_id",this.sessionId)):this.sessionId=t,this.storage.setItem("last_activity",e.toString()),"undefined"!=typeof window){const e=()=>this.storage.setItem("last_activity",Date.now().toString());window.addEventListener("click",e),window.addEventListener("scroll",e)}}listenToHistory(){const e=history.pushState;history.pushState=(...t)=>{e.apply(history,t),this.handleUrlChange()},window.addEventListener("popstate",()=>this.handleUrlChange())}handleUrlChange(){const e=window.location.href;e!==this.currentUrl&&(this.referrer=this.currentUrl,this.currentUrl=e)}getPayload(){var e;return{library:{name:"@engagepro/analytics",version:"2.0.0"},user:{anonymousId:this.deviceId,id:this.userId},session:{id:this.sessionId,startTime:parseInt(this.sessionId.split("_")[1]||Date.now().toString())},page:{path:"undefined"!=typeof window?window.location.pathname:"",referrer:this.referrer,title:"undefined"!=typeof document?document.title:"",search:"undefined"!=typeof window?window.location.search:"",url:this.currentUrl},network:{online:"undefined"==typeof navigator||navigator.onLine,downlink:null==(e=navigator.connection)?void 0:e.downlink},screen:{width:"undefined"!=typeof screen?screen.width:0,height:"undefined"!=typeof screen?screen.height:0,density:"undefined"!=typeof window?window.devicePixelRatio:1},device:{fingerprint:this.deviceId,type:this.getDeviceType(),userAgent:"undefined"!=typeof navigator?navigator.userAgent:"server"},locale:"undefined"!=typeof navigator?navigator.language:"en-US",timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}}getDeviceType(){if("undefined"==typeof navigator)return"desktop";const e=navigator.userAgent;return/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(e)?"tablet":/Mobile|Android|iP(hone|od)|IEMobile|BlackBerry|Kindle|Silk-Accelerated/.test(e)?"mobile":"desktop"}}class p{constructor(e){t(this,"engageQueue",[]),t(this,"storage"),t(this,"transport"),t(this,"ENGAGE_STORAGE_KEY","engage_events_v2"),t(this,"isFlushing",!1),t(this,"flushInterval"),t(this,"MAX_RETRIES",3),this.transport=e,this.storage=new l("local"),this.load(),"undefined"!=typeof window&&(window.addEventListener("online",()=>{this.flushEngageEvents()}),window.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState&&this.flushBeacon()}),window.addEventListener("beforeunload",()=>{this.flushBeacon()})),this.startTimer()}startTimer(){this.flushInterval&&clearInterval(this.flushInterval),this.flushInterval=setInterval(()=>{this.flushEngageEvents()},5e3)}enqueueEngageEvent(e){this.engageQueue.push(e),this.saveEngage(),this.engageQueue.length>=10&&this.flushEngageEvents()}enqueue(e){}saveEngage(){this.storage.setItem(this.ENGAGE_STORAGE_KEY,JSON.stringify(this.engageQueue))}load(){const e=this.storage.getItem(this.ENGAGE_STORAGE_KEY);if(e)try{this.engageQueue=JSON.parse(e)}catch(t){this.engageQueue=[]}}async flushEngageEvents(){if(0===this.engageQueue.length||this.isFlushing)return;if("undefined"!=typeof navigator&&!navigator.onLine)return;this.isFlushing=!0;const e=[...this.engageQueue];this.engageQueue=[],this.saveEngage();let t=0,i=!1;for(;t<this.MAX_RETRIES&&!i;){const a=await this.transport.sendEngageEvents(e);if(a.success){i=!0;break}if(a.permanent)return void(this.isFlushing=!1);if(t++,t<this.MAX_RETRIES){const e=1e3*Math.pow(2,t-1);await new Promise(t=>setTimeout(t,e))}}this.isFlushing=!1}flushBeacon(){if(this.engageQueue.length>0){const e=JSON.stringify({events:this.engageQueue});this.transport.beaconFlush(e)&&(this.engageQueue=[],this.saveEngage())}}}class f{constructor(e){t(this,"apiKey",""),this.endpoints=e}setApiKey(e){this.apiKey=e}async sendEngageEvents(e){const t=JSON.stringify({events:e});return this.sendRaw(t,this.endpoints.engage)}async sendRaw(e,t){const i={"Content-Type":"application/json"};this.apiKey&&(i.Authorization=`Bearer ${this.apiKey}`);try{const a=await fetch(t,{method:"POST",headers:i,body:e,keepalive:!0});return 401===a.status||422===a.status?{success:!1,permanent:!0,status:a.status}:{success:a.ok||202===a.status,permanent:!1,status:a.status}}catch(a){return{success:!1,permanent:!1}}}beaconFlush(e){if("undefined"==typeof navigator||!navigator.sendBeacon)return!1;const t=this.endpoints.engage,i=new Blob([e],{type:"application/json"});return navigator.sendBeacon(t,i)}}const m={"Asia/Kolkata":"IN","Asia/Calcutta":"IN","Asia/Mumbai":"IN","Asia/Dhaka":"BD","Asia/Kathmandu":"NP","Asia/Colombo":"LK","Asia/Karachi":"PK","Asia/Kabul":"AF","Asia/Tehran":"IR","Asia/Dubai":"AE","Asia/Muscat":"OM","Asia/Bahrain":"BH","Asia/Qatar":"QA","Asia/Kuwait":"KW","Asia/Riyadh":"SA","Asia/Aden":"YE","Asia/Baghdad":"IQ","Asia/Amman":"JO","Asia/Beirut":"LB","Asia/Damascus":"SY","Asia/Jerusalem":"IL","Asia/Tel_Aviv":"IL","Asia/Nicosia":"CY","Asia/Tokyo":"JP","Asia/Seoul":"KR","Asia/Pyongyang":"KP","Asia/Shanghai":"CN","Asia/Chongqing":"CN","Asia/Harbin":"CN","Asia/Urumqi":"CN","Asia/Hong_Kong":"HK","Asia/Macau":"MO","Asia/Taipei":"TW","Asia/Singapore":"SG","Asia/Kuala_Lumpur":"MY","Asia/Brunei":"BN","Asia/Jakarta":"ID","Asia/Makassar":"ID","Asia/Jayapura":"ID","Asia/Bangkok":"TH","Asia/Ho_Chi_Minh":"VN","Asia/Saigon":"VN","Asia/Phnom_Penh":"KH","Asia/Vientiane":"LA","Asia/Yangon":"MM","Asia/Rangoon":"MM","Asia/Manila":"PH","Asia/Ulaanbaatar":"MN","Asia/Hovd":"MN","Asia/Tbilisi":"GE","Asia/Baku":"AZ","Asia/Yerevan":"AM","Asia/Almaty":"KZ","Asia/Bishkek":"KG","Asia/Tashkent":"UZ","Asia/Ashgabat":"TM","Asia/Dushanbe":"TJ","Asia/Thimphu":"BT","Asia/Dili":"TL","Europe/London":"GB","Europe/Dublin":"IE","Europe/Lisbon":"PT","Europe/Madrid":"ES","Europe/Paris":"FR","Europe/Brussels":"BE","Europe/Amsterdam":"NL","Europe/Luxembourg":"LU","Europe/Berlin":"DE","Europe/Zurich":"CH","Europe/Vienna":"AT","Europe/Rome":"IT","Europe/Monaco":"MC","Europe/Vatican":"VA","Europe/Malta":"MT","Europe/Prague":"CZ","Europe/Budapest":"HU","Europe/Warsaw":"PL","Europe/Bratislava":"SK","Europe/Ljubljana":"SI","Europe/Zagreb":"HR","Europe/Belgrade":"RS","Europe/Sarajevo":"BA","Europe/Podgorica":"ME","Europe/Skopje":"MK","Europe/Tirane":"AL","Europe/Sofia":"BG","Europe/Bucharest":"RO","Europe/Chisinau":"MD","Europe/Athens":"GR","Europe/Istanbul":"TR","Europe/Helsinki":"FI","Europe/Stockholm":"SE","Europe/Oslo":"NO","Europe/Copenhagen":"DK","Europe/Tallinn":"EE","Europe/Riga":"LV","Europe/Vilnius":"LT","Europe/Minsk":"BY","Europe/Moscow":"RU","Europe/Kaliningrad":"RU","Europe/Samara":"RU","Europe/Kiev":"UA","Europe/Kyiv":"UA","Europe/Reykjavik":"IS","Europe/Andorra":"AD","Europe/Gibraltar":"GI","Europe/San_Marino":"SM","America/New_York":"US","America/Chicago":"US","America/Denver":"US","America/Los_Angeles":"US","America/Phoenix":"US","America/Anchorage":"US","Pacific/Honolulu":"US","America/Detroit":"US","America/Indianapolis":"US","America/Boise":"US","America/Juneau":"US","America/Adak":"US","America/Toronto":"CA","America/Vancouver":"CA","America/Montreal":"CA","America/Winnipeg":"CA","America/Edmonton":"CA","America/Halifax":"CA","America/St_Johns":"CA","America/Regina":"CA","America/Mexico_City":"MX","America/Cancun":"MX","America/Tijuana":"MX","America/Monterrey":"MX","America/Hermosillo":"MX","America/Guatemala":"GT","America/Belize":"BZ","America/El_Salvador":"SV","America/Tegucigalpa":"HN","America/Managua":"NI","America/Costa_Rica":"CR","America/Panama":"PA","America/Bogota":"CO","America/Lima":"PE","America/Guayaquil":"EC","America/Caracas":"VE","America/La_Paz":"BO","America/Asuncion":"PY","America/Montevideo":"UY","America/Buenos_Aires":"AR","America/Argentina/Buenos_Aires":"AR","America/Santiago":"CL","America/Sao_Paulo":"BR","America/Recife":"BR","America/Manaus":"BR","America/Fortaleza":"BR","America/Bahia":"BR","America/Havana":"CU","America/Jamaica":"JM","America/Port-au-Prince":"HT","America/Santo_Domingo":"DO","America/Puerto_Rico":"PR","America/Port_of_Spain":"TT","America/Barbados":"BB","America/Martinique":"MQ","America/Guyana":"GY","America/Paramaribo":"SR","America/Cayenne":"GF","America/Curacao":"CW","Africa/Cairo":"EG","Africa/Casablanca":"MA","Africa/Tunis":"TN","Africa/Algiers":"DZ","Africa/Tripoli":"LY","Africa/Khartoum":"SD","Africa/Addis_Ababa":"ET","Africa/Nairobi":"KE","Africa/Dar_es_Salaam":"TZ","Africa/Kampala":"UG","Africa/Mogadishu":"SO","Africa/Lagos":"NG","Africa/Accra":"GH","Africa/Abidjan":"CI","Africa/Dakar":"SN","Africa/Bamako":"ML","Africa/Ouagadougou":"BF","Africa/Conakry":"GN","Africa/Freetown":"SL","Africa/Monrovia":"LR","Africa/Lome":"TG","Africa/Porto-Novo":"BJ","Africa/Niamey":"NE","Africa/Douala":"CM","Africa/Libreville":"GA","Africa/Bangui":"CF","Africa/Brazzaville":"CG","Africa/Kinshasa":"CD","Africa/Lubumbashi":"CD","Africa/Luanda":"AO","Africa/Maputo":"MZ","Africa/Harare":"ZW","Africa/Lusaka":"ZM","Africa/Lilongwe":"MW","Africa/Johannesburg":"ZA","Africa/Windhoek":"NA","Africa/Gaborone":"BW","Africa/Maseru":"LS","Africa/Mbabane":"SZ","Indian/Antananarivo":"MG","Indian/Mauritius":"MU","Indian/Reunion":"RE","Indian/Comoro":"KM","Indian/Mayotte":"YT","Africa/Djibouti":"DJ","Africa/Asmara":"ER","Australia/Sydney":"AU","Australia/Melbourne":"AU","Australia/Brisbane":"AU","Australia/Perth":"AU","Australia/Adelaide":"AU","Australia/Hobart":"AU","Australia/Darwin":"AU","Australia/Lord_Howe":"AU","Pacific/Auckland":"NZ","Pacific/Chatham":"NZ","Pacific/Fiji":"FJ","Pacific/Tongatapu":"TO","Pacific/Apia":"WS","Pacific/Port_Moresby":"PG","Pacific/Noumea":"NC","Pacific/Guam":"GU","Pacific/Pago_Pago":"AS","Pacific/Tahiti":"PF","Atlantic/Reykjavik":"IS","Atlantic/Azores":"PT","Atlantic/Canary":"ES","Atlantic/Madeira":"PT","Atlantic/Cape_Verde":"CV","Atlantic/Bermuda":"BM","Indian/Maldives":"MV","Indian/Chagos":"IO","Indian/Christmas":"CX","Indian/Cocos":"CC"},g=new Set(["password","hidden","email","tel","number"]),y=["password","pass","cvv","card","credit","ssn","secret","name","phone","email","address"];class v{constructor(e){t(this,"instance"),t(this,"observer",null),t(this,"trackedProducts",new Set),this.instance=e}init(){"undefined"!=typeof window&&"undefined"!=typeof document&&(this.attachEventListeners(),this.startMutationObserver())}destroy(){this.observer&&this.observer.disconnect()}isSensitive(e,t){if(g.has(t.toLowerCase()))return!0;const i=e.toLowerCase();return y.some(e=>i.includes(e))}attachEventListeners(){document.addEventListener("click",e=>{var t;const i=e.target.closest("button, a, [role='button'], [data-engage-action]");if(!i)return;const a=i.getAttribute("data-engage-action")||(null==(t=i.textContent)?void 0:t.trim().slice(0,50)),n=i.getAttribute("data-engage-product-id"),r=i.getAttribute("data-engage-price"),o=i.getAttribute("data-engage-currency")||"USD",s=(null==a?void 0:a.toLowerCase())||"";s.includes("add to cart")||s.includes("buy now")||"add_to_cart"===i.getAttribute("data-engage-intent")?this.instance.track("ADD_TO_CART",{productId:n,amount:r?parseFloat(r):void 0,currency:o,actionName:a},{intent:"commerce",standardEvent:"ADD_TO_CART"}):s.includes("cancel")&&(s.includes("order")||s.includes("subscription"))?this.instance.track("ORDER_CANCELLED",{actionName:a},{intent:"commerce",standardEvent:"GENERIC"}):s.includes("review")||s.includes("submit rating")||"review"===i.getAttribute("data-engage-intent")?this.instance.track("REVIEW_SUBMITTED",{productId:n},{intent:"engagement"}):i.hasAttribute("data-engage-track")&&this.instance.track("CLICK",{actionName:a,productId:n})},{capture:!0,passive:!0}),document.addEventListener("submit",e=>{const t=e.target,i=t.getAttribute("action")||"",a=t.id||"",n=t.className||"",r=t.getAttribute("data-engage-intent"),o=`${i} ${a} ${n} ${r}`.toLowerCase(),s={};new FormData(t),t.querySelectorAll("input, select, textarea").forEach(e=>{const t=e;t.name&&!this.isSensitive(t.name,t.type)&&(s[`has_${t.name}`]=!0)}),o.includes("signup")||o.includes("register")?this.instance.track("SIGNUP",{formId:a,metadata:s},{intent:"identity",standardEvent:"REGISTER"}):o.includes("checkout")||o.includes("payment")?this.instance.track("CHECKOUT_STARTED",{formId:a},{intent:"commerce"}):r&&this.instance.track(r.toUpperCase(),{formId:a,metadata:s})},{capture:!0,passive:!0})}startMutationObserver(){this.observer=new MutationObserver(e=>{e.forEach(e=>{"childList"===e.type&&e.addedNodes.forEach(e=>{if(e.nodeType===Node.ELEMENT_NODE){const t=e;this.scanForProducts(t)}})})}),this.observer.observe(document.body,{childList:!0,subtree:!0}),this.scanForProducts(document.body)}scanForProducts(e){e.querySelectorAll("[data-engage-product-id]").forEach(e=>{const t=e.getAttribute("data-engage-product-id");if(!t||this.trackedProducts.has(t))return;this.trackedProducts.add(t);const i=e.getAttribute("data-engage-product-name"),a=e.getAttribute("data-engage-category"),n=e.getAttribute("data-engage-price"),r=e.getAttribute("data-engage-currency")||"USD";this.instance.track("VIEW_CONTENT",{productId:t,productName:i,productCategory:a,amount:n?parseFloat(n):void 0,currency:r},{intent:"commerce",standardEvent:"VIEW_CONTENT"})})}}const E=new Set(["localhost","127.0.0.1"]),w="engage_session_id",b={$:"USD",US$:"USD",USD:"USD","₹":"INR",RS:"INR","RS.":"INR",INR:"INR","€":"EUR",EUR:"EUR","£":"GBP",GBP:"GBP","¥":"JPY",JPY:"JPY"},S=e=>{if("string"!=typeof e)return;const t=e.trim().toUpperCase();return t?b[t]?b[t]:t.includes("₹")||t.startsWith("RS")?"INR":t.includes("$")&&!t.includes("CAD")?"USD":t.includes("€")?"EUR":t.includes("£")?"GBP":t.includes("¥")?"JPY":/^[A-Z]{3}$/.test(t)?t:void 0:void 0};function C(e){if(!e||"object"!=typeof e)return;const t={},i=Object.keys(e).slice(0,20);for(const a of i){const i=e[a];"boolean"==typeof i||"number"==typeof i?t[a]=i:"string"==typeof i&&(t[a]=i.slice(0,100))}return Object.keys(t).length>0?t:void 0}class R{constructor(e){t(this,"config"),t(this,"context"),t(this,"queue"),t(this,"transport"),t(this,"domTracker"),t(this,"sessionId"),t(this,"countryCode"),t(this,"currentSentiment"),t(this,"identify",(e,t)=>{this.context.userId=e,this.processEvent({event:"Identify",properties:{traits:t},standardEvent:"LOGIN",intent:"identity",confidence:1})}),t(this,"page",(e,t)=>{const i=this.context.getPayload().page;this.processEvent({event:e||i.title||"Unknown Page",properties:{path:i.path,referrer:i.referrer,title:i.title,...t},standardEvent:"PAGE_VIEW",intent:"navigation",confidence:1}),this.emitEngageEvent("pageview",t)}),t(this,"track",(e,t,i)=>{this.processEvent({event:e,properties:t||{},...i});const a={purchase:"purchase",PURCHASE:"purchase",signup:"signup",SIGNUP:"signup",register:"signup",REGISTER:"signup",add_to_cart:"add_to_cart",ADD_TO_CART:"add_to_cart",product_view:"product_view",VIEW_CONTENT:"product_view",session_start:"session_start",session_end:"session_end"},n=a[e]||a[(null==i?void 0:i.standardEvent)||""]||"custom";this.emitEngageEvent(n,t)}),t(this,"trackRevenue",(e,t,i)=>{const a=Math.max(0,(e=>{if("number"==typeof e)return Number.isFinite(e)?e:0;const t=e.trim().replace(/[^0-9.+-]/g,""),i=Number(t);return Number.isFinite(i)?i:0})(e)),n=S(null==t?void 0:t.currency)||S(null==t?void 0:t.currencyCode)||S(null==t?void 0:t.currencySymbol)||("string"==typeof e?S(e):void 0)||"USD";this.track("PURCHASE",{...t||{},value:a,amount:a,valuePaise:Math.round(100*a),amountPaise:Math.round(100*a),currency:n,currencyCode:n},{standardEvent:"PURCHASE",intent:"commerce",confidence:1,...i})}),t(this,"setSentiment",e=>{this.currentSentiment=e}),this.config=e;const i=e.apiKey,a=((e,t,i)=>{if(!e)return i;try{const t=new URL(e);return t.hostname.endsWith("bluenath.com")||E.has(t.hostname)?(t.pathname="/api/v1/analytics/ingest",t.search="",t.hash="",t.toString()):i}catch{return i}})(e.apiHost,0,"https://engage-api.bluenath.com/api/v1/analytics/ingest");this.transport=new f({engage:a}),this.transport.setApiKey(i),this.context=new A({persistence:e.tracking.useCookies?"cookie":"local"}),this.queue=new p(this.transport),this.sessionId=function(){if("undefined"==typeof sessionStorage)return d();let e=sessionStorage.getItem(w);return e||(e=d(),sessionStorage.setItem(w,e)),e}(),this.countryCode=function(){try{const e=Intl.DateTimeFormat().resolvedOptions().timeZone;if(!e)return;return m[e]}catch{return}}(),this.domTracker=new v(this),e.tracking.autoTrack&&"undefined"!=typeof window&&(this.page(),this.domTracker.init())}emitEngageEvent(e,t){const i=this.context.getPayload().page,a={type:e,timestamp:(new Date).toISOString(),sessionId:this.sessionId,userId:this.context.getPayload().user.id||void 0,countryCode:this.countryCode,sentiment:this.currentSentiment,referrer:(i.referrer||"").slice(0,500),path:i.path||("undefined"!=typeof window?window.location.pathname:"/"),currency:S(null==t?void 0:t.currency)||S(null==t?void 0:t.currencyCode)||void 0,amount:"number"==typeof(null==t?void 0:t.amountPaise)?t.amountPaise:"number"==typeof(null==t?void 0:t.amount)?Math.round(100*t.amount):void 0,productId:"string"==typeof(null==t?void 0:t.productId)?t.productId:void 0,productName:"string"==typeof(null==t?void 0:t.productName)?t.productName:void 0,productCategory:"string"==typeof(null==t?void 0:t.productCategory)?t.productCategory:void 0,metadata:C(null==t?void 0:t.metadata)};this.queue.enqueueEngageEvent(a),this.currentSentiment&&(this.currentSentiment=void 0)}parseRef(e){if(!e)return{};const t=e.match(/^camp_([^_]+)_cr_([^_]+)$/);return t?{campaignId:t[1],creatorId:t[2]}:{}}processEvent(e){const t=this.context.getPayload(),i=e.properties.ref,a=("string"==typeof i?i:void 0)||new URLSearchParams(t.page.search||"").get("ref")||void 0,n=this.parseRef(a),r=e.properties.value??e.properties.amount??e.properties.valuePaise??e.properties.amountPaise,o=Number(r),s=e.properties.campaignId,c=e.properties.creatorId,u=e.properties.currency,h={event:e.event,properties:e.properties,standardEvent:e.standardEvent,intent:e.intent,confidence:e.confidence,rawLabel:e.rawLabel,timestamp:(new Date).toISOString(),messageId:d(),writeKey:this.config.apiKey||"",ref:a,campaignId:("string"==typeof s?s:void 0)||n.campaignId,creatorId:("string"==typeof c?c:void 0)||n.creatorId,value:Number.isFinite(o)?Math.round(o):void 0,valuePaise:Number.isFinite(o)?Math.round(100*o):void 0,currency:("string"==typeof u?u:void 0)||"USD",userId:t.user.id||void 0,anonymousId:t.user.anonymousId,context:t};this.config.debug,this.queue.enqueue(h)}}class I{constructor(e){t(this,"analytics"),t(this,"metrics",{}),this.analytics=e,"undefined"!=typeof window&&"PerformanceObserver"in window&&this.observe()}observe(){try{new PerformanceObserver(e=>{for(const t of e.getEntries()){const e=t;e.hadRecentInput||(this.metrics.cls=(this.metrics.cls||0)+e.value)}}).observe({type:"layout-shift",buffered:!0}),new PerformanceObserver(e=>{const t=e.getEntries(),i=t[t.length-1];this.metrics.lcp=i.renderTime||i.loadTime,this.logMetric("LCP",this.metrics.lcp)}).observe({type:"largest-contentful-paint",buffered:!0}),new PerformanceObserver(e=>{const t=e.getEntries()[0];t&&(this.metrics.fid=t.processingStart-t.startTime,this.logMetric("FID",this.metrics.fid))}).observe({type:"first-input",buffered:!0}),window.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState&&this.metrics.cls&&this.logMetric("CLS",this.metrics.cls)})}catch(e){}}logMetric(e,t){t<0||this.analytics.track(`Core Web Vital: ${e}`,{metric:e,value:Math.round(t)},{standardEvent:"PERFORMANCE",intent:"performance",confidence:1,rawLabel:`${e}: ${Math.round(t)}ms`})}}const _=a.createContext(null);let P=null;const M=e=>{if(!P){const t={...e,apiKey:e.apiKey||""};P=new R(t)}return P},T={init:e=>M({apiKey:e.apiKey,apiHost:e.apiHost,tracking:e.tracking||{useCookies:!0,fingerprint:!0,autoTrack:!0},debug:e.debug}),track(e,t){P&&P.track(e,t)},page(e,t){P&&P.page(e,t)},identify(e,t){P&&P.identify(e,t)},trackRevenue(e,t){P&&P.trackRevenue(e,t)},setSentiment(e){P&&P.setSentiment(e)}};exports.EngageProProvider=({children:e,...t})=>{const n=a.useRef(null),r=a.useRef(null);n.current||(n.current=new R(t),"undefined"!=typeof window&&new I(n.current));const o=n.current;return a.useEffect(()=>{if(!t.tracking.autoTrack)return;const e=e=>{const t=e.target.closest('button, a, input[type="submit"], [data-track], .clickable');if(t){const i=Date.now(),a=r.current;a&&a.el===t&&i-a.ts<500?(a.count++,a.ts=i,3===a.count&&(o.track("Rage Click detected",{element:t.tagName},{standardEvent:"RAGE_CLICK",intent:"frustration",confidence:1}),r.current=null)):r.current={el:t,count:1,ts:i};const n=(e=>{let t=(e.innerText||e.value||e.getAttribute("aria-label")||"").trim();if(!t){const i=e.querySelector("img");i&&i.alt&&(t=i.alt);const a=e.querySelector("title");a&&(t=a.textContent||"")}const i=t.slice(0,100),a=i.toLowerCase(),n=(e.id||"").toLowerCase(),r=e.href||"";return/add to (cart|bag)|buy now/.test(a)||n.includes("add-to-cart")?{standard:"ADD_TO_CART",intent:"commerce",label:i,confidence:.9}:/checkout|proceed/.test(a)||r.includes("/checkout")?{standard:"INITIATE_CHECKOUT",intent:"commerce",label:i,confidence:.9}:/place order|pay now/.test(a)||n.includes("place-order")?{standard:"PURCHASE",intent:"commerce",label:i,confidence:.95}:/cancel order/.test(a)||n.includes("cancel")?{standard:"ORDER_CANCEL",intent:"lifecycle",label:i,confidence:.85}:/refund|return/.test(a)||n.includes("refund")?{standard:"ORDER_REFUND",intent:"lifecycle",label:i,confidence:.85}:/track package|shipping/.test(a)?{standard:"TRACK_PACKAGE",intent:"lifecycle",label:i,confidence:.8}:/write review/.test(a)||a.includes("star")&&/^[1-5]/.test(a)?{standard:"RATE_PRODUCT",intent:"engagement",label:i,confidence:.8}:a.includes("search")||n.includes("search")?{standard:"SEARCH",intent:"search",label:i,confidence:.7}:{standard:"GENERIC",intent:"interaction",label:i,confidence:.5}})(t),s="A"===t.tagName;let c={};"commerce"===n.intent&&(c=(t=>{let i={};try{const a=document.querySelectorAll('script[type="application/ld+json"]');for(const t of Array.from(a))try{const e=JSON.parse(t.innerHTML),a=Array.isArray(e)?e:[e];for(const t of a)if("Product"===t["@type"]){if(t.name&&(i.productName=t.name),(t.sku||t.productID)&&(i.productId=t.sku||t.productID),t.offers){const e=Array.isArray(t.offers)?t.offers[0]:t.offers;e.price&&(i.amount=Number(e.price)),e.priceCurrency&&(i.currency=e.priceCurrency)}if(i.amount)return i}}catch(e){}if(!i.amount){const e=document.querySelector('meta[property="product:price:amount"]'),t=document.querySelector('meta[property="product:price:currency"]'),a=document.querySelector('meta[property="og:title"]');e&&(i.amount=Number(e.getAttribute("content"))),t&&(i.currency=t.getAttribute("content")),a&&(i.productName=a.getAttribute("content"))}if(!i.amount){const e=(t.innerText||"").match(/([$€£₹¥])\s*([0-9,]+\.[0-9]{2})/);if(e){const t=e[1],a=e[2].replace(/,/g,"");i.amount=Number(a);const n={$:"USD","€":"EUR","£":"GBP","₹":"INR","¥":"JPY"};i.currency=n[t]||"USD"}else{let e=t,a=0;for(;e&&a<3&&!i.amount;){const t=e.innerText||"";if(t.length<500){const e=t.match(/([$€£₹¥])\s*([0-9,]+\.[0-9]{2})/);if(e){const t=e[1],a=e[2].replace(/,/g,"");i.amount=Number(a);const n={$:"USD","€":"EUR","£":"GBP","₹":"INR","¥":"JPY"};i.currency=n[t]||"USD"}}e=e.parentElement,a++}}}}catch(a){}return i})(t)),o.track("Interaction",{element:t.tagName.toLowerCase(),id:t.id,destination:s?t.href:void 0,...c},{standardEvent:n.standard,intent:n.intent,rawLabel:n.label,confidence:n.confidence})}},i=e=>{const t=e.target;(e=>"password"===e.getAttribute("type")||"hidden"===e.getAttribute("type")||/password|cvc|card|cc-num|ssn|credit|hidden/i.test(e.getAttribute("name")||e.id||""))(t)||"focusin"!==e.type||t.dataset.tracked||(t.dataset.tracked="true",o.track("Form Start",{field:t.name||t.id},{standardEvent:"FORM_START",intent:"identity"}))},a=()=>{const e=new URLSearchParams(window.location.search);e.has("q")&&o.track("Search Query",{query:e.get("q")},{standardEvent:"SEARCH",intent:"search"}),requestAnimationFrame(()=>o.page())},n=history.pushState;return history.pushState=(...e)=>{n.apply(history,e),a()},window.addEventListener("popstate",a),window.addEventListener("click",e,!0),window.addEventListener("focusin",i,!0),a(),()=>{history.pushState=n,window.removeEventListener("popstate",a),window.removeEventListener("click",e,!0),window.removeEventListener("focusin",i,!0)}},[t.tracking.autoTrack]),i.jsx(_.Provider,{value:o,children:e})},exports.default=R,exports.engage=T,exports.init=M,exports.useAnalytics=()=>{const e=a.useContext(_);if(!e)throw new Error("useAnalytics must be used within EngageProProvider");return e};
1
+ "use strict";var e=Object.defineProperty,t=(t,i,n)=>((t,i,n)=>i in t?e(t,i,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[i]=n)(t,"symbol"!=typeof i?i+"":i,n);Object.defineProperties(exports,{t:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const i=require("react/jsx-runtime"),n=require("react");let a;const r=new Uint8Array(16);function o(){if(!a&&(a="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!a))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return a(r)}const s=[];for(let U=0;U<256;++U)s.push((U+256).toString(16).slice(1));const c={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function d(e,t,i){if(c.randomUUID&&!e)return c.randomUUID();const n=(e=e||{}).random||(e.rng||o)();return n[6]=15&n[6]|64,n[8]=63&n[8]|128,function(e,t=0){return s[e[t+0]]+s[e[t+1]]+s[e[t+2]]+s[e[t+3]]+"-"+s[e[t+4]]+s[e[t+5]]+"-"+s[e[t+6]]+s[e[t+7]]+"-"+s[e[t+8]]+s[e[t+9]]+"-"+s[e[t+10]]+s[e[t+11]]+s[e[t+12]]+s[e[t+13]]+s[e[t+14]]+s[e[t+15]]}(n)}const u=e=>{let t=2166136261;const i=e.length;for(let n=0;n<i;n++)t^=e.charCodeAt(n),t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24);return("0000000"+(t>>>0).toString(16)).substr(-8)},h=()=>{try{const e=document.createElement("canvas");e.width=200,e.height=50;const t=e.getContext("2d");return t?(t.textBaseline="top",t.font="14px 'Arial'",t.textBaseline="alphabetic",t.fillStyle="#f60",t.fillRect(125,1,62,20),t.fillStyle="#069",t.fillText("EngagePro, 😃",2,15),t.fillStyle="rgba(102, 204, 0, 0.7)",t.fillText("EngagePro, 😃",4,17),u(e.toDataURL())):""}catch(e){return""}};class l{constructor(e="local"){t(this,"memoryStore",{}),t(this,"keyPrefix","engage_"),t(this,"domain"),this.type=e,this.domain=this.getCookieDomain()}getItem(e){const t=this.keyPrefix+e;if(this.memoryStore.hasOwnProperty(t))return this.memoryStore[t];try{if("local"===this.type&&this.isBrowser())return window.localStorage.getItem(t);if("cookie"===this.type&&this.isBrowser())return this.getCookie(t)}catch(i){return null}return null}setItem(e,t){const i=this.keyPrefix+e;this.memoryStore[i]=t;try{"local"===this.type&&this.isBrowser()?window.localStorage.setItem(i,t):"cookie"===this.type&&this.isBrowser()&&this.setCookie(i,t,365)}catch(n){this.isQuotaError(n)&&(this.type="memory")}}removeItem(e){const t=this.keyPrefix+e;delete this.memoryStore[t];try{"local"===this.type&&this.isBrowser()?window.localStorage.removeItem(t):"cookie"===this.type&&this.isBrowser()&&this.setCookie(t,"",-1)}catch(i){}}getCookie(e){const t=e+"=",i=document.cookie.split(";");for(let n=0;n<i.length;n++){let e=i[n];for(;" "===e.charAt(0);)e=e.substring(1,e.length);if(0===e.indexOf(t))return decodeURIComponent(e.substring(t.length,e.length))}return null}setCookie(e,t,i){let n="";if(i){const e=new Date;e.setTime(e.getTime()+24*i*60*60*1e3),n="; expires="+e.toUTCString()}document.cookie=`${e}=${encodeURIComponent(t)}${n}; path=/; domain=${this.domain}; SameSite=Lax; Secure`}getCookieDomain(){if(!this.isBrowser())return"";const e=window.location.hostname,t=e.split(".");return 1===t.length||"localhost"===e?"":t.length>2?"."+t.slice(-2).join("."):"."+e}isBrowser(){try{return"undefined"!=typeof window&&void 0!==window.document}catch(e){return!1}}isQuotaError(e){return e instanceof DOMException&&(22===e.code||1014===e.code||"QuotaExceededError"===e.name||"NS_ERROR_DOM_QUOTA_REACHED"===e.name)}}class A{constructor(e){t(this,"storage"),t(this,"SESSION_TIMEOUT",18e5),t(this,"deviceId"),t(this,"sessionId"),t(this,"userId",null),t(this,"currentUrl"),t(this,"referrer"),this.storage=new l(e.persistence),this.deviceId=this.getOrSetDeviceId(),this.sessionId="",this.manageSession(),"undefined"!=typeof window?(this.currentUrl=window.location.href,this.referrer=document.referrer,this.listenToHistory()):(this.currentUrl="",this.referrer="")}getOrSetDeviceId(){const e=this.storage.getItem("device_id");if(e)return e;const t=(()=>{if("undefined"==typeof window)return"server-side-id";const e=navigator,t=window.screen,i=(()=>{try{const e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");if(!t)return{vendor:"",renderer:""};const i=t.getExtension("WEBGL_debug_renderer_info");return i?{vendor:t.getParameter(i.UNMASKED_VENDOR_WEBGL),renderer:t.getParameter(i.UNMASKED_RENDERER_WEBGL)}:{vendor:"",renderer:""}}catch(e){return{vendor:"",renderer:""}}})(),n={userAgent:e.userAgent||"",screenRes:`${t.width}x${t.height}`,colorDepth:t.colorDepth||0,timezone:(new Date).getTimezoneOffset(),language:e.language||"en-US",platform:e.platform||"unknown",hardwareConcurrency:e.hardwareConcurrency||1,deviceMemory:e.deviceMemory||0,canvasFingerprint:h(),webglVendor:i.vendor,webglRenderer:i.renderer},a=[n.platform,n.language,n.screenRes,n.colorDepth,n.timezone,n.hardwareConcurrency,n.deviceMemory,n.canvasFingerprint,n.webglVendor,n.webglRenderer].join("|");return`${u(a)}-${u(n.userAgent)}`})();return this.storage.setItem("device_id",t),t}manageSession(){const e=Date.now(),t=this.storage.getItem("session_id"),i=parseInt(this.storage.getItem("last_activity")||"0");if(!t||e-i>this.SESSION_TIMEOUT?(this.sessionId=`sess_${e}_${Math.random().toString(36).substr(2,9)}`,this.storage.setItem("session_id",this.sessionId)):this.sessionId=t,this.storage.setItem("last_activity",e.toString()),"undefined"!=typeof window){const e=()=>this.storage.setItem("last_activity",Date.now().toString());window.addEventListener("click",e),window.addEventListener("scroll",e)}}listenToHistory(){const e=history.pushState;history.pushState=(...t)=>{e.apply(history,t),this.handleUrlChange()},window.addEventListener("popstate",()=>this.handleUrlChange())}handleUrlChange(){const e=window.location.href;e!==this.currentUrl&&(this.referrer=this.currentUrl,this.currentUrl=e)}getPayload(){var e;return{library:{name:"@engagepro/analytics",version:"2.0.0"},user:{anonymousId:this.deviceId,id:this.userId},session:{id:this.sessionId,startTime:parseInt(this.sessionId.split("_")[1]||Date.now().toString())},page:{path:"undefined"!=typeof window?window.location.pathname:"",referrer:this.referrer,title:"undefined"!=typeof document?document.title:"",search:"undefined"!=typeof window?window.location.search:"",url:this.currentUrl},network:{online:"undefined"==typeof navigator||navigator.onLine,downlink:null==(e=navigator.connection)?void 0:e.downlink},screen:{width:"undefined"!=typeof screen?screen.width:0,height:"undefined"!=typeof screen?screen.height:0,density:"undefined"!=typeof window?window.devicePixelRatio:1},device:{fingerprint:this.deviceId,type:this.getDeviceType(),userAgent:"undefined"!=typeof navigator?navigator.userAgent:"server"},locale:"undefined"!=typeof navigator?navigator.language:"en-US",timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}}getDeviceType(){if("undefined"==typeof navigator)return"desktop";const e=navigator.userAgent;return/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(e)?"tablet":/Mobile|Android|iP(hone|od)|IEMobile|BlackBerry|Kindle|Silk-Accelerated/.test(e)?"mobile":"desktop"}}class p{constructor(e){t(this,"engageQueue",[]),t(this,"storage"),t(this,"transport"),t(this,"ENGAGE_STORAGE_KEY","engage_events_v2"),t(this,"isFlushing",!1),t(this,"flushInterval"),t(this,"MAX_RETRIES",3),this.transport=e,this.storage=new l("local"),this.load(),"undefined"!=typeof window&&(window.addEventListener("online",()=>{this.flushEngageEvents()}),window.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState&&this.flushBeacon()}),window.addEventListener("beforeunload",()=>{this.flushBeacon()})),this.startTimer()}startTimer(){this.flushInterval&&clearInterval(this.flushInterval),this.flushInterval=setInterval(()=>{this.flushEngageEvents()},5e3)}enqueueEngageEvent(e){this.engageQueue.push(e),this.saveEngage(),this.engageQueue.length>=10&&this.flushEngageEvents()}enqueue(e){}saveEngage(){this.storage.setItem(this.ENGAGE_STORAGE_KEY,JSON.stringify(this.engageQueue))}load(){const e=this.storage.getItem(this.ENGAGE_STORAGE_KEY);if(e)try{this.engageQueue=JSON.parse(e)}catch(t){this.engageQueue=[]}}async flushEngageEvents(){if(0===this.engageQueue.length||this.isFlushing)return;if("undefined"!=typeof navigator&&!navigator.onLine)return;this.isFlushing=!0;const e=[...this.engageQueue];this.engageQueue=[],this.saveEngage();let t=0,i=!1;for(;t<this.MAX_RETRIES&&!i;){const n=await this.transport.sendEngageEvents(e);if(n.success){i=!0;break}if(n.permanent)return void(this.isFlushing=!1);if(t++,t<this.MAX_RETRIES){const e=1e3*Math.pow(2,t-1);await new Promise(t=>setTimeout(t,e))}}this.isFlushing=!1}flushBeacon(){if(this.engageQueue.length>0){const e=JSON.stringify({events:this.engageQueue});this.transport.beaconFlush(e)&&(this.engageQueue=[],this.saveEngage())}}}class f{constructor(e){t(this,"apiKey",""),this.endpoints=e}setApiKey(e){this.apiKey=e}async sendEngageEvents(e){const t=JSON.stringify({events:e});return this.sendRaw(t,this.endpoints.engage)}async sendRaw(e,t){const i={"Content-Type":"application/json"};this.apiKey&&(i.Authorization=`Bearer ${this.apiKey}`);try{const n=await fetch(t,{method:"POST",headers:i,body:e,keepalive:!0});return 401===n.status||422===n.status?{success:!1,permanent:!0,status:n.status}:{success:n.ok||202===n.status,permanent:!1,status:n.status}}catch(n){return{success:!1,permanent:!1}}}beaconFlush(e){if("undefined"==typeof navigator||!navigator.sendBeacon)return!1;let t=this.endpoints.engage;if(this.apiKey){const e=t.includes("?")?"&":"?";t=`${t}${e}apiKey=${encodeURIComponent(this.apiKey)}`}const i=new Blob([e],{type:"application/json"});return navigator.sendBeacon(t,i)}}const m={"Asia/Kolkata":"IN","Asia/Calcutta":"IN","Asia/Mumbai":"IN","Asia/Dhaka":"BD","Asia/Kathmandu":"NP","Asia/Colombo":"LK","Asia/Karachi":"PK","Asia/Kabul":"AF","Asia/Tehran":"IR","Asia/Dubai":"AE","Asia/Muscat":"OM","Asia/Bahrain":"BH","Asia/Qatar":"QA","Asia/Kuwait":"KW","Asia/Riyadh":"SA","Asia/Aden":"YE","Asia/Baghdad":"IQ","Asia/Amman":"JO","Asia/Beirut":"LB","Asia/Damascus":"SY","Asia/Jerusalem":"IL","Asia/Tel_Aviv":"IL","Asia/Nicosia":"CY","Asia/Tokyo":"JP","Asia/Seoul":"KR","Asia/Pyongyang":"KP","Asia/Shanghai":"CN","Asia/Chongqing":"CN","Asia/Harbin":"CN","Asia/Urumqi":"CN","Asia/Hong_Kong":"HK","Asia/Macau":"MO","Asia/Taipei":"TW","Asia/Singapore":"SG","Asia/Kuala_Lumpur":"MY","Asia/Brunei":"BN","Asia/Jakarta":"ID","Asia/Makassar":"ID","Asia/Jayapura":"ID","Asia/Bangkok":"TH","Asia/Ho_Chi_Minh":"VN","Asia/Saigon":"VN","Asia/Phnom_Penh":"KH","Asia/Vientiane":"LA","Asia/Yangon":"MM","Asia/Rangoon":"MM","Asia/Manila":"PH","Asia/Ulaanbaatar":"MN","Asia/Hovd":"MN","Asia/Tbilisi":"GE","Asia/Baku":"AZ","Asia/Yerevan":"AM","Asia/Almaty":"KZ","Asia/Bishkek":"KG","Asia/Tashkent":"UZ","Asia/Ashgabat":"TM","Asia/Dushanbe":"TJ","Asia/Thimphu":"BT","Asia/Dili":"TL","Europe/London":"GB","Europe/Dublin":"IE","Europe/Lisbon":"PT","Europe/Madrid":"ES","Europe/Paris":"FR","Europe/Brussels":"BE","Europe/Amsterdam":"NL","Europe/Luxembourg":"LU","Europe/Berlin":"DE","Europe/Zurich":"CH","Europe/Vienna":"AT","Europe/Rome":"IT","Europe/Monaco":"MC","Europe/Vatican":"VA","Europe/Malta":"MT","Europe/Prague":"CZ","Europe/Budapest":"HU","Europe/Warsaw":"PL","Europe/Bratislava":"SK","Europe/Ljubljana":"SI","Europe/Zagreb":"HR","Europe/Belgrade":"RS","Europe/Sarajevo":"BA","Europe/Podgorica":"ME","Europe/Skopje":"MK","Europe/Tirane":"AL","Europe/Sofia":"BG","Europe/Bucharest":"RO","Europe/Chisinau":"MD","Europe/Athens":"GR","Europe/Istanbul":"TR","Europe/Helsinki":"FI","Europe/Stockholm":"SE","Europe/Oslo":"NO","Europe/Copenhagen":"DK","Europe/Tallinn":"EE","Europe/Riga":"LV","Europe/Vilnius":"LT","Europe/Minsk":"BY","Europe/Moscow":"RU","Europe/Kaliningrad":"RU","Europe/Samara":"RU","Europe/Kiev":"UA","Europe/Kyiv":"UA","Europe/Reykjavik":"IS","Europe/Andorra":"AD","Europe/Gibraltar":"GI","Europe/San_Marino":"SM","America/New_York":"US","America/Chicago":"US","America/Denver":"US","America/Los_Angeles":"US","America/Phoenix":"US","America/Anchorage":"US","Pacific/Honolulu":"US","America/Detroit":"US","America/Indianapolis":"US","America/Boise":"US","America/Juneau":"US","America/Adak":"US","America/Toronto":"CA","America/Vancouver":"CA","America/Montreal":"CA","America/Winnipeg":"CA","America/Edmonton":"CA","America/Halifax":"CA","America/St_Johns":"CA","America/Regina":"CA","America/Mexico_City":"MX","America/Cancun":"MX","America/Tijuana":"MX","America/Monterrey":"MX","America/Hermosillo":"MX","America/Guatemala":"GT","America/Belize":"BZ","America/El_Salvador":"SV","America/Tegucigalpa":"HN","America/Managua":"NI","America/Costa_Rica":"CR","America/Panama":"PA","America/Bogota":"CO","America/Lima":"PE","America/Guayaquil":"EC","America/Caracas":"VE","America/La_Paz":"BO","America/Asuncion":"PY","America/Montevideo":"UY","America/Buenos_Aires":"AR","America/Argentina/Buenos_Aires":"AR","America/Santiago":"CL","America/Sao_Paulo":"BR","America/Recife":"BR","America/Manaus":"BR","America/Fortaleza":"BR","America/Bahia":"BR","America/Havana":"CU","America/Jamaica":"JM","America/Port-au-Prince":"HT","America/Santo_Domingo":"DO","America/Puerto_Rico":"PR","America/Port_of_Spain":"TT","America/Barbados":"BB","America/Martinique":"MQ","America/Guyana":"GY","America/Paramaribo":"SR","America/Cayenne":"GF","America/Curacao":"CW","Africa/Cairo":"EG","Africa/Casablanca":"MA","Africa/Tunis":"TN","Africa/Algiers":"DZ","Africa/Tripoli":"LY","Africa/Khartoum":"SD","Africa/Addis_Ababa":"ET","Africa/Nairobi":"KE","Africa/Dar_es_Salaam":"TZ","Africa/Kampala":"UG","Africa/Mogadishu":"SO","Africa/Lagos":"NG","Africa/Accra":"GH","Africa/Abidjan":"CI","Africa/Dakar":"SN","Africa/Bamako":"ML","Africa/Ouagadougou":"BF","Africa/Conakry":"GN","Africa/Freetown":"SL","Africa/Monrovia":"LR","Africa/Lome":"TG","Africa/Porto-Novo":"BJ","Africa/Niamey":"NE","Africa/Douala":"CM","Africa/Libreville":"GA","Africa/Bangui":"CF","Africa/Brazzaville":"CG","Africa/Kinshasa":"CD","Africa/Lubumbashi":"CD","Africa/Luanda":"AO","Africa/Maputo":"MZ","Africa/Harare":"ZW","Africa/Lusaka":"ZM","Africa/Lilongwe":"MW","Africa/Johannesburg":"ZA","Africa/Windhoek":"NA","Africa/Gaborone":"BW","Africa/Maseru":"LS","Africa/Mbabane":"SZ","Indian/Antananarivo":"MG","Indian/Mauritius":"MU","Indian/Reunion":"RE","Indian/Comoro":"KM","Indian/Mayotte":"YT","Africa/Djibouti":"DJ","Africa/Asmara":"ER","Australia/Sydney":"AU","Australia/Melbourne":"AU","Australia/Brisbane":"AU","Australia/Perth":"AU","Australia/Adelaide":"AU","Australia/Hobart":"AU","Australia/Darwin":"AU","Australia/Lord_Howe":"AU","Pacific/Auckland":"NZ","Pacific/Chatham":"NZ","Pacific/Fiji":"FJ","Pacific/Tongatapu":"TO","Pacific/Apia":"WS","Pacific/Port_Moresby":"PG","Pacific/Noumea":"NC","Pacific/Guam":"GU","Pacific/Pago_Pago":"AS","Pacific/Tahiti":"PF","Atlantic/Reykjavik":"IS","Atlantic/Azores":"PT","Atlantic/Canary":"ES","Atlantic/Madeira":"PT","Atlantic/Cape_Verde":"CV","Atlantic/Bermuda":"BM","Indian/Maldives":"MV","Indian/Chagos":"IO","Indian/Christmas":"CX","Indian/Cocos":"CC"},g=new Set(["password","hidden","email","tel","number"]),y=["password","pass","cvv","card","credit","ssn","secret","name","phone","email","address"];class v{constructor(e){t(this,"instance"),t(this,"observer",null),t(this,"trackedProducts",new Set),this.instance=e}init(){"undefined"!=typeof window&&"undefined"!=typeof document&&(this.attachEventListeners(),this.startMutationObserver())}destroy(){this.observer&&this.observer.disconnect()}isSensitive(e,t){if(g.has(t.toLowerCase()))return!0;const i=e.toLowerCase();return y.some(e=>i.includes(e))}attachEventListeners(){document.addEventListener("click",e=>{var t;const i=e.target.closest("button, a, [role='button'], [data-engage-action]");if(!i)return;const n=i.getAttribute("data-engage-action")||(null==(t=i.textContent)?void 0:t.trim().slice(0,50)),a=i.getAttribute("data-engage-product-id"),r=i.getAttribute("data-engage-price"),o=i.getAttribute("data-engage-currency")||"USD",s=(null==n?void 0:n.toLowerCase())||"";s.includes("add to cart")||s.includes("buy now")||"add_to_cart"===i.getAttribute("data-engage-intent")?this.instance.track("ADD_TO_CART",{productId:a,amount:r?parseFloat(r):void 0,currency:o,actionName:n},{intent:"commerce",standardEvent:"ADD_TO_CART"}):s.includes("cancel")&&(s.includes("order")||s.includes("subscription"))?this.instance.track("ORDER_CANCELLED",{actionName:n},{intent:"commerce",standardEvent:"GENERIC"}):s.includes("review")||s.includes("submit rating")||"review"===i.getAttribute("data-engage-intent")?this.instance.track("REVIEW_SUBMITTED",{productId:a},{intent:"engagement"}):i.hasAttribute("data-engage-track")&&this.instance.track("CLICK",{actionName:n,productId:a})},{capture:!0,passive:!0}),document.addEventListener("submit",e=>{const t=e.target,i=t.getAttribute("action")||"",n=t.id||"",a=t.className||"",r=t.getAttribute("data-engage-intent"),o=`${i} ${n} ${a} ${r}`.toLowerCase(),s={};new FormData(t),t.querySelectorAll("input, select, textarea").forEach(e=>{const t=e;t.name&&!this.isSensitive(t.name,t.type)&&(s[`has_${t.name}`]=!0)}),o.includes("signup")||o.includes("register")?this.instance.track("SIGNUP",{formId:n,metadata:s},{intent:"identity",standardEvent:"REGISTER"}):o.includes("checkout")||o.includes("payment")?this.instance.track("CHECKOUT_STARTED",{formId:n},{intent:"commerce"}):r&&this.instance.track(r.toUpperCase(),{formId:n,metadata:s})},{capture:!0,passive:!0})}startMutationObserver(){this.observer=new MutationObserver(e=>{e.forEach(e=>{"childList"===e.type&&e.addedNodes.forEach(e=>{if(e.nodeType===Node.ELEMENT_NODE){const t=e;this.scanForProducts(t)}})})}),this.observer.observe(document.body,{childList:!0,subtree:!0}),this.scanForProducts(document.body)}scanForProducts(e){e.querySelectorAll("[data-engage-product-id]").forEach(e=>{const t=e.getAttribute("data-engage-product-id");if(!t||this.trackedProducts.has(t))return;this.trackedProducts.add(t);const i=e.getAttribute("data-engage-product-name"),n=e.getAttribute("data-engage-category"),a=e.getAttribute("data-engage-price"),r=e.getAttribute("data-engage-currency")||"USD";this.instance.track("VIEW_CONTENT",{productId:t,productName:i,productCategory:n,amount:a?parseFloat(a):void 0,currency:r},{intent:"commerce",standardEvent:"VIEW_CONTENT"})})}}const E=new Set(["localhost","127.0.0.1"]),w="engage_session_id",b={$:"USD",US$:"USD",USD:"USD","₹":"INR",RS:"INR","RS.":"INR",INR:"INR","€":"EUR",EUR:"EUR","£":"GBP",GBP:"GBP","¥":"JPY",JPY:"JPY"},S=e=>{if("string"!=typeof e)return;const t=e.trim().toUpperCase();return t?b[t]?b[t]:t.includes("₹")||t.startsWith("RS")?"INR":t.includes("$")&&!t.includes("CAD")?"USD":t.includes("€")?"EUR":t.includes("£")?"GBP":t.includes("¥")?"JPY":/^[A-Z]{3}$/.test(t)?t:void 0:void 0};function C(e){if(!e||"object"!=typeof e)return;const t={},i=Object.keys(e).slice(0,20);for(const n of i){const i=e[n];"boolean"==typeof i||"number"==typeof i?t[n]=i:"string"==typeof i&&(t[n]=i.slice(0,100))}return Object.keys(t).length>0?t:void 0}class R{constructor(e){t(this,"config"),t(this,"context"),t(this,"queue"),t(this,"transport"),t(this,"domTracker"),t(this,"sessionId"),t(this,"countryCode"),t(this,"currentSentiment"),t(this,"identify",(e,t)=>{this.context.userId=e,this.processEvent({event:"Identify",properties:{traits:t},standardEvent:"LOGIN",intent:"identity",confidence:1})}),t(this,"page",(e,t)=>{const i=this.context.getPayload().page;this.processEvent({event:e||i.title||"Unknown Page",properties:{path:i.path,referrer:i.referrer,title:i.title,...t},standardEvent:"PAGE_VIEW",intent:"navigation",confidence:1}),this.emitEngageEvent("pageview",t)}),t(this,"track",(e,t,i)=>{this.processEvent({event:e,properties:t||{},...i});const n={purchase:"purchase",PURCHASE:"purchase",signup:"signup",SIGNUP:"signup",register:"signup",REGISTER:"signup",add_to_cart:"add_to_cart",ADD_TO_CART:"add_to_cart",product_view:"product_view",VIEW_CONTENT:"product_view",session_start:"session_start",session_end:"session_end"},a=n[e]||n[(null==i?void 0:i.standardEvent)||""]||"custom";this.emitEngageEvent(a,t)}),t(this,"trackRevenue",(e,t,i)=>{const n=Math.max(0,(e=>{if("number"==typeof e)return Number.isFinite(e)?e:0;const t=e.trim().replace(/[^0-9.+-]/g,""),i=Number(t);return Number.isFinite(i)?i:0})(e)),a=S(null==t?void 0:t.currency)||S(null==t?void 0:t.currencyCode)||S(null==t?void 0:t.currencySymbol)||("string"==typeof e?S(e):void 0)||"USD";this.track("PURCHASE",{...t||{},value:n,amount:n,valuePaise:Math.round(100*n),amountPaise:Math.round(100*n),currency:a,currencyCode:a},{standardEvent:"PURCHASE",intent:"commerce",confidence:1,...i})}),t(this,"setSentiment",e=>{this.currentSentiment=e}),this.config=e;const i=e.apiKey,n=((e,t,i)=>{if("undefined"!=typeof window&&"localhost"!==window.location.hostname&&"127.0.0.1"!==window.location.hostname||!e)return i;try{const t=new URL(e);return t.hostname.endsWith("bluenath.com")||E.has(t.hostname)?(t.pathname="/api/v1/analytics/ingest",t.search="",t.hash="",t.toString()):i}catch{return i}})(e.apiHost,0,"https://engage-api.bluenath.com/api/v1/analytics/ingest");this.transport=new f({engage:n}),this.transport.setApiKey(i),this.context=new A({persistence:e.tracking.useCookies?"cookie":"local"}),this.queue=new p(this.transport),this.sessionId=function(){if("undefined"==typeof sessionStorage)return d();let e=sessionStorage.getItem(w);return e||(e=d(),sessionStorage.setItem(w,e)),e}(),this.countryCode=function(){try{const e=Intl.DateTimeFormat().resolvedOptions().timeZone;if(!e)return;return m[e]}catch{return}}(),this.domTracker=new v(this),e.tracking.autoTrack&&"undefined"!=typeof window&&(this.page(),this.domTracker.init())}emitEngageEvent(e,t){const i=this.context.getPayload().page,n={type:e,timestamp:(new Date).toISOString(),sessionId:this.sessionId,userId:this.context.getPayload().user.id||void 0,countryCode:this.countryCode,sentiment:this.currentSentiment,referrer:(i.referrer||"").slice(0,500),path:i.path||("undefined"!=typeof window?window.location.pathname:"/"),currency:S(null==t?void 0:t.currency)||S(null==t?void 0:t.currencyCode)||void 0,amount:"number"==typeof(null==t?void 0:t.amountPaise)?t.amountPaise:"number"==typeof(null==t?void 0:t.amount)?Math.round(100*t.amount):void 0,productId:"string"==typeof(null==t?void 0:t.productId)?t.productId:void 0,productName:"string"==typeof(null==t?void 0:t.productName)?t.productName:void 0,productCategory:"string"==typeof(null==t?void 0:t.productCategory)?t.productCategory:void 0,metadata:C(null==t?void 0:t.metadata)};this.queue.enqueueEngageEvent(n),this.currentSentiment&&(this.currentSentiment=void 0)}parseRef(e){if(!e)return{};const t=e.match(/^camp_([^_]+)_cr_([^_]+)$/);return t?{campaignId:t[1],creatorId:t[2]}:{}}processEvent(e){const t=this.context.getPayload(),i=e.properties.ref,n=("string"==typeof i?i:void 0)||new URLSearchParams(t.page.search||"").get("ref")||void 0,a=this.parseRef(n),r=e.properties.value??e.properties.amount??e.properties.valuePaise??e.properties.amountPaise,o=Number(r),s=e.properties.campaignId,c=e.properties.creatorId,u=e.properties.currency,h={event:e.event,properties:e.properties,standardEvent:e.standardEvent,intent:e.intent,confidence:e.confidence,rawLabel:e.rawLabel,timestamp:(new Date).toISOString(),messageId:d(),writeKey:this.config.apiKey||"",ref:n,campaignId:("string"==typeof s?s:void 0)||a.campaignId,creatorId:("string"==typeof c?c:void 0)||a.creatorId,value:Number.isFinite(o)?Math.round(o):void 0,valuePaise:Number.isFinite(o)?Math.round(100*o):void 0,currency:("string"==typeof u?u:void 0)||"USD",userId:t.user.id||void 0,anonymousId:t.user.anonymousId,context:t};this.config.debug,this.queue.enqueue(h)}}class I{constructor(e){t(this,"analytics"),t(this,"metrics",{}),this.analytics=e,"undefined"!=typeof window&&"PerformanceObserver"in window&&this.observe()}observe(){try{new PerformanceObserver(e=>{for(const t of e.getEntries()){const e=t;e.hadRecentInput||(this.metrics.cls=(this.metrics.cls||0)+e.value)}}).observe({type:"layout-shift",buffered:!0}),new PerformanceObserver(e=>{const t=e.getEntries(),i=t[t.length-1];this.metrics.lcp=i.renderTime||i.loadTime,this.logMetric("LCP",this.metrics.lcp)}).observe({type:"largest-contentful-paint",buffered:!0}),new PerformanceObserver(e=>{const t=e.getEntries()[0];t&&(this.metrics.fid=t.processingStart-t.startTime,this.logMetric("FID",this.metrics.fid))}).observe({type:"first-input",buffered:!0}),window.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState&&this.metrics.cls&&this.logMetric("CLS",this.metrics.cls)})}catch(e){}}logMetric(e,t){t<0||this.analytics.track(`Core Web Vital: ${e}`,{metric:e,value:Math.round(t)},{standardEvent:"PERFORMANCE",intent:"performance",confidence:1,rawLabel:`${e}: ${Math.round(t)}ms`})}}const _=n.createContext(null);let P=null;const M=e=>{if(!P){const t={...e,apiKey:e.apiKey||""};P=new R(t)}return P},T={init:e=>M({apiKey:e.apiKey,apiHost:e.apiHost,tracking:e.tracking||{useCookies:!0,fingerprint:!0,autoTrack:!0},debug:e.debug}),track(e,t){P&&P.track(e,t)},page(e,t){P&&P.page(e,t)},identify(e,t){P&&P.identify(e,t)},trackRevenue(e,t){P&&P.trackRevenue(e,t)},setSentiment(e){P&&P.setSentiment(e)}};exports.EngageProProvider=({children:e,...t})=>{const a=n.useRef(null),r=n.useRef(null);a.current||(a.current=new R(t),"undefined"!=typeof window&&new I(a.current));const o=a.current;return n.useEffect(()=>{if(!t.tracking.autoTrack)return;const e=e=>{const t=e.target.closest('button, a, input[type="submit"], [data-track], .clickable');if(t){const i=Date.now(),n=r.current;n&&n.el===t&&i-n.ts<500?(n.count++,n.ts=i,3===n.count&&(o.track("Rage Click detected",{element:t.tagName},{standardEvent:"RAGE_CLICK",intent:"frustration",confidence:1}),r.current=null)):r.current={el:t,count:1,ts:i};const a=(e=>{let t=(e.innerText||e.value||e.getAttribute("aria-label")||"").trim();if(!t){const i=e.querySelector("img");i&&i.alt&&(t=i.alt);const n=e.querySelector("title");n&&(t=n.textContent||"")}const i=t.slice(0,100),n=i.toLowerCase(),a=(e.id||"").toLowerCase(),r=e.href||"";return/add to (cart|bag)|buy now/.test(n)||a.includes("add-to-cart")?{standard:"ADD_TO_CART",intent:"commerce",label:i,confidence:.9}:/checkout|proceed/.test(n)||r.includes("/checkout")?{standard:"INITIATE_CHECKOUT",intent:"commerce",label:i,confidence:.9}:/place order|pay now/.test(n)||a.includes("place-order")?{standard:"PURCHASE",intent:"commerce",label:i,confidence:.95}:/cancel order/.test(n)||a.includes("cancel")?{standard:"ORDER_CANCEL",intent:"lifecycle",label:i,confidence:.85}:/refund|return/.test(n)||a.includes("refund")?{standard:"ORDER_REFUND",intent:"lifecycle",label:i,confidence:.85}:/track package|shipping/.test(n)?{standard:"TRACK_PACKAGE",intent:"lifecycle",label:i,confidence:.8}:/write review/.test(n)||n.includes("star")&&/^[1-5]/.test(n)?{standard:"RATE_PRODUCT",intent:"engagement",label:i,confidence:.8}:n.includes("search")||a.includes("search")?{standard:"SEARCH",intent:"search",label:i,confidence:.7}:{standard:"GENERIC",intent:"interaction",label:i,confidence:.5}})(t),s="A"===t.tagName;let c={};"commerce"===a.intent&&(c=(t=>{let i={};try{const n=document.querySelectorAll('script[type="application/ld+json"]');for(const t of Array.from(n))try{const e=JSON.parse(t.innerHTML),n=Array.isArray(e)?e:[e];for(const t of n)if("Product"===t["@type"]){if(t.name&&(i.productName=t.name),(t.sku||t.productID)&&(i.productId=t.sku||t.productID),t.offers){const e=Array.isArray(t.offers)?t.offers[0]:t.offers;e.price&&(i.amount=Number(e.price)),e.priceCurrency&&(i.currency=e.priceCurrency)}if(i.amount)return i}}catch(e){}if(!i.amount){const e=document.querySelector('meta[property="product:price:amount"]'),t=document.querySelector('meta[property="product:price:currency"]'),n=document.querySelector('meta[property="og:title"]');e&&(i.amount=Number(e.getAttribute("content"))),t&&(i.currency=t.getAttribute("content")),n&&(i.productName=n.getAttribute("content"))}if(!i.amount){const e=(t.innerText||"").match(/([$€£₹¥])\s*([0-9,]+\.[0-9]{2})/);if(e){const t=e[1],n=e[2].replace(/,/g,"");i.amount=Number(n);const a={$:"USD","€":"EUR","£":"GBP","₹":"INR","¥":"JPY"};i.currency=a[t]||"USD"}else{let e=t,n=0;for(;e&&n<3&&!i.amount;){const t=e.innerText||"";if(t.length<500){const e=t.match(/([$€£₹¥])\s*([0-9,]+\.[0-9]{2})/);if(e){const t=e[1],n=e[2].replace(/,/g,"");i.amount=Number(n);const a={$:"USD","€":"EUR","£":"GBP","₹":"INR","¥":"JPY"};i.currency=a[t]||"USD"}}e=e.parentElement,n++}}}}catch(n){}return i})(t)),o.track("Interaction",{element:t.tagName.toLowerCase(),id:t.id,destination:s?t.href:void 0,...c},{standardEvent:a.standard,intent:a.intent,rawLabel:a.label,confidence:a.confidence})}},i=e=>{const t=e.target;(e=>"password"===e.getAttribute("type")||"hidden"===e.getAttribute("type")||/password|cvc|card|cc-num|ssn|credit|hidden/i.test(e.getAttribute("name")||e.id||""))(t)||"focusin"!==e.type||t.dataset.tracked||(t.dataset.tracked="true",o.track("Form Start",{field:t.name||t.id},{standardEvent:"FORM_START",intent:"identity"}))},n=()=>{const e=new URLSearchParams(window.location.search);e.has("q")&&o.track("Search Query",{query:e.get("q")},{standardEvent:"SEARCH",intent:"search"}),requestAnimationFrame(()=>o.page())},a=history.pushState;return history.pushState=(...e)=>{a.apply(history,e),n()},window.addEventListener("popstate",n),window.addEventListener("click",e,!0),window.addEventListener("focusin",i,!0),n(),()=>{history.pushState=a,window.removeEventListener("popstate",n),window.removeEventListener("click",e,!0),window.removeEventListener("focusin",i,!0)}},[t.tracking.autoTrack]),i.jsx(_.Provider,{value:o,children:e})},exports.default=R,exports.engage=T,exports.init=M,exports.useAnalytics=()=>{const e=n.useContext(_);if(!e)throw new Error("useAnalytics must be used within EngageProProvider");return e};
package/dist/index.js CHANGED
@@ -512,7 +512,11 @@ class Transport {
512
512
  */
513
513
  beaconFlush(payload) {
514
514
  if (typeof navigator === "undefined" || !navigator.sendBeacon) return false;
515
- const endpoint = this.endpoints.engage;
515
+ let endpoint = this.endpoints.engage;
516
+ if (this.apiKey) {
517
+ const separator = endpoint.includes("?") ? "&" : "?";
518
+ endpoint = `${endpoint}${separator}apiKey=${encodeURIComponent(this.apiKey)}`;
519
+ }
516
520
  const blob = new Blob([payload], { type: "application/json" });
517
521
  return navigator.sendBeacon(endpoint, blob);
518
522
  }
@@ -936,7 +940,8 @@ const SYMBOL_TO_CURRENCY = {
936
940
  JPY: "JPY"
937
941
  };
938
942
  const resolveEndpoint = (apiHost, path, defaultUrl) => {
939
- if (!apiHost) return defaultUrl;
943
+ const isLocalhostEnv = typeof window === "undefined" || window.location.hostname === "localhost" || window.location.hostname === "127.0.0.1";
944
+ if (!isLocalhostEnv || !apiHost) return defaultUrl;
940
945
  try {
941
946
  const parsed = new URL(apiHost);
942
947
  const isAllowedHost = parsed.hostname.endsWith("bluenath.com") || ALLOWED_DEV_HOSTS.has(parsed.hostname);
@@ -64,6 +64,7 @@ export interface AnalyticsEvent {
64
64
  }
65
65
  export interface EngageConfig {
66
66
  apiKey: string;
67
+ /** @internal */
67
68
  apiHost?: string;
68
69
  tracking: {
69
70
  useCookies: boolean;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bluenath/engage",
3
- "version": "2.0.10",
3
+ "version": "2.0.11",
4
4
  "type": "module",
5
5
  "main": "./dist/index.cjs",
6
6
  "module": "./dist/index.js",