@dashgram/javascript 1.0.3 → 1.0.5
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 +91 -103
- package/dist/core/config.js +1 -1
- package/dist/dashgram.min.js +1 -1
- package/dist/dashgram.min.js.map +1 -1
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/transport/transport.js +2 -2
- package/dist/types/index.d.ts +4 -4
- package/dist/utils/device.d.ts +1 -0
- package/dist/utils/device.d.ts.map +1 -1
- package/dist/utils/device.js +4 -0
- package/dist/utils/telegram.d.ts.map +1 -1
- package/dist/utils/telegram.js +15 -1
- package/dist/version.d.ts +4 -0
- package/dist/version.d.ts.map +1 -0
- package/dist/version.js +3 -0
- package/package.json +4 -3
package/README.md
CHANGED
|
@@ -1,67 +1,73 @@
|
|
|
1
1
|
# Dashgram JavaScript SDK
|
|
2
2
|
|
|
3
|
-
Analytics SDK for **Telegram Mini Apps**. Automatically captures user interactions and sends events to the Dashgram
|
|
3
|
+
Analytics SDK for **Telegram Mini Apps**. Automatically captures user interactions and sends events to the Dashgram.
|
|
4
4
|
|
|
5
|
-
>
|
|
6
|
-
>
|
|
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).
|
|
7
7
|
|
|
8
|
-
##
|
|
8
|
+
## Quick Start
|
|
9
|
+
|
|
10
|
+
### 1. Add scripts to your HTML
|
|
9
11
|
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
yarn add @dashgram/javascript
|
|
12
|
+
Place these scripts in your HTML before `</head>` closing tag:
|
|
13
|
+
|
|
14
|
+
```html
|
|
15
|
+
<script src="https://telegram.org/js/telegram-web-app.js"></script>
|
|
16
|
+
<script src="https://unpkg.com/@dashgram/javascript@latest/dist/dashgram.min.js"></script>
|
|
16
17
|
```
|
|
17
18
|
|
|
18
|
-
|
|
19
|
+
### 2. Initialize Dashgram
|
|
19
20
|
|
|
20
|
-
|
|
21
|
-
import DashgramMini from "@dashgram/javascript"
|
|
21
|
+
Initialize Dashgram inside `<body>`:
|
|
22
22
|
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
})
|
|
23
|
+
```html
|
|
24
|
+
<script>
|
|
25
|
+
DashgramMini.init({
|
|
26
|
+
projectId: "your-project-id",
|
|
27
|
+
trackLevel: 2
|
|
28
|
+
})
|
|
29
|
+
</script>
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
**Configuration parameters:**
|
|
33
|
+
|
|
34
|
+
- `projectId` — Your project identifier from the [Dashgram dashboard](https://app.dashgram.io). Get it after creating a project.
|
|
35
|
+
- `trackLevel` — Controls which events are automatically captured. See [Track Levels](#track-levels) section below for details.
|
|
29
36
|
|
|
30
|
-
|
|
37
|
+
### 3. Track custom events (optional)
|
|
38
|
+
|
|
39
|
+
If you want to send custom events to Dashgram, use the `DashgramMini.track()` method.
|
|
40
|
+
Simply call it with an event name and optional properties whenever the action happens.
|
|
41
|
+
|
|
42
|
+
```javascript
|
|
31
43
|
DashgramMini.track("purchase_completed", {
|
|
32
44
|
product_id: "premium-plan",
|
|
33
|
-
price:
|
|
34
|
-
currency: "
|
|
45
|
+
price: 100,
|
|
46
|
+
currency: "TON"
|
|
35
47
|
})
|
|
36
48
|
```
|
|
37
49
|
|
|
38
|
-
|
|
39
|
-
|
|
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
|
-
})
|
|
49
|
-
```
|
|
50
|
+
> [!TIP]
|
|
51
|
+
> **Looking for a complete example?** Check out [`examples/basic-usage.html`](examples/basic-usage.html) for a working HTML example with event tracking.
|
|
50
52
|
|
|
51
53
|
## Track Levels
|
|
52
54
|
|
|
53
|
-
|
|
55
|
+
Choose how much data to collect. Higher levels capture more events but send more data.
|
|
54
56
|
|
|
55
|
-
|
|
57
|
+
### Level 1 — Core
|
|
58
|
+
|
|
59
|
+
**Minimal tracking** — Basic app lifecycle events only.
|
|
56
60
|
|
|
57
61
|
| Event | Description |
|
|
58
62
|
| ----------- | --------------------------------- |
|
|
59
63
|
| `app_open` | Mini App opened or became visible |
|
|
60
64
|
| `app_close` | Mini App closed or hidden |
|
|
61
65
|
|
|
66
|
+
**Use when:** You only need basic usage metrics.
|
|
67
|
+
|
|
62
68
|
### Level 2 — Interactions
|
|
63
69
|
|
|
64
|
-
|
|
70
|
+
**Standard tracking** — Level 1 + user interactions.
|
|
65
71
|
|
|
66
72
|
| Event | Description |
|
|
67
73
|
| --------------------- | -------------------------------- |
|
|
@@ -78,9 +84,11 @@ Adds user interaction tracking:
|
|
|
78
84
|
| `js_error` | JavaScript errors |
|
|
79
85
|
| `unhandled_rejection` | Unhandled Promise rejections |
|
|
80
86
|
|
|
87
|
+
**Use when:** You want standard web analytics (recommended for most apps).
|
|
88
|
+
|
|
81
89
|
### Level 3 — Deep Analytics
|
|
82
90
|
|
|
83
|
-
|
|
91
|
+
**Comprehensive tracking** — Level 1 + 2 + performance metrics + all Telegram events.
|
|
84
92
|
|
|
85
93
|
| Event | Description |
|
|
86
94
|
| -------------------------------- | ------------------------------ |
|
|
@@ -101,100 +109,80 @@ Adds performance and Telegram-specific tracking:
|
|
|
101
109
|
| `telegram_invoice_closed` | Invoice closed |
|
|
102
110
|
| ...and all other Telegram events | |
|
|
103
111
|
|
|
104
|
-
|
|
112
|
+
**Use when:** You need detailed performance monitoring and all Telegram WebApp events.
|
|
105
113
|
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
Initialize the SDK. Call once when your app loads.
|
|
114
|
+
## API Reference
|
|
109
115
|
|
|
110
|
-
### `DashgramMini.
|
|
116
|
+
### `DashgramMini.init(config)`
|
|
111
117
|
|
|
112
|
-
|
|
118
|
+
Initialize the SDK. Must be called once when your app loads.
|
|
113
119
|
|
|
114
120
|
```typescript
|
|
115
|
-
DashgramMini.
|
|
116
|
-
|
|
117
|
-
|
|
121
|
+
DashgramMini.init({
|
|
122
|
+
projectId: "your-project-id",
|
|
123
|
+
trackLevel: 2
|
|
118
124
|
})
|
|
119
125
|
```
|
|
120
126
|
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
Change the track level at runtime.
|
|
127
|
+
#### All Configuration Options:
|
|
124
128
|
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
129
|
+
| Option | Type | Default | Description |
|
|
130
|
+
| --------------- | ------------- | ------- | ---------------------------------------------------------- |
|
|
131
|
+
| `projectId` | `string` | — | **Required.** Your project ID from Dashgram dashboard |
|
|
132
|
+
| `trackLevel` | `1 \| 2 \| 3` | `2` | Event collection level (see [Track Levels](#track-levels)) |
|
|
133
|
+
| `debug` | `boolean` | `false` | Enable debug logging to console |
|
|
134
|
+
| `disabled` | `boolean` | `false` | Disable all tracking (useful for opt-out) |
|
|
135
|
+
| `batchSize` | `number` | `10` | Number of events to batch before sending |
|
|
136
|
+
| `flushInterval` | `number` | `5000` | Milliseconds between automatic flushes |
|
|
137
|
+
| `onError` | `function` | — | Callback for handling errors |
|
|
128
138
|
|
|
129
|
-
### `DashgramMini.
|
|
139
|
+
### `DashgramMini.track(event, properties)`
|
|
130
140
|
|
|
131
|
-
|
|
141
|
+
Track a custom event with optional properties.
|
|
132
142
|
|
|
133
143
|
```typescript
|
|
134
|
-
|
|
144
|
+
DashgramMini.track("purchase_completed", {
|
|
145
|
+
product_id: "premium-plan",
|
|
146
|
+
price: 100,
|
|
147
|
+
currency: "TON"
|
|
148
|
+
})
|
|
135
149
|
```
|
|
136
150
|
|
|
137
|
-
|
|
151
|
+
**Parameters:**
|
|
138
152
|
|
|
139
|
-
|
|
153
|
+
- `event` — Event name (string)
|
|
154
|
+
- `properties` — Optional event properties (object)
|
|
140
155
|
|
|
141
|
-
|
|
142
|
-
DashgramMini.shutdown()
|
|
143
|
-
```
|
|
144
|
-
|
|
145
|
-
## User Identification
|
|
156
|
+
### `DashgramMini.flush()`
|
|
146
157
|
|
|
147
|
-
|
|
158
|
+
Force send all pending events immediately. Returns a Promise.
|
|
148
159
|
|
|
149
|
-
|
|
160
|
+
```typescript
|
|
161
|
+
await DashgramMini.flush()
|
|
162
|
+
```
|
|
150
163
|
|
|
151
|
-
|
|
164
|
+
**Use cases:**
|
|
152
165
|
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
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`
|
|
166
|
+
- Before page unload
|
|
167
|
+
- After critical user actions
|
|
168
|
+
- When switching users
|
|
163
169
|
|
|
164
|
-
|
|
170
|
+
### `DashgramMini.shutdown()`
|
|
165
171
|
|
|
166
|
-
|
|
172
|
+
Stop tracking and clean up resources.
|
|
167
173
|
|
|
168
174
|
```typescript
|
|
169
|
-
|
|
175
|
+
DashgramMini.shutdown()
|
|
170
176
|
```
|
|
171
177
|
|
|
172
|
-
##
|
|
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
|
-
```
|
|
178
|
+
## Contributing
|
|
188
179
|
|
|
189
|
-
|
|
180
|
+
Contributions are welcome! Please open issues or pull requests on the [GitHub repository](https://github.com/dashgram/dashgram-javascript).
|
|
190
181
|
|
|
191
|
-
|
|
192
|
-
- Firefox 67+
|
|
193
|
-
- Safari 12+
|
|
194
|
-
- Edge 79+
|
|
182
|
+
## License
|
|
195
183
|
|
|
196
|
-
|
|
184
|
+
This project is licensed under the MIT License. See the LICENSE file for more information.
|
|
197
185
|
|
|
198
|
-
##
|
|
186
|
+
## Contact
|
|
199
187
|
|
|
200
|
-
|
|
188
|
+
For questions or support, reach out to us at [team@dashgram.io](mailto:team@dashgram.io) or visit our [website](https://dashgram.io).
|
package/dist/core/config.js
CHANGED
package/dist/dashgram.min.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
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:1,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();return e?.initData||""}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:("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 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 j=h("deviceOrientationFailed",e=>{t("device_orientation_failed",{error:e?.error})});this.unsubscribers.push(j);const U=h("gyroscopeStarted",()=>{t("gyroscope_started",{})});this.unsubscribers.push(U);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)}}}();
|
|
1
|
+
var DashgramMini=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:2,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();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 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 b(e){try{return JSON.stringify(e)}catch(e){return"{}"}}function f(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:"@dashgram/javascript@1.0.5",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:b(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([b(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:f(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:f(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:f(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:f(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?f(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 b=d("fileDownloadRequested",e=>{t("file_download_requested",{status:e?.status})});this.unsubscribers.push(b);const f=d("customMethodInvoked",e=>{t("custom_method_invoked",{req_id:e?.req_id,result:e?.result,error:e?.error})});this.unsubscribers.push(f);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 U=d("gyroscopeStarted",()=>{t("gyroscope_started",{})});this.unsubscribers.push(U);const N=d("gyroscopeStopped",()=>{t("gyroscope_stopped",{})});this.unsubscribers.push(N);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)}};return e.DashgramAPIError=s,e.DashgramConfigurationError=n,e.DashgramError=t,e.DashgramMini=L,e.NetworkError=i,e.default=L,Object.defineProperty(e,"__esModule",{value:!0}),e}({});
|
|
2
2
|
//# sourceMappingURL=dashgram.min.js.map
|