@prodantix/sdk 0.2.0 → 0.3.0-beta.379

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/web.cjs CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var ct=Object.defineProperty;var dt=(t,e,n)=>e in t?ct(t,e,{enumerable:true,configurable:true,writable:true,value:n}):t[e]=n;var o=(t,e,n)=>dt(t,typeof e!="symbol"?e+"":e,n);var g=class extends Error{constructor(n,r,i){super(r,i);o(this,"code");this.code=n,this.name="ProdantixError";}},x=class extends g{constructor(e){super("config",e),this.name="ConfigError";}},v=class extends g{constructor(n,r){super("validation",r);o(this,"field");this.field=n,this.name="ValidationError";}},d=class extends g{constructor(n,r,i){super("transport",n,i);o(this,"status");this.status=r,this.name="TransportError";}};function p(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 fe=t=>new Promise(e=>{setTimeout(e,t);});function l(t){return t.replace(/\/+$/,"")}var k=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 ge(){try{let t=globalThis.localStorage;if(t){let e="__pdx_probe__";return t.setItem(e,"1"),t.removeItem(e),t}}catch{return new k}return new k}var C={now:()=>new Date};function T(t){return t.toISOString()}function lt(){return globalThis.crypto}function ut(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 W(){let t=lt();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 ut(e)}var me={uuid:W};var pt=/^pdx_pub_(?:(?:live|test)_)?[a-z0-9]{32}$/;var ht=/^(?:\$|[a-z])[a-z0-9_.]*$/;function w(t){let e=0;for(let n of t)e+=1;return e}function ye(t){return pt.test(t)}function ft(t){return ht.test(t)}function ve(t){let e=w(t);if(e<1||e>200)throw new v("distinct_id","distinct_id must be between 1 and 200 characters")}function ke(t){let e=w(t);if(e<1||e>200)throw new v("event_name","event_name must be between 1 and 200 characters");if(!ft(t))throw new v("event_name","event_name must match /^(\\$|[a-z])[a-z0-9_.]*$/")}var be="prodantix-js",xe="0.0.1";var gt=t=>{};function Se(t){if(!t.apiKey||!ye(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=l(t.host),n=t.defaultProperties,r=t.storage??new k;return {apiKey:t.apiKey,autocapture:t.autocapture??false,clock:t.clock??C,consent:t.consent,defaultProperties:typeof n=="function"?n:()=>n??{},flagsHost:t.flagsHost?l(t.flagsHost):e,flushAt:t.flushAt??20,flushIntervalMs:t.flushIntervalMs??1e4,host:e,ids:t.ids??me,locale:t.locale,maxQueueSize:t.maxQueueSize??1e3,maxRetries:t.maxRetries??3,namespace:A(t.apiKey),onError:t.onError??gt,os:t.os,requestTimeoutMs:t.requestTimeoutMs??1e4,sdkName:t.sdkName??be,sdkVersion:t.sdkVersion??xe,sessionTracking:t.sessionTracking??false,sharedStorage:t.sharedStorage??r,socketFactory:t.socketFactory,storage:r,streamFlags:t.streamFlags??false,transport:t.transport}}function A(t){return t.slice(0,16)}function Ee(t,e,n){ke(t.eventName),ve(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:T(t.timestamp??e.now())};return t.context&&(r.context=t.context),t.sessionId&&(r.session_id=t.sessionId),r}var y=Symbol("absent");function mt(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]:y}function m(t){return t===y?"undefined":String(t)}function Ie(t){return t===y?Number.NaN:Number(t)}function Ce(t){return t!==y&&t!==null&&t!==""}function Te(t,e){if(!Array.isArray(e))return false;let n=m(t);return e.map(r=>String(r)).includes(n)}function we(t,e){let n=mt(t.attribute,e),r=t.value;switch(t.op){case "is_set":return Ce(n);case "is_not_set":return !Ce(n);case "eq":return m(n)===m(r===void 0?y:r);case "neq":return m(n)!==m(r===void 0?y:r);case "contains":return m(n).includes(m(r===void 0?y:r));case "in":return Te(n,r);case "not_in":return Array.isArray(r)?!Te(n,r):false;case "gt":return _(n,r,(i,s)=>i>s);case "gte":return _(n,r,(i,s)=>i>=s);case "lt":return _(n,r,(i,s)=>i<s);case "lte":return _(n,r,(i,s)=>i<=s);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,e,n){let r=Ie(t),i=e===void 0?Number.NaN:Ie(e);return Number.isNaN(r)||Number.isNaN(i)?false:n(r,i)}function Ae(t,e){let n=`${t}:${e}`,r=2166136261;for(let i=0;i<n.length;i++)r^=n.charCodeAt(i),r=Math.imul(r,16777619);return (r>>>0)%100}function Q(t,e){return t.targeting.length===0||t.targeting.every(n=>we(n,e))}function _e(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 i=0;for(let s=r.length-1;s>=0;s--)if(i+=r[s].weight,n<i)return r[s].key;return r[0].key}function X(t,e,n,r){for(let i of t.prerequisites??[]){if(r.includes(i.flagKey))return false;let s=e.find(c=>c.key===i.flagKey);if(!s||!s.enabled)return false;r.push(s.key);let a=X(s,e,n,r)&&Q(s,n)&&_e(s,n)===i.variationKey;if(r.pop(),!a)return false}return true}function F(t,e,n){return t.enabled?X(t,e,n,[t.key])?Q(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 Fe(t,e){let n={};for(let r of t)n[r.key]=F(r,t,e).enabled;return n}function Y(t,e,n){let r=t.variations??[],i=r[0];if(!i)return null;if(!t.enabled||!X(t,e,n,[t.key])||!Q(t,n))return i;let s=_e(t,n);return r.find(a=>a.key===s)??i}function Ne(t){return t.some(e=>e.targeting.some(n=>n.op==="in_cohort"||n.op==="not_in_cohort"))}function Le(t){return `40${JSON.stringify(t)}`}function Re(){return "3"}function Pe(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=Z(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),i=n.slice(1);if(r==="0")return {kind:"connected"};if(r==="1")return {kind:"disconnect"};if(r==="4"){let a=Z(i);return {kind:"connectError",message:typeof a?.message=="string"?a.message:"refused"}}if(r!=="2")return {kind:"other"};let s=Z(i);return !Array.isArray(s)||typeof s[0]!="string"?{kind:"other"}:{kind:"event",name:s[0],payload:s[1]}}function Z(t){try{return JSON.parse(t)}catch{return null}}var yt="/socket.io/?EIO=4&transport=websocket",vt=250,N=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??kt,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(/\/+$/,"")}${yt}`,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=Pe(e);if(n.kind==="open"){this.armHeartbeat(n.pingInterval+n.pingTimeout),this.socket?.send(Le({projectKey:this.options.projectKey}));return}if(n.kind==="ping"){this.armHeartbeat(),this.socket?.send(Re());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);},vt));}}}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 kt(t){let e=globalThis.WebSocket;if(!e)throw new Error("no WebSocket");return new e(t)}var L=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=p(e.fetch),this.host=l(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 d("no fetch implementation available in this runtime");let r=`${this.host}/v1/flags?distinct_id=${encodeURIComponent(e)}`,i=h(),s=i?setTimeout(()=>i.abort(),this.requestTimeoutMs):void 0;try{let a=await n(r,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:i?.signal});if(!a.ok)throw new d(`flags request failed with status ${a.status}`,a.status);let c=JSON.parse(await a.text());return {flags:c.flags??{},variants:c.variants??{}}}finally{s!==void 0&&clearTimeout(s);}}async snapshot(){let e=this.fetch;if(!e)throw new d("no fetch implementation available in this runtime");let n=`${this.host}/v1/flags/snapshot`,r=h(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let s=await e(n,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!s.ok)throw new d(`flag snapshot request failed with status ${s.status}`,s.status);let a=JSON.parse(await s.text()),c={flags:a.flags??[],generatedAt:a.generatedAt};return typeof a.socketUrl=="string"&&a.socketUrl!==""&&(c.socketUrl=a.socketUrl),c}finally{i!==void 0&&clearTimeout(i);}}async memberships(e){let n=this.fetch;if(!n)throw new d("no fetch implementation available in this runtime");let r=`${this.host}/v1/flags/memberships?distinct_id=${encodeURIComponent(e)}`,i=h(),s=i?setTimeout(()=>i.abort(),this.requestTimeoutMs):void 0;try{let a=await n(r,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:i?.signal});if(!a.ok)throw new d(`memberships request failed with status ${a.status}`,a.status);return JSON.parse(await a.text()).cohorts??[]}finally{s!==void 0&&clearTimeout(s);}}};function S(t){if(typeof t!="string")return;let e=Array.from(t).length;return e>=1&&e<=200?t:void 0}function P(t,e){return `pdx.${t}.${e}`}var Oe="consent";function bt(t){if(typeof t!="string")return null;try{let e=JSON.parse(t);if(e===null||typeof e!="object"||Array.isArray(e))return null;let n=e.identityLink;return typeof n=="boolean"?{identityLink:n}:null}catch{return null}}function xt(t,e){return bt(t.getItem(P(e,Oe)))}function St(t,e,n){let r=P(e,Oe);if(typeof n.identityLink!="boolean"){t.removeItem(r);return}t.setItem(r,JSON.stringify({identityLink:n.identityLink}));}function Me(t,e,n,r){let i=P(n,"anonymous_id"),s=S(e.getItem(i))??S(t.getItem(i));return e.setItem(i,r),t.setItem(i,r),s!==void 0&&s!==r?s:void 0}var R=class{constructor(e,n,r,i){this.storage=e;this.shared=n;this.ids=r;this.namespace=i;o(this,"anonymousId");o(this,"distinctId");o(this,"identified");this.refresh();}refresh(){let e=S(this.shared.getItem(this.key("anonymous_id"))),n=S(this.storage.getItem(this.key("anonymous_id")));e?(this.anonymousId=e,n!==e&&this.storage.setItem(this.key("anonymous_id"),e)):n?(this.anonymousId=n,this.shared.setItem(this.key("anonymous_id"),n)):(this.anonymousId=this.ids.uuid(),this.shared.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.setItem(this.key("anonymous_id"),this.anonymousId));let r=S(this.storage.getItem(this.key("distinct_id")));r?(this.distinctId=r,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}}consent(){return xt(this.shared,this.namespace)}setConsent(e){St(this.shared,this.namespace,e);}identify(e){let n=!this.identified||this.distinctId!==e,r=this.storage.getItem(this.key("linked_anonymous_id")),i=n||r!==this.anonymousId;return this.distinctId=e,this.identified=true,n&&this.storage.setItem(this.key("distinct_id"),e),!i||this.consent()?.identityLink===false?{changed:n}:(this.storage.setItem(this.key("linked_anonymous_id"),this.anonymousId),{anonymousToLink:this.anonymousId,changed:n})}reset(){this.anonymousId=this.ids.uuid(),this.distinctId=this.anonymousId,this.identified=false,this.shared.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.removeItem(this.key("distinct_id")),this.storage.removeItem(this.key("linked_anonymous_id"));}key(e){return P(this.namespace,e)}};var O=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=p(e.fetch),this.host=l(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)}`,i=await this.request(n,r,{headers:this.authHeaders(),method:"GET"});if(!i.ok)throw new d(`inbox request failed with status ${i.status}`,i.status);return JSON.parse(await i.text()).messages??[]}async markRead(e,n){let r=this.requireFetch(),i=`${this.host}/v1/messages/read`,s=await this.request(r,i,{body:JSON.stringify({distinct_id:n,message_id:e}),headers:{...this.authHeaders(),"content-type":"application/json"},method:"POST"});if(!s.ok)throw new d(`mark-read request failed with status ${s.status}`,s.status)}requireFetch(){if(!this.fetch)throw new d("no fetch implementation available in this runtime");return this.fetch}authHeaders(){return {authorization:`Bearer ${this.projectKey}`}}async request(e,n,r){let i=h(),s=i?setTimeout(()=>i.abort(),this.requestTimeoutMs):void 0;try{return await e(n,{...r,signal:i?.signal})}finally{s!==void 0&&clearTimeout(s);}}};var M=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});}};var Et={idleMs:18e5,maxMs:864e5,throttleMs:1e4};function $e(t){return `pdx.${t}.session`}function De(t,e,n,r){let i={id:n.id,lastActivityAt:r,startedAt:n.startedAt};t.setItem($e(e),JSON.stringify(i));}var $=class{constructor(e,n,r,i,s=Et){this.storage=e;this.ids=n;this.clock=r;this.namespace=i;this.options=s;}current(){return this.touch().id}startedAt(){return this.touch().startedAt}reset(){this.storage.removeItem(this.key());}touch(){let e=this.clock.now().getTime(),n=this.live(this.read(),e);if(n===void 0)return this.write({id:this.ids.uuid(),lastActivityAt:e,startedAt:e});if(e-n.lastActivityAt<=this.options.throttleMs)return n;let r=this.live(this.read(),e),i=r!==void 0&&r.id!==n.id?r:n;return this.write({...i,lastActivityAt:e})}live(e,n){if(e!==void 0&&!(n-e.lastActivityAt>this.options.idleMs||n-e.startedAt>this.options.maxMs))return e}write(e){return this.storage.setItem(this.key(),JSON.stringify(e)),e}read(){let e=this.storage.getItem(this.key());if(e)try{let n=JSON.parse(e);return typeof n.id=="string"&&typeof n.startedAt=="number"&&typeof n.lastActivityAt=="number"?{id:n.id,lastActivityAt:n.lastActivityAt,startedAt:n.startedAt}:void 0}catch{return}}key(){return $e(this.namespace)}};function qe(t){return t>=400&&t<500&&t!==429}var b=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=p(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??fe,this.random=e.random??Math.random;}async send(e){let n=this.fetch;if(!n)throw new d("no fetch implementation available in this runtime");let r=JSON.stringify(e.body),i;for(let s=0;s<=this.maxRetries;s+=1){try{let a=await this.attempt(n,e,r);if(a.ok)return;if(qe(a.status))throw new d(`ingest rejected batch with status ${a.status}`,a.status);i=new d(`ingest transient status ${a.status}`,a.status);}catch(a){if(a instanceof d&&a.status!==void 0&&qe(a.status))throw a;i=a;}s<this.maxRetries&&await this.sleep(this.backoff(s));}throw new d("ingest delivery failed after retries",void 0,{cause:i})}async attempt(e,n,r){let i=h(),s=i?setTimeout(()=>i.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:i?.signal})}finally{s!==void 0&&clearTimeout(s);}}backoff(e){return Math.min(this.maxDelayMs,this.baseDelayMs*2**e)+this.random()*this.baseDelayMs}};var It="queue",Ct=1e3,Ke=3e4,ee=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},D=class{constructor(e){o(this,"config");o(this,"identity");o(this,"session");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=Se(e),this.identity=new R(this.config.storage,this.config.sharedStorage,this.config.ids,this.config.namespace),this.config.consent!==void 0&&this.identity.setConsent(this.config.consent),this.session=this.config.sessionTracking?new $(this.config.sharedStorage,this.config.ids,this.config.clock,this.config.namespace):void 0,this.queue=new M(this.config.maxQueueSize,({dropped:n})=>{this.config.onError(new g("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 L({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.messagesClient=new O({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()}get isIdentified(){return this.identity.isIdentified()}get sessionId(){return this.session?.current()}get sessionStartedAt(){return this.session?.startedAt()}capture(e,n={}){try{this.identity.refresh();let r={...this.config.defaultProperties(),...n.properties??{}},i=Ee({context:this.context,distinctId:n.distinctId??this.identity.getDistinctId(),eventName:e,properties:r,sessionId:n.sessionId??this.session?.current(),timestamp:n.timestamp},this.config.clock,this.config.ids);this.enqueue(i);}catch(r){this.config.onError(r);}}identify(e,n={}){this.identity.refresh();let r=this.identity.identify(e),i={};r.anonymousToLink!==void 0&&(i.$anon_distinct_id=r.anonymousToLink);let s={...ee(n.traits??{}),...n.set??{}};Object.keys(s).length>0&&(i.$set=s),this.capture("$identify",{properties:i});}link(e,n,r){let i={$anon_distinct_id:n},s=ee(r??{});Object.keys(s).length>0&&(i.$set=s),this.capture("$identify",{distinctId:e,properties:i});}setConsent(e){this.identity.setConsent(e);}consent(){return this.identity.consent()}alias(e){this.capture("$create_alias",{properties:{alias:e}});}group(e,n,r){let i={$group_key:n,$group_type:e};r&&(i.$set=r),this.capture("$group",{properties:i});}setPersonProperties(e,n){let r={};e&&(r.$set=e),n&&(r.$set_once=n),this.capture("$set",{properties:r});}setPersonTraits(e){let n=ee(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(),i=r.flags.find(u=>u.key===e),s=await this.localContext(n,r.flags),a=i?Y(i,r.flags,s):null,c=i?F(i,r.flags,s).enabled:false;return this.recordExposure(e,a?.key??String(c)),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 Fe(n.flags,await this.localContext(e,n.flags))}async isFeatureEnabledLocal(e,n={}){let r=await this.flagSnapshot(),i=r.flags.find(c=>c.key===e),s=await this.localContext(n,r.flags),a=i?F(i,r.flags,s).enabled:false;return this.recordExposure(e,(i?Y(i,r.flags,s)?.key:void 0)??String(a)),a}async localContext(e,n){let r=this.identity.getDistinctId(),i=e.cohorts;if(i===void 0&&Ne(n)){let s=this.config.clock.now().getTime();this.membershipCache&&this.membershipCache.distinctId===r&&s-this.membershipCache.fetchedAt<Ke?i=this.membershipCache.cohorts:(i=await this.flagsClient.memberships(r),this.membershipCache={cohorts:i,distinctId:r,fetchedAt:s});}return {attributes:e.attributes,cohorts:i,distinctId:r,properties:e.properties}}async flagSnapshot(){let e=this.config.clock.now().getTime();if(this.cachedSnapshot&&e-this.cachedSnapshot.fetchedAt<Ke)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 N({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(Ct);try{await this.transport.send({body:{events:e,sent_at:T(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.session?.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}.${It}`}};function Ve(){return globalThis.location}function je(){return globalThis.document}function Tt(){return globalThis.window??globalThis}function wt(t){return typeof t=="object"&&t!==null&&typeof t.tagName=="string"}function He(){let t=Ve(),e=je(),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 At(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 _t(t){let e=globalThis.history,n=Tt(),r="",i=()=>{let c=Ve(),u=c?`${c.pathname}${c.search}`:"";u!==r&&(r=u,t.capture("$pageview",{properties:He()}));};if(i(),!e||!n)return ()=>{};let s=e.pushState.bind(e),a=e.replaceState.bind(e);return e.pushState=(...c)=>{s(...c),i();},e.replaceState=(...c)=>{a(...c),i();},n.addEventListener("popstate",i),()=>{e.pushState=s,e.replaceState=a,n.removeEventListener("popstate",i);}}function Ft(t){let e=je();if(!e)return ()=>{};let n=r=>{let i=r.target;wt(i)&&t.capture("$autocapture",{properties:{...He(),...At(i)}});};return e.addEventListener("click",n,true),()=>e.removeEventListener("click",n,true)}function Ue(t,e={}){let n=[];return (e.pageviews??true)&&n.push(_t(t)),(e.clicks??true)&&n.push(Ft(t)),()=>{for(let r of n)r();}}function Nt(){return globalThis.document?.visibilityState==="hidden"}function Lt(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 i=new n([r],{type:"application/json"});return e.sendBeacon(t.url,i)}catch{return false}}var q=class{constructor(e={}){o(this,"fetchTransport");this.fetchTransport=new b(e);}async send(e){Nt()&&Lt(e)||await this.fetchTransport.send(e);}};var Rt=/^\d{1,3}(\.\d{1,3}){3}$/,Pt=/^[a-z0-9.-]+$/i;function Je(){return Math.random().toString(36).slice(2,12)}function K(t,e){let n=`${e}=`,r=[];for(let i of t.cookie.split(";")){let s=i.trim();s.startsWith(n)&&r.push(s.slice(n.length));}return r}function E(t,e,n){let r=["Path=/",`Max-Age=${e}`,"SameSite=Lax"];return t&&r.push(`Domain=${t}`),n&&r.push("Secure"),r.join("; ")}function ze(t,e,n,r){try{let i=`pdx_probe_${r()}`,s=r();t.cookie=`${i}=${s}; ${E(e,60,n)}`;let a=K(t,i).includes(s);t.cookie=`${i}=; ${E(e,0,n)}`;let c=K(t,i).includes(s);return a&&!c}catch{return false}}function ne(t){let e=t.replace(/^\[|\]$/g,"").toLowerCase();if(e.includes(":")||Rt.test(e)||!e.includes("."))return [];let n=e.split("."),r=[];for(let i=n.length-2;i>=0;i-=1)r.push(n.slice(i).join("."));return r}function Ge(t,e,n,r=Je){for(let i of ne(t))if(ze(e,i,n,r))return i}function Ot(t){let e=new Map,n=JSON.parse(decodeURIComponent(t));if(n===null||typeof n!="object"||Array.isArray(n))return e;for(let[r,i]of Object.entries(n))typeof i=="string"&&e.set(r,i);return e}var te=class{constructor(e,n,r,i){this.jar=e;this.name=n;this.domain=r;this.secure=i;}getItem(e){return this.read().get(e)??null}setItem(e,n){let r=this.read();r.set(e,n),this.write(r);}removeItem(e){let n=this.read();n.delete(e)&&this.write(n);}read(){try{let e=K(this.jar,this.name);e.length>1&&this.domain&&(this.jar.cookie=`${this.name}=; ${E(void 0,0,this.secure)}`,e=K(this.jar,this.name));let n=e[0];return n?Ot(n):new Map}catch{return new Map}}write(e){try{if(e.size===0){this.jar.cookie=`${this.name}=; ${E(this.domain,0,this.secure)}`;return}let n=encodeURIComponent(JSON.stringify(Object.fromEntries(e)));this.jar.cookie=`${this.name}=${n}; ${E(this.domain,31536e3,this.secure)}`;}catch{return}}};function Mt(){return globalThis.document}function $t(){return globalThis.location?.hostname??""}function Dt(){return globalThis.location?.protocol==="https:"}function qt(t){if(t===void 0)return;let e=t.startsWith(".")?t.slice(1):t;return Pt.test(e)?e.toLowerCase():void 0}function re(t){let e="jar"in t?t.jar:Mt();if(!e||globalThis.navigator?.cookieEnabled===false)return null;let r=t.random??Je,i=t.secure??Dt(),s=t.hostname??$t();try{let a=qt(t.domain)??Ge(s,e,i,r);return ze(e,a,i,r)?new te(e,t.name,a,i):null}catch{return null}}var Qe="_pdx",Xe="~",Kt=200,Vt=/^\d+$/;function Ye(t,e,n,r){let i=Ht(t.href);if(i===void 0||se(i.search).some(oe))return;let s=Be(i.hostname,n);s===void 0||s===Be(r,n)||(i.search=`${i.search}${i.search?"&":"?"}${Qe}=${jt(e)}`,t.href=i.href);}function jt(t){return [t.anonymousId,t.sessionId,String(t.sessionStartedAt)].map(Jt).join(Xe)}function Ze(t){let e=se(t).find(oe);if(e===void 0)return;let n=Ut(e).split(Xe);if(n.length!==3)return;let r=V(n[0]),i=V(n[1]),s=V(n[2]);if(!(!We(r)||!We(i)||!zt(s)))return {anonymousId:r,sessionId:i,sessionStartedAt:Number(s)}}function et(t,e){let n=se(e.search),r=n.filter(s=>!oe(s));if(r.length===n.length)return;let i=r.length>0?`?${r.join("&")}`:"";t.replaceState(t.state,"",`${e.pathname}${i}${e.hash}`);}function tt(t){if(t.location===void 0||typeof t.location.search!="string")return;let e=Ze(t.location.search);if(e===void 0)return;let n=Me(t.storage,t.shared,t.namespace,e.anonymousId);return De(t.shared,t.namespace,{id:e.sessionId,startedAt:e.sessionStartedAt},t.now),t.history!==void 0&&et(t.history,t.location),n}function ie(t,e,n){if(n.length===0)return ()=>{};let r=i=>{let s=Wt(i.target);if(s===void 0)return;let a=Gt(e);a!==void 0&&Ye(s,a,n,t.location?.hostname??"");};return t.addEventListener("click",r,true),t.addEventListener("auxclick",r,true),()=>{t.removeEventListener("click",r,true),t.removeEventListener("auxclick",r,true);}}function Ht(t){try{let e=new URL(t);return e.protocol==="http:"||e.protocol==="https:"?e:void 0}catch{return}}function Be(t,e){let n=e.map(r=>r.replace(/^\./,"").toLowerCase());return ne(t).find(r=>n.includes(r))}function se(t){return t.replace(/^\?/,"").split("&").filter(e=>e!=="")}function oe(t){let e=t.indexOf("=");return V(e===-1?t:t.slice(0,e))===Qe}function Ut(t){let e=t.indexOf("=");return e===-1?"":t.slice(e+1)}function Jt(t){return encodeURIComponent(t).replace(/~/g,"%7E")}function V(t){try{return decodeURIComponent(t)}catch{return}}function We(t){if(t===void 0)return false;let e=w(t);return e>=1&&e<=Kt}function zt(t){return t!==void 0&&Vt.test(t)&&Number.isSafeInteger(Number(t))}function Gt(t){if(t.consent?.()?.identityLink===false)return;let e=t.sessionId,n=t.sessionStartedAt;if(!(e===void 0||n===void 0))return {anonymousId:t.anonymousId,sessionId:e,sessionStartedAt:n}}function Bt(t){return typeof t.tagName=="string"&&t.tagName.toUpperCase()==="A"&&typeof t.href=="string"}function Wt(t){let e=typeof t=="object"?t:null;for(;e;){if(Bt(e))return e;e=e.parentElement??null;}}var nt={maskAllInputs:true,maskAllText:false},Qt=new Set(["email","password","tel"]);function rt(t){return t.replace(/\S/g,"*")}function j(t,e,n){return Xt(e)||n.maskAllInputs?rt(t):t}function H(t,e){return e.maskAllText?rt(t):t}function Xt(t){return Qt.has((t??"").toLowerCase())}var Yt=5e3,U=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),Yt);}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 ae=1,ce=3,Zt=9,J=class{constructor(){o(this,"next",1);}allocate(){let e=this.next;return this.next+=1,e}},en=new Set(["NOSCRIPT","SCRIPT"]);function z(t,e,n,r){if(t.nodeType===ce){let i=e.allocate();return r?.(t,i),{id:i,textContent:H(t.textValue??"",n),type:"text"}}if(t.nodeType===Zt){let i=e.allocate();return r?.(t,i),{childNodes:it(t,e,n,r),id:i,type:"document"}}if(t.nodeType===ae){let i=t.tagName??"";if(en.has(i))return null;let s=e.allocate();return r?.(t,s),{attributes:tn(t,n),childNodes:it(t,e,n,r),id:s,tagName:i,type:"element"}}return null}function it(t,e,n,r){let i=[];for(let s of t.childNodes??[]){let a=z(s,e,n,r);a&&i.push(a);}return i}function tn(t,e){let n={};for(let r of t.attributes??[])n[r.name]=r.value;return t.inputValue!==void 0&&(n.value=j(t.inputValue,t.inputType,e)),n}async function st(t,e){let n=`${l(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 ot=new Set(["INPUT","SELECT","TEXTAREA"]),G=class{constructor(e){this.options=e;o(this,"allocator",new J);o(this,"mirror",new Map);o(this,"chunker");o(this,"fetchImpl");o(this,"observer");o(this,"timer");o(this,"started",false);this.chunker=new U({distinctId:e.distinctId,masked:e.mask.maskAllInputs,maxEvents:e.maxEvents,now:e.now,sessionId:e.sessionId}),this.fetchImpl=p(e.fetch);}start(){if(this.started)return;let e=nn(),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=z(this.adapt(e),this.allocator,this.options.mask,(r,i)=>{let s=r.ref;s&&this.mirror.set(s,i);});n&&this.push(2,{node:n});}observeMutations(e){let n=globalThis.MutationObserver;n&&(this.observer=new n(r=>{for(let i of r)this.handleMutation(i);}),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:H(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 i=z(this.adapt(r),this.allocator,this.options.mask,(s,a)=>{let c=s.ref;c&&this.mirror.set(c,a);});i&&this.push(3,{adds:[{node:i,parentId:n}]});}for(let r of Array.from(e.removedNodes)){let i=this.mirror.get(r);i!==void 0&&(this.push(3,{removes:[{id:i,parentId:n}]}),this.mirror.delete(r));}}}observeInteractions(e){e.addEventListener("input",n=>{let r=n.target;if(!r||!ot.has(r.tagName))return;let i=this.mirror.get(r);i!==void 0&&this.push(3,{input:{id:i,value:j(r.value??"",r.type,this.options.mask)}});},true),e.addEventListener("scroll",n=>{let r=n.target,i=r?this.mirror.get(r):void 0;this.push(3,{scroll:{id:i??0,x:r?.scrollLeft??0,y:r?.scrollTop??0}});},true);}adapt(e){let n={childNodes:[],nodeType:e.nodeType,ref:e};if(e.nodeType===ce)return n.textValue=e.textContent??"",n;if(e.nodeType===ae){let r=e;if(n.tagName=r.tagName,n.attributes=Array.from(r.attributes).map(i=>({name:i.name,value:i.value})),ot.has(r.tagName)){let i=r;n.inputType=i.type,n.inputValue=i.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||st(e,{apiKey:this.options.apiKey,fetch:this.fetchImpl,replayHost:this.options.replayHost}).catch(n=>this.options.onError?.(n));}};function nn(){return globalThis.document}function at(t){let e=new G({apiKey:t.apiKey,distinctId:t.distinctId,flushIntervalMs:t.flushIntervalMs??5e3,mask:{...nt,...t.mask},maxEvents:t.maxEvents??200,now:t.now??(()=>Date.now()),onError:t.onError,replayHost:t.replayHost,sessionId:t.sessionId??W()});return e.start(),e}function rn(){return globalThis.navigator}function sn(){return globalThis.document}function on(){return globalThis.history}function an(){return globalThis.location}function cn(t){let e=t?.userAgentData?.platform??t?.platform;return e?e.slice(0,50):void 0}function dn(t){let e=()=>{t.flush();};globalThis.document?.addEventListener?.("visibilitychange",e),globalThis.addEventListener?.("pagehide",e);}function ln(t,e,n){try{return re({domain:e,name:`pdx_${A(t)}`})??n}catch{return n}}function ri(t){let{autocaptureOptions:e,cookieDomain:n,linkedDomains:r,replayHost:i,sessionReplay:s,sessionReplayOptions:a,...c}=t,u=rn(),de=ge(),le=c.storage??de,ue=c.sharedStorage??ln(c.apiKey,n,de),pe=tt({history:on(),location:an(),namespace:A(c.apiKey),now:(c.clock??C).now().getTime(),shared:ue,storage:le}),B={...c,locale:c.locale??(u?.language?u.language.slice(0,20):void 0),os:c.os??cn(u),sessionTracking:c.sessionTracking??true,sharedStorage:ue,storage:le,transport:c.transport??new q({maxRetries:c.maxRetries,requestTimeoutMs:c.requestTimeoutMs})},f=new D(B);pe!==void 0&&f.alias(pe),dn(f),(t.autocapture??true)&&Ue(f,e);let he=sn();return he&&r&&ie(he,f,r),s&&i&&at({apiKey:B.apiKey,distinctId:()=>f.distinctId,onError:B.onError,replayHost:i,...a,sessionId:a?.sessionId??f.sessionId}),f}exports.WebTransport=q;exports.createCookieStorage=re;exports.createWebClient=ri;exports.decorateLink=Ye;exports.installAutocapture=Ue;exports.installLinkCarry=ie;exports.installSessionReplay=at;exports.readCarry=Ze;exports.resolveCookieDomain=Ge;exports.stripCarry=et;//# sourceMappingURL=web.cjs.map
1
+ 'use strict';var dt=Object.defineProperty;var lt=(t,e,n)=>e in t?dt(t,e,{enumerable:true,configurable:true,writable:true,value:n}):t[e]=n;var o=(t,e,n)=>lt(t,typeof e!="symbol"?e+"":e,n);var g=class extends Error{constructor(n,r,i){super(r,i);o(this,"code");this.code=n,this.name="ProdantixError";}},E=class extends g{constructor(e){super("config",e),this.name="ConfigError";}},k=class extends g{constructor(n,r){super("validation",r);o(this,"field");this.field=n,this.name="ValidationError";}},d=class extends g{constructor(n,r,i){super("transport",n,i);o(this,"status");this.status=r,this.name="TransportError";}};function h(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 me=t=>new Promise(e=>{setTimeout(e,t);});function u(t){return t.replace(/\/+$/,"")}var b=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 ge(){try{let t=globalThis.localStorage;if(t){let e="__pdx_probe__";return t.setItem(e,"1"),t.removeItem(e),t}}catch{return new b}return new b}var C={now:()=>new Date};function T(t){return t.toISOString()}function ut(){return globalThis.crypto}function pt(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=ut();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 pt(e)}var ye={uuid:Q};var ht=/^pdx_pub_(?:(?:live|test)_)?[a-z0-9]{32}$/;var ft=/^(?:\$|[a-z])[a-z0-9_.]*$/;function A(t){let e=0;for(let n of t)e+=1;return e}function ve(t){return ht.test(t)}function mt(t){return ft.test(t)}function ke(t){let e=A(t);if(e<1||e>200)throw new k("distinct_id","distinct_id must be between 1 and 200 characters")}function be(t){let e=A(t);if(e<1||e>200)throw new k("event_name","event_name must be between 1 and 200 characters");if(!mt(t))throw new k("event_name","event_name must match /^(\\$|[a-z])[a-z0-9_.]*$/")}var xe="prodantix-js",Ee="0.0.1";var gt=t=>{};function Se(t){if(!t.apiKey||!ve(t.apiKey))throw new E("apiKey must be a public project key of the form pdx_pub_<32 lowercase alphanumerics>");if(!t.host)throw new E("host is required (the ingest base URL)");let e=u(t.host),n=t.defaultProperties,r=t.storage??new b;return {apiKey:t.apiKey,autocapture:t.autocapture??false,clock:t.clock??C,consent:t.consent,defaultProperties:typeof n=="function"?n:()=>n??{},flagsHost:t.flagsHost?u(t.flagsHost):e,flushAt:t.flushAt??20,flushIntervalMs:t.flushIntervalMs??1e4,host:e,ids:t.ids??ye,locale:t.locale,maxQueueSize:t.maxQueueSize??1e3,maxRetries:t.maxRetries??3,namespace:_(t.apiKey),onError:t.onError??gt,os:t.os,requestTimeoutMs:t.requestTimeoutMs??1e4,sdkName:t.sdkName??xe,sdkVersion:t.sdkVersion??Ee,sessionTracking:t.sessionTracking??false,sharedStorage:t.sharedStorage??r,socketFactory:t.socketFactory,storage:r,streamFlags:t.streamFlags??false,transport:t.transport}}function _(t){return t.slice(0,16)}function Ie(t,e,n){be(t.eventName),ke(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:T(t.timestamp??e.now())};return t.context&&(r.context=t.context),t.sessionId&&(r.session_id=t.sessionId),r}var v=Symbol("absent");function yt(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]:v}function y(t){return t===v?"undefined":String(t)}function we(t){return t===v?Number.NaN:Number(t)}function Ce(t){return t!==v&&t!==null&&t!==""}function Te(t,e){if(!Array.isArray(e))return false;let n=y(t);return e.map(r=>String(r)).includes(n)}function Ae(t,e){let n=yt(t.attribute,e),r=t.value;switch(t.op){case "is_set":return Ce(n);case "is_not_set":return !Ce(n);case "eq":return y(n)===y(r===void 0?v:r);case "neq":return y(n)!==y(r===void 0?v:r);case "contains":return y(n).includes(y(r===void 0?v:r));case "in":return Te(n,r);case "not_in":return Array.isArray(r)?!Te(n,r):false;case "gt":return N(n,r,(i,s)=>i>s);case "gte":return N(n,r,(i,s)=>i>=s);case "lt":return N(n,r,(i,s)=>i<s);case "lte":return N(n,r,(i,s)=>i<=s);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 N(t,e,n){let r=we(t),i=e===void 0?Number.NaN:we(e);return Number.isNaN(r)||Number.isNaN(i)?false:n(r,i)}function _e(t,e){let n=`${t}:${e}`,r=2166136261;for(let i=0;i<n.length;i++)r^=n.charCodeAt(i),r=Math.imul(r,16777619);return (r>>>0)%100}function X(t,e){return t.targeting.length===0||t.targeting.every(n=>Ae(n,e))}function Ne(t,e){let n=_e(t.key,e.distinctId),r=t.variations??[];if(r.length===0)return t.rolloutPercentage>=100||n<t.rolloutPercentage?"true":"false";let i=0;for(let s=r.length-1;s>=0;s--)if(i+=r[s].weight,n<i)return r[s].key;return r[0].key}function Y(t,e,n,r){for(let i of t.prerequisites??[]){if(r.includes(i.flagKey))return false;let s=e.find(c=>c.key===i.flagKey);if(!s||!s.enabled)return false;r.push(s.key);let a=Y(s,e,n,r)&&X(s,n)&&Ne(s,n)===i.variationKey;if(r.pop(),!a)return false}return true}function F(t,e,n){return t.enabled?Y(t,e,n,[t.key])?X(t,n)?t.rolloutPercentage>=100?{enabled:true,reason:"rollout_full"}:_e(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 Fe(t,e){let n={};for(let r of t)n[r.key]=F(r,t,e).enabled;return n}function Z(t,e,n){let r=t.variations??[],i=r[0];if(!i)return null;if(!t.enabled||!Y(t,e,n,[t.key])||!X(t,n))return i;let s=Ne(t,n);return r.find(a=>a.key===s)??i}function Le(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 Re(){return "3"}function Oe(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=ee(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),i=n.slice(1);if(r==="0")return {kind:"connected"};if(r==="1")return {kind:"disconnect"};if(r==="4"){let a=ee(i);return {kind:"connectError",message:typeof a?.message=="string"?a.message:"refused"}}if(r!=="2")return {kind:"other"};let s=ee(i);return !Array.isArray(s)||typeof s[0]!="string"?{kind:"other"}:{kind:"event",name:s[0],payload:s[1]}}function ee(t){try{return JSON.parse(t)}catch{return null}}var vt="/socket.io/?EIO=4&transport=websocket",kt=250,L=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??bt,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(/\/+$/,"")}${vt}`,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=Oe(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(Re());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);},kt));}}}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 bt(t){let e=globalThis.WebSocket;if(!e)throw new Error("no WebSocket");return new e(t)}var P=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=h(e.fetch),this.host=u(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 d("no fetch implementation available in this runtime");let r=`${this.host}/v1/flags?distinct_id=${encodeURIComponent(e)}`,i=f(),s=i?setTimeout(()=>i.abort(),this.requestTimeoutMs):void 0;try{let a=await n(r,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:i?.signal});if(!a.ok)throw new d(`flags request failed with status ${a.status}`,a.status);let c=JSON.parse(await a.text());return {flags:c.flags??{},variants:c.variants??{}}}finally{s!==void 0&&clearTimeout(s);}}async snapshot(){let e=this.fetch;if(!e)throw new d("no fetch implementation available in this runtime");let n=`${this.host}/v1/flags/snapshot`,r=f(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let s=await e(n,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!s.ok)throw new d(`flag snapshot request failed with status ${s.status}`,s.status);let a=JSON.parse(await s.text()),c={flags:a.flags??[],generatedAt:a.generatedAt};return typeof a.socketUrl=="string"&&a.socketUrl!==""&&(c.socketUrl=a.socketUrl),c}finally{i!==void 0&&clearTimeout(i);}}async memberships(e){let n=this.fetch;if(!n)throw new d("no fetch implementation available in this runtime");let r=`${this.host}/v1/flags/memberships?distinct_id=${encodeURIComponent(e)}`,i=f(),s=i?setTimeout(()=>i.abort(),this.requestTimeoutMs):void 0;try{let a=await n(r,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:i?.signal});if(!a.ok)throw new d(`memberships request failed with status ${a.status}`,a.status);return JSON.parse(await a.text()).cohorts??[]}finally{s!==void 0&&clearTimeout(s);}}};function S(t){if(typeof t!="string")return;let e=Array.from(t).length;return e>=1&&e<=200?t:void 0}function O(t,e){return `pdx.${t}.${e}`}var $e="consent";function xt(t){if(typeof t!="string")return null;try{let e=JSON.parse(t);if(e===null||typeof e!="object"||Array.isArray(e))return null;let n=e.identityLink;return typeof n=="boolean"?{identityLink:n}:null}catch{return null}}function Et(t,e){return xt(t.getItem(O(e,$e)))}function St(t,e,n){let r=O(e,$e);if(typeof n.identityLink!="boolean"){t.removeItem(r);return}t.setItem(r,JSON.stringify({identityLink:n.identityLink}));}function Me(t,e,n,r){let i=O(n,"anonymous_id"),s=S(e.getItem(i))??S(t.getItem(i));return e.setItem(i,r),t.setItem(i,r),s!==void 0&&s!==r?s:void 0}var R=class{constructor(e,n,r,i){this.storage=e;this.shared=n;this.ids=r;this.namespace=i;o(this,"anonymousId");o(this,"distinctId");o(this,"identified");this.refresh();}refresh(){let e=S(this.shared.getItem(this.key("anonymous_id"))),n=S(this.storage.getItem(this.key("anonymous_id")));e?(this.anonymousId=e,n!==e&&this.storage.setItem(this.key("anonymous_id"),e)):n?(this.anonymousId=n,this.shared.setItem(this.key("anonymous_id"),n)):(this.anonymousId=this.ids.uuid(),this.shared.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.setItem(this.key("anonymous_id"),this.anonymousId));let r=S(this.storage.getItem(this.key("distinct_id")));r?(this.distinctId=r,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}}consent(){return Et(this.shared,this.namespace)}setConsent(e){St(this.shared,this.namespace,e);}identify(e){let n=!this.identified||this.distinctId!==e,r=this.storage.getItem(this.key("linked_anonymous_id")),i=n||r!==this.anonymousId;return this.distinctId=e,this.identified=true,n&&this.storage.setItem(this.key("distinct_id"),e),!i||this.consent()?.identityLink===false?{changed:n}:(this.storage.setItem(this.key("linked_anonymous_id"),this.anonymousId),{anonymousToLink:this.anonymousId,changed:n})}reset(){this.anonymousId=this.ids.uuid(),this.distinctId=this.anonymousId,this.identified=false,this.shared.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.removeItem(this.key("distinct_id")),this.storage.removeItem(this.key("linked_anonymous_id"));}key(e){return O(this.namespace,e)}};var $=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=h(e.fetch),this.host=u(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)}`,i=await this.request(n,r,{headers:this.authHeaders(),method:"GET"});if(!i.ok)throw new d(`inbox request failed with status ${i.status}`,i.status);return JSON.parse(await i.text()).messages??[]}async markRead(e,n){let r=this.requireFetch(),i=`${this.host}/v1/messages/read`,s=await this.request(r,i,{body:JSON.stringify({distinct_id:n,message_id:e}),headers:{...this.authHeaders(),"content-type":"application/json"},method:"POST"});if(!s.ok)throw new d(`mark-read request failed with status ${s.status}`,s.status)}requireFetch(){if(!this.fetch)throw new d("no fetch implementation available in this runtime");return this.fetch}authHeaders(){return {authorization:`Bearer ${this.projectKey}`}}async request(e,n,r){let i=f(),s=i?setTimeout(()=>i.abort(),this.requestTimeoutMs):void 0;try{return await e(n,{...r,signal:i?.signal})}finally{s!==void 0&&clearTimeout(s);}}};var M=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});}};var It={idleMs:18e5,maxMs:864e5,throttleMs:1e4};function De(t){return `pdx.${t}.session`}function qe(t,e,n,r){let i={id:n.id,lastActivityAt:r,startedAt:n.startedAt};t.setItem(De(e),JSON.stringify(i));}var D=class{constructor(e,n,r,i,s=It){this.storage=e;this.ids=n;this.clock=r;this.namespace=i;this.options=s;}current(){return this.touch().id}startedAt(){return this.touch().startedAt}reset(){this.storage.removeItem(this.key());}touch(){let e=this.clock.now().getTime(),n=this.live(this.read(),e);if(n===void 0)return this.write({id:this.ids.uuid(),lastActivityAt:e,startedAt:e});if(e-n.lastActivityAt<=this.options.throttleMs)return n;let r=this.live(this.read(),e),i=r!==void 0&&r.id!==n.id?r:n;return this.write({...i,lastActivityAt:e})}live(e,n){if(e!==void 0&&!(n-e.lastActivityAt>this.options.idleMs||n-e.startedAt>this.options.maxMs))return e}write(e){return this.storage.setItem(this.key(),JSON.stringify(e)),e}read(){let e=this.storage.getItem(this.key());if(e)try{let n=JSON.parse(e);return typeof n.id=="string"&&typeof n.startedAt=="number"&&typeof n.lastActivityAt=="number"?{id:n.id,lastActivityAt:n.lastActivityAt,startedAt:n.startedAt}:void 0}catch{return}}key(){return De(this.namespace)}};var l={autocapture:"$autocapture",createAlias:"$create_alias",featureFlagCalled:"$feature_flag_called",group:"$group",identify:"$identify",pageview:"$pageview",set:"$set"};function Ke(t){return t>=400&&t<500&&t!==429}var x=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=h(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??me,this.random=e.random??Math.random;}async send(e){let n=this.fetch;if(!n)throw new d("no fetch implementation available in this runtime");let r=JSON.stringify(e.body),i;for(let s=0;s<=this.maxRetries;s+=1){try{let a=await this.attempt(n,e,r);if(a.ok)return;if(Ke(a.status))throw new d(`ingest rejected batch with status ${a.status}`,a.status);i=new d(`ingest transient status ${a.status}`,a.status);}catch(a){if(a instanceof d&&a.status!==void 0&&Ke(a.status))throw a;i=a;}s<this.maxRetries&&await this.sleep(this.backoff(s));}throw new d("ingest delivery failed after retries",void 0,{cause:i})}async attempt(e,n,r){let i=f(),s=i?setTimeout(()=>i.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:i?.signal})}finally{s!==void 0&&clearTimeout(s);}}backoff(e){return Math.min(this.maxDelayMs,this.baseDelayMs*2**e)+this.random()*this.baseDelayMs}};var wt="queue",Ct=1e3,Ve=3e4,te=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},q=class{constructor(e){o(this,"config");o(this,"identity");o(this,"session");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=Se(e),this.identity=new R(this.config.storage,this.config.sharedStorage,this.config.ids,this.config.namespace),this.config.consent!==void 0&&this.identity.setConsent(this.config.consent),this.session=this.config.sessionTracking?new D(this.config.sharedStorage,this.config.ids,this.config.clock,this.config.namespace):void 0,this.queue=new M(this.config.maxQueueSize,({dropped:n})=>{this.config.onError(new g("queue_overflow",`event queue overflow: dropped ${n.length} oldest event(s)`));}),this.transport=this.config.transport??new x({maxRetries:this.config.maxRetries,requestTimeoutMs:this.config.requestTimeoutMs}),this.flagsClient=new P({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.messagesClient=new $({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()}get isIdentified(){return this.identity.isIdentified()}get sessionId(){return this.session?.current()}get sessionStartedAt(){return this.session?.startedAt()}capture(e,n={}){try{this.identity.refresh();let r={...this.config.defaultProperties(),...n.properties??{}},i=Ie({context:this.context,distinctId:n.distinctId??this.identity.getDistinctId(),eventName:e,properties:r,sessionId:n.sessionId??this.session?.current(),timestamp:n.timestamp},this.config.clock,this.config.ids);this.enqueue(i);}catch(r){this.config.onError(r);}}identify(e,n={}){this.identity.refresh();let r=this.identity.identify(e),i={};r.anonymousToLink!==void 0&&(i.$anon_distinct_id=r.anonymousToLink);let s={...te(n.traits??{}),...n.set??{}};Object.keys(s).length>0&&(i.$set=s),this.capture(l.identify,{properties:i});}link(e,n,r){let i={$anon_distinct_id:n},s=te(r??{});Object.keys(s).length>0&&(i.$set=s),this.capture(l.identify,{distinctId:e,properties:i});}setConsent(e){this.identity.setConsent(e);}consent(){return this.identity.consent()}alias(e){this.capture(l.createAlias,{properties:{alias:e}});}group(e,n,r){let i={$group_key:n,$group_type:e};r&&(i.$set=r),this.capture(l.group,{properties:i});}setPersonProperties(e,n){let r={};e&&(r.$set=e),n&&(r.$set_once=n),this.capture(l.set,{properties:r});}setPersonTraits(e){let n=te(e);Object.keys(n).length!==0&&this.capture(l.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(),i=r.flags.find(p=>p.key===e),s=await this.localContext(n,r.flags),a=i?Z(i,r.flags,s):null,c=i?F(i,r.flags,s).enabled:false;return this.recordExposure(e,a?.key??String(c)),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(l.featureFlagCalled,{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 Fe(n.flags,await this.localContext(e,n.flags))}async isFeatureEnabledLocal(e,n={}){let r=await this.flagSnapshot(),i=r.flags.find(c=>c.key===e),s=await this.localContext(n,r.flags),a=i?F(i,r.flags,s).enabled:false;return this.recordExposure(e,(i?Z(i,r.flags,s)?.key:void 0)??String(a)),a}async localContext(e,n){let r=this.identity.getDistinctId(),i=e.cohorts;if(i===void 0&&Le(n)){let s=this.config.clock.now().getTime();this.membershipCache&&this.membershipCache.distinctId===r&&s-this.membershipCache.fetchedAt<Ve?i=this.membershipCache.cohorts:(i=await this.flagsClient.memberships(r),this.membershipCache={cohorts:i,distinctId:r,fetchedAt:s});}return {attributes:e.attributes,cohorts:i,distinctId:r,properties:e.properties}}async flagSnapshot(){let e=this.config.clock.now().getTime();if(this.cachedSnapshot&&e-this.cachedSnapshot.fetchedAt<Ve)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 L({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(Ct);try{await this.transport.send({body:{events:e,sent_at:T(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.session?.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}.${wt}`}};function je(){return globalThis.location}function He(){return globalThis.document}function Tt(){return globalThis.window??globalThis}function At(t){return typeof t=="object"&&t!==null&&typeof t.tagName=="string"}function Ue(){let t=je(),e=He(),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 _t(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 Nt(t){let e=globalThis.history,n=Tt(),r="",i=()=>{let c=je(),p=c?`${c.pathname}${c.search}`:"";p!==r&&(r=p,t.capture(l.pageview,{properties:Ue()}));};if(i(),!e||!n)return ()=>{};let s=e.pushState.bind(e),a=e.replaceState.bind(e);return e.pushState=(...c)=>{s(...c),i();},e.replaceState=(...c)=>{a(...c),i();},n.addEventListener("popstate",i),()=>{e.pushState=s,e.replaceState=a,n.removeEventListener("popstate",i);}}function Ft(t){let e=He();if(!e)return ()=>{};let n=r=>{let i=r.target;At(i)&&t.capture(l.autocapture,{properties:{...Ue(),..._t(i)}});};return e.addEventListener("click",n,true),()=>e.removeEventListener("click",n,true)}function Je(t,e={}){let n=[];return (e.pageviews??true)&&n.push(Nt(t)),(e.clicks??true)&&n.push(Ft(t)),()=>{for(let r of n)r();}}function Lt(){return globalThis.document?.visibilityState==="hidden"}function Pt(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 i=new n([r],{type:"application/json"});return e.sendBeacon(t.url,i)}catch{return false}}var K=class{constructor(e={}){o(this,"fetchTransport");this.fetchTransport=new x(e);}async send(e){Lt()&&Pt(e)||await this.fetchTransport.send(e);}};var Rt=/^\d{1,3}(\.\d{1,3}){3}$/,Ot=/^[a-z0-9.-]+$/i;function Be(){return Math.random().toString(36).slice(2,12)}function V(t,e){let n=`${e}=`,r=[];for(let i of t.cookie.split(";")){let s=i.trim();s.startsWith(n)&&r.push(s.slice(n.length));}return r}function I(t,e,n){let r=["Path=/",`Max-Age=${e}`,"SameSite=Lax"];return t&&r.push(`Domain=${t}`),n&&r.push("Secure"),r.join("; ")}function ze(t,e,n,r){try{let i=`pdx_probe_${r()}`,s=r();t.cookie=`${i}=${s}; ${I(e,60,n)}`;let a=V(t,i).includes(s);t.cookie=`${i}=; ${I(e,0,n)}`;let c=V(t,i).includes(s);return a&&!c}catch{return false}}function re(t){let e=t.replace(/^\[|\]$/g,"").toLowerCase();if(e.includes(":")||Rt.test(e)||!e.includes("."))return [];let n=e.split("."),r=[];for(let i=n.length-2;i>=0;i-=1)r.push(n.slice(i).join("."));return r}function Ge(t,e,n,r=Be){for(let i of re(t))if(ze(e,i,n,r))return i}function $t(t){let e=new Map,n=JSON.parse(decodeURIComponent(t));if(n===null||typeof n!="object"||Array.isArray(n))return e;for(let[r,i]of Object.entries(n))typeof i=="string"&&e.set(r,i);return e}var ne=class{constructor(e,n,r,i){this.jar=e;this.name=n;this.domain=r;this.secure=i;}getItem(e){return this.read().get(e)??null}setItem(e,n){let r=this.read();r.set(e,n),this.write(r);}removeItem(e){let n=this.read();n.delete(e)&&this.write(n);}read(){try{let e=V(this.jar,this.name);e.length>1&&this.domain&&(this.jar.cookie=`${this.name}=; ${I(void 0,0,this.secure)}`,e=V(this.jar,this.name));let n=e[0];return n?$t(n):new Map}catch{return new Map}}write(e){try{if(e.size===0){this.jar.cookie=`${this.name}=; ${I(this.domain,0,this.secure)}`;return}let n=encodeURIComponent(JSON.stringify(Object.fromEntries(e)));this.jar.cookie=`${this.name}=${n}; ${I(this.domain,31536e3,this.secure)}`;}catch{return}}};function Mt(){return globalThis.document}function Dt(){return globalThis.location?.hostname??""}function qt(){return globalThis.location?.protocol==="https:"}function Kt(t){if(t===void 0)return;let e=t.startsWith(".")?t.slice(1):t;return Ot.test(e)?e.toLowerCase():void 0}function ie(t){let e="jar"in t?t.jar:Mt();if(!e||globalThis.navigator?.cookieEnabled===false)return null;let r=t.random??Be,i=t.secure??qt(),s=t.hostname??Dt();try{let a=Kt(t.domain)??Ge(s,e,i,r);return ze(e,a,i,r)?new ne(e,t.name,a,i):null}catch{return null}}var Xe="_pdx",Ye="~",Vt=200,jt=/^\d+$/;function Ze(t,e,n,r){let i=Ut(t.href);if(i===void 0||oe(i.search).some(ae))return;let s=We(i.hostname,n);s===void 0||s===We(r,n)||(i.search=`${i.search}${i.search?"&":"?"}${Xe}=${Ht(e)}`,t.href=i.href);}function Ht(t){return [t.anonymousId,t.sessionId,String(t.sessionStartedAt)].map(Bt).join(Ye)}function et(t){let e=oe(t).find(ae);if(e===void 0)return;let n=Jt(e).split(Ye);if(n.length!==3)return;let r=j(n[0]),i=j(n[1]),s=j(n[2]);if(!(!Qe(r)||!Qe(i)||!zt(s)))return {anonymousId:r,sessionId:i,sessionStartedAt:Number(s)}}function tt(t,e){let n=oe(e.search),r=n.filter(s=>!ae(s));if(r.length===n.length)return;let i=r.length>0?`?${r.join("&")}`:"";t.replaceState(t.state,"",`${e.pathname}${i}${e.hash}`);}function nt(t){if(t.location===void 0||typeof t.location.search!="string")return;let e=et(t.location.search);if(e===void 0)return;let n=Me(t.storage,t.shared,t.namespace,e.anonymousId);return qe(t.shared,t.namespace,{id:e.sessionId,startedAt:e.sessionStartedAt},t.now),t.history!==void 0&&tt(t.history,t.location),n}function se(t,e,n){if(n.length===0)return ()=>{};let r=i=>{let s=Qt(i.target);if(s===void 0)return;let a=Gt(e);a!==void 0&&Ze(s,a,n,t.location?.hostname??"");};return t.addEventListener("click",r,true),t.addEventListener("auxclick",r,true),()=>{t.removeEventListener("click",r,true),t.removeEventListener("auxclick",r,true);}}function Ut(t){try{let e=new URL(t);return e.protocol==="http:"||e.protocol==="https:"?e:void 0}catch{return}}function We(t,e){let n=e.map(r=>r.replace(/^\./,"").toLowerCase());return re(t).find(r=>n.includes(r))}function oe(t){return t.replace(/^\?/,"").split("&").filter(e=>e!=="")}function ae(t){let e=t.indexOf("=");return j(e===-1?t:t.slice(0,e))===Xe}function Jt(t){let e=t.indexOf("=");return e===-1?"":t.slice(e+1)}function Bt(t){return encodeURIComponent(t).replace(/~/g,"%7E")}function j(t){try{return decodeURIComponent(t)}catch{return}}function Qe(t){if(t===void 0)return false;let e=A(t);return e>=1&&e<=Vt}function zt(t){return t!==void 0&&jt.test(t)&&Number.isSafeInteger(Number(t))}function Gt(t){if(t.consent?.()?.identityLink===false)return;let e=t.sessionId,n=t.sessionStartedAt;if(!(e===void 0||n===void 0))return {anonymousId:t.anonymousId,sessionId:e,sessionStartedAt:n}}function Wt(t){return typeof t.tagName=="string"&&t.tagName.toUpperCase()==="A"&&typeof t.href=="string"}function Qt(t){let e=typeof t=="object"?t:null;for(;e;){if(Wt(e))return e;e=e.parentElement??null;}}var rt={maskAllInputs:true,maskAllText:false},Xt=new Set(["email","password","tel"]);function it(t){return t.replace(/\S/g,"*")}function H(t,e,n){return Yt(e)||n.maskAllInputs?it(t):t}function U(t,e){return e.maskAllText?it(t):t}function Yt(t){return Xt.has((t??"").toLowerCase())}var Zt=5e3,J=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),Zt);}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 ce=1,de=3,en=9,B=class{constructor(){o(this,"next",1);}allocate(){let e=this.next;return this.next+=1,e}},tn=new Set(["NOSCRIPT","SCRIPT"]);function z(t,e,n,r){if(t.nodeType===de){let i=e.allocate();return r?.(t,i),{id:i,textContent:U(t.textValue??"",n),type:"text"}}if(t.nodeType===en){let i=e.allocate();return r?.(t,i),{childNodes:st(t,e,n,r),id:i,type:"document"}}if(t.nodeType===ce){let i=t.tagName??"";if(tn.has(i))return null;let s=e.allocate();return r?.(t,s),{attributes:nn(t,n),childNodes:st(t,e,n,r),id:s,tagName:i,type:"element"}}return null}function st(t,e,n,r){let i=[];for(let s of t.childNodes??[]){let a=z(s,e,n,r);a&&i.push(a);}return i}function nn(t,e){let n={};for(let r of t.attributes??[])n[r.name]=r.value;return t.inputValue!==void 0&&(n.value=H(t.inputValue,t.inputType,e)),n}async function ot(t,e){let n=`${u(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 at=new Set(["INPUT","SELECT","TEXTAREA"]),G=class{constructor(e){this.options=e;o(this,"allocator",new B);o(this,"mirror",new Map);o(this,"chunker");o(this,"fetchImpl");o(this,"observer");o(this,"timer");o(this,"started",false);this.chunker=new J({distinctId:e.distinctId,masked:e.mask.maskAllInputs,maxEvents:e.maxEvents,now:e.now,sessionId:e.sessionId}),this.fetchImpl=h(e.fetch);}start(){if(this.started)return;let e=rn(),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=z(this.adapt(e),this.allocator,this.options.mask,(r,i)=>{let s=r.ref;s&&this.mirror.set(s,i);});n&&this.push(2,{node:n});}observeMutations(e){let n=globalThis.MutationObserver;n&&(this.observer=new n(r=>{for(let i of r)this.handleMutation(i);}),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:U(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 i=z(this.adapt(r),this.allocator,this.options.mask,(s,a)=>{let c=s.ref;c&&this.mirror.set(c,a);});i&&this.push(3,{adds:[{node:i,parentId:n}]});}for(let r of Array.from(e.removedNodes)){let i=this.mirror.get(r);i!==void 0&&(this.push(3,{removes:[{id:i,parentId:n}]}),this.mirror.delete(r));}}}observeInteractions(e){e.addEventListener("input",n=>{let r=n.target;if(!r||!at.has(r.tagName))return;let i=this.mirror.get(r);i!==void 0&&this.push(3,{input:{id:i,value:H(r.value??"",r.type,this.options.mask)}});},true),e.addEventListener("scroll",n=>{let r=n.target,i=r?this.mirror.get(r):void 0;this.push(3,{scroll:{id:i??0,x:r?.scrollLeft??0,y:r?.scrollTop??0}});},true);}adapt(e){let n={childNodes:[],nodeType:e.nodeType,ref:e};if(e.nodeType===de)return n.textValue=e.textContent??"",n;if(e.nodeType===ce){let r=e;if(n.tagName=r.tagName,n.attributes=Array.from(r.attributes).map(i=>({name:i.name,value:i.value})),at.has(r.tagName)){let i=r;n.inputType=i.type,n.inputValue=i.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||ot(e,{apiKey:this.options.apiKey,fetch:this.fetchImpl,replayHost:this.options.replayHost}).catch(n=>this.options.onError?.(n));}};function rn(){return globalThis.document}function ct(t){let e=new G({apiKey:t.apiKey,distinctId:t.distinctId,flushIntervalMs:t.flushIntervalMs??5e3,mask:{...rt,...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 sn(){return globalThis.navigator}function on(){return globalThis.document}function an(){return globalThis.history}function cn(){return globalThis.location}function dn(t){let e=t?.userAgentData?.platform??t?.platform;return e?e.slice(0,50):void 0}function ln(t){let e=()=>{t.flush();};globalThis.document?.addEventListener?.("visibilitychange",e),globalThis.addEventListener?.("pagehide",e);}function un(t,e,n){try{return ie({domain:e,name:`pdx_${_(t)}`})??n}catch{return n}}function ci(t){let{autocaptureOptions:e,cookieDomain:n,linkedDomains:r,replayHost:i,sessionReplay:s,sessionReplayOptions:a,...c}=t,p=sn(),le=ge(),ue=c.storage??le,pe=c.sharedStorage??un(c.apiKey,n,le),he=nt({history:an(),location:cn(),namespace:_(c.apiKey),now:(c.clock??C).now().getTime(),shared:pe,storage:ue}),W={...c,locale:c.locale??(p?.language?p.language.slice(0,20):void 0),os:c.os??dn(p),sessionTracking:c.sessionTracking??true,sharedStorage:pe,storage:ue,transport:c.transport??new K({maxRetries:c.maxRetries,requestTimeoutMs:c.requestTimeoutMs})},m=new q(W);he!==void 0&&m.alias(he),ln(m),(t.autocapture??true)&&Je(m,e);let fe=on();return fe&&r&&se(fe,m,r),s&&i&&ct({apiKey:W.apiKey,distinctId:()=>m.distinctId,onError:W.onError,replayHost:i,...a,sessionId:a?.sessionId??m.sessionId}),m}exports.WebTransport=K;exports.createCookieStorage=ie;exports.createWebClient=ci;exports.decorateLink=Ze;exports.installAutocapture=Je;exports.installLinkCarry=se;exports.installSessionReplay=ct;exports.readCarry=et;exports.resolveCookieDomain=Ge;exports.stripCarry=tt;//# sourceMappingURL=web.cjs.map
2
2
  //# sourceMappingURL=web.cjs.map
package/dist/web.js CHANGED
@@ -1,2 +1,2 @@
1
- import {x as x$1,i,h as h$1,f as f$1,g as g$1,l as l$1,y as y$1,u,w as w$1}from'./chunk-5CBVQAZ2.js';import'./chunk-V77KYPOF.js';import {a as a$1,d}from'./chunk-VG77TYVX.js';import {a}from'./chunk-5XGN7UAV.js';function B(){return globalThis.location}function q(){return globalThis.document}function me(){return globalThis.window??globalThis}function he(t){return typeof t=="object"&&t!==null&&typeof t.tagName=="string"}function X(){let t=B(),e=q(),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 ge(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 ye(t){let e=globalThis.history,n=me(),r="",i=()=>{let s=B(),c=s?`${s.pathname}${s.search}`:"";c!==r&&(r=c,t.capture("$pageview",{properties:X()}));};if(i(),!e||!n)return ()=>{};let o=e.pushState.bind(e),a=e.replaceState.bind(e);return e.pushState=(...s)=>{o(...s),i();},e.replaceState=(...s)=>{a(...s),i();},n.addEventListener("popstate",i),()=>{e.pushState=o,e.replaceState=a,n.removeEventListener("popstate",i);}}function ke(t){let e=q();if(!e)return ()=>{};let n=r=>{let i=r.target;he(i)&&t.capture("$autocapture",{properties:{...X(),...ge(i)}});};return e.addEventListener("click",n,true),()=>e.removeEventListener("click",n,true)}function G(t,e={}){let n=[];return (e.pageviews??true)&&n.push(ye(t)),(e.clicks??true)&&n.push(ke(t)),()=>{for(let r of n)r();}}function ve(){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 i=new n([r],{type:"application/json"});return e.sendBeacon(t.url,i)}catch{return false}}var f=class{constructor(e={}){a(this,"fetchTransport");this.fetchTransport=new x$1(e);}async send(e){ve()&&be(e)||await this.fetchTransport.send(e);}};var xe=/^\d{1,3}(\.\d{1,3}){3}$/,Le=/^[a-z0-9.-]+$/i;function Y(){return Math.random().toString(36).slice(2,12)}function m(t,e){let n=`${e}=`,r=[];for(let i of t.cookie.split(";")){let o=i.trim();o.startsWith(n)&&r.push(o.slice(n.length));}return r}function l(t,e,n){let r=["Path=/",`Max-Age=${e}`,"SameSite=Lax"];return t&&r.push(`Domain=${t}`),n&&r.push("Secure"),r.join("; ")}function Q(t,e,n,r){try{let i=`pdx_probe_${r()}`,o=r();t.cookie=`${i}=${o}; ${l(e,60,n)}`;let a=m(t,i).includes(o);t.cookie=`${i}=; ${l(e,0,n)}`;let s=m(t,i).includes(o);return a&&!s}catch{return false}}function C(t){let e=t.replace(/^\[|\]$/g,"").toLowerCase();if(e.includes(":")||xe.test(e)||!e.includes("."))return [];let n=e.split("."),r=[];for(let i=n.length-2;i>=0;i-=1)r.push(n.slice(i).join("."));return r}function Z(t,e,n,r=Y){for(let i of C(t))if(Q(e,i,n,r))return i}function Ee(t){let e=new Map,n=JSON.parse(decodeURIComponent(t));if(n===null||typeof n!="object"||Array.isArray(n))return e;for(let[r,i]of Object.entries(n))typeof i=="string"&&e.set(r,i);return e}var S=class{constructor(e,n,r,i){this.jar=e;this.name=n;this.domain=r;this.secure=i;}getItem(e){return this.read().get(e)??null}setItem(e,n){let r=this.read();r.set(e,n),this.write(r);}removeItem(e){let n=this.read();n.delete(e)&&this.write(n);}read(){try{let e=m(this.jar,this.name);e.length>1&&this.domain&&(this.jar.cookie=`${this.name}=; ${l(void 0,0,this.secure)}`,e=m(this.jar,this.name));let n=e[0];return n?Ee(n):new Map}catch{return new Map}}write(e){try{if(e.size===0){this.jar.cookie=`${this.name}=; ${l(this.domain,0,this.secure)}`;return}let n=encodeURIComponent(JSON.stringify(Object.fromEntries(e)));this.jar.cookie=`${this.name}=${n}; ${l(this.domain,31536e3,this.secure)}`;}catch{return}}};function Se(){return globalThis.document}function Ce(){return globalThis.location?.hostname??""}function we(){return globalThis.location?.protocol==="https:"}function Te(t){if(t===void 0)return;let e=t.startsWith(".")?t.slice(1):t;return Le.test(e)?e.toLowerCase():void 0}function w(t){let e="jar"in t?t.jar:Se();if(!e||globalThis.navigator?.cookieEnabled===false)return null;let r=t.random??Y,i=t.secure??we(),o=t.hostname??Ce();try{let a=Te(t.domain)??Z(o,e,i,r);return Q(e,a,i,r)?new S(e,t.name,a,i):null}catch{return null}}var ne="_pdx",re="~",Ae=200,Ne=/^\d+$/;function ie(t,e,n,r){let i=Oe(t.href);if(i===void 0||A(i.search).some(N))return;let o=ee(i.hostname,n);o===void 0||o===ee(r,n)||(i.search=`${i.search}${i.search?"&":"?"}${ne}=${Ie(e)}`,t.href=i.href);}function Ie(t){return [t.anonymousId,t.sessionId,String(t.sessionStartedAt)].map(Pe).join(re)}function oe(t){let e=A(t).find(N);if(e===void 0)return;let n=Re(e).split(re);if(n.length!==3)return;let r=h(n[0]),i=h(n[1]),o=h(n[2]);if(!(!te(r)||!te(i)||!Me(o)))return {anonymousId:r,sessionId:i,sessionStartedAt:Number(o)}}function se(t,e){let n=A(e.search),r=n.filter(o=>!N(o));if(r.length===n.length)return;let i=r.length>0?`?${r.join("&")}`:"";t.replaceState(t.state,"",`${e.pathname}${i}${e.hash}`);}function ae(t){if(t.location===void 0||typeof t.location.search!="string")return;let e=oe(t.location.search);if(e===void 0)return;let n=u(t.storage,t.shared,t.namespace,e.anonymousId);return w$1(t.shared,t.namespace,{id:e.sessionId,startedAt:e.sessionStartedAt},t.now),t.history!==void 0&&se(t.history,t.location),n}function T(t,e,n){if(n.length===0)return ()=>{};let r=i=>{let o=De(i.target);if(o===void 0)return;let a=_e(e);a!==void 0&&ie(o,a,n,t.location?.hostname??"");};return t.addEventListener("click",r,true),t.addEventListener("auxclick",r,true),()=>{t.removeEventListener("click",r,true),t.removeEventListener("auxclick",r,true);}}function Oe(t){try{let e=new URL(t);return e.protocol==="http:"||e.protocol==="https:"?e:void 0}catch{return}}function ee(t,e){let n=e.map(r=>r.replace(/^\./,"").toLowerCase());return C(t).find(r=>n.includes(r))}function A(t){return t.replace(/^\?/,"").split("&").filter(e=>e!=="")}function N(t){let e=t.indexOf("=");return h(e===-1?t:t.slice(0,e))===ne}function Re(t){let e=t.indexOf("=");return e===-1?"":t.slice(e+1)}function Pe(t){return encodeURIComponent(t).replace(/~/g,"%7E")}function h(t){try{return decodeURIComponent(t)}catch{return}}function te(t){if(t===void 0)return false;let e=i(t);return e>=1&&e<=Ae}function Me(t){return t!==void 0&&Ne.test(t)&&Number.isSafeInteger(Number(t))}function _e(t){if(t.consent?.()?.identityLink===false)return;let e=t.sessionId,n=t.sessionStartedAt;if(!(e===void 0||n===void 0))return {anonymousId:t.anonymousId,sessionId:e,sessionStartedAt:n}}function $e(t){return typeof t.tagName=="string"&&t.tagName.toUpperCase()==="A"&&typeof t.href=="string"}function De(t){let e=typeof t=="object"?t:null;for(;e;){if($e(e))return e;e=e.parentElement??null;}}var ue={maskAllInputs:true,maskAllText:false},He=new Set(["email","password","tel"]);function de(t){return t.replace(/\S/g,"*")}function g(t,e,n){return je(e)||n.maskAllInputs?de(t):t}function y(t,e){return e.maskAllText?de(t):t}function je(t){return He.has((t??"").toLowerCase())}var Ve=5e3,k=class{constructor(e){this.options=e;a(this,"buffer",[]);a(this,"seq",0);a(this,"maxEvents");this.maxEvents=Math.min(Math.max(1,e.maxEvents),Ve);}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 I=1,O=3,Ke=9,v=class{constructor(){a(this,"next",1);}allocate(){let e=this.next;return this.next+=1,e}},Fe=new Set(["NOSCRIPT","SCRIPT"]);function b(t,e,n,r){if(t.nodeType===O){let i=e.allocate();return r?.(t,i),{id:i,textContent:y(t.textValue??"",n),type:"text"}}if(t.nodeType===Ke){let i=e.allocate();return r?.(t,i),{childNodes:ce(t,e,n,r),id:i,type:"document"}}if(t.nodeType===I){let i=t.tagName??"";if(Fe.has(i))return null;let o=e.allocate();return r?.(t,o),{attributes:Ue(t,n),childNodes:ce(t,e,n,r),id:o,tagName:i,type:"element"}}return null}function ce(t,e,n,r){let i=[];for(let o of t.childNodes??[]){let a=b(o,e,n,r);a&&i.push(a);}return i}function Ue(t,e){let n={};for(let r of t.attributes??[])n[r.name]=r.value;return t.inputValue!==void 0&&(n.value=g(t.inputValue,t.inputType,e)),n}async function le(t,e){let n=`${d(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 pe=new Set(["INPUT","SELECT","TEXTAREA"]),x=class{constructor(e){this.options=e;a(this,"allocator",new v);a(this,"mirror",new Map);a(this,"chunker");a(this,"fetchImpl");a(this,"observer");a(this,"timer");a(this,"started",false);this.chunker=new k({distinctId:e.distinctId,masked:e.mask.maskAllInputs,maxEvents:e.maxEvents,now:e.now,sessionId:e.sessionId}),this.fetchImpl=a$1(e.fetch);}start(){if(this.started)return;let e=Je(),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=b(this.adapt(e),this.allocator,this.options.mask,(r,i)=>{let o=r.ref;o&&this.mirror.set(o,i);});n&&this.push(2,{node:n});}observeMutations(e){let n=globalThis.MutationObserver;n&&(this.observer=new n(r=>{for(let i of r)this.handleMutation(i);}),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:y(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 i=b(this.adapt(r),this.allocator,this.options.mask,(o,a)=>{let s=o.ref;s&&this.mirror.set(s,a);});i&&this.push(3,{adds:[{node:i,parentId:n}]});}for(let r of Array.from(e.removedNodes)){let i=this.mirror.get(r);i!==void 0&&(this.push(3,{removes:[{id:i,parentId:n}]}),this.mirror.delete(r));}}}observeInteractions(e){e.addEventListener("input",n=>{let r=n.target;if(!r||!pe.has(r.tagName))return;let i=this.mirror.get(r);i!==void 0&&this.push(3,{input:{id:i,value:g(r.value??"",r.type,this.options.mask)}});},true),e.addEventListener("scroll",n=>{let r=n.target,i=r?this.mirror.get(r):void 0;this.push(3,{scroll:{id:i??0,x:r?.scrollLeft??0,y:r?.scrollTop??0}});},true);}adapt(e){let n={childNodes:[],nodeType:e.nodeType,ref:e};if(e.nodeType===O)return n.textValue=e.textContent??"",n;if(e.nodeType===I){let r=e;if(n.tagName=r.tagName,n.attributes=Array.from(r.attributes).map(i=>({name:i.name,value:i.value})),pe.has(r.tagName)){let i=r;n.inputType=i.type,n.inputValue=i.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||le(e,{apiKey:this.options.apiKey,fetch:this.fetchImpl,replayHost:this.options.replayHost}).catch(n=>this.options.onError?.(n));}};function Je(){return globalThis.document}function fe(t){let e=new x({apiKey:t.apiKey,distinctId:t.distinctId,flushIntervalMs:t.flushIntervalMs??5e3,mask:{...ue,...t.mask},maxEvents:t.maxEvents??200,now:t.now??(()=>Date.now()),onError:t.onError,replayHost:t.replayHost,sessionId:t.sessionId??h$1()});return e.start(),e}function We(){return globalThis.navigator}function ze(){return globalThis.document}function Be(){return globalThis.history}function qe(){return globalThis.location}function Xe(t){let e=t?.userAgentData?.platform??t?.platform;return e?e.slice(0,50):void 0}function Ge(t){let e=()=>{t.flush();};globalThis.document?.addEventListener?.("visibilitychange",e),globalThis.addEventListener?.("pagehide",e);}function Ye(t,e,n){try{return w({domain:e,name:`pdx_${l$1(t)}`})??n}catch{return n}}function Ht(t){let{autocaptureOptions:e,cookieDomain:n,linkedDomains:r,replayHost:i,sessionReplay:o,sessionReplayOptions:a,...s}=t,c=We(),R=f$1(),P=s.storage??R,M=s.sharedStorage??Ye(s.apiKey,n,R),_=ae({history:Be(),location:qe(),namespace:l$1(s.apiKey),now:(s.clock??g$1).now().getTime(),shared:M,storage:P}),L={...s,locale:s.locale??(c?.language?c.language.slice(0,20):void 0),os:s.os??Xe(c),sessionTracking:s.sessionTracking??true,sharedStorage:M,storage:P,transport:s.transport??new f({maxRetries:s.maxRetries,requestTimeoutMs:s.requestTimeoutMs})},d=new y$1(L);_!==void 0&&d.alias(_),Ge(d),(t.autocapture??true)&&G(d,e);let $=ze();return $&&r&&T($,d,r),o&&i&&fe({apiKey:L.apiKey,distinctId:()=>d.distinctId,onError:L.onError,replayHost:i,...a,sessionId:a?.sessionId??d.sessionId}),d}export{f as WebTransport,w as createCookieStorage,Ht as createWebClient,ie as decorateLink,G as installAutocapture,T as installLinkCarry,fe as installSessionReplay,oe as readCarry,Z as resolveCookieDomain,se as stripCarry};//# sourceMappingURL=web.js.map
1
+ import {B,i,h as h$1,f as f$1,g as g$1,l as l$1,C as C$1,u,w as w$1,x as x$1}from'./chunk-ESOQKMEE.js';import'./chunk-V77KYPOF.js';import {a as a$1,d}from'./chunk-VG77TYVX.js';import {a}from'./chunk-5XGN7UAV.js';function q(){return globalThis.location}function X(){return globalThis.document}function he(){return globalThis.window??globalThis}function ge(t){return typeof t=="object"&&t!==null&&typeof t.tagName=="string"}function G(){let t=q(),e=X(),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 ye(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 ke(t){let e=globalThis.history,n=he(),r="",i=()=>{let s=q(),c=s?`${s.pathname}${s.search}`:"";c!==r&&(r=c,t.capture(x$1.pageview,{properties:G()}));};if(i(),!e||!n)return ()=>{};let o=e.pushState.bind(e),a=e.replaceState.bind(e);return e.pushState=(...s)=>{o(...s),i();},e.replaceState=(...s)=>{a(...s),i();},n.addEventListener("popstate",i),()=>{e.pushState=o,e.replaceState=a,n.removeEventListener("popstate",i);}}function ve(t){let e=X();if(!e)return ()=>{};let n=r=>{let i=r.target;ge(i)&&t.capture(x$1.autocapture,{properties:{...G(),...ye(i)}});};return e.addEventListener("click",n,true),()=>e.removeEventListener("click",n,true)}function Y(t,e={}){let n=[];return (e.pageviews??true)&&n.push(ke(t)),(e.clicks??true)&&n.push(ve(t)),()=>{for(let r of n)r();}}function be(){return globalThis.document?.visibilityState==="hidden"}function xe(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 i=new n([r],{type:"application/json"});return e.sendBeacon(t.url,i)}catch{return false}}var f=class{constructor(e={}){a(this,"fetchTransport");this.fetchTransport=new B(e);}async send(e){be()&&xe(e)||await this.fetchTransport.send(e);}};var Le=/^\d{1,3}(\.\d{1,3}){3}$/,Ee=/^[a-z0-9.-]+$/i;function Q(){return Math.random().toString(36).slice(2,12)}function m(t,e){let n=`${e}=`,r=[];for(let i of t.cookie.split(";")){let o=i.trim();o.startsWith(n)&&r.push(o.slice(n.length));}return r}function l(t,e,n){let r=["Path=/",`Max-Age=${e}`,"SameSite=Lax"];return t&&r.push(`Domain=${t}`),n&&r.push("Secure"),r.join("; ")}function Z(t,e,n,r){try{let i=`pdx_probe_${r()}`,o=r();t.cookie=`${i}=${o}; ${l(e,60,n)}`;let a=m(t,i).includes(o);t.cookie=`${i}=; ${l(e,0,n)}`;let s=m(t,i).includes(o);return a&&!s}catch{return false}}function w(t){let e=t.replace(/^\[|\]$/g,"").toLowerCase();if(e.includes(":")||Le.test(e)||!e.includes("."))return [];let n=e.split("."),r=[];for(let i=n.length-2;i>=0;i-=1)r.push(n.slice(i).join("."));return r}function ee(t,e,n,r=Q){for(let i of w(t))if(Z(e,i,n,r))return i}function Se(t){let e=new Map,n=JSON.parse(decodeURIComponent(t));if(n===null||typeof n!="object"||Array.isArray(n))return e;for(let[r,i]of Object.entries(n))typeof i=="string"&&e.set(r,i);return e}var C=class{constructor(e,n,r,i){this.jar=e;this.name=n;this.domain=r;this.secure=i;}getItem(e){return this.read().get(e)??null}setItem(e,n){let r=this.read();r.set(e,n),this.write(r);}removeItem(e){let n=this.read();n.delete(e)&&this.write(n);}read(){try{let e=m(this.jar,this.name);e.length>1&&this.domain&&(this.jar.cookie=`${this.name}=; ${l(void 0,0,this.secure)}`,e=m(this.jar,this.name));let n=e[0];return n?Se(n):new Map}catch{return new Map}}write(e){try{if(e.size===0){this.jar.cookie=`${this.name}=; ${l(this.domain,0,this.secure)}`;return}let n=encodeURIComponent(JSON.stringify(Object.fromEntries(e)));this.jar.cookie=`${this.name}=${n}; ${l(this.domain,31536e3,this.secure)}`;}catch{return}}};function Ce(){return globalThis.document}function we(){return globalThis.location?.hostname??""}function Te(){return globalThis.location?.protocol==="https:"}function Ae(t){if(t===void 0)return;let e=t.startsWith(".")?t.slice(1):t;return Ee.test(e)?e.toLowerCase():void 0}function T(t){let e="jar"in t?t.jar:Ce();if(!e||globalThis.navigator?.cookieEnabled===false)return null;let r=t.random??Q,i=t.secure??Te(),o=t.hostname??we();try{let a=Ae(t.domain)??ee(o,e,i,r);return Z(e,a,i,r)?new C(e,t.name,a,i):null}catch{return null}}var re="_pdx",ie="~",Ne=200,Ie=/^\d+$/;function oe(t,e,n,r){let i=Re(t.href);if(i===void 0||N(i.search).some(I))return;let o=te(i.hostname,n);o===void 0||o===te(r,n)||(i.search=`${i.search}${i.search?"&":"?"}${re}=${Oe(e)}`,t.href=i.href);}function Oe(t){return [t.anonymousId,t.sessionId,String(t.sessionStartedAt)].map(Pe).join(ie)}function se(t){let e=N(t).find(I);if(e===void 0)return;let n=Me(e).split(ie);if(n.length!==3)return;let r=h(n[0]),i=h(n[1]),o=h(n[2]);if(!(!ne(r)||!ne(i)||!_e(o)))return {anonymousId:r,sessionId:i,sessionStartedAt:Number(o)}}function ae(t,e){let n=N(e.search),r=n.filter(o=>!I(o));if(r.length===n.length)return;let i=r.length>0?`?${r.join("&")}`:"";t.replaceState(t.state,"",`${e.pathname}${i}${e.hash}`);}function ue(t){if(t.location===void 0||typeof t.location.search!="string")return;let e=se(t.location.search);if(e===void 0)return;let n=u(t.storage,t.shared,t.namespace,e.anonymousId);return w$1(t.shared,t.namespace,{id:e.sessionId,startedAt:e.sessionStartedAt},t.now),t.history!==void 0&&ae(t.history,t.location),n}function A(t,e,n){if(n.length===0)return ()=>{};let r=i=>{let o=He(i.target);if(o===void 0)return;let a=$e(e);a!==void 0&&oe(o,a,n,t.location?.hostname??"");};return t.addEventListener("click",r,true),t.addEventListener("auxclick",r,true),()=>{t.removeEventListener("click",r,true),t.removeEventListener("auxclick",r,true);}}function Re(t){try{let e=new URL(t);return e.protocol==="http:"||e.protocol==="https:"?e:void 0}catch{return}}function te(t,e){let n=e.map(r=>r.replace(/^\./,"").toLowerCase());return w(t).find(r=>n.includes(r))}function N(t){return t.replace(/^\?/,"").split("&").filter(e=>e!=="")}function I(t){let e=t.indexOf("=");return h(e===-1?t:t.slice(0,e))===re}function Me(t){let e=t.indexOf("=");return e===-1?"":t.slice(e+1)}function Pe(t){return encodeURIComponent(t).replace(/~/g,"%7E")}function h(t){try{return decodeURIComponent(t)}catch{return}}function ne(t){if(t===void 0)return false;let e=i(t);return e>=1&&e<=Ne}function _e(t){return t!==void 0&&Ie.test(t)&&Number.isSafeInteger(Number(t))}function $e(t){if(t.consent?.()?.identityLink===false)return;let e=t.sessionId,n=t.sessionStartedAt;if(!(e===void 0||n===void 0))return {anonymousId:t.anonymousId,sessionId:e,sessionStartedAt:n}}function De(t){return typeof t.tagName=="string"&&t.tagName.toUpperCase()==="A"&&typeof t.href=="string"}function He(t){let e=typeof t=="object"?t:null;for(;e;){if(De(e))return e;e=e.parentElement??null;}}var de={maskAllInputs:true,maskAllText:false},Ve=new Set(["email","password","tel"]);function ce(t){return t.replace(/\S/g,"*")}function g(t,e,n){return je(e)||n.maskAllInputs?ce(t):t}function y(t,e){return e.maskAllText?ce(t):t}function je(t){return Ve.has((t??"").toLowerCase())}var Ke=5e3,k=class{constructor(e){this.options=e;a(this,"buffer",[]);a(this,"seq",0);a(this,"maxEvents");this.maxEvents=Math.min(Math.max(1,e.maxEvents),Ke);}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 O=1,R=3,Fe=9,v=class{constructor(){a(this,"next",1);}allocate(){let e=this.next;return this.next+=1,e}},Ue=new Set(["NOSCRIPT","SCRIPT"]);function b(t,e,n,r){if(t.nodeType===R){let i=e.allocate();return r?.(t,i),{id:i,textContent:y(t.textValue??"",n),type:"text"}}if(t.nodeType===Fe){let i=e.allocate();return r?.(t,i),{childNodes:le(t,e,n,r),id:i,type:"document"}}if(t.nodeType===O){let i=t.tagName??"";if(Ue.has(i))return null;let o=e.allocate();return r?.(t,o),{attributes:Je(t,n),childNodes:le(t,e,n,r),id:o,tagName:i,type:"element"}}return null}function le(t,e,n,r){let i=[];for(let o of t.childNodes??[]){let a=b(o,e,n,r);a&&i.push(a);}return i}function Je(t,e){let n={};for(let r of t.attributes??[])n[r.name]=r.value;return t.inputValue!==void 0&&(n.value=g(t.inputValue,t.inputType,e)),n}async function pe(t,e){let n=`${d(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 fe=new Set(["INPUT","SELECT","TEXTAREA"]),x=class{constructor(e){this.options=e;a(this,"allocator",new v);a(this,"mirror",new Map);a(this,"chunker");a(this,"fetchImpl");a(this,"observer");a(this,"timer");a(this,"started",false);this.chunker=new k({distinctId:e.distinctId,masked:e.mask.maskAllInputs,maxEvents:e.maxEvents,now:e.now,sessionId:e.sessionId}),this.fetchImpl=a$1(e.fetch);}start(){if(this.started)return;let e=We(),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=b(this.adapt(e),this.allocator,this.options.mask,(r,i)=>{let o=r.ref;o&&this.mirror.set(o,i);});n&&this.push(2,{node:n});}observeMutations(e){let n=globalThis.MutationObserver;n&&(this.observer=new n(r=>{for(let i of r)this.handleMutation(i);}),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:y(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 i=b(this.adapt(r),this.allocator,this.options.mask,(o,a)=>{let s=o.ref;s&&this.mirror.set(s,a);});i&&this.push(3,{adds:[{node:i,parentId:n}]});}for(let r of Array.from(e.removedNodes)){let i=this.mirror.get(r);i!==void 0&&(this.push(3,{removes:[{id:i,parentId:n}]}),this.mirror.delete(r));}}}observeInteractions(e){e.addEventListener("input",n=>{let r=n.target;if(!r||!fe.has(r.tagName))return;let i=this.mirror.get(r);i!==void 0&&this.push(3,{input:{id:i,value:g(r.value??"",r.type,this.options.mask)}});},true),e.addEventListener("scroll",n=>{let r=n.target,i=r?this.mirror.get(r):void 0;this.push(3,{scroll:{id:i??0,x:r?.scrollLeft??0,y:r?.scrollTop??0}});},true);}adapt(e){let n={childNodes:[],nodeType:e.nodeType,ref:e};if(e.nodeType===R)return n.textValue=e.textContent??"",n;if(e.nodeType===O){let r=e;if(n.tagName=r.tagName,n.attributes=Array.from(r.attributes).map(i=>({name:i.name,value:i.value})),fe.has(r.tagName)){let i=r;n.inputType=i.type,n.inputValue=i.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||pe(e,{apiKey:this.options.apiKey,fetch:this.fetchImpl,replayHost:this.options.replayHost}).catch(n=>this.options.onError?.(n));}};function We(){return globalThis.document}function me(t){let e=new x({apiKey:t.apiKey,distinctId:t.distinctId,flushIntervalMs:t.flushIntervalMs??5e3,mask:{...de,...t.mask},maxEvents:t.maxEvents??200,now:t.now??(()=>Date.now()),onError:t.onError,replayHost:t.replayHost,sessionId:t.sessionId??h$1()});return e.start(),e}function ze(){return globalThis.navigator}function Be(){return globalThis.document}function qe(){return globalThis.history}function Xe(){return globalThis.location}function Ge(t){let e=t?.userAgentData?.platform??t?.platform;return e?e.slice(0,50):void 0}function Ye(t){let e=()=>{t.flush();};globalThis.document?.addEventListener?.("visibilitychange",e),globalThis.addEventListener?.("pagehide",e);}function Qe(t,e,n){try{return T({domain:e,name:`pdx_${l$1(t)}`})??n}catch{return n}}function jt(t){let{autocaptureOptions:e,cookieDomain:n,linkedDomains:r,replayHost:i,sessionReplay:o,sessionReplayOptions:a,...s}=t,c=ze(),M=f$1(),P=s.storage??M,_=s.sharedStorage??Qe(s.apiKey,n,M),$=ue({history:qe(),location:Xe(),namespace:l$1(s.apiKey),now:(s.clock??g$1).now().getTime(),shared:_,storage:P}),L={...s,locale:s.locale??(c?.language?c.language.slice(0,20):void 0),os:s.os??Ge(c),sessionTracking:s.sessionTracking??true,sharedStorage:_,storage:P,transport:s.transport??new f({maxRetries:s.maxRetries,requestTimeoutMs:s.requestTimeoutMs})},d=new C$1(L);$!==void 0&&d.alias($),Ye(d),(t.autocapture??true)&&Y(d,e);let D=Be();return D&&r&&A(D,d,r),o&&i&&me({apiKey:L.apiKey,distinctId:()=>d.distinctId,onError:L.onError,replayHost:i,...a,sessionId:a?.sessionId??d.sessionId}),d}export{f as WebTransport,T as createCookieStorage,jt as createWebClient,oe as decorateLink,Y as installAutocapture,A as installLinkCarry,me as installSessionReplay,se as readCarry,ee as resolveCookieDomain,ae as stripCarry};//# sourceMappingURL=web.js.map
2
2
  //# sourceMappingURL=web.js.map
package/package.json CHANGED
@@ -2,8 +2,8 @@
2
2
  "description": "Prodantix analytics + feature-flag client SDK (isomorphic, zero-dependency)",
3
3
  "devDependencies": {
4
4
  "@bomdisoft/typescript-config": "0.0.0",
5
- "@happy-dom/global-registrator": "^20.11.6",
6
- "@types/bun": "^1.4.0",
5
+ "@happy-dom/global-registrator": "^20.14.0",
6
+ "@types/bun": "^1.4.1",
7
7
  "@types/node": "^26.2.0",
8
8
  "tsup": "8.5.1",
9
9
  "typescript": "^6.0.3"
@@ -63,5 +63,5 @@
63
63
  "sideEffects": false,
64
64
  "type": "module",
65
65
  "types": "./dist/index.d.ts",
66
- "version": "0.2.0"
66
+ "version": "0.3.0-beta.379"
67
67
  }
@@ -1,2 +0,0 @@
1
- import {c as c$2,a as a$2,b as b$2}from'./chunk-V77KYPOF.js';import {a as a$1,d,b as b$1,c as c$1}from'./chunk-VG77TYVX.js';import {a}from'./chunk-5XGN7UAV.js';var h=class extends Error{constructor(t,n,i){super(n,i);a(this,"code");this.code=t,this.name="ProdantixError";}},v=class extends h{constructor(e){super("config",e),this.name="ConfigError";}},m=class extends h{constructor(t,n){super("validation",n);a(this,"field");this.field=t,this.name="ValidationError";}},c=class extends h{constructor(t,n,i){super("transport",t,i);a(this,"status");this.status=n,this.name="TransportError";}};var y=class{constructor(){a(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);}};function _e(){try{let s=globalThis.localStorage;if(s){let e="__pdx_probe__";return s.setItem(e,"1"),s.removeItem(e),s}}catch{return new y}return new y}var D={now:()=>new Date};function S(s){return s.toISOString()}var le=/^pdx_pub_(?:(?:live|test)_)?[a-z0-9]{32}$/;var de=/^(?:\$|[a-z])[a-z0-9_.]*$/;function V(s){let e=0;for(let t of s)e+=1;return e}function j(s){return le.test(s)}function ue(s){return de.test(s)}function U(s){let e=V(s);if(e<1||e>200)throw new m("distinct_id","distinct_id must be between 1 and 200 characters")}function H(s){let e=V(s);if(e<1||e>200)throw new m("event_name","event_name must be between 1 and 200 characters");if(!ue(s))throw new m("event_name","event_name must match /^(\\$|[a-z])[a-z0-9_.]*$/")}var J="prodantix-js",z="0.0.1";function he(){return globalThis.crypto}function pe(s){s[6]=s[6]&15|64,s[8]=s[8]&63|128;let e=[];for(let t=0;t<16;t+=1)e.push(s[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 fe(){let s=he();if(s?.randomUUID)return s.randomUUID();let e=new Uint8Array(16);if(s?.getRandomValues)s.getRandomValues(e);else for(let t=0;t<16;t+=1)e[t]=Math.floor(Math.random()*256);return pe(e)}var Q={uuid:fe};var ge=s=>{};function B(s){if(!s.apiKey||!j(s.apiKey))throw new v("apiKey must be a public project key of the form pdx_pub_<32 lowercase alphanumerics>");if(!s.host)throw new v("host is required (the ingest base URL)");let e=d(s.host),t=s.defaultProperties,n=s.storage??new y;return {apiKey:s.apiKey,autocapture:s.autocapture??false,clock:s.clock??D,consent:s.consent,defaultProperties:typeof t=="function"?t:()=>t??{},flagsHost:s.flagsHost?d(s.flagsHost):e,flushAt:s.flushAt??20,flushIntervalMs:s.flushIntervalMs??1e4,host:e,ids:s.ids??Q,locale:s.locale,maxQueueSize:s.maxQueueSize??1e3,maxRetries:s.maxRetries??3,namespace:me(s.apiKey),onError:s.onError??ge,os:s.os,requestTimeoutMs:s.requestTimeoutMs??1e4,sdkName:s.sdkName??J,sdkVersion:s.sdkVersion??z,sessionTracking:s.sessionTracking??false,sharedStorage:s.sharedStorage??n,socketFactory:s.socketFactory,storage:n,streamFlags:s.streamFlags??false,transport:s.transport}}function me(s){return s.slice(0,16)}var f=Symbol("absent");function ye(s,e){if(s==="distinct_id")return e.distinctId;let t=e.properties??{};if(Object.prototype.hasOwnProperty.call(t,s))return t[s];let n=e.attributes??{};return Object.prototype.hasOwnProperty.call(n,s)?n[s]:f}function p(s){return s===f?"undefined":String(s)}function G(s){return s===f?Number.NaN:Number(s)}function W(s){return s!==f&&s!==null&&s!==""}function X(s,e){if(!Array.isArray(e))return false;let t=p(s);return e.map(n=>String(n)).includes(t)}function Y(s,e){let t=ye(s.attribute,e),n=s.value;switch(s.op){case "is_set":return W(t);case "is_not_set":return !W(t);case "eq":return p(t)===p(n===void 0?f:n);case "neq":return p(t)!==p(n===void 0?f:n);case "contains":return p(t).includes(p(n===void 0?f:n));case "in":return X(t,n);case "not_in":return Array.isArray(n)?!X(t,n):false;case "gt":return I(t,n,(i,r)=>i>r);case "gte":return I(t,n,(i,r)=>i>=r);case "lt":return I(t,n,(i,r)=>i<r);case "lte":return I(t,n,(i,r)=>i<=r);case "in_cohort":return typeof n=="string"&&n!==""&&(e.cohorts??[]).includes(n);case "not_in_cohort":return typeof n=="string"&&n!==""&&!(e.cohorts??[]).includes(n);default:return false}}function I(s,e,t){let n=G(s),i=e===void 0?Number.NaN:G(e);return Number.isNaN(n)||Number.isNaN(i)?false:t(n,i)}function Z(s,e){let t=`${s}:${e}`,n=2166136261;for(let i=0;i<t.length;i++)n^=t.charCodeAt(i),n=Math.imul(n,16777619);return (n>>>0)%100}function R(s,e){return s.targeting.length===0||s.targeting.every(t=>Y(t,e))}function ee(s,e){let t=Z(s.key,e.distinctId),n=s.variations??[];if(n.length===0)return s.rolloutPercentage>=100||t<s.rolloutPercentage?"true":"false";let i=0;for(let r=n.length-1;r>=0;r--)if(i+=n[r].weight,t<i)return n[r].key;return n[0].key}function $(s,e,t,n){for(let i of s.prerequisites??[]){if(n.includes(i.flagKey))return false;let r=e.find(l=>l.key===i.flagKey);if(!r||!r.enabled)return false;n.push(r.key);let a=$(r,e,t,n)&&R(r,t)&&ee(r,t)===i.variationKey;if(n.pop(),!a)return false}return true}function b(s,e,t){return s.enabled?$(s,e,t,[s.key])?R(s,t)?s.rolloutPercentage>=100?{enabled:true,reason:"rollout_full"}:Z(s.key,t.distinctId)<s.rolloutPercentage?{enabled:true,reason:"rollout"}:{enabled:false,reason:"rollout_excluded"}:{enabled:false,reason:"targeting"}:{enabled:false,reason:"prerequisite"}:{enabled:false,reason:"disabled"}}function Qe(s,e){return b(s,[],e)}function te(s,e){let t={};for(let n of s)t[n.key]=b(n,s,e).enabled;return t}function k(s,e,t){let n=s.variations??[],i=n[0];if(!i)return null;if(!s.enabled||!$(s,e,t,[s.key])||!R(s,t))return i;let r=ee(s,t);return n.find(a=>a.key===r)??i}function Be(s,e){return k(s,[],e)}function Ge(s,e,t){let n=s.find(i=>i.key===e);return n?k(n,s,t)?.value??null:null}function se(s){return s.some(e=>e.targeting.some(t=>t.op==="in_cohort"||t.op==="not_in_cohort"))}var F=class{constructor(e){a(this,"fetch");a(this,"host");a(this,"projectKey");a(this,"requestTimeoutMs");this.fetch=a$1(e.fetch),this.host=d(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 n=`${this.host}/v1/flags?distinct_id=${encodeURIComponent(e)}`,i=b$1(),r=i?setTimeout(()=>i.abort(),this.requestTimeoutMs):void 0;try{let a=await t(n,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:i?.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{r!==void 0&&clearTimeout(r);}}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`,n=b$1(),i=n?setTimeout(()=>n.abort(),this.requestTimeoutMs):void 0;try{let r=await e(t,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:n?.signal});if(!r.ok)throw new c(`flag snapshot request failed with status ${r.status}`,r.status);let a=JSON.parse(await r.text()),l={flags:a.flags??[],generatedAt:a.generatedAt};return typeof a.socketUrl=="string"&&a.socketUrl!==""&&(l.socketUrl=a.socketUrl),l}finally{i!==void 0&&clearTimeout(i);}}async memberships(e){let t=this.fetch;if(!t)throw new c("no fetch implementation available in this runtime");let n=`${this.host}/v1/flags/memberships?distinct_id=${encodeURIComponent(e)}`,i=b$1(),r=i?setTimeout(()=>i.abort(),this.requestTimeoutMs):void 0;try{let a=await t(n,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:i?.signal});if(!a.ok)throw new c(`memberships request failed with status ${a.status}`,a.status);return JSON.parse(await a.text()).cohorts??[]}finally{r!==void 0&&clearTimeout(r);}}};function x(s){if(typeof s!="string")return;let e=Array.from(s).length;return e>=1&&e<=200?s:void 0}function E(s,e){return `pdx.${s}.${e}`}var ne="consent";function ve(s){if(typeof s!="string")return null;try{let e=JSON.parse(s);if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e.identityLink;return typeof t=="boolean"?{identityLink:t}:null}catch{return null}}function be(s,e){return ve(s.getItem(E(e,ne)))}function ke(s,e,t){let n=E(e,ne);if(typeof t.identityLink!="boolean"){s.removeItem(n);return}s.setItem(n,JSON.stringify({identityLink:t.identityLink}));}function tt(s,e,t,n){let i=E(t,"anonymous_id"),r=x(e.getItem(i))??x(s.getItem(i));return e.setItem(i,n),s.setItem(i,n),r!==void 0&&r!==n?r:void 0}var w=class{constructor(e,t,n,i){this.storage=e;this.shared=t;this.ids=n;this.namespace=i;a(this,"anonymousId");a(this,"distinctId");a(this,"identified");this.refresh();}refresh(){let e=x(this.shared.getItem(this.key("anonymous_id"))),t=x(this.storage.getItem(this.key("anonymous_id")));e?(this.anonymousId=e,t!==e&&this.storage.setItem(this.key("anonymous_id"),e)):t?(this.anonymousId=t,this.shared.setItem(this.key("anonymous_id"),t)):(this.anonymousId=this.ids.uuid(),this.shared.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.setItem(this.key("anonymous_id"),this.anonymousId));let n=x(this.storage.getItem(this.key("distinct_id")));n?(this.distinctId=n,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}}consent(){return be(this.shared,this.namespace)}setConsent(e){ke(this.shared,this.namespace,e);}identify(e){let t=!this.identified||this.distinctId!==e,n=this.storage.getItem(this.key("linked_anonymous_id")),i=t||n!==this.anonymousId;return this.distinctId=e,this.identified=true,t&&this.storage.setItem(this.key("distinct_id"),e),!i||this.consent()?.identityLink===false?{changed:t}:(this.storage.setItem(this.key("linked_anonymous_id"),this.anonymousId),{anonymousToLink:this.anonymousId,changed:t})}reset(){this.anonymousId=this.ids.uuid(),this.distinctId=this.anonymousId,this.identified=false,this.shared.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.removeItem(this.key("distinct_id")),this.storage.removeItem(this.key("linked_anonymous_id"));}key(e){return E(this.namespace,e)}};var C=class{constructor(e){a(this,"fetch");a(this,"host");a(this,"projectKey");a(this,"requestTimeoutMs");this.fetch=a$1(e.fetch),this.host=d(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async inbox(e){let t=this.requireFetch(),n=`${this.host}/v1/messages?distinct_id=${encodeURIComponent(e)}`,i=await this.request(t,n,{headers:this.authHeaders(),method:"GET"});if(!i.ok)throw new c(`inbox request failed with status ${i.status}`,i.status);return JSON.parse(await i.text()).messages??[]}async markRead(e,t){let n=this.requireFetch(),i=`${this.host}/v1/messages/read`,r=await this.request(n,i,{body:JSON.stringify({distinct_id:t,message_id:e}),headers:{...this.authHeaders(),"content-type":"application/json"},method:"POST"});if(!r.ok)throw new c(`mark-read request failed with status ${r.status}`,r.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,n){let i=b$1(),r=i?setTimeout(()=>i.abort(),this.requestTimeoutMs):void 0;try{return await e(t,{...n,signal:i?.signal})}finally{r!==void 0&&clearTimeout(r);}}};function ie(s){return s>=400&&s<500&&s!==429}var T=class{constructor(e={}){a(this,"fetch");a(this,"maxRetries");a(this,"requestTimeoutMs");a(this,"baseDelayMs");a(this,"maxDelayMs");a(this,"sleep");a(this,"random");this.fetch=a$1(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??c$1,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 n=JSON.stringify(e.body),i;for(let r=0;r<=this.maxRetries;r+=1){try{let a=await this.attempt(t,e,n);if(a.ok)return;if(ie(a.status))throw new c(`ingest rejected batch with status ${a.status}`,a.status);i=new c(`ingest transient status ${a.status}`,a.status);}catch(a){if(a instanceof c&&a.status!==void 0&&ie(a.status))throw a;i=a;}r<this.maxRetries&&await this.sleep(this.backoff(r));}throw new c("ingest delivery failed after retries",void 0,{cause:i})}async attempt(e,t,n){let i=b$1(),r=i?setTimeout(()=>i.abort(),this.requestTimeoutMs):void 0;try{return await e(t.url,{body:n,headers:{authorization:`Bearer ${t.projectKey}`,"content-type":"application/json"},method:"POST",signal:i?.signal})}finally{r!==void 0&&clearTimeout(r);}}backoff(e){return Math.min(this.maxDelayMs,this.baseDelayMs*2**e)+this.random()*this.baseDelayMs}};function re(s,e,t){H(s.eventName),U(s.distinctId);let n={distinct_id:s.distinctId,event_id:s.eventId??t.uuid(),event_name:s.eventName,properties:s.properties??{},schema_version:1,timestamp:S(s.timestamp??e.now())};return s.context&&(n.context=s.context),s.sessionId&&(n.session_id=s.sessionId),n}var xe="/socket.io/?EIO=4&transport=websocket",Se=250,_=class{constructor(e){this.options=e;a(this,"socket",null);a(this,"heartbeat",null);a(this,"pending",null);a(this,"lastKey","");a(this,"ready",false);a(this,"closed",false);a(this,"heartbeatWindow",45e3);a(this,"factory");a(this,"setTimer");a(this,"clearTimer");this.factory=e.socketFactory??Ie,this.setTimer=e.setTimer??((t,n)=>setTimeout(t,n)),this.clearTimer=e.clearTimer??(t=>clearTimeout(t));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${xe}`,t;try{t=this.factory(e);}catch{this.options.onClosed(false);return}this.socket=t,t.onmessage=n=>this.receive(String(n.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=c$2(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),this.socket?.send(a$2({projectKey:this.options.projectKey}));return}if(t.kind==="ping"){this.armHeartbeat(),this.socket?.send(b$2());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 n=t.payload?.key;this.lastKey=typeof n=="string"?n:"",this.pending===null&&(this.pending=this.setTimer(()=>{this.pending=null,this.options.onChange(this.lastKey);},Se));}}}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 Ie(s){let e=globalThis.WebSocket;if(!e)throw new Error("no WebSocket");return new e(s)}var A=class{constructor(e,t){this.maxSize=e;this.onOverflow=t;a(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});}};var Fe={idleMs:18e5,maxMs:864e5,throttleMs:1e4};function oe(s){return `pdx.${s}.session`}function kt(s,e,t,n){let i={id:t.id,lastActivityAt:n,startedAt:t.startedAt};s.setItem(oe(e),JSON.stringify(i));}var P=class{constructor(e,t,n,i,r=Fe){this.storage=e;this.ids=t;this.clock=n;this.namespace=i;this.options=r;}current(){return this.touch().id}startedAt(){return this.touch().startedAt}reset(){this.storage.removeItem(this.key());}touch(){let e=this.clock.now().getTime(),t=this.live(this.read(),e);if(t===void 0)return this.write({id:this.ids.uuid(),lastActivityAt:e,startedAt:e});if(e-t.lastActivityAt<=this.options.throttleMs)return t;let n=this.live(this.read(),e),i=n!==void 0&&n.id!==t.id?n:t;return this.write({...i,lastActivityAt:e})}live(e,t){if(e!==void 0&&!(t-e.lastActivityAt>this.options.idleMs||t-e.startedAt>this.options.maxMs))return e}write(e){return this.storage.setItem(this.key(),JSON.stringify(e)),e}read(){let e=this.storage.getItem(this.key());if(e)try{let t=JSON.parse(e);return typeof t.id=="string"&&typeof t.startedAt=="number"&&typeof t.lastActivityAt=="number"?{id:t.id,lastActivityAt:t.lastActivityAt,startedAt:t.startedAt}:void 0}catch{return}}key(){return oe(this.namespace)}};var we="queue",Ee=1e3,ae=3e4,M=s=>{let e={};return s.avatar!==void 0&&(e.$avatar=s.avatar),s.email!==void 0&&(e.$email=s.email),s.name!==void 0&&(e.$name=s.name),s.phone!==void 0&&(e.$phone=s.phone),e},q=class{constructor(e){a(this,"config");a(this,"identity");a(this,"session");a(this,"queue");a(this,"transport");a(this,"flagsClient");a(this,"messagesClient");a(this,"context");a(this,"flushTimer");a(this,"flushing",false);a(this,"cachedFlags");a(this,"cachedSnapshot");a(this,"membershipCache");a(this,"stream");a(this,"shutDown",false);a(this,"exposures",new Set);this.config=B(e),this.identity=new w(this.config.storage,this.config.sharedStorage,this.config.ids,this.config.namespace),this.config.consent!==void 0&&this.identity.setConsent(this.config.consent),this.session=this.config.sessionTracking?new P(this.config.sharedStorage,this.config.ids,this.config.clock,this.config.namespace):void 0,this.queue=new A(this.config.maxQueueSize,({dropped:t})=>{this.config.onError(new h("queue_overflow",`event queue overflow: dropped ${t.length} oldest event(s)`));}),this.transport=this.config.transport??new T({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()}get isIdentified(){return this.identity.isIdentified()}get sessionId(){return this.session?.current()}get sessionStartedAt(){return this.session?.startedAt()}capture(e,t={}){try{this.identity.refresh();let n={...this.config.defaultProperties(),...t.properties??{}},i=re({context:this.context,distinctId:t.distinctId??this.identity.getDistinctId(),eventName:e,properties:n,sessionId:t.sessionId??this.session?.current(),timestamp:t.timestamp},this.config.clock,this.config.ids);this.enqueue(i);}catch(n){this.config.onError(n);}}identify(e,t={}){this.identity.refresh();let n=this.identity.identify(e),i={};n.anonymousToLink!==void 0&&(i.$anon_distinct_id=n.anonymousToLink);let r={...M(t.traits??{}),...t.set??{}};Object.keys(r).length>0&&(i.$set=r),this.capture("$identify",{properties:i});}link(e,t,n){let i={$anon_distinct_id:t},r=M(n??{});Object.keys(r).length>0&&(i.$set=r),this.capture("$identify",{distinctId:e,properties:i});}setConsent(e){this.identity.setConsent(e);}consent(){return this.identity.consent()}alias(e){this.capture("$create_alias",{properties:{alias:e}});}group(e,t,n){let i={$group_key:t,$group_type:e};n&&(i.$set=n),this.capture("$group",{properties:i});}setPersonProperties(e,t){let n={};e&&(n.$set=e),t&&(n.$set_once=t),this.capture("$set",{properties:n});}setPersonTraits(e){let t=M(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 n=(await this.getAllFlags())[e]??false;return this.recordExposure(e,this.cachedFlags?.variants[e]?.key??String(n)),n}async getVariant(e){let t=await this.getAllFlags(),n=this.cachedFlags?.variants[e]??null;return this.recordExposure(e,n?.key??String(t[e]??false)),n}async getVariantLocal(e,t={}){let n=await this.flagSnapshot(),i=n.flags.find(ce=>ce.key===e),r=await this.localContext(t,n.flags),a=i?k(i,n.flags,r):null,l=i?b(i,n.flags,r).enabled:false;return this.recordExposure(e,a?.key??String(l)),a?{key:a.key,value:a.value}:null}recordExposure(e,t){let n=`${this.identity.getDistinctId()} ${e} ${t}`;this.exposures.has(n)||(this.exposures.add(n),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 te(t.flags,await this.localContext(e,t.flags))}async isFeatureEnabledLocal(e,t={}){let n=await this.flagSnapshot(),i=n.flags.find(l=>l.key===e),r=await this.localContext(t,n.flags),a=i?b(i,n.flags,r).enabled:false;return this.recordExposure(e,(i?k(i,n.flags,r)?.key:void 0)??String(a)),a}async localContext(e,t){let n=this.identity.getDistinctId(),i=e.cohorts;if(i===void 0&&se(t)){let r=this.config.clock.now().getTime();this.membershipCache&&this.membershipCache.distinctId===n&&r-this.membershipCache.fetchedAt<ae?i=this.membershipCache.cohorts:(i=await this.flagsClient.memberships(n),this.membershipCache={cohorts:i,distinctId:n,fetchedAt:r});}return {attributes:e.attributes,cohorts:i,distinctId:n,properties:e.properties}}async flagSnapshot(){let e=this.config.clock.now().getTime();if(this.cachedSnapshot&&e-this.cachedSnapshot.fetchedAt<ae)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 _({host:e.socketUrl,onChange:()=>{this.cachedSnapshot=void 0,this.flagSnapshot().catch(n=>this.config.onError(n));},onClosed:n=>{this.stream=void 0,n&&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(Ee);try{await this.transport.send({body:{events:e,sent_at:S(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.session?.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}.${we}`}};function Mt(s){return new q(s)}export{h as a,v as b,m as c,c as d,y as e,_e as f,D as g,fe as h,V as i,J as j,z as k,me as l,Y as m,Z as n,Qe as o,te as p,Be as q,Ge as r,F as s,ve as t,tt as u,C as v,kt as w,T as x,q as y,Mt as z};//# sourceMappingURL=chunk-5CBVQAZ2.js.map
2
- //# sourceMappingURL=chunk-5CBVQAZ2.js.map