@dashgram/javascript 1.0.2 → 1.0.4

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,67 +1,56 @@
1
1
  # Dashgram JavaScript SDK
2
2
 
3
- Analytics SDK for **Telegram Mini Apps**. Automatically captures user interactions and sends events to the Dashgram backend.
3
+ Analytics SDK for **Telegram Mini Apps**. Automatically captures user interactions and sends events to the Dashgram.
4
4
 
5
- > ⚠️ **Important**: This SDK is designed exclusively for **Telegram Mini Apps** (WebApps).
6
- > It is **NOT** for Telegram bots. For bot analytics, use the [Python SDK](../sdk-python) or [Go SDK](../go-dashgram).
7
-
8
- ## Installation
9
-
10
- ```bash
11
- npm install @dashgram/javascript
12
- # or
13
- pnpm add @dashgram/javascript
14
- # or
15
- yarn add @dashgram/javascript
16
- ```
5
+ > [!NOTE]
6
+ > This SDK is for **Telegram Mini Apps** built with JavaScript/TypeScript. For Telegram bots or Mini Apps in other languages, see our [other SDKs](https://docs.dashgram.io/sdk).
17
7
 
18
8
  ## Quick Start
19
9
 
20
- ```typescript
21
- import DashgramMini from "@dashgram/javascript"
22
-
23
- // Initialize SDK
24
- DashgramMini.init({
25
- projectId: "your-project-id",
26
- trackLevel: 2, // 1 = core, 2 = interactions, 3 = deep analytics
27
- debug: true // Enable in development
28
- })
10
+ Place these scripts in your HTML before `</head>` closing tag:
29
11
 
30
- // Track custom events
31
- DashgramMini.track("purchase_completed", {
32
- product_id: "premium-plan",
33
- price: 9.99,
34
- currency: "USD"
35
- })
12
+ ```html
13
+ <script src="https://telegram.org/js/telegram-web-app.js"></script>
14
+ <script src="https://unpkg.com/@dashgram/javascript@latest/dist/dashgram.min.js"></script>
36
15
  ```
37
16
 
38
- ## Configuration
17
+ Initialize Dashgram inside `<body>`:
39
18
 
40
- ```typescript
41
- DashgramMini.init({
42
- projectId: "your-project-id", // Required
43
- trackLevel: 2, // Optional: 1, 2, or 3 (default: 1)
44
- debug: false, // Optional: enable console logs
45
- disabled: false, // Optional: disable tracking entirely
46
- batchSize: 10, // Optional: events per batch
47
- flushInterval: 5000 // Optional: flush interval in ms
48
- })
19
+ ```html
20
+ <script>
21
+ DashgramMini.init({
22
+ projectId: "your-project-id",
23
+ trackLevel: 2
24
+ })
25
+ </script>
49
26
  ```
50
27
 
28
+ **Configuration parameters:**
29
+
30
+ - `projectId` — Your project identifier from the [Dashgram dashboard](https://app.dashgram.io). Get it after creating a project.
31
+ - `trackLevel` — Controls which events are automatically captured. See [Track Levels](#track-levels) section below for details.
32
+
33
+ > [!TIP]
34
+ > **Looking for a complete example?** Check out [`examples/basic-usage.html`](examples/basic-usage.html) for a working HTML example with event tracking.
35
+
51
36
  ## Track Levels
52
37
 
53
- ### Level 1 Core (Default)
38
+ Choose how much data to collect. Higher levels capture more events but send more data.
54
39
 
55
- Minimal tracking:
40
+ ### Level 1 — Core
41
+
42
+ **Minimal tracking** — Basic app lifecycle events only.
56
43
 
57
44
  | Event | Description |
58
45
  | ----------- | --------------------------------- |
59
46
  | `app_open` | Mini App opened or became visible |
60
47
  | `app_close` | Mini App closed or hidden |
61
48
 
49
+ **Use when:** You only need basic usage metrics.
50
+
62
51
  ### Level 2 — Interactions
63
52
 
64
- Adds user interaction tracking:
53
+ **Standard tracking** — Level 1 + user interactions.
65
54
 
66
55
  | Event | Description |
67
56
  | --------------------- | -------------------------------- |
@@ -78,9 +67,11 @@ Adds user interaction tracking:
78
67
  | `js_error` | JavaScript errors |
79
68
  | `unhandled_rejection` | Unhandled Promise rejections |
80
69
 
70
+ **Use when:** You want standard web analytics (recommended for most apps).
71
+
81
72
  ### Level 3 — Deep Analytics
82
73
 
83
- Adds performance and Telegram-specific tracking:
74
+ **Comprehensive tracking** — Level 1 + 2 + performance metrics + all Telegram events.
84
75
 
85
76
  | Event | Description |
86
77
  | -------------------------------- | ------------------------------ |
@@ -101,100 +92,81 @@ Adds performance and Telegram-specific tracking:
101
92
  | `telegram_invoice_closed` | Invoice closed |
102
93
  | ...and all other Telegram events | |
103
94
 
104
- ## API
95
+ **Use when:** You need detailed performance monitoring and all Telegram WebApp events.
105
96
 
106
- ### `DashgramMini.init(config)`
97
+ ### All Configuration Options
107
98
 
108
- Initialize the SDK. Call once when your app loads.
99
+ | Option | Type | Default | Description |
100
+ | --------------- | ------------- | ------- | ---------------------------------------------------------- |
101
+ | `projectId` | `string` | — | **Required.** Your project ID from Dashgram dashboard |
102
+ | `trackLevel` | `1 \| 2 \| 3` | `2` | Event collection level (see [Track Levels](#track-levels)) |
103
+ | `debug` | `boolean` | `false` | Enable debug logging to console |
104
+ | `disabled` | `boolean` | `false` | Disable all tracking (useful for opt-out) |
105
+ | `batchSize` | `number` | `10` | Number of events to batch before sending |
106
+ | `flushInterval` | `number` | `5000` | Milliseconds between automatic flushes |
107
+ | `onError` | `function` | — | Callback for handling errors |
109
108
 
110
- ### `DashgramMini.track(event, properties)`
111
109
 
112
- Track a custom event.
110
+ ## API Reference
111
+
112
+ ### `DashgramMini.init(config)`
113
+
114
+ Initialize the SDK. Must be called once when your app loads.
113
115
 
114
116
  ```typescript
115
- DashgramMini.track("checkout_started", {
116
- cart_value: 49.99,
117
- item_count: 3
117
+ DashgramMini.init({
118
+ projectId: "your-project-id",
119
+ trackLevel: 2
118
120
  })
119
121
  ```
120
122
 
121
- ### `DashgramMini.setTrackLevel(level)`
123
+ ### `DashgramMini.track(event, properties)`
122
124
 
123
- Change the track level at runtime.
125
+ Track a custom event with optional properties.
124
126
 
125
127
  ```typescript
126
- DashgramMini.setTrackLevel(3) // Enable deep analytics
128
+ DashgramMini.track("purchase_completed", {
129
+ product_id: "premium-plan",
130
+ price: 9.99,
131
+ currency: "USD"
132
+ })
127
133
  ```
128
134
 
129
- ### `DashgramMini.flush()`
135
+ **Parameters:**
130
136
 
131
- Force send all pending events.
137
+ - `event` Event name (string)
138
+ - `properties` — Optional event properties (object)
132
139
 
133
- ```typescript
134
- await DashgramMini.flush()
135
- ```
136
-
137
- ### `DashgramMini.shutdown()`
140
+ ### `DashgramMini.flush()`
138
141
 
139
- Stop tracking and clean up.
142
+ Force send all pending events immediately. Returns a Promise.
140
143
 
141
144
  ```typescript
142
- DashgramMini.shutdown()
145
+ await DashgramMini.flush()
143
146
  ```
144
147
 
145
- ## User Identification
148
+ **Use cases:**
146
149
 
147
- User identification is handled **automatically** via Telegram's `initData`. The SDK sends the raw `initData` string with every event, allowing the backend to validate and extract user information securely.
150
+ - Before page unload
151
+ - After critical user actions
152
+ - When switching users
148
153
 
149
- You do **not** need to call any identify method.
150
-
151
- ## How It Works
152
-
153
- 1. SDK captures events based on `trackLevel`
154
- 2. Events are batched for efficiency
155
- 3. Each event includes:
156
- - `eventId`: UUID for deduplication
157
- - `type`: Event name
158
- - `initData`: Raw Telegram initData (for backend validation)
159
- - `properties`: Custom event data
160
- - `telemetry`: Platform, user agent, timezone, theme
161
- - `timestamp`: Unix milliseconds
162
- 4. Events are sent to `POST /v1/{projectId}/webapp/track`
163
-
164
- ## TypeScript Support
154
+ ### `DashgramMini.shutdown()`
165
155
 
166
- Full TypeScript support with exported types:
156
+ Stop tracking and clean up resources.
167
157
 
168
158
  ```typescript
169
- import type { DashgramConfig, WebAppEvent, EventProperties, TrackLevel } from "@dashgram/javascript"
159
+ DashgramMini.shutdown()
170
160
  ```
171
161
 
172
- ## Error Handling
173
-
174
- ```typescript
175
- import { DashgramMini, DashgramAPIError, NetworkError } from "@dashgram/javascript"
176
-
177
- DashgramMini.init({
178
- projectId: "your-project-id",
179
- onError: error => {
180
- if (error instanceof NetworkError) {
181
- console.log("Network issue:", error.message)
182
- } else if (error instanceof DashgramAPIError) {
183
- console.log("API error:", error.statusCode, error.details)
184
- }
185
- }
186
- })
187
- ```
162
+ ## Contributing
188
163
 
189
- ## Browser Support
164
+ Contributions are welcome! Please open issues or pull requests on the [GitHub repository](https://github.com/dashgram/dashgram-javascript).
190
165
 
191
- - Chrome 64+
192
- - Firefox 67+
193
- - Safari 12+
194
- - Edge 79+
166
+ ## License
195
167
 
196
- Works in all environments that support Telegram Mini Apps.
168
+ This project is licensed under the MIT License. See the LICENSE file for more information.
197
169
 
198
- ## License
170
+ ## Contact
199
171
 
200
- MIT
172
+ For questions or support, reach out to us at [team@dashgram.io](mailto:team@dashgram.io) or visit our [website](https://dashgram.io).
@@ -1,6 +1,6 @@
1
1
  import { DashgramConfigurationError } from "../errors";
2
2
  const DEFAULT_CONFIG = {
3
- trackLevel: 1,
3
+ trackLevel: 2,
4
4
  apiUrl: "https://api.dashgram.io/v1",
5
5
  batchSize: 10,
6
6
  flushInterval: 5000,
@@ -1,2 +1,2 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).DashgramMini={})}(this,function(e){"use strict";class t extends Error{constructor(e){super(e),this.name="DashgramError";const s=Error;"function"==typeof s.captureStackTrace&&s.captureStackTrace(this,t)}}class s extends t{constructor(e,t){super(`Dashgram API error (${e}): ${t}`),this.statusCode=e,this.details=t,this.name="DashgramAPIError";const i=Error;"function"==typeof i.captureStackTrace&&i.captureStackTrace(this,s)}}class i extends t{constructor(e){super(`Network error: ${e.message}`),this.originalError=e,this.name="NetworkError";const t=Error;"function"==typeof t.captureStackTrace&&t.captureStackTrace(this,i)}}class n extends t{constructor(e){super(e),this.name="DashgramConfigurationError";const t=Error;"function"==typeof t.captureStackTrace&&t.captureStackTrace(this,n)}}const r={trackLevel:1,apiUrl:"https://api.dashgram.io/v1",batchSize:10,flushInterval:5e3,debug:!1,disabled:!1};class o{constructor(e){this.config={...r,...e},this.validate()}validate(){if(!this.config.projectId)throw new n("projectId is required");if(![1,2,3].includes(this.config.trackLevel))throw new n("trackLevel must be 1, 2, or 3")}get(e){return this.config[e]}getOnError(){return this.config.onError}getTrackUrl(){return`${this.config.apiUrl.replace(/\/$/,"")}/${this.config.projectId}/webapp/track`}setTrackLevel(e){if(![1,2,3].includes(e))throw new n("trackLevel must be 1, 2, or 3");this.config.trackLevel=e}getTrackLevel(){return this.config.trackLevel}isDebug(){return this.config.debug}isDisabled(){return this.config.disabled}}function c(){if("undefined"==typeof window)return null;const e=window;return e.Telegram?.WebApp||null}function a(){const e=c();return e?.initData||""}function u(){const e=c();return e?.platform||"unknown"}function h(){const e=c();if(e?.colorScheme)return e.colorScheme;if(e?.themeParams?.bg_color){const t=e.themeParams.bg_color;try{const e=parseInt(t.slice(1),16);return.2126*(e>>16&255)+.7152*(e>>8&255)+.0722*(255&e)<128?"dark":"light"}catch{return}}}function d(e,t){const s=c();if(!s||!s.onEvent)return()=>{};try{const i=(s,i)=>{try{t(i)}catch(t){"undefined"!=typeof window&&window.__DASHGRAM_DEBUG__&&console.warn(`[Dashgram] Error in Telegram event callback for ${e}:`,t)}};return s.onEvent(e,i),()=>{try{s.offEvent&&s.offEvent(e,i)}catch{}}}catch{return()=>{}}}function l(){return"undefined"==typeof window?{platform:"unknown"}:{platform:u(),user_agent:navigator.userAgent,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone||void 0,theme:h()}}class p{constructor(){this.telemetry=l()}getTelemetry(){return{...this.telemetry}}updateTelemetry(){this.telemetry=l()}}function g(e,t){let s=null,i=0;return function(...n){const r=Date.now(),o=t-(r-i);o<=0||o>t?(s&&(clearTimeout(s),s=null),i=r,e.apply(this,n)):s||(s=setTimeout(()=>{i=Date.now(),s=null,e.apply(this,n)},o))}}function f(e){try{return JSON.stringify(e)}catch(e){return"{}"}}function b(e){if(e.id)return`#${e.id}`;if(e.className&&"string"==typeof e.className){const t=e.className.trim().split(/\s+/).slice(0,2).join(".");if(t)return`${e.tagName.toLowerCase()}.${t}`}return e.tagName.toLowerCase()}function m(e,t=50){const s=e.textContent?.trim()||"";return s.length>t?s.substring(0,t)+"...":s}class v{constructor(e){this.isOnline=!0,this.pendingRequests=new Set,this.config=e,this.setupOnlineListener()}setupOnlineListener(){"undefined"!=typeof window&&(window.addEventListener("online",()=>{this.isOnline=!0,this.log("Connection restored")}),window.addEventListener("offline",()=>{this.isOnline=!1,this.log("Connection lost")}),this.isOnline=navigator.onLine)}buildPayload(e){return{origin:("undefined"==typeof window?"":window.location.origin)||void 0,updates:e}}async send(e){if(0===e.length)return;if(this.config.isDisabled())return void this.log("Tracking disabled, skipping send");if(!this.isOnline)return void this.log("Offline, skipping send");const t=this.sendRequest(e);this.pendingRequests.add(t);try{await t}catch(e){this.logError("Failed to send events:",e);const t=this.config.getOnError();if(t)try{e instanceof s||e instanceof i?t(e):e instanceof Error&&t(new i(e))}catch(e){this.logError("Error in onError callback:",e)}}finally{this.pendingRequests.delete(t)}}async sendRequest(e){const t=this.config.getTrackUrl(),n=this.buildPayload(e);try{const i=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:f(n),keepalive:!0});if(!i.ok){let e=i.statusText;try{const t=await i.json();e=t.details||t.message||e}catch{}throw new s(i.status,e)}this.log(`Sent ${e.length} events successfully`)}catch(e){if(e instanceof s)throw e;if(e instanceof Error)throw new i(e);throw new i(new Error(String(e)))}}sendBeacon(e){if(0===e.length)return!0;if(this.config.isDisabled())return!0;if("undefined"==typeof navigator||!navigator.sendBeacon)return!1;const t=this.config.getTrackUrl(),s=this.buildPayload(e),i=new Blob([f(s)],{type:"application/json"}),n=navigator.sendBeacon(t,i);return this.log(`sendBeacon ${n?"succeeded":"failed"} for ${e.length} events`),n}async flush(){await Promise.all(Array.from(this.pendingRequests))}log(...e){this.config.isDebug()&&console.log("[Dashgram Transport]",...e)}logError(...e){this.config.isDebug()&&console.error("[Dashgram Transport]",...e)}}class _{constructor(e=100){this.queue=[],this.maxSize=e}enqueue(e){this.queue.push(e),this.queue.length>this.maxSize&&this.queue.shift()}flush(){const e=[...this.queue];return this.queue=[],e}peek(){return[...this.queue]}size(){return this.queue.length}isEmpty(){return 0===this.queue.length}clear(){this.queue=[]}}class k{constructor(e,t){this.flushTimer=null,this.isStarted=!1,this.config=e,this.transport=t,this.queue=new _(200)}start(){this.isStarted||(this.isStarted=!0,this.scheduleFlush(),this.setupPageUnloadHandler())}stop(){this.isStarted=!1,this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null)}addEvent(e){this.queue.enqueue(e);const t=this.config.get("batchSize");this.queue.size()>=t&&this.flush()}scheduleFlush(){this.flushTimer&&clearTimeout(this.flushTimer);const e=this.config.get("flushInterval");this.flushTimer=setTimeout(()=>{this.flush(),this.isStarted&&this.scheduleFlush()},e)}flush(){const e=this.queue.flush();e.length>0&&this.transport.send(e)}async flushAsync(){const e=this.queue.flush();e.length>0&&await this.transport.send(e),await this.transport.flush()}setupPageUnloadHandler(){if("undefined"==typeof window)return;const e=()=>{const e=this.queue.flush();e.length>0&&this.transport.sendBeacon(e)};window.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState&&e()}),window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e)}}class w{constructor(e,t,s){this.isActive=!1,this.config=e,this.trackCallback=t,this.level=s}start(){if(this.isActive)return;this.config.getTrackLevel()>=this.level&&(this.isActive=!0,this.setup(),this.log(`Started (level ${this.level})`))}stop(){this.isActive&&(this.isActive=!1,this.teardown(),this.log("Stopped"))}track(e,t={}){this.isActive&&this.trackCallback(e,t)}log(...e){this.config.isDebug()&&console.log(`[Dashgram ${this.constructor.name}]`,...e)}}class y extends w{constructor(e,t){super(e,t,1),this.unsubscribers=[],this.hasTrackedAppOpen=!1}setup(){"undefined"!=typeof window&&(this.trackAppOpen(),this.setupVisibilityTracking(),this.setupUnloadTracking())}teardown(){this.unsubscribers.forEach(e=>e()),this.unsubscribers=[]}trackAppOpen(){this.hasTrackedAppOpen||(this.track("app_open",{referrer:document.referrer||"direct"}),this.hasTrackedAppOpen=!0)}setupVisibilityTracking(){const e=()=>{"hidden"===document.visibilityState?this.track("app_close",{visibility_state:"hidden"}):"visible"===document.visibilityState&&this.track("app_open",{visibility_state:"visible"})};document.addEventListener("visibilitychange",e),this.unsubscribers.push(()=>{document.removeEventListener("visibilitychange",e)})}setupUnloadTracking(){const e=()=>{this.track("app_close",{reason:"unload"})};window.addEventListener("pagehide",e),this.unsubscribers.push(()=>{window.removeEventListener("pagehide",e)}),window.addEventListener("beforeunload",e),this.unsubscribers.push(()=>{window.removeEventListener("beforeunload",e)})}}class T extends w{constructor(e,t){super(e,t,2),this.unsubscribers=[],this.lastPath="",this.inputValues=new Map}setup(){"undefined"!=typeof window&&(this.trackScreenView(),this.setupHistoryTracking(),this.setupClickTracking(),this.setupFormTracking(),this.setupInputTracking(),this.setupClipboardTracking(),this.setupSelectionTracking(),this.setupErrorTracking())}teardown(){this.unsubscribers.forEach(e=>e()),this.unsubscribers=[]}trackScreenView(){const e="undefined"==typeof window?"":window.location.pathname;e!==this.lastPath&&(this.lastPath=e,this.track("screen_view",{path:e,url:"undefined"==typeof window?"":window.location.href,title:"undefined"==typeof document?"":document.title||"",referrer:document.referrer||"direct"}))}setupHistoryTracking(){const e=history.pushState,t=history.replaceState,s=()=>{this.trackScreenView()};history.pushState=function(...t){e.apply(history,t),s()},history.replaceState=function(...e){t.apply(history,e),s()},window.addEventListener("popstate",s),this.unsubscribers.push(()=>{history.pushState=e,history.replaceState=t,window.removeEventListener("popstate",s)})}setupClickTracking(){const e=e=>{const t=e.target;if(!t)return;const s=t.closest('button, [role="button"], a');if(s){if("a"===s.tagName.toLowerCase()){const e=s,t=e.href,i=!!t&&this.isExternalLink(t);this.track("link_click",{element:b(s),text:m(s),href:t||void 0,target:e.target||void 0,is_external:i,is_download:e.hasAttribute("download")})}else this.track("button_click",{element:b(s),text:m(s)})}};document.addEventListener("click",e,{capture:!0}),this.unsubscribers.push(()=>{document.removeEventListener("click",e,{capture:!0})})}isExternalLink(e){try{return new URL(e,window.location.href).origin!==window.location.origin}catch{return!1}}setupFormTracking(){const e=e=>{const t=e.target;t&&this.track("form_submit",{form_id:t.id||void 0,form_name:t.name||void 0,form_action:t.action||void 0,form_method:t.method||void 0})};document.addEventListener("submit",e,{capture:!0}),this.unsubscribers.push(()=>{document.removeEventListener("submit",e,{capture:!0})})}setupInputTracking(){const e=g(e=>{const t=e.target;if(!t)return;const s=t.tagName.toLowerCase();if(["input","textarea","select"].includes(s)){const e=t;this.inputValues.set(t,e.value||""),this.track("input_focus",{element:b(e),input_type:e.type||s,input_name:e.name||void 0,input_id:e.id||void 0})}},1e3),t=e=>{const t=e.target;if(!t)return;const s=t.tagName.toLowerCase();if(["input","textarea","select"].includes(s)){const e=t,i=this.inputValues.get(t),n=e.value||"";void 0!==i&&i!==n&&this.track("input_change",{element:b(e),input_type:e.type||s,input_name:e.name||void 0,input_id:e.id||void 0,had_value:i.length>0,has_value:n.length>0}),this.inputValues.delete(t)}};document.addEventListener("focus",e,{capture:!0}),document.addEventListener("blur",t,{capture:!0}),this.unsubscribers.push(()=>{document.removeEventListener("focus",e,{capture:!0}),document.removeEventListener("blur",t,{capture:!0}),this.inputValues.clear()})}setupClipboardTracking(){const e=e=>{const t=window.getSelection(),s=t?.toString()||"";this.track("copy",{text_length:s.length,has_selection:s.length>0})},t=e=>{const t=window.getSelection(),s=t?.toString()||"";this.track("cut",{text_length:s.length,has_selection:s.length>0})},s=e=>{const t=e.clipboardData?.getData("text")||"",s=e.target;this.track("paste",{text_length:t.length,target_element:s?b(s):void 0})};document.addEventListener("copy",e),document.addEventListener("cut",t),document.addEventListener("paste",s),this.unsubscribers.push(()=>{document.removeEventListener("copy",e),document.removeEventListener("cut",t),document.removeEventListener("paste",s)})}setupSelectionTracking(){let e;const t=()=>{clearTimeout(e),e=setTimeout(()=>{const e=window.getSelection(),t=e?.toString()||"";t.length>0&&this.track("text_select",{text_length:t.length})},500)};document.addEventListener("selectionchange",t),this.unsubscribers.push(()=>{document.removeEventListener("selectionchange",t),clearTimeout(e)})}setupErrorTracking(){const e=e=>{this.track("js_error",{message:e.message,filename:e.filename,lineno:e.lineno,colno:e.colno,stack:e.error?.stack})};window.addEventListener("error",e),this.unsubscribers.push(()=>{window.removeEventListener("error",e)});const t=e=>{this.track("unhandled_rejection",{reason:String(e.reason),promise:String(e.promise)})};window.addEventListener("unhandledrejection",t),this.unsubscribers.push(()=>{window.removeEventListener("unhandledrejection",t)})}}class E extends w{constructor(e,t){super(e,t,3),this.unsubscribers=[],this.observers=[],this.clickTracker=new Map,this.maxScrollDepth=0,this.trackedMedia=new WeakSet}setup(){"undefined"!=typeof window&&(this.setupScrollTracking(),this.setupVisibilityTracking(),this.setupRageClickTracking(),this.setupLongTaskTracking(),this.setupWebVitals(),this.setupNetworkTracking(),this.setupOrientationTracking(),this.setupMediaTracking(),this.setupTelegramTracking())}teardown(){this.unsubscribers.forEach(e=>e()),this.unsubscribers=[],this.observers.forEach(e=>e.disconnect()),this.observers=[],this.clickTracker.clear()}getScrollDepth(){const e=window.innerHeight,t=document.documentElement.scrollHeight,s=window.pageYOffset||document.documentElement.scrollTop;if(t<=e)return 100;const i=s/(t-e)*100;return Math.min(Math.round(i),100)}setupScrollTracking(){const e=g(()=>{const e=this.getScrollDepth();if(e>this.maxScrollDepth){this.maxScrollDepth=e;const t=[25,50,75,100].find(t=>e>=t&&this.maxScrollDepth-e<t);t&&this.track("scroll_depth",{depth:t,max_depth:this.maxScrollDepth})}},500);window.addEventListener("scroll",e,{passive:!0}),this.unsubscribers.push(()=>{window.removeEventListener("scroll",e)})}setupVisibilityTracking(){if(!("IntersectionObserver"in window))return;const e=new IntersectionObserver(t=>{t.forEach(t=>{if(t.isIntersecting){const s=t.target,i=s.getAttribute("data-track-visible");i&&(this.track("element_visible",{element:i,intersection_ratio:t.intersectionRatio}),e.unobserve(s))}})},{threshold:.5});document.querySelectorAll("[data-track-visible]").forEach(t=>{e.observe(t)}),this.observers.push(e);const t=new MutationObserver(t=>{t.forEach(t=>{t.addedNodes.forEach(t=>{t instanceof Element&&(t.hasAttribute("data-track-visible")&&e.observe(t),t.querySelectorAll("[data-track-visible]").forEach(t=>{e.observe(t)}))})})});t.observe(document.body,{childList:!0,subtree:!0}),this.unsubscribers.push(()=>{t.disconnect()})}setupRageClickTracking(){const e=e=>{const t=e.target;if(!t)return;const s=this.clickTracker.get(t);if(s)s.count++,clearTimeout(s.timer),s.count>=5?(this.track("rage_click",{element:t.tagName.toLowerCase(),click_count:s.count}),this.clickTracker.delete(t)):s.timer=setTimeout(()=>{this.clickTracker.delete(t)},2e3);else{const e=setTimeout(()=>{this.clickTracker.delete(t)},2e3);this.clickTracker.set(t,{count:1,timer:e})}};document.addEventListener("click",e),this.unsubscribers.push(()=>{document.removeEventListener("click",e)})}setupLongTaskTracking(){if("PerformanceObserver"in window)try{const e=new PerformanceObserver(e=>{for(const t of e.getEntries())t.duration>50&&this.track("long_task",{duration:Math.round(t.duration),start_time:Math.round(t.startTime)})});e.observe({entryTypes:["longtask"]}),this.observers.push(e)}catch(e){this.log("Long task tracking not supported")}}setupWebVitals(){if(!("PerformanceObserver"in window))return;try{const e=new PerformanceObserver(e=>{const t=e.getEntries(),s=t[t.length-1];this.track("web_vital_lcp",{value:Math.round(s.renderTime||s.loadTime),element:s.element?.tagName.toLowerCase()})});e.observe({entryTypes:["largest-contentful-paint"]}),this.observers.push(e)}catch(e){this.log("LCP tracking not supported")}try{const e=new PerformanceObserver(e=>{e.getEntries().forEach(e=>{this.track("web_vital_fid",{value:Math.round(e.processingStart-e.startTime),event_type:e.name})})});e.observe({entryTypes:["first-input"]}),this.observers.push(e)}catch(e){this.log("FID tracking not supported")}let e=0;try{const t=new PerformanceObserver(t=>{t.getEntries().forEach(t=>{t.hadRecentInput||(e+=t.value)})});t.observe({entryTypes:["layout-shift"]}),this.observers.push(t);const s=()=>{e>0&&this.track("web_vital_cls",{value:Math.round(1e3*e)/1e3})};window.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState&&s()}),this.unsubscribers.push(()=>{s()})}catch(e){this.log("CLS tracking not supported")}}setupNetworkTracking(){const e=()=>{this.track("network_status",{status:"online",effective_type:navigator.connection?.effectiveType,downlink:navigator.connection?.downlink,rtt:navigator.connection?.rtt})},t=()=>{this.track("network_status",{status:"offline"})};window.addEventListener("online",e),window.addEventListener("offline",t),this.unsubscribers.push(()=>{window.removeEventListener("online",e),window.removeEventListener("offline",t)});const s=navigator.connection;if(s){const e=()=>{this.track("network_change",{effective_type:s.effectiveType,downlink:s.downlink,rtt:s.rtt,save_data:s.saveData})};s.addEventListener("change",e),this.unsubscribers.push(()=>{s.removeEventListener("change",e)})}}setupOrientationTracking(){const e=()=>{const e=screen.orientation?.type||(window.innerWidth>window.innerHeight?"landscape":"portrait");this.track("orientation_change",{orientation:e,angle:screen.orientation?.angle,width:window.innerWidth,height:window.innerHeight})};screen.orientation?(screen.orientation.addEventListener("change",e),this.unsubscribers.push(()=>{screen.orientation.removeEventListener("change",e)})):(window.addEventListener("orientationchange",e),this.unsubscribers.push(()=>{window.removeEventListener("orientationchange",e)}))}setupMediaTracking(){const e=e=>{const t=e.target;if(!t||this.trackedMedia.has(t))return;const s=t.tagName.toLowerCase(),i=e.type,n={media_type:s,src:t.currentSrc||t.src,duration:isFinite(t.duration)?Math.round(t.duration):void 0,current_time:Math.round(t.currentTime),muted:t.muted,volume:Math.round(100*t.volume)};"play"===i?this.track("media_play",n):"pause"===i?this.track("media_pause",{...n,percent_played:t.duration?Math.round(t.currentTime/t.duration*100):0}):"ended"===i?this.track("media_ended",{...n,completed:!0}):"error"===i&&this.track("media_error",{media_type:s,src:t.currentSrc||t.src,error:t.error?.message||"unknown"})},t=t=>{this.trackedMedia.has(t)||(this.trackedMedia.add(t),t.addEventListener("play",e),t.addEventListener("pause",e),t.addEventListener("ended",e),t.addEventListener("error",e))};document.querySelectorAll("video, audio").forEach(e=>{t(e)});const s=new MutationObserver(e=>{e.forEach(e=>{e.addedNodes.forEach(e=>{e instanceof HTMLMediaElement&&t(e),e instanceof Element&&e.querySelectorAll("video, audio").forEach(e=>{t(e)})})})});s.observe(document.body,{childList:!0,subtree:!0}),this.observers.push(s)}setupTelegramTracking(){const e=window.Telegram?.WebApp,t=(e,t)=>{this.track(`telegram_${e}`,t||{})},s=d("themeChanged",()=>{t("theme_changed",{color_scheme:e?.colorScheme,theme_params:e?.themeParams})});this.unsubscribers.push(s);const i=d("viewportChanged",s=>{t("viewport_changed",{is_state_stable:s?.isStateStable,is_expanded:e?.isExpanded,viewport_height:e?.viewportHeight,viewport_stable_height:e?.viewportStableHeight})});this.unsubscribers.push(i);const n=d("safeAreaChanged",()=>{t("safe_area_changed",{safe_area:e?.safeAreaInset})});this.unsubscribers.push(n);const r=d("contentSafeAreaChanged",()=>{t("content_safe_area_changed",{content_safe_area:e?.contentSafeAreaInset})});this.unsubscribers.push(r);const o=d("backButtonClicked",()=>{t("back_button_clicked",{})});this.unsubscribers.push(o);const c=d("mainButtonClicked",()=>{t("main_button_clicked",{button_text:e?.MainButton?.text})});this.unsubscribers.push(c);const a=d("invoiceClosed",e=>{t("invoice_closed",{url:e?.url,status:e?.status})});this.unsubscribers.push(a);const u=d("popupClosed",e=>{t("popup_closed",{button_id:e?.button_id})});this.unsubscribers.push(u);const h=d("qrTextReceived",e=>{t("qr_text_received",{data:e?.data})});this.unsubscribers.push(h);const l=d("scanQrPopupClosed",()=>{t("scan_qr_popup_closed",{})});this.unsubscribers.push(l);const p=d("clipboardTextReceived",e=>{t("clipboard_text_received",{data:e?.data})});this.unsubscribers.push(p);const g=d("writeAccessRequested",e=>{t("write_access_requested",{status:e?.status})});this.unsubscribers.push(g);const f=d("fileDownloadRequested",e=>{t("file_download_requested",{status:e?.status})});this.unsubscribers.push(f);const b=d("customMethodInvoked",e=>{t("custom_method_invoked",{req_id:e?.req_id,result:e?.result,error:e?.error})});this.unsubscribers.push(b);const m=d("fullscreenChanged",e=>{t("fullscreen_changed",{is_fullscreen:e?.isFullscreen})});this.unsubscribers.push(m);const v=d("fullscreenFailed",e=>{t("fullscreen_failed",{error:e?.error})});this.unsubscribers.push(v);const _=d("homeScreenAdded",()=>{t("home_screen_added",{})});this.unsubscribers.push(_);const k=d("homeScreenChecked",e=>{t("home_screen_checked",{status:e?.status})});this.unsubscribers.push(k);const w=d("preparedMessageSent",()=>{t("prepared_message_sent",{})});this.unsubscribers.push(w);const y=d("preparedMessageFailed",e=>{t("prepared_message_failed",{error:e?.error})});this.unsubscribers.push(y);const T=d("emojiStatusSet",()=>{t("emoji_status_set",{})});this.unsubscribers.push(T);const E=d("emojiStatusFailed",e=>{t("emoji_status_failed",{error:e?.error})});this.unsubscribers.push(E);const L=d("emojiStatusAccessRequested",e=>{t("emoji_status_access_requested",{status:e?.status})});this.unsubscribers.push(L);const S=d("settingsButtonClicked",()=>{t("settings_button_clicked",{})});this.unsubscribers.push(S);const x=d("secondaryButtonClicked",()=>{t("secondary_button_clicked",{})});this.unsubscribers.push(x);const q=d("shareMessageSent",()=>{t("share_message_sent",{})});this.unsubscribers.push(q);const A=d("shareMessageFailed",e=>{t("share_message_failed",{error:e?.error})});this.unsubscribers.push(A);const D=d("locationManagerUpdated",()=>{const s=e?.LocationManager;t("location_manager_updated",{is_inited:s?.isInited,is_location_available:s?.isLocationAvailable,is_access_requested:s?.isAccessRequested,is_access_granted:s?.isAccessGranted})});this.unsubscribers.push(D);const I=d("locationRequested",e=>{t("location_requested",{available:!1!==e?.available,latitude:e?.latitude,longitude:e?.longitude,altitude:e?.altitude,course:e?.course,speed:e?.speed,horizontal_accuracy:e?.horizontal_accuracy,vertical_accuracy:e?.vertical_accuracy,course_accuracy:e?.course_accuracy,speed_accuracy:e?.speed_accuracy})});this.unsubscribers.push(I);const P=d("accelerometerStarted",()=>{t("accelerometer_started",{})});this.unsubscribers.push(P);const C=d("accelerometerStopped",()=>{t("accelerometer_stopped",{})});this.unsubscribers.push(C);const M=d("accelerometerChanged",()=>{const s=e?.Accelerometer;t("accelerometer_changed",{x:s?.x,y:s?.y,z:s?.z})});this.unsubscribers.push(M);const O=d("accelerometerFailed",e=>{t("accelerometer_failed",{error:e?.error})});this.unsubscribers.push(O);const z=d("deviceOrientationStarted",()=>{t("device_orientation_started",{})});this.unsubscribers.push(z);const R=d("deviceOrientationStopped",()=>{t("device_orientation_stopped",{})});this.unsubscribers.push(R);const j=d("deviceOrientationChanged",()=>{const s=e?.DeviceOrientation;t("device_orientation_changed",{absolute:s?.absolute,alpha:s?.alpha,beta:s?.beta,gamma:s?.gamma})});this.unsubscribers.push(j);const F=d("deviceOrientationFailed",e=>{t("device_orientation_failed",{error:e?.error})});this.unsubscribers.push(F);const N=d("gyroscopeStarted",()=>{t("gyroscope_started",{})});this.unsubscribers.push(N);const U=d("gyroscopeStopped",()=>{t("gyroscope_stopped",{})});this.unsubscribers.push(U);const B=d("gyroscopeChanged",()=>{const s=e?.Gyroscope;t("gyroscope_changed",{x:s?.x,y:s?.y,z:s?.z})});this.unsubscribers.push(B);const $=d("gyroscopeFailed",e=>{t("gyroscope_failed",{error:e?.error})});this.unsubscribers.push($);const V=d("contactRequested",e=>{t("contact_requested",{status:e?.status})});this.unsubscribers.push(V);const H=d("activated",()=>{t("activated",{})});this.unsubscribers.push(H);const W=d("deactivated",()=>{t("deactivated",{})});this.unsubscribers.push(W);const G=d("biometricManagerUpdated",()=>{const s=e?.BiometricManager;t("biometric_manager_updated",{is_inited:s?.isInited,is_biometric_available:s?.isBiometricAvailable,biometric_type:s?.biometricType,is_access_requested:s?.isAccessRequested,is_access_granted:s?.isAccessGranted,is_biometric_token_saved:s?.isBiometricTokenSaved,device_id:s?.deviceId})});this.unsubscribers.push(G);const Q=d("biometricAuthRequested",e=>{t("biometric_auth_requested",{is_authenticated:e?.isAuthenticated,biometric_token:e?.biometricToken})});this.unsubscribers.push(Q);const K=d("biometricTokenUpdated",e=>{t("biometric_token_updated",{is_updated:e?.isUpdated})});this.unsubscribers.push(K),this.patchWebAppMethods(e,t)}patchWebAppMethods(e,t){if(e&&!e.openLink?._dashgramPatched){if(e.openLink&&"function"==typeof e.openLink){const s=e.openLink.bind(e),i=(e,i)=>(t("open_link",{url:e,options:i}),s(e,i));i._dashgramPatched=!0,e.openLink=i}if(e.openTelegramLink&&"function"==typeof e.openTelegramLink){const s=e.openTelegramLink.bind(e),i=e=>(t("open_telegram_link",{url:e}),s(e));i._dashgramPatched=!0,e.openTelegramLink=i}if(e.switchInlineQuery&&"function"==typeof e.switchInlineQuery){const s=e.switchInlineQuery.bind(e),i=(e,i)=>(t("switch_inline_query",{query:e,choose_chat_types:i}),s(e,i));i._dashgramPatched=!0,e.switchInlineQuery=i}if(e.shareToStory&&"function"==typeof e.shareToStory){const s=e.shareToStory.bind(e),i=(e,i)=>(t("share_story",{media_url:e,params:i}),s(e,i));i._dashgramPatched=!0,e.shareToStory=i}if(e.close&&"function"==typeof e.close){const s=e.close.bind(e),i=e=>(t("webapp_close",{return_back:e?.return_back}),s(e));i._dashgramPatched=!0,e.close=i}if(e.exitFullscreen&&"function"==typeof e.exitFullscreen){const s=e.exitFullscreen.bind(e),i=()=>(t("webapp_exit_fullscreen",{}),s());i._dashgramPatched=!0,e.exitFullscreen=i}if(e.openInvoice&&"function"==typeof e.openInvoice){const s=e.openInvoice.bind(e),i=(e,i)=>(t("open_invoice",{slug:e}),s(e,i));i._dashgramPatched=!0,e.openInvoice=i}if(e.requestAccess&&"function"==typeof e.requestAccess){const s=e.requestAccess.bind(e),i=(e,i)=>(t("request_access",{access_type:e}),s(e,i));i._dashgramPatched=!0,e.requestAccess=i}if(e.requestContact&&"function"==typeof e.requestContact){const s=e.requestContact.bind(e),i=e=>(t("request_contact",{}),s(e));i._dashgramPatched=!0,e.requestContact=i}if(e.requestPhone&&"function"==typeof e.requestPhone){const s=e.requestPhone.bind(e),i=e=>(t("request_phone",{}),s(e));i._dashgramPatched=!0,e.requestPhone=i}if(e.requestLocation&&"function"==typeof e.requestLocation){const s=e.requestLocation.bind(e),i=e=>(t("request_location",{}),s(e));i._dashgramPatched=!0,e.requestLocation=i}if(e.checkLocation&&"function"==typeof e.checkLocation){const s=e.checkLocation.bind(e),i=e=>(t("check_location",{}),s(e));i._dashgramPatched=!0,e.checkLocation=i}}}}const L=new class{constructor(){this.config=null,this.context=null,this.transport=null,this.batchProcessor=null,this.trackers=[],this.isInitialized=!1}init(e){if(this.isInitialized)e.debug&&console.warn("Dashgram: Already initialized");else if("undefined"!=typeof window&&"undefined"!=typeof document)try{this.config=new o(e),"undefined"!=typeof window&&(window.__DASHGRAM_DEBUG__=this.config.isDebug()),this.context=new p,this.transport=new v(this.config),this.batchProcessor=new k(this.config,this.transport),this.setupTrackers(),this.batchProcessor.start(),this.isInitialized=!0,this.log("Initialized successfully",{projectId:this.config.get("projectId"),trackLevel:this.config.getTrackLevel()})}catch(e){throw console.error("Dashgram: Initialization failed",e),e}else e.debug&&console.warn("Dashgram: Not running in browser environment")}setupTrackers(){if(!this.config)return;const e=(e,t)=>{this.trackAuto(e,t)},t=new y(this.config,e);this.trackers.push(t),t.start();const s=new T(this.config,e);this.trackers.push(s),s.start();const i=new E(this.config,e);this.trackers.push(i),i.start()}track(e,t={}){this.ensureInitialized();const s=this.buildEvent(e,t,"manual");this.batchProcessor.addEvent(s),this.log("Tracked event",{event:e,properties:t})}trackAuto(e,t={}){if(!this.isInitialized)return;const s=this.buildEvent(e,t,"auto");this.batchProcessor.addEvent(s),this.log("Auto-tracked event",{event:e,properties:t})}buildEvent(e,t,s){return this.ensureInitialized(),{eventId:"undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}),type:e,initData:a(),properties:Object.keys(t).length>0?t:void 0,telemetry:this.context.getTelemetry(),source:s,level:this.config.getTrackLevel(),timestamp:Date.now()}}setTrackLevel(e){this.ensureInitialized();const t=this.config.getTrackLevel();this.config.setTrackLevel(e),this.trackers.forEach(e=>{e.stop(),e.start()}),this.log("Track level changed",{from:t,to:e})}async flush(){this.ensureInitialized(),await this.batchProcessor.flushAsync(),this.log("Flushed all events")}shutdown(){this.isInitialized&&(this.trackers.forEach(e=>e.stop()),this.trackers=[],this.batchProcessor.flush(),this.batchProcessor.stop(),this.isInitialized=!1,this.log("Shutdown complete"))}ensureInitialized(){if(!this.isInitialized)throw new Error("Dashgram: SDK not initialized. Call init() first.")}log(...e){this.config?.isDebug()&&console.log("[Dashgram SDK]",...e)}};e.DashgramAPIError=s,e.DashgramConfigurationError=n,e.DashgramError=t,e.DashgramMini=L,e.NetworkError=i,e.default=L,Object.defineProperty(e,"__esModule",{value:!0})});
1
+ var DashgramMini=function(){"use strict";class e extends Error{constructor(t){super(t),this.name="DashgramError";const s=Error;"function"==typeof s.captureStackTrace&&s.captureStackTrace(this,e)}}class t extends e{constructor(e,s){super(`Dashgram API error (${e}): ${s}`),this.statusCode=e,this.details=s,this.name="DashgramAPIError";const i=Error;"function"==typeof i.captureStackTrace&&i.captureStackTrace(this,t)}}class s extends e{constructor(e){super(`Network error: ${e.message}`),this.originalError=e,this.name="NetworkError";const t=Error;"function"==typeof t.captureStackTrace&&t.captureStackTrace(this,s)}}class i extends e{constructor(e){super(e),this.name="DashgramConfigurationError";const t=Error;"function"==typeof t.captureStackTrace&&t.captureStackTrace(this,i)}}const n={trackLevel:2,apiUrl:"https://api.dashgram.io/v1",batchSize:10,flushInterval:5e3,debug:!1,disabled:!1};class r{constructor(e){this.config={...n,...e},this.validate()}validate(){if(!this.config.projectId)throw new i("projectId is required");if(![1,2,3].includes(this.config.trackLevel))throw new i("trackLevel must be 1, 2, or 3")}get(e){return this.config[e]}getOnError(){return this.config.onError}getTrackUrl(){return`${this.config.apiUrl.replace(/\/$/,"")}/${this.config.projectId}/webapp/track`}setTrackLevel(e){if(![1,2,3].includes(e))throw new i("trackLevel must be 1, 2, or 3");this.config.trackLevel=e}getTrackLevel(){return this.config.trackLevel}isDebug(){return this.config.debug}isDisabled(){return this.config.disabled}}function o(){if("undefined"==typeof window)return null;const e=window;return e.Telegram?.WebApp||null}function c(){const e=o();if(e?.initData)return e.initData;if("undefined"!=typeof window)try{const e=new URLSearchParams(window.location.search).get("tgWebAppData");if(e)return decodeURIComponent(e)}catch{}return""}function a(){const e=o();return e?.platform||"unknown"}function u(){const e=o();if(e?.colorScheme)return e.colorScheme;if(e?.themeParams?.bg_color){const t=e.themeParams.bg_color;try{const e=parseInt(t.slice(1),16);return.2126*(e>>16&255)+.7152*(e>>8&255)+.0722*(255&e)<128?"dark":"light"}catch{return}}}function h(e,t){const s=o();if(!s||!s.onEvent)return()=>{};try{const i=(s,i)=>{try{t(i)}catch(t){"undefined"!=typeof window&&window.__DASHGRAM_DEBUG__&&console.warn(`[Dashgram] Error in Telegram event callback for ${e}:`,t)}};return s.onEvent(e,i),()=>{try{s.offEvent&&s.offEvent(e,i)}catch{}}}catch{return()=>{}}}function d(){return"undefined"==typeof window?{platform:"unknown"}:{platform:a(),user_agent:navigator.userAgent,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone||void 0,theme:u()}}class l{constructor(){this.telemetry=d()}getTelemetry(){return{...this.telemetry}}updateTelemetry(){this.telemetry=d()}}function p(e,t){let s=null,i=0;return function(...n){const r=Date.now(),o=t-(r-i);o<=0||o>t?(s&&(clearTimeout(s),s=null),i=r,e.apply(this,n)):s||(s=setTimeout(()=>{i=Date.now(),s=null,e.apply(this,n)},o))}}function g(e){try{return JSON.stringify(e)}catch(e){return"{}"}}function b(e){if(e.id)return`#${e.id}`;if(e.className&&"string"==typeof e.className){const t=e.className.trim().split(/\s+/).slice(0,2).join(".");if(t)return`${e.tagName.toLowerCase()}.${t}`}return e.tagName.toLowerCase()}function f(e,t=50){const s=e.textContent?.trim()||"";return s.length>t?s.substring(0,t)+"...":s}class m{constructor(e){this.isOnline=!0,this.pendingRequests=new Set,this.config=e,this.setupOnlineListener()}setupOnlineListener(){"undefined"!=typeof window&&(window.addEventListener("online",()=>{this.isOnline=!0,this.log("Connection restored")}),window.addEventListener("offline",()=>{this.isOnline=!1,this.log("Connection lost")}),this.isOnline=navigator.onLine)}buildPayload(e){return{origin:"@dashgram/javascript@1.0.4",updates:e}}async send(e){if(0===e.length)return;if(this.config.isDisabled())return void this.log("Tracking disabled, skipping send");if(!this.isOnline)return void this.log("Offline, skipping send");const i=this.sendRequest(e);this.pendingRequests.add(i);try{await i}catch(e){this.logError("Failed to send events:",e);const i=this.config.getOnError();if(i)try{e instanceof t||e instanceof s?i(e):e instanceof Error&&i(new s(e))}catch(e){this.logError("Error in onError callback:",e)}}finally{this.pendingRequests.delete(i)}}async sendRequest(e){const i=this.config.getTrackUrl(),n=this.buildPayload(e);try{const s=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:g(n),keepalive:!0});if(!s.ok){let e=s.statusText;try{const t=await s.json();e=t.details||t.message||e}catch{}throw new t(s.status,e)}this.log(`Sent ${e.length} events successfully`)}catch(e){if(e instanceof t)throw e;if(e instanceof Error)throw new s(e);throw new s(new Error(String(e)))}}sendBeacon(e){if(0===e.length)return!0;if(this.config.isDisabled())return!0;if("undefined"==typeof navigator||!navigator.sendBeacon)return!1;const t=this.config.getTrackUrl(),s=this.buildPayload(e),i=new Blob([g(s)],{type:"application/json"}),n=navigator.sendBeacon(t,i);return this.log(`sendBeacon ${n?"succeeded":"failed"} for ${e.length} events`),n}async flush(){await Promise.all(Array.from(this.pendingRequests))}log(...e){this.config.isDebug()&&console.log("[Dashgram Transport]",...e)}logError(...e){this.config.isDebug()&&console.error("[Dashgram Transport]",...e)}}class v{constructor(e=100){this.queue=[],this.maxSize=e}enqueue(e){this.queue.push(e),this.queue.length>this.maxSize&&this.queue.shift()}flush(){const e=[...this.queue];return this.queue=[],e}peek(){return[...this.queue]}size(){return this.queue.length}isEmpty(){return 0===this.queue.length}clear(){this.queue=[]}}class _{constructor(e,t){this.flushTimer=null,this.isStarted=!1,this.config=e,this.transport=t,this.queue=new v(200)}start(){this.isStarted||(this.isStarted=!0,this.scheduleFlush(),this.setupPageUnloadHandler())}stop(){this.isStarted=!1,this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null)}addEvent(e){this.queue.enqueue(e);const t=this.config.get("batchSize");this.queue.size()>=t&&this.flush()}scheduleFlush(){this.flushTimer&&clearTimeout(this.flushTimer);const e=this.config.get("flushInterval");this.flushTimer=setTimeout(()=>{this.flush(),this.isStarted&&this.scheduleFlush()},e)}flush(){const e=this.queue.flush();e.length>0&&this.transport.send(e)}async flushAsync(){const e=this.queue.flush();e.length>0&&await this.transport.send(e),await this.transport.flush()}setupPageUnloadHandler(){if("undefined"==typeof window)return;const e=()=>{const e=this.queue.flush();e.length>0&&this.transport.sendBeacon(e)};window.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState&&e()}),window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e)}}class k{constructor(e,t,s){this.isActive=!1,this.config=e,this.trackCallback=t,this.level=s}start(){if(this.isActive)return;this.config.getTrackLevel()>=this.level&&(this.isActive=!0,this.setup(),this.log(`Started (level ${this.level})`))}stop(){this.isActive&&(this.isActive=!1,this.teardown(),this.log("Stopped"))}track(e,t={}){this.isActive&&this.trackCallback(e,t)}log(...e){this.config.isDebug()&&console.log(`[Dashgram ${this.constructor.name}]`,...e)}}class w extends k{constructor(e,t){super(e,t,1),this.unsubscribers=[],this.hasTrackedAppOpen=!1}setup(){"undefined"!=typeof window&&(this.trackAppOpen(),this.setupVisibilityTracking(),this.setupUnloadTracking())}teardown(){this.unsubscribers.forEach(e=>e()),this.unsubscribers=[]}trackAppOpen(){this.hasTrackedAppOpen||(this.track("app_open",{referrer:document.referrer||"direct"}),this.hasTrackedAppOpen=!0)}setupVisibilityTracking(){const e=()=>{"hidden"===document.visibilityState?this.track("app_close",{visibility_state:"hidden"}):"visible"===document.visibilityState&&this.track("app_open",{visibility_state:"visible"})};document.addEventListener("visibilitychange",e),this.unsubscribers.push(()=>{document.removeEventListener("visibilitychange",e)})}setupUnloadTracking(){const e=()=>{this.track("app_close",{reason:"unload"})};window.addEventListener("pagehide",e),this.unsubscribers.push(()=>{window.removeEventListener("pagehide",e)}),window.addEventListener("beforeunload",e),this.unsubscribers.push(()=>{window.removeEventListener("beforeunload",e)})}}class y extends k{constructor(e,t){super(e,t,2),this.unsubscribers=[],this.lastPath="",this.inputValues=new Map}setup(){"undefined"!=typeof window&&(this.trackScreenView(),this.setupHistoryTracking(),this.setupClickTracking(),this.setupFormTracking(),this.setupInputTracking(),this.setupClipboardTracking(),this.setupSelectionTracking(),this.setupErrorTracking())}teardown(){this.unsubscribers.forEach(e=>e()),this.unsubscribers=[]}trackScreenView(){const e="undefined"==typeof window?"":window.location.pathname;e!==this.lastPath&&(this.lastPath=e,this.track("screen_view",{path:e,url:"undefined"==typeof window?"":window.location.href,title:"undefined"==typeof document?"":document.title||"",referrer:document.referrer||"direct"}))}setupHistoryTracking(){const e=history.pushState,t=history.replaceState,s=()=>{this.trackScreenView()};history.pushState=function(...t){e.apply(history,t),s()},history.replaceState=function(...e){t.apply(history,e),s()},window.addEventListener("popstate",s),this.unsubscribers.push(()=>{history.pushState=e,history.replaceState=t,window.removeEventListener("popstate",s)})}setupClickTracking(){const e=e=>{const t=e.target;if(!t)return;const s=t.closest('button, [role="button"], a');if(s){if("a"===s.tagName.toLowerCase()){const e=s,t=e.href,i=!!t&&this.isExternalLink(t);this.track("link_click",{element:b(s),text:f(s),href:t||void 0,target:e.target||void 0,is_external:i,is_download:e.hasAttribute("download")})}else this.track("button_click",{element:b(s),text:f(s)})}};document.addEventListener("click",e,{capture:!0}),this.unsubscribers.push(()=>{document.removeEventListener("click",e,{capture:!0})})}isExternalLink(e){try{return new URL(e,window.location.href).origin!==window.location.origin}catch{return!1}}setupFormTracking(){const e=e=>{const t=e.target;t&&this.track("form_submit",{form_id:t.id||void 0,form_name:t.name||void 0,form_action:t.action||void 0,form_method:t.method||void 0})};document.addEventListener("submit",e,{capture:!0}),this.unsubscribers.push(()=>{document.removeEventListener("submit",e,{capture:!0})})}setupInputTracking(){const e=p(e=>{const t=e.target;if(!t)return;const s=t.tagName.toLowerCase();if(["input","textarea","select"].includes(s)){const e=t;this.inputValues.set(t,e.value||""),this.track("input_focus",{element:b(e),input_type:e.type||s,input_name:e.name||void 0,input_id:e.id||void 0})}},1e3),t=e=>{const t=e.target;if(!t)return;const s=t.tagName.toLowerCase();if(["input","textarea","select"].includes(s)){const e=t,i=this.inputValues.get(t),n=e.value||"";void 0!==i&&i!==n&&this.track("input_change",{element:b(e),input_type:e.type||s,input_name:e.name||void 0,input_id:e.id||void 0,had_value:i.length>0,has_value:n.length>0}),this.inputValues.delete(t)}};document.addEventListener("focus",e,{capture:!0}),document.addEventListener("blur",t,{capture:!0}),this.unsubscribers.push(()=>{document.removeEventListener("focus",e,{capture:!0}),document.removeEventListener("blur",t,{capture:!0}),this.inputValues.clear()})}setupClipboardTracking(){const e=e=>{const t=window.getSelection(),s=t?.toString()||"";this.track("copy",{text_length:s.length,has_selection:s.length>0})},t=e=>{const t=window.getSelection(),s=t?.toString()||"";this.track("cut",{text_length:s.length,has_selection:s.length>0})},s=e=>{const t=e.clipboardData?.getData("text")||"",s=e.target;this.track("paste",{text_length:t.length,target_element:s?b(s):void 0})};document.addEventListener("copy",e),document.addEventListener("cut",t),document.addEventListener("paste",s),this.unsubscribers.push(()=>{document.removeEventListener("copy",e),document.removeEventListener("cut",t),document.removeEventListener("paste",s)})}setupSelectionTracking(){let e;const t=()=>{clearTimeout(e),e=setTimeout(()=>{const e=window.getSelection(),t=e?.toString()||"";t.length>0&&this.track("text_select",{text_length:t.length})},500)};document.addEventListener("selectionchange",t),this.unsubscribers.push(()=>{document.removeEventListener("selectionchange",t),clearTimeout(e)})}setupErrorTracking(){const e=e=>{this.track("js_error",{message:e.message,filename:e.filename,lineno:e.lineno,colno:e.colno,stack:e.error?.stack})};window.addEventListener("error",e),this.unsubscribers.push(()=>{window.removeEventListener("error",e)});const t=e=>{this.track("unhandled_rejection",{reason:String(e.reason),promise:String(e.promise)})};window.addEventListener("unhandledrejection",t),this.unsubscribers.push(()=>{window.removeEventListener("unhandledrejection",t)})}}class T extends k{constructor(e,t){super(e,t,3),this.unsubscribers=[],this.observers=[],this.clickTracker=new Map,this.maxScrollDepth=0,this.trackedMedia=new WeakSet}setup(){"undefined"!=typeof window&&(this.setupScrollTracking(),this.setupVisibilityTracking(),this.setupRageClickTracking(),this.setupLongTaskTracking(),this.setupWebVitals(),this.setupNetworkTracking(),this.setupOrientationTracking(),this.setupMediaTracking(),this.setupTelegramTracking())}teardown(){this.unsubscribers.forEach(e=>e()),this.unsubscribers=[],this.observers.forEach(e=>e.disconnect()),this.observers=[],this.clickTracker.clear()}getScrollDepth(){const e=window.innerHeight,t=document.documentElement.scrollHeight,s=window.pageYOffset||document.documentElement.scrollTop;if(t<=e)return 100;const i=s/(t-e)*100;return Math.min(Math.round(i),100)}setupScrollTracking(){const e=p(()=>{const e=this.getScrollDepth();if(e>this.maxScrollDepth){this.maxScrollDepth=e;const t=[25,50,75,100].find(t=>e>=t&&this.maxScrollDepth-e<t);t&&this.track("scroll_depth",{depth:t,max_depth:this.maxScrollDepth})}},500);window.addEventListener("scroll",e,{passive:!0}),this.unsubscribers.push(()=>{window.removeEventListener("scroll",e)})}setupVisibilityTracking(){if(!("IntersectionObserver"in window))return;const e=new IntersectionObserver(t=>{t.forEach(t=>{if(t.isIntersecting){const s=t.target,i=s.getAttribute("data-track-visible");i&&(this.track("element_visible",{element:i,intersection_ratio:t.intersectionRatio}),e.unobserve(s))}})},{threshold:.5});document.querySelectorAll("[data-track-visible]").forEach(t=>{e.observe(t)}),this.observers.push(e);const t=new MutationObserver(t=>{t.forEach(t=>{t.addedNodes.forEach(t=>{t instanceof Element&&(t.hasAttribute("data-track-visible")&&e.observe(t),t.querySelectorAll("[data-track-visible]").forEach(t=>{e.observe(t)}))})})});t.observe(document.body,{childList:!0,subtree:!0}),this.unsubscribers.push(()=>{t.disconnect()})}setupRageClickTracking(){const e=e=>{const t=e.target;if(!t)return;const s=this.clickTracker.get(t);if(s)s.count++,clearTimeout(s.timer),s.count>=5?(this.track("rage_click",{element:t.tagName.toLowerCase(),click_count:s.count}),this.clickTracker.delete(t)):s.timer=setTimeout(()=>{this.clickTracker.delete(t)},2e3);else{const e=setTimeout(()=>{this.clickTracker.delete(t)},2e3);this.clickTracker.set(t,{count:1,timer:e})}};document.addEventListener("click",e),this.unsubscribers.push(()=>{document.removeEventListener("click",e)})}setupLongTaskTracking(){if("PerformanceObserver"in window)try{const e=new PerformanceObserver(e=>{for(const t of e.getEntries())t.duration>50&&this.track("long_task",{duration:Math.round(t.duration),start_time:Math.round(t.startTime)})});e.observe({entryTypes:["longtask"]}),this.observers.push(e)}catch(e){this.log("Long task tracking not supported")}}setupWebVitals(){if(!("PerformanceObserver"in window))return;try{const e=new PerformanceObserver(e=>{const t=e.getEntries(),s=t[t.length-1];this.track("web_vital_lcp",{value:Math.round(s.renderTime||s.loadTime),element:s.element?.tagName.toLowerCase()})});e.observe({entryTypes:["largest-contentful-paint"]}),this.observers.push(e)}catch(e){this.log("LCP tracking not supported")}try{const e=new PerformanceObserver(e=>{e.getEntries().forEach(e=>{this.track("web_vital_fid",{value:Math.round(e.processingStart-e.startTime),event_type:e.name})})});e.observe({entryTypes:["first-input"]}),this.observers.push(e)}catch(e){this.log("FID tracking not supported")}let e=0;try{const t=new PerformanceObserver(t=>{t.getEntries().forEach(t=>{t.hadRecentInput||(e+=t.value)})});t.observe({entryTypes:["layout-shift"]}),this.observers.push(t);const s=()=>{e>0&&this.track("web_vital_cls",{value:Math.round(1e3*e)/1e3})};window.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState&&s()}),this.unsubscribers.push(()=>{s()})}catch(e){this.log("CLS tracking not supported")}}setupNetworkTracking(){const e=()=>{this.track("network_status",{status:"online",effective_type:navigator.connection?.effectiveType,downlink:navigator.connection?.downlink,rtt:navigator.connection?.rtt})},t=()=>{this.track("network_status",{status:"offline"})};window.addEventListener("online",e),window.addEventListener("offline",t),this.unsubscribers.push(()=>{window.removeEventListener("online",e),window.removeEventListener("offline",t)});const s=navigator.connection;if(s){const e=()=>{this.track("network_change",{effective_type:s.effectiveType,downlink:s.downlink,rtt:s.rtt,save_data:s.saveData})};s.addEventListener("change",e),this.unsubscribers.push(()=>{s.removeEventListener("change",e)})}}setupOrientationTracking(){const e=()=>{const e=screen.orientation?.type||(window.innerWidth>window.innerHeight?"landscape":"portrait");this.track("orientation_change",{orientation:e,angle:screen.orientation?.angle,width:window.innerWidth,height:window.innerHeight})};screen.orientation?(screen.orientation.addEventListener("change",e),this.unsubscribers.push(()=>{screen.orientation.removeEventListener("change",e)})):(window.addEventListener("orientationchange",e),this.unsubscribers.push(()=>{window.removeEventListener("orientationchange",e)}))}setupMediaTracking(){const e=e=>{const t=e.target;if(!t||this.trackedMedia.has(t))return;const s=t.tagName.toLowerCase(),i=e.type,n={media_type:s,src:t.currentSrc||t.src,duration:isFinite(t.duration)?Math.round(t.duration):void 0,current_time:Math.round(t.currentTime),muted:t.muted,volume:Math.round(100*t.volume)};"play"===i?this.track("media_play",n):"pause"===i?this.track("media_pause",{...n,percent_played:t.duration?Math.round(t.currentTime/t.duration*100):0}):"ended"===i?this.track("media_ended",{...n,completed:!0}):"error"===i&&this.track("media_error",{media_type:s,src:t.currentSrc||t.src,error:t.error?.message||"unknown"})},t=t=>{this.trackedMedia.has(t)||(this.trackedMedia.add(t),t.addEventListener("play",e),t.addEventListener("pause",e),t.addEventListener("ended",e),t.addEventListener("error",e))};document.querySelectorAll("video, audio").forEach(e=>{t(e)});const s=new MutationObserver(e=>{e.forEach(e=>{e.addedNodes.forEach(e=>{e instanceof HTMLMediaElement&&t(e),e instanceof Element&&e.querySelectorAll("video, audio").forEach(e=>{t(e)})})})});s.observe(document.body,{childList:!0,subtree:!0}),this.observers.push(s)}setupTelegramTracking(){const e=window.Telegram?.WebApp,t=(e,t)=>{this.track(`telegram_${e}`,t||{})},s=h("themeChanged",()=>{t("theme_changed",{color_scheme:e?.colorScheme,theme_params:e?.themeParams})});this.unsubscribers.push(s);const i=h("viewportChanged",s=>{t("viewport_changed",{is_state_stable:s?.isStateStable,is_expanded:e?.isExpanded,viewport_height:e?.viewportHeight,viewport_stable_height:e?.viewportStableHeight})});this.unsubscribers.push(i);const n=h("safeAreaChanged",()=>{t("safe_area_changed",{safe_area:e?.safeAreaInset})});this.unsubscribers.push(n);const r=h("contentSafeAreaChanged",()=>{t("content_safe_area_changed",{content_safe_area:e?.contentSafeAreaInset})});this.unsubscribers.push(r);const o=h("backButtonClicked",()=>{t("back_button_clicked",{})});this.unsubscribers.push(o);const c=h("mainButtonClicked",()=>{t("main_button_clicked",{button_text:e?.MainButton?.text})});this.unsubscribers.push(c);const a=h("invoiceClosed",e=>{t("invoice_closed",{url:e?.url,status:e?.status})});this.unsubscribers.push(a);const u=h("popupClosed",e=>{t("popup_closed",{button_id:e?.button_id})});this.unsubscribers.push(u);const d=h("qrTextReceived",e=>{t("qr_text_received",{data:e?.data})});this.unsubscribers.push(d);const l=h("scanQrPopupClosed",()=>{t("scan_qr_popup_closed",{})});this.unsubscribers.push(l);const p=h("clipboardTextReceived",e=>{t("clipboard_text_received",{data:e?.data})});this.unsubscribers.push(p);const g=h("writeAccessRequested",e=>{t("write_access_requested",{status:e?.status})});this.unsubscribers.push(g);const b=h("fileDownloadRequested",e=>{t("file_download_requested",{status:e?.status})});this.unsubscribers.push(b);const f=h("customMethodInvoked",e=>{t("custom_method_invoked",{req_id:e?.req_id,result:e?.result,error:e?.error})});this.unsubscribers.push(f);const m=h("fullscreenChanged",e=>{t("fullscreen_changed",{is_fullscreen:e?.isFullscreen})});this.unsubscribers.push(m);const v=h("fullscreenFailed",e=>{t("fullscreen_failed",{error:e?.error})});this.unsubscribers.push(v);const _=h("homeScreenAdded",()=>{t("home_screen_added",{})});this.unsubscribers.push(_);const k=h("homeScreenChecked",e=>{t("home_screen_checked",{status:e?.status})});this.unsubscribers.push(k);const w=h("preparedMessageSent",()=>{t("prepared_message_sent",{})});this.unsubscribers.push(w);const y=h("preparedMessageFailed",e=>{t("prepared_message_failed",{error:e?.error})});this.unsubscribers.push(y);const T=h("emojiStatusSet",()=>{t("emoji_status_set",{})});this.unsubscribers.push(T);const E=h("emojiStatusFailed",e=>{t("emoji_status_failed",{error:e?.error})});this.unsubscribers.push(E);const L=h("emojiStatusAccessRequested",e=>{t("emoji_status_access_requested",{status:e?.status})});this.unsubscribers.push(L);const S=h("settingsButtonClicked",()=>{t("settings_button_clicked",{})});this.unsubscribers.push(S);const x=h("secondaryButtonClicked",()=>{t("secondary_button_clicked",{})});this.unsubscribers.push(x);const q=h("shareMessageSent",()=>{t("share_message_sent",{})});this.unsubscribers.push(q);const A=h("shareMessageFailed",e=>{t("share_message_failed",{error:e?.error})});this.unsubscribers.push(A);const D=h("locationManagerUpdated",()=>{const s=e?.LocationManager;t("location_manager_updated",{is_inited:s?.isInited,is_location_available:s?.isLocationAvailable,is_access_requested:s?.isAccessRequested,is_access_granted:s?.isAccessGranted})});this.unsubscribers.push(D);const I=h("locationRequested",e=>{t("location_requested",{available:!1!==e?.available,latitude:e?.latitude,longitude:e?.longitude,altitude:e?.altitude,course:e?.course,speed:e?.speed,horizontal_accuracy:e?.horizontal_accuracy,vertical_accuracy:e?.vertical_accuracy,course_accuracy:e?.course_accuracy,speed_accuracy:e?.speed_accuracy})});this.unsubscribers.push(I);const P=h("accelerometerStarted",()=>{t("accelerometer_started",{})});this.unsubscribers.push(P);const C=h("accelerometerStopped",()=>{t("accelerometer_stopped",{})});this.unsubscribers.push(C);const M=h("accelerometerChanged",()=>{const s=e?.Accelerometer;t("accelerometer_changed",{x:s?.x,y:s?.y,z:s?.z})});this.unsubscribers.push(M);const O=h("accelerometerFailed",e=>{t("accelerometer_failed",{error:e?.error})});this.unsubscribers.push(O);const z=h("deviceOrientationStarted",()=>{t("device_orientation_started",{})});this.unsubscribers.push(z);const R=h("deviceOrientationStopped",()=>{t("device_orientation_stopped",{})});this.unsubscribers.push(R);const F=h("deviceOrientationChanged",()=>{const s=e?.DeviceOrientation;t("device_orientation_changed",{absolute:s?.absolute,alpha:s?.alpha,beta:s?.beta,gamma:s?.gamma})});this.unsubscribers.push(F);const U=h("deviceOrientationFailed",e=>{t("device_orientation_failed",{error:e?.error})});this.unsubscribers.push(U);const j=h("gyroscopeStarted",()=>{t("gyroscope_started",{})});this.unsubscribers.push(j);const N=h("gyroscopeStopped",()=>{t("gyroscope_stopped",{})});this.unsubscribers.push(N);const B=h("gyroscopeChanged",()=>{const s=e?.Gyroscope;t("gyroscope_changed",{x:s?.x,y:s?.y,z:s?.z})});this.unsubscribers.push(B);const $=h("gyroscopeFailed",e=>{t("gyroscope_failed",{error:e?.error})});this.unsubscribers.push($);const V=h("contactRequested",e=>{t("contact_requested",{status:e?.status})});this.unsubscribers.push(V);const H=h("activated",()=>{t("activated",{})});this.unsubscribers.push(H);const W=h("deactivated",()=>{t("deactivated",{})});this.unsubscribers.push(W);const G=h("biometricManagerUpdated",()=>{const s=e?.BiometricManager;t("biometric_manager_updated",{is_inited:s?.isInited,is_biometric_available:s?.isBiometricAvailable,biometric_type:s?.biometricType,is_access_requested:s?.isAccessRequested,is_access_granted:s?.isAccessGranted,is_biometric_token_saved:s?.isBiometricTokenSaved,device_id:s?.deviceId})});this.unsubscribers.push(G);const Q=h("biometricAuthRequested",e=>{t("biometric_auth_requested",{is_authenticated:e?.isAuthenticated,biometric_token:e?.biometricToken})});this.unsubscribers.push(Q);const K=h("biometricTokenUpdated",e=>{t("biometric_token_updated",{is_updated:e?.isUpdated})});this.unsubscribers.push(K),this.patchWebAppMethods(e,t)}patchWebAppMethods(e,t){if(e&&!e.openLink?._dashgramPatched){if(e.openLink&&"function"==typeof e.openLink){const s=e.openLink.bind(e),i=(e,i)=>(t("open_link",{url:e,options:i}),s(e,i));i._dashgramPatched=!0,e.openLink=i}if(e.openTelegramLink&&"function"==typeof e.openTelegramLink){const s=e.openTelegramLink.bind(e),i=e=>(t("open_telegram_link",{url:e}),s(e));i._dashgramPatched=!0,e.openTelegramLink=i}if(e.switchInlineQuery&&"function"==typeof e.switchInlineQuery){const s=e.switchInlineQuery.bind(e),i=(e,i)=>(t("switch_inline_query",{query:e,choose_chat_types:i}),s(e,i));i._dashgramPatched=!0,e.switchInlineQuery=i}if(e.shareToStory&&"function"==typeof e.shareToStory){const s=e.shareToStory.bind(e),i=(e,i)=>(t("share_story",{media_url:e,params:i}),s(e,i));i._dashgramPatched=!0,e.shareToStory=i}if(e.close&&"function"==typeof e.close){const s=e.close.bind(e),i=e=>(t("webapp_close",{return_back:e?.return_back}),s(e));i._dashgramPatched=!0,e.close=i}if(e.exitFullscreen&&"function"==typeof e.exitFullscreen){const s=e.exitFullscreen.bind(e),i=()=>(t("webapp_exit_fullscreen",{}),s());i._dashgramPatched=!0,e.exitFullscreen=i}if(e.openInvoice&&"function"==typeof e.openInvoice){const s=e.openInvoice.bind(e),i=(e,i)=>(t("open_invoice",{slug:e}),s(e,i));i._dashgramPatched=!0,e.openInvoice=i}if(e.requestAccess&&"function"==typeof e.requestAccess){const s=e.requestAccess.bind(e),i=(e,i)=>(t("request_access",{access_type:e}),s(e,i));i._dashgramPatched=!0,e.requestAccess=i}if(e.requestContact&&"function"==typeof e.requestContact){const s=e.requestContact.bind(e),i=e=>(t("request_contact",{}),s(e));i._dashgramPatched=!0,e.requestContact=i}if(e.requestPhone&&"function"==typeof e.requestPhone){const s=e.requestPhone.bind(e),i=e=>(t("request_phone",{}),s(e));i._dashgramPatched=!0,e.requestPhone=i}if(e.requestLocation&&"function"==typeof e.requestLocation){const s=e.requestLocation.bind(e),i=e=>(t("request_location",{}),s(e));i._dashgramPatched=!0,e.requestLocation=i}if(e.checkLocation&&"function"==typeof e.checkLocation){const s=e.checkLocation.bind(e),i=e=>(t("check_location",{}),s(e));i._dashgramPatched=!0,e.checkLocation=i}}}}return new class{constructor(){this.config=null,this.context=null,this.transport=null,this.batchProcessor=null,this.trackers=[],this.isInitialized=!1}init(e){if(this.isInitialized)e.debug&&console.warn("Dashgram: Already initialized");else if("undefined"!=typeof window&&"undefined"!=typeof document)try{this.config=new r(e),"undefined"!=typeof window&&(window.__DASHGRAM_DEBUG__=this.config.isDebug()),this.context=new l,this.transport=new m(this.config),this.batchProcessor=new _(this.config,this.transport),this.setupTrackers(),this.batchProcessor.start(),this.isInitialized=!0,this.log("Initialized successfully",{projectId:this.config.get("projectId"),trackLevel:this.config.getTrackLevel()})}catch(e){throw console.error("Dashgram: Initialization failed",e),e}else e.debug&&console.warn("Dashgram: Not running in browser environment")}setupTrackers(){if(!this.config)return;const e=(e,t)=>{this.trackAuto(e,t)},t=new w(this.config,e);this.trackers.push(t),t.start();const s=new y(this.config,e);this.trackers.push(s),s.start();const i=new T(this.config,e);this.trackers.push(i),i.start()}track(e,t={}){this.ensureInitialized();const s=this.buildEvent(e,t,"manual");this.batchProcessor.addEvent(s),this.log("Tracked event",{event:e,properties:t})}trackAuto(e,t={}){if(!this.isInitialized)return;const s=this.buildEvent(e,t,"auto");this.batchProcessor.addEvent(s),this.log("Auto-tracked event",{event:e,properties:t})}buildEvent(e,t,s){return this.ensureInitialized(),{eventId:"undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}),type:e,initData:c(),properties:Object.keys(t).length>0?t:void 0,telemetry:this.context.getTelemetry(),source:s,level:this.config.getTrackLevel(),timestamp:Date.now()}}setTrackLevel(e){this.ensureInitialized();const t=this.config.getTrackLevel();this.config.setTrackLevel(e),this.trackers.forEach(e=>{e.stop(),e.start()}),this.log("Track level changed",{from:t,to:e})}async flush(){this.ensureInitialized(),await this.batchProcessor.flushAsync(),this.log("Flushed all events")}shutdown(){this.isInitialized&&(this.trackers.forEach(e=>e.stop()),this.trackers=[],this.batchProcessor.flush(),this.batchProcessor.stop(),this.isInitialized=!1,this.log("Shutdown complete"))}ensureInitialized(){if(!this.isInitialized)throw new Error("Dashgram: SDK not initialized. Call init() first.")}log(...e){this.config?.isDebug()&&console.log("[Dashgram SDK]",...e)}}}();
2
2
  //# sourceMappingURL=dashgram.min.js.map