@prodantix/sdk 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/web.cjs CHANGED
@@ -1,2 +1,2 @@
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
1
+ 'use strict';var ut=Object.defineProperty;var pt=(t,e,n)=>e in t?ut(t,e,{enumerable:true,configurable:true,writable:true,value:n}):t[e]=n;var a=(t,e,n)=>pt(t,typeof e!="symbol"?e+"":e,n);var u=class extends Error{constructor(n,r,i){super(r,i);a(this,"code");this.code=n,this.name="ProdantixError";}},x=class extends u{constructor(e){super("config",e),this.name="ConfigError";}},k=class extends u{constructor(n,r){super("validation",r);a(this,"field");this.field=n,this.name="ValidationError";}},d=class extends u{constructor(n,r,i){super("transport",n,i);a(this,"status");this.status=r,this.name="TransportError";}};function f(t){if(t)return t;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function m(){let t=globalThis.AbortController;return t?new t:void 0}var ye=t=>new Promise(e=>{setTimeout(e,t);});function p(t){return t.replace(/\/+$/,"")}var b=class{constructor(){a(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 ve(){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 A(t){return t.toISOString()}function ht(){return globalThis.crypto}function ft(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=ht();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 ft(e)}var ke={uuid:Q};var mt=/^pdx_pub_(?:(?:live|test)_)?[a-z0-9]{32}$/;var gt=/^(?:\$|[a-z])[a-z0-9_.]*$/;function _(t){let e=0;for(let n of t)e+=1;return e}function be(t){return mt.test(t)}function yt(t){return gt.test(t)}function Ee(t){let e=_(t);if(e<1||e>200)throw new k("distinct_id","distinct_id must be between 1 and 200 characters")}function xe(t){let e=_(t);if(e<1||e>200)throw new k("event_name","event_name must be between 1 and 200 characters");if(!yt(t))throw new k("event_name","event_name must match /^(\\$|[a-z])[a-z0-9_.]*$/")}var Se="prodantix-js",we="0.0.1";var vt=t=>{};function Ie(t){if(!t.apiKey||!be(t.apiKey))throw new x("apiKey must be a public project key of the form pdx_pub_<32 lowercase alphanumerics>");if(!t.host)throw new x("host is required (the ingest base URL)");let e=p(t.host),n=t.defaultProperties,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?p(t.flagsHost):e,flushAt:t.flushAt??20,flushIntervalMs:t.flushIntervalMs??1e4,host:e,ids:t.ids??ke,locale:t.locale,maxQueueSize:t.maxQueueSize??1e3,maxRetries:t.maxRetries??3,namespace:F(t.apiKey),onError:t.onError??vt,os:t.os,requestTimeoutMs:t.requestTimeoutMs??1e4,sdkName:t.sdkName??Se,sdkVersion:t.sdkVersion??we,sessionTracking:t.sessionTracking??false,sharedStorage:t.sharedStorage??r,socketFactory:t.socketFactory,storage:r,streamFlags:t.streamFlags??false,transport:t.transport}}function F(t){return t.slice(0,16)}function Te(t,e,n){xe(t.eventName),Ee(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:A(t.timestamp??e.now())};return t.context&&(r.context=t.context),t.sessionId&&(r.session_id=t.sessionId),r}var v=Symbol("absent");function kt(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 Ce(t){return t===v?Number.NaN:Number(t)}function Ae(t){return t!==v&&t!==null&&t!==""}function _e(t,e){if(!Array.isArray(e))return false;let n=y(t);return e.map(r=>String(r)).includes(n)}function Fe(t,e){let n=kt(t.attribute,e),r=t.value;switch(t.op){case "is_set":return Ae(n);case "is_not_set":return !Ae(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 _e(n,r);case "not_in":return Array.isArray(r)?!_e(n,r):false;case "gt":return L(n,r,(i,s)=>i>s);case "gte":return L(n,r,(i,s)=>i>=s);case "lt":return L(n,r,(i,s)=>i<s);case "lte":return L(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 L(t,e,n){let r=Ce(t),i=e===void 0?Number.NaN:Ce(e);return Number.isNaN(r)||Number.isNaN(i)?false:n(r,i)}function Le(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 Y(t,e){return t.targeting.length===0||t.targeting.every(n=>Fe(n,e))}function Ne(t,e){let n=Le(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 o=X(s,e,n,r)&&Y(s,n)&&Ne(s,n)===i.variationKey;if(r.pop(),!o)return false}return true}function N(t,e,n){return t.enabled?X(t,e,n,[t.key])?Y(t,n)?t.rolloutPercentage>=100?{enabled:true,reason:"rollout_full"}:Le(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 Pe(t,e){let n={};for(let r of t)n[r.key]=N(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||!X(t,e,n,[t.key])||!Y(t,n))return i;let s=Ne(t,n);return r.find(o=>o.key===s)??i}function Re(t){return t.some(e=>e.targeting.some(n=>n.op==="in_cohort"||n.op==="not_in_cohort"))}function Oe(t){return `40${JSON.stringify(t)}`}function $e(){return "3"}function Me(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 o=ee(n);return {kind:"open",pingInterval:typeof o?.pingInterval=="number"?o.pingInterval:25e3,pingTimeout:typeof o?.pingTimeout=="number"?o.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 o=ee(i);return {kind:"connectError",message:typeof o?.message=="string"?o.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 bt="/socket.io/?EIO=4&transport=websocket",Et=250,P=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??xt,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(/\/+$/,"")}${bt}`,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=Me(e);if(n.kind==="open"){this.armHeartbeat(n.pingInterval+n.pingTimeout),this.socket?.send(Oe({projectKey:this.options.projectKey}));return}if(n.kind==="ping"){this.armHeartbeat(),this.socket?.send($e());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);},Et));}}}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 xt(t){let e=globalThis.WebSocket;if(!e)throw new d("no WebSocket");return new e(t)}var R=class{constructor(e){a(this,"fetch");a(this,"host");a(this,"projectKey");a(this,"requestTimeoutMs");this.fetch=f(e.fetch),this.host=p(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async fetchAll(e){return (await this.fetchDecisions(e)).flags}async fetchDecisions(e){let n=this.fetch;if(!n)throw new d("no fetch implementation available in this runtime");let r=`${this.host}/v1/flags?distinct_id=${encodeURIComponent(e)}`,i=m(),s=i?setTimeout(()=>i.abort(),this.requestTimeoutMs):void 0;try{let o=await n(r,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:i?.signal});if(!o.ok)throw new d(`flags request failed with status ${o.status}`,o.status);let c=JSON.parse(await o.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=m(),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 o=JSON.parse(await s.text()),c={flags:o.flags??[],generatedAt:o.generatedAt};return typeof o.socketUrl=="string"&&o.socketUrl!==""&&(c.socketUrl=o.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=m(),s=i?setTimeout(()=>i.abort(),this.requestTimeoutMs):void 0;try{let o=await n(r,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:i?.signal});if(!o.ok)throw new d(`memberships request failed with status ${o.status}`,o.status);return JSON.parse(await o.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 $(t,e){return `pdx.${t}.${e}`}var De="consent";function St(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 wt(t,e){return St(t.getItem($(e,De)))}function It(t,e,n){let r=$(e,De);if(typeof n.identityLink!="boolean"){t.removeItem(r);return}t.setItem(r,JSON.stringify({identityLink:n.identityLink}));}function Ke(t,e,n,r){let i=$(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 O=class{constructor(e,n,r,i){this.storage=e;this.shared=n;this.ids=r;this.namespace=i;a(this,"anonymousId");a(this,"distinctId");a(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 wt(this.shared,this.namespace)}setConsent(e){It(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 $(this.namespace,e)}};var M=class{constructor(e){a(this,"fetch");a(this,"host");a(this,"projectKey");a(this,"requestTimeoutMs");this.fetch=f(e.fetch),this.host=p(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async inbox(e){let n=this.requireFetch(),r=`${this.host}/v1/messages?distinct_id=${encodeURIComponent(e)}`,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=m(),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 D=class{constructor(e,n){this.maxSize=e;this.onOverflow=n;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 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 Tt={idleMs:18e5,maxMs:864e5,throttleMs:1e4};function qe(t){return `pdx.${t}.session`}function Ve(t,e,n,r){let i={id:n.id,lastActivityAt:r,startedAt:n.startedAt};t.setItem(qe(e),JSON.stringify(i));}var K=class{constructor(e,n,r,i,s=Tt){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 qe(this.namespace)}};var l={autocapture:"$autocapture",createAlias:"$create_alias",featureFlagCalled:"$feature_flag_called",group:"$group",identify:"$identify",pageview:"$pageview",set:"$set"};function je(t){return t>=400&&t<500&&t!==429}var E=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=f(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??ye,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 o=await this.attempt(n,e,r);if(o.ok)return;if(je(o.status))throw new d(`ingest rejected batch with status ${o.status}`,o.status);i=new d(`ingest transient status ${o.status}`,o.status);}catch(o){if(o instanceof d&&o.status!==void 0&&je(o.status))throw o;i=o;}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=m(),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 Ct="queue",At=1e3,He=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){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=Ie(e),this.identity=new O(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 K(this.config.sharedStorage,this.config.ids,this.config.clock,this.config.namespace):void 0,this.queue=new D(this.config.maxQueueSize,({dropped:n})=>{this.config.onError(new u("queue_overflow",`event queue overflow: dropped ${n.length} oldest event(s)`));}),this.transport=this.config.transport??new E({maxRetries:this.config.maxRetries,requestTimeoutMs:this.config.requestTimeoutMs}),this.flagsClient=new R({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.messagesClient=new M({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=Te({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(h=>h.key===e),s=await this.localContext(n,r.flags),o=i?Z(i,r.flags,s):null,c=i?N(i,r.flags,s).enabled:false;return this.recordExposure(e,o?.key??String(c)),o?{key:o.key,value:o.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 Pe(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),o=i?N(i,r.flags,s).enabled:false;return this.recordExposure(e,(i?Z(i,r.flags,s)?.key:void 0)??String(o)),o}async localContext(e,n){let r=this.identity.getDistinctId(),i=e.cohorts;if(i===void 0&&Re(n)){let s=this.config.clock.now().getTime();this.membershipCache&&this.membershipCache.distinctId===r&&s-this.membershipCache.fetchedAt<He?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<He)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 P({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(At);try{await this.transport.send({body:{events:e,sent_at:A(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}.${Ct}`}};var _t="data-pdx-no-capture",Ft="pdx-no-capture",Lt=new Set(["input","select","textarea"]),Nt=new Set(["email","password","tel"]);function re(){return globalThis.location}function Ue(){return globalThis.document}function Pt(){return globalThis.window??globalThis}function Rt(t){return typeof t=="object"&&t!==null&&typeof t.tagName=="string"}function ne(t,e){let n;try{n=new URL(t,e);}catch{return}return n.protocol==="http:"||n.protocol==="https:"?`${n.origin}${n.pathname}`:n.protocol}function Je(){let t=re(),e=Ue(),n={};if(t){let r=ne(t.href);r&&(n.$current_url=r),n.$pathname=t.pathname,n.$host=t.host;}if(e){e.title&&(n.$title=e.title);let r=e.referrer?ne(e.referrer):void 0;r&&(n.$referrer=r);}return n}function Be(t){return typeof t.className=="string"?t.className:""}function Ot(t){return Lt.has(t.tagName.toLowerCase())||Nt.has((t.getAttribute("type")??"").toLowerCase())}function $t(t,e,n){let r={$el_tag:t.tagName.toLowerCase(),$event_type:"click"};if(e)return r;let i=n?t.textContent?.trim():void 0;i&&(r.$el_text=i.slice(0,255)),t.id&&(r.$el_id=t.id);let s=Be(t);s&&(r.$el_classes=s);let o=t.getAttribute("href"),c=o?ne(o,re()?.href):void 0;return c&&(r.$el_href=c),r}function Mt(t,e){let n=new Set,r=(s,o)=>{if(n.has(o)||!s.matches)return false;try{return s.matches(o)}catch(c){return n.add(o),e(new u("config",`autocapture maskSelectors entry "${o}" is not a valid selector`,{cause:c})),false}},i=s=>s.getAttribute(_t)!==null||Be(s).split(/\s+/).includes(Ft)||Ot(s)||t.some(o=>r(s,o));return s=>{for(let o=s;o;o=o.parentElement)if(i(o))return true;return false}}function Dt(t){let e=globalThis.history,n=Pt(),r="",i=()=>{let c=re(),h=c?`${c.pathname}${c.search}`:"";h!==r&&(r=h,t.capture(l.pageview,{properties:Je()}));};if(i(),!e||!n)return ()=>{};let s=e.pushState.bind(e),o=e.replaceState.bind(e);return e.pushState=(...c)=>{s(...c),i();},e.replaceState=(...c)=>{o(...c),i();},n.addEventListener("popstate",i),()=>{e.pushState=s,e.replaceState=o,n.removeEventListener("popstate",i);}}function Kt(t,e){let n=Ue();if(!n)return ()=>{};let r=Mt(e.maskSelectors??[],e.onError??(()=>{})),i=e.captureElementText??false,s=o=>{let c=o.target;Rt(c)&&t.capture(l.autocapture,{properties:{...Je(),...$t(c,r(c),i)}});};return n.addEventListener("click",s,true),()=>n.removeEventListener("click",s,true)}function ze(t,e={}){let n=[];return (e.pageviews??true)&&n.push(Dt(t)),(e.clicks??true)&&n.push(Kt(t,e)),()=>{for(let r of n)r();}}function qt(){return globalThis.document?.visibilityState==="hidden"}function Vt(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 V=class{constructor(e={}){a(this,"fetchTransport");this.fetchTransport=new E(e);}async send(e){qt()&&Vt(e)||await this.fetchTransport.send(e);}};var jt=/^\d{1,3}(\.\d{1,3}){3}$/,Ht=/^[a-z0-9.-]+$/i;function Ge(){return Math.random().toString(36).slice(2,12)}function j(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 w(t,e,n){let r=["Path=/",`Max-Age=${e}`,"SameSite=Lax"];return t&&r.push(`Domain=${t}`),n&&r.push("Secure"),r.join("; ")}function We(t,e,n,r){try{let i=`pdx_probe_${r()}`,s=r();t.cookie=`${i}=${s}; ${w(e,60,n)}`;let o=j(t,i).includes(s);t.cookie=`${i}=; ${w(e,0,n)}`;let c=j(t,i).includes(s);return o&&!c}catch{return false}}function se(t){let e=t.replace(/^\[|\]$/g,"").toLowerCase();if(e.includes(":")||jt.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 Qe(t,e,n,r=Ge){for(let i of se(t))if(We(e,i,n,r))return i}function Ut(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 ie=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=j(this.jar,this.name);e.length>1&&this.domain&&(this.jar.cookie=`${this.name}=; ${w(void 0,0,this.secure)}`,e=j(this.jar,this.name));let n=e[0];return n?Ut(n):new Map}catch{return new Map}}write(e){try{if(e.size===0){this.jar.cookie=`${this.name}=; ${w(this.domain,0,this.secure)}`;return}let n=encodeURIComponent(JSON.stringify(Object.fromEntries(e)));this.jar.cookie=`${this.name}=${n}; ${w(this.domain,31536e3,this.secure)}`;}catch{return}}};function Jt(){return globalThis.document}function Bt(){return globalThis.location?.hostname??""}function zt(){return globalThis.location?.protocol==="https:"}function Gt(t){if(t===void 0)return;let e=t.startsWith(".")?t.slice(1):t;return Ht.test(e)?e.toLowerCase():void 0}function oe(t){let e="jar"in t?t.jar:Jt();if(!e||globalThis.navigator?.cookieEnabled===false)return null;let r=t.random??Ge,i=t.secure??zt(),s=t.hostname??Bt();try{let o=Gt(t.domain)??Qe(s,e,i,r);return We(e,o,i,r)?new ie(e,t.name,o,i):null}catch{return null}}var Ze="_pdx",et="~",Wt=200,Qt=/^\d+$/;function tt(t,e,n,r){let i=Xt(t.href);if(i===void 0||ce(i.search).some(de))return;let s=Ye(i.hostname,n);s===void 0||s===Ye(r,n)||(i.search=`${i.search}${i.search?"&":"?"}${Ze}=${Yt(e)}`,t.href=i.href);}function Yt(t){return [t.anonymousId,t.sessionId,String(t.sessionStartedAt)].map(en).join(et)}function nt(t){let e=ce(t).find(de);if(e===void 0)return;let n=Zt(e).split(et);if(n.length!==3)return;let r=H(n[0]),i=H(n[1]),s=H(n[2]);if(!(!Xe(r)||!Xe(i)||!tn(s)))return {anonymousId:r,sessionId:i,sessionStartedAt:Number(s)}}function rt(t,e){let n=ce(e.search),r=n.filter(s=>!de(s));if(r.length===n.length)return;let i=r.length>0?`?${r.join("&")}`:"";t.replaceState(t.state,"",`${e.pathname}${i}${e.hash}`);}function it(t){if(t.location===void 0||typeof t.location.search!="string")return;let e=nt(t.location.search);if(e===void 0)return;let n=Ke(t.storage,t.shared,t.namespace,e.anonymousId);return Ve(t.shared,t.namespace,{id:e.sessionId,startedAt:e.sessionStartedAt},t.now),t.history!==void 0&&rt(t.history,t.location),n}function ae(t,e,n){if(n.length===0)return ()=>{};let r=i=>{let s=sn(i.target);if(s===void 0)return;let o=nn(e);o!==void 0&&tt(s,o,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 Xt(t){try{let e=new URL(t);return e.protocol==="http:"||e.protocol==="https:"?e:void 0}catch{return}}function Ye(t,e){let n=e.map(r=>r.replace(/^\./,"").toLowerCase());return se(t).find(r=>n.includes(r))}function ce(t){return t.replace(/^\?/,"").split("&").filter(e=>e!=="")}function de(t){let e=t.indexOf("=");return H(e===-1?t:t.slice(0,e))===Ze}function Zt(t){let e=t.indexOf("=");return e===-1?"":t.slice(e+1)}function en(t){return encodeURIComponent(t).replace(/~/g,"%7E")}function H(t){try{return decodeURIComponent(t)}catch{return}}function Xe(t){if(t===void 0)return false;let e=_(t);return e>=1&&e<=Wt}function tn(t){return t!==void 0&&Qt.test(t)&&Number.isSafeInteger(Number(t))}function nn(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 rn(t){return typeof t.tagName=="string"&&t.tagName.toUpperCase()==="A"&&typeof t.href=="string"}function sn(t){let e=typeof t=="object"?t:null;for(;e;){if(rn(e))return e;e=e.parentElement??null;}}var st={maskAllInputs:true,maskAllText:false},on=new Set(["email","password","tel"]);function ot(t){return t.replace(/\S/g,"*")}function U(t,e,n){return an(e)||n.maskAllInputs?ot(t):t}function J(t,e){return e.maskAllText?ot(t):t}function an(t){return on.has((t??"").toLowerCase())}var cn=5e3,B=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),cn);}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 le=1,ue=3,dn=9,z=class{constructor(){a(this,"next",1);}allocate(){let e=this.next;return this.next+=1,e}},ln=new Set(["NOSCRIPT","SCRIPT"]);function G(t,e,n,r){if(t.nodeType===ue){let i=e.allocate();return r?.(t,i),{id:i,textContent:J(t.textValue??"",n),type:"text"}}if(t.nodeType===dn){let i=e.allocate();return r?.(t,i),{childNodes:at(t,e,n,r),id:i,type:"document"}}if(t.nodeType===le){let i=t.tagName??"";if(ln.has(i))return null;let s=e.allocate();return r?.(t,s),{attributes:un(t,n),childNodes:at(t,e,n,r),id:s,tagName:i,type:"element"}}return null}function at(t,e,n,r){let i=[];for(let s of t.childNodes??[]){let o=G(s,e,n,r);o&&i.push(o);}return i}function un(t,e){let n={};for(let r of t.attributes??[])n[r.name]=r.value;return t.inputValue!==void 0&&(n.value=U(t.inputValue,t.inputType,e)),n}async function ct(t,e){let n=`${p(e.replayHost)}/v1/replay`;return (await e.fetch(n,{body:JSON.stringify(t),headers:{authorization:`Bearer ${e.apiKey}`,"content-type":"application/json"},method:"POST"})).ok}var dt=new Set(["INPUT","SELECT","TEXTAREA"]),W=class{constructor(e){this.options=e;a(this,"allocator",new z);a(this,"mirror",new Map);a(this,"chunker");a(this,"fetchImpl");a(this,"observer");a(this,"timer");a(this,"started",false);this.chunker=new B({distinctId:e.distinctId,masked:e.mask.maskAllInputs,maxEvents:e.maxEvents,now:e.now,sessionId:e.sessionId}),this.fetchImpl=f(e.fetch);}start(){if(this.started)return;let e=pn(),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=G(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:J(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=G(this.adapt(r),this.allocator,this.options.mask,(s,o)=>{let c=s.ref;c&&this.mirror.set(c,o);});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||!dt.has(r.tagName))return;let i=this.mirror.get(r);i!==void 0&&this.push(3,{input:{id:i,value:U(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===ue)return n.textValue=e.textContent??"",n;if(e.nodeType===le){let r=e;if(n.tagName=r.tagName,n.attributes=Array.from(r.attributes).map(i=>({name:i.name,value:i.value})),dt.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||ct(e,{apiKey:this.options.apiKey,fetch:this.fetchImpl,replayHost:this.options.replayHost}).catch(n=>this.options.onError?.(n));}};function pn(){return globalThis.document}function lt(t){let e=new W({apiKey:t.apiKey,distinctId:t.distinctId,flushIntervalMs:t.flushIntervalMs??5e3,mask:{...st,...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 hn(){return globalThis.navigator}function fn(){return globalThis.document}function mn(){return globalThis.history}function gn(){return globalThis.location}function yn(t){let e=t?.userAgentData?.platform??t?.platform;return e?e.slice(0,50):void 0}function vn(t){let e=()=>{t.flush();};globalThis.document?.addEventListener?.("visibilitychange",e),globalThis.addEventListener?.("pagehide",e);}function kn(t,e,n){try{return oe({domain:e,name:`pdx_${F(t)}`})??n}catch{return n}}function vi(t){let{autocaptureOptions:e,cookieDomain:n,linkedDomains:r,replayHost:i,sessionReplay:s,sessionReplayOptions:o,...c}=t,h=hn(),pe=ve(),he=c.storage??pe,fe=c.sharedStorage??kn(c.apiKey,n,pe),me=it({history:mn(),location:gn(),namespace:F(c.apiKey),now:(c.clock??C).now().getTime(),shared:fe,storage:he}),T={...c,locale:c.locale??(h?.language?h.language.slice(0,20):void 0),os:c.os??yn(h),sessionTracking:c.sessionTracking??true,sharedStorage:fe,storage:he,transport:c.transport??new V({maxRetries:c.maxRetries,requestTimeoutMs:c.requestTimeoutMs})},g=new q(T);me!==void 0&&g.alias(me),vn(g),(t.autocapture??true)&&ze(g,{onError:T.onError,...e});let ge=fn();return ge&&r&&ae(ge,g,r),s&&i&&lt({apiKey:T.apiKey,distinctId:()=>g.distinctId,onError:T.onError,replayHost:i,...o,sessionId:o?.sessionId??g.sessionId}),g}exports.WebTransport=V;exports.createCookieStorage=oe;exports.createWebClient=vi;exports.decorateLink=tt;exports.installAutocapture=ze;exports.installLinkCarry=ae;exports.installSessionReplay=lt;exports.readCarry=nt;exports.resolveCookieDomain=Qe;exports.stripCarry=rt;//# sourceMappingURL=web.cjs.map
2
2
  //# sourceMappingURL=web.cjs.map
package/dist/web.d.cts CHANGED
@@ -4,10 +4,14 @@ import { a as FetchTransportOptions } from './transport-Cy42FY5A.cjs';
4
4
  import { F as FetchLike } from './http-BCh716Vs.cjs';
5
5
 
6
6
  interface AutocaptureOptions {
7
+ captureElementText?: boolean;
7
8
  clicks?: boolean;
9
+ maskSelectors?: readonly string[];
10
+ onError?: (error: unknown) => void;
8
11
  pageviews?: boolean;
9
12
  }
10
- declare function installAutocapture(client: ProdantixClient, options?: AutocaptureOptions): () => void;
13
+ type Capturer = Pick<ProdantixClient, 'capture'>;
14
+ declare function installAutocapture(client: Capturer, options?: AutocaptureOptions): () => void;
11
15
 
12
16
  declare class WebTransport implements Transport {
13
17
  private readonly fetchTransport;
package/dist/web.d.ts CHANGED
@@ -4,10 +4,14 @@ import { a as FetchTransportOptions } from './transport-CqAmRbpQ.js';
4
4
  import { F as FetchLike } from './http-BCh716Vs.js';
5
5
 
6
6
  interface AutocaptureOptions {
7
+ captureElementText?: boolean;
7
8
  clicks?: boolean;
9
+ maskSelectors?: readonly string[];
10
+ onError?: (error: unknown) => void;
8
11
  pageviews?: boolean;
9
12
  }
10
- declare function installAutocapture(client: ProdantixClient, options?: AutocaptureOptions): () => void;
13
+ type Capturer = Pick<ProdantixClient, 'capture'>;
14
+ declare function installAutocapture(client: Capturer, options?: AutocaptureOptions): () => void;
11
15
 
12
16
  declare class WebTransport implements Transport {
13
17
  private readonly fetchTransport;
package/dist/web.js CHANGED
@@ -1,2 +1,2 @@
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
1
+ import {x,e,d,b as b$1,c,h as h$1,y as y$1,q,s,t}from'./chunk-4RLPQZ5L.js';import'./chunk-V77KYPOF.js';import {e as e$1,h as h$2,a as a$1}from'./chunk-ODN4ZELX.js';import {a}from'./chunk-5XGN7UAV.js';var ke="data-pdx-no-capture",ve="pdx-no-capture",be=new Set(["input","select","textarea"]),Ee=new Set(["email","password","tel"]);function T(){return globalThis.location}function G(){return globalThis.document}function Le(){return globalThis.window??globalThis}function xe(t){return typeof t=="object"&&t!==null&&typeof t.tagName=="string"}function w(t,e){let n;try{n=new URL(t,e);}catch{return}return n.protocol==="http:"||n.protocol==="https:"?`${n.origin}${n.pathname}`:n.protocol}function Q(){let t=T(),e=G(),n={};if(t){let r=w(t.href);r&&(n.$current_url=r),n.$pathname=t.pathname,n.$host=t.host;}if(e){e.title&&(n.$title=e.title);let r=e.referrer?w(e.referrer):void 0;r&&(n.$referrer=r);}return n}function Z(t){return typeof t.className=="string"?t.className:""}function Se(t){return be.has(t.tagName.toLowerCase())||Ee.has((t.getAttribute("type")??"").toLowerCase())}function we(t,e,n){let r={$el_tag:t.tagName.toLowerCase(),$event_type:"click"};if(e)return r;let i=n?t.textContent?.trim():void 0;i&&(r.$el_text=i.slice(0,255)),t.id&&(r.$el_id=t.id);let o=Z(t);o&&(r.$el_classes=o);let s=t.getAttribute("href"),a=s?w(s,T()?.href):void 0;return a&&(r.$el_href=a),r}function Te(t,e){let n=new Set,r=(o,s)=>{if(n.has(s)||!o.matches)return false;try{return o.matches(s)}catch(a){return n.add(s),e(new a$1("config",`autocapture maskSelectors entry "${s}" is not a valid selector`,{cause:a})),false}},i=o=>o.getAttribute(ke)!==null||Z(o).split(/\s+/).includes(ve)||Se(o)||t.some(s=>r(o,s));return o=>{for(let s=o;s;s=s.parentElement)if(i(s))return true;return false}}function Ce(t$1){let e=globalThis.history,n=Le(),r="",i=()=>{let a=T(),d=a?`${a.pathname}${a.search}`:"";d!==r&&(r=d,t$1.capture(t.pageview,{properties:Q()}));};if(i(),!e||!n)return ()=>{};let o=e.pushState.bind(e),s=e.replaceState.bind(e);return e.pushState=(...a)=>{o(...a),i();},e.replaceState=(...a)=>{s(...a),i();},n.addEventListener("popstate",i),()=>{e.pushState=o,e.replaceState=s,n.removeEventListener("popstate",i);}}function Ae(t$1,e){let n=G();if(!n)return ()=>{};let r=Te(e.maskSelectors??[],e.onError??(()=>{})),i=e.captureElementText??false,o=s=>{let a=s.target;xe(a)&&t$1.capture(t.autocapture,{properties:{...Q(),...we(a,r(a),i)}});};return n.addEventListener("click",o,true),()=>n.removeEventListener("click",o,true)}function ee(t,e={}){let n=[];return (e.pageviews??true)&&n.push(Ce(t)),(e.clicks??true)&&n.push(Ae(t,e)),()=>{for(let r of n)r();}}function Ne(){return globalThis.document?.visibilityState==="hidden"}function Ie(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 m=class{constructor(e={}){a(this,"fetchTransport");this.fetchTransport=new x(e);}async send(e){Ne()&&Ie(e)||await this.fetchTransport.send(e);}};var Oe=/^\d{1,3}(\.\d{1,3}){3}$/,Re=/^[a-z0-9.-]+$/i;function te(){return Math.random().toString(36).slice(2,12)}function h(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 ne(t,e,n,r){try{let i=`pdx_probe_${r()}`,o=r();t.cookie=`${i}=${o}; ${l(e,60,n)}`;let s=h(t,i).includes(o);t.cookie=`${i}=; ${l(e,0,n)}`;let a=h(t,i).includes(o);return s&&!a}catch{return false}}function A(t){let e=t.replace(/^\[|\]$/g,"").toLowerCase();if(e.includes(":")||Oe.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 re(t,e,n,r=te){for(let i of A(t))if(ne(e,i,n,r))return i}function Me(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=h(this.jar,this.name);e.length>1&&this.domain&&(this.jar.cookie=`${this.name}=; ${l(void 0,0,this.secure)}`,e=h(this.jar,this.name));let n=e[0];return n?Me(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 Pe(){return globalThis.document}function _e(){return globalThis.location?.hostname??""}function $e(){return globalThis.location?.protocol==="https:"}function De(t){if(t===void 0)return;let e=t.startsWith(".")?t.slice(1):t;return Re.test(e)?e.toLowerCase():void 0}function N(t){let e="jar"in t?t.jar:Pe();if(!e||globalThis.navigator?.cookieEnabled===false)return null;let r=t.random??te,i=t.secure??$e(),o=t.hostname??_e();try{let s=De(t.domain)??re(o,e,i,r);return ne(e,s,i,r)?new C(e,t.name,s,i):null}catch{return null}}var se="_pdx",ae="~",He=200,Fe=/^\d+$/;function ue(t,e,n,r){let i=Ve(t.href);if(i===void 0||O(i.search).some(R))return;let o=ie(i.hostname,n);o===void 0||o===ie(r,n)||(i.search=`${i.search}${i.search?"&":"?"}${se}=${Ue(e)}`,t.href=i.href);}function Ue(t){return [t.anonymousId,t.sessionId,String(t.sessionStartedAt)].map(Ke).join(ae)}function ce(t){let e=O(t).find(R);if(e===void 0)return;let n=je(e).split(ae);if(n.length!==3)return;let r=g(n[0]),i=g(n[1]),o=g(n[2]);if(!(!oe(r)||!oe(i)||!Je(o)))return {anonymousId:r,sessionId:i,sessionStartedAt:Number(o)}}function de(t,e){let n=O(e.search),r=n.filter(o=>!R(o));if(r.length===n.length)return;let i=r.length>0?`?${r.join("&")}`:"";t.replaceState(t.state,"",`${e.pathname}${i}${e.hash}`);}function le(t){if(t.location===void 0||typeof t.location.search!="string")return;let e=ce(t.location.search);if(e===void 0)return;let n=q(t.storage,t.shared,t.namespace,e.anonymousId);return s(t.shared,t.namespace,{id:e.sessionId,startedAt:e.sessionStartedAt},t.now),t.history!==void 0&&de(t.history,t.location),n}function I(t,e,n){if(n.length===0)return ()=>{};let r=i=>{let o=ze(i.target);if(o===void 0)return;let s=Be(e);s!==void 0&&ue(o,s,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 Ve(t){try{let e=new URL(t);return e.protocol==="http:"||e.protocol==="https:"?e:void 0}catch{return}}function ie(t,e){let n=e.map(r=>r.replace(/^\./,"").toLowerCase());return A(t).find(r=>n.includes(r))}function O(t){return t.replace(/^\?/,"").split("&").filter(e=>e!=="")}function R(t){let e=t.indexOf("=");return g(e===-1?t:t.slice(0,e))===se}function je(t){let e=t.indexOf("=");return e===-1?"":t.slice(e+1)}function Ke(t){return encodeURIComponent(t).replace(/~/g,"%7E")}function g(t){try{return decodeURIComponent(t)}catch{return}}function oe(t){if(t===void 0)return false;let e$1=e(t);return e$1>=1&&e$1<=He}function Je(t){return t!==void 0&&Fe.test(t)&&Number.isSafeInteger(Number(t))}function Be(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 We(t){return typeof t.tagName=="string"&&t.tagName.toUpperCase()==="A"&&typeof t.href=="string"}function ze(t){let e=typeof t=="object"?t:null;for(;e;){if(We(e))return e;e=e.parentElement??null;}}var pe={maskAllInputs:true,maskAllText:false},qe=new Set(["email","password","tel"]);function fe(t){return t.replace(/\S/g,"*")}function y(t,e,n){return Xe(e)||n.maskAllInputs?fe(t):t}function k(t,e){return e.maskAllText?fe(t):t}function Xe(t){return qe.has((t??"").toLowerCase())}var Ye=5e3,v=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),Ye);}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 M=1,P=3,Ge=9,b=class{constructor(){a(this,"next",1);}allocate(){let e=this.next;return this.next+=1,e}},Qe=new Set(["NOSCRIPT","SCRIPT"]);function E(t,e,n,r){if(t.nodeType===P){let i=e.allocate();return r?.(t,i),{id:i,textContent:k(t.textValue??"",n),type:"text"}}if(t.nodeType===Ge){let i=e.allocate();return r?.(t,i),{childNodes:me(t,e,n,r),id:i,type:"document"}}if(t.nodeType===M){let i=t.tagName??"";if(Qe.has(i))return null;let o=e.allocate();return r?.(t,o),{attributes:Ze(t,n),childNodes:me(t,e,n,r),id:o,tagName:i,type:"element"}}return null}function me(t,e,n,r){let i=[];for(let o of t.childNodes??[]){let s=E(o,e,n,r);s&&i.push(s);}return i}function Ze(t,e){let n={};for(let r of t.attributes??[])n[r.name]=r.value;return t.inputValue!==void 0&&(n.value=y(t.inputValue,t.inputType,e)),n}async function he(t,e){let n=`${h$2(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 ge=new Set(["INPUT","SELECT","TEXTAREA"]),L=class{constructor(e){this.options=e;a(this,"allocator",new b);a(this,"mirror",new Map);a(this,"chunker");a(this,"fetchImpl");a(this,"observer");a(this,"timer");a(this,"started",false);this.chunker=new v({distinctId:e.distinctId,masked:e.mask.maskAllInputs,maxEvents:e.maxEvents,now:e.now,sessionId:e.sessionId}),this.fetchImpl=e$1(e.fetch);}start(){if(this.started)return;let e=et(),n=e?.documentElement;!e||!n||!this.fetchImpl||(this.started=true,this.captureFullSnapshot(n),this.observeMutations(n),this.observeInteractions(e),this.timer=setInterval(()=>this.upload(this.chunker.flush()),this.options.flushIntervalMs));}stop(){this.started&&(this.started=false,this.observer?.disconnect(),this.timer&&clearInterval(this.timer),this.upload(this.chunker.flush()));}captureFullSnapshot(e){let n=E(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:k(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=E(this.adapt(r),this.allocator,this.options.mask,(o,s)=>{let a=o.ref;a&&this.mirror.set(a,s);});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||!ge.has(r.tagName))return;let i=this.mirror.get(r);i!==void 0&&this.push(3,{input:{id:i,value:y(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===P)return n.textValue=e.textContent??"",n;if(e.nodeType===M){let r=e;if(n.tagName=r.tagName,n.attributes=Array.from(r.attributes).map(i=>({name:i.name,value:i.value})),ge.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||he(e,{apiKey:this.options.apiKey,fetch:this.fetchImpl,replayHost:this.options.replayHost}).catch(n=>this.options.onError?.(n));}};function et(){return globalThis.document}function ye(t){let e=new L({apiKey:t.apiKey,distinctId:t.distinctId,flushIntervalMs:t.flushIntervalMs??5e3,mask:{...pe,...t.mask},maxEvents:t.maxEvents??200,now:t.now??(()=>Date.now()),onError:t.onError,replayHost:t.replayHost,sessionId:t.sessionId??d()});return e.start(),e}function tt(){return globalThis.navigator}function nt(){return globalThis.document}function rt(){return globalThis.history}function it(){return globalThis.location}function ot(t){let e=t?.userAgentData?.platform??t?.platform;return e?e.slice(0,50):void 0}function st(t){let e=()=>{t.flush();};globalThis.document?.addEventListener?.("visibilitychange",e),globalThis.addEventListener?.("pagehide",e);}function at(t,e,n){try{return N({domain:e,name:`pdx_${h$1(t)}`})??n}catch{return n}}function Yt(t){let{autocaptureOptions:e,cookieDomain:n,linkedDomains:r,replayHost:i,sessionReplay:o,sessionReplayOptions:s,...a}=t,d=tt(),_=b$1(),$=a.storage??_,D=a.sharedStorage??at(a.apiKey,n,_),H=le({history:rt(),location:it(),namespace:h$1(a.apiKey),now:(a.clock??c).now().getTime(),shared:D,storage:$}),f={...a,locale:a.locale??(d?.language?d.language.slice(0,20):void 0),os:a.os??ot(d),sessionTracking:a.sessionTracking??true,sharedStorage:D,storage:$,transport:a.transport??new m({maxRetries:a.maxRetries,requestTimeoutMs:a.requestTimeoutMs})},c$1=new y$1(f);H!==void 0&&c$1.alias(H),st(c$1),(t.autocapture??true)&&ee(c$1,{onError:f.onError,...e});let F=nt();return F&&r&&I(F,c$1,r),o&&i&&ye({apiKey:f.apiKey,distinctId:()=>c$1.distinctId,onError:f.onError,replayHost:i,...s,sessionId:s?.sessionId??c$1.sessionId}),c$1}export{m as WebTransport,N as createCookieStorage,Yt as createWebClient,ue as decorateLink,ee as installAutocapture,I as installLinkCarry,ye as installSessionReplay,ce as readCarry,re as resolveCookieDomain,de as stripCarry};//# sourceMappingURL=web.js.map
2
2
  //# sourceMappingURL=web.js.map
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "@bomdisoft/typescript-config": "0.0.0",
5
5
  "@happy-dom/global-registrator": "^20.14.5",
6
6
  "@types/bun": "^1.4.2",
7
- "@types/node": "^26.2.0",
7
+ "@types/node": "^26.6.4",
8
8
  "tsup": "8.5.1",
9
9
  "typescript": "^6.0.3"
10
10
  },
@@ -63,5 +63,5 @@
63
63
  "sideEffects": false,
64
64
  "type": "module",
65
65
  "types": "./dist/index.d.ts",
66
- "version": "0.5.0"
66
+ "version": "0.6.0"
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 p=class extends Error{constructor(t,n,r){super(n,r);a(this,"code");this.code=t,this.name="ProdantixError";}},b=class extends p{constructor(e){super("config",e),this.name="ConfigError";}},y=class extends p{constructor(t,n){super("validation",n);a(this,"field");this.field=t,this.name="ValidationError";}},l=class extends p{constructor(t,n,r){super("transport",t,r);a(this,"status");this.status=n,this.name="TransportError";}};var v=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 v}return new v}var V={now:()=>new Date};function I(s){return s.toISOString()}var de=/^pdx_pub_(?:(?:live|test)_)?[a-z0-9]{32}$/;var ue=/^(?:\$|[a-z])[a-z0-9_.]*$/;function j(s){let e=0;for(let t of s)e+=1;return e}function H(s){return de.test(s)}function he(s){return ue.test(s)}function U(s){let e=j(s);if(e<1||e>200)throw new y("distinct_id","distinct_id must be between 1 and 200 characters")}function B(s){let e=j(s);if(e<1||e>200)throw new y("event_name","event_name must be between 1 and 200 characters");if(!he(s))throw new y("event_name","event_name must match /^(\\$|[a-z])[a-z0-9_.]*$/")}var J="prodantix-js",z="0.0.1";function pe(){return globalThis.crypto}function fe(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 ge(){let s=pe();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 fe(e)}var Q={uuid:ge};var me=s=>{};function G(s){if(!s.apiKey||!H(s.apiKey))throw new b("apiKey must be a public project key of the form pdx_pub_<32 lowercase alphanumerics>");if(!s.host)throw new b("host is required (the ingest base URL)");let e=d(s.host),t=s.defaultProperties,n=s.storage??new v;return {apiKey:s.apiKey,autocapture:s.autocapture??false,clock:s.clock??V,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:ye(s.apiKey),onError:s.onError??me,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 ye(s){return s.slice(0,16)}var g=Symbol("absent");function ve(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]:g}function f(s){return s===g?"undefined":String(s)}function W(s){return s===g?Number.NaN:Number(s)}function Y(s){return s!==g&&s!==null&&s!==""}function X(s,e){if(!Array.isArray(e))return false;let t=f(s);return e.map(n=>String(n)).includes(t)}function Z(s,e){let t=ve(s.attribute,e),n=s.value;switch(s.op){case "is_set":return Y(t);case "is_not_set":return !Y(t);case "eq":return f(t)===f(n===void 0?g:n);case "neq":return f(t)!==f(n===void 0?g:n);case "contains":return f(t).includes(f(n===void 0?g:n));case "in":return X(t,n);case "not_in":return Array.isArray(n)?!X(t,n):false;case "gt":return w(t,n,(r,i)=>r>i);case "gte":return w(t,n,(r,i)=>r>=i);case "lt":return w(t,n,(r,i)=>r<i);case "lte":return w(t,n,(r,i)=>r<=i);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 w(s,e,t){let n=W(s),r=e===void 0?Number.NaN:W(e);return Number.isNaN(n)||Number.isNaN(r)?false:t(n,r)}function ee(s,e){let t=`${s}:${e}`,n=2166136261;for(let r=0;r<t.length;r++)n^=t.charCodeAt(r),n=Math.imul(n,16777619);return (n>>>0)%100}function R(s,e){return s.targeting.length===0||s.targeting.every(t=>Z(t,e))}function te(s,e){let t=ee(s.key,e.distinctId),n=s.variations??[];if(n.length===0)return s.rolloutPercentage>=100||t<s.rolloutPercentage?"true":"false";let r=0;for(let i=n.length-1;i>=0;i--)if(r+=n[i].weight,t<r)return n[i].key;return n[0].key}function M(s,e,t,n){for(let r of s.prerequisites??[]){if(n.includes(r.flagKey))return false;let i=e.find(d=>d.key===r.flagKey);if(!i||!i.enabled)return false;n.push(i.key);let a=M(i,e,t,n)&&R(i,t)&&te(i,t)===r.variationKey;if(n.pop(),!a)return false}return true}function k(s,e,t){return s.enabled?M(s,e,t,[s.key])?R(s,t)?s.rolloutPercentage>=100?{enabled:true,reason:"rollout_full"}:ee(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 Ge(s,e){return k(s,[],e)}function se(s,e){let t={};for(let n of s)t[n.key]=k(n,s,e).enabled;return t}function x(s,e,t){let n=s.variations??[],r=n[0];if(!r)return null;if(!s.enabled||!M(s,e,t,[s.key])||!R(s,t))return r;let i=te(s,t);return n.find(a=>a.key===i)??r}function We(s,e){return x(s,[],e)}function Ye(s,e,t){let n=s.find(r=>r.key===e);return n?x(n,s,t)?.value??null:null}function ne(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 l("no fetch implementation available in this runtime");let n=`${this.host}/v1/flags?distinct_id=${encodeURIComponent(e)}`,r=b$1(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let a=await t(n,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!a.ok)throw new l(`flags request failed with status ${a.status}`,a.status);let d=JSON.parse(await a.text());return {flags:d.flags??{},variants:d.variants??{}}}finally{i!==void 0&&clearTimeout(i);}}async snapshot(){let e=this.fetch;if(!e)throw new l("no fetch implementation available in this runtime");let t=`${this.host}/v1/flags/snapshot`,n=b$1(),r=n?setTimeout(()=>n.abort(),this.requestTimeoutMs):void 0;try{let i=await e(t,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:n?.signal});if(!i.ok)throw new l(`flag snapshot request failed with status ${i.status}`,i.status);let a=JSON.parse(await i.text()),d={flags:a.flags??[],generatedAt:a.generatedAt};return typeof a.socketUrl=="string"&&a.socketUrl!==""&&(d.socketUrl=a.socketUrl),d}finally{r!==void 0&&clearTimeout(r);}}async memberships(e){let t=this.fetch;if(!t)throw new l("no fetch implementation available in this runtime");let n=`${this.host}/v1/flags/memberships?distinct_id=${encodeURIComponent(e)}`,r=b$1(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let a=await t(n,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!a.ok)throw new l(`memberships request failed with status ${a.status}`,a.status);return JSON.parse(await a.text()).cohorts??[]}finally{i!==void 0&&clearTimeout(i);}}};function S(s){if(typeof s!="string")return;let e=Array.from(s).length;return e>=1&&e<=200?s:void 0}function T(s,e){return `pdx.${s}.${e}`}var re="consent";function be(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 ke(s,e){return be(s.getItem(T(e,re)))}function xe(s,e,t){let n=T(e,re);if(typeof t.identityLink!="boolean"){s.removeItem(n);return}s.setItem(n,JSON.stringify({identityLink:t.identityLink}));}function nt(s,e,t,n){let r=T(t,"anonymous_id"),i=S(e.getItem(r))??S(s.getItem(r));return e.setItem(r,n),s.setItem(r,n),i!==void 0&&i!==n?i:void 0}var E=class{constructor(e,t,n,r){this.storage=e;this.shared=t;this.ids=n;this.namespace=r;a(this,"anonymousId");a(this,"distinctId");a(this,"identified");this.refresh();}refresh(){let e=S(this.shared.getItem(this.key("anonymous_id"))),t=S(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=S(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 ke(this.shared,this.namespace)}setConsent(e){xe(this.shared,this.namespace,e);}identify(e){let t=!this.identified||this.distinctId!==e,n=this.storage.getItem(this.key("linked_anonymous_id")),r=t||n!==this.anonymousId;return this.distinctId=e,this.identified=true,t&&this.storage.setItem(this.key("distinct_id"),e),!r||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 T(this.namespace,e)}};var _=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)}`,r=await this.request(t,n,{headers:this.authHeaders(),method:"GET"});if(!r.ok)throw new l(`inbox request failed with status ${r.status}`,r.status);return JSON.parse(await r.text()).messages??[]}async markRead(e,t){let n=this.requireFetch(),r=`${this.host}/v1/messages/read`,i=await this.request(n,r,{body:JSON.stringify({distinct_id:t,message_id:e}),headers:{...this.authHeaders(),"content-type":"application/json"},method:"POST"});if(!i.ok)throw new l(`mark-read request failed with status ${i.status}`,i.status)}requireFetch(){if(!this.fetch)throw new l("no fetch implementation available in this runtime");return this.fetch}authHeaders(){return {authorization:`Bearer ${this.projectKey}`}}async request(e,t,n){let r=b$1(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{return await e(t,{...n,signal:r?.signal})}finally{i!==void 0&&clearTimeout(i);}}};var c={autocapture:"$autocapture",createAlias:"$create_alias",featureFlagCalled:"$feature_flag_called",group:"$group",identify:"$identify",pageview:"$pageview",screen:"$screen",set:"$set"},Se=[{emittedBy:"web",meaning:"A click anywhere on the page, with the element that was clicked. The web SDK sends it by default; autocapture: false or autocaptureOptions.clicks: false turns it off.",name:c.autocapture,properties:["$event_type","$el_tag","$el_text","$el_id","$el_classes","$el_href","$current_url","$pathname","$host","$title","$referrer"]},{emittedBy:"web",meaning:"A page shown, including every client-side navigation the History API makes: one per distinct path and query.",name:c.pageview,properties:["$current_url","$pathname","$host","$title","$referrer"]},{emittedBy:"flutter",meaning:"A named route pushed or replaced in a Flutter app, the mobile counterpart of $pageview.",name:c.screen,properties:["screen"]},{emittedBy:"every",meaning:"A person becomes known by a distinct id. The anonymous trail before it is joined to them, and any traits ride along under $set.",name:c.identify,properties:["$anon_distinct_id","$set"]},{emittedBy:"every",meaning:"A second id for the same person, so events sent under either resolve to one profile.",name:c.createAlias,properties:["alias"]},{emittedBy:"every",meaning:"The person is placed in a group such as a company or a team; group properties ride along under $set.",name:c.group,properties:["$group_type","$group_key","$set"]},{emittedBy:"every",meaning:"Person properties written without an identify: $set overwrites, $set_once fills only what is still empty.",name:c.set,properties:["$set","$set_once"]},{emittedBy:"every",meaning:"A flag was evaluated for this person, sent once per distinct answer. Experiments attribute exposure from it.",name:c.featureFlagCalled,properties:["$feature_flag","$feature_flag_response"]}],dt=s=>s.startsWith("$"),ut=s=>Se.find(e=>e.name===s);function ie(s){return s>=400&&s<500&&s!==429}var C=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 l("no fetch implementation available in this runtime");let n=JSON.stringify(e.body),r;for(let i=0;i<=this.maxRetries;i+=1){try{let a=await this.attempt(t,e,n);if(a.ok)return;if(ie(a.status))throw new l(`ingest rejected batch with status ${a.status}`,a.status);r=new l(`ingest transient status ${a.status}`,a.status);}catch(a){if(a instanceof l&&a.status!==void 0&&ie(a.status))throw a;r=a;}i<this.maxRetries&&await this.sleep(this.backoff(i));}throw new l("ingest delivery failed after retries",void 0,{cause:r})}async attempt(e,t,n){let r=b$1(),i=r?setTimeout(()=>r.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:r?.signal})}finally{i!==void 0&&clearTimeout(i);}}backoff(e){return Math.min(this.maxDelayMs,this.baseDelayMs*2**e)+this.random()*this.baseDelayMs}};function oe(s,e,t){B(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:I(s.timestamp??e.now())};return s.context&&(n.context=s.context),s.sessionId&&(n.session_id=s.sessionId),n}var Ie="/socket.io/?EIO=4&transport=websocket",we=250,A=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??Fe,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(/\/+$/,"")}${Ie}`,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);},we));}}}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 Fe(s){let e=globalThis.WebSocket;if(!e)throw new Error("no WebSocket");return new e(s)}var $=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 Ee={idleMs:18e5,maxMs:864e5,throttleMs:1e4};function ae(s){return `pdx.${s}.session`}function Ft(s,e,t,n){let r={id:t.id,lastActivityAt:n,startedAt:t.startedAt};s.setItem(ae(e),JSON.stringify(r));}var P=class{constructor(e,t,n,r,i=Ee){this.storage=e;this.ids=t;this.clock=n;this.namespace=r;this.options=i;}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),r=n!==void 0&&n.id!==t.id?n:t;return this.write({...r,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 ae(this.namespace)}};var Te="queue",_e=1e3,le=3e4,q=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},N=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=G(e),this.identity=new E(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 $(this.config.maxQueueSize,({dropped:t})=>{this.config.onError(new p("queue_overflow",`event queue overflow: dropped ${t.length} oldest event(s)`));}),this.transport=this.config.transport??new C({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 _({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??{}},r=oe({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(r);}catch(n){this.config.onError(n);}}identify(e,t={}){this.identity.refresh();let n=this.identity.identify(e),r={};n.anonymousToLink!==void 0&&(r.$anon_distinct_id=n.anonymousToLink);let i={...q(t.traits??{}),...t.set??{}};Object.keys(i).length>0&&(r.$set=i),this.capture(c.identify,{properties:r});}link(e,t,n){let r={$anon_distinct_id:t},i=q(n??{});Object.keys(i).length>0&&(r.$set=i),this.capture(c.identify,{distinctId:e,properties:r});}setConsent(e){this.identity.setConsent(e);}consent(){return this.identity.consent()}alias(e){this.capture(c.createAlias,{properties:{alias:e}});}group(e,t,n){let r={$group_key:t,$group_type:e};n&&(r.$set=n),this.capture(c.group,{properties:r});}setPersonProperties(e,t){let n={};e&&(n.$set=e),t&&(n.$set_once=t),this.capture(c.set,{properties:n});}setPersonTraits(e){let t=q(e);Object.keys(t).length!==0&&this.capture(c.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(),r=n.flags.find(ce=>ce.key===e),i=await this.localContext(t,n.flags),a=r?x(r,n.flags,i):null,d=r?k(r,n.flags,i).enabled:false;return this.recordExposure(e,a?.key??String(d)),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(c.featureFlagCalled,{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 se(t.flags,await this.localContext(e,t.flags))}async isFeatureEnabledLocal(e,t={}){let n=await this.flagSnapshot(),r=n.flags.find(d=>d.key===e),i=await this.localContext(t,n.flags),a=r?k(r,n.flags,i).enabled:false;return this.recordExposure(e,(r?x(r,n.flags,i)?.key:void 0)??String(a)),a}async localContext(e,t){let n=this.identity.getDistinctId(),r=e.cohorts;if(r===void 0&&ne(t)){let i=this.config.clock.now().getTime();this.membershipCache&&this.membershipCache.distinctId===n&&i-this.membershipCache.fetchedAt<le?r=this.membershipCache.cohorts:(r=await this.flagsClient.memberships(n),this.membershipCache={cohorts:r,distinctId:n,fetchedAt:i});}return {attributes:e.attributes,cohorts:r,distinctId:n,properties:e.properties}}async flagSnapshot(){let e=this.config.clock.now().getTime();if(this.cachedSnapshot&&e-this.cachedSnapshot.fetchedAt<le)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 A({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(_e);try{await this.transport.send({body:{events:e,sent_at:I(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}.${Te}`}};function Dt(s){return new N(s)}export{ut as A,C as B,N as C,Dt as D,p as a,b,y as c,l as d,v as e,$e as f,V as g,ge as h,j as i,J as j,z as k,ye as l,Z as m,ee as n,Ge as o,se as p,We as q,Ye as r,F as s,be as t,nt as u,_ as v,Ft as w,c as x,Se as y,dt as z};//# sourceMappingURL=chunk-ESOQKMEE.js.map
2
- //# sourceMappingURL=chunk-ESOQKMEE.js.map
@@ -1,2 +0,0 @@
1
- function r(e){if(e)return e;let t=globalThis.fetch;if(typeof t=="function")return t.bind(globalThis)}function n(){let e=globalThis.AbortController;return e?new e:void 0}var o=e=>new Promise(t=>{setTimeout(t,e);});function i(e){return e.replace(/\/+$/,"")}export{r as a,n as b,o as c,i as d};//# sourceMappingURL=chunk-VG77TYVX.js.map
2
- //# sourceMappingURL=chunk-VG77TYVX.js.map