@product-intelligence-hub/sdk-web 0.1.3 → 0.3.0
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 +102 -5
- package/dist/hooks.cjs +2 -0
- package/dist/hooks.cjs.map +1 -0
- package/dist/hooks.d.cts +32 -0
- package/dist/hooks.d.ts +32 -0
- package/dist/hooks.js +2 -0
- package/dist/hooks.js.map +1 -0
- package/dist/index.cjs +2 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +40 -2
- package/dist/index.d.ts +40 -2
- package/dist/index.global.js +36 -2
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/package.json +25 -2
package/dist/index.d.cts
CHANGED
|
@@ -1,5 +1,36 @@
|
|
|
1
1
|
import { PIHClient, PIHConfig, StorageAdapter } from '@product-intelligence-hub/sdk-core';
|
|
2
|
-
export { AutocaptureConfig, PIHConfig, PIHError, PIHErrorCode, TrackEvent, TrackOptions, TransportOptions } from '@product-intelligence-hub/sdk-core';
|
|
2
|
+
export { AutocaptureConfig, FeatureFlagConfig, FeatureFlags, PIHConfig, PIHError, PIHErrorCode, TrackEvent, TrackOptions, TransportOptions } from '@product-intelligence-hub/sdk-core';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Notify all subscribers of flag changes.
|
|
6
|
+
* Call this after refreshFlags() completes.
|
|
7
|
+
*/
|
|
8
|
+
declare function notifyFlagListeners(): void;
|
|
9
|
+
/**
|
|
10
|
+
* React hook to check if a feature flag is enabled.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```tsx
|
|
14
|
+
* function MyComponent() {
|
|
15
|
+
* const isEnabled = useFeatureFlag("enable_ai_chat");
|
|
16
|
+
* if (!isEnabled) return null;
|
|
17
|
+
* return <AIChatWidget />;
|
|
18
|
+
* }
|
|
19
|
+
* ```
|
|
20
|
+
*/
|
|
21
|
+
declare function useFeatureFlag(key: string, defaultValue?: boolean): boolean;
|
|
22
|
+
/**
|
|
23
|
+
* React hook to get all feature flags.
|
|
24
|
+
*
|
|
25
|
+
* @example
|
|
26
|
+
* ```tsx
|
|
27
|
+
* function FlagDebugPanel() {
|
|
28
|
+
* const flags = useFeatureFlags();
|
|
29
|
+
* return <pre>{JSON.stringify(flags, null, 2)}</pre>;
|
|
30
|
+
* }
|
|
31
|
+
* ```
|
|
32
|
+
*/
|
|
33
|
+
declare function useFeatureFlags(): Record<string, boolean>;
|
|
3
34
|
|
|
4
35
|
/**
|
|
5
36
|
* Web-specific PIH configuration
|
|
@@ -15,7 +46,14 @@ interface WebPIHConfig extends Omit<PIHConfig, "platform"> {
|
|
|
15
46
|
declare class WebPIHClient extends PIHClient {
|
|
16
47
|
private autocapture;
|
|
17
48
|
private beacon;
|
|
49
|
+
private performanceTracker;
|
|
50
|
+
private engagementTracker;
|
|
51
|
+
private errorTracker;
|
|
18
52
|
constructor(config: WebPIHConfig, storage?: StorageAdapter);
|
|
53
|
+
/**
|
|
54
|
+
* Return browser context for every event
|
|
55
|
+
*/
|
|
56
|
+
protected getContext(): Record<string, unknown>;
|
|
19
57
|
/**
|
|
20
58
|
* Initialize the web client
|
|
21
59
|
*/
|
|
@@ -57,4 +95,4 @@ declare const PIH: {
|
|
|
57
95
|
WebPIHClient: typeof WebPIHClient;
|
|
58
96
|
};
|
|
59
97
|
|
|
60
|
-
export { WebPIHClient, type WebPIHConfig, PIH as default, getInstance, init, resetInstance };
|
|
98
|
+
export { WebPIHClient, type WebPIHConfig, PIH as default, getInstance, init, notifyFlagListeners, resetInstance, useFeatureFlag, useFeatureFlags };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,36 @@
|
|
|
1
1
|
import { PIHClient, PIHConfig, StorageAdapter } from '@product-intelligence-hub/sdk-core';
|
|
2
|
-
export { AutocaptureConfig, PIHConfig, PIHError, PIHErrorCode, TrackEvent, TrackOptions, TransportOptions } from '@product-intelligence-hub/sdk-core';
|
|
2
|
+
export { AutocaptureConfig, FeatureFlagConfig, FeatureFlags, PIHConfig, PIHError, PIHErrorCode, TrackEvent, TrackOptions, TransportOptions } from '@product-intelligence-hub/sdk-core';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Notify all subscribers of flag changes.
|
|
6
|
+
* Call this after refreshFlags() completes.
|
|
7
|
+
*/
|
|
8
|
+
declare function notifyFlagListeners(): void;
|
|
9
|
+
/**
|
|
10
|
+
* React hook to check if a feature flag is enabled.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```tsx
|
|
14
|
+
* function MyComponent() {
|
|
15
|
+
* const isEnabled = useFeatureFlag("enable_ai_chat");
|
|
16
|
+
* if (!isEnabled) return null;
|
|
17
|
+
* return <AIChatWidget />;
|
|
18
|
+
* }
|
|
19
|
+
* ```
|
|
20
|
+
*/
|
|
21
|
+
declare function useFeatureFlag(key: string, defaultValue?: boolean): boolean;
|
|
22
|
+
/**
|
|
23
|
+
* React hook to get all feature flags.
|
|
24
|
+
*
|
|
25
|
+
* @example
|
|
26
|
+
* ```tsx
|
|
27
|
+
* function FlagDebugPanel() {
|
|
28
|
+
* const flags = useFeatureFlags();
|
|
29
|
+
* return <pre>{JSON.stringify(flags, null, 2)}</pre>;
|
|
30
|
+
* }
|
|
31
|
+
* ```
|
|
32
|
+
*/
|
|
33
|
+
declare function useFeatureFlags(): Record<string, boolean>;
|
|
3
34
|
|
|
4
35
|
/**
|
|
5
36
|
* Web-specific PIH configuration
|
|
@@ -15,7 +46,14 @@ interface WebPIHConfig extends Omit<PIHConfig, "platform"> {
|
|
|
15
46
|
declare class WebPIHClient extends PIHClient {
|
|
16
47
|
private autocapture;
|
|
17
48
|
private beacon;
|
|
49
|
+
private performanceTracker;
|
|
50
|
+
private engagementTracker;
|
|
51
|
+
private errorTracker;
|
|
18
52
|
constructor(config: WebPIHConfig, storage?: StorageAdapter);
|
|
53
|
+
/**
|
|
54
|
+
* Return browser context for every event
|
|
55
|
+
*/
|
|
56
|
+
protected getContext(): Record<string, unknown>;
|
|
19
57
|
/**
|
|
20
58
|
* Initialize the web client
|
|
21
59
|
*/
|
|
@@ -57,4 +95,4 @@ declare const PIH: {
|
|
|
57
95
|
WebPIHClient: typeof WebPIHClient;
|
|
58
96
|
};
|
|
59
97
|
|
|
60
|
-
export { WebPIHClient, type WebPIHConfig, PIH as default, getInstance, init, resetInstance };
|
|
98
|
+
export { WebPIHClient, type WebPIHConfig, PIH as default, getInstance, init, notifyFlagListeners, resetInstance, useFeatureFlag, useFeatureFlags };
|
package/dist/index.global.js
CHANGED
|
@@ -1,3 +1,37 @@
|
|
|
1
|
-
var PIH=(function(exports){'use strict';var O=Object.defineProperty;var C=(n,t,e)=>t in n?O(n,t,{enumerable:true,configurable:true,writable:true,value:e}):n[t]=e;var s=(n,t,e)=>C(n,typeof t!="symbol"?t+"":t,e);var a=class n extends Error{constructor(e,i,r){super(e);s(this,"code");s(this,"details");this.name="PIHError",this.code=i,this.details=r,Error.captureStackTrace&&Error.captureStackTrace(this,n);}static networkError(e,i){return new n(e,"NETWORK_ERROR",i)}static invalidConfig(e,i){return new n(e,"INVALID_CONFIG",i)}static queueFull(e,i){return new n(e,"QUEUE_FULL",i)}static rateLimited(e,i){return new n(e,"RATE_LIMITED",i)}static invalidPayload(e,i){return new n(e,"INVALID_PAYLOAD",i)}static storageError(e,i){return new n(e,"STORAGE_ERROR",i)}static sessionError(e,i){return new n(e,"SESSION_ERROR",i)}static fromUnknown(e){return e instanceof n?e:e instanceof Error?new n(e.message,"UNKNOWN_ERROR",e):new n(String(e),"UNKNOWN_ERROR",e)}};function g(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function"){let n=new Uint8Array(16);crypto.getRandomValues(n),n[6]=n[6]&15|64,n[8]=n[8]&63|128;let t=Array.from(n,e=>e.toString(16).padStart(2,"0")).join("");return `${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{let t=Math.random()*16|0;return (n==="x"?t:t&3|8).toString(16)})}function T(){return new Date().toISOString()}function A(n){return n.toISOString()}function U(n,t=1e3,e=16e3){let i=t*Math.pow(2,n);return Math.min(i,e)}var f="pih_",u={QUEUE:`${f}queue`,ANONYMOUS_ID:`${f}anonymous_id`,USER_ID:`${f}user_id`,USER_TRAITS:`${f}user_traits`,SESSION_ID:`${f}session_id`,SESSION_LAST_ACTIVITY:`${f}session_last_activity`},h={API_URL:"https://repoingest-production.up.railway.app",FLUSH_INTERVAL:1e4,FLUSH_AT:25,MAX_QUEUE_SIZE:5e3,SESSION_TIMEOUT:18e5,MAX_BATCH_SIZE:100,MAX_RETRIES:5,BASE_BACKOFF_DELAY:1e3,MAX_BACKOFF_DELAY:16e3};var m=class{constructor(t,e=false){s(this,"anonymousId");s(this,"userId",null);s(this,"userTraits",{});s(this,"storage");s(this,"debug");this.storage=t,this.debug=e,this.anonymousId=g();}async initialize(){if(!this.storage){this.log("No storage adapter, using in-memory identity only");return}try{let t=await this.storage.get(u.ANONYMOUS_ID);t?(this.anonymousId=t,this.log("Loaded anonymous ID from storage:",this.anonymousId)):(await this.storage.set(u.ANONYMOUS_ID,this.anonymousId),this.log("Generated new anonymous ID:",this.anonymousId));let e=await this.storage.get(u.USER_ID);e&&(this.userId=e,this.log("Loaded user ID from storage:",this.userId));let i=await this.storage.get(u.USER_TRAITS);if(i)try{this.userTraits=JSON.parse(i),this.log("Loaded user traits from storage:",this.userTraits);}catch{this.log("Failed to parse stored user traits");}}catch(t){this.log("Error loading identity from storage:",t);}}getAnonymousId(){return this.anonymousId}getUserId(){return this.userId}getUserTraits(){return {...this.userTraits}}async setUserId(t){if(this.userId=t,this.log("Set user ID:",t),this.storage)try{await this.storage.set(u.USER_ID,t);}catch(e){this.log("Error persisting user ID:",e);}}async setUserTraits(t){if(this.userTraits={...this.userTraits,...t},this.log("Set user traits:",this.userTraits),this.storage)try{await this.storage.set(u.USER_TRAITS,JSON.stringify(this.userTraits));}catch(e){this.log("Error persisting user traits:",e);}}async reset(){if(this.anonymousId=g(),this.userId=null,this.userTraits={},this.log("Identity reset, new anonymous ID:",this.anonymousId),this.storage)try{await Promise.all([this.storage.set(u.ANONYMOUS_ID,this.anonymousId),this.storage.remove(u.USER_ID),this.storage.remove(u.USER_TRAITS)]);}catch(t){this.log("Error resetting identity in storage:",t);}}setDebug(t){this.debug=t;}log(...t){this.debug&&[...t];}};var y=class{constructor(t,e=h.SESSION_TIMEOUT,i={},r=false){s(this,"sessionId",null);s(this,"sessionStartTime",0);s(this,"lastActivity",0);s(this,"timeout");s(this,"storage");s(this,"callbacks");s(this,"debug");this.storage=t,this.timeout=e,this.callbacks=i,this.debug=r;}async initialize(){if(!this.storage){this.log("No storage adapter, using in-memory session only");return}try{let t=await this.storage.get(u.SESSION_ID),e=await this.storage.get(u.SESSION_LAST_ACTIVITY);if(t&&e){let i=parseInt(e,10);Date.now()-i<this.timeout?(this.sessionId=t,this.lastActivity=i,this.sessionStartTime=i,this.log("Restored session from storage:",this.sessionId)):(this.log("Stored session expired, will start new session"),await this.clearStoredSession());}}catch(t){this.log("Error loading session from storage:",t);}}getSessionId(){let t=Date.now();return this.sessionId&&t-this.lastActivity>this.timeout&&this.endSession(),this.sessionId||this.startSession(),this.lastActivity=t,this.persistLastActivity(),this.sessionId}touch(){this.sessionId&&(this.lastActivity=Date.now(),this.persistLastActivity());}hasActiveSession(){return this.sessionId?Date.now()-this.lastActivity<this.timeout:false}getCurrentSessionId(){return this.sessionId}getSessionDuration(){return this.sessionId?Date.now()-this.sessionStartTime:0}startSession(){let t=Date.now();this.sessionId=g(),this.sessionStartTime=t,this.lastActivity=t,this.log("Started new session:",this.sessionId),this.persistSession(),this.callbacks.onSessionStart?.(this.sessionId);}endSession(){if(!this.sessionId)return;let t=this.getSessionDuration(),e=this.sessionId;this.log("Ended session:",e,"duration:",t),this.sessionId=null,this.sessionStartTime=0,this.lastActivity=0,this.clearStoredSession(),this.callbacks.onSessionEnd?.(e,t);}forceEndSession(){this.sessionId&&this.endSession();}setDebug(t){this.debug=t;}setTimeout(t){this.timeout=t;}async persistSession(){if(!(!this.storage||!this.sessionId))try{await Promise.all([this.storage.set(u.SESSION_ID,this.sessionId),this.storage.set(u.SESSION_LAST_ACTIVITY,String(this.lastActivity))]);}catch(t){this.log("Error persisting session:",t);}}async persistLastActivity(){if(this.storage)try{await this.storage.set(u.SESSION_LAST_ACTIVITY,String(this.lastActivity));}catch(t){this.log("Error persisting last activity:",t);}}async clearStoredSession(){if(this.storage)try{await Promise.all([this.storage.remove(u.SESSION_ID),this.storage.remove(u.SESSION_LAST_ACTIVITY)]);}catch(t){this.log("Error clearing stored session:",t);}}log(...t){this.debug&&[...t];}};var I=class{constructor(t){s(this,"apiUrl");s(this,"apiKey");s(this,"tenantId");s(this,"debug");this.apiUrl=t.apiUrl.replace(/\/$/,""),this.apiKey=t.apiKey,this.tenantId=t.tenantId,this.debug=t.debug??false;}async sendEvents(t,e){let i=`${this.apiUrl}/v1/track`,r=t.map(o=>this.toTrackApiPayload(o)),l=JSON.stringify({events:r});if(this.log("Sending",t.length,"events to",i),e?.useBeacon&&typeof navigator<"u"&&typeof navigator.sendBeacon=="function"&&this.sendViaBeacon(i,l))return this.log("Events sent via sendBeacon"),{accepted:t.map(c=>({event_id:c.event_id,timestamp:c.timestamp})),rejected:[],stats:{received:t.length,accepted:t.length,rejected:0,processing_time_ms:0}};try{let o=await this.fetch(i,{method:"POST",headers:this.getHeaders(),body:l,keepalive:e?.useBeacon});if(!o.ok)throw o.status===429?a.rateLimited(`Rate limited: ${o.statusText}`,{status:o.status}):a.networkError(`HTTP ${o.status}: ${o.statusText}`,{status:o.status});let c=await o.json();return this.log("Track response:",c),c}catch(o){throw o instanceof a?o:a.networkError(`Failed to send events: ${o instanceof Error?o.message:String(o)}`,o)}}async sendIdentify(t){let e=`${this.apiUrl}/v1/identify`,i=JSON.stringify(this.toIdentifyApiPayload(t));this.log("Sending identify to",e,t);try{let r=await this.fetch(e,{method:"POST",headers:this.getHeaders(),body:i});if(!r.ok)throw r.status===429?a.rateLimited(`Rate limited: ${r.statusText}`,{status:r.status}):a.networkError(`HTTP ${r.status}: ${r.statusText}`,{status:r.status});let l=await r.json();return this.log("Identify response:",l),l}catch(r){throw r instanceof a?r:a.networkError(`Failed to send identify: ${r instanceof Error?r.message:String(r)}`,r)}}setTenantId(t){this.tenantId=t;}setDebug(t){this.debug=t;}getHeaders(){let t={"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`};return this.tenantId&&(t["X-Tenant-Id"]=this.tenantId),t}toTrackApiPayload(t){return {eventId:t.event_id,eventName:t.event_name,timestamp:t.timestamp,anonymousId:t.anonymous_id,userId:t.user_id??void 0,sessionId:t.session_id??void 0,properties:t.properties,userTraits:t.user_traits,context:{platform:t.platform,appVersion:t.app_version??void 0}}}toIdentifyApiPayload(t){return {userId:t.user_id,anonymousId:t.anonymous_id,traits:t.traits,timestamp:t.timestamp}}sendViaBeacon(t,e){try{let i=new Blob([e],{type:"application/json"});return navigator.sendBeacon(t,i)}catch(i){return this.log("sendBeacon failed:",i),false}}async fetch(t,e){if(typeof fetch<"u")return fetch(t,e);throw a.networkError("fetch is not available in this environment")}log(...t){this.debug&&[...t];}};var S=class{constructor(t){s(this,"queue",[]);s(this,"isFlushing",false);s(this,"flushTimer",null);s(this,"retryTimer",null);s(this,"config");s(this,"initialized",false);this.config={flushAt:t.flushAt??h.FLUSH_AT,flushInterval:t.flushInterval??h.FLUSH_INTERVAL,maxQueueSize:t.maxQueueSize??h.MAX_QUEUE_SIZE,storage:t.storage,transport:t.transport,onError:t.onError,debug:t.debug??false};}async initialize(){this.initialized||(await this.loadPersistedQueue(),this.startFlushTimer(),this.initialized=true,this.log("Queue initialized with",this.queue.length,"persisted events"));}async enqueue(t){for(;this.queue.length>=this.config.maxQueueSize;){let i=this.queue.shift();i&&(this.log("Queue full, dropping oldest event:",i.event.event_id),this.config.onError?.(a.queueFull("Queue full, dropped oldest event",{dropped_event_id:i.event.event_id}),[i.event]));}let e={event:t,attempts:0,firstAttempt:Date.now()};this.queue.push(e),this.log("Enqueued event:",t.event_id,"Queue size:",this.queue.length),await this.persistQueue(),this.queue.length>=this.config.flushAt&&(this.log("Queue reached flushAt threshold, flushing"),this.flush());}async flush(t){if(!(this.isFlushing||this.queue.length===0)){this.isFlushing=true,this.log("Flushing",this.queue.length,"events");try{let e=this.queue.splice(0,h.MAX_BATCH_SIZE),i=e.map(r=>r.event);try{let r=await this.config.transport.sendEvents(i,t);for(let l of r.rejected)if(l.reason==="rate_limited"){let o=e.find(c=>c.event.event_id===l.event_id);o&&o.attempts<h.MAX_RETRIES&&(o.attempts++,this.queue.unshift(o),this.log("Rate limited event re-queued:",l.event_id,"attempt:",o.attempts));}else this.log("Event permanently rejected:",l.event_id,l.reason,l.details);this.log("Flush complete. Accepted:",r.stats.accepted,"Rejected:",r.stats.rejected);}catch(r){let l=a.fromUnknown(r);for(let p of e)p.attempts<h.MAX_RETRIES?(p.attempts++,this.queue.unshift(p)):this.log("Event dropped after max retries:",p.event.event_id);let o=e[0]?.attempts??1,c=U(o);this.log("Network error, scheduling retry in",c,"ms"),this.retryTimer=setTimeout(()=>{this.retryTimer=null,this.flush(t);},c),this.config.onError?.(l,i);}await this.persistQueue(),this.queue.length>=this.config.flushAt&&setTimeout(()=>this.flush(t),0);}finally{this.isFlushing=false;}}}getQueueLength(){return this.queue.length}isEmpty(){return this.queue.length===0}isBusy(){return this.isFlushing}async clear(){this.queue=[],await this.persistQueue(),this.log("Queue cleared");}destroy(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null),this.log("Queue destroyed");}setDebug(t){this.config.debug=t;}async persistQueue(){if(this.config.storage)try{await this.config.storage.set(u.QUEUE,JSON.stringify(this.queue));}catch(t){this.log("Error persisting queue:",t);}}async loadPersistedQueue(){if(this.config.storage)try{let t=await this.config.storage.get(u.QUEUE);if(t){let e=JSON.parse(t);Array.isArray(e)&&(this.queue=e.filter(i=>i&&typeof i=="object"&&"event"in i&&"attempts"in i));}}catch(t){this.log("Error loading persisted queue:",t),this.queue=[];}}startFlushTimer(){this.flushTimer||(this.flushTimer=setInterval(()=>{this.queue.length>0&&(this.log("Flush timer triggered"),this.flush());},this.config.flushInterval));}log(...t){this.config.debug&&[...t];}};var v=class{constructor(t,e=null){s(this,"config");s(this,"storage",null);s(this,"identity");s(this,"session");s(this,"transport");s(this,"queue");s(this,"initialized",false);s(this,"tenantId");this.validateConfig(t),this.config={apiUrl:h.API_URL,debug:false,flushInterval:h.FLUSH_INTERVAL,flushAt:h.FLUSH_AT,maxQueueSize:h.MAX_QUEUE_SIZE,sessionTimeout:h.SESSION_TIMEOUT,...t},this.storage=e,this.tenantId=t.tenantId??"",this.identity=new m(e,this.config.debug),this.session=new y(e,this.config.sessionTimeout,{onSessionStart:i=>{this.log("Session started:",i),this.trackInternal("session_started",{session_id:i});},onSessionEnd:(i,r)=>{this.log("Session ended:",i,"duration:",r),this.trackInternal("session_ended",{session_id:i,duration_ms:r});}},this.config.debug),this.transport=new I({apiUrl:this.config.apiUrl,apiKey:this.config.apiKey,tenantId:this.tenantId,debug:this.config.debug}),this.queue=new S({flushAt:this.config.flushAt,flushInterval:this.config.flushInterval,maxQueueSize:this.config.maxQueueSize,storage:e,transport:this.transport,onError:(i,r)=>{this.config.onError?.(i),this.log("Queue error:",i.message,"events:",r.length);},debug:this.config.debug});}async initialize(){this.initialized||(await Promise.all([this.identity.initialize(),this.session.initialize(),this.queue.initialize()]),this.initialized=true,this.log("Client initialized"));}setTenant(t){this.tenantId=t,this.transport.setTenantId(t),this.log("Tenant set:",t);}async identify(t,e){await this.ensureInitialized(),await this.identity.setUserId(t),e&&await this.identity.setUserTraits(e);try{await this.transport.sendIdentify({project_id:this.config.projectId,environment:this.config.environment,tenant_id:this.tenantId,anonymous_id:this.identity.getAnonymousId(),user_id:t,traits:e,timestamp:T()});}catch(i){let r=a.fromUnknown(i);this.config.onError?.(r),this.log("Identify error:",r.message);}}async setUserTraits(t){await this.ensureInitialized(),await this.identity.setUserTraits(t);}async track(t,e,i){await this.ensureInitialized();let r=this.createEvent(t,e,i);if(this.session.touch(),i?.immediate)try{await this.transport.sendEvents([r]);}catch(l){let o=a.fromUnknown(l);this.config.onError?.(o),this.log("Immediate track error:",o.message);}else await this.queue.enqueue(r);}async flush(t){await this.ensureInitialized(),await this.queue.flush(t);}async reset(){await this.ensureInitialized(),this.session.forceEndSession(),await this.identity.reset(),this.log("Client reset");}setDebug(t){this.config.debug=t,this.identity.setDebug(t),this.session.setDebug(t),this.transport.setDebug(t),this.queue.setDebug(t);}getAnonymousId(){return this.identity.getAnonymousId()}getUserId(){return this.identity.getUserId()}getSessionId(){return this.session.getCurrentSessionId()}getQueueLength(){return this.queue.getQueueLength()}destroy(){this.queue.destroy(),this.log("Client destroyed");}trackInternal(t,e){let i=this.createEvent(t,e);this.queue.enqueue(i).catch(r=>{this.log("Internal track error:",r);});}createEvent(t,e,i){let r=i?.timestamp?A(i.timestamp):T();return {event_id:g(),timestamp:r,project_id:this.config.projectId,environment:this.config.environment,tenant_id:this.tenantId,event_name:t,anonymous_id:this.identity.getAnonymousId(),user_id:this.identity.getUserId(),session_id:this.session.getSessionId(),platform:this.config.platform,app_version:this.config.appVersion??null,properties:e??{},user_traits:this.identity.getUserTraits()}}async ensureInitialized(){this.initialized||await this.initialize();}validateConfig(t){if(!t.apiKey)throw a.invalidConfig("apiKey is required");if(!t.projectId)throw a.invalidConfig("projectId is required");if(!t.environment)throw a.invalidConfig("environment is required");if(!t.platform)throw a.invalidConfig("platform is required")}log(...t){this.config.debug&&[...t];}};var w=class{constructor(){s(this,"data",new Map);}async get(t){return this.data.get(t)??null}async set(t,e){this.data.set(t,e);}async remove(t){this.data.delete(t);}};function H(){try{let n="__pih_test__";return localStorage.setItem(n,n),localStorage.removeItem(n),!0}catch{return false}}var P=class{constructor(){s(this,"fallback",null);s(this,"useLocalStorage");this.useLocalStorage=H(),this.useLocalStorage||(this.fallback=new w,console.warn("[PIH] localStorage unavailable, using in-memory storage. Data will not persist across page loads."));}async get(t){if(this.fallback)return this.fallback.get(t);try{return localStorage.getItem(t)}catch{return this.fallback||(this.fallback=new w),this.fallback.get(t)}}async set(t,e){if(this.fallback)return this.fallback.set(t,e);try{localStorage.setItem(t,e);}catch(i){return this.fallback||(this.fallback=new w,console.warn("[PIH] localStorage write failed, falling back to in-memory storage:",i)),this.fallback.set(t,e)}}async remove(t){if(this.fallback)return this.fallback.remove(t);try{localStorage.removeItem(t);}catch{}}};function x(){return new P}x();var k="pih_utm_params",L=["utm_source","utm_medium","utm_campaign","utm_term","utm_content"],E=class{constructor(t,e={}){s(this,"client");s(this,"config");s(this,"cachedUtmParams",null);s(this,"originalPushState",null);s(this,"originalReplaceState",null);s(this,"boundHandleClick");s(this,"boundHandlePopState");this.client=t,this.config={pageViews:e.pageViews!==false,clicks:e.clicks??false,clickSelector:e.clickSelector??"[data-track]",forms:e.forms??false},this.boundHandleClick=this.handleClick.bind(this),this.boundHandlePopState=this.handlePopState.bind(this);}start(){typeof window>"u"||typeof document>"u"||(this.loadCachedUtmParams(),this.config.pageViews&&(this.setupPageViews(),this.trackPageView()),this.config.clicks&&this.setupClickTracking());}stop(){this.originalPushState&&(history.pushState=this.originalPushState,this.originalPushState=null),this.originalReplaceState&&(history.replaceState=this.originalReplaceState,this.originalReplaceState=null),typeof window<"u"&&window.removeEventListener("popstate",this.boundHandlePopState),typeof document<"u"&&document.removeEventListener("click",this.boundHandleClick,true);}trackPageView(){let t=new URL(window.location.href),e=this.extractUtmParams(t);Object.keys(e).length>0&&!this.cachedUtmParams&&(this.cachedUtmParams=e,this.persistUtmParams(e)),this.client.track("page_viewed",{path:t.pathname,search:t.search,hash:t.hash,referrer:document.referrer||null,title:document.title,url:window.location.href,...this.getUtmParams(t)});}setupPageViews(){this.originalPushState=history.pushState,this.originalReplaceState=history.replaceState;let t=this;history.pushState=function(...e){t.originalPushState.apply(history,e),setTimeout(()=>t.trackPageView(),0);},history.replaceState=function(...e){t.originalReplaceState.apply(history,e),setTimeout(()=>t.trackPageView(),0);},window.addEventListener("popstate",this.boundHandlePopState);}handlePopState(){this.trackPageView();}setupClickTracking(){document.addEventListener("click",this.boundHandleClick,true);}handleClick(t){let e=t.target;if(!e)return;let i=e.closest(this.config.clickSelector);if(!i)return;let r=i.tagName.toLowerCase(),l=(i.textContent||"").trim().slice(0,100),o=i.id||null,c=i.className||null,p=i.getAttribute("data-track"),R=i instanceof HTMLAnchorElement?i.href:null;this.client.track("element_clicked",{element_tag:r,element_text:l,element_id:o,element_classes:c,data_track:p,href:R,path:window.location.pathname});}extractUtmParams(t){let e={};for(let i of L){let r=t.searchParams.get(i);r&&(e[i]=r);}return e}getUtmParams(t){let e=this.extractUtmParams(t);return Object.keys(e).length>0?e:this.cachedUtmParams??{}}loadCachedUtmParams(){try{let t=localStorage.getItem(k);t&&(this.cachedUtmParams=JSON.parse(t));}catch{}}persistUtmParams(t){try{localStorage.setItem(k,JSON.stringify(t));}catch{}}};var b=class{constructor(t){s(this,"client");s(this,"boundHandleVisibilityChange");s(this,"boundHandleBeforeUnload");this.client=t,this.boundHandleVisibilityChange=this.handleVisibilityChange.bind(this),this.boundHandleBeforeUnload=this.handleBeforeUnload.bind(this);}start(){typeof document<"u"&&document.addEventListener("visibilitychange",this.boundHandleVisibilityChange),typeof window<"u"&&(window.addEventListener("beforeunload",this.boundHandleBeforeUnload),window.addEventListener("pagehide",this.boundHandleBeforeUnload));}stop(){typeof document<"u"&&document.removeEventListener("visibilitychange",this.boundHandleVisibilityChange),typeof window<"u"&&(window.removeEventListener("beforeunload",this.boundHandleBeforeUnload),window.removeEventListener("pagehide",this.boundHandleBeforeUnload));}handleVisibilityChange(){document.visibilityState==="hidden"&&this.flushWithBeacon();}handleBeforeUnload(){this.flushWithBeacon();}flushWithBeacon(){this.client.flush({useBeacon:true}).catch(()=>{});}};var _=class extends v{constructor(e,i){let r={...e,platform:"web"};super(r,i??x());s(this,"autocapture",null);s(this,"beacon");this.beacon=new b(this);}async initialize(){await super.initialize(),this.beacon.start(),this.config.autocapture&&(this.autocapture=new E(this,this.config.autocapture),this.autocapture.start()),this.log("Web client initialized");}enableAutocapture(e){this.autocapture&&this.autocapture.stop(),this.autocapture=new E(this,e),this.autocapture.start();}disableAutocapture(){this.autocapture&&(this.autocapture.stop(),this.autocapture=null);}trackPageView(){if(this.autocapture)this.autocapture.trackPageView();else {let e=new URL(window.location.href);this.track("page_viewed",{path:e.pathname,search:e.search,hash:e.hash,referrer:document.referrer||null,title:document.title,url:window.location.href});}}destroy(){this.beacon.stop(),this.autocapture&&this.autocapture.stop(),super.destroy();}log(...e){this.config.debug&&[...e];}},d=null;function D(n){return d?(console.warn("[PIH] SDK already initialized. Returning existing instance."),d):(d=new _(n),d.initialize().catch(t=>{console.error("[PIH] Failed to initialize:",t);}),d)}function N(){return d}function q(){d&&(d.destroy(),d=null);}var z={init:D,getInstance:N,resetInstance:q,WebPIHClient:_},Ht=z;
|
|
2
|
-
|
|
1
|
+
var PIH=(function(exports){'use strict';var Ut=Object.create;var ve=Object.defineProperty;var Nt=Object.getOwnPropertyDescriptor;var Lt=Object.getOwnPropertyNames;var xt=Object.getPrototypeOf,jt=Object.prototype.hasOwnProperty;var Mt=(e,n,r)=>n in e?ve(e,n,{enumerable:true,configurable:true,writable:true,value:r}):e[n]=r;var ye=(e,n)=>()=>(n||e((n={exports:{}}).exports,n),n.exports);var Dt=(e,n,r,s)=>{if(n&&typeof n=="object"||typeof n=="function")for(let a of Lt(n))!jt.call(e,a)&&a!==r&&ve(e,a,{get:()=>n[a],enumerable:!(s=Nt(n,a))||s.enumerable});return e};var Ft=(e,n,r)=>(r=e!=null?Ut(xt(e)):{},Dt(ve(r,"default",{value:e,enumerable:true}),e));var p=(e,n,r)=>Mt(e,typeof n!="symbol"?n+"":n,r);var vt=ye(h=>{var be=Symbol.for("react.transitional.element"),nn=Symbol.for("react.portal"),rn=Symbol.for("react.fragment"),sn=Symbol.for("react.strict_mode"),on=Symbol.for("react.profiler"),an=Symbol.for("react.consumer"),un=Symbol.for("react.context"),ln=Symbol.for("react.forward_ref"),cn=Symbol.for("react.suspense"),dn=Symbol.for("react.memo"),dt=Symbol.for("react.lazy"),hn=Symbol.for("react.activity"),at=Symbol.iterator;function fn(e){return e===null||typeof e!="object"?null:(e=at&&e[at]||e["@@iterator"],typeof e=="function"?e:null)}var ht={isMounted:function(){return false},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},ft=Object.assign,pt={};function M(e,n,r){this.props=e,this.context=n,this.refs=pt,this.updater=r||ht;}M.prototype.isReactComponent={};M.prototype.setState=function(e,n){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,n,"setState");};M.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate");};function gt(){}gt.prototype=M.prototype;function Te(e,n,r){this.props=e,this.context=n,this.refs=pt,this.updater=r||ht;}var Ie=Te.prototype=new gt;Ie.constructor=Te;ft(Ie,M.prototype);Ie.isPureReactComponent=true;var ut=Array.isArray;function Se(){}var _={H:null,A:null,T:null,S:null},mt=Object.prototype.hasOwnProperty;function ke(e,n,r){var s=r.ref;return {$$typeof:be,type:e,key:n,ref:s!==void 0?s:null,props:r}}function pn(e,n){return ke(e.type,n,e.props)}function Re(e){return typeof e=="object"&&e!==null&&e.$$typeof===be}function gn(e){var n={"=":"=0",":":"=2"};return "$"+e.replace(/[=:]/g,function(r){return n[r]})}var lt=/\/+/g;function _e(e,n){return typeof e=="object"&&e!==null&&e.key!=null?gn(""+e.key):n.toString(36)}function mn(e){switch(e.status){case "fulfilled":return e.value;case "rejected":throw e.reason;default:switch(typeof e.status=="string"?e.then(Se,Se):(e.status="pending",e.then(function(n){e.status==="pending"&&(e.status="fulfilled",e.value=n);},function(n){e.status==="pending"&&(e.status="rejected",e.reason=n);})),e.status){case "fulfilled":return e.value;case "rejected":throw e.reason}}throw e}function j(e,n,r,s,a){var l=typeof e;(l==="undefined"||l==="boolean")&&(e=null);var g=false;if(e===null)g=true;else switch(l){case "bigint":case "string":case "number":g=true;break;case "object":switch(e.$$typeof){case be:case nn:g=true;break;case dt:return g=e._init,j(g(e._payload),n,r,s,a)}}if(g)return a=a(e),g=s===""?"."+_e(e,0):s,ut(a)?(r="",g!=null&&(r=g.replace(lt,"$&/")+"/"),j(a,n,r,"",function(H){return H})):a!=null&&(Re(a)&&(a=pn(a,r+(a.key==null||e&&e.key===a.key?"":(""+a.key).replace(lt,"$&/")+"/")+g)),n.push(a)),1;g=0;var k=s===""?".":s+":";if(ut(e))for(var T=0;T<e.length;T++)s=e[T],l=k+_e(s,T),g+=j(s,n,r,l,a);else if(T=fn(e),typeof T=="function")for(e=T.call(e),T=0;!(s=e.next()).done;)s=s.value,l=k+_e(s,T++),g+=j(s,n,r,l,a);else if(l==="object"){if(typeof e.then=="function")return j(mn(e),n,r,s,a);throw n=String(e),Error("Objects are not valid as a React child (found: "+(n==="[object Object]"?"object with keys {"+Object.keys(e).join(", ")+"}":n)+"). If you meant to render a collection of children, use an array instead.")}return g}function re(e,n,r){if(e==null)return e;var s=[],a=0;return j(e,s,"","",function(l){return n.call(r,l,a++)}),s}function vn(e){if(e._status===-1){var n=e._result;n=n(),n.then(function(r){(e._status===0||e._status===-1)&&(e._status=1,e._result=r);},function(r){(e._status===0||e._status===-1)&&(e._status=2,e._result=r);}),e._status===-1&&(e._status=0,e._result=n);}if(e._status===1)return e._result.default;throw e._result}var ct=typeof reportError=="function"?reportError:function(e){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var n=new window.ErrorEvent("error",{bubbles:true,cancelable:true,message:typeof e=="object"&&e!==null&&typeof e.message=="string"?String(e.message):String(e),error:e});if(!window.dispatchEvent(n))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",e);return}console.error(e);},yn={map:re,forEach:function(e,n,r){re(e,function(){n.apply(this,arguments);},r);},count:function(e){var n=0;return re(e,function(){n++;}),n},toArray:function(e){return re(e,function(n){return n})||[]},only:function(e){if(!Re(e))throw Error("React.Children.only expected to receive a single React element child.");return e}};h.Activity=hn;h.Children=yn;h.Component=M;h.Fragment=rn;h.Profiler=on;h.PureComponent=Te;h.StrictMode=sn;h.Suspense=cn;h.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=_;h.__COMPILER_RUNTIME={__proto__:null,c:function(e){return _.H.useMemoCache(e)}};h.cache=function(e){return function(){return e.apply(null,arguments)}};h.cacheSignal=function(){return null};h.cloneElement=function(e,n,r){if(e==null)throw Error("The argument must be a React element, but you passed "+e+".");var s=ft({},e.props),a=e.key;if(n!=null)for(l in n.key!==void 0&&(a=""+n.key),n)!mt.call(n,l)||l==="key"||l==="__self"||l==="__source"||l==="ref"&&n.ref===void 0||(s[l]=n[l]);var l=arguments.length-2;if(l===1)s.children=r;else if(1<l){for(var g=Array(l),k=0;k<l;k++)g[k]=arguments[k+2];s.children=g;}return ke(e.type,a,s)};h.createContext=function(e){return e={$$typeof:un,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null},e.Provider=e,e.Consumer={$$typeof:an,_context:e},e};h.createElement=function(e,n,r){var s,a={},l=null;if(n!=null)for(s in n.key!==void 0&&(l=""+n.key),n)mt.call(n,s)&&s!=="key"&&s!=="__self"&&s!=="__source"&&(a[s]=n[s]);var g=arguments.length-2;if(g===1)a.children=r;else if(1<g){for(var k=Array(g),T=0;T<g;T++)k[T]=arguments[T+2];a.children=k;}if(e&&e.defaultProps)for(s in g=e.defaultProps,g)a[s]===void 0&&(a[s]=g[s]);return ke(e,l,a)};h.createRef=function(){return {current:null}};h.forwardRef=function(e){return {$$typeof:ln,render:e}};h.isValidElement=Re;h.lazy=function(e){return {$$typeof:dt,_payload:{_status:-1,_result:e},_init:vn}};h.memo=function(e,n){return {$$typeof:dn,type:e,compare:n===void 0?null:n}};h.startTransition=function(e){var n=_.T,r={};_.T=r;try{var s=e(),a=_.S;a!==null&&a(r,s),typeof s=="object"&&s!==null&&typeof s.then=="function"&&s.then(Se,ct);}catch(l){ct(l);}finally{n!==null&&r.types!==null&&(n.types=r.types),_.T=n;}};h.unstable_useCacheRefresh=function(){return _.H.useCacheRefresh()};h.use=function(e){return _.H.use(e)};h.useActionState=function(e,n,r){return _.H.useActionState(e,n,r)};h.useCallback=function(e,n){return _.H.useCallback(e,n)};h.useContext=function(e){return _.H.useContext(e)};h.useDebugValue=function(){};h.useDeferredValue=function(e,n){return _.H.useDeferredValue(e,n)};h.useEffect=function(e,n){return _.H.useEffect(e,n)};h.useEffectEvent=function(e){return _.H.useEffectEvent(e)};h.useId=function(){return _.H.useId()};h.useImperativeHandle=function(e,n,r){return _.H.useImperativeHandle(e,n,r)};h.useInsertionEffect=function(e,n){return _.H.useInsertionEffect(e,n)};h.useLayoutEffect=function(e,n){return _.H.useLayoutEffect(e,n)};h.useMemo=function(e,n){return _.H.useMemo(e,n)};h.useOptimistic=function(e,n){return _.H.useOptimistic(e,n)};h.useReducer=function(e,n,r){return _.H.useReducer(e,n,r)};h.useRef=function(e){return _.H.useRef(e)};h.useState=function(e){return _.H.useState(e)};h.useSyncExternalStore=function(e,n,r){return _.H.useSyncExternalStore(e,n,r)};h.useTransition=function(){return _.H.useTransition()};h.version="19.2.4";});var yt=ye((d,ie)=>{process.env.NODE_ENV!=="production"&&(function(){function e(t,i){Object.defineProperty(s.prototype,t,{get:function(){console.warn("%s(...) is deprecated in plain JavaScript React classes. %s",i[0],i[1]);}});}function n(t){return t===null||typeof t!="object"?null:(t=Ve&&t[Ve]||t["@@iterator"],typeof t=="function"?t:null)}function r(t,i){t=(t=t.constructor)&&(t.displayName||t.name)||"ReactClass";var o=t+"."+i;ze[o]||(console.error("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.",i,t),ze[o]=true);}function s(t,i,o){this.props=t,this.context=i,this.refs=ge,this.updater=o||Ye;}function a(){}function l(t,i,o){this.props=t,this.context=i,this.refs=ge,this.updater=o||Ye;}function g(){}function k(t){return ""+t}function T(t){try{k(t);var i=!1;}catch{i=true;}if(i){i=console;var o=i.error,u=typeof Symbol=="function"&&Symbol.toStringTag&&t[Symbol.toStringTag]||t.constructor.name||"Object";return o.call(i,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",u),k(t)}}function H(t){if(t==null)return null;if(typeof t=="function")return t.$$typeof===At?null:t.displayName||t.name||null;if(typeof t=="string")return t;switch(t){case he:return "Fragment";case Me:return "Profiler";case je:return "StrictMode";case $e:return "Suspense";case Rt:return "SuspenseList";case qe:return "Activity"}if(typeof t=="object")switch(typeof t.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),t.$$typeof){case xe:return "Portal";case De:return t.displayName||"Context";case fe:return (t._context.displayName||"Context")+".Consumer";case Fe:var i=t.render;return t=t.displayName,t||(t=i.displayName||i.name||"",t=t!==""?"ForwardRef("+t+")":"ForwardRef"),t;case pe:return i=t.displayName||null,i!==null?i:H(t.type)||"Memo";case $:i=t._payload,t=t._init;try{return H(t(i))}catch{}}return null}function Pe(t){if(t===he)return "<>";if(typeof t=="object"&&t!==null&&t.$$typeof===$)return "<...>";try{var i=H(t);return i?"<"+i+">":"<...>"}catch{return "<...>"}}function Oe(){var t=m.A;return t===null?null:t.getOwner()}function He(){return Error("react-stack-top-frame")}function Ue(t){if(Q.call(t,"key")){var i=Object.getOwnPropertyDescriptor(t,"key").get;if(i&&i.isReactWarning)return false}return t.key!==void 0}function _t(t,i){function o(){Ke||(Ke=true,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",i));}o.isReactWarning=true,Object.defineProperty(t,"key",{get:o,configurable:true});}function St(){var t=H(this.type);return Xe[t]||(Xe[t]=true,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),t=this.props.ref,t!==void 0?t:null}function ae(t,i,o,u,c,y){var f=o.ref;return t={$$typeof:de,type:t,key:i,props:o,_owner:u},(f!==void 0?f:null)!==null?Object.defineProperty(t,"ref",{enumerable:false,get:St}):Object.defineProperty(t,"ref",{enumerable:false,value:null}),t._store={},Object.defineProperty(t._store,"validated",{configurable:false,enumerable:false,writable:true,value:0}),Object.defineProperty(t,"_debugInfo",{configurable:false,enumerable:false,writable:true,value:null}),Object.defineProperty(t,"_debugStack",{configurable:false,enumerable:false,writable:true,value:c}),Object.defineProperty(t,"_debugTask",{configurable:false,enumerable:false,writable:true,value:y}),Object.freeze&&(Object.freeze(t.props),Object.freeze(t)),t}function bt(t,i){return i=ae(t.type,i,t.props,t._owner,t._debugStack,t._debugTask),t._store&&(i._store.validated=t._store.validated),i}function Ne(t){N(t)?t._store&&(t._store.validated=1):typeof t=="object"&&t!==null&&t.$$typeof===$&&(t._payload.status==="fulfilled"?N(t._payload.value)&&t._payload.value._store&&(t._payload.value._store.validated=1):t._store&&(t._store.validated=1));}function N(t){return typeof t=="object"&&t!==null&&t.$$typeof===de}function Tt(t){var i={"=":"=0",":":"=2"};return "$"+t.replace(/[=:]/g,function(o){return i[o]})}function ue(t,i){return typeof t=="object"&&t!==null&&t.key!=null?(T(t.key),Tt(""+t.key)):i.toString(36)}function It(t){switch(t.status){case "fulfilled":return t.value;case "rejected":throw t.reason;default:switch(typeof t.status=="string"?t.then(g,g):(t.status="pending",t.then(function(i){t.status==="pending"&&(t.status="fulfilled",t.value=i);},function(i){t.status==="pending"&&(t.status="rejected",t.reason=i);})),t.status){case "fulfilled":return t.value;case "rejected":throw t.reason}}throw t}function L(t,i,o,u,c){var y=typeof t;(y==="undefined"||y==="boolean")&&(t=null);var f=false;if(t===null)f=true;else switch(y){case "bigint":case "string":case "number":f=true;break;case "object":switch(t.$$typeof){case de:case xe:f=true;break;case $:return f=t._init,L(f(t._payload),i,o,u,c)}}if(f){f=t,c=c(f);var w=u===""?"."+ue(f,0):u;return Be(c)?(o="",w!=null&&(o=w.replace(Je,"$&/")+"/"),L(c,i,o,"",function(U){return U})):c!=null&&(N(c)&&(c.key!=null&&(f&&f.key===c.key||T(c.key)),o=bt(c,o+(c.key==null||f&&f.key===c.key?"":(""+c.key).replace(Je,"$&/")+"/")+w),u!==""&&f!=null&&N(f)&&f.key==null&&f._store&&!f._store.validated&&(o._store.validated=2),c=o),i.push(c)),1}if(f=0,w=u===""?".":u+":",Be(t))for(var E=0;E<t.length;E++)u=t[E],y=w+ue(u,E),f+=L(u,i,o,y,c);else if(E=n(t),typeof E=="function")for(E===t.entries&&(Ze||console.warn("Using Maps as children is not supported. Use an array of keyed ReactElements instead."),Ze=true),t=E.call(t),E=0;!(u=t.next()).done;)u=u.value,y=w+ue(u,E++),f+=L(u,i,o,y,c);else if(y==="object"){if(typeof t.then=="function")return L(It(t),i,o,u,c);throw i=String(t),Error("Objects are not valid as a React child (found: "+(i==="[object Object]"?"object with keys {"+Object.keys(t).join(", ")+"}":i)+"). If you meant to render a collection of children, use an array instead.")}return f}function Y(t,i,o){if(t==null)return t;var u=[],c=0;return L(t,u,"","",function(y){return i.call(o,y,c++)}),u}function kt(t){if(t._status===-1){var i=t._ioInfo;i!=null&&(i.start=i.end=performance.now()),i=t._result;var o=i();if(o.then(function(c){if(t._status===0||t._status===-1){t._status=1,t._result=c;var y=t._ioInfo;y!=null&&(y.end=performance.now()),o.status===void 0&&(o.status="fulfilled",o.value=c);}},function(c){if(t._status===0||t._status===-1){t._status=2,t._result=c;var y=t._ioInfo;y!=null&&(y.end=performance.now()),o.status===void 0&&(o.status="rejected",o.reason=c);}}),i=t._ioInfo,i!=null){i.value=o;var u=o.displayName;typeof u=="string"&&(i.name=u);}t._status===-1&&(t._status=0,t._result=o);}if(t._status===1)return i=t._result,i===void 0&&console.error(`lazy: Expected the result of a dynamic import() call. Instead received: %s
|
|
2
|
+
|
|
3
|
+
Your code should look like:
|
|
4
|
+
const MyComponent = lazy(() => import('./MyComponent'))
|
|
5
|
+
|
|
6
|
+
Did you accidentally put curly braces around the import?`,i),"default"in i||console.error(`lazy: Expected the result of a dynamic import() call. Instead received: %s
|
|
7
|
+
|
|
8
|
+
Your code should look like:
|
|
9
|
+
const MyComponent = lazy(() => import('./MyComponent'))`,i),i.default;throw t._result}function I(){var t=m.H;return t===null&&console.error(`Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
|
|
10
|
+
1. You might have mismatching versions of React and the renderer (such as React DOM)
|
|
11
|
+
2. You might be breaking the Rules of Hooks
|
|
12
|
+
3. You might have more than one copy of React in the same app
|
|
13
|
+
See https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem.`),t}function Le(){m.asyncTransitions--;}function W(t){if(K===null)try{var i=("require"+Math.random()).slice(0,7);K=(ie&&ie[i]).call(ie,"timers").setImmediate;}catch{K=function(u){tt===false&&(tt=true,typeof MessageChannel>"u"&&console.error("This browser does not have a MessageChannel implementation, so enqueuing tasks via await act(async () => ...) will fail. Please file an issue at https://github.com/facebook/react/issues if you encounter this warning."));var c=new MessageChannel;c.port1.onmessage=u,c.port2.postMessage(void 0);};}return K(t)}function F(t){return 1<t.length&&typeof AggregateError=="function"?new AggregateError(t):t[0]}function B(t,i){i!==G-1&&console.error("You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. "),G=i;}function le(t,i,o){var u=m.actQueue;if(u!==null)if(u.length!==0)try{ce(u),W(function(){return le(t,i,o)});return}catch(c){m.thrownErrors.push(c);}else m.actQueue=null;0<m.thrownErrors.length?(u=F(m.thrownErrors),m.thrownErrors.length=0,o(u)):i(t);}function ce(t){if(!me){me=true;var i=0;try{for(;i<t.length;i++){var o=t[i];do{m.didUsePromise=!1;var u=o(!1);if(u!==null){if(m.didUsePromise){t[i]=o,t.splice(0,i);return}o=u;}else break}while(!0)}t.length=0;}catch(c){t.splice(0,i+1),m.thrownErrors.push(c);}finally{me=false;}}}typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var de=Symbol.for("react.transitional.element"),xe=Symbol.for("react.portal"),he=Symbol.for("react.fragment"),je=Symbol.for("react.strict_mode"),Me=Symbol.for("react.profiler"),fe=Symbol.for("react.consumer"),De=Symbol.for("react.context"),Fe=Symbol.for("react.forward_ref"),$e=Symbol.for("react.suspense"),Rt=Symbol.for("react.suspense_list"),pe=Symbol.for("react.memo"),$=Symbol.for("react.lazy"),qe=Symbol.for("react.activity"),Ve=Symbol.iterator,ze={},Ye={isMounted:function(){return false},enqueueForceUpdate:function(t){r(t,"forceUpdate");},enqueueReplaceState:function(t){r(t,"replaceState");},enqueueSetState:function(t){r(t,"setState");}},We=Object.assign,ge={};Object.freeze(ge),s.prototype.isReactComponent={},s.prototype.setState=function(t,i){if(typeof t!="object"&&typeof t!="function"&&t!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,t,i,"setState");},s.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate");};var R={isMounted:["isMounted","Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."],replaceState:["replaceState","Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."]};for(q in R)R.hasOwnProperty(q)&&e(q,R[q]);a.prototype=s.prototype,R=l.prototype=new a,R.constructor=l,We(R,s.prototype),R.isPureReactComponent=true;var Be=Array.isArray,At=Symbol.for("react.client.reference"),m={H:null,A:null,T:null,S:null,actQueue:null,asyncTransitions:0,isBatchingLegacy:false,didScheduleLegacyUpdate:false,didUsePromise:false,thrownErrors:[],getCurrentStack:null,recentlyCreatedOwnerStacks:0},Q=Object.prototype.hasOwnProperty,Qe=console.createTask?console.createTask:function(){return null};R={react_stack_bottom_frame:function(t){return t()}};var Ke,Ge,Xe={},Ct=R.react_stack_bottom_frame.bind(R,He)(),Pt=Qe(Pe(He)),Ze=false,Je=/\/+/g,et=typeof reportError=="function"?reportError:function(t){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var i=new window.ErrorEvent("error",{bubbles:true,cancelable:true,message:typeof t=="object"&&t!==null&&typeof t.message=="string"?String(t.message):String(t),error:t});if(!window.dispatchEvent(i))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",t);return}console.error(t);},tt=false,K=null,G=0,X=false,me=false,nt=typeof queueMicrotask=="function"?function(t){queueMicrotask(function(){return queueMicrotask(t)});}:W;R=Object.freeze({__proto__:null,c:function(t){return I().useMemoCache(t)}});var q={map:Y,forEach:function(t,i,o){Y(t,function(){i.apply(this,arguments);},o);},count:function(t){var i=0;return Y(t,function(){i++;}),i},toArray:function(t){return Y(t,function(i){return i})||[]},only:function(t){if(!N(t))throw Error("React.Children.only expected to receive a single React element child.");return t}};d.Activity=qe,d.Children=q,d.Component=s,d.Fragment=he,d.Profiler=Me,d.PureComponent=l,d.StrictMode=je,d.Suspense=$e,d.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=m,d.__COMPILER_RUNTIME=R,d.act=function(t){var i=m.actQueue,o=G;G++;var u=m.actQueue=i!==null?i:[],c=false;try{var y=t();}catch(E){m.thrownErrors.push(E);}if(0<m.thrownErrors.length)throw B(i,o),t=F(m.thrownErrors),m.thrownErrors.length=0,t;if(y!==null&&typeof y=="object"&&typeof y.then=="function"){var f=y;return nt(function(){c||X||(X=true,console.error("You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);"));}),{then:function(E,U){c=true,f.then(function(x){if(B(i,o),o===0){try{ce(u),W(function(){return le(x,E,U)});}catch(Ht){m.thrownErrors.push(Ht);}if(0<m.thrownErrors.length){var Ot=F(m.thrownErrors);m.thrownErrors.length=0,U(Ot);}}else E(x);},function(x){B(i,o),0<m.thrownErrors.length&&(x=F(m.thrownErrors),m.thrownErrors.length=0),U(x);});}}}var w=y;if(B(i,o),o===0&&(ce(u),u.length!==0&&nt(function(){c||X||(X=true,console.error("A component suspended inside an `act` scope, but the `act` call was not awaited. When testing React components that depend on asynchronous data, you must await the result:\n\nawait act(() => ...)"));}),m.actQueue=null),0<m.thrownErrors.length)throw t=F(m.thrownErrors),m.thrownErrors.length=0,t;return {then:function(E,U){c=true,o===0?(m.actQueue=u,W(function(){return le(w,E,U)})):E(w);}}},d.cache=function(t){return function(){return t.apply(null,arguments)}},d.cacheSignal=function(){return null},d.captureOwnerStack=function(){var t=m.getCurrentStack;return t===null?null:t()},d.cloneElement=function(t,i,o){if(t==null)throw Error("The argument must be a React element, but you passed "+t+".");var u=We({},t.props),c=t.key,y=t._owner;if(i!=null){var f;e:{if(Q.call(i,"ref")&&(f=Object.getOwnPropertyDescriptor(i,"ref").get)&&f.isReactWarning){f=false;break e}f=i.ref!==void 0;}f&&(y=Oe()),Ue(i)&&(T(i.key),c=""+i.key);for(w in i)!Q.call(i,w)||w==="key"||w==="__self"||w==="__source"||w==="ref"&&i.ref===void 0||(u[w]=i[w]);}var w=arguments.length-2;if(w===1)u.children=o;else if(1<w){f=Array(w);for(var E=0;E<w;E++)f[E]=arguments[E+2];u.children=f;}for(u=ae(t.type,c,u,y,t._debugStack,t._debugTask),c=2;c<arguments.length;c++)Ne(arguments[c]);return u},d.createContext=function(t){return t={$$typeof:De,_currentValue:t,_currentValue2:t,_threadCount:0,Provider:null,Consumer:null},t.Provider=t,t.Consumer={$$typeof:fe,_context:t},t._currentRenderer=null,t._currentRenderer2=null,t},d.createElement=function(t,i,o){for(var u=2;u<arguments.length;u++)Ne(arguments[u]);u={};var c=null;if(i!=null)for(E in Ge||!("__self"in i)||"key"in i||(Ge=true,console.warn("Your app (or one of its dependencies) is using an outdated JSX transform. Update to the modern JSX transform for faster performance: https://react.dev/link/new-jsx-transform")),Ue(i)&&(T(i.key),c=""+i.key),i)Q.call(i,E)&&E!=="key"&&E!=="__self"&&E!=="__source"&&(u[E]=i[E]);var y=arguments.length-2;if(y===1)u.children=o;else if(1<y){for(var f=Array(y),w=0;w<y;w++)f[w]=arguments[w+2];Object.freeze&&Object.freeze(f),u.children=f;}if(t&&t.defaultProps)for(E in y=t.defaultProps,y)u[E]===void 0&&(u[E]=y[E]);c&&_t(u,typeof t=="function"?t.displayName||t.name||"Unknown":t);var E=1e4>m.recentlyCreatedOwnerStacks++;return ae(t,c,u,Oe(),E?Error("react-stack-top-frame"):Ct,E?Qe(Pe(t)):Pt)},d.createRef=function(){var t={current:null};return Object.seal(t),t},d.forwardRef=function(t){t!=null&&t.$$typeof===pe?console.error("forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))."):typeof t!="function"?console.error("forwardRef requires a render function but was given %s.",t===null?"null":typeof t):t.length!==0&&t.length!==2&&console.error("forwardRef render functions accept exactly two parameters: props and ref. %s",t.length===1?"Did you forget to use the ref parameter?":"Any additional parameter will be undefined."),t!=null&&t.defaultProps!=null&&console.error("forwardRef render functions do not support defaultProps. Did you accidentally pass a React component?");var i={$$typeof:Fe,render:t},o;return Object.defineProperty(i,"displayName",{enumerable:false,configurable:true,get:function(){return o},set:function(u){o=u,t.name||t.displayName||(Object.defineProperty(t,"name",{value:u}),t.displayName=u);}}),i},d.isValidElement=N,d.lazy=function(t){t={_status:-1,_result:t};var i={$$typeof:$,_payload:t,_init:kt},o={name:"lazy",start:-1,end:-1,value:null,owner:null,debugStack:Error("react-stack-top-frame"),debugTask:console.createTask?console.createTask("lazy()"):null};return t._ioInfo=o,i._debugInfo=[{awaited:o}],i},d.memo=function(t,i){t==null&&console.error("memo: The first argument must be a component. Instead received: %s",t===null?"null":typeof t),i={$$typeof:pe,type:t,compare:i===void 0?null:i};var o;return Object.defineProperty(i,"displayName",{enumerable:false,configurable:true,get:function(){return o},set:function(u){o=u,t.name||t.displayName||(Object.defineProperty(t,"name",{value:u}),t.displayName=u);}}),i},d.startTransition=function(t){var i=m.T,o={};o._updatedFibers=new Set,m.T=o;try{var u=t(),c=m.S;c!==null&&c(o,u),typeof u=="object"&&u!==null&&typeof u.then=="function"&&(m.asyncTransitions++,u.then(Le,Le),u.then(g,et));}catch(y){et(y);}finally{i===null&&o._updatedFibers&&(t=o._updatedFibers.size,o._updatedFibers.clear(),10<t&&console.warn("Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table.")),i!==null&&o.types!==null&&(i.types!==null&&i.types!==o.types&&console.error("We expected inner Transitions to have transferred the outer types set and that you cannot add to the outer Transition while inside the inner.This is a bug in React."),i.types=o.types),m.T=i;}},d.unstable_useCacheRefresh=function(){return I().useCacheRefresh()},d.use=function(t){return I().use(t)},d.useActionState=function(t,i,o){return I().useActionState(t,i,o)},d.useCallback=function(t,i){return I().useCallback(t,i)},d.useContext=function(t){var i=I();return t.$$typeof===fe&&console.error("Calling useContext(Context.Consumer) is not supported and will cause bugs. Did you mean to call useContext(Context) instead?"),i.useContext(t)},d.useDebugValue=function(t,i){return I().useDebugValue(t,i)},d.useDeferredValue=function(t,i){return I().useDeferredValue(t,i)},d.useEffect=function(t,i){return t==null&&console.warn("React Hook useEffect requires an effect callback. Did you forget to pass a callback to the hook?"),I().useEffect(t,i)},d.useEffectEvent=function(t){return I().useEffectEvent(t)},d.useId=function(){return I().useId()},d.useImperativeHandle=function(t,i,o){return I().useImperativeHandle(t,i,o)},d.useInsertionEffect=function(t,i){return t==null&&console.warn("React Hook useInsertionEffect requires an effect callback. Did you forget to pass a callback to the hook?"),I().useInsertionEffect(t,i)},d.useLayoutEffect=function(t,i){return t==null&&console.warn("React Hook useLayoutEffect requires an effect callback. Did you forget to pass a callback to the hook?"),I().useLayoutEffect(t,i)},d.useMemo=function(t,i){return I().useMemo(t,i)},d.useOptimistic=function(t,i){return I().useOptimistic(t,i)},d.useReducer=function(t,i,o){return I().useReducer(t,i,o)},d.useRef=function(t){return I().useRef(t)},d.useState=function(t){return I().useState(t)},d.useSyncExternalStore=function(t,i,o){return I().useSyncExternalStore(t,i,o)},d.useTransition=function(){return I().useTransition()},d.version="19.2.4",typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());})();});var Et=ye((Bn,Ae)=>{process.env.NODE_ENV==="production"?Ae.exports=vt():Ae.exports=yt();});var $t=Object.defineProperty,qt=(e,n,r)=>n in e?$t(e,n,{enumerable:true,configurable:true,writable:true,value:r}):e[n]=r,v=(e,n,r)=>qt(e,typeof n!="symbol"?n+"":n,r),b=class A extends Error{constructor(n,r,s){super(n),v(this,"code"),v(this,"details"),this.name="PIHError",this.code=r,this.details=s,Error.captureStackTrace&&Error.captureStackTrace(this,A);}static networkError(n,r){return new A(n,"NETWORK_ERROR",r)}static invalidConfig(n,r){return new A(n,"INVALID_CONFIG",r)}static queueFull(n,r){return new A(n,"QUEUE_FULL",r)}static rateLimited(n,r){return new A(n,"RATE_LIMITED",r)}static invalidPayload(n,r){return new A(n,"INVALID_PAYLOAD",r)}static storageError(n,r){return new A(n,"STORAGE_ERROR",r)}static sessionError(n,r){return new A(n,"SESSION_ERROR",r)}static fromUnknown(n){return n instanceof A?n:n instanceof Error?new A(n.message,"UNKNOWN_ERROR",n):new A(String(n),"UNKNOWN_ERROR",n)}};function Z(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function"){let e=new Uint8Array(16);crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;let n=Array.from(e,r=>r.toString(16).padStart(2,"0")).join("");return `${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let n=Math.random()*16|0;return (e==="x"?n:n&3|8).toString(16)})}function rt(){return new Date().toISOString()}function Vt(e){return e.toISOString()}function zt(e,n=1e3,r=16e3){let s=n*Math.pow(2,e);return Math.min(s,r)}var P="pih_",S={QUEUE:`${P}queue`,ANONYMOUS_ID:`${P}anonymous_id`,USER_ID:`${P}user_id`,USER_TRAITS:`${P}user_traits`,SESSION_ID:`${P}session_id`,SESSION_LAST_ACTIVITY:`${P}session_last_activity`,SESSION_NUMBER:`${P}session_number`,EVENT_INDEX:`${P}event_index`,FLAGS:`${P}flags`},C={API_URL:"https://repoingest-production.up.railway.app",FLUSH_INTERVAL:1e4,FLUSH_AT:25,MAX_QUEUE_SIZE:5e3,SESSION_TIMEOUT:18e5,MAX_BATCH_SIZE:100,MAX_RETRIES:5,BASE_BACKOFF_DELAY:1e3,MAX_BACKOFF_DELAY:16e3},Yt=class{constructor(e,n=false){v(this,"anonymousId"),v(this,"userId",null),v(this,"userTraits",{}),v(this,"storage"),v(this,"debug"),this.storage=e,this.debug=n,this.anonymousId=Z();}async initialize(){if(!this.storage){this.log("No storage adapter, using in-memory identity only");return}try{let e=await this.storage.get(S.ANONYMOUS_ID);e?(this.anonymousId=e,this.log("Loaded anonymous ID from storage:",this.anonymousId)):(await this.storage.set(S.ANONYMOUS_ID,this.anonymousId),this.log("Generated new anonymous ID:",this.anonymousId));let n=await this.storage.get(S.USER_ID);n&&(this.userId=n,this.log("Loaded user ID from storage:",this.userId));let r=await this.storage.get(S.USER_TRAITS);if(r)try{this.userTraits=JSON.parse(r),this.log("Loaded user traits from storage:",this.userTraits);}catch{this.log("Failed to parse stored user traits");}}catch(e){this.log("Error loading identity from storage:",e);}}getAnonymousId(){return this.anonymousId}getUserId(){return this.userId}getUserTraits(){return {...this.userTraits}}async setUserId(e){if(this.userId=e,this.log("Set user ID:",e),this.storage)try{await this.storage.set(S.USER_ID,e);}catch(n){this.log("Error persisting user ID:",n);}}async setUserTraits(e){if(this.userTraits={...this.userTraits,...e},this.log("Set user traits:",this.userTraits),this.storage)try{await this.storage.set(S.USER_TRAITS,JSON.stringify(this.userTraits));}catch(n){this.log("Error persisting user traits:",n);}}async reset(){if(this.anonymousId=Z(),this.userId=null,this.userTraits={},this.log("Identity reset, new anonymous ID:",this.anonymousId),this.storage)try{await Promise.all([this.storage.set(S.ANONYMOUS_ID,this.anonymousId),this.storage.remove(S.USER_ID),this.storage.remove(S.USER_TRAITS)]);}catch(e){this.log("Error resetting identity in storage:",e);}}setDebug(e){this.debug=e;}log(...e){this.debug&&[...e];}},Wt=class{constructor(e){v(this,"queue",[]),v(this,"isFlushing",false),v(this,"flushTimer",null),v(this,"retryTimer",null),v(this,"config"),v(this,"initialized",false),this.config={flushAt:e.flushAt??C.FLUSH_AT,flushInterval:e.flushInterval??C.FLUSH_INTERVAL,maxQueueSize:e.maxQueueSize??C.MAX_QUEUE_SIZE,storage:e.storage,transport:e.transport,onError:e.onError,debug:e.debug??false};}async initialize(){this.initialized||(await this.loadPersistedQueue(),this.startFlushTimer(),this.initialized=true,this.log("Queue initialized with",this.queue.length,"persisted events"));}async enqueue(e){for(;this.queue.length>=this.config.maxQueueSize;){let r=this.queue.shift();r&&(this.log("Queue full, dropping oldest event:",r.event.event_id),this.config.onError?.(b.queueFull("Queue full, dropped oldest event",{dropped_event_id:r.event.event_id}),[r.event]));}let n={event:e,attempts:0,firstAttempt:Date.now()};this.queue.push(n),this.log("Enqueued event:",e.event_id,"Queue size:",this.queue.length),await this.persistQueue(),this.queue.length>=this.config.flushAt&&(this.log("Queue reached flushAt threshold, flushing"),this.flush());}async flush(e){if(!(this.isFlushing||this.queue.length===0)){this.isFlushing=true,this.log("Flushing",this.queue.length,"events");try{let n=this.queue.splice(0,C.MAX_BATCH_SIZE),r=n.map(s=>s.event);try{let s=await this.config.transport.sendEvents(r,e);for(let a of s.rejected)if(a.reason==="rate_limited"){let l=n.find(g=>g.event.event_id===a.event_id);l&&l.attempts<C.MAX_RETRIES&&(l.attempts++,this.queue.unshift(l),this.log("Rate limited event re-queued:",a.event_id,"attempt:",l.attempts));}else this.log("Event permanently rejected:",a.event_id,a.reason,a.details);this.log("Flush complete. Accepted:",s.stats.accepted,"Rejected:",s.stats.rejected);}catch(s){let a=b.fromUnknown(s);for(let k of n)k.attempts<C.MAX_RETRIES?(k.attempts++,this.queue.unshift(k)):this.log("Event dropped after max retries:",k.event.event_id);let l=n[0]?.attempts??1,g=zt(l);this.log("Network error, scheduling retry in",g,"ms"),this.retryTimer=setTimeout(()=>{this.retryTimer=null,this.flush(e);},g),this.config.onError?.(a,r);}await this.persistQueue(),this.queue.length>=this.config.flushAt&&setTimeout(()=>this.flush(e),0);}finally{this.isFlushing=false;}}}getQueueLength(){return this.queue.length}isEmpty(){return this.queue.length===0}isBusy(){return this.isFlushing}async clear(){this.queue=[],await this.persistQueue(),this.log("Queue cleared");}destroy(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null),this.log("Queue destroyed");}setDebug(e){this.config.debug=e;}async persistQueue(){if(this.config.storage)try{await this.config.storage.set(S.QUEUE,JSON.stringify(this.queue));}catch(e){this.log("Error persisting queue:",e);}}async loadPersistedQueue(){if(this.config.storage)try{let e=await this.config.storage.get(S.QUEUE);if(e){let n=JSON.parse(e);Array.isArray(n)&&(this.queue=n.filter(r=>r&&typeof r=="object"&&"event"in r&&"attempts"in r));}}catch(e){this.log("Error loading persisted queue:",e),this.queue=[];}}startFlushTimer(){this.flushTimer||(this.flushTimer=setInterval(()=>{this.queue.length>0&&(this.log("Flush timer triggered"),this.flush());},this.config.flushInterval));}log(...e){this.config.debug&&[...e];}},Bt=class{constructor(e,n=C.SESSION_TIMEOUT,r={},s=false){v(this,"sessionId",null),v(this,"sessionStartTime",0),v(this,"lastActivity",0),v(this,"timeout"),v(this,"storage"),v(this,"callbacks"),v(this,"debug"),this.storage=e,this.timeout=n,this.callbacks=r,this.debug=s;}async initialize(){if(!this.storage){this.log("No storage adapter, using in-memory session only");return}try{let e=await this.storage.get(S.SESSION_ID),n=await this.storage.get(S.SESSION_LAST_ACTIVITY);if(e&&n){let r=parseInt(n,10);Date.now()-r<this.timeout?(this.sessionId=e,this.lastActivity=r,this.sessionStartTime=r,this.log("Restored session from storage:",this.sessionId)):(this.log("Stored session expired, will start new session"),await this.clearStoredSession());}}catch(e){this.log("Error loading session from storage:",e);}}getSessionId(){let e=Date.now();return this.sessionId&&e-this.lastActivity>this.timeout&&this.endSession(),this.sessionId||this.startSession(),this.lastActivity=e,this.persistLastActivity(),this.sessionId}touch(){this.sessionId&&(this.lastActivity=Date.now(),this.persistLastActivity());}hasActiveSession(){return this.sessionId?Date.now()-this.lastActivity<this.timeout:false}getCurrentSessionId(){return this.sessionId}getSessionDuration(){return this.sessionId?Date.now()-this.sessionStartTime:0}startSession(){let e=Date.now();this.sessionId=Z(),this.sessionStartTime=e,this.lastActivity=e,this.log("Started new session:",this.sessionId),this.persistSession(),this.callbacks.onSessionStart?.(this.sessionId);}endSession(){if(!this.sessionId)return;let e=this.getSessionDuration(),n=this.sessionId;this.log("Ended session:",n,"duration:",e),this.sessionId=null,this.sessionStartTime=0,this.lastActivity=0,this.clearStoredSession(),this.callbacks.onSessionEnd?.(n,e);}forceEndSession(){this.sessionId&&this.endSession();}setDebug(e){this.debug=e;}setTimeout(e){this.timeout=e;}async persistSession(){if(!(!this.storage||!this.sessionId))try{await Promise.all([this.storage.set(S.SESSION_ID,this.sessionId),this.storage.set(S.SESSION_LAST_ACTIVITY,String(this.lastActivity))]);}catch(e){this.log("Error persisting session:",e);}}async persistLastActivity(){if(this.storage)try{await this.storage.set(S.SESSION_LAST_ACTIVITY,String(this.lastActivity));}catch(e){this.log("Error persisting last activity:",e);}}async clearStoredSession(){if(this.storage)try{await Promise.all([this.storage.remove(S.SESSION_ID),this.storage.remove(S.SESSION_LAST_ACTIVITY)]);}catch(e){this.log("Error clearing stored session:",e);}}log(...e){this.debug&&[...e];}},Qt={name:"pih-sdk-core",version:"0.3.0"},Kt=class{constructor(e){v(this,"apiUrl"),v(this,"apiKey"),v(this,"tenantId"),v(this,"debug"),v(this,"sdkMeta"),this.apiUrl=e.apiUrl.replace(/\/$/,""),this.apiKey=e.apiKey,this.tenantId=e.tenantId,this.debug=e.debug??false,this.sdkMeta=e.sdkMeta??Qt;}async sendEvents(e,n){let r=`${this.apiUrl}/v1/track`,s=e.map(l=>this.toTrackApiPayload(l)),a=JSON.stringify({events:s});if(this.log("Sending",e.length,"events to",r),n?.useBeacon&&typeof navigator<"u"&&typeof navigator.sendBeacon=="function"&&this.sendViaBeacon(r,a))return this.log("Events sent via sendBeacon"),{accepted:e.map(l=>({event_id:l.event_id,timestamp:l.timestamp})),rejected:[],stats:{received:e.length,accepted:e.length,rejected:0,processing_time_ms:0}};try{let l=await this.fetch(r,{method:"POST",headers:this.getHeaders(),body:a,keepalive:n?.useBeacon});if(!l.ok)throw l.status===429?b.rateLimited(`Rate limited: ${l.statusText}`,{status:l.status}):b.networkError(`HTTP ${l.status}: ${l.statusText}`,{status:l.status});let g=await l.json();return this.log("Track response:",g),g}catch(l){throw l instanceof b?l:b.networkError(`Failed to send events: ${l instanceof Error?l.message:String(l)}`,l)}}async sendIdentify(e){let n=`${this.apiUrl}/v1/identify`,r=JSON.stringify(this.toIdentifyApiPayload(e));this.log("Sending identify to",n,e);try{let s=await this.fetch(n,{method:"POST",headers:this.getHeaders(),body:r});if(!s.ok)throw s.status===429?b.rateLimited(`Rate limited: ${s.statusText}`,{status:s.status}):b.networkError(`HTTP ${s.status}: ${s.statusText}`,{status:s.status});let a=await s.json();return this.log("Identify response:",a),a}catch(s){throw s instanceof b?s:b.networkError(`Failed to send identify: ${s instanceof Error?s.message:String(s)}`,s)}}async fetchFlags(){let e=`${this.apiUrl}/v1/flags`;this.log("Fetching flags from",e);try{let n=await this.fetch(e,{method:"GET",headers:this.getHeaders()});if(!n.ok)throw b.networkError(`HTTP ${n.status}: ${n.statusText}`);let r=await n.json();return this.log("Flags response:",r),r.flags}catch(n){throw n instanceof b?n:b.networkError(`Failed to fetch flags: ${n instanceof Error?n.message:String(n)}`)}}async evaluateFlags(e){let n=`${this.apiUrl}/v1/flags/evaluate`,r=JSON.stringify({userId:e.userId??void 0,anonymousId:e.anonymousId,userTraits:e.userTraits});this.log("Evaluating flags at",n);try{let s=await this.fetch(n,{method:"POST",headers:this.getHeaders(),body:r});if(!s.ok)throw b.networkError(`HTTP ${s.status}: ${s.statusText}`);let a=await s.json();return this.log("Evaluate flags response:",a),a.flags}catch(s){throw s instanceof b?s:b.networkError(`Failed to evaluate flags: ${s instanceof Error?s.message:String(s)}`)}}setTenantId(e){this.tenantId=e;}setDebug(e){this.debug=e;}setSDKMeta(e){this.sdkMeta=e;}getHeaders(){let e={"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-SDK-Name":this.sdkMeta.name,"X-SDK-Version":this.sdkMeta.version};return this.tenantId&&(e["X-Tenant-Id"]=this.tenantId),e}toTrackApiPayload(e){return {eventId:e.event_id,eventName:e.event_name,timestamp:e.timestamp,anonymousId:e.anonymous_id,userId:e.user_id??void 0,sessionId:e.session_id??void 0,properties:e.properties,userTraits:e.user_traits,context:{platform:e.platform,appVersion:e.app_version??void 0,...e.context??{}}}}toIdentifyApiPayload(e){return {userId:e.user_id,anonymousId:e.anonymous_id,traits:e.traits,timestamp:e.timestamp}}sendViaBeacon(e,n){try{let r=new Blob([n],{type:"application/json"});return navigator.sendBeacon(e,r)}catch(r){return this.log("sendBeacon failed:",r),false}}async fetch(e,n){if(typeof fetch<"u")return fetch(e,n);throw b.networkError("fetch is not available in this environment")}log(...e){this.debug&&[...e];}},it=class{constructor(e,n=null){v(this,"config"),v(this,"storage",null),v(this,"identity"),v(this,"session"),v(this,"transport"),v(this,"queue"),v(this,"initialized",false),v(this,"tenantId"),v(this,"sessionNumber",0),v(this,"eventIndex",0),v(this,"lastSessionId",null),v(this,"flags",{}),v(this,"flagRefreshTimer",null),this.validateConfig(e),this.config={apiUrl:C.API_URL,debug:false,flushInterval:C.FLUSH_INTERVAL,flushAt:C.FLUSH_AT,maxQueueSize:C.MAX_QUEUE_SIZE,sessionTimeout:C.SESSION_TIMEOUT,...e},this.storage=n,this.tenantId=e.tenantId??"",this.identity=new Yt(n,this.config.debug),this.session=new Bt(n,this.config.sessionTimeout,{onSessionStart:r=>{this.log("Session started:",r),this.trackInternal("session_started",{session_id:r});},onSessionEnd:(r,s)=>{this.log("Session ended:",r,"duration:",s),this.trackInternal("session_ended",{session_id:r,duration_ms:s});}},this.config.debug),this.transport=new Kt({apiUrl:this.config.apiUrl,apiKey:this.config.apiKey,tenantId:this.tenantId,debug:this.config.debug}),this.queue=new Wt({flushAt:this.config.flushAt,flushInterval:this.config.flushInterval,maxQueueSize:this.config.maxQueueSize,storage:n,transport:this.transport,onError:(r,s)=>{this.config.onError?.(r),this.log("Queue error:",r.message,"events:",s.length);},debug:this.config.debug});}async initialize(){if(!this.initialized&&(await Promise.all([this.identity.initialize(),this.session.initialize(),this.queue.initialize()]),await this.loadSessionEnrichment(),await this.loadCachedFlags(),this.initialized=true,this.log("Client initialized"),this.config.featureFlags?.autoFetch!==false)){this.refreshFlags().catch(n=>{this.log("Auto-fetch flags error:",n);});let e=this.config.featureFlags?.refreshInterval??3e5;e>0&&(this.flagRefreshTimer=setInterval(()=>{this.refreshFlags().catch(n=>{this.log("Flag refresh error:",n);});},e));}}setTenant(e){this.tenantId=e,this.transport.setTenantId(e),this.log("Tenant set:",e);}async identify(e,n){await this.ensureInitialized(),await this.identity.setUserId(e),n&&await this.identity.setUserTraits(n);try{await this.transport.sendIdentify({project_id:this.config.projectId,environment:this.config.environment,tenant_id:this.tenantId,anonymous_id:this.identity.getAnonymousId(),user_id:e,traits:n,timestamp:rt()});}catch(r){let s=b.fromUnknown(r);this.config.onError?.(s),this.log("Identify error:",s.message);}this.config.featureFlags?.autoFetch!==false&&this.refreshFlags().catch(r=>{this.log("Post-identify flag refresh error:",r);});}async setUserTraits(e){await this.ensureInitialized(),await this.identity.setUserTraits(e);}async track(e,n,r){await this.ensureInitialized();let s=this.createEvent(e,n,r);if(this.session.touch(),r?.immediate)try{await this.transport.sendEvents([s]);}catch(a){let l=b.fromUnknown(a);this.config.onError?.(l),this.log("Immediate track error:",l.message);}else await this.queue.enqueue(s);}async flush(e){await this.ensureInitialized(),await this.queue.flush(e);}async reset(){await this.ensureInitialized(),this.session.forceEndSession(),await this.identity.reset(),this.log("Client reset");}setDebug(e){this.config.debug=e,this.identity.setDebug(e),this.session.setDebug(e),this.transport.setDebug(e),this.queue.setDebug(e);}getAnonymousId(){return this.identity.getAnonymousId()}getUserId(){return this.identity.getUserId()}getSessionId(){return this.session.getCurrentSessionId()}getQueueLength(){return this.queue.getQueueLength()}isFeatureEnabled(e,n=false){return this.flags[e]??n}getFeatureFlag(e,n=false){return this.flags[e]??n}getFeatureFlags(){return {...this.flags}}async refreshFlags(){try{let e=await this.transport.evaluateFlags({userId:this.identity.getUserId(),anonymousId:this.identity.getAnonymousId(),userTraits:this.identity.getUserTraits()});this.flags=e,this.persistFlags(),this.config.featureFlags?.onFlagsUpdated?.(e),this.log("Flags refreshed:",Object.keys(e).length,"flags");}catch(e){this.log("Flag refresh error:",e);}}destroy(){this.flagRefreshTimer&&(clearInterval(this.flagRefreshTimer),this.flagRefreshTimer=null),this.queue.destroy(),this.log("Client destroyed");}trackInternal(e,n){let r=this.createEvent(e,n);this.queue.enqueue(r).catch(s=>{this.log("Internal track error:",s);});}getContext(){return {}}createEvent(e,n,r){let s=r?.timestamp?Vt(r.timestamp):rt(),a=this.session.getSessionId();this.updateSessionEnrichment();let l={...this.getContext(),sessionNumber:this.sessionNumber,eventIndex:this.eventIndex};return {event_id:Z(),timestamp:s,project_id:this.config.projectId,environment:this.config.environment,tenant_id:this.tenantId,event_name:e,anonymous_id:this.identity.getAnonymousId(),user_id:this.identity.getUserId(),session_id:a,platform:this.config.platform,app_version:this.config.appVersion??null,properties:n??{},user_traits:this.identity.getUserTraits(),context:l}}async ensureInitialized(){this.initialized||await this.initialize();}validateConfig(e){if(!e.apiKey)throw b.invalidConfig("apiKey is required");if(!e.projectId)throw b.invalidConfig("projectId is required");if(!e.environment)throw b.invalidConfig("environment is required");if(!e.platform)throw b.invalidConfig("platform is required")}async loadSessionEnrichment(){if(this.storage)try{let e=await this.storage.get(S.SESSION_NUMBER),n=await this.storage.get(S.EVENT_INDEX);e&&(this.sessionNumber=parseInt(e,10)||0),n&&(this.eventIndex=parseInt(n,10)||0);}catch(e){this.log("Error loading session enrichment:",e);}}updateSessionEnrichment(){let e=this.session.getCurrentSessionId();e&&e!==this.lastSessionId&&(this.sessionNumber++,this.eventIndex=0,this.lastSessionId=e,this.persistSessionEnrichment()),this.eventIndex++,this.persistEventIndex();}persistSessionEnrichment(){this.storage&&this.storage.set(S.SESSION_NUMBER,String(this.sessionNumber)).catch(e=>{this.log("Error persisting session number:",e);});}persistEventIndex(){this.storage&&this.storage.set(S.EVENT_INDEX,String(this.eventIndex)).catch(e=>{this.log("Error persisting event index:",e);});}async loadCachedFlags(){if(this.storage)try{let e=await this.storage.get(S.FLAGS);e&&(this.flags=JSON.parse(e));}catch(e){this.log("Error loading cached flags:",e);}}persistFlags(){this.storage&&this.storage.set(S.FLAGS,JSON.stringify(this.flags)).catch(e=>{this.log("Error persisting flags:",e);});}log(...e){this.config.debug&&[...e];}};var st="pih_utm_params",Gt=["utm_source","utm_medium","utm_campaign","utm_term","utm_content"],V=class{constructor(n,r={}){p(this,"client");p(this,"config");p(this,"cachedUtmParams",null);p(this,"originalPushState",null);p(this,"originalReplaceState",null);p(this,"boundHandleClick");p(this,"boundHandlePopState");p(this,"boundHandleSubmit");this.client=n,this.config={pageViews:r.pageViews!==false,clicks:r.clicks??false,clickSelector:r.clickSelector??"[data-track]",forms:r.forms??false},this.boundHandleClick=this.handleClick.bind(this),this.boundHandlePopState=this.handlePopState.bind(this),this.boundHandleSubmit=this.handleSubmit.bind(this);}start(){typeof window>"u"||typeof document>"u"||(this.loadCachedUtmParams(),this.config.pageViews&&(this.setupPageViews(),this.trackPageView()),this.config.clicks&&this.setupClickTracking(),this.config.forms&&this.setupFormTracking());}stop(){this.originalPushState&&(history.pushState=this.originalPushState,this.originalPushState=null),this.originalReplaceState&&(history.replaceState=this.originalReplaceState,this.originalReplaceState=null),typeof window<"u"&&window.removeEventListener("popstate",this.boundHandlePopState),typeof document<"u"&&(document.removeEventListener("click",this.boundHandleClick,true),document.removeEventListener("submit",this.boundHandleSubmit,true));}trackPageView(){let n=new URL(window.location.href),r=this.extractUtmParams(n);Object.keys(r).length>0&&!this.cachedUtmParams&&(this.cachedUtmParams=r,this.persistUtmParams(r)),this.client.track("page_viewed",{path:n.pathname,search:n.search,hash:n.hash,referrer:document.referrer||null,title:document.title,url:window.location.href,...this.getUtmParams(n)});}setupPageViews(){this.originalPushState=history.pushState,this.originalReplaceState=history.replaceState;let n=this.originalPushState,r=this.originalReplaceState,s=()=>this.trackPageView();history.pushState=function(...a){n.apply(history,a),setTimeout(s,0);},history.replaceState=function(...a){r.apply(history,a),setTimeout(s,0);},window.addEventListener("popstate",this.boundHandlePopState);}handlePopState(){this.trackPageView();}setupClickTracking(){document.addEventListener("click",this.boundHandleClick,true);}handleClick(n){let r=n.target;if(!r)return;let s=r.closest(this.config.clickSelector);if(!s)return;let a=s.tagName.toLowerCase(),l=(s.textContent||"").trim().slice(0,100),g=s.id||null,k=s.className||null,T=s.getAttribute("data-track"),H=s instanceof HTMLAnchorElement?s.href:null;this.client.track("element_clicked",{element_tag:a,element_text:l,element_id:g,element_classes:k,data_track:T,href:H,path:window.location.pathname});}setupFormTracking(){document.addEventListener("submit",this.boundHandleSubmit,true);}handleSubmit(n){let r=n.target;!r||!(r instanceof HTMLFormElement)||this.client.track("form_submitted",{form_id:r.id||void 0,form_action:r.action||void 0,form_method:(r.method||"get").toUpperCase(),field_count:r.elements.length});}extractUtmParams(n){let r={};for(let s of Gt){let a=n.searchParams.get(s);a&&(r[s]=a);}return r}getUtmParams(n){let r=this.extractUtmParams(n);return Object.keys(r).length>0?r:this.cachedUtmParams??{}}loadCachedUtmParams(){try{let n=localStorage.getItem(st);n&&(this.cachedUtmParams=JSON.parse(n));}catch{}}persistUtmParams(n){try{localStorage.setItem(st,JSON.stringify(n));}catch{}}};var J=class{constructor(n){p(this,"client");p(this,"boundHandleVisibilityChange");p(this,"boundHandleBeforeUnload");this.client=n,this.boundHandleVisibilityChange=this.handleVisibilityChange.bind(this),this.boundHandleBeforeUnload=this.handleBeforeUnload.bind(this);}start(){typeof document<"u"&&document.addEventListener("visibilitychange",this.boundHandleVisibilityChange),typeof window<"u"&&(window.addEventListener("beforeunload",this.boundHandleBeforeUnload),window.addEventListener("pagehide",this.boundHandleBeforeUnload));}stop(){typeof document<"u"&&document.removeEventListener("visibilitychange",this.boundHandleVisibilityChange),typeof window<"u"&&(window.removeEventListener("beforeunload",this.boundHandleBeforeUnload),window.removeEventListener("pagehide",this.boundHandleBeforeUnload));}handleVisibilityChange(){document.visibilityState==="hidden"&&this.flushWithBeacon();}handleBeforeUnload(){this.flushWithBeacon();}flushWithBeacon(){this.client.flush({useBeacon:true}).catch(()=>{});}};function Xt(){if(typeof navigator>"u"||typeof window>"u")return "unknown";let e=navigator.userAgent.toLowerCase();if(/ipad|tablet|playbook|silk/.test(e))return "tablet";if(/mobile|iphone|ipod|android.*mobile|windows phone|blackberry|opera mini|opera mobi/.test(e))return "mobile";let n=window.screen?.width??0;return n>0&&n<768?"mobile":n>=768&&n<1024?"tablet":"desktop"}function Zt(){return typeof navigator>"u"?void 0:navigator.connection?.effectiveType??void 0}function ot(){if(typeof window>"u"||typeof document>"u")return {};let e={screenWidth:window.screen?.width??void 0,screenHeight:window.screen?.height??void 0,viewportWidth:window.innerWidth??void 0,viewportHeight:window.innerHeight??void 0,locale:navigator?.language??void 0,timezone:Jt(),deviceType:Xt(),pageUrl:window.location.href,pagePath:window.location.pathname,pageTitle:document.title||void 0,referrer:document.referrer||void 0},n=Zt();return n&&(e.connectionType=n),Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0))}function Jt(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}var en=[25,50,75,100],ee=class{constructor(){p(this,"client",null);p(this,"started",false);p(this,"visibleStartTime",0);p(this,"totalVisibleTime",0);p(this,"reachedThresholds",new Set);p(this,"boundHandleVisibilityChange");p(this,"boundHandleScroll");this.boundHandleVisibilityChange=this.handleVisibilityChange.bind(this),this.boundHandleScroll=this.handleScroll.bind(this);}start(n){this.started||typeof window>"u"||typeof document>"u"||(this.client=n,this.started=true,this.visibleStartTime=Date.now(),this.totalVisibleTime=0,this.reachedThresholds.clear(),document.visibilityState==="visible"&&(this.visibleStartTime=Date.now()),document.addEventListener("visibilitychange",this.boundHandleVisibilityChange),window.addEventListener("scroll",this.boundHandleScroll,{passive:true}));}stop(){this.started&&(this.accumulateVisibleTime(),this.totalVisibleTime>0&&this.client&&this.client.track("page_engaged",{visible_duration_ms:this.totalVisibleTime,page_path:typeof window<"u"?window.location.pathname:void 0}),typeof document<"u"&&document.removeEventListener("visibilitychange",this.boundHandleVisibilityChange),typeof window<"u"&&window.removeEventListener("scroll",this.boundHandleScroll),this.started=false,this.client=null);}handleVisibilityChange(){!this.started||!this.client||(document.visibilityState==="hidden"?(this.accumulateVisibleTime(),this.totalVisibleTime>0&&(this.client.track("page_engaged",{visible_duration_ms:this.totalVisibleTime,page_path:window.location.pathname}),this.totalVisibleTime=0)):this.visibleStartTime=Date.now());}accumulateVisibleTime(){this.visibleStartTime>0&&(this.totalVisibleTime+=Date.now()-this.visibleStartTime,this.visibleStartTime=Date.now());}handleScroll(){if(!this.started||!this.client)return;let n=this.getScrollPercent();for(let r of en)n>=r&&!this.reachedThresholds.has(r)&&(this.reachedThresholds.add(r),this.client.track("scroll_depth_reached",{depth_percent:r,page_path:window.location.pathname}));}getScrollPercent(){let n=Math.max(document.body.scrollHeight,document.documentElement.scrollHeight,document.body.offsetHeight,document.documentElement.offsetHeight,document.body.clientHeight,document.documentElement.clientHeight),r=window.innerHeight,s=window.scrollY||document.documentElement.scrollTop,a=n-r;return a<=0?100:Math.min(100,Math.round(s/a*100))}};var te=class{constructor(){p(this,"client",null);p(this,"started",false);p(this,"errorCount",0);p(this,"boundHandleError");p(this,"boundHandleRejection");this.boundHandleError=this.handleError.bind(this),this.boundHandleRejection=this.handleRejection.bind(this);}start(n){this.started||typeof window>"u"||(this.client=n,this.started=true,this.errorCount=0,window.addEventListener("error",this.boundHandleError),window.addEventListener("unhandledrejection",this.boundHandleRejection));}stop(){this.started&&(typeof window<"u"&&(window.removeEventListener("error",this.boundHandleError),window.removeEventListener("unhandledrejection",this.boundHandleRejection)),this.started=false,this.client=null);}handleError(n){!this.started||!this.client||this.canReport()&&(this.errorCount++,this.client.track("js_error",{message:n.message||"Unknown error",filename:n.filename||void 0,lineno:n.lineno||void 0,colno:n.colno||void 0,stack:n.error?.stack||void 0}));}handleRejection(n){if(!this.started||!this.client||!this.canReport())return;this.errorCount++;let r=n.reason,s=r instanceof Error?r.message:typeof r=="string"?r:"Unhandled promise rejection",a=r instanceof Error?r.stack:void 0;this.client.track("js_error",{message:s,filename:void 0,lineno:void 0,colno:void 0,stack:a});}canReport(){return this.errorCount<10}};var ne=class{constructor(){p(this,"client",null);p(this,"started",false);}start(n){this.started||(this.client=n,this.started=true,this.initWebVitals());}stop(){this.started=false,this.client=null;}async initWebVitals(){try{let r=await import('web-vitals'),s=a=>{!this.started||!this.client||this.client.track("web_vital",{name:a.name,value:a.value,rating:a.rating});};r.onLCP&&r.onLCP(s),r.onFID&&r.onFID(s),r.onCLS&&r.onCLS(s),r.onINP&&r.onINP(s),r.onTTFB&&r.onTTFB(s);}catch{}}};var z=class{constructor(){p(this,"data",new Map);}async get(n){return this.data.get(n)??null}async set(n,r){this.data.set(n,r);}async remove(n){this.data.delete(n);}};function tn(){try{let e="__pih_test__";return localStorage.setItem(e,e),localStorage.removeItem(e),!0}catch{return false}}var Ee=class{constructor(){p(this,"fallback",null);p(this,"useLocalStorage");this.useLocalStorage=tn(),this.useLocalStorage||(this.fallback=new z,console.warn("[PIH] localStorage unavailable, using in-memory storage. Data will not persist across page loads."));}async get(n){if(this.fallback)return this.fallback.get(n);try{return localStorage.getItem(n)}catch{return this.fallback||(this.fallback=new z),this.fallback.get(n)}}async set(n,r){if(this.fallback)return this.fallback.set(n,r);try{localStorage.setItem(n,r);}catch(s){return this.fallback||(this.fallback=new z,console.warn("[PIH] localStorage write failed, falling back to in-memory storage:",s)),this.fallback.set(n,r)}}async remove(n){if(this.fallback)return this.fallback.remove(n);try{localStorage.removeItem(n);}catch{}}};function we(){return new Ee}we();var D=Ft(Et());var Ce=new Set;function wt(e){return Ce.add(e),()=>Ce.delete(e)}function En(){for(let e of Ce)e();}function wn(e,n=false){let r=(0, D.useCallback)(()=>se()?.isFeatureEnabled(e,n)??n,[e,n]);return (0, D.useSyncExternalStore)(wt,r,()=>n)}function _n(){let e=(0, D.useCallback)(()=>se()?.getFeatureFlags()??{},[]);return (0, D.useSyncExternalStore)(wt,e,()=>({}))}var oe=class extends it{constructor(r,s){let a={...r,platform:"web"};super(a,s??we());p(this,"autocapture",null);p(this,"beacon");p(this,"performanceTracker",null);p(this,"engagementTracker",null);p(this,"errorTracker",null);this.transport.setSDKMeta({name:"pih-sdk-web",version:"0.2.0"}),this.beacon=new J(this);}getContext(){return ot()}async initialize(){await super.initialize(),this.beacon.start(),this.config.autocapture&&(this.autocapture=new V(this,this.config.autocapture),this.autocapture.start(),this.config.autocapture.performance&&(this.performanceTracker=new ne,this.performanceTracker.start(this)),this.config.autocapture.engagement&&(this.engagementTracker=new ee,this.engagementTracker.start(this)),this.config.autocapture.errorTracking&&(this.errorTracker=new te,this.errorTracker.start(this))),this.log("Web client initialized");}enableAutocapture(r){this.autocapture&&this.autocapture.stop(),this.autocapture=new V(this,r),this.autocapture.start();}disableAutocapture(){this.autocapture&&(this.autocapture.stop(),this.autocapture=null);}trackPageView(){if(this.autocapture)this.autocapture.trackPageView();else {let r=new URL(window.location.href);this.track("page_viewed",{path:r.pathname,search:r.search,hash:r.hash,referrer:document.referrer||null,title:document.title,url:window.location.href});}}destroy(){this.beacon.stop(),this.autocapture&&this.autocapture.stop(),this.performanceTracker&&(this.performanceTracker.stop(),this.performanceTracker=null),this.engagementTracker&&(this.engagementTracker.stop(),this.engagementTracker=null),this.errorTracker&&(this.errorTracker.stop(),this.errorTracker=null),super.destroy();}log(...r){this.config.debug&&[...r];}},O=null;function Sn(e){return O?(console.warn("[PIH] SDK already initialized. Returning existing instance."),O):(O=new oe(e),O.initialize().catch(n=>{console.error("[PIH] Failed to initialize:",n);}),O)}function se(){return O}function bn(){O&&(O.destroy(),O=null);}var Tn={init:Sn,getInstance:se,resetInstance:bn,WebPIHClient:oe},ir=Tn;/*! Bundled license information:
|
|
14
|
+
|
|
15
|
+
react/cjs/react.production.js:
|
|
16
|
+
(**
|
|
17
|
+
* @license React
|
|
18
|
+
* react.production.js
|
|
19
|
+
*
|
|
20
|
+
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
21
|
+
*
|
|
22
|
+
* This source code is licensed under the MIT license found in the
|
|
23
|
+
* LICENSE file in the root directory of this source tree.
|
|
24
|
+
*)
|
|
25
|
+
|
|
26
|
+
react/cjs/react.development.js:
|
|
27
|
+
(**
|
|
28
|
+
* @license React
|
|
29
|
+
* react.development.js
|
|
30
|
+
*
|
|
31
|
+
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
32
|
+
*
|
|
33
|
+
* This source code is licensed under the MIT license found in the
|
|
34
|
+
* LICENSE file in the root directory of this source tree.
|
|
35
|
+
*)
|
|
36
|
+
*/exports.WebPIHClient=oe;exports.default=ir;exports.getInstance=se;exports.init=Sn;exports.notifyFlagListeners=En;exports.resetInstance=bn;exports.useFeatureFlag=wn;exports.useFeatureFlags=_n;Object.defineProperty(exports,'__esModule',{value:true});return exports;})({});//# sourceMappingURL=index.global.js.map
|
|
3
37
|
//# sourceMappingURL=index.global.js.map
|