@altertable/altertable-js 1.0.5 → 1.0.6
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/dist/index.d.mts +8 -6
- package/dist/index.d.ts +8 -6
- package/dist/index.global.js +7 -7
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +7 -7
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +6 -6
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
|
@@ -88,7 +88,7 @@ interface AltertableConfig {
|
|
|
88
88
|
declare class Altertable {
|
|
89
89
|
private _cleanupAutoCapture;
|
|
90
90
|
private _config;
|
|
91
|
-
private
|
|
91
|
+
private _queue;
|
|
92
92
|
private _isInitialized;
|
|
93
93
|
private _lastUrl;
|
|
94
94
|
private _logger;
|
|
@@ -149,6 +149,7 @@ declare class Altertable {
|
|
|
149
149
|
* ```
|
|
150
150
|
*/
|
|
151
151
|
identify(userId: DistinctId, traits?: UserTraits): void;
|
|
152
|
+
private _identify;
|
|
152
153
|
/**
|
|
153
154
|
* Link a new ID to the current identity.
|
|
154
155
|
*
|
|
@@ -160,6 +161,7 @@ declare class Altertable {
|
|
|
160
161
|
* ```
|
|
161
162
|
*/
|
|
162
163
|
alias(newUserId: DistinctId): void;
|
|
164
|
+
private _alias;
|
|
163
165
|
/**
|
|
164
166
|
* Updates user traits for the current user.
|
|
165
167
|
*
|
|
@@ -173,9 +175,7 @@ declare class Altertable {
|
|
|
173
175
|
* ```
|
|
174
176
|
*/
|
|
175
177
|
updateTraits(traits: UserTraits): void;
|
|
176
|
-
private
|
|
177
|
-
private _aliasWithContext;
|
|
178
|
-
private _updateTraitsWithContext;
|
|
178
|
+
private _updateTraits;
|
|
179
179
|
/**
|
|
180
180
|
* Resets device and session IDs.
|
|
181
181
|
*
|
|
@@ -220,7 +220,7 @@ declare class Altertable {
|
|
|
220
220
|
* - Server-side tracking where auto-capture isn't available
|
|
221
221
|
*/
|
|
222
222
|
page(url: string): void;
|
|
223
|
-
private
|
|
223
|
+
private _page;
|
|
224
224
|
/**
|
|
225
225
|
* Tracks a custom event with optional properties.
|
|
226
226
|
*
|
|
@@ -237,7 +237,7 @@ declare class Altertable {
|
|
|
237
237
|
* ```
|
|
238
238
|
*/
|
|
239
239
|
track(event: string, properties?: EventProperties): void;
|
|
240
|
-
private
|
|
240
|
+
private _track;
|
|
241
241
|
/**
|
|
242
242
|
* Returns the current tracking consent state.
|
|
243
243
|
*
|
|
@@ -254,10 +254,12 @@ declare class Altertable {
|
|
|
254
254
|
*/
|
|
255
255
|
getTrackingConsent(): TrackingConsentType;
|
|
256
256
|
private _flushQueue;
|
|
257
|
+
private _executeQueueItem;
|
|
257
258
|
private _executeCommand;
|
|
258
259
|
private _checkForChanges;
|
|
259
260
|
private _getContext;
|
|
260
261
|
private _processEvent;
|
|
262
|
+
private _sendEvent;
|
|
261
263
|
}
|
|
262
264
|
|
|
263
265
|
declare global {
|
package/dist/index.d.ts
CHANGED
|
@@ -88,7 +88,7 @@ interface AltertableConfig {
|
|
|
88
88
|
declare class Altertable {
|
|
89
89
|
private _cleanupAutoCapture;
|
|
90
90
|
private _config;
|
|
91
|
-
private
|
|
91
|
+
private _queue;
|
|
92
92
|
private _isInitialized;
|
|
93
93
|
private _lastUrl;
|
|
94
94
|
private _logger;
|
|
@@ -149,6 +149,7 @@ declare class Altertable {
|
|
|
149
149
|
* ```
|
|
150
150
|
*/
|
|
151
151
|
identify(userId: DistinctId, traits?: UserTraits): void;
|
|
152
|
+
private _identify;
|
|
152
153
|
/**
|
|
153
154
|
* Link a new ID to the current identity.
|
|
154
155
|
*
|
|
@@ -160,6 +161,7 @@ declare class Altertable {
|
|
|
160
161
|
* ```
|
|
161
162
|
*/
|
|
162
163
|
alias(newUserId: DistinctId): void;
|
|
164
|
+
private _alias;
|
|
163
165
|
/**
|
|
164
166
|
* Updates user traits for the current user.
|
|
165
167
|
*
|
|
@@ -173,9 +175,7 @@ declare class Altertable {
|
|
|
173
175
|
* ```
|
|
174
176
|
*/
|
|
175
177
|
updateTraits(traits: UserTraits): void;
|
|
176
|
-
private
|
|
177
|
-
private _aliasWithContext;
|
|
178
|
-
private _updateTraitsWithContext;
|
|
178
|
+
private _updateTraits;
|
|
179
179
|
/**
|
|
180
180
|
* Resets device and session IDs.
|
|
181
181
|
*
|
|
@@ -220,7 +220,7 @@ declare class Altertable {
|
|
|
220
220
|
* - Server-side tracking where auto-capture isn't available
|
|
221
221
|
*/
|
|
222
222
|
page(url: string): void;
|
|
223
|
-
private
|
|
223
|
+
private _page;
|
|
224
224
|
/**
|
|
225
225
|
* Tracks a custom event with optional properties.
|
|
226
226
|
*
|
|
@@ -237,7 +237,7 @@ declare class Altertable {
|
|
|
237
237
|
* ```
|
|
238
238
|
*/
|
|
239
239
|
track(event: string, properties?: EventProperties): void;
|
|
240
|
-
private
|
|
240
|
+
private _track;
|
|
241
241
|
/**
|
|
242
242
|
* Returns the current tracking consent state.
|
|
243
243
|
*
|
|
@@ -254,10 +254,12 @@ declare class Altertable {
|
|
|
254
254
|
*/
|
|
255
255
|
getTrackingConsent(): TrackingConsentType;
|
|
256
256
|
private _flushQueue;
|
|
257
|
+
private _executeQueueItem;
|
|
257
258
|
private _executeCommand;
|
|
258
259
|
private _checkForChanges;
|
|
259
260
|
private _getContext;
|
|
260
261
|
private _processEvent;
|
|
262
|
+
private _sendEvent;
|
|
261
263
|
}
|
|
262
264
|
|
|
263
265
|
declare global {
|
package/dist/index.global.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
/*! @altertable/altertable-js 1.0.
|
|
2
|
-
var Altertable=(()=>{var F=Object.defineProperty;var De=Object.getOwnPropertyDescriptor;var Ae=Object.getOwnPropertyNames;var xe=Object.prototype.hasOwnProperty;var Re=(n,e)=>{for(var t in e)F(n,t,{get:e[t],enumerable:!0})},Pe=(n,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Ae(e))!xe.call(n,i)&&i!==t&&F(n,i,{get:()=>e[i],enumerable:!(s=De(e,i))||s.enumerable});return n};var $e=n=>Pe(F({},"__esModule",{value:!0}),n);var qe={};Re(qe,{TrackingConsent:()=>c,altertable:()=>Z});function ee(n,e){return(...t)=>[n,...t].join(e)}var Ue="atbl",Q=ee(Ue,"."),y=Q("check"),te="session",ne="anonymous",se="device",Ne=1e3*60,ie=100,re=30*Ne,m=1e3,oe=5e3,ae="$pageview",ce="$lib",le="$lib_version",ge="$referer",de="$release",_="$url",ue="$viewport",c={DENIED:"denied",DISMISSED:"dismissed",GRANTED:"granted",PENDING:"pending"},W=["anonymous_id","anonymous","distinct_id","distinctid","false","guest","id","not_authenticated","true","undefined","user_id","user","visitor_id","visitor"],q=new Set(["[object Object]","0","NaN","none","None","null"]);var P=class{_items=[];_maxSize;constructor(e){this._maxSize=e}enqueue(e){this._items.length>=this._maxSize&&this._items.shift(),this._items.push(e)}flush(){let e=[...this._items];return this._items=[],e}clear(){this._items=[]}getSize(){return this._items.length}isFull(){return this._items.length>=this._maxSize}};var D=class extends Error{constructor(e){super(e),this.name="AltertableError"}},v=class extends D{constructor(t,s,i,r,o){super(`HTTP ${t}: ${s}${i?` (${i})`:""}`);this.status=t;this.statusText=s;this.errorCode=i;this.details=r;this.requestContext=o;this.name="ApiError"}},A=class extends D{constructor(t,s){super(t);this.cause=s;this.name="NetworkError"}};function me(n){return n instanceof D}function _e(n){return n instanceof v}function he(n){return n instanceof A}function h(n,e){if(!n)throw new z(`[Altertable] ${typeof e=="function"?e():e}`)}var z=class n extends Error{constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};function pe(n=""){return`https://altertable.ai/dashboard${n}`}function fe(n){return{log:(...e)=>{console.log(`[${n}]`,...e)},logHeader:()=>{let e="Altertable v1.0.4 %c\u2022 Debug mode enabled";$.current[e]||($.current[e]=!0,console.log(e,"color: #64748b;"))},logEvent:(e,{trackingConsent:t})=>{let[s,i]=K(e.event==="$pageview"?"Page":"Track"),[r,o]=Me(e.event==="$pageview"?String(e.properties[_]):e.event),[l,d]=G(e.environment),[g,u]=Ve(e.timestamp),[S,T]=Y(t);console.groupCollapsed(`[${n}] %c${s}%c ${r} %c[${l}] %c${g} %c${S}`,i,o,d,u,T);let[b,k]=p("User ID"),[C,w]=f(e.distinct_id??"Not set"),[Ie,Ee]=p("Anonymous ID"),[Se,Te]=f(e.anonymous_id??"Not set"),[be,ke]=p("Session ID"),[Ce,we]=f(e.session_id??"Not set");console.log(`%c${b} %c${C}`,k,w),console.log(`%c${Ie} %c${Se}`,Ee,Te),console.log(`%c${be} %c${Ce}`,ke,we),console.table(e.properties),console.groupEnd()},logIdentify:(e,{trackingConsent:t})=>{let[s,i]=K("Identify"),[r,o]=G(e.environment),[l,d]=Y(t);console.groupCollapsed(`[${n}] %c${s}%c ${e.distinct_id} %c[${r}] %c${l}`,i,"font-weight: 600;",o,d);let[g,u]=p("Distinct ID"),[S,T]=f(e.distinct_id??"Not set"),[b,k]=p("Anonymous ID"),[C,w]=f(e.anonymous_id??"Not set");console.log(`%c${g} %c${S}`,u,T),console.log(`%c${b} %c${C}`,k,w),console.table(e.traits),console.groupEnd()},logAlias:(e,{trackingConsent:t})=>{let[s,i]=K("Alias"),[r,o]=G(e.environment),[l,d]=Y(t);console.groupCollapsed(`[${n}] %c${s}%c ${e.distinct_id} %c[${r}] %c${l}`,i,"font-weight: 600;",o,d);let[g,u]=p("Distinct ID"),[S,T]=f(e.distinct_id??"Not set"),[b,k]=p("New User ID"),[C,w]=f(e.new_user_id??"Not set");console.log(`%c${g} %c${S}`,u,T),console.log(`%c${b} %c${C}`,k,w),console.groupEnd()},warn:(...e)=>{console.warn(`[${n}]`,...e)},warnDev:(e,...t)=>{return;if(!i){$.current[s]=!0;let r=`[${n}] ${s}`;console.warn(r,...t);try{throw new Error(r)}catch{}}},error:(...e)=>{console.error(`[${n}]`,...e)}}}var $={current:{}};function Le(n){return new Date(n).toLocaleTimeString("en-US",{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"})}function Oe(n){switch(n){case"Page":return"#64748b";case"Identify":return"#a855f7";case"Track":return"#10b981";default:return"#1e293b"}}function K(n){return[n,`background: ${Oe(n)}; color: #ffffff; padding: 2px 8px; border-radius: 6px; font-weight: 400;`]}function Me(n){return[n==="$pageview"?"Page Viewed":n,"font-weight: 600;"]}function G(n){return[n,`color: ${Be(n)}; font-weight: 400;`]}function Be(n){switch(n.toLocaleLowerCase().startsWith("prod")?"production":n){case"production":return"#ef4444";default:return"#3b82f6"}}function Ve(n){return[Le(n),"color: #64748b; font-weight: 400;"]}function p(n){return[n,"color: #64748b; font-size: 11px;"]}function f(n){return[n,'background: #f8fafc; color: #1e293b; padding: 2px 8px; border: 1px solid #e2e8f0; border-radius: 6px; font-family: "SF Mono", "Monaco", monospace; font-size: 11px;']}function Y(n){switch(n){case c.GRANTED:return["",""];case c.DENIED:return["DENIED","background: #ef4444; color: #ffffff; padding: 2px 6px; border-radius: 4px; font-size: 10px; font-weight: 600;"];case c.PENDING:case c.DISMISSED:return["PENDING","background: #f59e0b; color: #ffffff; padding: 2px 6px; border-radius: 4px; font-size: 10px; font-weight: 600;"];default:return["UNKNOWN","background: #6b7280; color: #ffffff; padding: 2px 6px; border-radius: 4px; font-size: 10px; font-weight: 600;"]}}function j(n){try{let e=new URL(n);return{baseUrl:`${e.origin}${e.pathname}`,searchParams:Object.fromEntries(e.searchParams)}}catch{return null}}function ye(){return typeof window<"u"&&typeof navigator<"u"&&typeof navigator.sendBeacon=="function"}var U=class{_config;constructor(e){this._config=e}_constructUrl(e){return`${this._config.baseUrl}${e}?apiKey=${encodeURIComponent(this._config.apiKey)}`}async send(e,t){return ye()?this._sendWithBeacon(e,t):this._sendWithFetch(e,t)}async _sendWithBeacon(e,t){let s=this._constructUrl(e),i=new Blob([JSON.stringify(t)],{type:"application/json"});try{if(!navigator.sendBeacon(s,i))return this._sendWithFetch(e,t)}catch{return this._sendWithFetch(e,t)}}async _sendWithFetch(e,t){let s=this._constructUrl(e),i=new AbortController,r=setTimeout(()=>i.abort(),this._config.requestTimeout);try{let o=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),keepalive:!0,signal:i.signal});if(!o.ok){let l;try{l=await o.json()}catch{}throw new v(o.status,o.statusText,l?.error_code,l,{url:s,method:"POST",payload:t})}}catch(o){throw o instanceof v?o:new A(o instanceof Error?o.message:"Network request failed",o)}finally{clearTimeout(r)}}};function a(n,e=()=>{}){return typeof window>"u"?e():n({window})}function N(){return a(({window:n})=>`${n.innerWidth}x${n.innerHeight}`,()=>null)}function L(){return{timestamp:new Date().toISOString(),url:a(({window:n})=>n.location.href||null,()=>null),referrer:a(({window:n})=>n.document.referrer||null,()=>null),viewport:N()}}function O(n){if(typeof globalThis.crypto<"u"&&typeof globalThis.crypto.randomUUID=="function")try{return`${n}-${crypto.randomUUID()}`}catch{}return`${n}-${Math.random().toString(36).substring(2)}`}var M=class{_defaultTrackingConsent;_logger;_sessionData;_storage;_storageKey;constructor(e){this._storage=e.storage,this._storageKey=e.storageKey,this._logger=e.logger,this._defaultTrackingConsent=e.defaultTrackingConsent??c.PENDING,this._sessionData=this._createDefaultSessionData()}init(){let e=this._storage.getItem(this._storageKey);if(!e){this._sessionData=this._createDefaultSessionData(),this._persistToStorage();return}try{let t=JSON.parse(e);this._sessionData={deviceId:t.deviceId||this._generateDeviceId(),distinctId:t.distinctId||this._generateAnonymousId(),sessionId:t.sessionId||this._generateSessionId(),anonymousId:t.anonymousId||null,lastEventAt:t.lastEventAt||null,trackingConsent:Fe(t.trackingConsent)?t.trackingConsent:this._defaultTrackingConsent}}catch{this._logger.warnDev("Failed to parse storage data. Resetting session data."),this._sessionData=this._createDefaultSessionData()}this._persistToStorage()}getSessionId(){return this._sessionData.sessionId}getDeviceId(){return this._sessionData.deviceId}getDistinctId(){return this._sessionData.distinctId}getAnonymousId(){return this._sessionData.anonymousId}isIdentified(){return!!this._sessionData.anonymousId}getLastEventAt(){return this._sessionData.lastEventAt}getTrackingConsent(){return this._sessionData.trackingConsent}identify(e){this._sessionData.anonymousId=this._sessionData.distinctId,this._sessionData.distinctId=e,this._persistToStorage()}setTrackingConsent(e){this._sessionData.trackingConsent=e,this._persistToStorage()}updateLastEventAt(e){this._sessionData.lastEventAt=e,this._persistToStorage()}renewSessionIfNeeded(){return this._shouldRenewSession()?(this._renewSession(),this._persistToStorage(),!0):!1}reset({resetDeviceId:e=!1,resetTrackingConsent:t=!1}={}){e&&(this._sessionData.deviceId=this._generateDeviceId()),t&&(this._sessionData.trackingConsent=this._defaultTrackingConsent),this._sessionData.sessionId=this._generateSessionId(),this._sessionData.anonymousId=null,this._sessionData.distinctId=this._generateAnonymousId(),this._sessionData.lastEventAt=null,this._persistToStorage()}_createDefaultSessionData(){return{anonymousId:null,deviceId:this._generateDeviceId(),distinctId:this._generateAnonymousId(),lastEventAt:null,sessionId:this._generateSessionId(),trackingConsent:this._defaultTrackingConsent}}_generateSessionId(){return O(te)}_generateDeviceId(){return O(se)}_generateAnonymousId(){return O(ne)}_shouldRenewSession(){let{lastEventAt:e}=this._sessionData;if(!e)return!0;let t=new Date().getTime(),s=new Date(e).getTime();return t-s>re}_renewSession(){this._sessionData.sessionId=this._generateSessionId(),this._sessionData.lastEventAt=null}_persistToStorage(){try{this._storage.setItem(this._storageKey,JSON.stringify(this._sessionData))}catch{this._logger.warnDev("Failed to persist session data to storage.")}}};function Fe(n){return typeof n=="string"&&Object.values(c).includes(n)}function H(n,e,t){for(let s of t){let i=e.getItem(s);i!==null&&(n.setItem(s,i),e.removeItem(s))}}var I=class{store={};getItem(e){return this.store[e]??null}setItem(e,t){this.store[e]=t}removeItem(e){delete this.store[e]}migrate(e,t){H(this,e,t)}},R=class{getItem(e){return a(({window:t})=>{let s=t.document.cookie.match(new RegExp("(^| )"+e+"=([^;]+)"));return s?decodeURIComponent(s[2]):null},()=>null)}setItem(e,t){a(({window:s})=>{s.document.cookie=`${e}=${encodeURIComponent(t)}; path=/;`})}removeItem(e){a(({window:t})=>{t.document.cookie=`${e}=; Max-Age=0; path=/;`})}migrate(e,t){H(this,e,t)}},E=class{constructor(e){this.storage=e}getItem(e){return a(({window:t})=>{try{return t[this.storage].getItem(e)}catch{return null}},()=>null)}setItem(e,t){a(({window:s})=>{try{s[this.storage].setItem(e,t)}catch{}})}removeItem(e){a(({window:t})=>{try{t[this.storage].removeItem(e)}catch{}})}migrate(e,t){H(this,e,t)}},X=class{localStore=new E("localStorage");cookieStore=new R;getItem(e){return this.localStore.getItem(e)??this.cookieStore.getItem(e)}setItem(e,t){this.localStore.setItem(e,t),this.cookieStore.setItem(e,t)}removeItem(e){this.localStore.removeItem(e),this.cookieStore.removeItem(e)}migrate(e,t){for(let s of t){let i=e.getItem(s);i!==null&&(this.localStore.setItem(s,i),this.cookieStore.setItem(s,i))}for(let s of t)e.removeItem(s)}};function x(n){return a(({window:e})=>{try{if(n==="cookie"){e.document.cookie=`${y}=1`;let t=e.document.cookie.indexOf(`${y}=`)!==-1;return e.document.cookie=`${y}=; Max-Age=0`,t}else return e[n].setItem(y,"1"),e[n].removeItem(y),!0}catch{return!1}},()=>!1)}function B(n,e){let{onFallback:t}=e;switch(n){case"localStorage":return x("localStorage")?new E("localStorage"):(t("localStorage not supported, falling back to localStorage+cookie."),B("localStorage+cookie",e));case"localStorage+cookie":{let s=x("localStorage"),i=x("cookie");return s&&i?new X:i?(t("localStorage+cookie not fully supported, falling back to cookie."),new R):s?(t("cookie not supported, falling back to localStorage."),new E("localStorage")):(t("Neither localStorage nor cookie supported, falling back to memory."),new I)}case"sessionStorage":return x("sessionStorage")?new E("sessionStorage"):(t("sessionStorage not supported, falling back to memory."),new I);case"cookie":return x("cookie")?new R:(t("cookie not supported, falling back to memory."),new I);case"memory":return new I;default:throw new Error(`Unknown storage type: "${n}". Valid types are: localStorage, sessionStorage, cookie, memory, localStorage+cookie.`)}}var Qe=[...W,...q].map(n=>`- "${n}"`).join(`
|
|
3
|
-
`),
|
|
4
|
-
${
|
|
1
|
+
/*! @altertable/altertable-js 1.0.6 (UNRELEASED 8b22b09) | MIT License | Altertable | https://github.com/altertable-ai/altertable-js */
|
|
2
|
+
var Altertable=(()=>{var V=Object.defineProperty;var we=Object.getOwnPropertyDescriptor;var Ae=Object.getOwnPropertyNames;var Re=Object.prototype.hasOwnProperty;var Pe=(n,e)=>{for(var t in e)V(n,t,{get:e[t],enumerable:!0})},xe=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ae(e))!Re.call(n,s)&&s!==t&&V(n,s,{get:()=>e[s],enumerable:!(r=we(e,s))||r.enumerable});return n};var $e=n=>xe(V({},"__esModule",{value:!0}),n);var ze={};Pe(ze,{TrackingConsent:()=>o,altertable:()=>Z});function ee(n,e){return(...t)=>[n,...t].join(e)}var Ue="atbl",q=ee(Ue,"."),f=q("check"),te="session",ne="anonymous",re="device",Ne=1e3*60,se=100,ie=30*Ne,F=1e3,oe=5e3,ae="$pageview",ce="$lib",le="$lib_version",ge="$referer",ue="$release",y="$url",de="$viewport",o={DENIED:"denied",DISMISSED:"dismissed",GRANTED:"granted",PENDING:"pending"},Q=["anonymous_id","anonymous","distinct_id","distinctid","false","guest","id","not_authenticated","true","undefined","user_id","user","visitor_id","visitor"],z=new Set(["[object Object]","0","NaN","none","None","null"]);var C=class extends Error{constructor(e){super(e),this.name="AltertableError"}},I=class extends C{constructor(t,r,s,c,i){super(`HTTP ${t}: ${r}${s?` (${s})`:""}`);this.status=t;this.statusText=r;this.errorCode=s;this.details=c;this.requestContext=i;this.name="ApiError"}},D=class extends C{constructor(t,r){super(t);this.cause=r;this.name="NetworkError"}};function pe(n){return n instanceof C}function me(n){return n instanceof I}function _e(n){return n instanceof D}function w(n,e){if(!n)throw new G(`[Altertable] ${typeof e=="function"?e():e}`)}var G=class n extends Error{constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};function he(n=""){return`https://altertable.ai/dashboard${n}`}function fe(n){return{log:(...e)=>{console.log(`[${n}]`,...e)},logHeader:()=>{let e="Altertable v1.0.6 %c\u2022 Debug mode enabled";P.current[e]||(P.current[e]=!0,console.log(e,"color: #64748b;"))},logEvent:(e,{trackingConsent:t})=>{let[r,s]=K(e.event==="$pageview"?"Page":"Track"),[c,i]=Be(e.event==="$pageview"?String(e.properties[y]):e.event),[l,g]=Y(e.environment),[u,p]=Ve(e.timestamp),[d,m]=W(t);console.groupCollapsed(`[${n}] %c${r}%c ${c} %c[${l}] %c${u} %c${d}`,s,i,g,p,m);let[S,T]=_("User ID"),[k,b]=h(e.distinct_id??"Not set"),[ve,Ee]=_("Anonymous ID"),[Se,Te]=h(e.anonymous_id??"Not set"),[ke,be]=_("Session ID"),[Ce,De]=h(e.session_id??"Not set");console.log(`%c${S} %c${k}`,T,b),console.log(`%c${ve} %c${Se}`,Ee,Te),console.log(`%c${ke} %c${Ce}`,be,De),console.table(e.properties),console.groupEnd()},logIdentify:(e,{trackingConsent:t})=>{let[r,s]=K("Identify"),[c,i]=Y(e.environment),[l,g]=W(t);console.groupCollapsed(`[${n}] %c${r}%c ${e.distinct_id} %c[${c}] %c${l}`,s,"font-weight: 600;",i,g);let[u,p]=_("Distinct ID"),[d,m]=h(e.distinct_id??"Not set"),[S,T]=_("Anonymous ID"),[k,b]=h(e.anonymous_id??"Not set");console.log(`%c${u} %c${d}`,p,m),console.log(`%c${S} %c${k}`,T,b),console.table(e.traits),console.groupEnd()},logAlias:(e,{trackingConsent:t})=>{let[r,s]=K("Alias"),[c,i]=Y(e.environment),[l,g]=W(t);console.groupCollapsed(`[${n}] %c${r}%c ${e.distinct_id} %c[${c}] %c${l}`,s,"font-weight: 600;",i,g);let[u,p]=_("Distinct ID"),[d,m]=h(e.distinct_id??"Not set"),[S,T]=_("New User ID"),[k,b]=h(e.new_user_id??"Not set");console.log(`%c${u} %c${d}`,p,m),console.log(`%c${S} %c${k}`,T,b),console.groupEnd()},warn:(...e)=>{console.warn(`[${n}]`,...e)},warnDev:(e,...t)=>{return;if(!s){P.current[r]=!0;let c=`[${n}] ${r}`;console.warn(c,...t);try{throw new Error(c)}catch{}}},error:(...e)=>{console.error(`[${n}]`,...e)}}}var P={current:{}};function Le(n){return new Date(n).toLocaleTimeString("en-US",{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"})}function Oe(n){switch(n){case"Page":return"#64748b";case"Identify":return"#a855f7";case"Track":return"#10b981";default:return"#1e293b"}}function K(n){return[n,`background: ${Oe(n)}; color: #ffffff; padding: 2px 8px; border-radius: 6px; font-weight: 400;`]}function Be(n){return[n==="$pageview"?"Page Viewed":n,"font-weight: 600;"]}function Y(n){return[n,`color: ${Me(n)}; font-weight: 400;`]}function Me(n){switch(n.toLocaleLowerCase().startsWith("prod")?"production":n){case"production":return"#ef4444";default:return"#3b82f6"}}function Ve(n){return[Le(n),"color: #64748b; font-weight: 400;"]}function _(n){return[n,"color: #64748b; font-size: 11px;"]}function h(n){return[n,'background: #f8fafc; color: #1e293b; padding: 2px 8px; border: 1px solid #e2e8f0; border-radius: 6px; font-family: "SF Mono", "Monaco", monospace; font-size: 11px;']}function W(n){switch(n){case o.GRANTED:return["",""];case o.DENIED:return["DENIED","background: #ef4444; color: #ffffff; padding: 2px 6px; border-radius: 4px; font-size: 10px; font-weight: 600;"];case o.PENDING:case o.DISMISSED:return["PENDING","background: #f59e0b; color: #ffffff; padding: 2px 6px; border-radius: 4px; font-size: 10px; font-weight: 600;"];default:return["UNKNOWN","background: #6b7280; color: #ffffff; padding: 2px 6px; border-radius: 4px; font-size: 10px; font-weight: 600;"]}}function X(n){try{let e=new URL(n);return{baseUrl:`${e.origin}${e.pathname}`,searchParams:Object.fromEntries(e.searchParams)}}catch{return null}}var x=class{_items=[];_maxSize;_onDropOldest;constructor(e){this._maxSize=e.capacity,this._onDropOldest=e.onDropOldest}enqueue(e){if(this._items.length>=this._maxSize){let t=this._items.shift();t&&this._onDropOldest?.(t)}this._items.push(e)}flush(){let e=[...this._items];return this._items=[],e}clear(){this._items=[]}getSize(){return this._items.length}getAll(){return this._items}};function ye(){return typeof window<"u"&&typeof navigator<"u"&&typeof navigator.sendBeacon=="function"}var $=class{_config;constructor(e){this._config=e}_constructUrl(e){return`${this._config.baseUrl}${e}?apiKey=${encodeURIComponent(this._config.apiKey)}`}async send(e,t){return ye()?this._sendWithBeacon(e,t):this._sendWithFetch(e,t)}async _sendWithBeacon(e,t){let r=this._constructUrl(e),s=new Blob([JSON.stringify(t)],{type:"application/json"});try{if(!navigator.sendBeacon(r,s))return this._sendWithFetch(e,t)}catch{return this._sendWithFetch(e,t)}}async _sendWithFetch(e,t){let r=this._constructUrl(e),s=new AbortController,c=setTimeout(()=>s.abort(),this._config.requestTimeout);try{let i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),keepalive:!0,signal:s.signal});if(!i.ok){let l;try{l=await i.json()}catch{}throw new I(i.status,i.statusText,l?.error_code,l,{url:r,method:"POST",payload:t})}}catch(i){throw i instanceof I?i:new D(i instanceof Error?i.message:"Network request failed",i)}finally{clearTimeout(c)}}};function a(n,e=()=>{}){return typeof window>"u"?e():n({window})}function U(){return a(({window:n})=>`${n.innerWidth}x${n.innerHeight}`,()=>null)}function N(){return{timestamp:new Date().toISOString(),url:a(({window:n})=>n.location.href||null,()=>null),referrer:a(({window:n})=>n.document.referrer||null,()=>null),viewport:U()}}function L(n){if(typeof globalThis.crypto<"u"&&typeof globalThis.crypto.randomUUID=="function")try{return`${n}-${crypto.randomUUID()}`}catch{}return`${n}-${Math.random().toString(36).substring(2)}`}var O=class{_defaultTrackingConsent;_logger;_sessionData;_storage;_storageKey;constructor(e){this._storage=e.storage,this._storageKey=e.storageKey,this._logger=e.logger,this._defaultTrackingConsent=e.defaultTrackingConsent??o.PENDING,this._sessionData=this._createDefaultSessionData()}init(){let e=this._storage.getItem(this._storageKey);if(!e){this._sessionData=this._createDefaultSessionData(),this._persistToStorage();return}try{let t=JSON.parse(e);this._sessionData={deviceId:t.deviceId||this._generateDeviceId(),distinctId:t.distinctId||this._generateAnonymousId(),sessionId:t.sessionId||this._generateSessionId(),anonymousId:t.anonymousId||null,lastEventAt:t.lastEventAt||null,trackingConsent:qe(t.trackingConsent)?t.trackingConsent:this._defaultTrackingConsent}}catch{this._logger.warnDev("Failed to parse storage data. Resetting session data."),this._sessionData=this._createDefaultSessionData()}this._persistToStorage()}getSessionId(){return this._sessionData.sessionId}getDeviceId(){return this._sessionData.deviceId}getDistinctId(){return this._sessionData.distinctId}getAnonymousId(){return this._sessionData.anonymousId}isIdentified(){return!!this._sessionData.anonymousId}getLastEventAt(){return this._sessionData.lastEventAt}getTrackingConsent(){return this._sessionData.trackingConsent}identify(e){this._sessionData.anonymousId=this._sessionData.distinctId,this._sessionData.distinctId=e,this._persistToStorage()}setTrackingConsent(e){this._sessionData.trackingConsent=e,this._persistToStorage()}updateLastEventAt(e){this._sessionData.lastEventAt=e,this._persistToStorage()}renewSessionIfNeeded(){return this._shouldRenewSession()?(this._renewSession(),this._persistToStorage(),!0):!1}reset({resetDeviceId:e=!1,resetTrackingConsent:t=!1}={}){e&&(this._sessionData.deviceId=this._generateDeviceId()),t&&(this._sessionData.trackingConsent=this._defaultTrackingConsent),this._sessionData.sessionId=this._generateSessionId(),this._sessionData.anonymousId=null,this._sessionData.distinctId=this._generateAnonymousId(),this._sessionData.lastEventAt=null,this._persistToStorage()}_createDefaultSessionData(){return{anonymousId:null,deviceId:this._generateDeviceId(),distinctId:this._generateAnonymousId(),lastEventAt:null,sessionId:this._generateSessionId(),trackingConsent:this._defaultTrackingConsent}}_generateSessionId(){return L(te)}_generateDeviceId(){return L(re)}_generateAnonymousId(){return L(ne)}_shouldRenewSession(){let{lastEventAt:e}=this._sessionData;if(!e)return!0;let t=new Date().getTime(),r=new Date(e).getTime();return t-r>ie}_renewSession(){this._sessionData.sessionId=this._generateSessionId(),this._sessionData.lastEventAt=null}_persistToStorage(){try{this._storage.setItem(this._storageKey,JSON.stringify(this._sessionData))}catch{this._logger.warnDev("Failed to persist session data to storage.")}}};function qe(n){return typeof n=="string"&&Object.values(o).includes(n)}function H(n,e,t){for(let r of t){let s=e.getItem(r);s!==null&&(n.setItem(r,s),e.removeItem(r))}}var v=class{store={};getItem(e){return this.store[e]??null}setItem(e,t){this.store[e]=t}removeItem(e){delete this.store[e]}migrate(e,t){H(this,e,t)}},R=class{getItem(e){return a(({window:t})=>{let r=t.document.cookie.match(new RegExp("(^| )"+e+"=([^;]+)"));return r?decodeURIComponent(r[2]):null},()=>null)}setItem(e,t){a(({window:r})=>{r.document.cookie=`${e}=${encodeURIComponent(t)}; path=/;`})}removeItem(e){a(({window:t})=>{t.document.cookie=`${e}=; Max-Age=0; path=/;`})}migrate(e,t){H(this,e,t)}},E=class{constructor(e){this.storage=e}getItem(e){return a(({window:t})=>{try{return t[this.storage].getItem(e)}catch{return null}},()=>null)}setItem(e,t){a(({window:r})=>{try{r[this.storage].setItem(e,t)}catch{}})}removeItem(e){a(({window:t})=>{try{t[this.storage].removeItem(e)}catch{}})}migrate(e,t){H(this,e,t)}},j=class{localStore=new E("localStorage");cookieStore=new R;getItem(e){return this.localStore.getItem(e)??this.cookieStore.getItem(e)}setItem(e,t){this.localStore.setItem(e,t),this.cookieStore.setItem(e,t)}removeItem(e){this.localStore.removeItem(e),this.cookieStore.removeItem(e)}migrate(e,t){for(let r of t){let s=e.getItem(r);s!==null&&(this.localStore.setItem(r,s),this.cookieStore.setItem(r,s))}for(let r of t)e.removeItem(r)}};function A(n){return a(({window:e})=>{try{if(n==="cookie"){e.document.cookie=`${f}=1`;let t=e.document.cookie.indexOf(`${f}=`)!==-1;return e.document.cookie=`${f}=; Max-Age=0`,t}else return e[n].setItem(f,"1"),e[n].removeItem(f),!0}catch{return!1}},()=>!1)}function B(n,e){let{onFallback:t}=e;switch(n){case"localStorage":return A("localStorage")?new E("localStorage"):(t("localStorage not supported, falling back to localStorage+cookie."),B("localStorage+cookie",e));case"localStorage+cookie":{let r=A("localStorage"),s=A("cookie");return r&&s?new j:s?(t("localStorage+cookie not fully supported, falling back to cookie."),new R):r?(t("cookie not supported, falling back to localStorage."),new E("localStorage")):(t("Neither localStorage nor cookie supported, falling back to memory."),new v)}case"sessionStorage":return A("sessionStorage")?new E("sessionStorage"):(t("sessionStorage not supported, falling back to memory."),new v);case"cookie":return A("cookie")?new R:(t("cookie not supported, falling back to memory."),new v);case"memory":return new v;default:throw new Error(`Unknown storage type: "${n}". Valid types are: localStorage, sessionStorage, cookie, memory, localStorage+cookie.`)}}var Fe=[...Q,...z].map(n=>`- "${n}"`).join(`
|
|
3
|
+
`),Ie=`List of reserved identifiers:
|
|
4
|
+
${Fe}`;function J(n){if(!n||n.trim()==="")throw new Error("User ID cannot be empty or contain only whitespace.");if(Q.some(r=>n.toLowerCase()===r.toLowerCase()))throw new Error(`User ID "${n}" is a reserved identifier and cannot be used.
|
|
5
5
|
|
|
6
|
-
`+
|
|
6
|
+
`+Ie);if(z.has(n))throw new Error(`User ID "${n}" is a reserved identifier and cannot be used.
|
|
7
7
|
|
|
8
|
-
`+
|
|
9
|
-
${
|
|
8
|
+
`+Ie)}var Qe={autoCapture:!0,baseUrl:"https://api.altertable.ai",debug:!1,environment:"production",persistence:"localStorage+cookie",release:void 0,trackingConsent:o.GRANTED},M=class{_cleanupAutoCapture;_config;_queue;_isInitialized=!1;_lastUrl;_logger=fe("Altertable");_referrer;_requester;_sessionManager;_storage;_storageKey;constructor(){this._lastUrl=null,this._referrer=null,this._queue=new x({capacity:F,onDropOldest:e=>{let t=e.type==="command"?e.method:e.eventType;this._logger.warnDev(`Queue is full (${F} items). Dropping ${t} call.`)}})}init(e,t={}){w(e,"Missing API key"),this._config={...Qe,...t},this._storageKey=q(e,this._config.environment),this._referrer=a(({window:s})=>s.document.referrer||null,()=>null),this._lastUrl=a(({window:s})=>s.location.href||null,()=>null),this._storage=B(this._config.persistence,{onFallback:s=>this._logger.warn(s)}),this._requester=new $({baseUrl:this._config.baseUrl,apiKey:e,requestTimeout:oe}),this._sessionManager=new O({storage:this._storage,storageKey:this._storageKey,logger:this._logger,defaultTrackingConsent:this._config.trackingConsent}),this._sessionManager.init(),this._isInitialized=!0,this._config.debug&&this._logger.logHeader();let r=this._sessionManager.getTrackingConsent();return r===o.GRANTED?this._flushQueue():r===o.DENIED&&this._queue.clear(),this._handleAutoCaptureChange(this._config.autoCapture),()=>{this._cleanupAutoCapture?.()}}configure(e){if(w(this._isInitialized,"The client must be initialized with init() before configuring."),e.autoCapture!==void 0&&e.autoCapture!==this._config.autoCapture&&this._handleAutoCaptureChange(e.autoCapture),e.persistence!==void 0&&e.persistence!==this._config.persistence){let r=this._storage;this._storage=B(e.persistence,{onFallback:s=>this._logger.warn(s)}),this._storage.migrate(r,[this._storageKey])}let t=this._sessionManager.getTrackingConsent();e.trackingConsent!==void 0&&e.trackingConsent!==t&&(this._sessionManager.setTrackingConsent(e.trackingConsent),t!==o.GRANTED&&e.trackingConsent===o.GRANTED?this._flushQueue():e.trackingConsent===o.DENIED&&this._queue.clear()),this._config={...this._config,...e}}_handleAutoCaptureChange(e){if(this._cleanupAutoCapture?.(),e){this._lastUrl&&this.page(this._lastUrl);let t=this._checkForChanges.bind(this),r=setInterval(t,se);a(({window:s})=>{s.addEventListener("popstate",t),s.addEventListener("hashchange",t)}),this._cleanupAutoCapture=()=>{clearInterval(r),a(({window:s})=>{s.removeEventListener("popstate",t),s.removeEventListener("hashchange",t)})}}else this._cleanupAutoCapture=void 0}identify(e,t={}){try{J(e)}catch(r){throw new Error(`[Altertable] ${r.message}`)}if(!this._isInitialized){this._queue.enqueue({type:"command",method:"identify",args:[e,{...t}]});return}this._identify(e,{...t})}_identify(e,t={}){w(!this._sessionManager.isIdentified()||e===this._sessionManager.getDistinctId(),`User (${e}) is already identified as a different user (${this._sessionManager.getDistinctId()}). This usually indicates a development issue, as it would merge two separate identities. Call reset() before identifying a new user, or use alias() to link the new ID to the existing one.`),e!==this._sessionManager.getDistinctId()&&this._sessionManager.identify(e);let r=this._getContext(),s={environment:r.environment,device_id:r.device_id,distinct_id:r.distinct_id,traits:t,anonymous_id:r.anonymous_id};if(this._processEvent("identify",s),this._config.debug){let c=this._sessionManager.getTrackingConsent();this._logger.logIdentify(s,{trackingConsent:c})}}alias(e){try{J(e)}catch(t){throw new Error(`[Altertable] ${t.message}`)}if(!this._isInitialized){this._queue.enqueue({type:"command",method:"alias",args:[e]});return}this._alias(e)}_alias(e){let t=this._getContext(),r={environment:t.environment,device_id:t.device_id,anonymous_id:t.anonymous_id,distinct_id:t.distinct_id,new_user_id:e};if(this._processEvent("alias",r),this._config.debug){let s=this._sessionManager.getTrackingConsent();this._logger.logAlias(r,{trackingConsent:s})}}updateTraits(e){if(!this._isInitialized){this._queue.enqueue({type:"command",method:"updateTraits",args:[{...e}]});return}this._updateTraits({...e})}_updateTraits(e){let t=this._getContext();w(t.anonymous_id!==null,"User must be identified with identify() before updating traits.");let r={environment:t.environment,device_id:t.device_id,distinct_id:t.distinct_id,traits:e,anonymous_id:t.anonymous_id,session_id:t.session_id};if(this._processEvent("identify",r),this._config.debug){let s=this._sessionManager.getTrackingConsent();this._logger.logIdentify(r,{trackingConsent:s})}}reset({resetDeviceId:e=!1}={}){this._queue.clear(),this._isInitialized&&this._sessionManager.reset({resetDeviceId:e})}page(e){if(!this._isInitialized){this._queue.enqueue({type:"command",method:"page",runtimeContext:N(),args:[e]});return}this._page(e)}_page(e,t){let r=X(e),s=r?r.baseUrl:e,c=t?.viewport??U(),i=t?.referrer??this._referrer;this._track(ae,{[y]:s,[de]:c,[ge]:i,...r?.searchParams},t)}track(e,t={}){if(!this._isInitialized){this._queue.enqueue({type:"command",method:"track",runtimeContext:N(),args:[e,{...t}]});return}this._track(e,{...t})}_track(e,t,r=N()){this._sessionManager.renewSessionIfNeeded(),this._sessionManager.updateLastEventAt(r.timestamp);let s=this._getContext(),{[y]:c,...i}=t,l=c!==void 0,g=l?null:r.url,u=g?X(g):null,p=u?u.baseUrl:g,d={timestamp:r.timestamp,event:e,environment:s.environment,device_id:s.device_id,distinct_id:s.distinct_id,anonymous_id:s.anonymous_id,session_id:s.session_id,properties:{[ce]:"@altertable/altertable-js",[le]:"1.0.6",[ue]:this._config.release,[y]:l?c:p,...i}};if(this._processEvent("track",d),this._config.debug){let m=this._sessionManager.getTrackingConsent();this._logger.logEvent(d,{trackingConsent:m})}}getTrackingConsent(){return this._isInitialized?this._sessionManager.getTrackingConsent():o.PENDING}_flushQueue(){let e=this._queue.flush();if(e.length!==0){this._config.debug&&this._logger.log(`Processing ${e.length} queued ${e.length===1?"item":"items"}.`);for(let t of e)this._executeQueueItem(t)}}_executeQueueItem(e){if(e.type==="event"){this._sendEvent(e.eventType,e.payload);return}this._executeCommand(e)}_executeCommand(e){try{switch(e.method){case"identify":this._identify(...e.args);break;case"track":this._track(...e.args,e.runtimeContext);break;case"page":this._page(...e.args,e.runtimeContext);break;case"alias":this._alias(...e.args);break;case"updateTraits":this._updateTraits(...e.args);break}}catch(t){let r=t instanceof Error?t.message:String(t);this._logger.warnDev(`Failed to process queued ${e.method}() command:
|
|
9
|
+
${r}`)}}_checkForChanges(){a(({window:e})=>{let t=e.location.href;t!==this._lastUrl&&(this._referrer=this._lastUrl,this._lastUrl=t,this.page(t))})}_getContext(){return{environment:this._config.environment,device_id:this._sessionManager.getDeviceId(),distinct_id:this._sessionManager.getDistinctId(),anonymous_id:this._sessionManager.getAnonymousId(),session_id:this._sessionManager.getSessionId()}}_processEvent(e,t){switch(this._sessionManager.getTrackingConsent()){case o.GRANTED:this._sendEvent(e,t);break;case o.PENDING:case o.DISMISSED:this._queue.enqueue({type:"event",eventType:e,payload:t});break;case o.DENIED:break}}async _sendEvent(e,t){try{await this._requester.send(`/${e}`,t)}catch(r){pe(r)&&this._config.onError?.(r),me(r)&&r.errorCode==="environment-not-found"?this._logger.warnDev(`Environment "${this._config.environment}" not found. Please create this environment in your Altertable dashboard at ${he(`/environments/new?name=${this._config.environment}`)} before tracking events.`):_e(r)?this._logger.error("Network error while sending event",{error:r.message,cause:r.cause,eventType:e}):this._logger.error("Failed to send event",{error:r,eventType:e,payload:t})}}};var Z=new M;a(({window:n})=>{let e=n.Altertable;if(e&&Array.isArray(e))for(let t of e){let r=t[0],s=t.slice(1);Z[r](...s)}n.Altertable=Z});return $e(ze);})();
|
|
10
10
|
//# sourceMappingURL=index.global.js.map
|