@unisights/tracker 0.0.2
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/LICENSE +21 -0
- package/README.md +121 -0
- package/dist/unisights.min.js +2 -0
- package/package.json +33 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
# Unisights Client SDK
|
|
2
|
+
|
|
3
|
+
Welcome to the **Unisights Client SDK**, the heart of the Unisights real-time analytics platform! This folder contains the WebAssembly (WASM)-powered tracking SDK, built with Rust and TypeScript, designed to efficiently and securely capture user interactions on your website or application. The SDK is lightweight, privacy-focused, and easy to integrate, enabling real-time event tracking with minimal performance impact.
|
|
4
|
+
|
|
5
|
+
## 🌟 Purpose
|
|
6
|
+
|
|
7
|
+
The Unisights Client SDK collects events (e.g., page views, clicks, custom actions) directly in the browser using WASM for speed and efficiency. It encrypts data in-browser before sending it to your Unisights ingestion service, ensuring privacy and compliance with regulations like GDPR. This SDK powers the client-side tracking for the Unisights platform, feeding data into Apache Kafka and Druid for real-time analytics.
|
|
8
|
+
|
|
9
|
+
## 📦 Folder Structure
|
|
10
|
+
|
|
11
|
+
```
|
|
12
|
+
client-sdk/
|
|
13
|
+
├── core/ # Rust WASM core logic (compiled to analytics-bundle.min.js)
|
|
14
|
+
├── src/ # TypeScript wrapper and utilities
|
|
15
|
+
├── package.json # Node.js configuration for building
|
|
16
|
+
├── tsconfig.json # TypeScript configuration
|
|
17
|
+
└── README.md # You are here
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
- **`core/`**: Contains the Rust source code compiled to WASM, providing the high-performance event collection logic.
|
|
21
|
+
- **`src/`**: Includes TypeScript files that wrap the WASM module and expose a simple JavaScript API for developers.
|
|
22
|
+
|
|
23
|
+
## 🚀 Getting Started
|
|
24
|
+
|
|
25
|
+
### 1️⃣ Prerequisites
|
|
26
|
+
|
|
27
|
+
- **Node.js** (>= 16.x) with npm
|
|
28
|
+
- **Rust** (for building or modifying the WASM core)
|
|
29
|
+
- **WasmPack** (install with `cargo install wasm-pack` for development)
|
|
30
|
+
|
|
31
|
+
### 2️⃣ Install Dependencies
|
|
32
|
+
|
|
33
|
+
Navigate to the `client-sdk` folder and install dependencies:
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
npm install
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
### 3️⃣ Build the SDK
|
|
40
|
+
|
|
41
|
+
Compile the Rust WASM code and bundle it with TypeScript:
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
npm run build
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
This generates `analytics-bundle.min.js` in the `dist/` folder (or configure the output path as needed), ready for deployment.
|
|
48
|
+
|
|
49
|
+
### 4️⃣ Integrate into Your HTML
|
|
50
|
+
|
|
51
|
+
Inject the SDK into your website by adding the following `<script>` tag to your HTML file. Replace `your-insights-id` with your unique Unisights API key and adjust the `src` URL to point to your hosted SDK file (e.g., a CDN or local server):
|
|
52
|
+
|
|
53
|
+
```html
|
|
54
|
+
<script
|
|
55
|
+
type="module"
|
|
56
|
+
id="unisights-script"
|
|
57
|
+
defer
|
|
58
|
+
data-insights-id="your-insights-id"
|
|
59
|
+
data-secret="..."
|
|
60
|
+
data-salt="..."
|
|
61
|
+
src="http://localhost:9005/analytics-bundle.min.js"
|
|
62
|
+
></script>
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
- **`type="module"`**: Ensures the SDK loads as an ES module.
|
|
66
|
+
- **`id="unisights-script"`**: A unique identifier for the script tag.
|
|
67
|
+
- **`defer`**: Loads the script asynchronously without blocking HTML parsing.
|
|
68
|
+
- **`data-insights-id`**: Your Unisights API key for identifying the data source.
|
|
69
|
+
- **`src`**: Path to the compiled `analytics-bundle.min.js` file.
|
|
70
|
+
|
|
71
|
+
### 5️⃣ Usage
|
|
72
|
+
|
|
73
|
+
Once loaded, the SDK is available globally as `unisights`. You can track events like this:
|
|
74
|
+
|
|
75
|
+
```html
|
|
76
|
+
<script>
|
|
77
|
+
// Initialize the SDK (optional, auto-runs with data-insights-id)
|
|
78
|
+
unisights.init({ apiKey: "your-insights-id" });
|
|
79
|
+
|
|
80
|
+
// Track a custom event
|
|
81
|
+
unisights.track("page_view", {
|
|
82
|
+
path: window.location.pathname,
|
|
83
|
+
timestamp: new Date().toISOString(),
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
// Track a click event
|
|
87
|
+
document.querySelector("button").addEventListener("click", () => {
|
|
88
|
+
unisights.track("button_click", { element: "submit-btn" });
|
|
89
|
+
});
|
|
90
|
+
</script>
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
- **`init()`**: Configures the SDK with your API key (optional if set in `data-insights-id`).
|
|
94
|
+
- **`track(eventName, data)`**: Sends an event with a name and optional metadata to the Unisights ingestion service.
|
|
95
|
+
|
|
96
|
+
## 🛠 Development
|
|
97
|
+
|
|
98
|
+
### Modify the WASM Core
|
|
99
|
+
|
|
100
|
+
- Edit Rust files in `core/`.
|
|
101
|
+
- Rebuild with `npm run build` to regenerate `analytics-bundle.min.js`.
|
|
102
|
+
|
|
103
|
+
### Test Locally
|
|
104
|
+
|
|
105
|
+
- Serve the `dist/` folder with a local server (e.g., `npx serve dist` or use `http://localhost:9005`).
|
|
106
|
+
- Open your HTML file in a browser and check the console for errors or use network tools to verify event transmission.
|
|
107
|
+
|
|
108
|
+
## ✨ Why This SDK Stands Out
|
|
109
|
+
|
|
110
|
+
- **WASM Performance**: Rust-compiled WASM offers faster execution and lower overhead than traditional JavaScript trackers.
|
|
111
|
+
- **Privacy-Focused**: In-browser encryption protects user data before it leaves the client.
|
|
112
|
+
- **Lightweight**: Minimal impact on page load times, ideal for high-traffic sites.
|
|
113
|
+
- **Extensible**: Easy to add custom events or integrate with your analytics workflow.
|
|
114
|
+
|
|
115
|
+
## 🌟 Support the Project
|
|
116
|
+
|
|
117
|
+
If you find the Unisights Client SDK useful, give the main Unisights repository a ⭐ on GitHub at [https://github.com/<your-username>/unisights](https://github.com/<your-username>/unisights). Share it with your network or suggest improvements via GitHub Issues. More contributors will help us enhance this SDK!
|
|
118
|
+
|
|
119
|
+
## 📜 License
|
|
120
|
+
|
|
121
|
+
Licensed under the [MIT License](https://github.com/<your-username>/unisights/blob/main/LICENSE)—see the root `LICENSE` file for details.
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var o,f=0,C=null;function W(){return(C===null||C.byteLength===0)&&(C=new Uint8Array(o.memory.buffer)),C}var F=typeof TextEncoder<"u"?new TextEncoder("utf-8"):{encode:()=>{throw Error("TextEncoder not available")}},xe=typeof F.encodeInto=="function"?function(t,e){return F.encodeInto(t,e)}:function(t,e){let n=F.encode(t);return e.set(n),{read:t.length,written:n.length}};function d(t,e,n){if(n===void 0){let c=F.encode(t),l=e(c.length,1)>>>0;return W().subarray(l,l+c.length).set(c),f=c.length,l}let r=t.length,i=e(r,1)>>>0,a=W(),s=0;for(;s<r;s++){let c=t.charCodeAt(s);if(c>127)break;a[i+s]=c}if(s!==r){s!==0&&(t=t.slice(s)),i=n(i,r,r=s+t.length*3,1)>>>0;let c=W().subarray(i+s,i+r),l=xe(t,c);s+=l.written,i=n(i,r,s,1)>>>0}return f=s,i}var I=null;function w(){return(I===null||I.buffer.detached===!0||I.buffer.detached===void 0&&I.buffer!==o.memory.buffer)&&(I=new DataView(o.memory.buffer)),I}function k(t){let e=o.__externref_table_alloc();return o.__wbindgen_export_4.set(e,t),e}function S(t,e){try{return t.apply(this,e)}catch(n){let r=k(n);o.__wbindgen_exn_store(r)}}var ae=typeof TextDecoder<"u"?new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}):{decode:()=>{throw Error("TextDecoder not available")}};typeof TextDecoder<"u"&&ae.decode();function D(t,e){return t=t>>>0,ae.decode(W().subarray(t,t+e))}function y(t){return t==null}function q(t){let e=typeof t;if(e=="number"||e=="boolean"||t==null)return`${t}`;if(e=="string")return`"${t}"`;if(e=="symbol"){let i=t.description;return i==null?"Symbol":`Symbol(${i})`}if(e=="function"){let i=t.name;return typeof i=="string"&&i.length>0?`Function(${i})`:"Function"}if(Array.isArray(t)){let i=t.length,a="[";i>0&&(a+=q(t[0]));for(let s=1;s<i;s++)a+=", "+q(t[s]);return a+="]",a}let n=/\[object ([^\]]+)\]/.exec(toString.call(t)),r;if(n&&n.length>1)r=n[1];else return toString.call(t);if(r=="Object")try{return"Object("+JSON.stringify(t)+")"}catch{return"Object"}return t instanceof Error?`${t.name}: ${t.message}
|
|
2
|
+
${t.stack}`:r}function se(t){let e=o.__wbindgen_export_4.get(t);return o.__externref_table_dealloc(t),e}var ce=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(t=>o.__wbg_tracker_free(t>>>0,1)),U=class{__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,ce.unregister(this),e}free(){let e=this.__destroy_into_raw();o.__wbg_tracker_free(e,0)}clearEvents(){o.tracker_clearEvents(this.__wbg_ptr)}setPageUrl(e){let n=d(e,o.__wbindgen_malloc,o.__wbindgen_realloc),r=f;o.tracker_setPageUrl(this.__wbg_ptr,n,r)}logExitPage(e){let n=d(e,o.__wbindgen_malloc,o.__wbindgen_realloc),r=f;o.tracker_logExitPage(this.__wbg_ptr,n,r)}logPageView(e){let n=d(e,o.__wbindgen_malloc,o.__wbindgen_realloc),r=f;o.tracker_logPageView(this.__wbg_ptr,n,r)}logWebVital(e,n,r,i,a,s,c){let l=d(e,o.__wbindgen_malloc,o.__wbindgen_realloc),u=f,_=d(r,o.__wbindgen_malloc,o.__wbindgen_realloc),m=f,P=d(i,o.__wbindgen_malloc,o.__wbindgen_realloc),j=f,V=d(c,o.__wbindgen_malloc,o.__wbindgen_realloc),$=f;o.tracker_logWebVital(this.__wbg_ptr,l,u,n,_,m,P,j,a,s,V,$)}updateScroll(e){o.tracker_updateScroll(this.__wbg_ptr,e)}logEntryPage(e){let n=d(e,o.__wbindgen_malloc,o.__wbindgen_realloc),r=f;o.tracker_logEntryPage(this.__wbg_ptr,n,r)}logCustomEvent(e,n){let r=d(e,o.__wbindgen_malloc,o.__wbindgen_realloc),i=f,a=d(n,o.__wbindgen_malloc,o.__wbindgen_realloc),s=f;o.tracker_logCustomEvent(this.__wbg_ptr,r,i,a,s)}setSessionInfo(e,n,r,i,a){let s=d(e,o.__wbindgen_malloc,o.__wbindgen_realloc),c=f,l=d(n,o.__wbindgen_malloc,o.__wbindgen_realloc),u=f,_=d(r,o.__wbindgen_malloc,o.__wbindgen_realloc),m=f;o.tracker_setSessionInfo(this.__wbg_ptr,s,c,l,u,_,m,i,a)}setEncryptionKey(e,n){let r=d(e,o.__wbindgen_malloc,o.__wbindgen_realloc),i=f,a=d(n,o.__wbindgen_malloc,o.__wbindgen_realloc),s=f;o.tracker_setEncryptionKey(this.__wbg_ptr,r,i,a,s)}exportEncryptedPayload(){let e=o.tracker_exportEncryptedPayload(this.__wbg_ptr);if(e[2])throw se(e[1]);return se(e[0])}constructor(){let e=o.tracker_new();return this.__wbg_ptr=e>>>0,ce.register(this,this.__wbg_ptr,this),this}tick(e){o.tracker_tick(this.__wbg_ptr,e)}logClick(e,n){o.tracker_logClick(this.__wbg_ptr,e,n)}};async function Oe(t,e){if(typeof Response=="function"&&t instanceof Response){if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(t,e)}catch(r){if(t.headers.get("Content-Type")!="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",r);else throw r}let n=await t.arrayBuffer();return await WebAssembly.instantiate(n,e)}else{let n=await WebAssembly.instantiate(t,e);return n instanceof WebAssembly.Instance?{instance:n,module:t}:n}}function Me(){let t={};return t.wbg={},t.wbg.__wbg_String_eecc4a11987127d6=function(e,n){let r=String(n),i=d(r,o.__wbindgen_malloc,o.__wbindgen_realloc),a=f;w().setInt32(e+4*1,a,!0),w().setInt32(e+4*0,i,!0)},t.wbg.__wbg_buffer_609cc3eee51ed158=function(e){return e.buffer},t.wbg.__wbg_call_672a4d21634d4a24=function(){return S(function(e,n){return e.call(n)},arguments)},t.wbg.__wbg_call_7cccdd69e0791ae2=function(){return S(function(e,n,r){return e.call(n,r)},arguments)},t.wbg.__wbg_crypto_574e78ad8b13b65f=function(e){return e.crypto},t.wbg.__wbg_done_769e5ede4b31c67b=function(e){return e.done},t.wbg.__wbg_entries_3265d4158b33e5dc=function(e){return Object.entries(e)},t.wbg.__wbg_getRandomValues_b8f5dbd5f3995a9e=function(){return S(function(e,n){e.getRandomValues(n)},arguments)},t.wbg.__wbg_get_67b2ba62fc30de12=function(){return S(function(e,n){return Reflect.get(e,n)},arguments)},t.wbg.__wbg_get_b9b93047fe3cf45b=function(e,n){return e[n>>>0]},t.wbg.__wbg_instanceof_ArrayBuffer_e14585432e3737fc=function(e){let n;try{n=e instanceof ArrayBuffer}catch{n=!1}return n},t.wbg.__wbg_instanceof_Uint8Array_17156bcf118086a9=function(e){let n;try{n=e instanceof Uint8Array}catch{n=!1}return n},t.wbg.__wbg_isArray_a1eab7e0d067391b=function(e){return Array.isArray(e)},t.wbg.__wbg_isSafeInteger_343e2beeeece1bb0=function(e){return Number.isSafeInteger(e)},t.wbg.__wbg_iterator_9a24c88df860dc65=function(){return Symbol.iterator},t.wbg.__wbg_length_a446193dc22c12f8=function(e){return e.length},t.wbg.__wbg_length_e2d2a49132c1b256=function(e){return e.length},t.wbg.__wbg_msCrypto_a61aeb35a24c1329=function(e){return e.msCrypto},t.wbg.__wbg_new_405e22f390576ce2=function(){return new Object},t.wbg.__wbg_new_5e0be73521bc8c17=function(){return new Map},t.wbg.__wbg_new_78feb108b6472713=function(){return new Array},t.wbg.__wbg_new_a12002a7f91c75be=function(e){return new Uint8Array(e)},t.wbg.__wbg_newnoargs_105ed471475aaf50=function(e,n){return new Function(D(e,n))},t.wbg.__wbg_newwithbyteoffsetandlength_d97e637ebe145a9a=function(e,n,r){return new Uint8Array(e,n>>>0,r>>>0)},t.wbg.__wbg_newwithlength_a381634e90c276d4=function(e){return new Uint8Array(e>>>0)},t.wbg.__wbg_next_25feadfc0913fea9=function(e){return e.next},t.wbg.__wbg_next_6574e1a8a62d1055=function(){return S(function(e){return e.next()},arguments)},t.wbg.__wbg_node_905d3e251edff8a2=function(e){return e.node},t.wbg.__wbg_now_807e54c39636c349=function(){return Date.now()},t.wbg.__wbg_process_dc0fbacc7c1c06f7=function(e){return e.process},t.wbg.__wbg_randomFillSync_ac0988aba3254290=function(){return S(function(e,n){e.randomFillSync(n)},arguments)},t.wbg.__wbg_require_60cc747a6bc5215a=function(){return S(function(){return module.require},arguments)},t.wbg.__wbg_set_37837023f3d740e8=function(e,n,r){e[n>>>0]=r},t.wbg.__wbg_set_3807d5f0bfc24aa7=function(e,n,r){e[n]=r},t.wbg.__wbg_set_65595bdd868b3009=function(e,n,r){e.set(n,r>>>0)},t.wbg.__wbg_set_8fc6bf8a5b1071d1=function(e,n,r){return e.set(n,r)},t.wbg.__wbg_static_accessor_GLOBAL_88a902d13a557d07=function(){let e=typeof global>"u"?null:global;return y(e)?0:k(e)},t.wbg.__wbg_static_accessor_GLOBAL_THIS_56578be7e9f832b0=function(){let e=typeof globalThis>"u"?null:globalThis;return y(e)?0:k(e)},t.wbg.__wbg_static_accessor_SELF_37c5d418e4bf5819=function(){let e=typeof self>"u"?null:self;return y(e)?0:k(e)},t.wbg.__wbg_static_accessor_WINDOW_5de37043a91a9c40=function(){let e=typeof window>"u"?null:window;return y(e)?0:k(e)},t.wbg.__wbg_subarray_aa9065fa9dc5df96=function(e,n,r){return e.subarray(n>>>0,r>>>0)},t.wbg.__wbg_value_cd1ffa7b1ab794f1=function(e){return e.value},t.wbg.__wbg_versions_c01dfd4722a88165=function(e){return e.versions},t.wbg.__wbindgen_bigint_from_i64=function(e){return e},t.wbg.__wbindgen_bigint_from_u64=function(e){return BigInt.asUintN(64,e)},t.wbg.__wbindgen_bigint_get_as_i64=function(e,n){let r=n,i=typeof r=="bigint"?r:void 0;w().setBigInt64(e+8*1,y(i)?BigInt(0):i,!0),w().setInt32(e+4*0,!y(i),!0)},t.wbg.__wbindgen_boolean_get=function(e){let n=e;return typeof n=="boolean"?n?1:0:2},t.wbg.__wbindgen_debug_string=function(e,n){let r=q(n),i=d(r,o.__wbindgen_malloc,o.__wbindgen_realloc),a=f;w().setInt32(e+4*1,a,!0),w().setInt32(e+4*0,i,!0)},t.wbg.__wbindgen_error_new=function(e,n){return new Error(D(e,n))},t.wbg.__wbindgen_in=function(e,n){return e in n},t.wbg.__wbindgen_init_externref_table=function(){let e=o.__wbindgen_export_4,n=e.grow(4);e.set(0,void 0),e.set(n+0,void 0),e.set(n+1,null),e.set(n+2,!0),e.set(n+3,!1)},t.wbg.__wbindgen_is_bigint=function(e){return typeof e=="bigint"},t.wbg.__wbindgen_is_function=function(e){return typeof e=="function"},t.wbg.__wbindgen_is_object=function(e){let n=e;return typeof n=="object"&&n!==null},t.wbg.__wbindgen_is_string=function(e){return typeof e=="string"},t.wbg.__wbindgen_is_undefined=function(e){return e===void 0},t.wbg.__wbindgen_jsval_eq=function(e,n){return e===n},t.wbg.__wbindgen_jsval_loose_eq=function(e,n){return e==n},t.wbg.__wbindgen_memory=function(){return o.memory},t.wbg.__wbindgen_number_get=function(e,n){let r=n,i=typeof r=="number"?r:void 0;w().setFloat64(e+8*1,y(i)?0:i,!0),w().setInt32(e+4*0,!y(i),!0)},t.wbg.__wbindgen_number_new=function(e){return e},t.wbg.__wbindgen_string_get=function(e,n){let r=n,i=typeof r=="string"?r:void 0;var a=y(i)?0:d(i,o.__wbindgen_malloc,o.__wbindgen_realloc),s=f;w().setInt32(e+4*1,s,!0),w().setInt32(e+4*0,a,!0)},t.wbg.__wbindgen_string_new=function(e,n){return D(e,n)},t.wbg.__wbindgen_throw=function(e,n){throw new Error(D(e,n))},t}function Ne(t,e){return o=t.exports,le.__wbindgen_wasm_module=e,I=null,C=null,o.__wbindgen_start(),o}async function le(t){if(o!==void 0)return o;typeof t<"u"&&(Object.getPrototypeOf(t)===Object.prototype?{module_or_path:t}=t:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),typeof t>"u"&&(t=new URL("unisights_core_bg.wasm",import.meta.url));let e=Me();(typeof t=="string"||typeof Request=="function"&&t instanceof Request||typeof URL=="function"&&t instanceof URL)&&(t=fetch(t));let{instance:n,module:r}=await Oe(await t,e);return Ne(n,r)}var _e=le;var ye=-1,T=t=>{addEventListener("pageshow",e=>{e.persisted&&(ye=e.timeStamp,t(e))},!0)},p=(t,e,n,r)=>{let i,a;return s=>{e.value>=0&&(s||r)&&(a=e.value-(i??0),(a||i===void 0)&&(i=e.value,e.delta=a,e.rating=((c,l)=>c>l[1]?"poor":c>l[0]?"needs-improvement":"good")(e.value,n),t(e)))}},te=t=>{requestAnimationFrame(()=>requestAnimationFrame(()=>t()))},ne=()=>{let t=performance.getEntriesByType("navigation")[0];if(t&&t.responseStart>0&&t.responseStart<performance.now())return t},L=()=>ne()?.activationStart??0,h=(t,e=-1)=>{let n=ne(),r="navigate";return ye>=0?r="back-forward-cache":n&&(document.prerendering||L()>0?r="prerender":document.wasDiscarded?r="restore":n.type&&(r=n.type.replace(/_/g,"-"))),{name:t,value:e,rating:"good",delta:0,entries:[],id:`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+1e12}`,navigationType:r}},J=new WeakMap;function re(t,e){return J.get(t)||J.set(t,new e),J.get(t)}var z=class{t;i=0;o=[];h(e){if(e.hadRecentInput)return;let n=this.o[0],r=this.o.at(-1);this.i&&n&&r&&e.startTime-r.startTime<1e3&&e.startTime-n.startTime<5e3?(this.i+=e.value,this.o.push(e)):(this.i=e.value,this.o=[e]),this.t?.(e)}},x=(t,e,n={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(t)){let r=new PerformanceObserver(i=>{Promise.resolve().then(()=>{e(i.getEntries())})});return r.observe({type:t,buffered:!0,...n}),r}}catch{}},ie=t=>{let e=!1;return()=>{e||(t(),e=!0)}},E=-1,me=new Set,ge=()=>document.visibilityState!=="hidden"||document.prerendering?1/0:0,Q=t=>{if(document.visibilityState==="hidden"){if(t.type==="visibilitychange")for(let e of me)e();isFinite(E)||(E=t.type==="visibilitychange"?t.timeStamp:0,removeEventListener("prerenderingchange",Q,!0))}},B=()=>{if(E<0){let t=L();E=(document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").filter(n=>n.name==="hidden"&&n.startTime>t)[0]?.startTime)??ge(),addEventListener("visibilitychange",Q,!0),addEventListener("prerenderingchange",Q,!0),T(()=>{setTimeout(()=>{E=ge()})})}return{get firstHiddenTime(){return E},onHidden(t){me.add(t)}}},R=t=>{document.prerendering?addEventListener("prerenderingchange",()=>t(),!0):t()},ue=[1800,3e3],oe=(t,e={})=>{R(()=>{let n=B(),r,i=h("FCP"),a=x("paint",s=>{for(let c of s)c.name==="first-contentful-paint"&&(a.disconnect(),c.startTime<n.firstHiddenTime&&(i.value=Math.max(c.startTime-L(),0),i.entries.push(c),r(!0)))});a&&(r=p(t,i,ue,e.reportAllChanges),T(s=>{i=h("FCP"),r=p(t,i,ue,e.reportAllChanges),te(()=>{i.value=performance.now()-s.timeStamp,r(!0)})}))})},fe=[.1,.25],ve=(t,e={})=>{let n=B();oe(ie(()=>{let r,i=h("CLS",0),a=re(e,z),s=l=>{for(let u of l)a.h(u);a.i>i.value&&(i.value=a.i,i.entries=a.o,r())},c=x("layout-shift",s);c&&(r=p(t,i,fe,e.reportAllChanges),n.onHidden(()=>{s(c.takeRecords()),r(!0)}),T(()=>{a.i=0,i=h("CLS",0),r=p(t,i,fe,e.reportAllChanges),te(()=>r())}),setTimeout(r))}))},Se=0,K=1/0,H=0,We=t=>{for(let e of t)e.interactionId&&(K=Math.min(K,e.interactionId),H=Math.max(H,e.interactionId),Se=H?(H-K)/7+1:0)},Y,de=()=>Y?Se:performance.interactionCount??0,Fe=()=>{"interactionCount"in performance||Y||(Y=x("event",We,{type:"event",buffered:!0,durationThreshold:0}))},be=0,X=class{u=[];l=new Map;m;p;v(){be=de(),this.u.length=0,this.l.clear()}L(){let e=Math.min(this.u.length-1,Math.floor((de()-be)/50));return this.u[e]}h(e){if(this.m?.(e),!e.interactionId&&e.entryType!=="first-input")return;let n=this.u.at(-1),r=this.l.get(e.interactionId);if(r||this.u.length<10||e.duration>n.P){if(r?e.duration>r.P?(r.entries=[e],r.P=e.duration):e.duration===r.P&&e.startTime===r.entries[0].startTime&&r.entries.push(e):(r={id:e.interactionId,entries:[e],P:e.duration},this.l.set(r.id,r),this.u.push(r)),this.u.sort((i,a)=>a.P-i.P),this.u.length>10){let i=this.u.splice(10);for(let a of i)this.l.delete(a.id)}this.p?.(r)}}},Ie=t=>{let e=globalThis.requestIdleCallback||setTimeout;document.visibilityState==="hidden"?t():(t=ie(t),addEventListener("visibilitychange",t,{once:!0,capture:!0}),e(()=>{t(),removeEventListener("visibilitychange",t,{capture:!0})}))},we=[200,500],Ee=(t,e={})=>{if(!globalThis.PerformanceEventTiming||!("interactionId"in PerformanceEventTiming.prototype))return;let n=B();R(()=>{Fe();let r,i=h("INP"),a=re(e,X),s=l=>{Ie(()=>{for(let _ of l)a.h(_);let u=a.L();u&&u.P!==i.value&&(i.value=u.P,i.entries=u.entries,r())})},c=x("event",s,{durationThreshold:e.durationThreshold??40});r=p(t,i,we,e.reportAllChanges),c&&(c.observe({type:"first-input",buffered:!0}),n.onHidden(()=>{s(c.takeRecords()),r(!0)}),T(()=>{a.v(),i=h("INP"),r=p(t,i,we,e.reportAllChanges)}))})},Z=class{m;h(e){this.m?.(e)}},pe=[2500,4e3],Te=(t,e={})=>{R(()=>{let n=B(),r,i=h("LCP"),a=re(e,Z),s=l=>{e.reportAllChanges||(l=l.slice(-1));for(let u of l)a.h(u),u.startTime<n.firstHiddenTime&&(i.value=Math.max(u.startTime-L(),0),i.entries=[u],r())},c=x("largest-contentful-paint",s);if(c){r=p(t,i,pe,e.reportAllChanges);let l=ie(()=>{s(c.takeRecords()),c.disconnect(),r(!0)}),u=_=>{_.isTrusted&&(Ie(l),removeEventListener(_.type,u,{capture:!0}))};for(let _ of["keydown","click","visibilitychange"])addEventListener(_,u,{capture:!0});T(_=>{i=h("LCP"),r=p(t,i,pe,e.reportAllChanges),te(()=>{i.value=performance.now()-_.timeStamp,r(!0)})})}})},he=[800,1800],ee=t=>{document.prerendering?R(()=>ee(t)):document.readyState!=="complete"?addEventListener("load",()=>ee(t),!0):setTimeout(t)},Ae=(t,e={})=>{let n=h("TTFB"),r=p(t,n,he,e.reportAllChanges);ee(()=>{let i=ne();i&&(n.value=Math.max(i.responseStart-L(),0),n.entries=[i],r(!0),T(()=>{n=h("TTFB",0),r=p(t,n,he,e.reportAllChanges),r(!0)}))})};var Ue=()=>{let e=document.getElementById("unisights-script")?.src||"";return e.substring(0,e.lastIndexOf("/"))||""},He={endpoint:"",debug:!1,flushIntervalMs:15e3,wasmPath:`${Ue()}/pkg/unisights_core_bg.wasm`,trackPageViews:!0,trackClicks:!0,trackScroll:!0};function Be(t,e){let n=r=>{try{t.logWebVital(r.name,r.value,r.id,r.rating,r.delta,r.entries?.length||0,r.navigationType||"navigate"),e.debug&&console.log("[Insights] - Web Vital logged:",r)}catch(i){console.error("[Insights] - Web Vital Error:",i)}};[ve,Ee,Te,oe,Ae].forEach(r=>r(n))}function Re(){let t=["utm_source","utm_medium","utm_campaign","utm_term","utm_content"],e={},n=new URLSearchParams(window.location.search);for(let r of t){let i=n.get(r)||sessionStorage.getItem(`_us_${r}`);i&&(e[r]=i,sessionStorage.setItem(`_us_${r}`,i))}return e}function je(){let t=navigator.userAgent,e=navigator.platform,n=/Win/.test(e)?"Windows":/Mac/.test(e)?"macOS":/Linux/.test(e)?"Linux":/Android/.test(t)?"Android":/iPhone|iPad|iPod/.test(t)?"iOS":"Unknown",r=/Mobi|Android/i.test(t)?"Mobile":"Desktop";return{userAgent:t,platform:e,os:n,screenWidth:screen.width,screenHeight:screen.height,deviceType:r}}var Ve=/bot|crawler|spider|crawling/i.test(navigator.userAgent),N="__ua_session",$e=30*60*1e3;function Ge(){let t=Date.now(),e=localStorage.getItem(N);if(e){let r=JSON.parse(e);if(t-r.lastActivity<$e)return r.lastActivity=t,localStorage.setItem(N,JSON.stringify(r)),r.sessionId}let n={sessionId:crypto.randomUUID(),startedAt:t,lastActivity:t};return localStorage.setItem(N,JSON.stringify(n)),n.sessionId}function O(){let t=localStorage.getItem(N);if(!t)return;let e=JSON.parse(t);e.lastActivity=Date.now(),localStorage.setItem(N,JSON.stringify(e))}var Pe=!1,qe,A=location.href;async function Ce(t={}){if(Pe)return;Pe=!0;let e=document.querySelector("script[data-insights-id]"),n=e?.getAttribute("data-insights-id"),r=e?.getAttribute("data-secret"),i=e?.getAttribute("data-salt");if(!n)throw new Error("Missing data-insights-id");let a={};try{a=JSON.parse(e?.getAttribute("data-analytics-config")||"{}")}catch(g){console.error("[Insights] - Config parse error:",g)}if(Ve)return;let s={...He,...a,...t,insightsId:n};await _e(s.wasmPath);let c=new U,l=Ge(),u=performance.now(),_=!1;c.setEncryptionKey(r||"",i||""),c.setSessionInfo(s.insightsId,l,location.href,Re(),je()),Be(c,s),s.debug&&console.log("[Insights] - Session ID:",l);let m=new Map;if(s.trackClicks){let g=b=>{c.logClick(b.clientX,b.clientY),O(),_=!0};window.addEventListener("click",g),m.set("click",g)}if(s.trackScroll){let g=-50,b=()=>{let v=performance.now();if(v-g<50)return;g=v;let G=(window.scrollY+window.innerHeight)/(document.body.scrollHeight||1)*100;c.updateScroll(G),O(),_=!0};window.addEventListener("scroll",b),m.set("scroll",b)}s.trackPageViews&&(c.logEntryPage(location.href),c.logPageView(location.href),s.debug&&console.log("[Insights] - Entry page event:",location.href),_=!0);let P=()=>{let g=location.href;g!==A&&(_&&(M(c,s),_=!1),A=g,s.trackPageViews&&(c.logPageView(A),s.debug&&console.log("[Insights] - Page view event:",A),O(),_=!0))};window.addEventListener("popstate",P);let j=history.pushState,V=history.replaceState;history.pushState=function(...g){j.apply(this,g),P()},history.replaceState=function(...g){V.apply(this,g),P()};let $=()=>{c.logExitPage(A),s.debug&&console.log("[Insights] - Exit page (via pagehide) event:",A),M(c,s,!0),O(),_=!1};window.addEventListener("pagehide",$),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&(M(c,s,!0),_=!1)}),qe=window.setInterval(()=>{let g=performance.now();c.tick((g-u)/1e3),u=g,_&&(M(c,s),_=!1)},s.flushIntervalMs),window.AnalyticsSDK={init:Ce,registerEvent:(g,b)=>{let v=typeof b=="function"?b:()=>{};return window.addEventListener(g,v),m.set(g,v),(G,ke)=>{try{c.logCustomEvent(G,JSON.stringify(ke)),_=!0}catch(Le){console.error("[Insights] - Custom Event Error:",Le)}}},flushNow:()=>M(c,s,!0),log:(g,b)=>{try{c.logCustomEvent(g,JSON.stringify(b)),O(),_=!0}catch(v){console.error("[Insights] - log() error:",v)}}},Array.isArray(window.AnalyticsQueue)&&window.AnalyticsQueue.splice(0).forEach(g=>{try{g()}catch(b){console.error("[Insights] - Queue Error:",b)}})}function M(t,e,n=!1){try{let r=t.exportEncryptedPayload();if(e.debug&&console.log("[Insights] - Payload:",r),!r||r instanceof Error)return;let i=r instanceof Map?Object.fromEntries(r.entries()):r,a=new Blob([JSON.stringify(i)],{type:"application/json"}),s=navigator.sendBeacon(e.endpoint,a);e.debug&&console.log("[Insights] - Encrypted payload sent:",{success:s,length:a.size}),s&&t.clearEvents()}catch(r){e.debug&&console.error("[Insights] - Send Error:",r)}}typeof window<"u"&&(window.AnalyticsQueue||=[],Ce().catch(t=>console.error("[Insights] - Init Error:",t)));
|
package/package.json
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@unisights/tracker",
|
|
3
|
+
"description": "Unisights browser event tracking script",
|
|
4
|
+
"version": "0.0.2",
|
|
5
|
+
"main": "dist/unisights.min.js",
|
|
6
|
+
"author": {
|
|
7
|
+
"name": "Pradeep Arul",
|
|
8
|
+
"email": "pradeeparul2@gmail.com",
|
|
9
|
+
"url": "https://github.com/Pradeeparul2"
|
|
10
|
+
},
|
|
11
|
+
"scripts": {
|
|
12
|
+
"build": "tsc && node build.mjs && cpx \"core/pkg/**/*\" dist/pkg",
|
|
13
|
+
"dev:build": "tsc && esbuild src/analytics.ts --bundle --outfile=dist/analytics.js --format=esm --sourcemap --loader:.wasm=binary --define:process.env.NODE_ENV='\"development\"' && cpx \"core/pkg/**/*\" dist/pkg",
|
|
14
|
+
"dev:watch": "node build.mjs --watch --define:process.env.NODE_ENV='\"development\"'",
|
|
15
|
+
"serve": "live-server dist --no-browser --port=9005 --watch=dist --cors",
|
|
16
|
+
"dev": "concurrently \"pnpm dev:watch\" \"pnpm serve\""
|
|
17
|
+
},
|
|
18
|
+
"dependencies": {
|
|
19
|
+
"dotenv": "^17.0.1",
|
|
20
|
+
"web-vitals": "^5.0.3"
|
|
21
|
+
},
|
|
22
|
+
"devDependencies": {
|
|
23
|
+
"concurrently": "^9.2.0",
|
|
24
|
+
"cpx": "^1.5.0",
|
|
25
|
+
"esbuild": "^0.23.0",
|
|
26
|
+
"live-server": "^1.2.2",
|
|
27
|
+
"typescript": "^5.5.0"
|
|
28
|
+
},
|
|
29
|
+
"files": [
|
|
30
|
+
"dist"
|
|
31
|
+
],
|
|
32
|
+
"license": "MIT"
|
|
33
|
+
}
|