@altertable/altertable-js 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 CHANGED
@@ -47,7 +47,7 @@ altertable.alias('new_user_id-019aca6a-1e42-71af-81a0-1e14bbe2ccbd');
47
47
  ## Features
48
48
 
49
49
  - **Automatic page view tracking** – Captures page views automatically
50
- - **Session management** – Handles visitor and session IDs automatically
50
+ - **Session management** – Handles anonymous and session IDs automatically
51
51
  - **Event queuing** – Queues events when offline or consent is pending
52
52
  - **Privacy compliance** – Built-in tracking consent management
53
53
  - **Multiple storage options** – localStorage, cookies, or both
package/dist/index.d.mts CHANGED
@@ -37,8 +37,8 @@ type StorageType = 'localStorage' | 'sessionStorage' | 'cookie' | 'memory' | 'lo
37
37
  type StringWithAutocomplete<T> = T | (string & {});
38
38
  type EventProperties = Record<string, unknown>;
39
39
  type UserId = string;
40
- type DistinctId = StringWithAutocomplete<UserId | VisitorId>;
41
- type VisitorId = `visitor-${string}`;
40
+ type DistinctId = StringWithAutocomplete<UserId | AnonymousId>;
41
+ type AnonymousId = `anonymous-${string}`;
42
42
  type Environment = StringWithAutocomplete<'production' | 'development' | 'staging'>;
43
43
  interface UserTraits extends Record<string, unknown> {
44
44
  email?: string;
@@ -88,7 +88,7 @@ interface AltertableConfig {
88
88
  declare class Altertable {
89
89
  private _cleanupAutoCapture;
90
90
  private _config;
91
- private _eventQueue;
91
+ private _commandQueue;
92
92
  private _isInitialized;
93
93
  private _lastUrl;
94
94
  private _logger;
@@ -148,7 +148,7 @@ declare class Altertable {
148
148
  * });
149
149
  * ```
150
150
  */
151
- identify(userId: string, traits?: UserTraits): void;
151
+ identify(userId: DistinctId, traits?: UserTraits): void;
152
152
  /**
153
153
  * Link a new ID to the current identity.
154
154
  *
@@ -173,6 +173,9 @@ declare class Altertable {
173
173
  * ```
174
174
  */
175
175
  updateTraits(traits: UserTraits): void;
176
+ private _identifyWithContext;
177
+ private _aliasWithContext;
178
+ private _updateTraitsWithContext;
176
179
  /**
177
180
  * Resets device and session IDs.
178
181
  *
@@ -217,6 +220,7 @@ declare class Altertable {
217
220
  * - Server-side tracking where auto-capture isn't available
218
221
  */
219
222
  page(url: string): void;
223
+ private _pageWithContext;
220
224
  /**
221
225
  * Tracks a custom event with optional properties.
222
226
  *
@@ -233,6 +237,7 @@ declare class Altertable {
233
237
  * ```
234
238
  */
235
239
  track(event: string, properties?: EventProperties): void;
240
+ private _trackWithContext;
236
241
  /**
237
242
  * Returns the current tracking consent state.
238
243
  *
@@ -248,6 +253,8 @@ declare class Altertable {
248
253
  * ```
249
254
  */
250
255
  getTrackingConsent(): TrackingConsentType;
256
+ private _flushQueue;
257
+ private _executeCommand;
251
258
  private _checkForChanges;
252
259
  private _getContext;
253
260
  private _processEvent;
package/dist/index.d.ts CHANGED
@@ -37,8 +37,8 @@ type StorageType = 'localStorage' | 'sessionStorage' | 'cookie' | 'memory' | 'lo
37
37
  type StringWithAutocomplete<T> = T | (string & {});
38
38
  type EventProperties = Record<string, unknown>;
39
39
  type UserId = string;
40
- type DistinctId = StringWithAutocomplete<UserId | VisitorId>;
41
- type VisitorId = `visitor-${string}`;
40
+ type DistinctId = StringWithAutocomplete<UserId | AnonymousId>;
41
+ type AnonymousId = `anonymous-${string}`;
42
42
  type Environment = StringWithAutocomplete<'production' | 'development' | 'staging'>;
43
43
  interface UserTraits extends Record<string, unknown> {
44
44
  email?: string;
@@ -88,7 +88,7 @@ interface AltertableConfig {
88
88
  declare class Altertable {
89
89
  private _cleanupAutoCapture;
90
90
  private _config;
91
- private _eventQueue;
91
+ private _commandQueue;
92
92
  private _isInitialized;
93
93
  private _lastUrl;
94
94
  private _logger;
@@ -148,7 +148,7 @@ declare class Altertable {
148
148
  * });
149
149
  * ```
150
150
  */
151
- identify(userId: string, traits?: UserTraits): void;
151
+ identify(userId: DistinctId, traits?: UserTraits): void;
152
152
  /**
153
153
  * Link a new ID to the current identity.
154
154
  *
@@ -173,6 +173,9 @@ declare class Altertable {
173
173
  * ```
174
174
  */
175
175
  updateTraits(traits: UserTraits): void;
176
+ private _identifyWithContext;
177
+ private _aliasWithContext;
178
+ private _updateTraitsWithContext;
176
179
  /**
177
180
  * Resets device and session IDs.
178
181
  *
@@ -217,6 +220,7 @@ declare class Altertable {
217
220
  * - Server-side tracking where auto-capture isn't available
218
221
  */
219
222
  page(url: string): void;
223
+ private _pageWithContext;
220
224
  /**
221
225
  * Tracks a custom event with optional properties.
222
226
  *
@@ -233,6 +237,7 @@ declare class Altertable {
233
237
  * ```
234
238
  */
235
239
  track(event: string, properties?: EventProperties): void;
240
+ private _trackWithContext;
236
241
  /**
237
242
  * Returns the current tracking consent state.
238
243
  *
@@ -248,6 +253,8 @@ declare class Altertable {
248
253
  * ```
249
254
  */
250
255
  getTrackingConsent(): TrackingConsentType;
256
+ private _flushQueue;
257
+ private _executeCommand;
251
258
  private _checkForChanges;
252
259
  private _getContext;
253
260
  private _processEvent;
@@ -1,9 +1,10 @@
1
- /*! @altertable/altertable-js 1.0.3 (UNRELEASED c051861) | MIT License | Altertable | https://github.com/altertable-ai/altertable-js */
2
- var Altertable=(()=>{var V=Object.defineProperty;var we=Object.getOwnPropertyDescriptor;var De=Object.getOwnPropertyNames;var Ae=Object.prototype.hasOwnProperty;var Re=(n,e)=>{for(var t in e)V(n,t,{get:e[t],enumerable:!0})},xe=(n,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of De(e))!Ae.call(n,r)&&r!==t&&V(n,r,{get:()=>e[r],enumerable:!(s=we(e,r))||s.enumerable});return n};var Pe=n=>xe(V({},"__esModule",{value:!0}),n);var ze={};Re(ze,{TrackingConsent:()=>a,altertable:()=>j});function H(n,e){return(...t)=>[n,...t].join(e)}var $e="atbl",B=H($e,"."),f=B("check"),J="session",Z="visitor",ee="device",Ue=1e3*60,te=100,ne=30*Ue,se=1e3,re=5e3,ie="$pageview",oe="$lib",ae="$lib_version",ce="$referer",le="$release",h="$url",ge="$viewport",a={DENIED:"denied",DISMISSED:"dismissed",GRANTED:"granted",PENDING:"pending"},M=["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 w=class extends Error{constructor(e){super(e),this.name="AltertableError"}},m=class extends w{constructor(t,s,r,i,o){super(`HTTP ${t}: ${s}${r?` (${r})`:""}`);this.status=t;this.statusText=s;this.errorCode=r;this.details=i;this.requestContext=o;this.name="ApiError"}},D=class extends w{constructor(t,s){super(t);this.cause=s;this.name="NetworkError"}};function de(n){return n instanceof w}function ue(n){return n instanceof m}function pe(n){return n instanceof D}var x=class{_queue=[];_queueMaxSize;constructor(e){this._queueMaxSize=e}enqueue(e,t,s){this._queue.length>=this._queueMaxSize&&this._queue.shift(),this._queue.push({eventType:e,payload:t,context:s,sentAt:new Date})}flush(){let e=[...this._queue];return this._queue=[],e}clear(){this._queue=[]}getSize(){return this._queue.length}};function g(n,e){if(!n)throw new F(`[Altertable] ${typeof e=="function"?e():e}`)}var F=class n extends Error{constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};function _e(n=""){return`https://altertable.ai/dashboard${n}`}function fe(n){return{log:(...e)=>{console.log(`[${n}]`,...e)},logHeader:()=>{let e="Altertable v1.0.3 %c\u2022 Debug mode enabled";P.current[e]||(P.current[e]=!0,console.log(e,"color: #64748b;"))},logEvent:(e,{trackingConsent:t})=>{let[s,r]=z(e.event==="$pageview"?"Page":"Track"),[i,o]=Oe(e.event==="$pageview"?String(e.properties[h]):e.event),[l,d]=K(e.environment),[u,E]=Be(e.timestamp),[y,S]=G(t);console.groupCollapsed(`[${n}] %c${s}%c ${i} %c[${l}] %c${u} %c${y}`,r,o,d,E,S);let[T,b]=p("User ID"),[k,C]=_(e.distinct_id??"Not set"),[ve,Ee]=p("Visitor ID"),[ye,Se]=_(e.anonymous_id??"Not set"),[Te,be]=p("Session ID"),[ke,Ce]=_(e.session_id??"Not set");console.log(`%c${T} %c${k}`,b,C),console.log(`%c${ve} %c${ye}`,Ee,Se),console.log(`%c${Te} %c${ke}`,be,Ce),console.table(e.properties),console.groupEnd()},logIdentify:(e,{trackingConsent:t})=>{let[s,r]=z("Identify"),[i,o]=K(e.environment),[l,d]=G(t);console.groupCollapsed(`[${n}] %c${s}%c ${e.distinct_id} %c[${i}] %c${l}`,r,"font-weight: 600;",o,d);let[u,E]=p("Distinct ID"),[y,S]=_(e.distinct_id??"Not set"),[T,b]=p("Anonymous ID"),[k,C]=_(e.anonymous_id??"Not set");console.log(`%c${u} %c${y}`,E,S),console.log(`%c${T} %c${k}`,b,C),console.table(e.traits),console.groupEnd()},logAlias:(e,{trackingConsent:t})=>{let[s,r]=z("Alias"),[i,o]=K(e.environment),[l,d]=G(t);console.groupCollapsed(`[${n}] %c${s}%c ${e.distinct_id} %c[${i}] %c${l}`,r,"font-weight: 600;",o,d);let[u,E]=p("Distinct ID"),[y,S]=_(e.distinct_id??"Not set"),[T,b]=p("New User ID"),[k,C]=_(e.new_user_id??"Not set");console.log(`%c${u} %c${y}`,E,S),console.log(`%c${T} %c${k}`,b,C),console.groupEnd()},warn:(...e)=>{console.warn(`[${n}]`,...e)},warnDev:(e,...t)=>{return;if(!r){P.current[s]=!0;let i=`[${n}] ${s}`;console.warn(i,...t);try{throw new Error(i)}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 Ne(n){switch(n){case"Page":return"#64748b";case"Identify":return"#a855f7";case"Track":return"#10b981";default:return"#1e293b"}}function z(n){return[n,`background: ${Ne(n)}; color: #ffffff; padding: 2px 8px; border-radius: 6px; font-weight: 400;`]}function Oe(n){return[n==="$pageview"?"Page Viewed":n,"font-weight: 600;"]}function K(n){return[n,`color: ${Ve(n)}; font-weight: 400;`]}function Ve(n){switch(n.toLocaleLowerCase().startsWith("prod")?"production":n){case"production":return"#ef4444";default:return"#3b82f6"}}function Be(n){return[Le(n),"color: #64748b; font-weight: 400;"]}function p(n){return[n,"color: #64748b; font-size: 11px;"]}function _(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 G(n){switch(n){case a.GRANTED:return["",""];case a.DENIED:return["DENIED","background: #ef4444; color: #ffffff; padding: 2px 6px; border-radius: 4px; font-size: 10px; font-weight: 600;"];case a.PENDING:case a.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 Y(n){try{let e=new URL(n);return{baseUrl:`${e.origin}${e.pathname}`,searchParams:Object.fromEntries(e.searchParams)}}catch{return null}}function he(){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 he()?this._sendWithBeacon(e,t):this._sendWithFetch(e,t)}async _sendWithBeacon(e,t){let s=this._constructUrl(e),r=new Blob([JSON.stringify(t)],{type:"application/json"});try{if(!navigator.sendBeacon(s,r))return this._sendWithFetch(e,t)}catch{return this._sendWithFetch(e,t)}}async _sendWithFetch(e,t){let s=this._constructUrl(e),r=new AbortController,i=setTimeout(()=>r.abort(),this._config.requestTimeout);try{let o=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),keepalive:!0,signal:r.signal});if(!o.ok){let l;try{l=await o.json()}catch{}throw new m(o.status,o.statusText,l?.error_code,l,{url:s,method:"POST",payload:t})}}catch(o){throw o instanceof m?o:new D(o instanceof Error?o.message:"Network request failed",o)}finally{clearTimeout(i)}}};function c(n,e=()=>{}){return typeof window>"u"?e():n({window})}function U(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 L=class{_defaultTrackingConsent;_logger;_sessionData;_storage;_storageKey;constructor(e){this._storage=e.storage,this._storageKey=e.storageKey,this._logger=e.logger,this._defaultTrackingConsent=e.defaultTrackingConsent??a.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._generateVisitorId(),sessionId:t.sessionId||this._generateSessionId(),anonymousId:t.anonymousId||null,lastEventAt:t.lastEventAt||null,trackingConsent:Me(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._generateVisitorId(),this._sessionData.lastEventAt=null,this._persistToStorage()}_createDefaultSessionData(){return{anonymousId:null,deviceId:this._generateDeviceId(),distinctId:this._generateVisitorId(),lastEventAt:null,sessionId:this._generateSessionId(),trackingConsent:this._defaultTrackingConsent}}_generateSessionId(){return U(J)}_generateDeviceId(){return U(ee)}_generateVisitorId(){return U(Z)}_shouldRenewSession(){let{lastEventAt:e}=this._sessionData;if(!e)return!0;let t=new Date().getTime(),s=new Date(e).getTime();return t-s>ne}_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 Me(n){return typeof n=="string"&&Object.values(a).includes(n)}function Q(n,e,t){for(let s of t){let r=e.getItem(s);r!==null&&(n.setItem(s,r),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){Q(this,e,t)}},R=class{getItem(e){return c(({window:t})=>{let s=t.document.cookie.match(new RegExp("(^| )"+e+"=([^;]+)"));return s?decodeURIComponent(s[2]):null},()=>null)}setItem(e,t){c(({window:s})=>{s.document.cookie=`${e}=${encodeURIComponent(t)}; path=/;`})}removeItem(e){c(({window:t})=>{t.document.cookie=`${e}=; Max-Age=0; path=/;`})}migrate(e,t){Q(this,e,t)}},v=class{constructor(e){this.storage=e}getItem(e){return c(({window:t})=>{try{return t[this.storage].getItem(e)}catch{return null}},()=>null)}setItem(e,t){c(({window:s})=>{try{s[this.storage].setItem(e,t)}catch{}})}removeItem(e){c(({window:t})=>{try{t[this.storage].removeItem(e)}catch{}})}migrate(e,t){Q(this,e,t)}},W=class{localStore=new v("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 r=e.getItem(s);r!==null&&(this.localStore.setItem(s,r),this.cookieStore.setItem(s,r))}for(let s of t)e.removeItem(s)}};function A(n){return c(({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 N(n,e){let{onFallback:t}=e;switch(n){case"localStorage":return A("localStorage")?new v("localStorage"):(t("localStorage not supported, falling back to localStorage+cookie."),N("localStorage+cookie",e));case"localStorage+cookie":{let s=A("localStorage"),r=A("cookie");return s&&r?new W:r?(t("localStorage+cookie not fully supported, falling back to cookie."),new R):s?(t("cookie not supported, falling back to localStorage."),new v("localStorage")):(t("Neither localStorage nor cookie supported, falling back to memory."),new I)}case"sessionStorage":return A("sessionStorage")?new v("sessionStorage"):(t("sessionStorage not supported, falling back to memory."),new I);case"cookie":return A("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=[...M,...q].map(n=>`- "${n}"`).join(`
3
- `),me=`List of reserved identifiers:
4
- ${qe}`;function X(n){if(!n||n.trim()==="")throw new Error("User ID cannot be empty or contain only whitespace.");if(M.some(s=>n.toLowerCase()===s.toLowerCase()))throw new Error(`User ID "${n}" is a reserved identifier and cannot be used.
1
+ /*! @altertable/altertable-js 1.0.4 (UNRELEASED a71d553) | MIT License | Altertable | https://github.com/altertable-ai/altertable-js */
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
+ `),ve=`List of reserved identifiers:
4
+ ${Qe}`;function J(n){if(!n||n.trim()==="")throw new Error("User ID cannot be empty or contain only whitespace.");if(W.some(s=>n.toLowerCase()===s.toLowerCase()))throw new Error(`User ID "${n}" is a reserved identifier and cannot be used.
5
5
 
6
- `+me);if(q.has(n))throw new Error(`User ID "${n}" is a reserved identifier and cannot be used.
6
+ `+ve);if(q.has(n))throw new Error(`User ID "${n}" is a reserved identifier and cannot be used.
7
7
 
8
- `+me)}function Ie(){return c(({window:n})=>`${n.innerWidth}x${n.innerHeight}`,()=>null)}var Fe={autoCapture:!0,baseUrl:"https://api.altertable.ai",debug:!1,environment:"production",persistence:"localStorage+cookie",release:void 0,trackingConsent:a.GRANTED},O=class{_cleanupAutoCapture;_config;_eventQueue;_isInitialized=!1;_lastUrl;_logger=fe("Altertable");_referrer;_requester;_sessionManager;_storage;_storageKey;constructor(){this._lastUrl=null,this._referrer=null,this._eventQueue=new x(se)}init(e,t={}){return g(e,"Missing API key"),this._config={...Fe,...t},this._storageKey=B(e,this._config.environment),this._referrer=c(({window:s})=>s.document.referrer||null,()=>null),this._lastUrl=c(({window:s})=>s.location.href||null,()=>null),this._storage=N(this._config.persistence,{onFallback:s=>this._logger.warn(s)}),this._requester=new $({baseUrl:this._config.baseUrl,apiKey:e,requestTimeout:re}),this._sessionManager=new L({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(),this._handleAutoCaptureChange(this._config.autoCapture),()=>{this._cleanupAutoCapture?.()}}configure(e){if(g(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 s=this._storage;this._storage=N(e.persistence,{onFallback:r=>this._logger.warn(r)}),this._storage.migrate(s,[this._storageKey])}let t=this._sessionManager.getTrackingConsent();if(e.trackingConsent!==void 0&&e.trackingConsent!==t)if(this._sessionManager.setTrackingConsent(e.trackingConsent),t!==a.GRANTED&&e.trackingConsent===a.GRANTED){let s=this._eventQueue.flush();s.length>0&&s.forEach(r=>{this._processEvent(r.eventType,r.payload,r.context)})}else e.trackingConsent===a.DENIED&&this._eventQueue.clear();this._config={...this._config,...e}}_handleAutoCaptureChange(e){if(this._cleanupAutoCapture?.(),e){this._lastUrl&&this.page(this._lastUrl);let t=this._checkForChanges.bind(this),s=setInterval(t,te);c(({window:r})=>{r.addEventListener("popstate",t),r.addEventListener("hashchange",t)}),this._cleanupAutoCapture=()=>{clearInterval(s),c(({window:r})=>{r.removeEventListener("popstate",t),r.removeEventListener("hashchange",t)})}}else this._cleanupAutoCapture=void 0}identify(e,t={}){g(this._isInitialized,"The client must be initialized with init() before identifying users."),g(!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.`);try{X(e)}catch(i){throw new Error(`[Altertable] ${i.message}`)}e!==this._sessionManager.getDistinctId()&&this._sessionManager.identify(e);let s=this._getContext(),r={environment:s.environment,device_id:s.device_id,distinct_id:s.distinct_id,traits:t,anonymous_id:s.anonymous_id};if(this._processEvent("identify",r,s),this._config.debug){let i=this._sessionManager.getTrackingConsent();this._logger.logIdentify(r,{trackingConsent:i})}}alias(e){g(this._isInitialized,"The client must be initialized with init() before aliasing users.");try{X(e)}catch(r){throw new Error(`[Altertable] ${r.message}`)}let t=this._getContext(),s={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",s,t),this._config.debug){let r=this._sessionManager.getTrackingConsent();this._logger.logAlias(s,{trackingConsent:r})}}updateTraits(e){let t=this._getContext();g(t.anonymous_id!==null,"User must be identified with identify() before updating traits.");let s={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",s,t),this._config.debug){let r=this._sessionManager.getTrackingConsent();this._logger.logIdentify(s,{trackingConsent:r})}}reset({resetDeviceId:e=!1}={}){g(this._isInitialized,"The client must be initialized with init() before resetting."),this._sessionManager.reset({resetDeviceId:e})}page(e){g(this._isInitialized,"The client must be initialized with init() before tracking page views.");let t=Y(e),s=t?t.baseUrl:e;this.track(ie,{[h]:s,[ge]:Ie(),[ce]:this._referrer,...t?.searchParams})}track(e,t={}){g(this._isInitialized,"The client must be initialized with init() before tracking events."),this._sessionManager.renewSessionIfNeeded();let s=new Date().toISOString();this._sessionManager.updateLastEventAt(s);let r=this._getContext(),i={timestamp:s,event:e,environment:r.environment,device_id:r.device_id,distinct_id:r.distinct_id,anonymous_id:r.anonymous_id,session_id:r.session_id,properties:{[oe]:"@altertable/altertable-js",[ae]:"1.0.3",[le]:this._config.release,...t[h]===void 0&&(()=>{let o=c(({window:u})=>u.location.href||null,()=>null),l=Y(o),d=l?l.baseUrl:o;return{[h]:d}})(),...t}};if(this._processEvent("track",i,r),this._config.debug){let o=this._sessionManager.getTrackingConsent();this._logger.logEvent(i,{trackingConsent:o})}}getTrackingConsent(){return this._sessionManager.getTrackingConsent()}_checkForChanges(){c(({window:e})=>{let t=e.location.href;t!==this._lastUrl&&(this.page(t),this._referrer=this._lastUrl,this._lastUrl=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()}}async _processEvent(e,t,s){switch(this._sessionManager.getTrackingConsent()){case a.GRANTED:try{await this._requester.send(`/${e}`,t)}catch(i){de(i)&&this._config.onError?.(i),ue(i)&&i.errorCode==="environment-not-found"?this._logger.warnDev(`Environment "${this._config.environment}" not found. Please create this environment in your Altertable dashboard at ${_e(`/environments/new?name=${this._config.environment}`)} before tracking events.`):pe(i)?this._logger.error("Network error while sending event",{error:i.message,cause:i.cause,eventType:e}):this._logger.error("Failed to send event",{error:i,eventType:e,payload:t})}break;case a.PENDING:case a.DISMISSED:this._eventQueue.enqueue(e,t,s);break;case a.DENIED:break}}};var j=new O;c(({window:n})=>{let e=n.Altertable;if(e&&Array.isArray(e))for(let t of e){let s=t[0],r=t.slice(1);j[s](...r)}n.Altertable=j});return Pe(ze);})();
8
+ `+ve)}var We={autoCapture:!0,baseUrl:"https://api.altertable.ai",debug:!1,environment:"production",persistence:"localStorage+cookie",release:void 0,trackingConsent:c.GRANTED},V=class{_cleanupAutoCapture;_config;_commandQueue;_isInitialized=!1;_lastUrl;_logger=fe("Altertable");_referrer;_requester;_sessionManager;_storage;_storageKey;constructor(){this._lastUrl=null,this._referrer=null,this._commandQueue=new P(m)}init(e,t={}){return h(e,"Missing API key"),this._config={...We,...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 U({baseUrl:this._config.baseUrl,apiKey:e,requestTimeout:oe}),this._sessionManager=new M({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(),this._flushQueue(),this._handleAutoCaptureChange(this._config.autoCapture),()=>{this._cleanupAutoCapture?.()}}configure(e){if(h(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 s=this._storage;this._storage=B(e.persistence,{onFallback:i=>this._logger.warn(i)}),this._storage.migrate(s,[this._storageKey])}let t=this._sessionManager.getTrackingConsent();e.trackingConsent!==void 0&&e.trackingConsent!==t&&(this._sessionManager.setTrackingConsent(e.trackingConsent),t!==c.GRANTED&&e.trackingConsent===c.GRANTED?this._flushQueue():e.trackingConsent===c.DENIED&&this._commandQueue.clear()),this._config={...this._config,...e}}_handleAutoCaptureChange(e){if(this._cleanupAutoCapture?.(),e){this._lastUrl&&this.page(this._lastUrl);let t=this._checkForChanges.bind(this),s=setInterval(t,ie);a(({window:i})=>{i.addEventListener("popstate",t),i.addEventListener("hashchange",t)}),this._cleanupAutoCapture=()=>{clearInterval(s),a(({window:i})=>{i.removeEventListener("popstate",t),i.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){if(this._commandQueue.isFull()){this._logger.warnDev(`Queue is full (${m} commands). Dropping identify("${e}") call.`);return}this._commandQueue.enqueue({method:"identify",args:[e,{...t}]});return}h(!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 s=this._getContext(),i={environment:s.environment,device_id:s.device_id,distinct_id:s.distinct_id,traits:t,anonymous_id:s.anonymous_id};if(this._processEvent("identify",i,{method:"identify",args:[e,t]}),this._config.debug){let r=this._sessionManager.getTrackingConsent();this._logger.logIdentify(i,{trackingConsent:r})}}alias(e){try{J(e)}catch(i){throw new Error(`[Altertable] ${i.message}`)}if(!this._isInitialized){if(this._commandQueue.isFull()){this._logger.warnDev(`Queue is full (${m} commands). Dropping alias("${e}") call.`);return}this._commandQueue.enqueue({method:"alias",args:[e]});return}let t=this._getContext(),s={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",s,{method:"alias",args:[e]}),this._config.debug){let i=this._sessionManager.getTrackingConsent();this._logger.logAlias(s,{trackingConsent:i})}}updateTraits(e){if(!this._isInitialized){if(this._commandQueue.isFull()){this._logger.warnDev(`Queue is full (${m} commands). Dropping updateTraits() call.`);return}this._commandQueue.enqueue({method:"updateTraits",args:[{...e}]});return}let t=this._getContext();h(t.anonymous_id!==null,"User must be identified with identify() before updating traits.");let s={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",s,{method:"updateTraits",args:[e]}),this._config.debug){let i=this._sessionManager.getTrackingConsent();this._logger.logIdentify(s,{trackingConsent:i})}}_identifyWithContext(e,t={}){h(!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 s=this._getContext(),i={environment:s.environment,device_id:s.device_id,distinct_id:s.distinct_id,traits:t,anonymous_id:s.anonymous_id};if(this._processEvent("identify",i,{method:"identify",args:[e,t]}),this._config.debug){let r=this._sessionManager.getTrackingConsent();this._logger.logIdentify(i,{trackingConsent:r})}}_aliasWithContext(e){let t=this._getContext(),s={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",s,{method:"alias",args:[e]}),this._config.debug){let i=this._sessionManager.getTrackingConsent();this._logger.logAlias(s,{trackingConsent:i})}}_updateTraitsWithContext(e){let t=this._getContext();h(t.anonymous_id!==null,"User must be identified with identify() before updating traits.");let s={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",s,{method:"updateTraits",args:[e]}),this._config.debug){let i=this._sessionManager.getTrackingConsent();this._logger.logIdentify(s,{trackingConsent:i})}}reset({resetDeviceId:e=!1}={}){if(!this._isInitialized){this._commandQueue.clear();return}this._sessionManager.reset({resetDeviceId:e})}page(e){if(!this._isInitialized){if(this._commandQueue.isFull()){this._logger.warnDev(`Queue is full (${m} commands). Dropping page("${e}") call.`);return}this._commandQueue.enqueue({method:"page",runtimeContext:L(),args:[e]});return}this._pageWithContext(e)}_pageWithContext(e,t){let s=j(e),i=s?s.baseUrl:e,r=t?.viewport??N(),o=t?.referrer??this._referrer;this._trackWithContext(ae,{[_]:i,[ue]:r,[ge]:o,...s?.searchParams},t)}track(e,t={}){if(!this._isInitialized){if(this._commandQueue.isFull()){this._logger.warnDev(`Queue is full (${m} commands). Dropping track("${e}") event.`);return}this._commandQueue.enqueue({method:"track",runtimeContext:L(),args:[e,{...t}]});return}this._trackWithContext(e,t)}_trackWithContext(e,t,s=L()){this._sessionManager.renewSessionIfNeeded(),this._sessionManager.updateLastEventAt(s.timestamp);let i=this._getContext(),o=Object.prototype.hasOwnProperty.call(t,_)&&t[_]!==void 0?null:s.url,l=o?j(o):null,d=l?l.baseUrl:o,g={timestamp:s.timestamp,event:e,environment:i.environment,device_id:i.device_id,distinct_id:i.distinct_id,anonymous_id:i.anonymous_id,session_id:i.session_id,properties:{[ce]:"@altertable/altertable-js",[le]:"1.0.4",[de]:this._config.release,[_]:d,...t}};if(this._processEvent("track",g,{method:"track",args:[e,t],runtimeContext:s}),this._config.debug){let u=this._sessionManager.getTrackingConsent();this._logger.logEvent(g,{trackingConsent:u})}}getTrackingConsent(){return this._isInitialized?this._sessionManager.getTrackingConsent():c.PENDING}_flushQueue(){let e=this._commandQueue.flush();if(e.length!==0){this._config.debug&&this._logger.log(`Processing ${e.length} queued ${e.length===1?"command":"commands"}.`);for(let t of e)this._executeCommand(t)}}_executeCommand(e){try{switch(e.method){case"identify":this._identifyWithContext(...e.args);break;case"track":this._trackWithContext(...e.args,e.runtimeContext);break;case"page":this._pageWithContext(...e.args,e.runtimeContext);break;case"alias":this._aliasWithContext(...e.args);break;case"updateTraits":this._updateTraitsWithContext(...e.args);break}}catch(t){let s=t instanceof Error?t.message:String(t);this._logger.warnDev(`Failed to process queued ${e.method}() command:
9
+ ${s}`)}}_checkForChanges(){a(({window:e})=>{let t=e.location.href;t!==this._lastUrl&&(this.page(t),this._referrer=this._lastUrl,this._lastUrl=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()}}async _processEvent(e,t,s){switch(this._sessionManager.getTrackingConsent()){case c.GRANTED:try{await this._requester.send(`/${e}`,t)}catch(r){me(r)&&this._config.onError?.(r),_e(r)&&r.errorCode==="environment-not-found"?this._logger.warnDev(`Environment "${this._config.environment}" not found. Please create this environment in your Altertable dashboard at ${pe(`/environments/new?name=${this._config.environment}`)} before tracking events.`):he(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})}break;case c.PENDING:case c.DISMISSED:this._commandQueue.enqueue(s);break;case c.DENIED:break}}};var Z=new V;a(({window:n})=>{let e=n.Altertable;if(e&&Array.isArray(e))for(let t of e){let s=t[0],i=t.slice(1);Z[s](...i)}n.Altertable=Z});return $e(qe);})();
9
10
  //# sourceMappingURL=index.global.js.map