@prodantix/sdk 0.1.0-beta.341 → 0.1.0-beta.348

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1,7 +1,8 @@
1
- import { J as JsonValue, I as InboxMessage, S as StorageAdapter } from './client-BBUAoQg2.cjs';
2
- export { C as CaptureOptions, a as Clock, E as EventBatch, b as EventContext, c as EventEnvelope, d as EventProperties, F as FlagsResponse, e as IdFactory, f as IdentifyOptions, g as InboxResponse, L as LocalFlagContext, P as ProdantixClient, h as ProdantixConfig, T as Transport, i as TransportRequest, j as createClient } from './client-BBUAoQg2.cjs';
1
+ export { C as CaptureOptions, I as IdentifyOptions, L as LocalFlagContext, P as ProdantixClient, c as createClient } from './client-y1xyVF6C.cjs';
2
+ import { J as JsonValue, F as FlagsResponse, I as InboxMessage, a as StorageAdapter } from './types-68Sc11g8.cjs';
3
+ export { C as Clock, E as EventBatch, b as EventContext, c as EventEnvelope, d as EventProperties, e as FlagVariant, f as IdFactory, g as InboxResponse, P as ProdantixConfig, T as Transport, h as TransportRequest } from './types-68Sc11g8.cjs';
3
4
  import { F as FetchLike } from './http-BCh716Vs.cjs';
4
- export { F as FetchTransport } from './transport-DhhzvwpV.cjs';
5
+ export { F as FetchTransport } from './transport-Bj4nXmgt.cjs';
5
6
 
6
7
  type ProdantixErrorCode = 'config' | 'queue_overflow' | 'transport' | 'validation';
7
8
  declare class ProdantixError extends Error {
@@ -20,7 +21,7 @@ declare class TransportError extends ProdantixError {
20
21
  constructor(message: string, status?: number, options?: ErrorOptions);
21
22
  }
22
23
 
23
- type FlagOp = 'eq' | 'neq' | 'in' | 'not_in' | 'contains' | 'gt' | 'gte' | 'lt' | 'lte' | 'is_set' | 'is_not_set';
24
+ type FlagOp = 'eq' | 'neq' | 'in' | 'not_in' | 'contains' | 'gt' | 'gte' | 'lt' | 'lte' | 'is_set' | 'is_not_set' | 'in_cohort' | 'not_in_cohort';
24
25
  interface FlagCondition {
25
26
  attribute: string;
26
27
  op: FlagOp;
@@ -28,6 +29,7 @@ interface FlagCondition {
28
29
  }
29
30
  interface FlagEvalContext {
30
31
  attributes?: Record<string, JsonValue>;
32
+ cohorts?: string[];
31
33
  distinctId: string;
32
34
  properties?: Record<string, JsonValue>;
33
35
  }
@@ -38,11 +40,16 @@ interface FlagVariation {
38
40
  value: unknown;
39
41
  weight: number;
40
42
  }
43
+ interface FlagPrerequisite {
44
+ flagKey: string;
45
+ variationKey: string;
46
+ }
41
47
  interface FlagRule {
42
48
  description?: string;
43
49
  enabled: boolean;
44
50
  intent?: string;
45
51
  key: string;
52
+ prerequisites?: FlagPrerequisite[];
46
53
  rolloutPercentage: number;
47
54
  targeting: FlagCondition[];
48
55
  type?: string;
@@ -51,6 +58,7 @@ interface FlagRule {
51
58
  interface FlagSnapshot {
52
59
  flags: FlagRule[];
53
60
  generatedAt: string;
61
+ socketUrl?: string;
54
62
  }
55
63
  interface FlagDecision {
56
64
  enabled: boolean;
@@ -75,7 +83,11 @@ declare class FlagsClient {
75
83
  private readonly requestTimeoutMs;
76
84
  constructor(options: FlagsClientOptions);
77
85
  fetchAll(distinctId: string): Promise<Record<string, boolean>>;
86
+ fetchDecisions(distinctId: string): Promise<FlagsResponse>;
78
87
  snapshot(): Promise<FlagSnapshot>;
88
+ /** The cohorts a distinct id belongs to, for local evaluation of cohort
89
+ * conditions against the same membership store the server reads. */
90
+ memberships(distinctId: string): Promise<string[]>;
79
91
  }
80
92
 
81
93
  interface MessagesClientOptions {
@@ -107,4 +119,4 @@ declare class MemoryStorage implements StorageAdapter {
107
119
  declare const SDK_NAME = "prodantix-js";
108
120
  declare const SDK_VERSION = "0.0.1";
109
121
 
110
- export { ConfigError, type FlagCondition, type FlagDecision, type FlagEvalContext, type FlagOp, type FlagRule, type FlagSnapshot, type FlagVariation, FlagsClient, InboxMessage, JsonValue, MemoryStorage, MessagesClient, ProdantixError, type ProdantixErrorCode, SDK_NAME, SDK_VERSION, StorageAdapter, TransportError, ValidationError, assignVariant, bucket, evaluateAll, evaluateFlag, getVariant, matches };
122
+ export { ConfigError, type FlagCondition, type FlagDecision, type FlagEvalContext, type FlagOp, type FlagRule, type FlagSnapshot, type FlagVariation, FlagsClient, FlagsResponse, InboxMessage, JsonValue, MemoryStorage, MessagesClient, ProdantixError, type ProdantixErrorCode, SDK_NAME, SDK_VERSION, StorageAdapter, TransportError, ValidationError, assignVariant, bucket, evaluateAll, evaluateFlag, getVariant, matches };
package/dist/index.d.ts CHANGED
@@ -1,7 +1,8 @@
1
- import { J as JsonValue, I as InboxMessage, S as StorageAdapter } from './client-BBUAoQg2.js';
2
- export { C as CaptureOptions, a as Clock, E as EventBatch, b as EventContext, c as EventEnvelope, d as EventProperties, F as FlagsResponse, e as IdFactory, f as IdentifyOptions, g as InboxResponse, L as LocalFlagContext, P as ProdantixClient, h as ProdantixConfig, T as Transport, i as TransportRequest, j as createClient } from './client-BBUAoQg2.js';
1
+ export { C as CaptureOptions, I as IdentifyOptions, L as LocalFlagContext, P as ProdantixClient, c as createClient } from './client-Ca6xJESF.js';
2
+ import { J as JsonValue, F as FlagsResponse, I as InboxMessage, a as StorageAdapter } from './types-68Sc11g8.js';
3
+ export { C as Clock, E as EventBatch, b as EventContext, c as EventEnvelope, d as EventProperties, e as FlagVariant, f as IdFactory, g as InboxResponse, P as ProdantixConfig, T as Transport, h as TransportRequest } from './types-68Sc11g8.js';
3
4
  import { F as FetchLike } from './http-BCh716Vs.js';
4
- export { F as FetchTransport } from './transport-dWp3NUMj.js';
5
+ export { F as FetchTransport } from './transport-CTPih3Jj.js';
5
6
 
6
7
  type ProdantixErrorCode = 'config' | 'queue_overflow' | 'transport' | 'validation';
7
8
  declare class ProdantixError extends Error {
@@ -20,7 +21,7 @@ declare class TransportError extends ProdantixError {
20
21
  constructor(message: string, status?: number, options?: ErrorOptions);
21
22
  }
22
23
 
23
- type FlagOp = 'eq' | 'neq' | 'in' | 'not_in' | 'contains' | 'gt' | 'gte' | 'lt' | 'lte' | 'is_set' | 'is_not_set';
24
+ type FlagOp = 'eq' | 'neq' | 'in' | 'not_in' | 'contains' | 'gt' | 'gte' | 'lt' | 'lte' | 'is_set' | 'is_not_set' | 'in_cohort' | 'not_in_cohort';
24
25
  interface FlagCondition {
25
26
  attribute: string;
26
27
  op: FlagOp;
@@ -28,6 +29,7 @@ interface FlagCondition {
28
29
  }
29
30
  interface FlagEvalContext {
30
31
  attributes?: Record<string, JsonValue>;
32
+ cohorts?: string[];
31
33
  distinctId: string;
32
34
  properties?: Record<string, JsonValue>;
33
35
  }
@@ -38,11 +40,16 @@ interface FlagVariation {
38
40
  value: unknown;
39
41
  weight: number;
40
42
  }
43
+ interface FlagPrerequisite {
44
+ flagKey: string;
45
+ variationKey: string;
46
+ }
41
47
  interface FlagRule {
42
48
  description?: string;
43
49
  enabled: boolean;
44
50
  intent?: string;
45
51
  key: string;
52
+ prerequisites?: FlagPrerequisite[];
46
53
  rolloutPercentage: number;
47
54
  targeting: FlagCondition[];
48
55
  type?: string;
@@ -51,6 +58,7 @@ interface FlagRule {
51
58
  interface FlagSnapshot {
52
59
  flags: FlagRule[];
53
60
  generatedAt: string;
61
+ socketUrl?: string;
54
62
  }
55
63
  interface FlagDecision {
56
64
  enabled: boolean;
@@ -75,7 +83,11 @@ declare class FlagsClient {
75
83
  private readonly requestTimeoutMs;
76
84
  constructor(options: FlagsClientOptions);
77
85
  fetchAll(distinctId: string): Promise<Record<string, boolean>>;
86
+ fetchDecisions(distinctId: string): Promise<FlagsResponse>;
78
87
  snapshot(): Promise<FlagSnapshot>;
88
+ /** The cohorts a distinct id belongs to, for local evaluation of cohort
89
+ * conditions against the same membership store the server reads. */
90
+ memberships(distinctId: string): Promise<string[]>;
79
91
  }
80
92
 
81
93
  interface MessagesClientOptions {
@@ -107,4 +119,4 @@ declare class MemoryStorage implements StorageAdapter {
107
119
  declare const SDK_NAME = "prodantix-js";
108
120
  declare const SDK_VERSION = "0.0.1";
109
121
 
110
- export { ConfigError, type FlagCondition, type FlagDecision, type FlagEvalContext, type FlagOp, type FlagRule, type FlagSnapshot, type FlagVariation, FlagsClient, InboxMessage, JsonValue, MemoryStorage, MessagesClient, ProdantixError, type ProdantixErrorCode, SDK_NAME, SDK_VERSION, StorageAdapter, TransportError, ValidationError, assignVariant, bucket, evaluateAll, evaluateFlag, getVariant, matches };
122
+ export { ConfigError, type FlagCondition, type FlagDecision, type FlagEvalContext, type FlagOp, type FlagRule, type FlagSnapshot, type FlagVariation, FlagsClient, FlagsResponse, InboxMessage, JsonValue, MemoryStorage, MessagesClient, ProdantixError, type ProdantixErrorCode, SDK_NAME, SDK_VERSION, StorageAdapter, TransportError, ValidationError, assignVariant, bucket, evaluateAll, evaluateFlag, getVariant, matches };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- export{b as ConfigError,r as FetchTransport,p as FlagsClient,e as MemoryStorage,q as MessagesClient,s as ProdantixClient,a as ProdantixError,h as SDK_NAME,i as SDK_VERSION,d as TransportError,c as ValidationError,n as assignVariant,k as bucket,t as createClient,m as evaluateAll,l as evaluateFlag,o as getVariant,j as matches}from'./chunk-7J6AQICL.js';import'./chunk-VG77TYVX.js';import'./chunk-5XGN7UAV.js';//# sourceMappingURL=index.js.map
1
+ export{b as ConfigError,r as FetchTransport,p as FlagsClient,e as MemoryStorage,q as MessagesClient,s as ProdantixClient,a as ProdantixError,h as SDK_NAME,i as SDK_VERSION,d as TransportError,c as ValidationError,n as assignVariant,k as bucket,t as createClient,m as evaluateAll,l as evaluateFlag,o as getVariant,j as matches}from'./chunk-CSIP3PZ7.js';import'./chunk-V77KYPOF.js';import'./chunk-VG77TYVX.js';import'./chunk-5XGN7UAV.js';//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map
package/dist/node.cjs CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var U=Object.defineProperty;var B=(t,e,r)=>e in t?U(t,e,{enumerable:true,configurable:true,writable:true,value:r}):t[e]=r;var i=(t,e,r)=>B(t,typeof e!="symbol"?e+"":e,r);var c=class extends Error{constructor(r,s,n){super(s,n);i(this,"code");this.code=r,this.name="ProdantixError";}},g=class extends c{constructor(e){super("config",e),this.name="ConfigError";}},f=class extends c{constructor(r,s){super("validation",s);i(this,"field");this.field=r,this.name="ValidationError";}},l=class extends c{constructor(r,s,n){super("transport",r,n);i(this,"status");this.status=s,this.name="TransportError";}};function m(t){if(t)return t;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function d(){let t=globalThis.AbortController;return t?new t:void 0}var P=t=>new Promise(e=>{setTimeout(e,t);});function u(t){return t.replace(/\/+$/,"")}var y=class{constructor(){i(this,"store",new Map);}getItem(e){return this.store.get(e)??null}removeItem(e){this.store.delete(e);}setItem(e,r){this.store.set(e,r);}};var S={now:()=>new Date};function v(t){return t.toISOString()}function H(){return globalThis.crypto}function G(t){t[6]=t[6]&15|64,t[8]=t[8]&63|128;let e=[];for(let r=0;r<16;r+=1)e.push(t[r].toString(16).padStart(2,"0"));return `${e[0]}${e[1]}${e[2]}${e[3]}-${e[4]}${e[5]}-${e[6]}${e[7]}-${e[8]}${e[9]}-${e[10]}${e[11]}${e[12]}${e[13]}${e[14]}${e[15]}`}function X(){let t=H();if(t?.randomUUID)return t.randomUUID();let e=new Uint8Array(16);if(t?.getRandomValues)t.getRandomValues(e);else for(let r=0;r<16;r+=1)e[r]=Math.floor(Math.random()*256);return G(e)}var C={uuid:X};var Y=/^pdx_pub_(?:(?:live|test)_)?[a-z0-9]{32}$/;var Z=/^(?:\$|[a-z])[a-z0-9_.]*$/;function _(t){let e=0;for(let r of t)e+=1;return e}function R(t){return Y.test(t)}function W(t){return Z.test(t)}function $(t){let e=_(t);if(e<1||e>200)throw new f("distinct_id","distinct_id must be between 1 and 200 characters")}function M(t){let e=_(t);if(e<1||e>200)throw new f("event_name","event_name must be between 1 and 200 characters");if(!W(t))throw new f("event_name","event_name must match /^(\\$|[a-z])[a-z0-9_.]*$/")}var A="prodantix-js",q="0.0.1";var ee=t=>{};function N(t){if(!t.apiKey||!R(t.apiKey))throw new g("apiKey must be a public project key of the form pdx_pub_<32 lowercase alphanumerics>");if(!t.host)throw new g("host is required (the ingest base URL)");let e=u(t.host),r=t.defaultProperties;return {apiKey:t.apiKey,autocapture:t.autocapture??false,clock:t.clock??S,defaultProperties:typeof r=="function"?r:()=>r??{},flagsHost:t.flagsHost?u(t.flagsHost):e,flushAt:t.flushAt??20,flushIntervalMs:t.flushIntervalMs??1e4,host:e,ids:t.ids??C,locale:t.locale,maxQueueSize:t.maxQueueSize??1e3,maxRetries:t.maxRetries??3,namespace:t.apiKey.slice(0,16),onError:t.onError??ee,os:t.os,requestTimeoutMs:t.requestTimeoutMs??1e4,sdkName:t.sdkName??A,sdkVersion:t.sdkVersion??q,storage:t.storage??new y,transport:t.transport}}function O(t,e,r){M(t.eventName),$(t.distinctId);let s={distinct_id:t.distinctId,event_id:t.eventId??r.uuid(),event_name:t.eventName,properties:t.properties??{},schema_version:1,timestamp:v(t.timestamp??e.now())};return t.context&&(s.context=t.context),t.sessionId&&(s.session_id=t.sessionId),s}var h=Symbol("absent");function te(t,e){if(t==="distinct_id")return e.distinctId;let r=e.properties??{};if(Object.prototype.hasOwnProperty.call(r,t))return r[t];let s=e.attributes??{};return Object.prototype.hasOwnProperty.call(s,t)?s[t]:h}function p(t){return t===h?"undefined":String(t)}function L(t){return t===h?Number.NaN:Number(t)}function D(t){return t!==h&&t!==null&&t!==""}function K(t,e){if(!Array.isArray(e))return false;let r=p(t);return e.map(s=>String(s)).includes(r)}function j(t,e){let r=te(t.attribute,e),s=t.value;switch(t.op){case "is_set":return D(r);case "is_not_set":return !D(r);case "eq":return p(r)===p(s===void 0?h:s);case "neq":return p(r)!==p(s===void 0?h:s);case "contains":return p(r).includes(p(s===void 0?h:s));case "in":return K(r,s);case "not_in":return Array.isArray(s)?!K(r,s):false;case "gt":return x(r,s,(n,o)=>n>o);case "gte":return x(r,s,(n,o)=>n>=o);case "lt":return x(r,s,(n,o)=>n<o);case "lte":return x(r,s,(n,o)=>n<=o);default:return false}}function x(t,e,r){let s=L(t),n=e===void 0?Number.NaN:L(e);return Number.isNaN(s)||Number.isNaN(n)?false:r(s,n)}function re(t,e){let r=`${t}:${e}`,s=2166136261;for(let n=0;n<r.length;n++)s^=r.charCodeAt(n),s=Math.imul(s,16777619);return (s>>>0)%100}function se(t,e){return t.enabled?t.targeting.length>0&&!t.targeting.every(r=>j(r,e))?{enabled:false,reason:"targeting"}:t.rolloutPercentage>=100?{enabled:true,reason:"rollout_full"}:re(t.key,e.distinctId)<t.rolloutPercentage?{enabled:true,reason:"rollout"}:{enabled:false,reason:"rollout_excluded"}:{enabled:false,reason:"disabled"}}function V(t,e){let r={};for(let s of t)r[s.key]=se(s,e).enabled;return r}var b=class{constructor(e){i(this,"fetch");i(this,"host");i(this,"projectKey");i(this,"requestTimeoutMs");this.fetch=m(e.fetch),this.host=u(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async fetchAll(e){let r=this.fetch;if(!r)throw new l("no fetch implementation available in this runtime");let s=`${this.host}/v1/flags?distinct_id=${encodeURIComponent(e)}`,n=d(),o=n?setTimeout(()=>n.abort(),this.requestTimeoutMs):void 0;try{let a=await r(s,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:n?.signal});if(!a.ok)throw new l(`flags request failed with status ${a.status}`,a.status);return JSON.parse(await a.text()).flags??{}}finally{o!==void 0&&clearTimeout(o);}}async snapshot(){let e=this.fetch;if(!e)throw new l("no fetch implementation available in this runtime");let r=`${this.host}/v1/flags/snapshot`,s=d(),n=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{let o=await e(r,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:s?.signal});if(!o.ok)throw new l(`flag snapshot request failed with status ${o.status}`,o.status);let a=JSON.parse(await o.text());return {flags:a.flags??[],generatedAt:a.generatedAt}}finally{n!==void 0&&clearTimeout(n);}}};var I=class{constructor(e,r,s){this.storage=e;this.ids=r;this.namespace=s;i(this,"anonymousId");i(this,"distinctId");i(this,"identified");let n=e.getItem(this.key("anonymous_id"));n?this.anonymousId=n:(this.anonymousId=r.uuid(),e.setItem(this.key("anonymous_id"),this.anonymousId));let o=e.getItem(this.key("distinct_id"));o?(this.distinctId=o,this.identified=true):(this.distinctId=this.anonymousId,this.identified=false);}getAnonymousId(){return this.anonymousId}getDistinctId(){return this.distinctId}isIdentified(){return this.identified}snapshot(){return {anonymousId:this.anonymousId,distinctId:this.distinctId,identified:this.identified}}identify(e){return this.identified&&this.distinctId===e?{changed:false}:(this.distinctId=e,this.identified=true,this.storage.setItem(this.key("distinct_id"),e),{changed:true})}reset(){this.anonymousId=this.ids.uuid(),this.distinctId=this.anonymousId,this.identified=false,this.storage.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.removeItem(this.key("distinct_id"));}key(e){return `pdx.${this.namespace}.${e}`}};var E=class{constructor(e){i(this,"fetch");i(this,"host");i(this,"projectKey");i(this,"requestTimeoutMs");this.fetch=m(e.fetch),this.host=u(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async inbox(e){let r=this.requireFetch(),s=`${this.host}/v1/messages?distinct_id=${encodeURIComponent(e)}`,n=await this.request(r,s,{headers:this.authHeaders(),method:"GET"});if(!n.ok)throw new l(`inbox request failed with status ${n.status}`,n.status);return JSON.parse(await n.text()).messages??[]}async markRead(e,r){let s=this.requireFetch(),n=`${this.host}/v1/messages/read`,o=await this.request(s,n,{body:JSON.stringify({distinct_id:r,message_id:e}),headers:{...this.authHeaders(),"content-type":"application/json"},method:"POST"});if(!o.ok)throw new l(`mark-read request failed with status ${o.status}`,o.status)}requireFetch(){if(!this.fetch)throw new l("no fetch implementation available in this runtime");return this.fetch}authHeaders(){return {authorization:`Bearer ${this.projectKey}`}}async request(e,r,s){let n=d(),o=n?setTimeout(()=>n.abort(),this.requestTimeoutMs):void 0;try{return await e(r,{...s,signal:n?.signal})}finally{o!==void 0&&clearTimeout(o);}}};var F=class{constructor(e,r){this.maxSize=e;this.onOverflow=r;i(this,"events",[]);}get size(){return this.events.length}enqueue(e){this.events.push(e),this.enforceCap();}restore(e){this.events.push(...e),this.enforceCap();}requeue(e){this.events.unshift(...e),this.enforceCap();}drain(e){let r=e===void 0?this.events.length:Math.min(e,this.events.length);return this.events.splice(0,r)}snapshot(){return [...this.events]}enforceCap(){if(this.events.length<=this.maxSize)return;let e=this.events.splice(0,this.events.length-this.maxSize);this.onOverflow?.({dropped:e});}};function z(t){return t>=400&&t<500&&t!==429}var k=class{constructor(e={}){i(this,"fetch");i(this,"maxRetries");i(this,"requestTimeoutMs");i(this,"baseDelayMs");i(this,"maxDelayMs");i(this,"sleep");i(this,"random");this.fetch=m(e.fetch),this.maxRetries=e.maxRetries??3,this.requestTimeoutMs=e.requestTimeoutMs??1e4,this.baseDelayMs=e.baseDelayMs??500,this.maxDelayMs=e.maxDelayMs??3e4,this.sleep=e.sleep??P,this.random=e.random??Math.random;}async send(e){let r=this.fetch;if(!r)throw new l("no fetch implementation available in this runtime");let s=JSON.stringify(e.body),n;for(let o=0;o<=this.maxRetries;o+=1){try{let a=await this.attempt(r,e,s);if(a.ok)return;if(z(a.status))throw new l(`ingest rejected batch with status ${a.status}`,a.status);n=new l(`ingest transient status ${a.status}`,a.status);}catch(a){if(a instanceof l&&a.status!==void 0&&z(a.status))throw a;n=a;}o<this.maxRetries&&await this.sleep(this.backoff(o));}throw new l("ingest delivery failed after retries",void 0,{cause:n})}async attempt(e,r,s){let n=d(),o=n?setTimeout(()=>n.abort(),this.requestTimeoutMs):void 0;try{return await e(r.url,{body:s,headers:{authorization:`Bearer ${r.projectKey}`,"content-type":"application/json"},method:"POST",signal:n?.signal})}finally{o!==void 0&&clearTimeout(o);}}backoff(e){return Math.min(this.maxDelayMs,this.baseDelayMs*2**e)+this.random()*this.baseDelayMs}};var ne="queue",ie=1e3,oe=3e4,J=t=>{let e={};return t.avatar!==void 0&&(e.$avatar=t.avatar),t.email!==void 0&&(e.$email=t.email),t.name!==void 0&&(e.$name=t.name),t.phone!==void 0&&(e.$phone=t.phone),e},w=class{constructor(e){i(this,"config");i(this,"identity");i(this,"queue");i(this,"transport");i(this,"flagsClient");i(this,"messagesClient");i(this,"context");i(this,"flushTimer");i(this,"flushing",false);i(this,"cachedFlags");i(this,"cachedSnapshot");this.config=N(e),this.identity=new I(this.config.storage,this.config.ids,this.config.namespace),this.queue=new F(this.config.maxQueueSize,({dropped:r})=>{this.config.onError(new c("queue_overflow",`event queue overflow: dropped ${r.length} oldest event(s)`));}),this.transport=this.config.transport??new k({maxRetries:this.config.maxRetries,requestTimeoutMs:this.config.requestTimeoutMs}),this.flagsClient=new b({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.messagesClient=new E({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.context={sdk:this.config.sdkName,sdk_version:this.config.sdkVersion},this.config.os&&(this.context.os=this.config.os),this.config.locale&&(this.context.locale=this.config.locale),this.restoreQueue(),this.startTimer();}get distinctId(){return this.identity.getDistinctId()}get anonymousId(){return this.identity.getAnonymousId()}capture(e,r={}){try{let s={...this.config.defaultProperties(),...r.properties??{}},n=O({context:this.context,distinctId:this.identity.getDistinctId(),eventName:e,properties:s,sessionId:r.sessionId,timestamp:r.timestamp},this.config.clock,this.config.ids);this.enqueue(n);}catch(s){this.config.onError(s);}}identify(e,r={}){let s=this.identity.getAnonymousId(),n=!this.identity.isIdentified(),o=this.identity.identify(e),a={};n&&o.changed&&(a.$anon_distinct_id=s);let T={...J(r.traits??{}),...r.set??{}};Object.keys(T).length>0&&(a.$set=T),this.capture("$identify",{properties:a});}alias(e){this.capture("$create_alias",{properties:{alias:e}});}group(e,r,s){let n={$group_key:r,$group_type:e};s&&(n.$set=s),this.capture("$group",{properties:n});}setPersonProperties(e,r){let s={};e&&(s.$set=e),r&&(s.$set_once=r),this.capture("$set",{properties:s});}setPersonTraits(e){let r=J(e);Object.keys(r).length!==0&&this.capture("$set",{properties:{$set:r}});}async getAllFlags(){let e=this.identity.getDistinctId(),r=await this.flagsClient.fetchAll(e);return this.cachedFlags={distinctId:e,flags:r},r}async isFeatureEnabled(e){return (await this.getAllFlags())[e]??false}getCachedFlag(e){if(!(!this.cachedFlags||this.cachedFlags.distinctId!==this.distinctId))return this.cachedFlags.flags[e]}async getLocalFlags(e={}){let r=await this.flagSnapshot();return V(r.flags,{attributes:e.attributes,distinctId:this.identity.getDistinctId(),properties:e.properties})}async isFeatureEnabledLocal(e,r){return (await this.getLocalFlags(r))[e]??false}async flagSnapshot(){let e=this.config.clock.now().getTime();if(this.cachedSnapshot&&e-this.cachedSnapshot.fetchedAt<oe)return this.cachedSnapshot.snapshot;let r=await this.flagsClient.snapshot();return this.cachedSnapshot={fetchedAt:e,snapshot:r},r}async getInbox(){return this.messagesClient.inbox(this.identity.getDistinctId())}async markMessageRead(e){await this.messagesClient.markRead(e,this.identity.getDistinctId());}async flush(){if(this.flushing||this.queue.size===0)return;this.flushing=true;let e=this.queue.drain(ie);try{await this.transport.send({body:{events:e,sent_at:v(this.config.clock.now())},projectKey:this.config.apiKey,url:`${this.config.host}/v1/events`}),this.persistQueue();}catch(r){this.queue.requeue(e),this.persistQueue(),this.config.onError(r);}finally{this.flushing=false;}}reset(){this.identity.reset(),this.cachedFlags=void 0,this.cachedSnapshot=void 0;}async shutdown(){this.stopTimer(),await this.flush();}enqueue(e){this.queue.enqueue(e),this.persistQueue(),this.queue.size>=this.config.flushAt&&this.flush();}persistQueue(){try{this.config.storage.setItem(this.persistKey(),JSON.stringify(this.queue.snapshot()));}catch(e){this.config.onError(e);}}restoreQueue(){try{let e=this.config.storage.getItem(this.persistKey());if(!e)return;let r=JSON.parse(e);Array.isArray(r)&&this.queue.restore(r);}catch(e){this.config.onError(e);}}startTimer(){if(this.config.flushIntervalMs<=0)return;let e=setInterval(()=>{this.flush();},this.config.flushIntervalMs),r=e;typeof r.unref=="function"&&r.unref(),this.flushTimer=e;}stopTimer(){this.flushTimer!==void 0&&(clearInterval(this.flushTimer),this.flushTimer=void 0);}persistKey(){return `pdx.${this.config.namespace}.${ne}`}};function Q(){return globalThis.process}function ae(t){Q()?.on("beforeExit",()=>{t.flush();});}function lt(t){let e=Q(),r={...t,os:t.os??(e?.platform?e.platform.slice(0,50):void 0)},s=new w(r);return ae(s),s}exports.createNodeClient=lt;//# sourceMappingURL=node.cjs.map
1
+ 'use strict';var oe=Object.defineProperty;var ae=(n,e,t)=>e in n?oe(n,e,{enumerable:true,configurable:true,writable:true,value:t}):n[e]=t;var o=(n,e,t)=>ae(n,typeof e!="symbol"?e+"":e,t);var d=class extends Error{constructor(t,r,s){super(r,s);o(this,"code");this.code=t,this.name="ProdantixError";}},y=class extends d{constructor(e){super("config",e),this.name="ConfigError";}},g=class extends d{constructor(t,r){super("validation",r);o(this,"field");this.field=t,this.name="ValidationError";}},c=class extends d{constructor(t,r,s){super("transport",t,s);o(this,"status");this.status=r,this.name="TransportError";}};function m(n){if(n)return n;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function u(){let n=globalThis.AbortController;return n?new n:void 0}var $=n=>new Promise(e=>{setTimeout(e,n);});function h(n){return n.replace(/\/+$/,"")}var v=class{constructor(){o(this,"store",new Map);}getItem(e){return this.store.get(e)??null}removeItem(e){this.store.delete(e);}setItem(e,t){this.store.set(e,t);}};var A={now:()=>new Date};function b(n){return n.toISOString()}function ce(){return globalThis.crypto}function le(n){n[6]=n[6]&15|64,n[8]=n[8]&63|128;let e=[];for(let t=0;t<16;t+=1)e.push(n[t].toString(16).padStart(2,"0"));return `${e[0]}${e[1]}${e[2]}${e[3]}-${e[4]}${e[5]}-${e[6]}${e[7]}-${e[8]}${e[9]}-${e[10]}${e[11]}${e[12]}${e[13]}${e[14]}${e[15]}`}function ue(){let n=ce();if(n?.randomUUID)return n.randomUUID();let e=new Uint8Array(16);if(n?.getRandomValues)n.getRandomValues(e);else for(let t=0;t<16;t+=1)e[t]=Math.floor(Math.random()*256);return le(e)}var O={uuid:ue};var de=/^pdx_pub_(?:(?:live|test)_)?[a-z0-9]{32}$/;var he=/^(?:\$|[a-z])[a-z0-9_.]*$/;function q(n){let e=0;for(let t of n)e+=1;return e}function M(n){return de.test(n)}function pe(n){return he.test(n)}function K(n){let e=q(n);if(e<1||e>200)throw new g("distinct_id","distinct_id must be between 1 and 200 characters")}function L(n){let e=q(n);if(e<1||e>200)throw new g("event_name","event_name must be between 1 and 200 characters");if(!pe(n))throw new g("event_name","event_name must match /^(\\$|[a-z])[a-z0-9_.]*$/")}var D="prodantix-js",V="0.0.1";var fe=n=>{};function j(n){if(!n.apiKey||!M(n.apiKey))throw new y("apiKey must be a public project key of the form pdx_pub_<32 lowercase alphanumerics>");if(!n.host)throw new y("host is required (the ingest base URL)");let e=h(n.host),t=n.defaultProperties;return {apiKey:n.apiKey,autocapture:n.autocapture??false,clock:n.clock??A,defaultProperties:typeof t=="function"?t:()=>t??{},flagsHost:n.flagsHost?h(n.flagsHost):e,flushAt:n.flushAt??20,flushIntervalMs:n.flushIntervalMs??1e4,host:e,ids:n.ids??O,locale:n.locale,maxQueueSize:n.maxQueueSize??1e3,maxRetries:n.maxRetries??3,namespace:n.apiKey.slice(0,16),onError:n.onError??fe,os:n.os,requestTimeoutMs:n.requestTimeoutMs??1e4,sdkName:n.sdkName??D,sdkVersion:n.sdkVersion??V,socketFactory:n.socketFactory,storage:n.storage??new v,streamFlags:n.streamFlags??false,transport:n.transport}}function G(n,e,t){L(n.eventName),K(n.distinctId);let r={distinct_id:n.distinctId,event_id:n.eventId??t.uuid(),event_name:n.eventName,properties:n.properties??{},schema_version:1,timestamp:b(n.timestamp??e.now())};return n.context&&(r.context=n.context),n.sessionId&&(r.session_id=n.sessionId),r}var f=Symbol("absent");function ge(n,e){if(n==="distinct_id")return e.distinctId;let t=e.properties??{};if(Object.prototype.hasOwnProperty.call(t,n))return t[n];let r=e.attributes??{};return Object.prototype.hasOwnProperty.call(r,n)?r[n]:f}function p(n){return n===f?"undefined":String(n)}function U(n){return n===f?Number.NaN:Number(n)}function z(n){return n!==f&&n!==null&&n!==""}function H(n,e){if(!Array.isArray(e))return false;let t=p(n);return e.map(r=>String(r)).includes(t)}function J(n,e){let t=ge(n.attribute,e),r=n.value;switch(n.op){case "is_set":return z(t);case "is_not_set":return !z(t);case "eq":return p(t)===p(r===void 0?f:r);case "neq":return p(t)!==p(r===void 0?f:r);case "contains":return p(t).includes(p(r===void 0?f:r));case "in":return H(t,r);case "not_in":return Array.isArray(r)?!H(t,r):false;case "gt":return k(t,r,(s,i)=>s>i);case "gte":return k(t,r,(s,i)=>s>=i);case "lt":return k(t,r,(s,i)=>s<i);case "lte":return k(t,r,(s,i)=>s<=i);case "in_cohort":return typeof r=="string"&&r!==""&&(e.cohorts??[]).includes(r);case "not_in_cohort":return typeof r=="string"&&r!==""&&!(e.cohorts??[]).includes(r);default:return false}}function k(n,e,t){let r=U(n),s=e===void 0?Number.NaN:U(e);return Number.isNaN(r)||Number.isNaN(s)?false:t(r,s)}function Q(n,e){let t=`${n}:${e}`,r=2166136261;for(let s=0;s<t.length;s++)r^=t.charCodeAt(s),r=Math.imul(r,16777619);return (r>>>0)%100}function _(n,e){return n.targeting.length===0||n.targeting.every(t=>J(t,e))}function B(n,e){let t=Q(n.key,e.distinctId),r=n.variations??[];if(r.length===0)return n.rolloutPercentage>=100||t<n.rolloutPercentage?"true":"false";let s=0;for(let i=r.length-1;i>=0;i--)if(s+=r[i].weight,t<s)return r[i].key;return r[0].key}function P(n,e,t,r){for(let s of n.prerequisites??[]){if(r.includes(s.flagKey))return false;let i=e.find(l=>l.key===s.flagKey);if(!i||!i.enabled)return false;r.push(i.key);let a=P(i,e,t,r)&&_(i,t)&&B(i,t)===s.variationKey;if(r.pop(),!a)return false}return true}function x(n,e,t){return n.enabled?P(n,e,t,[n.key])?_(n,t)?n.rolloutPercentage>=100?{enabled:true,reason:"rollout_full"}:Q(n.key,t.distinctId)<n.rolloutPercentage?{enabled:true,reason:"rollout"}:{enabled:false,reason:"rollout_excluded"}:{enabled:false,reason:"targeting"}:{enabled:false,reason:"prerequisite"}:{enabled:false,reason:"disabled"}}function W(n,e){let t={};for(let r of n)t[r.key]=x(r,n,e).enabled;return t}function R(n,e,t){let r=n.variations??[],s=r[0];if(!s)return null;if(!n.enabled||!P(n,e,t,[n.key])||!_(n,t))return s;let i=B(n,t);return r.find(a=>a.key===i)??s}function X(n){return n.some(e=>e.targeting.some(t=>t.op==="in_cohort"||t.op==="not_in_cohort"))}function Y(n){return `40${JSON.stringify(n)}`}function Z(){return "3"}function ee(n){let e=n.charAt(0),t=n.slice(1);if(e==="2")return {kind:"ping"};if(e==="1")return {kind:"disconnect"};if(e==="0"){let a=N(t);return {kind:"open",pingInterval:typeof a?.pingInterval=="number"?a.pingInterval:25e3,pingTimeout:typeof a?.pingTimeout=="number"?a.pingTimeout:2e4}}if(e!=="4")return {kind:"other"};let r=t.charAt(0),s=t.slice(1);if(r==="0")return {kind:"connected"};if(r==="1")return {kind:"disconnect"};if(r==="4"){let a=N(s);return {kind:"connectError",message:typeof a?.message=="string"?a.message:"refused"}}if(r!=="2")return {kind:"other"};let i=N(s);return !Array.isArray(i)||typeof i[0]!="string"?{kind:"other"}:{kind:"event",name:i[0],payload:i[1]}}function N(n){try{return JSON.parse(n)}catch{return null}}var me="/socket.io/?EIO=4&transport=websocket",ye=250,E=class{constructor(e){this.options=e;o(this,"socket",null);o(this,"heartbeat",null);o(this,"pending",null);o(this,"lastKey","");o(this,"ready",false);o(this,"closed",false);o(this,"heartbeatWindow",45e3);o(this,"factory");o(this,"setTimer");o(this,"clearTimer");this.factory=e.socketFactory??ve,this.setTimer=e.setTimer??((t,r)=>setTimeout(t,r)),this.clearTimer=e.clearTimer??(t=>clearTimeout(t));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${me}`,t;try{t=this.factory(e);}catch{this.options.onClosed(false);return}this.socket=t,t.onmessage=r=>this.receive(String(r.data)),t.onerror=()=>t.close(),t.onclose=()=>this.fell();}close(){this.closed=true,this.stopHeartbeat(),this.pending!==null&&this.clearTimer(this.pending),this.pending=null;let e=this.socket;this.socket=null,e?.close();}receive(e){let t=ee(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),this.socket?.send(Y({projectKey:this.options.projectKey}));return}if(t.kind==="ping"){this.armHeartbeat(),this.socket?.send(Z());return}if(t.kind==="connectError"||t.kind==="disconnect"){this.stopHeartbeat(),this.socket?.close();return}if(t.kind==="event"){if(t.name==="ready"){this.ready=true;return}if(t.name==="flagChange"){let r=t.payload?.key;this.lastKey=typeof r=="string"?r:"",this.pending===null&&(this.pending=this.setTimer(()=>{this.pending=null,this.options.onChange(this.lastKey);},ye));}}}fell(){this.stopHeartbeat();let e=this.ready;this.socket=null,this.ready=false,this.closed||this.options.onClosed(e);}armHeartbeat(e){e!==void 0&&(this.heartbeatWindow=e),this.stopHeartbeat(),this.heartbeat=this.setTimer(()=>this.socket?.close(),this.heartbeatWindow);}stopHeartbeat(){this.heartbeat!==null&&this.clearTimer(this.heartbeat),this.heartbeat=null;}};function ve(n){let e=globalThis.WebSocket;if(!e)throw new Error("no WebSocket");return new e(n)}var F=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=m(e.fetch),this.host=h(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async fetchAll(e){return (await this.fetchDecisions(e)).flags}async fetchDecisions(e){let t=this.fetch;if(!t)throw new c("no fetch implementation available in this runtime");let r=`${this.host}/v1/flags?distinct_id=${encodeURIComponent(e)}`,s=u(),i=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{let a=await t(r,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:s?.signal});if(!a.ok)throw new c(`flags request failed with status ${a.status}`,a.status);let l=JSON.parse(await a.text());return {flags:l.flags??{},variants:l.variants??{}}}finally{i!==void 0&&clearTimeout(i);}}async snapshot(){let e=this.fetch;if(!e)throw new c("no fetch implementation available in this runtime");let t=`${this.host}/v1/flags/snapshot`,r=u(),s=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let i=await e(t,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!i.ok)throw new c(`flag snapshot request failed with status ${i.status}`,i.status);let a=JSON.parse(await i.text()),l={flags:a.flags??[],generatedAt:a.generatedAt};return typeof a.socketUrl=="string"&&a.socketUrl!==""&&(l.socketUrl=a.socketUrl),l}finally{s!==void 0&&clearTimeout(s);}}async memberships(e){let t=this.fetch;if(!t)throw new c("no fetch implementation available in this runtime");let r=`${this.host}/v1/flags/memberships?distinct_id=${encodeURIComponent(e)}`,s=u(),i=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{let a=await t(r,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:s?.signal});if(!a.ok)throw new c(`memberships request failed with status ${a.status}`,a.status);return JSON.parse(await a.text()).cohorts??[]}finally{i!==void 0&&clearTimeout(i);}}};var I=class{constructor(e,t,r){this.storage=e;this.ids=t;this.namespace=r;o(this,"anonymousId");o(this,"distinctId");o(this,"identified");let s=e.getItem(this.key("anonymous_id"));s?this.anonymousId=s:(this.anonymousId=t.uuid(),e.setItem(this.key("anonymous_id"),this.anonymousId));let i=e.getItem(this.key("distinct_id"));i?(this.distinctId=i,this.identified=true):(this.distinctId=this.anonymousId,this.identified=false);}getAnonymousId(){return this.anonymousId}getDistinctId(){return this.distinctId}isIdentified(){return this.identified}snapshot(){return {anonymousId:this.anonymousId,distinctId:this.distinctId,identified:this.identified}}identify(e){return this.identified&&this.distinctId===e?{changed:false}:(this.distinctId=e,this.identified=true,this.storage.setItem(this.key("distinct_id"),e),{changed:true})}reset(){this.anonymousId=this.ids.uuid(),this.distinctId=this.anonymousId,this.identified=false,this.storage.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.removeItem(this.key("distinct_id"));}key(e){return `pdx.${this.namespace}.${e}`}};var C=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=m(e.fetch),this.host=h(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async inbox(e){let t=this.requireFetch(),r=`${this.host}/v1/messages?distinct_id=${encodeURIComponent(e)}`,s=await this.request(t,r,{headers:this.authHeaders(),method:"GET"});if(!s.ok)throw new c(`inbox request failed with status ${s.status}`,s.status);return JSON.parse(await s.text()).messages??[]}async markRead(e,t){let r=this.requireFetch(),s=`${this.host}/v1/messages/read`,i=await this.request(r,s,{body:JSON.stringify({distinct_id:t,message_id:e}),headers:{...this.authHeaders(),"content-type":"application/json"},method:"POST"});if(!i.ok)throw new c(`mark-read request failed with status ${i.status}`,i.status)}requireFetch(){if(!this.fetch)throw new c("no fetch implementation available in this runtime");return this.fetch}authHeaders(){return {authorization:`Bearer ${this.projectKey}`}}async request(e,t,r){let s=u(),i=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{return await e(t,{...r,signal:s?.signal})}finally{i!==void 0&&clearTimeout(i);}}};var S=class{constructor(e,t){this.maxSize=e;this.onOverflow=t;o(this,"events",[]);}get size(){return this.events.length}enqueue(e){this.events.push(e),this.enforceCap();}restore(e){this.events.push(...e),this.enforceCap();}requeue(e){this.events.unshift(...e),this.enforceCap();}drain(e){let t=e===void 0?this.events.length:Math.min(e,this.events.length);return this.events.splice(0,t)}snapshot(){return [...this.events]}enforceCap(){if(this.events.length<=this.maxSize)return;let e=this.events.splice(0,this.events.length-this.maxSize);this.onOverflow?.({dropped:e});}};function te(n){return n>=400&&n<500&&n!==429}var w=class{constructor(e={}){o(this,"fetch");o(this,"maxRetries");o(this,"requestTimeoutMs");o(this,"baseDelayMs");o(this,"maxDelayMs");o(this,"sleep");o(this,"random");this.fetch=m(e.fetch),this.maxRetries=e.maxRetries??3,this.requestTimeoutMs=e.requestTimeoutMs??1e4,this.baseDelayMs=e.baseDelayMs??500,this.maxDelayMs=e.maxDelayMs??3e4,this.sleep=e.sleep??$,this.random=e.random??Math.random;}async send(e){let t=this.fetch;if(!t)throw new c("no fetch implementation available in this runtime");let r=JSON.stringify(e.body),s;for(let i=0;i<=this.maxRetries;i+=1){try{let a=await this.attempt(t,e,r);if(a.ok)return;if(te(a.status))throw new c(`ingest rejected batch with status ${a.status}`,a.status);s=new c(`ingest transient status ${a.status}`,a.status);}catch(a){if(a instanceof c&&a.status!==void 0&&te(a.status))throw a;s=a;}i<this.maxRetries&&await this.sleep(this.backoff(i));}throw new c("ingest delivery failed after retries",void 0,{cause:s})}async attempt(e,t,r){let s=u(),i=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{return await e(t.url,{body:r,headers:{authorization:`Bearer ${t.projectKey}`,"content-type":"application/json"},method:"POST",signal:s?.signal})}finally{i!==void 0&&clearTimeout(i);}}backoff(e){return Math.min(this.maxDelayMs,this.baseDelayMs*2**e)+this.random()*this.baseDelayMs}};var be="queue",ke=1e3,ne=3e4,re=n=>{let e={};return n.avatar!==void 0&&(e.$avatar=n.avatar),n.email!==void 0&&(e.$email=n.email),n.name!==void 0&&(e.$name=n.name),n.phone!==void 0&&(e.$phone=n.phone),e},T=class{constructor(e){o(this,"config");o(this,"identity");o(this,"queue");o(this,"transport");o(this,"flagsClient");o(this,"messagesClient");o(this,"context");o(this,"flushTimer");o(this,"flushing",false);o(this,"cachedFlags");o(this,"cachedSnapshot");o(this,"membershipCache");o(this,"stream");o(this,"shutDown",false);o(this,"exposures",new Set);this.config=j(e),this.identity=new I(this.config.storage,this.config.ids,this.config.namespace),this.queue=new S(this.config.maxQueueSize,({dropped:t})=>{this.config.onError(new d("queue_overflow",`event queue overflow: dropped ${t.length} oldest event(s)`));}),this.transport=this.config.transport??new w({maxRetries:this.config.maxRetries,requestTimeoutMs:this.config.requestTimeoutMs}),this.flagsClient=new F({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.messagesClient=new C({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.context={sdk:this.config.sdkName,sdk_version:this.config.sdkVersion},this.config.os&&(this.context.os=this.config.os),this.config.locale&&(this.context.locale=this.config.locale),this.restoreQueue(),this.startTimer();}get distinctId(){return this.identity.getDistinctId()}get anonymousId(){return this.identity.getAnonymousId()}capture(e,t={}){try{let r={...this.config.defaultProperties(),...t.properties??{}},s=G({context:this.context,distinctId:this.identity.getDistinctId(),eventName:e,properties:r,sessionId:t.sessionId,timestamp:t.timestamp},this.config.clock,this.config.ids);this.enqueue(s);}catch(r){this.config.onError(r);}}identify(e,t={}){let r=this.identity.getAnonymousId(),s=!this.identity.isIdentified(),i=this.identity.identify(e),a={};s&&i.changed&&(a.$anon_distinct_id=r);let l={...re(t.traits??{}),...t.set??{}};Object.keys(l).length>0&&(a.$set=l),this.capture("$identify",{properties:a});}alias(e){this.capture("$create_alias",{properties:{alias:e}});}group(e,t,r){let s={$group_key:t,$group_type:e};r&&(s.$set=r),this.capture("$group",{properties:s});}setPersonProperties(e,t){let r={};e&&(r.$set=e),t&&(r.$set_once=t),this.capture("$set",{properties:r});}setPersonTraits(e){let t=re(e);Object.keys(t).length!==0&&this.capture("$set",{properties:{$set:t}});}async getAllFlags(){let e=this.identity.getDistinctId(),t=await this.flagsClient.fetchDecisions(e);return this.cachedFlags={distinctId:e,flags:t.flags,variants:t.variants??{}},t.flags}async isFeatureEnabled(e){let r=(await this.getAllFlags())[e]??false;return this.recordExposure(e,this.cachedFlags?.variants[e]?.key??String(r)),r}async getVariant(e){let t=await this.getAllFlags(),r=this.cachedFlags?.variants[e]??null;return this.recordExposure(e,r?.key??String(t[e]??false)),r}async getVariantLocal(e,t={}){let r=await this.flagSnapshot(),s=r.flags.find(ie=>ie.key===e),i=await this.localContext(t,r.flags),a=s?R(s,r.flags,i):null,l=s?x(s,r.flags,i).enabled:false;return this.recordExposure(e,a?.key??String(l)),a?{key:a.key,value:a.value}:null}recordExposure(e,t){let r=`${this.identity.getDistinctId()} ${e} ${t}`;this.exposures.has(r)||(this.exposures.add(r),this.capture("$feature_flag_called",{properties:{$feature_flag:e,$feature_flag_response:t}}));}getCachedFlag(e){if(!(!this.cachedFlags||this.cachedFlags.distinctId!==this.distinctId))return this.cachedFlags.flags[e]}async getLocalFlags(e={}){let t=await this.flagSnapshot();return W(t.flags,await this.localContext(e,t.flags))}async isFeatureEnabledLocal(e,t={}){let r=await this.flagSnapshot(),s=r.flags.find(l=>l.key===e),i=await this.localContext(t,r.flags),a=s?x(s,r.flags,i).enabled:false;return this.recordExposure(e,(s?R(s,r.flags,i)?.key:void 0)??String(a)),a}async localContext(e,t){let r=this.identity.getDistinctId(),s=e.cohorts;if(s===void 0&&X(t)){let i=this.config.clock.now().getTime();this.membershipCache&&this.membershipCache.distinctId===r&&i-this.membershipCache.fetchedAt<ne?s=this.membershipCache.cohorts:(s=await this.flagsClient.memberships(r),this.membershipCache={cohorts:s,distinctId:r,fetchedAt:i});}return {attributes:e.attributes,cohorts:s,distinctId:r,properties:e.properties}}async flagSnapshot(){let e=this.config.clock.now().getTime();if(this.cachedSnapshot&&e-this.cachedSnapshot.fetchedAt<ne)return this.cachedSnapshot.snapshot;let t=await this.flagsClient.snapshot();return this.cachedSnapshot={fetchedAt:e,snapshot:t},this.maybeStream(t),t}maybeStream(e){if(!this.config.streamFlags||this.shutDown||this.stream||!e.socketUrl)return;let t=new E({host:e.socketUrl,onChange:()=>{this.cachedSnapshot=void 0,this.flagSnapshot().catch(r=>this.config.onError(r));},onClosed:r=>{this.stream=void 0,r&&this.maybeStream(e);},projectKey:this.config.apiKey,socketFactory:this.config.socketFactory});this.stream=t,t.open();}async getInbox(){return this.messagesClient.inbox(this.identity.getDistinctId())}async markMessageRead(e){await this.messagesClient.markRead(e,this.identity.getDistinctId());}async flush(){if(this.flushing||this.queue.size===0)return;this.flushing=true;let e=this.queue.drain(ke);try{await this.transport.send({body:{events:e,sent_at:b(this.config.clock.now())},projectKey:this.config.apiKey,url:`${this.config.host}/v1/events`}),this.persistQueue();}catch(t){this.queue.requeue(e),this.persistQueue(),this.config.onError(t);}finally{this.flushing=false;}}reset(){this.identity.reset(),this.cachedFlags=void 0,this.cachedSnapshot=void 0,this.membershipCache=void 0;}async shutdown(){this.shutDown=true,this.stopTimer(),this.stream?.close(),this.stream=void 0,await this.flush();}enqueue(e){this.queue.enqueue(e),this.persistQueue(),this.queue.size>=this.config.flushAt&&this.flush();}persistQueue(){try{this.config.storage.setItem(this.persistKey(),JSON.stringify(this.queue.snapshot()));}catch(e){this.config.onError(e);}}restoreQueue(){try{let e=this.config.storage.getItem(this.persistKey());if(!e)return;let t=JSON.parse(e);Array.isArray(t)&&this.queue.restore(t);}catch(e){this.config.onError(e);}}startTimer(){if(this.config.flushIntervalMs<=0)return;let e=setInterval(()=>{this.flush();},this.config.flushIntervalMs),t=e;typeof t.unref=="function"&&t.unref(),this.flushTimer=e;}stopTimer(){this.flushTimer!==void 0&&(clearInterval(this.flushTimer),this.flushTimer=void 0);}persistKey(){return `pdx.${this.config.namespace}.${be}`}};function se(){return globalThis.process}function xe(n){se()?.on("beforeExit",()=>{n.flush();});}function wt(n){let e=se(),t={...n,os:n.os??(e?.platform?e.platform.slice(0,50):void 0),streamFlags:n.streamFlags??true},r=new T(t);return xe(r),r}exports.createNodeClient=wt;//# sourceMappingURL=node.cjs.map
2
2
  //# sourceMappingURL=node.cjs.map
package/dist/node.d.cts CHANGED
@@ -1,4 +1,5 @@
1
- import { h as ProdantixConfig, P as ProdantixClient } from './client-BBUAoQg2.cjs';
1
+ import { P as ProdantixClient } from './client-y1xyVF6C.cjs';
2
+ import { P as ProdantixConfig } from './types-68Sc11g8.cjs';
2
3
 
3
4
  declare function createNodeClient(options: ProdantixConfig): ProdantixClient;
4
5
 
package/dist/node.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- import { h as ProdantixConfig, P as ProdantixClient } from './client-BBUAoQg2.js';
1
+ import { P as ProdantixClient } from './client-Ca6xJESF.js';
2
+ import { P as ProdantixConfig } from './types-68Sc11g8.js';
2
3
 
3
4
  declare function createNodeClient(options: ProdantixConfig): ProdantixClient;
4
5
 
package/dist/node.js CHANGED
@@ -1,2 +1,2 @@
1
- import {s as s$1}from'./chunk-7J6AQICL.js';import'./chunk-VG77TYVX.js';import'./chunk-5XGN7UAV.js';function t(){return globalThis.process}function s(o){t()?.on("beforeExit",()=>{o.flush();});}function f(o){let e=t(),r={...o,os:o.os??(e?.platform?e.platform.slice(0,50):void 0)},n=new s$1(r);return s(n),n}export{f as createNodeClient};//# sourceMappingURL=node.js.map
1
+ import {s as s$1}from'./chunk-CSIP3PZ7.js';import'./chunk-V77KYPOF.js';import'./chunk-VG77TYVX.js';import'./chunk-5XGN7UAV.js';function r(){return globalThis.process}function s(e){r()?.on("beforeExit",()=>{e.flush();});}function a(e){let o=r(),i={...e,os:e.os??(o?.platform?o.platform.slice(0,50):void 0),streamFlags:e.streamFlags??true},n=new s$1(i);return s(n),n}export{a as createNodeClient};//# sourceMappingURL=node.js.map
2
2
  //# sourceMappingURL=node.js.map
@@ -1,5 +1,5 @@
1
1
  import { F as FetchLike } from './http-BCh716Vs.cjs';
2
- import { T as Transport, i as TransportRequest } from './client-BBUAoQg2.cjs';
2
+ import { T as Transport, h as TransportRequest } from './types-68Sc11g8.cjs';
3
3
 
4
4
  interface FetchTransportOptions {
5
5
  baseDelayMs?: number;
@@ -1,5 +1,5 @@
1
1
  import { F as FetchLike } from './http-BCh716Vs.js';
2
- import { T as Transport, i as TransportRequest } from './client-BBUAoQg2.js';
2
+ import { T as Transport, h as TransportRequest } from './types-68Sc11g8.js';
3
3
 
4
4
  interface FetchTransportOptions {
5
5
  baseDelayMs?: number;
@@ -0,0 +1,105 @@
1
+ type JsonPrimitive = string | number | boolean | null;
2
+ type JsonValue = JsonPrimitive | JsonValue[] | {
3
+ [key: string]: JsonValue;
4
+ };
5
+ type EventProperties = Record<string, JsonValue>;
6
+ interface EventContext {
7
+ locale?: string;
8
+ os?: string;
9
+ sdk?: string;
10
+ sdk_version?: string;
11
+ }
12
+ interface EventEnvelope {
13
+ context?: EventContext;
14
+ distinct_id: string;
15
+ event_id: string;
16
+ event_name: string;
17
+ properties: EventProperties;
18
+ schema_version: 1;
19
+ session_id?: string;
20
+ timestamp: string;
21
+ }
22
+ interface EventBatch {
23
+ api_key?: string;
24
+ events: EventEnvelope[];
25
+ sent_at: string;
26
+ }
27
+ interface FlagVariant {
28
+ key: string;
29
+ value: unknown;
30
+ }
31
+ interface FlagsResponse {
32
+ flags: Record<string, boolean>;
33
+ variants?: Record<string, FlagVariant>;
34
+ }
35
+ interface InboxMessage {
36
+ body: string;
37
+ createdAt: string;
38
+ id: string;
39
+ read: boolean;
40
+ title: string;
41
+ }
42
+ interface InboxResponse {
43
+ messages: InboxMessage[];
44
+ }
45
+ interface Clock {
46
+ now(): Date;
47
+ }
48
+ interface IdFactory {
49
+ uuid(): string;
50
+ }
51
+ interface StorageAdapter {
52
+ getItem(key: string): string | null;
53
+ removeItem(key: string): void;
54
+ setItem(key: string, value: string): void;
55
+ }
56
+ interface TransportRequest {
57
+ body: EventBatch;
58
+ projectKey: string;
59
+ url: string;
60
+ }
61
+ interface Transport {
62
+ send(request: TransportRequest): Promise<void>;
63
+ }
64
+ /** The browser's `WebSocket`, narrowed to what the SDK uses so a test can hand
65
+ * in a fake without a DOM. Assigning the handlers rather than using
66
+ * `addEventListener` keeps the surface to four properties. */
67
+ interface SocketLike {
68
+ send(data: string): void;
69
+ close(): void;
70
+ onopen: (() => void) | null;
71
+ onclose: (() => void) | null;
72
+ onerror: (() => void) | null;
73
+ onmessage: ((event: {
74
+ data: string;
75
+ }) => void) | null;
76
+ }
77
+ type SocketFactory = (url: string) => SocketLike;
78
+ interface ProdantixConfig {
79
+ apiKey: string;
80
+ autocapture?: boolean;
81
+ clock?: Clock;
82
+ defaultProperties?: EventProperties | (() => EventProperties);
83
+ flagsHost?: string;
84
+ flushAt?: number;
85
+ flushIntervalMs?: number;
86
+ host: string;
87
+ ids?: IdFactory;
88
+ locale?: string;
89
+ maxQueueSize?: number;
90
+ maxRetries?: number;
91
+ onError?: (error: unknown) => void;
92
+ os?: string;
93
+ requestTimeoutMs?: number;
94
+ sdkName?: string;
95
+ sdkVersion?: string;
96
+ /** The socket constructor the flag stream uses; the test seam. */
97
+ socketFactory?: SocketFactory;
98
+ storage?: StorageAdapter;
99
+ /** Hold a Socket.IO subscription to flag changes and refetch the snapshot on
100
+ * push. Off unless asked; the node entry turns it on. */
101
+ streamFlags?: boolean;
102
+ transport?: Transport;
103
+ }
104
+
105
+ export type { Clock as C, EventBatch as E, FlagsResponse as F, InboxMessage as I, JsonValue as J, ProdantixConfig as P, SocketFactory as S, Transport as T, StorageAdapter as a, EventContext as b, EventEnvelope as c, EventProperties as d, FlagVariant as e, IdFactory as f, InboxResponse as g, TransportRequest as h };
@@ -0,0 +1,105 @@
1
+ type JsonPrimitive = string | number | boolean | null;
2
+ type JsonValue = JsonPrimitive | JsonValue[] | {
3
+ [key: string]: JsonValue;
4
+ };
5
+ type EventProperties = Record<string, JsonValue>;
6
+ interface EventContext {
7
+ locale?: string;
8
+ os?: string;
9
+ sdk?: string;
10
+ sdk_version?: string;
11
+ }
12
+ interface EventEnvelope {
13
+ context?: EventContext;
14
+ distinct_id: string;
15
+ event_id: string;
16
+ event_name: string;
17
+ properties: EventProperties;
18
+ schema_version: 1;
19
+ session_id?: string;
20
+ timestamp: string;
21
+ }
22
+ interface EventBatch {
23
+ api_key?: string;
24
+ events: EventEnvelope[];
25
+ sent_at: string;
26
+ }
27
+ interface FlagVariant {
28
+ key: string;
29
+ value: unknown;
30
+ }
31
+ interface FlagsResponse {
32
+ flags: Record<string, boolean>;
33
+ variants?: Record<string, FlagVariant>;
34
+ }
35
+ interface InboxMessage {
36
+ body: string;
37
+ createdAt: string;
38
+ id: string;
39
+ read: boolean;
40
+ title: string;
41
+ }
42
+ interface InboxResponse {
43
+ messages: InboxMessage[];
44
+ }
45
+ interface Clock {
46
+ now(): Date;
47
+ }
48
+ interface IdFactory {
49
+ uuid(): string;
50
+ }
51
+ interface StorageAdapter {
52
+ getItem(key: string): string | null;
53
+ removeItem(key: string): void;
54
+ setItem(key: string, value: string): void;
55
+ }
56
+ interface TransportRequest {
57
+ body: EventBatch;
58
+ projectKey: string;
59
+ url: string;
60
+ }
61
+ interface Transport {
62
+ send(request: TransportRequest): Promise<void>;
63
+ }
64
+ /** The browser's `WebSocket`, narrowed to what the SDK uses so a test can hand
65
+ * in a fake without a DOM. Assigning the handlers rather than using
66
+ * `addEventListener` keeps the surface to four properties. */
67
+ interface SocketLike {
68
+ send(data: string): void;
69
+ close(): void;
70
+ onopen: (() => void) | null;
71
+ onclose: (() => void) | null;
72
+ onerror: (() => void) | null;
73
+ onmessage: ((event: {
74
+ data: string;
75
+ }) => void) | null;
76
+ }
77
+ type SocketFactory = (url: string) => SocketLike;
78
+ interface ProdantixConfig {
79
+ apiKey: string;
80
+ autocapture?: boolean;
81
+ clock?: Clock;
82
+ defaultProperties?: EventProperties | (() => EventProperties);
83
+ flagsHost?: string;
84
+ flushAt?: number;
85
+ flushIntervalMs?: number;
86
+ host: string;
87
+ ids?: IdFactory;
88
+ locale?: string;
89
+ maxQueueSize?: number;
90
+ maxRetries?: number;
91
+ onError?: (error: unknown) => void;
92
+ os?: string;
93
+ requestTimeoutMs?: number;
94
+ sdkName?: string;
95
+ sdkVersion?: string;
96
+ /** The socket constructor the flag stream uses; the test seam. */
97
+ socketFactory?: SocketFactory;
98
+ storage?: StorageAdapter;
99
+ /** Hold a Socket.IO subscription to flag changes and refetch the snapshot on
100
+ * push. Off unless asked; the node entry turns it on. */
101
+ streamFlags?: boolean;
102
+ transport?: Transport;
103
+ }
104
+
105
+ export type { Clock as C, EventBatch as E, FlagsResponse as F, InboxMessage as I, JsonValue as J, ProdantixConfig as P, SocketFactory as S, Transport as T, StorageAdapter as a, EventContext as b, EventEnvelope as c, EventProperties as d, FlagVariant as e, IdFactory as f, InboxResponse as g, TransportRequest as h };
package/dist/web.cjs CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var fe=Object.defineProperty;var me=(t,e,n)=>e in t?fe(t,e,{enumerable:true,configurable:true,writable:true,value:n}):t[e]=n;var i=(t,e,n)=>me(t,typeof e!="symbol"?e+"":e,n);var h=class extends Error{constructor(n,r,s){super(r,s);i(this,"code");this.code=n,this.name="ProdantixError";}},x=class extends h{constructor(e){super("config",e),this.name="ConfigError";}},y=class extends h{constructor(n,r){super("validation",r);i(this,"field");this.field=n,this.name="ValidationError";}},u=class extends h{constructor(n,r,s){super("transport",n,s);i(this,"status");this.status=r,this.name="TransportError";}};function c(t){if(t)return t;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function f(){let t=globalThis.AbortController;return t?new t:void 0}var D=t=>new Promise(e=>{setTimeout(e,t);});function p(t){return t.replace(/\/+$/,"")}var v=class{constructor(){i(this,"store",new Map);}getItem(e){return this.store.get(e)??null}removeItem(e){this.store.delete(e);}setItem(e,n){this.store.set(e,n);}};function K(){try{let t=globalThis.localStorage;if(t){let e="__pdx_probe__";return t.setItem(e,"1"),t.removeItem(e),t}}catch{return new v}return new v}var V={now:()=>new Date};function E(t){return t.toISOString()}function ge(){return globalThis.crypto}function ye(t){t[6]=t[6]&15|64,t[8]=t[8]&63|128;let e=[];for(let n=0;n<16;n+=1)e.push(t[n].toString(16).padStart(2,"0"));return `${e[0]}${e[1]}${e[2]}${e[3]}-${e[4]}${e[5]}-${e[6]}${e[7]}-${e[8]}${e[9]}-${e[10]}${e[11]}${e[12]}${e[13]}${e[14]}${e[15]}`}function O(){let t=ge();if(t?.randomUUID)return t.randomUUID();let e=new Uint8Array(16);if(t?.getRandomValues)t.getRandomValues(e);else for(let n=0;n<16;n+=1)e[n]=Math.floor(Math.random()*256);return ye(e)}var j={uuid:O};var ve=/^pdx_pub_(?:(?:live|test)_)?[a-z0-9]{32}$/;var be=/^(?:\$|[a-z])[a-z0-9_.]*$/;function z(t){let e=0;for(let n of t)e+=1;return e}function H(t){return ve.test(t)}function xe(t){return be.test(t)}function B(t){let e=z(t);if(e<1||e>200)throw new y("distinct_id","distinct_id must be between 1 and 200 characters")}function U(t){let e=z(t);if(e<1||e>200)throw new y("event_name","event_name must be between 1 and 200 characters");if(!xe(t))throw new y("event_name","event_name must match /^(\\$|[a-z])[a-z0-9_.]*$/")}var J="prodantix-js",Q="0.0.1";var ke=t=>{};function W(t){if(!t.apiKey||!H(t.apiKey))throw new x("apiKey must be a public project key of the form pdx_pub_<32 lowercase alphanumerics>");if(!t.host)throw new x("host is required (the ingest base URL)");let e=p(t.host),n=t.defaultProperties;return {apiKey:t.apiKey,autocapture:t.autocapture??false,clock:t.clock??V,defaultProperties:typeof n=="function"?n:()=>n??{},flagsHost:t.flagsHost?p(t.flagsHost):e,flushAt:t.flushAt??20,flushIntervalMs:t.flushIntervalMs??1e4,host:e,ids:t.ids??j,locale:t.locale,maxQueueSize:t.maxQueueSize??1e3,maxRetries:t.maxRetries??3,namespace:t.apiKey.slice(0,16),onError:t.onError??ke,os:t.os,requestTimeoutMs:t.requestTimeoutMs??1e4,sdkName:t.sdkName??J,sdkVersion:t.sdkVersion??Q,storage:t.storage??new v,transport:t.transport}}function G(t,e,n){U(t.eventName),B(t.distinctId);let r={distinct_id:t.distinctId,event_id:t.eventId??n.uuid(),event_name:t.eventName,properties:t.properties??{},schema_version:1,timestamp:E(t.timestamp??e.now())};return t.context&&(r.context=t.context),t.sessionId&&(r.session_id=t.sessionId),r}var g=Symbol("absent");function Ee(t,e){if(t==="distinct_id")return e.distinctId;let n=e.properties??{};if(Object.prototype.hasOwnProperty.call(n,t))return n[t];let r=e.attributes??{};return Object.prototype.hasOwnProperty.call(r,t)?r[t]:g}function m(t){return t===g?"undefined":String(t)}function X(t){return t===g?Number.NaN:Number(t)}function Y(t){return t!==g&&t!==null&&t!==""}function Z(t,e){if(!Array.isArray(e))return false;let n=m(t);return e.map(r=>String(r)).includes(n)}function ee(t,e){let n=Ee(t.attribute,e),r=t.value;switch(t.op){case "is_set":return Y(n);case "is_not_set":return !Y(n);case "eq":return m(n)===m(r===void 0?g:r);case "neq":return m(n)!==m(r===void 0?g:r);case "contains":return m(n).includes(m(r===void 0?g:r));case "in":return Z(n,r);case "not_in":return Array.isArray(r)?!Z(n,r):false;case "gt":return I(n,r,(s,o)=>s>o);case "gte":return I(n,r,(s,o)=>s>=o);case "lt":return I(n,r,(s,o)=>s<o);case "lte":return I(n,r,(s,o)=>s<=o);default:return false}}function I(t,e,n){let r=X(t),s=e===void 0?Number.NaN:X(e);return Number.isNaN(r)||Number.isNaN(s)?false:n(r,s)}function Ie(t,e){let n=`${t}:${e}`,r=2166136261;for(let s=0;s<n.length;s++)r^=n.charCodeAt(s),r=Math.imul(r,16777619);return (r>>>0)%100}function Te(t,e){return t.enabled?t.targeting.length>0&&!t.targeting.every(n=>ee(n,e))?{enabled:false,reason:"targeting"}:t.rolloutPercentage>=100?{enabled:true,reason:"rollout_full"}:Ie(t.key,e.distinctId)<t.rolloutPercentage?{enabled:true,reason:"rollout"}:{enabled:false,reason:"rollout_excluded"}:{enabled:false,reason:"disabled"}}function te(t,e){let n={};for(let r of t)n[r.key]=Te(r,e).enabled;return n}var T=class{constructor(e){i(this,"fetch");i(this,"host");i(this,"projectKey");i(this,"requestTimeoutMs");this.fetch=c(e.fetch),this.host=p(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async fetchAll(e){let n=this.fetch;if(!n)throw new u("no fetch implementation available in this runtime");let r=`${this.host}/v1/flags?distinct_id=${encodeURIComponent(e)}`,s=f(),o=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{let a=await n(r,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:s?.signal});if(!a.ok)throw new u(`flags request failed with status ${a.status}`,a.status);return JSON.parse(await a.text()).flags??{}}finally{o!==void 0&&clearTimeout(o);}}async snapshot(){let e=this.fetch;if(!e)throw new u("no fetch implementation available in this runtime");let n=`${this.host}/v1/flags/snapshot`,r=f(),s=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let o=await e(n,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!o.ok)throw new u(`flag snapshot request failed with status ${o.status}`,o.status);let a=JSON.parse(await o.text());return {flags:a.flags??[],generatedAt:a.generatedAt}}finally{s!==void 0&&clearTimeout(s);}}};var w=class{constructor(e,n,r){this.storage=e;this.ids=n;this.namespace=r;i(this,"anonymousId");i(this,"distinctId");i(this,"identified");let s=e.getItem(this.key("anonymous_id"));s?this.anonymousId=s:(this.anonymousId=n.uuid(),e.setItem(this.key("anonymous_id"),this.anonymousId));let o=e.getItem(this.key("distinct_id"));o?(this.distinctId=o,this.identified=true):(this.distinctId=this.anonymousId,this.identified=false);}getAnonymousId(){return this.anonymousId}getDistinctId(){return this.distinctId}isIdentified(){return this.identified}snapshot(){return {anonymousId:this.anonymousId,distinctId:this.distinctId,identified:this.identified}}identify(e){return this.identified&&this.distinctId===e?{changed:false}:(this.distinctId=e,this.identified=true,this.storage.setItem(this.key("distinct_id"),e),{changed:true})}reset(){this.anonymousId=this.ids.uuid(),this.distinctId=this.anonymousId,this.identified=false,this.storage.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.removeItem(this.key("distinct_id"));}key(e){return `pdx.${this.namespace}.${e}`}};var S=class{constructor(e){i(this,"fetch");i(this,"host");i(this,"projectKey");i(this,"requestTimeoutMs");this.fetch=c(e.fetch),this.host=p(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async inbox(e){let n=this.requireFetch(),r=`${this.host}/v1/messages?distinct_id=${encodeURIComponent(e)}`,s=await this.request(n,r,{headers:this.authHeaders(),method:"GET"});if(!s.ok)throw new u(`inbox request failed with status ${s.status}`,s.status);return JSON.parse(await s.text()).messages??[]}async markRead(e,n){let r=this.requireFetch(),s=`${this.host}/v1/messages/read`,o=await this.request(r,s,{body:JSON.stringify({distinct_id:n,message_id:e}),headers:{...this.authHeaders(),"content-type":"application/json"},method:"POST"});if(!o.ok)throw new u(`mark-read request failed with status ${o.status}`,o.status)}requireFetch(){if(!this.fetch)throw new u("no fetch implementation available in this runtime");return this.fetch}authHeaders(){return {authorization:`Bearer ${this.projectKey}`}}async request(e,n,r){let s=f(),o=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{return await e(n,{...r,signal:s?.signal})}finally{o!==void 0&&clearTimeout(o);}}};var P=class{constructor(e,n){this.maxSize=e;this.onOverflow=n;i(this,"events",[]);}get size(){return this.events.length}enqueue(e){this.events.push(e),this.enforceCap();}restore(e){this.events.push(...e),this.enforceCap();}requeue(e){this.events.unshift(...e),this.enforceCap();}drain(e){let n=e===void 0?this.events.length:Math.min(e,this.events.length);return this.events.splice(0,n)}snapshot(){return [...this.events]}enforceCap(){if(this.events.length<=this.maxSize)return;let e=this.events.splice(0,this.events.length-this.maxSize);this.onOverflow?.({dropped:e});}};function ne(t){return t>=400&&t<500&&t!==429}var b=class{constructor(e={}){i(this,"fetch");i(this,"maxRetries");i(this,"requestTimeoutMs");i(this,"baseDelayMs");i(this,"maxDelayMs");i(this,"sleep");i(this,"random");this.fetch=c(e.fetch),this.maxRetries=e.maxRetries??3,this.requestTimeoutMs=e.requestTimeoutMs??1e4,this.baseDelayMs=e.baseDelayMs??500,this.maxDelayMs=e.maxDelayMs??3e4,this.sleep=e.sleep??D,this.random=e.random??Math.random;}async send(e){let n=this.fetch;if(!n)throw new u("no fetch implementation available in this runtime");let r=JSON.stringify(e.body),s;for(let o=0;o<=this.maxRetries;o+=1){try{let a=await this.attempt(n,e,r);if(a.ok)return;if(ne(a.status))throw new u(`ingest rejected batch with status ${a.status}`,a.status);s=new u(`ingest transient status ${a.status}`,a.status);}catch(a){if(a instanceof u&&a.status!==void 0&&ne(a.status))throw a;s=a;}o<this.maxRetries&&await this.sleep(this.backoff(o));}throw new u("ingest delivery failed after retries",void 0,{cause:s})}async attempt(e,n,r){let s=f(),o=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{return await e(n.url,{body:r,headers:{authorization:`Bearer ${n.projectKey}`,"content-type":"application/json"},method:"POST",signal:s?.signal})}finally{o!==void 0&&clearTimeout(o);}}backoff(e){return Math.min(this.maxDelayMs,this.baseDelayMs*2**e)+this.random()*this.baseDelayMs}};var we="queue",Se=1e3,Pe=3e4,re=t=>{let e={};return t.avatar!==void 0&&(e.$avatar=t.avatar),t.email!==void 0&&(e.$email=t.email),t.name!==void 0&&(e.$name=t.name),t.phone!==void 0&&(e.$phone=t.phone),e},C=class{constructor(e){i(this,"config");i(this,"identity");i(this,"queue");i(this,"transport");i(this,"flagsClient");i(this,"messagesClient");i(this,"context");i(this,"flushTimer");i(this,"flushing",false);i(this,"cachedFlags");i(this,"cachedSnapshot");this.config=W(e),this.identity=new w(this.config.storage,this.config.ids,this.config.namespace),this.queue=new P(this.config.maxQueueSize,({dropped:n})=>{this.config.onError(new h("queue_overflow",`event queue overflow: dropped ${n.length} oldest event(s)`));}),this.transport=this.config.transport??new b({maxRetries:this.config.maxRetries,requestTimeoutMs:this.config.requestTimeoutMs}),this.flagsClient=new T({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.messagesClient=new S({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.context={sdk:this.config.sdkName,sdk_version:this.config.sdkVersion},this.config.os&&(this.context.os=this.config.os),this.config.locale&&(this.context.locale=this.config.locale),this.restoreQueue(),this.startTimer();}get distinctId(){return this.identity.getDistinctId()}get anonymousId(){return this.identity.getAnonymousId()}capture(e,n={}){try{let r={...this.config.defaultProperties(),...n.properties??{}},s=G({context:this.context,distinctId:this.identity.getDistinctId(),eventName:e,properties:r,sessionId:n.sessionId,timestamp:n.timestamp},this.config.clock,this.config.ids);this.enqueue(s);}catch(r){this.config.onError(r);}}identify(e,n={}){let r=this.identity.getAnonymousId(),s=!this.identity.isIdentified(),o=this.identity.identify(e),a={};s&&o.changed&&(a.$anon_distinct_id=r);let l={...re(n.traits??{}),...n.set??{}};Object.keys(l).length>0&&(a.$set=l),this.capture("$identify",{properties:a});}alias(e){this.capture("$create_alias",{properties:{alias:e}});}group(e,n,r){let s={$group_key:n,$group_type:e};r&&(s.$set=r),this.capture("$group",{properties:s});}setPersonProperties(e,n){let r={};e&&(r.$set=e),n&&(r.$set_once=n),this.capture("$set",{properties:r});}setPersonTraits(e){let n=re(e);Object.keys(n).length!==0&&this.capture("$set",{properties:{$set:n}});}async getAllFlags(){let e=this.identity.getDistinctId(),n=await this.flagsClient.fetchAll(e);return this.cachedFlags={distinctId:e,flags:n},n}async isFeatureEnabled(e){return (await this.getAllFlags())[e]??false}getCachedFlag(e){if(!(!this.cachedFlags||this.cachedFlags.distinctId!==this.distinctId))return this.cachedFlags.flags[e]}async getLocalFlags(e={}){let n=await this.flagSnapshot();return te(n.flags,{attributes:e.attributes,distinctId:this.identity.getDistinctId(),properties:e.properties})}async isFeatureEnabledLocal(e,n){return (await this.getLocalFlags(n))[e]??false}async flagSnapshot(){let e=this.config.clock.now().getTime();if(this.cachedSnapshot&&e-this.cachedSnapshot.fetchedAt<Pe)return this.cachedSnapshot.snapshot;let n=await this.flagsClient.snapshot();return this.cachedSnapshot={fetchedAt:e,snapshot:n},n}async getInbox(){return this.messagesClient.inbox(this.identity.getDistinctId())}async markMessageRead(e){await this.messagesClient.markRead(e,this.identity.getDistinctId());}async flush(){if(this.flushing||this.queue.size===0)return;this.flushing=true;let e=this.queue.drain(Se);try{await this.transport.send({body:{events:e,sent_at:E(this.config.clock.now())},projectKey:this.config.apiKey,url:`${this.config.host}/v1/events`}),this.persistQueue();}catch(n){this.queue.requeue(e),this.persistQueue(),this.config.onError(n);}finally{this.flushing=false;}}reset(){this.identity.reset(),this.cachedFlags=void 0,this.cachedSnapshot=void 0;}async shutdown(){this.stopTimer(),await this.flush();}enqueue(e){this.queue.enqueue(e),this.persistQueue(),this.queue.size>=this.config.flushAt&&this.flush();}persistQueue(){try{this.config.storage.setItem(this.persistKey(),JSON.stringify(this.queue.snapshot()));}catch(e){this.config.onError(e);}}restoreQueue(){try{let e=this.config.storage.getItem(this.persistKey());if(!e)return;let n=JSON.parse(e);Array.isArray(n)&&this.queue.restore(n);}catch(e){this.config.onError(e);}}startTimer(){if(this.config.flushIntervalMs<=0)return;let e=setInterval(()=>{this.flush();},this.config.flushIntervalMs),n=e;typeof n.unref=="function"&&n.unref(),this.flushTimer=e;}stopTimer(){this.flushTimer!==void 0&&(clearInterval(this.flushTimer),this.flushTimer=void 0);}persistKey(){return `pdx.${this.config.namespace}.${we}`}};function se(){return globalThis.location}function ie(){return globalThis.document}function Ce(){return globalThis.window??globalThis}function Fe(t){return typeof t=="object"&&t!==null&&typeof t.tagName=="string"}function oe(){let t=se(),e=ie(),n={};return t&&(n.$current_url=t.href,n.$pathname=t.pathname,n.$host=t.host),e&&(e.title&&(n.$title=e.title),e.referrer&&(n.$referrer=e.referrer)),n}function Re(t){let e={$el_tag:t.tagName.toLowerCase(),$event_type:"click"},n=t.textContent?.trim();n&&(e.$el_text=n.slice(0,255)),t.id&&(e.$el_id=t.id),typeof t.className=="string"&&t.className&&(e.$el_classes=t.className);let r=t.getAttribute("href");return r&&(e.$el_href=r),e}function Ne(t){let e=globalThis.history,n=Ce(),r="",s=()=>{let l=se(),d=l?`${l.pathname}${l.search}`:"";d!==r&&(r=d,t.capture("$pageview",{properties:oe()}));};if(s(),!e||!n)return ()=>{};let o=e.pushState.bind(e),a=e.replaceState.bind(e);return e.pushState=(...l)=>{o(...l),s();},e.replaceState=(...l)=>{a(...l),s();},n.addEventListener("popstate",s),()=>{e.pushState=o,e.replaceState=a,n.removeEventListener("popstate",s);}}function _e(t){let e=ie();if(!e)return ()=>{};let n=r=>{let s=r.target;Fe(s)&&t.capture("$autocapture",{properties:{...oe(),...Re(s)}});};return e.addEventListener("click",n,true),()=>e.removeEventListener("click",n,true)}function ae(t,e={}){let n=[];return (e.pageviews??true)&&n.push(Ne(t)),(e.clicks??true)&&n.push(_e(t)),()=>{for(let r of n)r();}}function Me(){return globalThis.document?.visibilityState==="hidden"}function Ae(t){let e=globalThis.navigator,n=globalThis.Blob;if(!e?.sendBeacon||!n)return false;let r=JSON.stringify({...t.body,api_key:t.projectKey});try{let s=new n([r],{type:"application/json"});return e.sendBeacon(t.url,s)}catch{return false}}var F=class{constructor(e={}){i(this,"fetchTransport");this.fetchTransport=new b(e);}async send(e){Me()&&Ae(e)||await this.fetchTransport.send(e);}};var le={maskAllInputs:true,maskAllText:false},Le=new Set(["email","password","tel"]);function ue(t){return t.replace(/\S/g,"*")}function R(t,e,n){return Oe(e)||n.maskAllInputs?ue(t):t}function N(t,e){return e.maskAllText?ue(t):t}function Oe(t){return Le.has((t??"").toLowerCase())}var $e=5e3,_=class{constructor(e){this.options=e;i(this,"buffer",[]);i(this,"seq",0);i(this,"maxEvents");this.maxEvents=Math.min(Math.max(1,e.maxEvents),$e);}add(e){return this.buffer.push(e),this.buffer.length>=this.maxEvents?this.flush():null}flush(){if(this.buffer.length===0)return null;let e=this.buffer;this.buffer=[];let n={distinct_id:this.options.distinctId(),events:e,masked:this.options.masked,schema_version:1,seq:this.seq,session_id:this.options.sessionId,timestamp:new Date(this.options.now()).toISOString()};return this.seq+=1,n}};var $=1,q=3,qe=9,M=class{constructor(){i(this,"next",1);}allocate(){let e=this.next;return this.next+=1,e}},De=new Set(["NOSCRIPT","SCRIPT"]);function A(t,e,n,r){if(t.nodeType===q){let s=e.allocate();return r?.(t,s),{id:s,textContent:N(t.textValue??"",n),type:"text"}}if(t.nodeType===qe){let s=e.allocate();return r?.(t,s),{childNodes:pe(t,e,n,r),id:s,type:"document"}}if(t.nodeType===$){let s=t.tagName??"";if(De.has(s))return null;let o=e.allocate();return r?.(t,o),{attributes:Ke(t,n),childNodes:pe(t,e,n,r),id:o,tagName:s,type:"element"}}return null}function pe(t,e,n,r){let s=[];for(let o of t.childNodes??[]){let a=A(o,e,n,r);a&&s.push(a);}return s}function Ke(t,e){let n={};for(let r of t.attributes??[])n[r.name]=r.value;return t.inputValue!==void 0&&(n.value=R(t.inputValue,t.inputType,e)),n}async function ce(t,e){let n=`${p(e.replayHost)}/v1/replay`;return (await e.fetch(n,{body:JSON.stringify(t),headers:{authorization:`Bearer ${e.apiKey}`,"content-type":"application/json"},method:"POST"})).ok}var de=new Set(["INPUT","SELECT","TEXTAREA"]),L=class{constructor(e){this.options=e;i(this,"allocator",new M);i(this,"mirror",new Map);i(this,"chunker");i(this,"fetchImpl");i(this,"observer");i(this,"timer");i(this,"started",false);this.chunker=new _({distinctId:e.distinctId,masked:e.mask.maskAllInputs,maxEvents:e.maxEvents,now:e.now,sessionId:e.sessionId}),this.fetchImpl=c(e.fetch);}start(){if(this.started)return;let e=Ve(),n=e?.documentElement;!e||!n||!this.fetchImpl||(this.started=true,this.captureFullSnapshot(n),this.observeMutations(n),this.observeInteractions(e),this.timer=setInterval(()=>this.upload(this.chunker.flush()),this.options.flushIntervalMs));}stop(){this.started&&(this.started=false,this.observer?.disconnect(),this.timer&&clearInterval(this.timer),this.upload(this.chunker.flush()));}captureFullSnapshot(e){let n=A(this.adapt(e),this.allocator,this.options.mask,(r,s)=>{let o=r.ref;o&&this.mirror.set(o,s);});n&&this.push(2,{node:n});}observeMutations(e){let n=globalThis.MutationObserver;n&&(this.observer=new n(r=>{for(let s of r)this.handleMutation(s);}),this.observer.observe(e,{attributes:true,characterData:true,childList:true,subtree:true}));}handleMutation(e){if(e.type==="characterData"){let n=this.mirror.get(e.target);n!==void 0&&this.push(3,{texts:[{id:n,value:N(e.target.textContent??"",this.options.mask)}]});return}if(e.type==="attributes"&&e.attributeName){let n=this.mirror.get(e.target),r=e.target;n!==void 0&&this.push(3,{attributes:[{attributes:{[e.attributeName]:r.getAttribute(e.attributeName)??""},id:n}]});return}if(e.type==="childList"){let n=this.mirror.get(e.target);if(n===void 0)return;for(let r of Array.from(e.addedNodes)){let s=A(this.adapt(r),this.allocator,this.options.mask,(o,a)=>{let l=o.ref;l&&this.mirror.set(l,a);});s&&this.push(3,{adds:[{node:s,parentId:n}]});}for(let r of Array.from(e.removedNodes)){let s=this.mirror.get(r);s!==void 0&&(this.push(3,{removes:[{id:s,parentId:n}]}),this.mirror.delete(r));}}}observeInteractions(e){e.addEventListener("input",n=>{let r=n.target;if(!r||!de.has(r.tagName))return;let s=this.mirror.get(r);s!==void 0&&this.push(3,{input:{id:s,value:R(r.value??"",r.type,this.options.mask)}});},true),e.addEventListener("scroll",n=>{let r=n.target,s=r?this.mirror.get(r):void 0;this.push(3,{scroll:{id:s??0,x:r?.scrollLeft??0,y:r?.scrollTop??0}});},true);}adapt(e){let n={childNodes:[],nodeType:e.nodeType,ref:e};if(e.nodeType===q)return n.textValue=e.textContent??"",n;if(e.nodeType===$){let r=e;if(n.tagName=r.tagName,n.attributes=Array.from(r.attributes).map(s=>({name:s.name,value:s.value})),de.has(r.tagName)){let s=r;n.inputType=s.type,n.inputValue=s.value??"";}}return n.childNodes=Array.from(e.childNodes).map(r=>this.adapt(r)),n}push(e,n){let r=this.chunker.add({data:n,timestamp:this.options.now(),type:e});r&&this.upload(r);}upload(e){!e||!this.fetchImpl||ce(e,{apiKey:this.options.apiKey,fetch:this.fetchImpl,replayHost:this.options.replayHost}).catch(n=>this.options.onError?.(n));}};function Ve(){return globalThis.document}function he(t){let e=new L({apiKey:t.apiKey,distinctId:t.distinctId,flushIntervalMs:t.flushIntervalMs??5e3,mask:{...le,...t.mask},maxEvents:t.maxEvents??200,now:t.now??(()=>Date.now()),onError:t.onError,replayHost:t.replayHost,sessionId:t.sessionId??O()});return e.start(),e}function je(){return globalThis.navigator}function ze(t){let e=t?.userAgentData?.platform??t?.platform;return e?e.slice(0,50):void 0}function He(t){let e=()=>{t.flush();};globalThis.document?.addEventListener?.("visibilitychange",e),globalThis.addEventListener?.("pagehide",e);}function kn(t){let{autocaptureOptions:e,replayHost:n,sessionReplay:r,sessionReplayOptions:s,...o}=t,a=je(),l={...o,locale:o.locale??(a?.language?a.language.slice(0,20):void 0),os:o.os??ze(a),storage:o.storage??K(),transport:o.transport??new F({maxRetries:o.maxRetries,requestTimeoutMs:o.requestTimeoutMs})},d=new C(l);return He(d),(t.autocapture??true)&&ae(d,e),r&&n&&he({apiKey:l.apiKey,distinctId:()=>d.distinctId,onError:l.onError,replayHost:n,...s}),d}exports.WebTransport=F;exports.createWebClient=kn;exports.installAutocapture=ae;exports.installSessionReplay=he;//# sourceMappingURL=web.cjs.map
1
+ 'use strict';var Ce=Object.defineProperty;var Fe=(t,e,n)=>e in t?Ce(t,e,{enumerable:true,configurable:true,writable:true,value:n}):t[e]=n;var o=(t,e,n)=>Fe(t,typeof e!="symbol"?e+"":e,n);var f=class extends Error{constructor(n,r,s){super(r,s);o(this,"code");this.code=n,this.name="ProdantixError";}},b=class extends f{constructor(e){super("config",e),this.name="ConfigError";}},y=class extends f{constructor(n,r){super("validation",r);o(this,"field");this.field=n,this.name="ValidationError";}},c=class extends f{constructor(n,r,s){super("transport",n,s);o(this,"status");this.status=r,this.name="TransportError";}};function d(t){if(t)return t;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function h(){let t=globalThis.AbortController;return t?new t:void 0}var U=t=>new Promise(e=>{setTimeout(e,t);});function p(t){return t.replace(/\/+$/,"")}var v=class{constructor(){o(this,"store",new Map);}getItem(e){return this.store.get(e)??null}removeItem(e){this.store.delete(e);}setItem(e,n){this.store.set(e,n);}};function G(){try{let t=globalThis.localStorage;if(t){let e="__pdx_probe__";return t.setItem(e,"1"),t.removeItem(e),t}}catch{return new v}return new v}var B={now:()=>new Date};function E(t){return t.toISOString()}function Ne(){return globalThis.crypto}function _e(t){t[6]=t[6]&15|64,t[8]=t[8]&63|128;let e=[];for(let n=0;n<16;n+=1)e.push(t[n].toString(16).padStart(2,"0"));return `${e[0]}${e[1]}${e[2]}${e[3]}-${e[4]}${e[5]}-${e[6]}${e[7]}-${e[8]}${e[9]}-${e[10]}${e[11]}${e[12]}${e[13]}${e[14]}${e[15]}`}function q(){let t=Ne();if(t?.randomUUID)return t.randomUUID();let e=new Uint8Array(16);if(t?.getRandomValues)t.getRandomValues(e);else for(let n=0;n<16;n+=1)e[n]=Math.floor(Math.random()*256);return _e(e)}var J={uuid:q};var Pe=/^pdx_pub_(?:(?:live|test)_)?[a-z0-9]{32}$/;var Re=/^(?:\$|[a-z])[a-z0-9_.]*$/;function W(t){let e=0;for(let n of t)e+=1;return e}function Q(t){return Pe.test(t)}function Oe(t){return Re.test(t)}function X(t){let e=W(t);if(e<1||e>200)throw new y("distinct_id","distinct_id must be between 1 and 200 characters")}function Y(t){let e=W(t);if(e<1||e>200)throw new y("event_name","event_name must be between 1 and 200 characters");if(!Oe(t))throw new y("event_name","event_name must match /^(\\$|[a-z])[a-z0-9_.]*$/")}var Z="prodantix-js",ee="0.0.1";var Ae=t=>{};function te(t){if(!t.apiKey||!Q(t.apiKey))throw new b("apiKey must be a public project key of the form pdx_pub_<32 lowercase alphanumerics>");if(!t.host)throw new b("host is required (the ingest base URL)");let e=p(t.host),n=t.defaultProperties;return {apiKey:t.apiKey,autocapture:t.autocapture??false,clock:t.clock??B,defaultProperties:typeof n=="function"?n:()=>n??{},flagsHost:t.flagsHost?p(t.flagsHost):e,flushAt:t.flushAt??20,flushIntervalMs:t.flushIntervalMs??1e4,host:e,ids:t.ids??J,locale:t.locale,maxQueueSize:t.maxQueueSize??1e3,maxRetries:t.maxRetries??3,namespace:t.apiKey.slice(0,16),onError:t.onError??Ae,os:t.os,requestTimeoutMs:t.requestTimeoutMs??1e4,sdkName:t.sdkName??Z,sdkVersion:t.sdkVersion??ee,socketFactory:t.socketFactory,storage:t.storage??new v,streamFlags:t.streamFlags??false,transport:t.transport}}function ne(t,e,n){Y(t.eventName),X(t.distinctId);let r={distinct_id:t.distinctId,event_id:t.eventId??n.uuid(),event_name:t.eventName,properties:t.properties??{},schema_version:1,timestamp:E(t.timestamp??e.now())};return t.context&&(r.context=t.context),t.sessionId&&(r.session_id=t.sessionId),r}var g=Symbol("absent");function Le(t,e){if(t==="distinct_id")return e.distinctId;let n=e.properties??{};if(Object.prototype.hasOwnProperty.call(n,t))return n[t];let r=e.attributes??{};return Object.prototype.hasOwnProperty.call(r,t)?r[t]:g}function m(t){return t===g?"undefined":String(t)}function re(t){return t===g?Number.NaN:Number(t)}function se(t){return t!==g&&t!==null&&t!==""}function ie(t,e){if(!Array.isArray(e))return false;let n=m(t);return e.map(r=>String(r)).includes(n)}function oe(t,e){let n=Le(t.attribute,e),r=t.value;switch(t.op){case "is_set":return se(n);case "is_not_set":return !se(n);case "eq":return m(n)===m(r===void 0?g:r);case "neq":return m(n)!==m(r===void 0?g:r);case "contains":return m(n).includes(m(r===void 0?g:r));case "in":return ie(n,r);case "not_in":return Array.isArray(r)?!ie(n,r):false;case "gt":return T(n,r,(s,i)=>s>i);case "gte":return T(n,r,(s,i)=>s>=i);case "lt":return T(n,r,(s,i)=>s<i);case "lte":return T(n,r,(s,i)=>s<=i);case "in_cohort":return typeof r=="string"&&r!==""&&(e.cohorts??[]).includes(r);case "not_in_cohort":return typeof r=="string"&&r!==""&&!(e.cohorts??[]).includes(r);default:return false}}function T(t,e,n){let r=re(t),s=e===void 0?Number.NaN:re(e);return Number.isNaN(r)||Number.isNaN(s)?false:n(r,s)}function ae(t,e){let n=`${t}:${e}`,r=2166136261;for(let s=0;s<n.length;s++)r^=n.charCodeAt(s),r=Math.imul(r,16777619);return (r>>>0)%100}function K(t,e){return t.targeting.length===0||t.targeting.every(n=>oe(n,e))}function le(t,e){let n=ae(t.key,e.distinctId),r=t.variations??[];if(r.length===0)return t.rolloutPercentage>=100||n<t.rolloutPercentage?"true":"false";let s=0;for(let i=r.length-1;i>=0;i--)if(s+=r[i].weight,n<s)return r[i].key;return r[0].key}function D(t,e,n,r){for(let s of t.prerequisites??[]){if(r.includes(s.flagKey))return false;let i=e.find(l=>l.key===s.flagKey);if(!i||!i.enabled)return false;r.push(i.key);let a=D(i,e,n,r)&&K(i,n)&&le(i,n)===s.variationKey;if(r.pop(),!a)return false}return true}function S(t,e,n){return t.enabled?D(t,e,n,[t.key])?K(t,n)?t.rolloutPercentage>=100?{enabled:true,reason:"rollout_full"}:ae(t.key,n.distinctId)<t.rolloutPercentage?{enabled:true,reason:"rollout"}:{enabled:false,reason:"rollout_excluded"}:{enabled:false,reason:"targeting"}:{enabled:false,reason:"prerequisite"}:{enabled:false,reason:"disabled"}}function ce(t,e){let n={};for(let r of t)n[r.key]=S(r,t,e).enabled;return n}function V(t,e,n){let r=t.variations??[],s=r[0];if(!s)return null;if(!t.enabled||!D(t,e,n,[t.key])||!K(t,n))return s;let i=le(t,n);return r.find(a=>a.key===i)??s}function ue(t){return t.some(e=>e.targeting.some(n=>n.op==="in_cohort"||n.op==="not_in_cohort"))}function pe(t){return `40${JSON.stringify(t)}`}function de(){return "3"}function he(t){let e=t.charAt(0),n=t.slice(1);if(e==="2")return {kind:"ping"};if(e==="1")return {kind:"disconnect"};if(e==="0"){let a=j(n);return {kind:"open",pingInterval:typeof a?.pingInterval=="number"?a.pingInterval:25e3,pingTimeout:typeof a?.pingTimeout=="number"?a.pingTimeout:2e4}}if(e!=="4")return {kind:"other"};let r=n.charAt(0),s=n.slice(1);if(r==="0")return {kind:"connected"};if(r==="1")return {kind:"disconnect"};if(r==="4"){let a=j(s);return {kind:"connectError",message:typeof a?.message=="string"?a.message:"refused"}}if(r!=="2")return {kind:"other"};let i=j(s);return !Array.isArray(i)||typeof i[0]!="string"?{kind:"other"}:{kind:"event",name:i[0],payload:i[1]}}function j(t){try{return JSON.parse(t)}catch{return null}}var Me="/socket.io/?EIO=4&transport=websocket",$e=250,w=class{constructor(e){this.options=e;o(this,"socket",null);o(this,"heartbeat",null);o(this,"pending",null);o(this,"lastKey","");o(this,"ready",false);o(this,"closed",false);o(this,"heartbeatWindow",45e3);o(this,"factory");o(this,"setTimer");o(this,"clearTimer");this.factory=e.socketFactory??qe,this.setTimer=e.setTimer??((n,r)=>setTimeout(n,r)),this.clearTimer=e.clearTimer??(n=>clearTimeout(n));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${Me}`,n;try{n=this.factory(e);}catch{this.options.onClosed(false);return}this.socket=n,n.onmessage=r=>this.receive(String(r.data)),n.onerror=()=>n.close(),n.onclose=()=>this.fell();}close(){this.closed=true,this.stopHeartbeat(),this.pending!==null&&this.clearTimer(this.pending),this.pending=null;let e=this.socket;this.socket=null,e?.close();}receive(e){let n=he(e);if(n.kind==="open"){this.armHeartbeat(n.pingInterval+n.pingTimeout),this.socket?.send(pe({projectKey:this.options.projectKey}));return}if(n.kind==="ping"){this.armHeartbeat(),this.socket?.send(de());return}if(n.kind==="connectError"||n.kind==="disconnect"){this.stopHeartbeat(),this.socket?.close();return}if(n.kind==="event"){if(n.name==="ready"){this.ready=true;return}if(n.name==="flagChange"){let r=n.payload?.key;this.lastKey=typeof r=="string"?r:"",this.pending===null&&(this.pending=this.setTimer(()=>{this.pending=null,this.options.onChange(this.lastKey);},$e));}}}fell(){this.stopHeartbeat();let e=this.ready;this.socket=null,this.ready=false,this.closed||this.options.onClosed(e);}armHeartbeat(e){e!==void 0&&(this.heartbeatWindow=e),this.stopHeartbeat(),this.heartbeat=this.setTimer(()=>this.socket?.close(),this.heartbeatWindow);}stopHeartbeat(){this.heartbeat!==null&&this.clearTimer(this.heartbeat),this.heartbeat=null;}};function qe(t){let e=globalThis.WebSocket;if(!e)throw new Error("no WebSocket");return new e(t)}var I=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=d(e.fetch),this.host=p(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async fetchAll(e){return (await this.fetchDecisions(e)).flags}async fetchDecisions(e){let n=this.fetch;if(!n)throw new c("no fetch implementation available in this runtime");let r=`${this.host}/v1/flags?distinct_id=${encodeURIComponent(e)}`,s=h(),i=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{let a=await n(r,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:s?.signal});if(!a.ok)throw new c(`flags request failed with status ${a.status}`,a.status);let l=JSON.parse(await a.text());return {flags:l.flags??{},variants:l.variants??{}}}finally{i!==void 0&&clearTimeout(i);}}async snapshot(){let e=this.fetch;if(!e)throw new c("no fetch implementation available in this runtime");let n=`${this.host}/v1/flags/snapshot`,r=h(),s=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let i=await e(n,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!i.ok)throw new c(`flag snapshot request failed with status ${i.status}`,i.status);let a=JSON.parse(await i.text()),l={flags:a.flags??[],generatedAt:a.generatedAt};return typeof a.socketUrl=="string"&&a.socketUrl!==""&&(l.socketUrl=a.socketUrl),l}finally{s!==void 0&&clearTimeout(s);}}async memberships(e){let n=this.fetch;if(!n)throw new c("no fetch implementation available in this runtime");let r=`${this.host}/v1/flags/memberships?distinct_id=${encodeURIComponent(e)}`,s=h(),i=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{let a=await n(r,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:s?.signal});if(!a.ok)throw new c(`memberships request failed with status ${a.status}`,a.status);return JSON.parse(await a.text()).cohorts??[]}finally{i!==void 0&&clearTimeout(i);}}};var C=class{constructor(e,n,r){this.storage=e;this.ids=n;this.namespace=r;o(this,"anonymousId");o(this,"distinctId");o(this,"identified");let s=e.getItem(this.key("anonymous_id"));s?this.anonymousId=s:(this.anonymousId=n.uuid(),e.setItem(this.key("anonymous_id"),this.anonymousId));let i=e.getItem(this.key("distinct_id"));i?(this.distinctId=i,this.identified=true):(this.distinctId=this.anonymousId,this.identified=false);}getAnonymousId(){return this.anonymousId}getDistinctId(){return this.distinctId}isIdentified(){return this.identified}snapshot(){return {anonymousId:this.anonymousId,distinctId:this.distinctId,identified:this.identified}}identify(e){return this.identified&&this.distinctId===e?{changed:false}:(this.distinctId=e,this.identified=true,this.storage.setItem(this.key("distinct_id"),e),{changed:true})}reset(){this.anonymousId=this.ids.uuid(),this.distinctId=this.anonymousId,this.identified=false,this.storage.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.removeItem(this.key("distinct_id"));}key(e){return `pdx.${this.namespace}.${e}`}};var F=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=d(e.fetch),this.host=p(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async inbox(e){let n=this.requireFetch(),r=`${this.host}/v1/messages?distinct_id=${encodeURIComponent(e)}`,s=await this.request(n,r,{headers:this.authHeaders(),method:"GET"});if(!s.ok)throw new c(`inbox request failed with status ${s.status}`,s.status);return JSON.parse(await s.text()).messages??[]}async markRead(e,n){let r=this.requireFetch(),s=`${this.host}/v1/messages/read`,i=await this.request(r,s,{body:JSON.stringify({distinct_id:n,message_id:e}),headers:{...this.authHeaders(),"content-type":"application/json"},method:"POST"});if(!i.ok)throw new c(`mark-read request failed with status ${i.status}`,i.status)}requireFetch(){if(!this.fetch)throw new c("no fetch implementation available in this runtime");return this.fetch}authHeaders(){return {authorization:`Bearer ${this.projectKey}`}}async request(e,n,r){let s=h(),i=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{return await e(n,{...r,signal:s?.signal})}finally{i!==void 0&&clearTimeout(i);}}};var N=class{constructor(e,n){this.maxSize=e;this.onOverflow=n;o(this,"events",[]);}get size(){return this.events.length}enqueue(e){this.events.push(e),this.enforceCap();}restore(e){this.events.push(...e),this.enforceCap();}requeue(e){this.events.unshift(...e),this.enforceCap();}drain(e){let n=e===void 0?this.events.length:Math.min(e,this.events.length);return this.events.splice(0,n)}snapshot(){return [...this.events]}enforceCap(){if(this.events.length<=this.maxSize)return;let e=this.events.splice(0,this.events.length-this.maxSize);this.onOverflow?.({dropped:e});}};function fe(t){return t>=400&&t<500&&t!==429}var k=class{constructor(e={}){o(this,"fetch");o(this,"maxRetries");o(this,"requestTimeoutMs");o(this,"baseDelayMs");o(this,"maxDelayMs");o(this,"sleep");o(this,"random");this.fetch=d(e.fetch),this.maxRetries=e.maxRetries??3,this.requestTimeoutMs=e.requestTimeoutMs??1e4,this.baseDelayMs=e.baseDelayMs??500,this.maxDelayMs=e.maxDelayMs??3e4,this.sleep=e.sleep??U,this.random=e.random??Math.random;}async send(e){let n=this.fetch;if(!n)throw new c("no fetch implementation available in this runtime");let r=JSON.stringify(e.body),s;for(let i=0;i<=this.maxRetries;i+=1){try{let a=await this.attempt(n,e,r);if(a.ok)return;if(fe(a.status))throw new c(`ingest rejected batch with status ${a.status}`,a.status);s=new c(`ingest transient status ${a.status}`,a.status);}catch(a){if(a instanceof c&&a.status!==void 0&&fe(a.status))throw a;s=a;}i<this.maxRetries&&await this.sleep(this.backoff(i));}throw new c("ingest delivery failed after retries",void 0,{cause:s})}async attempt(e,n,r){let s=h(),i=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{return await e(n.url,{body:r,headers:{authorization:`Bearer ${n.projectKey}`,"content-type":"application/json"},method:"POST",signal:s?.signal})}finally{i!==void 0&&clearTimeout(i);}}backoff(e){return Math.min(this.maxDelayMs,this.baseDelayMs*2**e)+this.random()*this.baseDelayMs}};var Ke="queue",De=1e3,me=3e4,ge=t=>{let e={};return t.avatar!==void 0&&(e.$avatar=t.avatar),t.email!==void 0&&(e.$email=t.email),t.name!==void 0&&(e.$name=t.name),t.phone!==void 0&&(e.$phone=t.phone),e},_=class{constructor(e){o(this,"config");o(this,"identity");o(this,"queue");o(this,"transport");o(this,"flagsClient");o(this,"messagesClient");o(this,"context");o(this,"flushTimer");o(this,"flushing",false);o(this,"cachedFlags");o(this,"cachedSnapshot");o(this,"membershipCache");o(this,"stream");o(this,"shutDown",false);o(this,"exposures",new Set);this.config=te(e),this.identity=new C(this.config.storage,this.config.ids,this.config.namespace),this.queue=new N(this.config.maxQueueSize,({dropped:n})=>{this.config.onError(new f("queue_overflow",`event queue overflow: dropped ${n.length} oldest event(s)`));}),this.transport=this.config.transport??new k({maxRetries:this.config.maxRetries,requestTimeoutMs:this.config.requestTimeoutMs}),this.flagsClient=new I({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.messagesClient=new F({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.context={sdk:this.config.sdkName,sdk_version:this.config.sdkVersion},this.config.os&&(this.context.os=this.config.os),this.config.locale&&(this.context.locale=this.config.locale),this.restoreQueue(),this.startTimer();}get distinctId(){return this.identity.getDistinctId()}get anonymousId(){return this.identity.getAnonymousId()}capture(e,n={}){try{let r={...this.config.defaultProperties(),...n.properties??{}},s=ne({context:this.context,distinctId:this.identity.getDistinctId(),eventName:e,properties:r,sessionId:n.sessionId,timestamp:n.timestamp},this.config.clock,this.config.ids);this.enqueue(s);}catch(r){this.config.onError(r);}}identify(e,n={}){let r=this.identity.getAnonymousId(),s=!this.identity.isIdentified(),i=this.identity.identify(e),a={};s&&i.changed&&(a.$anon_distinct_id=r);let l={...ge(n.traits??{}),...n.set??{}};Object.keys(l).length>0&&(a.$set=l),this.capture("$identify",{properties:a});}alias(e){this.capture("$create_alias",{properties:{alias:e}});}group(e,n,r){let s={$group_key:n,$group_type:e};r&&(s.$set=r),this.capture("$group",{properties:s});}setPersonProperties(e,n){let r={};e&&(r.$set=e),n&&(r.$set_once=n),this.capture("$set",{properties:r});}setPersonTraits(e){let n=ge(e);Object.keys(n).length!==0&&this.capture("$set",{properties:{$set:n}});}async getAllFlags(){let e=this.identity.getDistinctId(),n=await this.flagsClient.fetchDecisions(e);return this.cachedFlags={distinctId:e,flags:n.flags,variants:n.variants??{}},n.flags}async isFeatureEnabled(e){let r=(await this.getAllFlags())[e]??false;return this.recordExposure(e,this.cachedFlags?.variants[e]?.key??String(r)),r}async getVariant(e){let n=await this.getAllFlags(),r=this.cachedFlags?.variants[e]??null;return this.recordExposure(e,r?.key??String(n[e]??false)),r}async getVariantLocal(e,n={}){let r=await this.flagSnapshot(),s=r.flags.find(u=>u.key===e),i=await this.localContext(n,r.flags),a=s?V(s,r.flags,i):null,l=s?S(s,r.flags,i).enabled:false;return this.recordExposure(e,a?.key??String(l)),a?{key:a.key,value:a.value}:null}recordExposure(e,n){let r=`${this.identity.getDistinctId()} ${e} ${n}`;this.exposures.has(r)||(this.exposures.add(r),this.capture("$feature_flag_called",{properties:{$feature_flag:e,$feature_flag_response:n}}));}getCachedFlag(e){if(!(!this.cachedFlags||this.cachedFlags.distinctId!==this.distinctId))return this.cachedFlags.flags[e]}async getLocalFlags(e={}){let n=await this.flagSnapshot();return ce(n.flags,await this.localContext(e,n.flags))}async isFeatureEnabledLocal(e,n={}){let r=await this.flagSnapshot(),s=r.flags.find(l=>l.key===e),i=await this.localContext(n,r.flags),a=s?S(s,r.flags,i).enabled:false;return this.recordExposure(e,(s?V(s,r.flags,i)?.key:void 0)??String(a)),a}async localContext(e,n){let r=this.identity.getDistinctId(),s=e.cohorts;if(s===void 0&&ue(n)){let i=this.config.clock.now().getTime();this.membershipCache&&this.membershipCache.distinctId===r&&i-this.membershipCache.fetchedAt<me?s=this.membershipCache.cohorts:(s=await this.flagsClient.memberships(r),this.membershipCache={cohorts:s,distinctId:r,fetchedAt:i});}return {attributes:e.attributes,cohorts:s,distinctId:r,properties:e.properties}}async flagSnapshot(){let e=this.config.clock.now().getTime();if(this.cachedSnapshot&&e-this.cachedSnapshot.fetchedAt<me)return this.cachedSnapshot.snapshot;let n=await this.flagsClient.snapshot();return this.cachedSnapshot={fetchedAt:e,snapshot:n},this.maybeStream(n),n}maybeStream(e){if(!this.config.streamFlags||this.shutDown||this.stream||!e.socketUrl)return;let n=new w({host:e.socketUrl,onChange:()=>{this.cachedSnapshot=void 0,this.flagSnapshot().catch(r=>this.config.onError(r));},onClosed:r=>{this.stream=void 0,r&&this.maybeStream(e);},projectKey:this.config.apiKey,socketFactory:this.config.socketFactory});this.stream=n,n.open();}async getInbox(){return this.messagesClient.inbox(this.identity.getDistinctId())}async markMessageRead(e){await this.messagesClient.markRead(e,this.identity.getDistinctId());}async flush(){if(this.flushing||this.queue.size===0)return;this.flushing=true;let e=this.queue.drain(De);try{await this.transport.send({body:{events:e,sent_at:E(this.config.clock.now())},projectKey:this.config.apiKey,url:`${this.config.host}/v1/events`}),this.persistQueue();}catch(n){this.queue.requeue(e),this.persistQueue(),this.config.onError(n);}finally{this.flushing=false;}}reset(){this.identity.reset(),this.cachedFlags=void 0,this.cachedSnapshot=void 0,this.membershipCache=void 0;}async shutdown(){this.shutDown=true,this.stopTimer(),this.stream?.close(),this.stream=void 0,await this.flush();}enqueue(e){this.queue.enqueue(e),this.persistQueue(),this.queue.size>=this.config.flushAt&&this.flush();}persistQueue(){try{this.config.storage.setItem(this.persistKey(),JSON.stringify(this.queue.snapshot()));}catch(e){this.config.onError(e);}}restoreQueue(){try{let e=this.config.storage.getItem(this.persistKey());if(!e)return;let n=JSON.parse(e);Array.isArray(n)&&this.queue.restore(n);}catch(e){this.config.onError(e);}}startTimer(){if(this.config.flushIntervalMs<=0)return;let e=setInterval(()=>{this.flush();},this.config.flushIntervalMs),n=e;typeof n.unref=="function"&&n.unref(),this.flushTimer=e;}stopTimer(){this.flushTimer!==void 0&&(clearInterval(this.flushTimer),this.flushTimer=void 0);}persistKey(){return `pdx.${this.config.namespace}.${Ke}`}};function ye(){return globalThis.location}function ve(){return globalThis.document}function Ve(){return globalThis.window??globalThis}function je(t){return typeof t=="object"&&t!==null&&typeof t.tagName=="string"}function ke(){let t=ye(),e=ve(),n={};return t&&(n.$current_url=t.href,n.$pathname=t.pathname,n.$host=t.host),e&&(e.title&&(n.$title=e.title),e.referrer&&(n.$referrer=e.referrer)),n}function He(t){let e={$el_tag:t.tagName.toLowerCase(),$event_type:"click"},n=t.textContent?.trim();n&&(e.$el_text=n.slice(0,255)),t.id&&(e.$el_id=t.id),typeof t.className=="string"&&t.className&&(e.$el_classes=t.className);let r=t.getAttribute("href");return r&&(e.$el_href=r),e}function ze(t){let e=globalThis.history,n=Ve(),r="",s=()=>{let l=ye(),u=l?`${l.pathname}${l.search}`:"";u!==r&&(r=u,t.capture("$pageview",{properties:ke()}));};if(s(),!e||!n)return ()=>{};let i=e.pushState.bind(e),a=e.replaceState.bind(e);return e.pushState=(...l)=>{i(...l),s();},e.replaceState=(...l)=>{a(...l),s();},n.addEventListener("popstate",s),()=>{e.pushState=i,e.replaceState=a,n.removeEventListener("popstate",s);}}function Ue(t){let e=ve();if(!e)return ()=>{};let n=r=>{let s=r.target;je(s)&&t.capture("$autocapture",{properties:{...ke(),...He(s)}});};return e.addEventListener("click",n,true),()=>e.removeEventListener("click",n,true)}function be(t,e={}){let n=[];return (e.pageviews??true)&&n.push(ze(t)),(e.clicks??true)&&n.push(Ue(t)),()=>{for(let r of n)r();}}function Ge(){return globalThis.document?.visibilityState==="hidden"}function Be(t){let e=globalThis.navigator,n=globalThis.Blob;if(!e?.sendBeacon||!n)return false;let r=JSON.stringify({...t.body,api_key:t.projectKey});try{let s=new n([r],{type:"application/json"});return e.sendBeacon(t.url,s)}catch{return false}}var P=class{constructor(e={}){o(this,"fetchTransport");this.fetchTransport=new k(e);}async send(e){Ge()&&Be(e)||await this.fetchTransport.send(e);}};var xe={maskAllInputs:true,maskAllText:false},Je=new Set(["email","password","tel"]);function Ee(t){return t.replace(/\S/g,"*")}function R(t,e,n){return We(e)||n.maskAllInputs?Ee(t):t}function O(t,e){return e.maskAllText?Ee(t):t}function We(t){return Je.has((t??"").toLowerCase())}var Qe=5e3,A=class{constructor(e){this.options=e;o(this,"buffer",[]);o(this,"seq",0);o(this,"maxEvents");this.maxEvents=Math.min(Math.max(1,e.maxEvents),Qe);}add(e){return this.buffer.push(e),this.buffer.length>=this.maxEvents?this.flush():null}flush(){if(this.buffer.length===0)return null;let e=this.buffer;this.buffer=[];let n={distinct_id:this.options.distinctId(),events:e,masked:this.options.masked,schema_version:1,seq:this.seq,session_id:this.options.sessionId,timestamp:new Date(this.options.now()).toISOString()};return this.seq+=1,n}};var H=1,z=3,Xe=9,L=class{constructor(){o(this,"next",1);}allocate(){let e=this.next;return this.next+=1,e}},Ye=new Set(["NOSCRIPT","SCRIPT"]);function M(t,e,n,r){if(t.nodeType===z){let s=e.allocate();return r?.(t,s),{id:s,textContent:O(t.textValue??"",n),type:"text"}}if(t.nodeType===Xe){let s=e.allocate();return r?.(t,s),{childNodes:Te(t,e,n,r),id:s,type:"document"}}if(t.nodeType===H){let s=t.tagName??"";if(Ye.has(s))return null;let i=e.allocate();return r?.(t,i),{attributes:Ze(t,n),childNodes:Te(t,e,n,r),id:i,tagName:s,type:"element"}}return null}function Te(t,e,n,r){let s=[];for(let i of t.childNodes??[]){let a=M(i,e,n,r);a&&s.push(a);}return s}function Ze(t,e){let n={};for(let r of t.attributes??[])n[r.name]=r.value;return t.inputValue!==void 0&&(n.value=R(t.inputValue,t.inputType,e)),n}async function Se(t,e){let n=`${p(e.replayHost)}/v1/replay`;return (await e.fetch(n,{body:JSON.stringify(t),headers:{authorization:`Bearer ${e.apiKey}`,"content-type":"application/json"},method:"POST"})).ok}var we=new Set(["INPUT","SELECT","TEXTAREA"]),$=class{constructor(e){this.options=e;o(this,"allocator",new L);o(this,"mirror",new Map);o(this,"chunker");o(this,"fetchImpl");o(this,"observer");o(this,"timer");o(this,"started",false);this.chunker=new A({distinctId:e.distinctId,masked:e.mask.maskAllInputs,maxEvents:e.maxEvents,now:e.now,sessionId:e.sessionId}),this.fetchImpl=d(e.fetch);}start(){if(this.started)return;let e=et(),n=e?.documentElement;!e||!n||!this.fetchImpl||(this.started=true,this.captureFullSnapshot(n),this.observeMutations(n),this.observeInteractions(e),this.timer=setInterval(()=>this.upload(this.chunker.flush()),this.options.flushIntervalMs));}stop(){this.started&&(this.started=false,this.observer?.disconnect(),this.timer&&clearInterval(this.timer),this.upload(this.chunker.flush()));}captureFullSnapshot(e){let n=M(this.adapt(e),this.allocator,this.options.mask,(r,s)=>{let i=r.ref;i&&this.mirror.set(i,s);});n&&this.push(2,{node:n});}observeMutations(e){let n=globalThis.MutationObserver;n&&(this.observer=new n(r=>{for(let s of r)this.handleMutation(s);}),this.observer.observe(e,{attributes:true,characterData:true,childList:true,subtree:true}));}handleMutation(e){if(e.type==="characterData"){let n=this.mirror.get(e.target);n!==void 0&&this.push(3,{texts:[{id:n,value:O(e.target.textContent??"",this.options.mask)}]});return}if(e.type==="attributes"&&e.attributeName){let n=this.mirror.get(e.target),r=e.target;n!==void 0&&this.push(3,{attributes:[{attributes:{[e.attributeName]:r.getAttribute(e.attributeName)??""},id:n}]});return}if(e.type==="childList"){let n=this.mirror.get(e.target);if(n===void 0)return;for(let r of Array.from(e.addedNodes)){let s=M(this.adapt(r),this.allocator,this.options.mask,(i,a)=>{let l=i.ref;l&&this.mirror.set(l,a);});s&&this.push(3,{adds:[{node:s,parentId:n}]});}for(let r of Array.from(e.removedNodes)){let s=this.mirror.get(r);s!==void 0&&(this.push(3,{removes:[{id:s,parentId:n}]}),this.mirror.delete(r));}}}observeInteractions(e){e.addEventListener("input",n=>{let r=n.target;if(!r||!we.has(r.tagName))return;let s=this.mirror.get(r);s!==void 0&&this.push(3,{input:{id:s,value:R(r.value??"",r.type,this.options.mask)}});},true),e.addEventListener("scroll",n=>{let r=n.target,s=r?this.mirror.get(r):void 0;this.push(3,{scroll:{id:s??0,x:r?.scrollLeft??0,y:r?.scrollTop??0}});},true);}adapt(e){let n={childNodes:[],nodeType:e.nodeType,ref:e};if(e.nodeType===z)return n.textValue=e.textContent??"",n;if(e.nodeType===H){let r=e;if(n.tagName=r.tagName,n.attributes=Array.from(r.attributes).map(s=>({name:s.name,value:s.value})),we.has(r.tagName)){let s=r;n.inputType=s.type,n.inputValue=s.value??"";}}return n.childNodes=Array.from(e.childNodes).map(r=>this.adapt(r)),n}push(e,n){let r=this.chunker.add({data:n,timestamp:this.options.now(),type:e});r&&this.upload(r);}upload(e){!e||!this.fetchImpl||Se(e,{apiKey:this.options.apiKey,fetch:this.fetchImpl,replayHost:this.options.replayHost}).catch(n=>this.options.onError?.(n));}};function et(){return globalThis.document}function Ie(t){let e=new $({apiKey:t.apiKey,distinctId:t.distinctId,flushIntervalMs:t.flushIntervalMs??5e3,mask:{...xe,...t.mask},maxEvents:t.maxEvents??200,now:t.now??(()=>Date.now()),onError:t.onError,replayHost:t.replayHost,sessionId:t.sessionId??q()});return e.start(),e}function tt(){return globalThis.navigator}function nt(t){let e=t?.userAgentData?.platform??t?.platform;return e?e.slice(0,50):void 0}function rt(t){let e=()=>{t.flush();};globalThis.document?.addEventListener?.("visibilitychange",e),globalThis.addEventListener?.("pagehide",e);}function Kn(t){let{autocaptureOptions:e,replayHost:n,sessionReplay:r,sessionReplayOptions:s,...i}=t,a=tt(),l={...i,locale:i.locale??(a?.language?a.language.slice(0,20):void 0),os:i.os??nt(a),storage:i.storage??G(),transport:i.transport??new P({maxRetries:i.maxRetries,requestTimeoutMs:i.requestTimeoutMs})},u=new _(l);return rt(u),(t.autocapture??true)&&be(u,e),r&&n&&Ie({apiKey:l.apiKey,distinctId:()=>u.distinctId,onError:l.onError,replayHost:n,...s}),u}exports.WebTransport=P;exports.createWebClient=Kn;exports.installAutocapture=be;exports.installSessionReplay=Ie;//# sourceMappingURL=web.cjs.map
2
2
  //# sourceMappingURL=web.cjs.map