@prodantix/sdk 0.1.0-beta.351 → 0.2.0-beta.357

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/node.cjs CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var oe=Object.defineProperty;var ae=(n,e,t)=>e in n?oe(n,e,{enumerable:true,configurable:true,writable:true,value:t}):n[e]=t;var o=(n,e,t)=>ae(n,typeof e!="symbol"?e+"":e,t);var d=class extends Error{constructor(t,r,s){super(r,s);o(this,"code");this.code=t,this.name="ProdantixError";}},y=class extends d{constructor(e){super("config",e),this.name="ConfigError";}},g=class extends d{constructor(t,r){super("validation",r);o(this,"field");this.field=t,this.name="ValidationError";}},c=class extends d{constructor(t,r,s){super("transport",t,s);o(this,"status");this.status=r,this.name="TransportError";}};function m(n){if(n)return n;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function u(){let n=globalThis.AbortController;return n?new n:void 0}var $=n=>new Promise(e=>{setTimeout(e,n);});function h(n){return n.replace(/\/+$/,"")}var v=class{constructor(){o(this,"store",new Map);}getItem(e){return this.store.get(e)??null}removeItem(e){this.store.delete(e);}setItem(e,t){this.store.set(e,t);}};var A={now:()=>new Date};function b(n){return n.toISOString()}function ce(){return globalThis.crypto}function le(n){n[6]=n[6]&15|64,n[8]=n[8]&63|128;let e=[];for(let t=0;t<16;t+=1)e.push(n[t].toString(16).padStart(2,"0"));return `${e[0]}${e[1]}${e[2]}${e[3]}-${e[4]}${e[5]}-${e[6]}${e[7]}-${e[8]}${e[9]}-${e[10]}${e[11]}${e[12]}${e[13]}${e[14]}${e[15]}`}function ue(){let n=ce();if(n?.randomUUID)return n.randomUUID();let e=new Uint8Array(16);if(n?.getRandomValues)n.getRandomValues(e);else for(let t=0;t<16;t+=1)e[t]=Math.floor(Math.random()*256);return le(e)}var O={uuid:ue};var de=/^pdx_pub_(?:(?:live|test)_)?[a-z0-9]{32}$/;var he=/^(?:\$|[a-z])[a-z0-9_.]*$/;function q(n){let e=0;for(let t of n)e+=1;return e}function M(n){return de.test(n)}function pe(n){return he.test(n)}function K(n){let e=q(n);if(e<1||e>200)throw new g("distinct_id","distinct_id must be between 1 and 200 characters")}function L(n){let e=q(n);if(e<1||e>200)throw new g("event_name","event_name must be between 1 and 200 characters");if(!pe(n))throw new g("event_name","event_name must match /^(\\$|[a-z])[a-z0-9_.]*$/")}var D="prodantix-js",V="0.0.1";var fe=n=>{};function j(n){if(!n.apiKey||!M(n.apiKey))throw new y("apiKey must be a public project key of the form pdx_pub_<32 lowercase alphanumerics>");if(!n.host)throw new y("host is required (the ingest base URL)");let e=h(n.host),t=n.defaultProperties;return {apiKey:n.apiKey,autocapture:n.autocapture??false,clock:n.clock??A,defaultProperties:typeof t=="function"?t:()=>t??{},flagsHost:n.flagsHost?h(n.flagsHost):e,flushAt:n.flushAt??20,flushIntervalMs:n.flushIntervalMs??1e4,host:e,ids:n.ids??O,locale:n.locale,maxQueueSize:n.maxQueueSize??1e3,maxRetries:n.maxRetries??3,namespace:n.apiKey.slice(0,16),onError:n.onError??fe,os:n.os,requestTimeoutMs:n.requestTimeoutMs??1e4,sdkName:n.sdkName??D,sdkVersion:n.sdkVersion??V,socketFactory:n.socketFactory,storage:n.storage??new v,streamFlags:n.streamFlags??false,transport:n.transport}}function G(n,e,t){L(n.eventName),K(n.distinctId);let r={distinct_id:n.distinctId,event_id:n.eventId??t.uuid(),event_name:n.eventName,properties:n.properties??{},schema_version:1,timestamp:b(n.timestamp??e.now())};return n.context&&(r.context=n.context),n.sessionId&&(r.session_id=n.sessionId),r}var f=Symbol("absent");function ge(n,e){if(n==="distinct_id")return e.distinctId;let t=e.properties??{};if(Object.prototype.hasOwnProperty.call(t,n))return t[n];let r=e.attributes??{};return Object.prototype.hasOwnProperty.call(r,n)?r[n]:f}function p(n){return n===f?"undefined":String(n)}function U(n){return n===f?Number.NaN:Number(n)}function z(n){return n!==f&&n!==null&&n!==""}function H(n,e){if(!Array.isArray(e))return false;let t=p(n);return e.map(r=>String(r)).includes(t)}function J(n,e){let t=ge(n.attribute,e),r=n.value;switch(n.op){case "is_set":return z(t);case "is_not_set":return !z(t);case "eq":return p(t)===p(r===void 0?f:r);case "neq":return p(t)!==p(r===void 0?f:r);case "contains":return p(t).includes(p(r===void 0?f:r));case "in":return H(t,r);case "not_in":return Array.isArray(r)?!H(t,r):false;case "gt":return k(t,r,(s,i)=>s>i);case "gte":return k(t,r,(s,i)=>s>=i);case "lt":return k(t,r,(s,i)=>s<i);case "lte":return k(t,r,(s,i)=>s<=i);case "in_cohort":return typeof r=="string"&&r!==""&&(e.cohorts??[]).includes(r);case "not_in_cohort":return typeof r=="string"&&r!==""&&!(e.cohorts??[]).includes(r);default:return false}}function k(n,e,t){let r=U(n),s=e===void 0?Number.NaN:U(e);return Number.isNaN(r)||Number.isNaN(s)?false:t(r,s)}function Q(n,e){let t=`${n}:${e}`,r=2166136261;for(let s=0;s<t.length;s++)r^=t.charCodeAt(s),r=Math.imul(r,16777619);return (r>>>0)%100}function _(n,e){return n.targeting.length===0||n.targeting.every(t=>J(t,e))}function B(n,e){let t=Q(n.key,e.distinctId),r=n.variations??[];if(r.length===0)return n.rolloutPercentage>=100||t<n.rolloutPercentage?"true":"false";let s=0;for(let i=r.length-1;i>=0;i--)if(s+=r[i].weight,t<s)return r[i].key;return r[0].key}function P(n,e,t,r){for(let s of n.prerequisites??[]){if(r.includes(s.flagKey))return false;let i=e.find(l=>l.key===s.flagKey);if(!i||!i.enabled)return false;r.push(i.key);let a=P(i,e,t,r)&&_(i,t)&&B(i,t)===s.variationKey;if(r.pop(),!a)return false}return true}function x(n,e,t){return n.enabled?P(n,e,t,[n.key])?_(n,t)?n.rolloutPercentage>=100?{enabled:true,reason:"rollout_full"}:Q(n.key,t.distinctId)<n.rolloutPercentage?{enabled:true,reason:"rollout"}:{enabled:false,reason:"rollout_excluded"}:{enabled:false,reason:"targeting"}:{enabled:false,reason:"prerequisite"}:{enabled:false,reason:"disabled"}}function W(n,e){let t={};for(let r of n)t[r.key]=x(r,n,e).enabled;return t}function R(n,e,t){let r=n.variations??[],s=r[0];if(!s)return null;if(!n.enabled||!P(n,e,t,[n.key])||!_(n,t))return s;let i=B(n,t);return r.find(a=>a.key===i)??s}function X(n){return n.some(e=>e.targeting.some(t=>t.op==="in_cohort"||t.op==="not_in_cohort"))}function Y(n){return `40${JSON.stringify(n)}`}function Z(){return "3"}function ee(n){let e=n.charAt(0),t=n.slice(1);if(e==="2")return {kind:"ping"};if(e==="1")return {kind:"disconnect"};if(e==="0"){let a=N(t);return {kind:"open",pingInterval:typeof a?.pingInterval=="number"?a.pingInterval:25e3,pingTimeout:typeof a?.pingTimeout=="number"?a.pingTimeout:2e4}}if(e!=="4")return {kind:"other"};let r=t.charAt(0),s=t.slice(1);if(r==="0")return {kind:"connected"};if(r==="1")return {kind:"disconnect"};if(r==="4"){let a=N(s);return {kind:"connectError",message:typeof a?.message=="string"?a.message:"refused"}}if(r!=="2")return {kind:"other"};let i=N(s);return !Array.isArray(i)||typeof i[0]!="string"?{kind:"other"}:{kind:"event",name:i[0],payload:i[1]}}function N(n){try{return JSON.parse(n)}catch{return null}}var me="/socket.io/?EIO=4&transport=websocket",ye=250,E=class{constructor(e){this.options=e;o(this,"socket",null);o(this,"heartbeat",null);o(this,"pending",null);o(this,"lastKey","");o(this,"ready",false);o(this,"closed",false);o(this,"heartbeatWindow",45e3);o(this,"factory");o(this,"setTimer");o(this,"clearTimer");this.factory=e.socketFactory??ve,this.setTimer=e.setTimer??((t,r)=>setTimeout(t,r)),this.clearTimer=e.clearTimer??(t=>clearTimeout(t));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${me}`,t;try{t=this.factory(e);}catch{this.options.onClosed(false);return}this.socket=t,t.onmessage=r=>this.receive(String(r.data)),t.onerror=()=>t.close(),t.onclose=()=>this.fell();}close(){this.closed=true,this.stopHeartbeat(),this.pending!==null&&this.clearTimer(this.pending),this.pending=null;let e=this.socket;this.socket=null,e?.close();}receive(e){let t=ee(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),this.socket?.send(Y({projectKey:this.options.projectKey}));return}if(t.kind==="ping"){this.armHeartbeat(),this.socket?.send(Z());return}if(t.kind==="connectError"||t.kind==="disconnect"){this.stopHeartbeat(),this.socket?.close();return}if(t.kind==="event"){if(t.name==="ready"){this.ready=true;return}if(t.name==="flagChange"){let r=t.payload?.key;this.lastKey=typeof r=="string"?r:"",this.pending===null&&(this.pending=this.setTimer(()=>{this.pending=null,this.options.onChange(this.lastKey);},ye));}}}fell(){this.stopHeartbeat();let e=this.ready;this.socket=null,this.ready=false,this.closed||this.options.onClosed(e);}armHeartbeat(e){e!==void 0&&(this.heartbeatWindow=e),this.stopHeartbeat(),this.heartbeat=this.setTimer(()=>this.socket?.close(),this.heartbeatWindow);}stopHeartbeat(){this.heartbeat!==null&&this.clearTimer(this.heartbeat),this.heartbeat=null;}};function ve(n){let e=globalThis.WebSocket;if(!e)throw new Error("no WebSocket");return new e(n)}var F=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=m(e.fetch),this.host=h(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async fetchAll(e){return (await this.fetchDecisions(e)).flags}async fetchDecisions(e){let t=this.fetch;if(!t)throw new c("no fetch implementation available in this runtime");let r=`${this.host}/v1/flags?distinct_id=${encodeURIComponent(e)}`,s=u(),i=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{let a=await t(r,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:s?.signal});if(!a.ok)throw new c(`flags request failed with status ${a.status}`,a.status);let l=JSON.parse(await a.text());return {flags:l.flags??{},variants:l.variants??{}}}finally{i!==void 0&&clearTimeout(i);}}async snapshot(){let e=this.fetch;if(!e)throw new c("no fetch implementation available in this runtime");let t=`${this.host}/v1/flags/snapshot`,r=u(),s=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let i=await e(t,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!i.ok)throw new c(`flag snapshot request failed with status ${i.status}`,i.status);let a=JSON.parse(await i.text()),l={flags:a.flags??[],generatedAt:a.generatedAt};return typeof a.socketUrl=="string"&&a.socketUrl!==""&&(l.socketUrl=a.socketUrl),l}finally{s!==void 0&&clearTimeout(s);}}async memberships(e){let t=this.fetch;if(!t)throw new c("no fetch implementation available in this runtime");let r=`${this.host}/v1/flags/memberships?distinct_id=${encodeURIComponent(e)}`,s=u(),i=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{let a=await t(r,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:s?.signal});if(!a.ok)throw new c(`memberships request failed with status ${a.status}`,a.status);return JSON.parse(await a.text()).cohorts??[]}finally{i!==void 0&&clearTimeout(i);}}};var I=class{constructor(e,t,r){this.storage=e;this.ids=t;this.namespace=r;o(this,"anonymousId");o(this,"distinctId");o(this,"identified");let s=e.getItem(this.key("anonymous_id"));s?this.anonymousId=s:(this.anonymousId=t.uuid(),e.setItem(this.key("anonymous_id"),this.anonymousId));let i=e.getItem(this.key("distinct_id"));i?(this.distinctId=i,this.identified=true):(this.distinctId=this.anonymousId,this.identified=false);}getAnonymousId(){return this.anonymousId}getDistinctId(){return this.distinctId}isIdentified(){return this.identified}snapshot(){return {anonymousId:this.anonymousId,distinctId:this.distinctId,identified:this.identified}}identify(e){return this.identified&&this.distinctId===e?{changed:false}:(this.distinctId=e,this.identified=true,this.storage.setItem(this.key("distinct_id"),e),{changed:true})}reset(){this.anonymousId=this.ids.uuid(),this.distinctId=this.anonymousId,this.identified=false,this.storage.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.removeItem(this.key("distinct_id"));}key(e){return `pdx.${this.namespace}.${e}`}};var C=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=m(e.fetch),this.host=h(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async inbox(e){let t=this.requireFetch(),r=`${this.host}/v1/messages?distinct_id=${encodeURIComponent(e)}`,s=await this.request(t,r,{headers:this.authHeaders(),method:"GET"});if(!s.ok)throw new c(`inbox request failed with status ${s.status}`,s.status);return JSON.parse(await s.text()).messages??[]}async markRead(e,t){let r=this.requireFetch(),s=`${this.host}/v1/messages/read`,i=await this.request(r,s,{body:JSON.stringify({distinct_id:t,message_id:e}),headers:{...this.authHeaders(),"content-type":"application/json"},method:"POST"});if(!i.ok)throw new c(`mark-read request failed with status ${i.status}`,i.status)}requireFetch(){if(!this.fetch)throw new c("no fetch implementation available in this runtime");return this.fetch}authHeaders(){return {authorization:`Bearer ${this.projectKey}`}}async request(e,t,r){let s=u(),i=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{return await e(t,{...r,signal:s?.signal})}finally{i!==void 0&&clearTimeout(i);}}};var S=class{constructor(e,t){this.maxSize=e;this.onOverflow=t;o(this,"events",[]);}get size(){return this.events.length}enqueue(e){this.events.push(e),this.enforceCap();}restore(e){this.events.push(...e),this.enforceCap();}requeue(e){this.events.unshift(...e),this.enforceCap();}drain(e){let t=e===void 0?this.events.length:Math.min(e,this.events.length);return this.events.splice(0,t)}snapshot(){return [...this.events]}enforceCap(){if(this.events.length<=this.maxSize)return;let e=this.events.splice(0,this.events.length-this.maxSize);this.onOverflow?.({dropped:e});}};function te(n){return n>=400&&n<500&&n!==429}var w=class{constructor(e={}){o(this,"fetch");o(this,"maxRetries");o(this,"requestTimeoutMs");o(this,"baseDelayMs");o(this,"maxDelayMs");o(this,"sleep");o(this,"random");this.fetch=m(e.fetch),this.maxRetries=e.maxRetries??3,this.requestTimeoutMs=e.requestTimeoutMs??1e4,this.baseDelayMs=e.baseDelayMs??500,this.maxDelayMs=e.maxDelayMs??3e4,this.sleep=e.sleep??$,this.random=e.random??Math.random;}async send(e){let t=this.fetch;if(!t)throw new c("no fetch implementation available in this runtime");let r=JSON.stringify(e.body),s;for(let i=0;i<=this.maxRetries;i+=1){try{let a=await this.attempt(t,e,r);if(a.ok)return;if(te(a.status))throw new c(`ingest rejected batch with status ${a.status}`,a.status);s=new c(`ingest transient status ${a.status}`,a.status);}catch(a){if(a instanceof c&&a.status!==void 0&&te(a.status))throw a;s=a;}i<this.maxRetries&&await this.sleep(this.backoff(i));}throw new c("ingest delivery failed after retries",void 0,{cause:s})}async attempt(e,t,r){let s=u(),i=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{return await e(t.url,{body:r,headers:{authorization:`Bearer ${t.projectKey}`,"content-type":"application/json"},method:"POST",signal:s?.signal})}finally{i!==void 0&&clearTimeout(i);}}backoff(e){return Math.min(this.maxDelayMs,this.baseDelayMs*2**e)+this.random()*this.baseDelayMs}};var be="queue",ke=1e3,ne=3e4,re=n=>{let e={};return n.avatar!==void 0&&(e.$avatar=n.avatar),n.email!==void 0&&(e.$email=n.email),n.name!==void 0&&(e.$name=n.name),n.phone!==void 0&&(e.$phone=n.phone),e},T=class{constructor(e){o(this,"config");o(this,"identity");o(this,"queue");o(this,"transport");o(this,"flagsClient");o(this,"messagesClient");o(this,"context");o(this,"flushTimer");o(this,"flushing",false);o(this,"cachedFlags");o(this,"cachedSnapshot");o(this,"membershipCache");o(this,"stream");o(this,"shutDown",false);o(this,"exposures",new Set);this.config=j(e),this.identity=new I(this.config.storage,this.config.ids,this.config.namespace),this.queue=new S(this.config.maxQueueSize,({dropped:t})=>{this.config.onError(new d("queue_overflow",`event queue overflow: dropped ${t.length} oldest event(s)`));}),this.transport=this.config.transport??new w({maxRetries:this.config.maxRetries,requestTimeoutMs:this.config.requestTimeoutMs}),this.flagsClient=new F({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.messagesClient=new C({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.context={sdk:this.config.sdkName,sdk_version:this.config.sdkVersion},this.config.os&&(this.context.os=this.config.os),this.config.locale&&(this.context.locale=this.config.locale),this.restoreQueue(),this.startTimer();}get distinctId(){return this.identity.getDistinctId()}get anonymousId(){return this.identity.getAnonymousId()}capture(e,t={}){try{let r={...this.config.defaultProperties(),...t.properties??{}},s=G({context:this.context,distinctId:this.identity.getDistinctId(),eventName:e,properties:r,sessionId:t.sessionId,timestamp:t.timestamp},this.config.clock,this.config.ids);this.enqueue(s);}catch(r){this.config.onError(r);}}identify(e,t={}){let r=this.identity.getAnonymousId(),s=!this.identity.isIdentified(),i=this.identity.identify(e),a={};s&&i.changed&&(a.$anon_distinct_id=r);let l={...re(t.traits??{}),...t.set??{}};Object.keys(l).length>0&&(a.$set=l),this.capture("$identify",{properties:a});}alias(e){this.capture("$create_alias",{properties:{alias:e}});}group(e,t,r){let s={$group_key:t,$group_type:e};r&&(s.$set=r),this.capture("$group",{properties:s});}setPersonProperties(e,t){let r={};e&&(r.$set=e),t&&(r.$set_once=t),this.capture("$set",{properties:r});}setPersonTraits(e){let t=re(e);Object.keys(t).length!==0&&this.capture("$set",{properties:{$set:t}});}async getAllFlags(){let e=this.identity.getDistinctId(),t=await this.flagsClient.fetchDecisions(e);return this.cachedFlags={distinctId:e,flags:t.flags,variants:t.variants??{}},t.flags}async isFeatureEnabled(e){let r=(await this.getAllFlags())[e]??false;return this.recordExposure(e,this.cachedFlags?.variants[e]?.key??String(r)),r}async getVariant(e){let t=await this.getAllFlags(),r=this.cachedFlags?.variants[e]??null;return this.recordExposure(e,r?.key??String(t[e]??false)),r}async getVariantLocal(e,t={}){let r=await this.flagSnapshot(),s=r.flags.find(ie=>ie.key===e),i=await this.localContext(t,r.flags),a=s?R(s,r.flags,i):null,l=s?x(s,r.flags,i).enabled:false;return this.recordExposure(e,a?.key??String(l)),a?{key:a.key,value:a.value}:null}recordExposure(e,t){let r=`${this.identity.getDistinctId()} ${e} ${t}`;this.exposures.has(r)||(this.exposures.add(r),this.capture("$feature_flag_called",{properties:{$feature_flag:e,$feature_flag_response:t}}));}getCachedFlag(e){if(!(!this.cachedFlags||this.cachedFlags.distinctId!==this.distinctId))return this.cachedFlags.flags[e]}async getLocalFlags(e={}){let t=await this.flagSnapshot();return W(t.flags,await this.localContext(e,t.flags))}async isFeatureEnabledLocal(e,t={}){let r=await this.flagSnapshot(),s=r.flags.find(l=>l.key===e),i=await this.localContext(t,r.flags),a=s?x(s,r.flags,i).enabled:false;return this.recordExposure(e,(s?R(s,r.flags,i)?.key:void 0)??String(a)),a}async localContext(e,t){let r=this.identity.getDistinctId(),s=e.cohorts;if(s===void 0&&X(t)){let i=this.config.clock.now().getTime();this.membershipCache&&this.membershipCache.distinctId===r&&i-this.membershipCache.fetchedAt<ne?s=this.membershipCache.cohorts:(s=await this.flagsClient.memberships(r),this.membershipCache={cohorts:s,distinctId:r,fetchedAt:i});}return {attributes:e.attributes,cohorts:s,distinctId:r,properties:e.properties}}async flagSnapshot(){let e=this.config.clock.now().getTime();if(this.cachedSnapshot&&e-this.cachedSnapshot.fetchedAt<ne)return this.cachedSnapshot.snapshot;let t=await this.flagsClient.snapshot();return this.cachedSnapshot={fetchedAt:e,snapshot:t},this.maybeStream(t),t}maybeStream(e){if(!this.config.streamFlags||this.shutDown||this.stream||!e.socketUrl)return;let t=new E({host:e.socketUrl,onChange:()=>{this.cachedSnapshot=void 0,this.flagSnapshot().catch(r=>this.config.onError(r));},onClosed:r=>{this.stream=void 0,r&&this.maybeStream(e);},projectKey:this.config.apiKey,socketFactory:this.config.socketFactory});this.stream=t,t.open();}async getInbox(){return this.messagesClient.inbox(this.identity.getDistinctId())}async markMessageRead(e){await this.messagesClient.markRead(e,this.identity.getDistinctId());}async flush(){if(this.flushing||this.queue.size===0)return;this.flushing=true;let e=this.queue.drain(ke);try{await this.transport.send({body:{events:e,sent_at:b(this.config.clock.now())},projectKey:this.config.apiKey,url:`${this.config.host}/v1/events`}),this.persistQueue();}catch(t){this.queue.requeue(e),this.persistQueue(),this.config.onError(t);}finally{this.flushing=false;}}reset(){this.identity.reset(),this.cachedFlags=void 0,this.cachedSnapshot=void 0,this.membershipCache=void 0;}async shutdown(){this.shutDown=true,this.stopTimer(),this.stream?.close(),this.stream=void 0,await this.flush();}enqueue(e){this.queue.enqueue(e),this.persistQueue(),this.queue.size>=this.config.flushAt&&this.flush();}persistQueue(){try{this.config.storage.setItem(this.persistKey(),JSON.stringify(this.queue.snapshot()));}catch(e){this.config.onError(e);}}restoreQueue(){try{let e=this.config.storage.getItem(this.persistKey());if(!e)return;let t=JSON.parse(e);Array.isArray(t)&&this.queue.restore(t);}catch(e){this.config.onError(e);}}startTimer(){if(this.config.flushIntervalMs<=0)return;let e=setInterval(()=>{this.flush();},this.config.flushIntervalMs),t=e;typeof t.unref=="function"&&t.unref(),this.flushTimer=e;}stopTimer(){this.flushTimer!==void 0&&(clearInterval(this.flushTimer),this.flushTimer=void 0);}persistKey(){return `pdx.${this.config.namespace}.${be}`}};function se(){return globalThis.process}function xe(n){se()?.on("beforeExit",()=>{n.flush();});}function wt(n){let e=se(),t={...n,os:n.os??(e?.platform?e.platform.slice(0,50):void 0),streamFlags:n.streamFlags??true},r=new T(t);return xe(r),r}exports.createNodeClient=wt;//# sourceMappingURL=node.cjs.map
1
+ 'use strict';var pe=Object.defineProperty;var fe=(n,e,t)=>e in n?pe(n,e,{enumerable:true,configurable:true,writable:true,value:t}):n[e]=t;var o=(n,e,t)=>fe(n,typeof e!="symbol"?e+"":e,t);var u=class extends Error{constructor(t,s,r){super(s,r);o(this,"code");this.code=t,this.name="ProdantixError";}},y=class extends u{constructor(e){super("config",e),this.name="ConfigError";}},g=class extends u{constructor(t,s){super("validation",s);o(this,"field");this.field=t,this.name="ValidationError";}},c=class extends u{constructor(t,s,r){super("transport",t,r);o(this,"status");this.status=s,this.name="TransportError";}};function m(n){if(n)return n;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function l(){let n=globalThis.AbortController;return n?new n:void 0}var D=n=>new Promise(e=>{setTimeout(e,n);});function h(n){return n.replace(/\/+$/,"")}var v=class{constructor(){o(this,"store",new Map);}getItem(e){return this.store.get(e)??null}removeItem(e){this.store.delete(e);}setItem(e,t){this.store.set(e,t);}};var V={now:()=>new Date};function k(n){return n.toISOString()}function ge(){return globalThis.crypto}function me(n){n[6]=n[6]&15|64,n[8]=n[8]&63|128;let e=[];for(let t=0;t<16;t+=1)e.push(n[t].toString(16).padStart(2,"0"));return `${e[0]}${e[1]}${e[2]}${e[3]}-${e[4]}${e[5]}-${e[6]}${e[7]}-${e[8]}${e[9]}-${e[10]}${e[11]}${e[12]}${e[13]}${e[14]}${e[15]}`}function ye(){let n=ge();if(n?.randomUUID)return n.randomUUID();let e=new Uint8Array(16);if(n?.getRandomValues)n.getRandomValues(e);else for(let t=0;t<16;t+=1)e[t]=Math.floor(Math.random()*256);return me(e)}var j={uuid:ye};var ve=/^pdx_pub_(?:(?:live|test)_)?[a-z0-9]{32}$/;var ke=/^(?:\$|[a-z])[a-z0-9_.]*$/;function b(n){let e=0;for(let t of n)e+=1;return e}function G(n){return ve.test(n)}function be(n){return ke.test(n)}function J(n){let e=b(n);if(e<1||e>200)throw new g("distinct_id","distinct_id must be between 1 and 200 characters")}function U(n){let e=b(n);if(e<1||e>200)throw new g("event_name","event_name must be between 1 and 200 characters");if(!be(n))throw new g("event_name","event_name must match /^(\\$|[a-z])[a-z0-9_.]*$/")}var H="prodantix-js",z="0.0.1";var xe=n=>{};function Q(n){if(!n.apiKey||!G(n.apiKey))throw new y("apiKey must be a public project key of the form pdx_pub_<32 lowercase alphanumerics>");if(!n.host)throw new y("host is required (the ingest base URL)");let e=h(n.host),t=n.defaultProperties,s=n.storage??new v;return {apiKey:n.apiKey,autocapture:n.autocapture??false,clock:n.clock??V,consent:n.consent,defaultProperties:typeof t=="function"?t:()=>t??{},flagsHost:n.flagsHost?h(n.flagsHost):e,flushAt:n.flushAt??20,flushIntervalMs:n.flushIntervalMs??1e4,host:e,ids:n.ids??j,locale:n.locale,maxQueueSize:n.maxQueueSize??1e3,maxRetries:n.maxRetries??3,namespace:P(n.apiKey),onError:n.onError??xe,os:n.os,requestTimeoutMs:n.requestTimeoutMs??1e4,sdkName:n.sdkName??H,sdkVersion:n.sdkVersion??z,sessionTracking:n.sessionTracking??false,sharedStorage:n.sharedStorage??s,socketFactory:n.socketFactory,storage:s,streamFlags:n.streamFlags??false,transport:n.transport}}function P(n){return n.slice(0,16)}function B(n,e,t){U(n.eventName),J(n.distinctId);let s={distinct_id:n.distinctId,event_id:n.eventId??t.uuid(),event_name:n.eventName,properties:n.properties??{},schema_version:1,timestamp:k(n.timestamp??e.now())};return n.context&&(s.context=n.context),n.sessionId&&(s.session_id=n.sessionId),s}var f=Symbol("absent");function Se(n,e){if(n==="distinct_id")return e.distinctId;let t=e.properties??{};if(Object.prototype.hasOwnProperty.call(t,n))return t[n];let s=e.attributes??{};return Object.prototype.hasOwnProperty.call(s,n)?s[n]:f}function p(n){return n===f?"undefined":String(n)}function W(n){return n===f?Number.NaN:Number(n)}function X(n){return n!==f&&n!==null&&n!==""}function Y(n,e){if(!Array.isArray(e))return false;let t=p(n);return e.map(s=>String(s)).includes(t)}function Z(n,e){let t=Se(n.attribute,e),s=n.value;switch(n.op){case "is_set":return X(t);case "is_not_set":return !X(t);case "eq":return p(t)===p(s===void 0?f:s);case "neq":return p(t)!==p(s===void 0?f:s);case "contains":return p(t).includes(p(s===void 0?f:s));case "in":return Y(t,s);case "not_in":return Array.isArray(s)?!Y(t,s):false;case "gt":return x(t,s,(r,i)=>r>i);case "gte":return x(t,s,(r,i)=>r>=i);case "lt":return x(t,s,(r,i)=>r<i);case "lte":return x(t,s,(r,i)=>r<=i);case "in_cohort":return typeof s=="string"&&s!==""&&(e.cohorts??[]).includes(s);case "not_in_cohort":return typeof s=="string"&&s!==""&&!(e.cohorts??[]).includes(s);default:return false}}function x(n,e,t){let s=W(n),r=e===void 0?Number.NaN:W(e);return Number.isNaN(s)||Number.isNaN(r)?false:t(s,r)}function ee(n,e){let t=`${n}:${e}`,s=2166136261;for(let r=0;r<t.length;r++)s^=t.charCodeAt(r),s=Math.imul(s,16777619);return (s>>>0)%100}function R(n,e){return n.targeting.length===0||n.targeting.every(t=>Z(t,e))}function te(n,e){let t=ee(n.key,e.distinctId),s=n.variations??[];if(s.length===0)return n.rolloutPercentage>=100||t<n.rolloutPercentage?"true":"false";let r=0;for(let i=s.length-1;i>=0;i--)if(r+=s[i].weight,t<r)return s[i].key;return s[0].key}function N(n,e,t,s){for(let r of n.prerequisites??[]){if(s.includes(r.flagKey))return false;let i=e.find(d=>d.key===r.flagKey);if(!i||!i.enabled)return false;s.push(i.key);let a=N(i,e,t,s)&&R(i,t)&&te(i,t)===r.variationKey;if(s.pop(),!a)return false}return true}function S(n,e,t){return n.enabled?N(n,e,t,[n.key])?R(n,t)?n.rolloutPercentage>=100?{enabled:true,reason:"rollout_full"}:ee(n.key,t.distinctId)<n.rolloutPercentage?{enabled:true,reason:"rollout"}:{enabled:false,reason:"rollout_excluded"}:{enabled:false,reason:"targeting"}:{enabled:false,reason:"prerequisite"}:{enabled:false,reason:"disabled"}}function ne(n,e){let t={};for(let s of n)t[s.key]=S(s,n,e).enabled;return t}function $(n,e,t){let s=n.variations??[],r=s[0];if(!r)return null;if(!n.enabled||!N(n,e,t,[n.key])||!R(n,t))return r;let i=te(n,t);return s.find(a=>a.key===i)??r}function se(n){return n.some(e=>e.targeting.some(t=>t.op==="in_cohort"||t.op==="not_in_cohort"))}function re(n){return `40${JSON.stringify(n)}`}function ie(){return "3"}function oe(n){let e=n.charAt(0),t=n.slice(1);if(e==="2")return {kind:"ping"};if(e==="1")return {kind:"disconnect"};if(e==="0"){let a=O(t);return {kind:"open",pingInterval:typeof a?.pingInterval=="number"?a.pingInterval:25e3,pingTimeout:typeof a?.pingTimeout=="number"?a.pingTimeout:2e4}}if(e!=="4")return {kind:"other"};let s=t.charAt(0),r=t.slice(1);if(s==="0")return {kind:"connected"};if(s==="1")return {kind:"disconnect"};if(s==="4"){let a=O(r);return {kind:"connectError",message:typeof a?.message=="string"?a.message:"refused"}}if(s!=="2")return {kind:"other"};let i=O(r);return !Array.isArray(i)||typeof i[0]!="string"?{kind:"other"}:{kind:"event",name:i[0],payload:i[1]}}function O(n){try{return JSON.parse(n)}catch{return null}}var Ie="/socket.io/?EIO=4&transport=websocket",Ee=250,I=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??Ce,this.setTimer=e.setTimer??((t,s)=>setTimeout(t,s)),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=s=>this.receive(String(s.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=oe(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),this.socket?.send(re({projectKey:this.options.projectKey}));return}if(t.kind==="ping"){this.armHeartbeat(),this.socket?.send(ie());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 s=t.payload?.key;this.lastKey=typeof s=="string"?s:"",this.pending===null&&(this.pending=this.setTimer(()=>{this.pending=null,this.options.onChange(this.lastKey);},Ee));}}}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 Ce(n){let e=globalThis.WebSocket;if(!e)throw new Error("no WebSocket");return new e(n)}var E=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=m(e.fetch),this.host=h(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async fetchAll(e){return (await this.fetchDecisions(e)).flags}async fetchDecisions(e){let t=this.fetch;if(!t)throw new c("no fetch implementation available in this runtime");let s=`${this.host}/v1/flags?distinct_id=${encodeURIComponent(e)}`,r=l(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let a=await t(s,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!a.ok)throw new c(`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 c("no fetch implementation available in this runtime");let t=`${this.host}/v1/flags/snapshot`,s=l(),r=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{let i=await e(t,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:s?.signal});if(!i.ok)throw new c(`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 c("no fetch implementation available in this runtime");let s=`${this.host}/v1/flags/memberships?distinct_id=${encodeURIComponent(e)}`,r=l(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let a=await t(s,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!a.ok)throw new c(`memberships request failed with status ${a.status}`,a.status);return JSON.parse(await a.text()).cohorts??[]}finally{i!==void 0&&clearTimeout(i);}}};function M(n){if(typeof n!="string")return;let e=Array.from(n).length;return e>=1&&e<=200?n:void 0}function q(n,e){return `pdx.${n}.${e}`}var ae="consent";function L(n){if(typeof n!="string")return null;try{let e=JSON.parse(n);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 Fe(n,e){return L(n.getItem(q(e,ae)))}function we(n,e,t){let s=q(e,ae);if(typeof t.identityLink!="boolean"){n.removeItem(s);return}n.setItem(s,JSON.stringify({identityLink:t.identityLink}));}var C=class{constructor(e,t,s,r){this.storage=e;this.shared=t;this.ids=s;this.namespace=r;o(this,"anonymousId");o(this,"distinctId");o(this,"identified");this.refresh();}refresh(){let e=M(this.shared.getItem(this.key("anonymous_id"))),t=M(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 s=M(this.storage.getItem(this.key("distinct_id")));s?(this.distinctId=s,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 Fe(this.shared,this.namespace)}setConsent(e){we(this.shared,this.namespace,e);}identify(e){let t=!this.identified||this.distinctId!==e,s=this.storage.getItem(this.key("linked_anonymous_id")),r=t||s!==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 q(this.namespace,e)}};var F=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=m(e.fetch),this.host=h(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async inbox(e){let t=this.requireFetch(),s=`${this.host}/v1/messages?distinct_id=${encodeURIComponent(e)}`,r=await this.request(t,s,{headers:this.authHeaders(),method:"GET"});if(!r.ok)throw new c(`inbox request failed with status ${r.status}`,r.status);return JSON.parse(await r.text()).messages??[]}async markRead(e,t){let s=this.requireFetch(),r=`${this.host}/v1/messages/read`,i=await this.request(s,r,{body:JSON.stringify({distinct_id:t,message_id:e}),headers:{...this.authHeaders(),"content-type":"application/json"},method:"POST"});if(!i.ok)throw new c(`mark-read request failed with status ${i.status}`,i.status)}requireFetch(){if(!this.fetch)throw new c("no fetch implementation available in this runtime");return this.fetch}authHeaders(){return {authorization:`Bearer ${this.projectKey}`}}async request(e,t,s){let r=l(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{return await e(t,{...s,signal:r?.signal})}finally{i!==void 0&&clearTimeout(i);}}};var w=class{constructor(e,t){this.maxSize=e;this.onOverflow=t;o(this,"events",[]);}get size(){return this.events.length}enqueue(e){this.events.push(e),this.enforceCap();}restore(e){this.events.push(...e),this.enforceCap();}requeue(e){this.events.unshift(...e),this.enforceCap();}drain(e){let t=e===void 0?this.events.length:Math.min(e,this.events.length);return this.events.splice(0,t)}snapshot(){return [...this.events]}enforceCap(){if(this.events.length<=this.maxSize)return;let e=this.events.splice(0,this.events.length-this.maxSize);this.onOverflow?.({dropped:e});}};var Te={idleMs:18e5,maxMs:864e5,throttleMs:1e4};function _e(n){return `pdx.${n}.session`}var T=class{constructor(e,t,s,r,i=Te){this.storage=e;this.ids=t;this.clock=s;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 s=this.live(this.read(),e),r=s!==void 0&&s.id!==t.id?s: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 _e(this.namespace)}};function ce(n){return n>=400&&n<500&&n!==429}var _=class{constructor(e={}){o(this,"fetch");o(this,"maxRetries");o(this,"requestTimeoutMs");o(this,"baseDelayMs");o(this,"maxDelayMs");o(this,"sleep");o(this,"random");this.fetch=m(e.fetch),this.maxRetries=e.maxRetries??3,this.requestTimeoutMs=e.requestTimeoutMs??1e4,this.baseDelayMs=e.baseDelayMs??500,this.maxDelayMs=e.maxDelayMs??3e4,this.sleep=e.sleep??D,this.random=e.random??Math.random;}async send(e){let t=this.fetch;if(!t)throw new c("no fetch implementation available in this runtime");let s=JSON.stringify(e.body),r;for(let i=0;i<=this.maxRetries;i+=1){try{let a=await this.attempt(t,e,s);if(a.ok)return;if(ce(a.status))throw new c(`ingest rejected batch with status ${a.status}`,a.status);r=new c(`ingest transient status ${a.status}`,a.status);}catch(a){if(a instanceof c&&a.status!==void 0&&ce(a.status))throw a;r=a;}i<this.maxRetries&&await this.sleep(this.backoff(i));}throw new c("ingest delivery failed after retries",void 0,{cause:r})}async attempt(e,t,s){let r=l(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{return await e(t.url,{body:s,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}};var Ae="queue",Pe=1e3,de=3e4,K=n=>{let e={};return n.avatar!==void 0&&(e.$avatar=n.avatar),n.email!==void 0&&(e.$email=n.email),n.name!==void 0&&(e.$name=n.name),n.phone!==void 0&&(e.$phone=n.phone),e},A=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=Q(e),this.identity=new C(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 T(this.config.sharedStorage,this.config.ids,this.config.clock,this.config.namespace):void 0,this.queue=new w(this.config.maxQueueSize,({dropped:t})=>{this.config.onError(new u("queue_overflow",`event queue overflow: dropped ${t.length} oldest event(s)`));}),this.transport=this.config.transport??new _({maxRetries:this.config.maxRetries,requestTimeoutMs:this.config.requestTimeoutMs}),this.flagsClient=new E({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.messagesClient=new F({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.context={sdk:this.config.sdkName,sdk_version:this.config.sdkVersion},this.config.os&&(this.context.os=this.config.os),this.config.locale&&(this.context.locale=this.config.locale),this.restoreQueue(),this.startTimer();}get distinctId(){return this.identity.getDistinctId()}get anonymousId(){return this.identity.getAnonymousId()}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 s={...this.config.defaultProperties(),...t.properties??{}},r=B({context:this.context,distinctId:t.distinctId??this.identity.getDistinctId(),eventName:e,properties:s,sessionId:t.sessionId??this.session?.current(),timestamp:t.timestamp},this.config.clock,this.config.ids);this.enqueue(r);}catch(s){this.config.onError(s);}}identify(e,t={}){this.identity.refresh();let s=this.identity.identify(e),r={};s.anonymousToLink!==void 0&&(r.$anon_distinct_id=s.anonymousToLink);let i={...K(t.traits??{}),...t.set??{}};Object.keys(i).length>0&&(r.$set=i),this.capture("$identify",{properties:r});}link(e,t,s){let r={$anon_distinct_id:t},i=K(s??{});Object.keys(i).length>0&&(r.$set=i),this.capture("$identify",{distinctId:e,properties:r});}setConsent(e){this.identity.setConsent(e);}consent(){return this.identity.consent()}alias(e){this.capture("$create_alias",{properties:{alias:e}});}group(e,t,s){let r={$group_key:t,$group_type:e};s&&(r.$set=s),this.capture("$group",{properties:r});}setPersonProperties(e,t){let s={};e&&(s.$set=e),t&&(s.$set_once=t),this.capture("$set",{properties:s});}setPersonTraits(e){let t=K(e);Object.keys(t).length!==0&&this.capture("$set",{properties:{$set:t}});}async getAllFlags(){let e=this.identity.getDistinctId(),t=await this.flagsClient.fetchDecisions(e);return this.cachedFlags={distinctId:e,flags:t.flags,variants:t.variants??{}},t.flags}async isFeatureEnabled(e){let s=(await this.getAllFlags())[e]??false;return this.recordExposure(e,this.cachedFlags?.variants[e]?.key??String(s)),s}async getVariant(e){let t=await this.getAllFlags(),s=this.cachedFlags?.variants[e]??null;return this.recordExposure(e,s?.key??String(t[e]??false)),s}async getVariantLocal(e,t={}){let s=await this.flagSnapshot(),r=s.flags.find(he=>he.key===e),i=await this.localContext(t,s.flags),a=r?$(r,s.flags,i):null,d=r?S(r,s.flags,i).enabled:false;return this.recordExposure(e,a?.key??String(d)),a?{key:a.key,value:a.value}:null}recordExposure(e,t){let s=`${this.identity.getDistinctId()} ${e} ${t}`;this.exposures.has(s)||(this.exposures.add(s),this.capture("$feature_flag_called",{properties:{$feature_flag:e,$feature_flag_response:t}}));}getCachedFlag(e){if(!(!this.cachedFlags||this.cachedFlags.distinctId!==this.distinctId))return this.cachedFlags.flags[e]}async getLocalFlags(e={}){let t=await this.flagSnapshot();return ne(t.flags,await this.localContext(e,t.flags))}async isFeatureEnabledLocal(e,t={}){let s=await this.flagSnapshot(),r=s.flags.find(d=>d.key===e),i=await this.localContext(t,s.flags),a=r?S(r,s.flags,i).enabled:false;return this.recordExposure(e,(r?$(r,s.flags,i)?.key:void 0)??String(a)),a}async localContext(e,t){let s=this.identity.getDistinctId(),r=e.cohorts;if(r===void 0&&se(t)){let i=this.config.clock.now().getTime();this.membershipCache&&this.membershipCache.distinctId===s&&i-this.membershipCache.fetchedAt<de?r=this.membershipCache.cohorts:(r=await this.flagsClient.memberships(s),this.membershipCache={cohorts:r,distinctId:s,fetchedAt:i});}return {attributes:e.attributes,cohorts:r,distinctId:s,properties:e.properties}}async flagSnapshot(){let e=this.config.clock.now().getTime();if(this.cachedSnapshot&&e-this.cachedSnapshot.fetchedAt<de)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 I({host:e.socketUrl,onChange:()=>{this.cachedSnapshot=void 0,this.flagSnapshot().catch(s=>this.config.onError(s));},onClosed:s=>{this.stream=void 0,s&&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(Pe);try{await this.transport.send({body:{events:e,sent_at:k(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}.${Ae}`}};var Re=200;function le(){return globalThis.process}function Ne(n){le()?.on("beforeExit",()=>{n.flush();});}function zt(n){let e=le(),t={...n,os:n.os??(e?.platform?e.platform.slice(0,50):void 0),streamFlags:n.streamFlags??true},s=new A(t);return Ne(s),s}function Qt(n,e){let t=P(e),s=$e(n,`pdx_${t}`);if(s===void 0)return null;let r=Oe(s);if(r===void 0)return null;let i=ue(r[`pdx.${t}.anonymous_id`]);return i===void 0?null:{anonymousId:i,consent:L(r[`pdx.${t}.consent`]),sessionId:Me(r[`pdx.${t}.session`])}}function $e(n,e){let t=`${e}=`;for(let s of n.split(";")){let r=s.trim();if(r.startsWith(t))return r.slice(t.length)}}function Oe(n){try{let e=JSON.parse(decodeURIComponent(n));return e===null||typeof e!="object"||Array.isArray(e)?void 0:e}catch{return}}function ue(n){if(typeof n!="string")return;let e=b(n);return e>=1&&e<=Re?n:void 0}function Me(n){if(typeof n!="string")return null;try{let e=JSON.parse(n);return e===null||typeof e!="object"||typeof e.startedAt!="number"||typeof e.lastActivityAt!="number"?null:ue(e.id)??null}catch{return null}}exports.createNodeClient=zt;exports.readSharedIdentity=Qt;//# sourceMappingURL=node.cjs.map
2
2
  //# sourceMappingURL=node.cjs.map
package/dist/node.d.cts CHANGED
@@ -1,6 +1,21 @@
1
- import { P as ProdantixClient } from './client-y1xyVF6C.cjs';
2
- import { P as ProdantixConfig } from './types-68Sc11g8.cjs';
1
+ import { P as ProdantixClient } from './client-BO7f6q5k.cjs';
2
+ import { b as Consent, P as ProdantixConfig } from './types-DjMXp6Wg.cjs';
3
3
 
4
+ /** What the web SDK's cookie says about the visitor on this request: the
5
+ * anonymous id every subdomain of the site shares, the session it is in, and
6
+ * the answer they gave about the join (null when they were never asked). */
7
+ interface SharedIdentity {
8
+ anonymousId: string;
9
+ consent: Consent | null;
10
+ sessionId: string | null;
11
+ }
4
12
  declare function createNodeClient(options: ProdantixConfig): ProdantixClient;
13
+ /**
14
+ * Reads the visitor the web SDK's cookie names, from a request's `Cookie`
15
+ * header. A sign-in that completes in a redirect has no page to identify from,
16
+ * so the server reads the browser's anonymous id here and links it with
17
+ * `ProdantixClient.link`. Null when the cookie is absent or not the SDK's own.
18
+ */
19
+ declare function readSharedIdentity(cookieHeader: string, apiKey: string): SharedIdentity | null;
5
20
 
6
- export { createNodeClient };
21
+ export { Consent, type SharedIdentity, createNodeClient, readSharedIdentity };
package/dist/node.d.ts CHANGED
@@ -1,6 +1,21 @@
1
- import { P as ProdantixClient } from './client-Ca6xJESF.js';
2
- import { P as ProdantixConfig } from './types-68Sc11g8.js';
1
+ import { P as ProdantixClient } from './client-BQlU_3Dc.js';
2
+ import { b as Consent, P as ProdantixConfig } from './types-DjMXp6Wg.js';
3
3
 
4
+ /** What the web SDK's cookie says about the visitor on this request: the
5
+ * anonymous id every subdomain of the site shares, the session it is in, and
6
+ * the answer they gave about the join (null when they were never asked). */
7
+ interface SharedIdentity {
8
+ anonymousId: string;
9
+ consent: Consent | null;
10
+ sessionId: string | null;
11
+ }
4
12
  declare function createNodeClient(options: ProdantixConfig): ProdantixClient;
13
+ /**
14
+ * Reads the visitor the web SDK's cookie names, from a request's `Cookie`
15
+ * header. A sign-in that completes in a redirect has no page to identify from,
16
+ * so the server reads the browser's anonymous id here and links it with
17
+ * `ProdantixClient.link`. Null when the cookie is absent or not the SDK's own.
18
+ */
19
+ declare function readSharedIdentity(cookieHeader: string, apiKey: string): SharedIdentity | null;
5
20
 
6
- export { createNodeClient };
21
+ export { Consent, type SharedIdentity, createNodeClient, readSharedIdentity };
package/dist/node.js CHANGED
@@ -1,2 +1,2 @@
1
- import {s as s$1}from'./chunk-CSIP3PZ7.js';import'./chunk-V77KYPOF.js';import'./chunk-VG77TYVX.js';import'./chunk-5XGN7UAV.js';function r(){return globalThis.process}function s(e){r()?.on("beforeExit",()=>{e.flush();});}function a(e){let o=r(),i={...e,os:e.os??(o?.platform?o.platform.slice(0,50):void 0),streamFlags:e.streamFlags??true},n=new s$1(i);return s(n),n}export{a as createNodeClient};//# sourceMappingURL=node.js.map
1
+ import {y as y$1,l as l$1,t,i}from'./chunk-5CBVQAZ2.js';import'./chunk-V77KYPOF.js';import'./chunk-VG77TYVX.js';import'./chunk-5XGN7UAV.js';var a=200;function f(){return globalThis.process}function p(t){f()?.on("beforeExit",()=>{t.flush();});}function h(t){let n=f(),e={...t,os:t.os??(n?.platform?n.platform.slice(0,50):void 0),streamFlags:t.streamFlags??true},r=new y$1(e);return p(r),r}function w(t$1,n){let e=l$1(n),r=m(t$1,`pdx_${e}`);if(r===void 0)return null;let o=g(r);if(o===void 0)return null;let i=l(o[`pdx.${e}.anonymous_id`]);return i===void 0?null:{anonymousId:i,consent:t(o[`pdx.${e}.consent`]),sessionId:y(o[`pdx.${e}.session`])}}function m(t,n){let e=`${n}=`;for(let r of t.split(";")){let o=r.trim();if(o.startsWith(e))return o.slice(e.length)}}function g(t){try{let n=JSON.parse(decodeURIComponent(t));return n===null||typeof n!="object"||Array.isArray(n)?void 0:n}catch{return}}function l(t){if(typeof t!="string")return;let n=i(t);return n>=1&&n<=a?t:void 0}function y(t){if(typeof t!="string")return null;try{let n=JSON.parse(t);return n===null||typeof n!="object"||typeof n.startedAt!="number"||typeof n.lastActivityAt!="number"?null:l(n.id)??null}catch{return null}}export{h as createNodeClient,w as readSharedIdentity};//# sourceMappingURL=node.js.map
2
2
  //# sourceMappingURL=node.js.map
@@ -1,5 +1,5 @@
1
1
  import { F as FetchLike } from './http-BCh716Vs.js';
2
- import { T as Transport, h as TransportRequest } from './types-68Sc11g8.js';
2
+ import { T as Transport, i as TransportRequest } from './types-DjMXp6Wg.js';
3
3
 
4
4
  interface FetchTransportOptions {
5
5
  baseDelayMs?: number;
@@ -1,5 +1,5 @@
1
1
  import { F as FetchLike } from './http-BCh716Vs.cjs';
2
- import { T as Transport, h as TransportRequest } from './types-68Sc11g8.cjs';
2
+ import { T as Transport, i as TransportRequest } from './types-DjMXp6Wg.cjs';
3
3
 
4
4
  interface FetchTransportOptions {
5
5
  baseDelayMs?: number;
@@ -45,6 +45,14 @@ interface InboxResponse {
45
45
  interface Clock {
46
46
  now(): Date;
47
47
  }
48
+ /**
49
+ * What the visitor answered about their anonymous trail being joined to the
50
+ * person they sign in as. Unset means allowed: the answer is the customer's
51
+ * banner to collect, and a site that never asks keeps the platform's default.
52
+ */
53
+ interface Consent {
54
+ identityLink?: boolean;
55
+ }
48
56
  interface IdFactory {
49
57
  uuid(): string;
50
58
  }
@@ -79,6 +87,9 @@ interface ProdantixConfig {
79
87
  apiKey: string;
80
88
  autocapture?: boolean;
81
89
  clock?: Clock;
90
+ /** The visitor's answer, for an app that already holds it. Written to the
91
+ * shared store when the client is built, so the answer survives the page. */
92
+ consent?: Consent;
82
93
  defaultProperties?: EventProperties | (() => EventProperties);
83
94
  flagsHost?: string;
84
95
  flushAt?: number;
@@ -93,6 +104,8 @@ interface ProdantixConfig {
93
104
  requestTimeoutMs?: number;
94
105
  sdkName?: string;
95
106
  sdkVersion?: string;
107
+ sessionTracking?: boolean;
108
+ sharedStorage?: StorageAdapter;
96
109
  /** The socket constructor the flag stream uses; the test seam. */
97
110
  socketFactory?: SocketFactory;
98
111
  storage?: StorageAdapter;
@@ -102,4 +115,4 @@ interface ProdantixConfig {
102
115
  transport?: Transport;
103
116
  }
104
117
 
105
- export type { Clock as C, EventBatch as E, FlagsResponse as F, InboxMessage as I, JsonValue as J, ProdantixConfig as P, SocketFactory as S, Transport as T, StorageAdapter as a, EventContext as b, EventEnvelope as c, EventProperties as d, FlagVariant as e, IdFactory as f, InboxResponse as g, TransportRequest as h };
118
+ export type { Clock as C, EventBatch as E, FlagsResponse as F, InboxMessage as I, JsonValue as J, ProdantixConfig as P, SocketFactory as S, Transport as T, StorageAdapter as a, Consent as b, EventContext as c, EventEnvelope as d, EventProperties as e, FlagVariant as f, IdFactory as g, InboxResponse as h, TransportRequest as i };
@@ -45,6 +45,14 @@ interface InboxResponse {
45
45
  interface Clock {
46
46
  now(): Date;
47
47
  }
48
+ /**
49
+ * What the visitor answered about their anonymous trail being joined to the
50
+ * person they sign in as. Unset means allowed: the answer is the customer's
51
+ * banner to collect, and a site that never asks keeps the platform's default.
52
+ */
53
+ interface Consent {
54
+ identityLink?: boolean;
55
+ }
48
56
  interface IdFactory {
49
57
  uuid(): string;
50
58
  }
@@ -79,6 +87,9 @@ interface ProdantixConfig {
79
87
  apiKey: string;
80
88
  autocapture?: boolean;
81
89
  clock?: Clock;
90
+ /** The visitor's answer, for an app that already holds it. Written to the
91
+ * shared store when the client is built, so the answer survives the page. */
92
+ consent?: Consent;
82
93
  defaultProperties?: EventProperties | (() => EventProperties);
83
94
  flagsHost?: string;
84
95
  flushAt?: number;
@@ -93,6 +104,8 @@ interface ProdantixConfig {
93
104
  requestTimeoutMs?: number;
94
105
  sdkName?: string;
95
106
  sdkVersion?: string;
107
+ sessionTracking?: boolean;
108
+ sharedStorage?: StorageAdapter;
96
109
  /** The socket constructor the flag stream uses; the test seam. */
97
110
  socketFactory?: SocketFactory;
98
111
  storage?: StorageAdapter;
@@ -102,4 +115,4 @@ interface ProdantixConfig {
102
115
  transport?: Transport;
103
116
  }
104
117
 
105
- export type { Clock as C, EventBatch as E, FlagsResponse as F, InboxMessage as I, JsonValue as J, ProdantixConfig as P, SocketFactory as S, Transport as T, StorageAdapter as a, EventContext as b, EventEnvelope as c, EventProperties as d, FlagVariant as e, IdFactory as f, InboxResponse as g, TransportRequest as h };
118
+ export type { Clock as C, EventBatch as E, FlagsResponse as F, InboxMessage as I, JsonValue as J, ProdantixConfig as P, SocketFactory as S, Transport as T, StorageAdapter as a, Consent as b, EventContext as c, EventEnvelope as d, EventProperties as e, FlagVariant as f, IdFactory as g, InboxResponse as h, TransportRequest as i };
package/dist/web.cjs CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var Ce=Object.defineProperty;var Fe=(t,e,n)=>e in t?Ce(t,e,{enumerable:true,configurable:true,writable:true,value:n}):t[e]=n;var o=(t,e,n)=>Fe(t,typeof e!="symbol"?e+"":e,n);var f=class extends Error{constructor(n,r,s){super(r,s);o(this,"code");this.code=n,this.name="ProdantixError";}},b=class extends f{constructor(e){super("config",e),this.name="ConfigError";}},y=class extends f{constructor(n,r){super("validation",r);o(this,"field");this.field=n,this.name="ValidationError";}},c=class extends f{constructor(n,r,s){super("transport",n,s);o(this,"status");this.status=r,this.name="TransportError";}};function d(t){if(t)return t;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function h(){let t=globalThis.AbortController;return t?new t:void 0}var U=t=>new Promise(e=>{setTimeout(e,t);});function p(t){return t.replace(/\/+$/,"")}var v=class{constructor(){o(this,"store",new Map);}getItem(e){return this.store.get(e)??null}removeItem(e){this.store.delete(e);}setItem(e,n){this.store.set(e,n);}};function G(){try{let t=globalThis.localStorage;if(t){let e="__pdx_probe__";return t.setItem(e,"1"),t.removeItem(e),t}}catch{return new v}return new v}var B={now:()=>new Date};function E(t){return t.toISOString()}function Ne(){return globalThis.crypto}function _e(t){t[6]=t[6]&15|64,t[8]=t[8]&63|128;let e=[];for(let n=0;n<16;n+=1)e.push(t[n].toString(16).padStart(2,"0"));return `${e[0]}${e[1]}${e[2]}${e[3]}-${e[4]}${e[5]}-${e[6]}${e[7]}-${e[8]}${e[9]}-${e[10]}${e[11]}${e[12]}${e[13]}${e[14]}${e[15]}`}function q(){let t=Ne();if(t?.randomUUID)return t.randomUUID();let e=new Uint8Array(16);if(t?.getRandomValues)t.getRandomValues(e);else for(let n=0;n<16;n+=1)e[n]=Math.floor(Math.random()*256);return _e(e)}var J={uuid:q};var Pe=/^pdx_pub_(?:(?:live|test)_)?[a-z0-9]{32}$/;var Re=/^(?:\$|[a-z])[a-z0-9_.]*$/;function W(t){let e=0;for(let n of t)e+=1;return e}function Q(t){return Pe.test(t)}function Oe(t){return Re.test(t)}function X(t){let e=W(t);if(e<1||e>200)throw new y("distinct_id","distinct_id must be between 1 and 200 characters")}function Y(t){let e=W(t);if(e<1||e>200)throw new y("event_name","event_name must be between 1 and 200 characters");if(!Oe(t))throw new y("event_name","event_name must match /^(\\$|[a-z])[a-z0-9_.]*$/")}var Z="prodantix-js",ee="0.0.1";var Ae=t=>{};function te(t){if(!t.apiKey||!Q(t.apiKey))throw new b("apiKey must be a public project key of the form pdx_pub_<32 lowercase alphanumerics>");if(!t.host)throw new b("host is required (the ingest base URL)");let e=p(t.host),n=t.defaultProperties;return {apiKey:t.apiKey,autocapture:t.autocapture??false,clock:t.clock??B,defaultProperties:typeof n=="function"?n:()=>n??{},flagsHost:t.flagsHost?p(t.flagsHost):e,flushAt:t.flushAt??20,flushIntervalMs:t.flushIntervalMs??1e4,host:e,ids:t.ids??J,locale:t.locale,maxQueueSize:t.maxQueueSize??1e3,maxRetries:t.maxRetries??3,namespace:t.apiKey.slice(0,16),onError:t.onError??Ae,os:t.os,requestTimeoutMs:t.requestTimeoutMs??1e4,sdkName:t.sdkName??Z,sdkVersion:t.sdkVersion??ee,socketFactory:t.socketFactory,storage:t.storage??new v,streamFlags:t.streamFlags??false,transport:t.transport}}function ne(t,e,n){Y(t.eventName),X(t.distinctId);let r={distinct_id:t.distinctId,event_id:t.eventId??n.uuid(),event_name:t.eventName,properties:t.properties??{},schema_version:1,timestamp:E(t.timestamp??e.now())};return t.context&&(r.context=t.context),t.sessionId&&(r.session_id=t.sessionId),r}var g=Symbol("absent");function Le(t,e){if(t==="distinct_id")return e.distinctId;let n=e.properties??{};if(Object.prototype.hasOwnProperty.call(n,t))return n[t];let r=e.attributes??{};return Object.prototype.hasOwnProperty.call(r,t)?r[t]:g}function m(t){return t===g?"undefined":String(t)}function re(t){return t===g?Number.NaN:Number(t)}function se(t){return t!==g&&t!==null&&t!==""}function ie(t,e){if(!Array.isArray(e))return false;let n=m(t);return e.map(r=>String(r)).includes(n)}function oe(t,e){let n=Le(t.attribute,e),r=t.value;switch(t.op){case "is_set":return se(n);case "is_not_set":return !se(n);case "eq":return m(n)===m(r===void 0?g:r);case "neq":return m(n)!==m(r===void 0?g:r);case "contains":return m(n).includes(m(r===void 0?g:r));case "in":return ie(n,r);case "not_in":return Array.isArray(r)?!ie(n,r):false;case "gt":return T(n,r,(s,i)=>s>i);case "gte":return T(n,r,(s,i)=>s>=i);case "lt":return T(n,r,(s,i)=>s<i);case "lte":return T(n,r,(s,i)=>s<=i);case "in_cohort":return typeof r=="string"&&r!==""&&(e.cohorts??[]).includes(r);case "not_in_cohort":return typeof r=="string"&&r!==""&&!(e.cohorts??[]).includes(r);default:return false}}function T(t,e,n){let r=re(t),s=e===void 0?Number.NaN:re(e);return Number.isNaN(r)||Number.isNaN(s)?false:n(r,s)}function ae(t,e){let n=`${t}:${e}`,r=2166136261;for(let s=0;s<n.length;s++)r^=n.charCodeAt(s),r=Math.imul(r,16777619);return (r>>>0)%100}function K(t,e){return t.targeting.length===0||t.targeting.every(n=>oe(n,e))}function le(t,e){let n=ae(t.key,e.distinctId),r=t.variations??[];if(r.length===0)return t.rolloutPercentage>=100||n<t.rolloutPercentage?"true":"false";let s=0;for(let i=r.length-1;i>=0;i--)if(s+=r[i].weight,n<s)return r[i].key;return r[0].key}function D(t,e,n,r){for(let s of t.prerequisites??[]){if(r.includes(s.flagKey))return false;let i=e.find(l=>l.key===s.flagKey);if(!i||!i.enabled)return false;r.push(i.key);let a=D(i,e,n,r)&&K(i,n)&&le(i,n)===s.variationKey;if(r.pop(),!a)return false}return true}function S(t,e,n){return t.enabled?D(t,e,n,[t.key])?K(t,n)?t.rolloutPercentage>=100?{enabled:true,reason:"rollout_full"}:ae(t.key,n.distinctId)<t.rolloutPercentage?{enabled:true,reason:"rollout"}:{enabled:false,reason:"rollout_excluded"}:{enabled:false,reason:"targeting"}:{enabled:false,reason:"prerequisite"}:{enabled:false,reason:"disabled"}}function ce(t,e){let n={};for(let r of t)n[r.key]=S(r,t,e).enabled;return n}function V(t,e,n){let r=t.variations??[],s=r[0];if(!s)return null;if(!t.enabled||!D(t,e,n,[t.key])||!K(t,n))return s;let i=le(t,n);return r.find(a=>a.key===i)??s}function ue(t){return t.some(e=>e.targeting.some(n=>n.op==="in_cohort"||n.op==="not_in_cohort"))}function pe(t){return `40${JSON.stringify(t)}`}function de(){return "3"}function he(t){let e=t.charAt(0),n=t.slice(1);if(e==="2")return {kind:"ping"};if(e==="1")return {kind:"disconnect"};if(e==="0"){let a=j(n);return {kind:"open",pingInterval:typeof a?.pingInterval=="number"?a.pingInterval:25e3,pingTimeout:typeof a?.pingTimeout=="number"?a.pingTimeout:2e4}}if(e!=="4")return {kind:"other"};let r=n.charAt(0),s=n.slice(1);if(r==="0")return {kind:"connected"};if(r==="1")return {kind:"disconnect"};if(r==="4"){let a=j(s);return {kind:"connectError",message:typeof a?.message=="string"?a.message:"refused"}}if(r!=="2")return {kind:"other"};let i=j(s);return !Array.isArray(i)||typeof i[0]!="string"?{kind:"other"}:{kind:"event",name:i[0],payload:i[1]}}function j(t){try{return JSON.parse(t)}catch{return null}}var Me="/socket.io/?EIO=4&transport=websocket",$e=250,w=class{constructor(e){this.options=e;o(this,"socket",null);o(this,"heartbeat",null);o(this,"pending",null);o(this,"lastKey","");o(this,"ready",false);o(this,"closed",false);o(this,"heartbeatWindow",45e3);o(this,"factory");o(this,"setTimer");o(this,"clearTimer");this.factory=e.socketFactory??qe,this.setTimer=e.setTimer??((n,r)=>setTimeout(n,r)),this.clearTimer=e.clearTimer??(n=>clearTimeout(n));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${Me}`,n;try{n=this.factory(e);}catch{this.options.onClosed(false);return}this.socket=n,n.onmessage=r=>this.receive(String(r.data)),n.onerror=()=>n.close(),n.onclose=()=>this.fell();}close(){this.closed=true,this.stopHeartbeat(),this.pending!==null&&this.clearTimer(this.pending),this.pending=null;let e=this.socket;this.socket=null,e?.close();}receive(e){let n=he(e);if(n.kind==="open"){this.armHeartbeat(n.pingInterval+n.pingTimeout),this.socket?.send(pe({projectKey:this.options.projectKey}));return}if(n.kind==="ping"){this.armHeartbeat(),this.socket?.send(de());return}if(n.kind==="connectError"||n.kind==="disconnect"){this.stopHeartbeat(),this.socket?.close();return}if(n.kind==="event"){if(n.name==="ready"){this.ready=true;return}if(n.name==="flagChange"){let r=n.payload?.key;this.lastKey=typeof r=="string"?r:"",this.pending===null&&(this.pending=this.setTimer(()=>{this.pending=null,this.options.onChange(this.lastKey);},$e));}}}fell(){this.stopHeartbeat();let e=this.ready;this.socket=null,this.ready=false,this.closed||this.options.onClosed(e);}armHeartbeat(e){e!==void 0&&(this.heartbeatWindow=e),this.stopHeartbeat(),this.heartbeat=this.setTimer(()=>this.socket?.close(),this.heartbeatWindow);}stopHeartbeat(){this.heartbeat!==null&&this.clearTimer(this.heartbeat),this.heartbeat=null;}};function qe(t){let e=globalThis.WebSocket;if(!e)throw new Error("no WebSocket");return new e(t)}var I=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=d(e.fetch),this.host=p(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async fetchAll(e){return (await this.fetchDecisions(e)).flags}async fetchDecisions(e){let n=this.fetch;if(!n)throw new c("no fetch implementation available in this runtime");let r=`${this.host}/v1/flags?distinct_id=${encodeURIComponent(e)}`,s=h(),i=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{let a=await n(r,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:s?.signal});if(!a.ok)throw new c(`flags request failed with status ${a.status}`,a.status);let l=JSON.parse(await a.text());return {flags:l.flags??{},variants:l.variants??{}}}finally{i!==void 0&&clearTimeout(i);}}async snapshot(){let e=this.fetch;if(!e)throw new c("no fetch implementation available in this runtime");let n=`${this.host}/v1/flags/snapshot`,r=h(),s=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let i=await e(n,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!i.ok)throw new c(`flag snapshot request failed with status ${i.status}`,i.status);let a=JSON.parse(await i.text()),l={flags:a.flags??[],generatedAt:a.generatedAt};return typeof a.socketUrl=="string"&&a.socketUrl!==""&&(l.socketUrl=a.socketUrl),l}finally{s!==void 0&&clearTimeout(s);}}async memberships(e){let n=this.fetch;if(!n)throw new c("no fetch implementation available in this runtime");let r=`${this.host}/v1/flags/memberships?distinct_id=${encodeURIComponent(e)}`,s=h(),i=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{let a=await n(r,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:s?.signal});if(!a.ok)throw new c(`memberships request failed with status ${a.status}`,a.status);return JSON.parse(await a.text()).cohorts??[]}finally{i!==void 0&&clearTimeout(i);}}};var C=class{constructor(e,n,r){this.storage=e;this.ids=n;this.namespace=r;o(this,"anonymousId");o(this,"distinctId");o(this,"identified");let s=e.getItem(this.key("anonymous_id"));s?this.anonymousId=s:(this.anonymousId=n.uuid(),e.setItem(this.key("anonymous_id"),this.anonymousId));let i=e.getItem(this.key("distinct_id"));i?(this.distinctId=i,this.identified=true):(this.distinctId=this.anonymousId,this.identified=false);}getAnonymousId(){return this.anonymousId}getDistinctId(){return this.distinctId}isIdentified(){return this.identified}snapshot(){return {anonymousId:this.anonymousId,distinctId:this.distinctId,identified:this.identified}}identify(e){return this.identified&&this.distinctId===e?{changed:false}:(this.distinctId=e,this.identified=true,this.storage.setItem(this.key("distinct_id"),e),{changed:true})}reset(){this.anonymousId=this.ids.uuid(),this.distinctId=this.anonymousId,this.identified=false,this.storage.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.removeItem(this.key("distinct_id"));}key(e){return `pdx.${this.namespace}.${e}`}};var F=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=d(e.fetch),this.host=p(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async inbox(e){let n=this.requireFetch(),r=`${this.host}/v1/messages?distinct_id=${encodeURIComponent(e)}`,s=await this.request(n,r,{headers:this.authHeaders(),method:"GET"});if(!s.ok)throw new c(`inbox request failed with status ${s.status}`,s.status);return JSON.parse(await s.text()).messages??[]}async markRead(e,n){let r=this.requireFetch(),s=`${this.host}/v1/messages/read`,i=await this.request(r,s,{body:JSON.stringify({distinct_id:n,message_id:e}),headers:{...this.authHeaders(),"content-type":"application/json"},method:"POST"});if(!i.ok)throw new c(`mark-read request failed with status ${i.status}`,i.status)}requireFetch(){if(!this.fetch)throw new c("no fetch implementation available in this runtime");return this.fetch}authHeaders(){return {authorization:`Bearer ${this.projectKey}`}}async request(e,n,r){let s=h(),i=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{return await e(n,{...r,signal:s?.signal})}finally{i!==void 0&&clearTimeout(i);}}};var N=class{constructor(e,n){this.maxSize=e;this.onOverflow=n;o(this,"events",[]);}get size(){return this.events.length}enqueue(e){this.events.push(e),this.enforceCap();}restore(e){this.events.push(...e),this.enforceCap();}requeue(e){this.events.unshift(...e),this.enforceCap();}drain(e){let n=e===void 0?this.events.length:Math.min(e,this.events.length);return this.events.splice(0,n)}snapshot(){return [...this.events]}enforceCap(){if(this.events.length<=this.maxSize)return;let e=this.events.splice(0,this.events.length-this.maxSize);this.onOverflow?.({dropped:e});}};function fe(t){return t>=400&&t<500&&t!==429}var k=class{constructor(e={}){o(this,"fetch");o(this,"maxRetries");o(this,"requestTimeoutMs");o(this,"baseDelayMs");o(this,"maxDelayMs");o(this,"sleep");o(this,"random");this.fetch=d(e.fetch),this.maxRetries=e.maxRetries??3,this.requestTimeoutMs=e.requestTimeoutMs??1e4,this.baseDelayMs=e.baseDelayMs??500,this.maxDelayMs=e.maxDelayMs??3e4,this.sleep=e.sleep??U,this.random=e.random??Math.random;}async send(e){let n=this.fetch;if(!n)throw new c("no fetch implementation available in this runtime");let r=JSON.stringify(e.body),s;for(let i=0;i<=this.maxRetries;i+=1){try{let a=await this.attempt(n,e,r);if(a.ok)return;if(fe(a.status))throw new c(`ingest rejected batch with status ${a.status}`,a.status);s=new c(`ingest transient status ${a.status}`,a.status);}catch(a){if(a instanceof c&&a.status!==void 0&&fe(a.status))throw a;s=a;}i<this.maxRetries&&await this.sleep(this.backoff(i));}throw new c("ingest delivery failed after retries",void 0,{cause:s})}async attempt(e,n,r){let s=h(),i=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{return await e(n.url,{body:r,headers:{authorization:`Bearer ${n.projectKey}`,"content-type":"application/json"},method:"POST",signal:s?.signal})}finally{i!==void 0&&clearTimeout(i);}}backoff(e){return Math.min(this.maxDelayMs,this.baseDelayMs*2**e)+this.random()*this.baseDelayMs}};var Ke="queue",De=1e3,me=3e4,ge=t=>{let e={};return t.avatar!==void 0&&(e.$avatar=t.avatar),t.email!==void 0&&(e.$email=t.email),t.name!==void 0&&(e.$name=t.name),t.phone!==void 0&&(e.$phone=t.phone),e},_=class{constructor(e){o(this,"config");o(this,"identity");o(this,"queue");o(this,"transport");o(this,"flagsClient");o(this,"messagesClient");o(this,"context");o(this,"flushTimer");o(this,"flushing",false);o(this,"cachedFlags");o(this,"cachedSnapshot");o(this,"membershipCache");o(this,"stream");o(this,"shutDown",false);o(this,"exposures",new Set);this.config=te(e),this.identity=new C(this.config.storage,this.config.ids,this.config.namespace),this.queue=new N(this.config.maxQueueSize,({dropped:n})=>{this.config.onError(new f("queue_overflow",`event queue overflow: dropped ${n.length} oldest event(s)`));}),this.transport=this.config.transport??new k({maxRetries:this.config.maxRetries,requestTimeoutMs:this.config.requestTimeoutMs}),this.flagsClient=new I({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.messagesClient=new F({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.context={sdk:this.config.sdkName,sdk_version:this.config.sdkVersion},this.config.os&&(this.context.os=this.config.os),this.config.locale&&(this.context.locale=this.config.locale),this.restoreQueue(),this.startTimer();}get distinctId(){return this.identity.getDistinctId()}get anonymousId(){return this.identity.getAnonymousId()}capture(e,n={}){try{let r={...this.config.defaultProperties(),...n.properties??{}},s=ne({context:this.context,distinctId:this.identity.getDistinctId(),eventName:e,properties:r,sessionId:n.sessionId,timestamp:n.timestamp},this.config.clock,this.config.ids);this.enqueue(s);}catch(r){this.config.onError(r);}}identify(e,n={}){let r=this.identity.getAnonymousId(),s=!this.identity.isIdentified(),i=this.identity.identify(e),a={};s&&i.changed&&(a.$anon_distinct_id=r);let l={...ge(n.traits??{}),...n.set??{}};Object.keys(l).length>0&&(a.$set=l),this.capture("$identify",{properties:a});}alias(e){this.capture("$create_alias",{properties:{alias:e}});}group(e,n,r){let s={$group_key:n,$group_type:e};r&&(s.$set=r),this.capture("$group",{properties:s});}setPersonProperties(e,n){let r={};e&&(r.$set=e),n&&(r.$set_once=n),this.capture("$set",{properties:r});}setPersonTraits(e){let n=ge(e);Object.keys(n).length!==0&&this.capture("$set",{properties:{$set:n}});}async getAllFlags(){let e=this.identity.getDistinctId(),n=await this.flagsClient.fetchDecisions(e);return this.cachedFlags={distinctId:e,flags:n.flags,variants:n.variants??{}},n.flags}async isFeatureEnabled(e){let r=(await this.getAllFlags())[e]??false;return this.recordExposure(e,this.cachedFlags?.variants[e]?.key??String(r)),r}async getVariant(e){let n=await this.getAllFlags(),r=this.cachedFlags?.variants[e]??null;return this.recordExposure(e,r?.key??String(n[e]??false)),r}async getVariantLocal(e,n={}){let r=await this.flagSnapshot(),s=r.flags.find(u=>u.key===e),i=await this.localContext(n,r.flags),a=s?V(s,r.flags,i):null,l=s?S(s,r.flags,i).enabled:false;return this.recordExposure(e,a?.key??String(l)),a?{key:a.key,value:a.value}:null}recordExposure(e,n){let r=`${this.identity.getDistinctId()} ${e} ${n}`;this.exposures.has(r)||(this.exposures.add(r),this.capture("$feature_flag_called",{properties:{$feature_flag:e,$feature_flag_response:n}}));}getCachedFlag(e){if(!(!this.cachedFlags||this.cachedFlags.distinctId!==this.distinctId))return this.cachedFlags.flags[e]}async getLocalFlags(e={}){let n=await this.flagSnapshot();return ce(n.flags,await this.localContext(e,n.flags))}async isFeatureEnabledLocal(e,n={}){let r=await this.flagSnapshot(),s=r.flags.find(l=>l.key===e),i=await this.localContext(n,r.flags),a=s?S(s,r.flags,i).enabled:false;return this.recordExposure(e,(s?V(s,r.flags,i)?.key:void 0)??String(a)),a}async localContext(e,n){let r=this.identity.getDistinctId(),s=e.cohorts;if(s===void 0&&ue(n)){let i=this.config.clock.now().getTime();this.membershipCache&&this.membershipCache.distinctId===r&&i-this.membershipCache.fetchedAt<me?s=this.membershipCache.cohorts:(s=await this.flagsClient.memberships(r),this.membershipCache={cohorts:s,distinctId:r,fetchedAt:i});}return {attributes:e.attributes,cohorts:s,distinctId:r,properties:e.properties}}async flagSnapshot(){let e=this.config.clock.now().getTime();if(this.cachedSnapshot&&e-this.cachedSnapshot.fetchedAt<me)return this.cachedSnapshot.snapshot;let n=await this.flagsClient.snapshot();return this.cachedSnapshot={fetchedAt:e,snapshot:n},this.maybeStream(n),n}maybeStream(e){if(!this.config.streamFlags||this.shutDown||this.stream||!e.socketUrl)return;let n=new w({host:e.socketUrl,onChange:()=>{this.cachedSnapshot=void 0,this.flagSnapshot().catch(r=>this.config.onError(r));},onClosed:r=>{this.stream=void 0,r&&this.maybeStream(e);},projectKey:this.config.apiKey,socketFactory:this.config.socketFactory});this.stream=n,n.open();}async getInbox(){return this.messagesClient.inbox(this.identity.getDistinctId())}async markMessageRead(e){await this.messagesClient.markRead(e,this.identity.getDistinctId());}async flush(){if(this.flushing||this.queue.size===0)return;this.flushing=true;let e=this.queue.drain(De);try{await this.transport.send({body:{events:e,sent_at:E(this.config.clock.now())},projectKey:this.config.apiKey,url:`${this.config.host}/v1/events`}),this.persistQueue();}catch(n){this.queue.requeue(e),this.persistQueue(),this.config.onError(n);}finally{this.flushing=false;}}reset(){this.identity.reset(),this.cachedFlags=void 0,this.cachedSnapshot=void 0,this.membershipCache=void 0;}async shutdown(){this.shutDown=true,this.stopTimer(),this.stream?.close(),this.stream=void 0,await this.flush();}enqueue(e){this.queue.enqueue(e),this.persistQueue(),this.queue.size>=this.config.flushAt&&this.flush();}persistQueue(){try{this.config.storage.setItem(this.persistKey(),JSON.stringify(this.queue.snapshot()));}catch(e){this.config.onError(e);}}restoreQueue(){try{let e=this.config.storage.getItem(this.persistKey());if(!e)return;let n=JSON.parse(e);Array.isArray(n)&&this.queue.restore(n);}catch(e){this.config.onError(e);}}startTimer(){if(this.config.flushIntervalMs<=0)return;let e=setInterval(()=>{this.flush();},this.config.flushIntervalMs),n=e;typeof n.unref=="function"&&n.unref(),this.flushTimer=e;}stopTimer(){this.flushTimer!==void 0&&(clearInterval(this.flushTimer),this.flushTimer=void 0);}persistKey(){return `pdx.${this.config.namespace}.${Ke}`}};function ye(){return globalThis.location}function ve(){return globalThis.document}function Ve(){return globalThis.window??globalThis}function je(t){return typeof t=="object"&&t!==null&&typeof t.tagName=="string"}function ke(){let t=ye(),e=ve(),n={};return t&&(n.$current_url=t.href,n.$pathname=t.pathname,n.$host=t.host),e&&(e.title&&(n.$title=e.title),e.referrer&&(n.$referrer=e.referrer)),n}function He(t){let e={$el_tag:t.tagName.toLowerCase(),$event_type:"click"},n=t.textContent?.trim();n&&(e.$el_text=n.slice(0,255)),t.id&&(e.$el_id=t.id),typeof t.className=="string"&&t.className&&(e.$el_classes=t.className);let r=t.getAttribute("href");return r&&(e.$el_href=r),e}function ze(t){let e=globalThis.history,n=Ve(),r="",s=()=>{let l=ye(),u=l?`${l.pathname}${l.search}`:"";u!==r&&(r=u,t.capture("$pageview",{properties:ke()}));};if(s(),!e||!n)return ()=>{};let i=e.pushState.bind(e),a=e.replaceState.bind(e);return e.pushState=(...l)=>{i(...l),s();},e.replaceState=(...l)=>{a(...l),s();},n.addEventListener("popstate",s),()=>{e.pushState=i,e.replaceState=a,n.removeEventListener("popstate",s);}}function Ue(t){let e=ve();if(!e)return ()=>{};let n=r=>{let s=r.target;je(s)&&t.capture("$autocapture",{properties:{...ke(),...He(s)}});};return e.addEventListener("click",n,true),()=>e.removeEventListener("click",n,true)}function be(t,e={}){let n=[];return (e.pageviews??true)&&n.push(ze(t)),(e.clicks??true)&&n.push(Ue(t)),()=>{for(let r of n)r();}}function Ge(){return globalThis.document?.visibilityState==="hidden"}function Be(t){let e=globalThis.navigator,n=globalThis.Blob;if(!e?.sendBeacon||!n)return false;let r=JSON.stringify({...t.body,api_key:t.projectKey});try{let s=new n([r],{type:"application/json"});return e.sendBeacon(t.url,s)}catch{return false}}var P=class{constructor(e={}){o(this,"fetchTransport");this.fetchTransport=new k(e);}async send(e){Ge()&&Be(e)||await this.fetchTransport.send(e);}};var xe={maskAllInputs:true,maskAllText:false},Je=new Set(["email","password","tel"]);function Ee(t){return t.replace(/\S/g,"*")}function R(t,e,n){return We(e)||n.maskAllInputs?Ee(t):t}function O(t,e){return e.maskAllText?Ee(t):t}function We(t){return Je.has((t??"").toLowerCase())}var Qe=5e3,A=class{constructor(e){this.options=e;o(this,"buffer",[]);o(this,"seq",0);o(this,"maxEvents");this.maxEvents=Math.min(Math.max(1,e.maxEvents),Qe);}add(e){return this.buffer.push(e),this.buffer.length>=this.maxEvents?this.flush():null}flush(){if(this.buffer.length===0)return null;let e=this.buffer;this.buffer=[];let n={distinct_id:this.options.distinctId(),events:e,masked:this.options.masked,schema_version:1,seq:this.seq,session_id:this.options.sessionId,timestamp:new Date(this.options.now()).toISOString()};return this.seq+=1,n}};var H=1,z=3,Xe=9,L=class{constructor(){o(this,"next",1);}allocate(){let e=this.next;return this.next+=1,e}},Ye=new Set(["NOSCRIPT","SCRIPT"]);function M(t,e,n,r){if(t.nodeType===z){let s=e.allocate();return r?.(t,s),{id:s,textContent:O(t.textValue??"",n),type:"text"}}if(t.nodeType===Xe){let s=e.allocate();return r?.(t,s),{childNodes:Te(t,e,n,r),id:s,type:"document"}}if(t.nodeType===H){let s=t.tagName??"";if(Ye.has(s))return null;let i=e.allocate();return r?.(t,i),{attributes:Ze(t,n),childNodes:Te(t,e,n,r),id:i,tagName:s,type:"element"}}return null}function Te(t,e,n,r){let s=[];for(let i of t.childNodes??[]){let a=M(i,e,n,r);a&&s.push(a);}return s}function Ze(t,e){let n={};for(let r of t.attributes??[])n[r.name]=r.value;return t.inputValue!==void 0&&(n.value=R(t.inputValue,t.inputType,e)),n}async function Se(t,e){let n=`${p(e.replayHost)}/v1/replay`;return (await e.fetch(n,{body:JSON.stringify(t),headers:{authorization:`Bearer ${e.apiKey}`,"content-type":"application/json"},method:"POST"})).ok}var we=new Set(["INPUT","SELECT","TEXTAREA"]),$=class{constructor(e){this.options=e;o(this,"allocator",new L);o(this,"mirror",new Map);o(this,"chunker");o(this,"fetchImpl");o(this,"observer");o(this,"timer");o(this,"started",false);this.chunker=new A({distinctId:e.distinctId,masked:e.mask.maskAllInputs,maxEvents:e.maxEvents,now:e.now,sessionId:e.sessionId}),this.fetchImpl=d(e.fetch);}start(){if(this.started)return;let e=et(),n=e?.documentElement;!e||!n||!this.fetchImpl||(this.started=true,this.captureFullSnapshot(n),this.observeMutations(n),this.observeInteractions(e),this.timer=setInterval(()=>this.upload(this.chunker.flush()),this.options.flushIntervalMs));}stop(){this.started&&(this.started=false,this.observer?.disconnect(),this.timer&&clearInterval(this.timer),this.upload(this.chunker.flush()));}captureFullSnapshot(e){let n=M(this.adapt(e),this.allocator,this.options.mask,(r,s)=>{let i=r.ref;i&&this.mirror.set(i,s);});n&&this.push(2,{node:n});}observeMutations(e){let n=globalThis.MutationObserver;n&&(this.observer=new n(r=>{for(let s of r)this.handleMutation(s);}),this.observer.observe(e,{attributes:true,characterData:true,childList:true,subtree:true}));}handleMutation(e){if(e.type==="characterData"){let n=this.mirror.get(e.target);n!==void 0&&this.push(3,{texts:[{id:n,value:O(e.target.textContent??"",this.options.mask)}]});return}if(e.type==="attributes"&&e.attributeName){let n=this.mirror.get(e.target),r=e.target;n!==void 0&&this.push(3,{attributes:[{attributes:{[e.attributeName]:r.getAttribute(e.attributeName)??""},id:n}]});return}if(e.type==="childList"){let n=this.mirror.get(e.target);if(n===void 0)return;for(let r of Array.from(e.addedNodes)){let s=M(this.adapt(r),this.allocator,this.options.mask,(i,a)=>{let l=i.ref;l&&this.mirror.set(l,a);});s&&this.push(3,{adds:[{node:s,parentId:n}]});}for(let r of Array.from(e.removedNodes)){let s=this.mirror.get(r);s!==void 0&&(this.push(3,{removes:[{id:s,parentId:n}]}),this.mirror.delete(r));}}}observeInteractions(e){e.addEventListener("input",n=>{let r=n.target;if(!r||!we.has(r.tagName))return;let s=this.mirror.get(r);s!==void 0&&this.push(3,{input:{id:s,value:R(r.value??"",r.type,this.options.mask)}});},true),e.addEventListener("scroll",n=>{let r=n.target,s=r?this.mirror.get(r):void 0;this.push(3,{scroll:{id:s??0,x:r?.scrollLeft??0,y:r?.scrollTop??0}});},true);}adapt(e){let n={childNodes:[],nodeType:e.nodeType,ref:e};if(e.nodeType===z)return n.textValue=e.textContent??"",n;if(e.nodeType===H){let r=e;if(n.tagName=r.tagName,n.attributes=Array.from(r.attributes).map(s=>({name:s.name,value:s.value})),we.has(r.tagName)){let s=r;n.inputType=s.type,n.inputValue=s.value??"";}}return n.childNodes=Array.from(e.childNodes).map(r=>this.adapt(r)),n}push(e,n){let r=this.chunker.add({data:n,timestamp:this.options.now(),type:e});r&&this.upload(r);}upload(e){!e||!this.fetchImpl||Se(e,{apiKey:this.options.apiKey,fetch:this.fetchImpl,replayHost:this.options.replayHost}).catch(n=>this.options.onError?.(n));}};function et(){return globalThis.document}function Ie(t){let e=new $({apiKey:t.apiKey,distinctId:t.distinctId,flushIntervalMs:t.flushIntervalMs??5e3,mask:{...xe,...t.mask},maxEvents:t.maxEvents??200,now:t.now??(()=>Date.now()),onError:t.onError,replayHost:t.replayHost,sessionId:t.sessionId??q()});return e.start(),e}function tt(){return globalThis.navigator}function nt(t){let e=t?.userAgentData?.platform??t?.platform;return e?e.slice(0,50):void 0}function rt(t){let e=()=>{t.flush();};globalThis.document?.addEventListener?.("visibilitychange",e),globalThis.addEventListener?.("pagehide",e);}function Kn(t){let{autocaptureOptions:e,replayHost:n,sessionReplay:r,sessionReplayOptions:s,...i}=t,a=tt(),l={...i,locale:i.locale??(a?.language?a.language.slice(0,20):void 0),os:i.os??nt(a),storage:i.storage??G(),transport:i.transport??new P({maxRetries:i.maxRetries,requestTimeoutMs:i.requestTimeoutMs})},u=new _(l);return rt(u),(t.autocapture??true)&&be(u,e),r&&n&&Ie({apiKey:l.apiKey,distinctId:()=>u.distinctId,onError:l.onError,replayHost:n,...s}),u}exports.WebTransport=P;exports.createWebClient=Kn;exports.installAutocapture=be;exports.installSessionReplay=Ie;//# sourceMappingURL=web.cjs.map
1
+ 'use strict';var ct=Object.defineProperty;var dt=(t,e,n)=>e in t?ct(t,e,{enumerable:true,configurable:true,writable:true,value:n}):t[e]=n;var o=(t,e,n)=>dt(t,typeof e!="symbol"?e+"":e,n);var g=class extends Error{constructor(n,r,i){super(r,i);o(this,"code");this.code=n,this.name="ProdantixError";}},x=class extends g{constructor(e){super("config",e),this.name="ConfigError";}},v=class extends g{constructor(n,r){super("validation",r);o(this,"field");this.field=n,this.name="ValidationError";}},d=class extends g{constructor(n,r,i){super("transport",n,i);o(this,"status");this.status=r,this.name="TransportError";}};function p(t){if(t)return t;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function h(){let t=globalThis.AbortController;return t?new t:void 0}var fe=t=>new Promise(e=>{setTimeout(e,t);});function l(t){return t.replace(/\/+$/,"")}var k=class{constructor(){o(this,"store",new Map);}getItem(e){return this.store.get(e)??null}removeItem(e){this.store.delete(e);}setItem(e,n){this.store.set(e,n);}};function ge(){try{let t=globalThis.localStorage;if(t){let e="__pdx_probe__";return t.setItem(e,"1"),t.removeItem(e),t}}catch{return new k}return new k}var C={now:()=>new Date};function T(t){return t.toISOString()}function lt(){return globalThis.crypto}function ut(t){t[6]=t[6]&15|64,t[8]=t[8]&63|128;let e=[];for(let n=0;n<16;n+=1)e.push(t[n].toString(16).padStart(2,"0"));return `${e[0]}${e[1]}${e[2]}${e[3]}-${e[4]}${e[5]}-${e[6]}${e[7]}-${e[8]}${e[9]}-${e[10]}${e[11]}${e[12]}${e[13]}${e[14]}${e[15]}`}function W(){let t=lt();if(t?.randomUUID)return t.randomUUID();let e=new Uint8Array(16);if(t?.getRandomValues)t.getRandomValues(e);else for(let n=0;n<16;n+=1)e[n]=Math.floor(Math.random()*256);return ut(e)}var me={uuid:W};var pt=/^pdx_pub_(?:(?:live|test)_)?[a-z0-9]{32}$/;var ht=/^(?:\$|[a-z])[a-z0-9_.]*$/;function w(t){let e=0;for(let n of t)e+=1;return e}function ye(t){return pt.test(t)}function ft(t){return ht.test(t)}function ve(t){let e=w(t);if(e<1||e>200)throw new v("distinct_id","distinct_id must be between 1 and 200 characters")}function ke(t){let e=w(t);if(e<1||e>200)throw new v("event_name","event_name must be between 1 and 200 characters");if(!ft(t))throw new v("event_name","event_name must match /^(\\$|[a-z])[a-z0-9_.]*$/")}var be="prodantix-js",xe="0.0.1";var gt=t=>{};function Se(t){if(!t.apiKey||!ye(t.apiKey))throw new x("apiKey must be a public project key of the form pdx_pub_<32 lowercase alphanumerics>");if(!t.host)throw new x("host is required (the ingest base URL)");let e=l(t.host),n=t.defaultProperties,r=t.storage??new k;return {apiKey:t.apiKey,autocapture:t.autocapture??false,clock:t.clock??C,consent:t.consent,defaultProperties:typeof n=="function"?n:()=>n??{},flagsHost:t.flagsHost?l(t.flagsHost):e,flushAt:t.flushAt??20,flushIntervalMs:t.flushIntervalMs??1e4,host:e,ids:t.ids??me,locale:t.locale,maxQueueSize:t.maxQueueSize??1e3,maxRetries:t.maxRetries??3,namespace:A(t.apiKey),onError:t.onError??gt,os:t.os,requestTimeoutMs:t.requestTimeoutMs??1e4,sdkName:t.sdkName??be,sdkVersion:t.sdkVersion??xe,sessionTracking:t.sessionTracking??false,sharedStorage:t.sharedStorage??r,socketFactory:t.socketFactory,storage:r,streamFlags:t.streamFlags??false,transport:t.transport}}function A(t){return t.slice(0,16)}function Ee(t,e,n){ke(t.eventName),ve(t.distinctId);let r={distinct_id:t.distinctId,event_id:t.eventId??n.uuid(),event_name:t.eventName,properties:t.properties??{},schema_version:1,timestamp:T(t.timestamp??e.now())};return t.context&&(r.context=t.context),t.sessionId&&(r.session_id=t.sessionId),r}var y=Symbol("absent");function mt(t,e){if(t==="distinct_id")return e.distinctId;let n=e.properties??{};if(Object.prototype.hasOwnProperty.call(n,t))return n[t];let r=e.attributes??{};return Object.prototype.hasOwnProperty.call(r,t)?r[t]:y}function m(t){return t===y?"undefined":String(t)}function Ie(t){return t===y?Number.NaN:Number(t)}function Ce(t){return t!==y&&t!==null&&t!==""}function Te(t,e){if(!Array.isArray(e))return false;let n=m(t);return e.map(r=>String(r)).includes(n)}function we(t,e){let n=mt(t.attribute,e),r=t.value;switch(t.op){case "is_set":return Ce(n);case "is_not_set":return !Ce(n);case "eq":return m(n)===m(r===void 0?y:r);case "neq":return m(n)!==m(r===void 0?y:r);case "contains":return m(n).includes(m(r===void 0?y:r));case "in":return Te(n,r);case "not_in":return Array.isArray(r)?!Te(n,r):false;case "gt":return _(n,r,(i,s)=>i>s);case "gte":return _(n,r,(i,s)=>i>=s);case "lt":return _(n,r,(i,s)=>i<s);case "lte":return _(n,r,(i,s)=>i<=s);case "in_cohort":return typeof r=="string"&&r!==""&&(e.cohorts??[]).includes(r);case "not_in_cohort":return typeof r=="string"&&r!==""&&!(e.cohorts??[]).includes(r);default:return false}}function _(t,e,n){let r=Ie(t),i=e===void 0?Number.NaN:Ie(e);return Number.isNaN(r)||Number.isNaN(i)?false:n(r,i)}function Ae(t,e){let n=`${t}:${e}`,r=2166136261;for(let i=0;i<n.length;i++)r^=n.charCodeAt(i),r=Math.imul(r,16777619);return (r>>>0)%100}function Q(t,e){return t.targeting.length===0||t.targeting.every(n=>we(n,e))}function _e(t,e){let n=Ae(t.key,e.distinctId),r=t.variations??[];if(r.length===0)return t.rolloutPercentage>=100||n<t.rolloutPercentage?"true":"false";let i=0;for(let s=r.length-1;s>=0;s--)if(i+=r[s].weight,n<i)return r[s].key;return r[0].key}function X(t,e,n,r){for(let i of t.prerequisites??[]){if(r.includes(i.flagKey))return false;let s=e.find(c=>c.key===i.flagKey);if(!s||!s.enabled)return false;r.push(s.key);let a=X(s,e,n,r)&&Q(s,n)&&_e(s,n)===i.variationKey;if(r.pop(),!a)return false}return true}function F(t,e,n){return t.enabled?X(t,e,n,[t.key])?Q(t,n)?t.rolloutPercentage>=100?{enabled:true,reason:"rollout_full"}:Ae(t.key,n.distinctId)<t.rolloutPercentage?{enabled:true,reason:"rollout"}:{enabled:false,reason:"rollout_excluded"}:{enabled:false,reason:"targeting"}:{enabled:false,reason:"prerequisite"}:{enabled:false,reason:"disabled"}}function Fe(t,e){let n={};for(let r of t)n[r.key]=F(r,t,e).enabled;return n}function Y(t,e,n){let r=t.variations??[],i=r[0];if(!i)return null;if(!t.enabled||!X(t,e,n,[t.key])||!Q(t,n))return i;let s=_e(t,n);return r.find(a=>a.key===s)??i}function Ne(t){return t.some(e=>e.targeting.some(n=>n.op==="in_cohort"||n.op==="not_in_cohort"))}function Le(t){return `40${JSON.stringify(t)}`}function Re(){return "3"}function Pe(t){let e=t.charAt(0),n=t.slice(1);if(e==="2")return {kind:"ping"};if(e==="1")return {kind:"disconnect"};if(e==="0"){let a=Z(n);return {kind:"open",pingInterval:typeof a?.pingInterval=="number"?a.pingInterval:25e3,pingTimeout:typeof a?.pingTimeout=="number"?a.pingTimeout:2e4}}if(e!=="4")return {kind:"other"};let r=n.charAt(0),i=n.slice(1);if(r==="0")return {kind:"connected"};if(r==="1")return {kind:"disconnect"};if(r==="4"){let a=Z(i);return {kind:"connectError",message:typeof a?.message=="string"?a.message:"refused"}}if(r!=="2")return {kind:"other"};let s=Z(i);return !Array.isArray(s)||typeof s[0]!="string"?{kind:"other"}:{kind:"event",name:s[0],payload:s[1]}}function Z(t){try{return JSON.parse(t)}catch{return null}}var yt="/socket.io/?EIO=4&transport=websocket",vt=250,N=class{constructor(e){this.options=e;o(this,"socket",null);o(this,"heartbeat",null);o(this,"pending",null);o(this,"lastKey","");o(this,"ready",false);o(this,"closed",false);o(this,"heartbeatWindow",45e3);o(this,"factory");o(this,"setTimer");o(this,"clearTimer");this.factory=e.socketFactory??kt,this.setTimer=e.setTimer??((n,r)=>setTimeout(n,r)),this.clearTimer=e.clearTimer??(n=>clearTimeout(n));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${yt}`,n;try{n=this.factory(e);}catch{this.options.onClosed(false);return}this.socket=n,n.onmessage=r=>this.receive(String(r.data)),n.onerror=()=>n.close(),n.onclose=()=>this.fell();}close(){this.closed=true,this.stopHeartbeat(),this.pending!==null&&this.clearTimer(this.pending),this.pending=null;let e=this.socket;this.socket=null,e?.close();}receive(e){let n=Pe(e);if(n.kind==="open"){this.armHeartbeat(n.pingInterval+n.pingTimeout),this.socket?.send(Le({projectKey:this.options.projectKey}));return}if(n.kind==="ping"){this.armHeartbeat(),this.socket?.send(Re());return}if(n.kind==="connectError"||n.kind==="disconnect"){this.stopHeartbeat(),this.socket?.close();return}if(n.kind==="event"){if(n.name==="ready"){this.ready=true;return}if(n.name==="flagChange"){let r=n.payload?.key;this.lastKey=typeof r=="string"?r:"",this.pending===null&&(this.pending=this.setTimer(()=>{this.pending=null,this.options.onChange(this.lastKey);},vt));}}}fell(){this.stopHeartbeat();let e=this.ready;this.socket=null,this.ready=false,this.closed||this.options.onClosed(e);}armHeartbeat(e){e!==void 0&&(this.heartbeatWindow=e),this.stopHeartbeat(),this.heartbeat=this.setTimer(()=>this.socket?.close(),this.heartbeatWindow);}stopHeartbeat(){this.heartbeat!==null&&this.clearTimer(this.heartbeat),this.heartbeat=null;}};function kt(t){let e=globalThis.WebSocket;if(!e)throw new Error("no WebSocket");return new e(t)}var L=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=p(e.fetch),this.host=l(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async fetchAll(e){return (await this.fetchDecisions(e)).flags}async fetchDecisions(e){let n=this.fetch;if(!n)throw new d("no fetch implementation available in this runtime");let r=`${this.host}/v1/flags?distinct_id=${encodeURIComponent(e)}`,i=h(),s=i?setTimeout(()=>i.abort(),this.requestTimeoutMs):void 0;try{let a=await n(r,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:i?.signal});if(!a.ok)throw new d(`flags request failed with status ${a.status}`,a.status);let c=JSON.parse(await a.text());return {flags:c.flags??{},variants:c.variants??{}}}finally{s!==void 0&&clearTimeout(s);}}async snapshot(){let e=this.fetch;if(!e)throw new d("no fetch implementation available in this runtime");let n=`${this.host}/v1/flags/snapshot`,r=h(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let s=await e(n,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!s.ok)throw new d(`flag snapshot request failed with status ${s.status}`,s.status);let a=JSON.parse(await s.text()),c={flags:a.flags??[],generatedAt:a.generatedAt};return typeof a.socketUrl=="string"&&a.socketUrl!==""&&(c.socketUrl=a.socketUrl),c}finally{i!==void 0&&clearTimeout(i);}}async memberships(e){let n=this.fetch;if(!n)throw new d("no fetch implementation available in this runtime");let r=`${this.host}/v1/flags/memberships?distinct_id=${encodeURIComponent(e)}`,i=h(),s=i?setTimeout(()=>i.abort(),this.requestTimeoutMs):void 0;try{let a=await n(r,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:i?.signal});if(!a.ok)throw new d(`memberships request failed with status ${a.status}`,a.status);return JSON.parse(await a.text()).cohorts??[]}finally{s!==void 0&&clearTimeout(s);}}};function S(t){if(typeof t!="string")return;let e=Array.from(t).length;return e>=1&&e<=200?t:void 0}function P(t,e){return `pdx.${t}.${e}`}var Oe="consent";function bt(t){if(typeof t!="string")return null;try{let e=JSON.parse(t);if(e===null||typeof e!="object"||Array.isArray(e))return null;let n=e.identityLink;return typeof n=="boolean"?{identityLink:n}:null}catch{return null}}function xt(t,e){return bt(t.getItem(P(e,Oe)))}function St(t,e,n){let r=P(e,Oe);if(typeof n.identityLink!="boolean"){t.removeItem(r);return}t.setItem(r,JSON.stringify({identityLink:n.identityLink}));}function Me(t,e,n,r){let i=P(n,"anonymous_id"),s=S(e.getItem(i))??S(t.getItem(i));return e.setItem(i,r),t.setItem(i,r),s!==void 0&&s!==r?s:void 0}var R=class{constructor(e,n,r,i){this.storage=e;this.shared=n;this.ids=r;this.namespace=i;o(this,"anonymousId");o(this,"distinctId");o(this,"identified");this.refresh();}refresh(){let e=S(this.shared.getItem(this.key("anonymous_id"))),n=S(this.storage.getItem(this.key("anonymous_id")));e?(this.anonymousId=e,n!==e&&this.storage.setItem(this.key("anonymous_id"),e)):n?(this.anonymousId=n,this.shared.setItem(this.key("anonymous_id"),n)):(this.anonymousId=this.ids.uuid(),this.shared.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.setItem(this.key("anonymous_id"),this.anonymousId));let r=S(this.storage.getItem(this.key("distinct_id")));r?(this.distinctId=r,this.identified=true):(this.distinctId=this.anonymousId,this.identified=false);}getAnonymousId(){return this.anonymousId}getDistinctId(){return this.distinctId}isIdentified(){return this.identified}snapshot(){return {anonymousId:this.anonymousId,distinctId:this.distinctId,identified:this.identified}}consent(){return xt(this.shared,this.namespace)}setConsent(e){St(this.shared,this.namespace,e);}identify(e){let n=!this.identified||this.distinctId!==e,r=this.storage.getItem(this.key("linked_anonymous_id")),i=n||r!==this.anonymousId;return this.distinctId=e,this.identified=true,n&&this.storage.setItem(this.key("distinct_id"),e),!i||this.consent()?.identityLink===false?{changed:n}:(this.storage.setItem(this.key("linked_anonymous_id"),this.anonymousId),{anonymousToLink:this.anonymousId,changed:n})}reset(){this.anonymousId=this.ids.uuid(),this.distinctId=this.anonymousId,this.identified=false,this.shared.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.removeItem(this.key("distinct_id")),this.storage.removeItem(this.key("linked_anonymous_id"));}key(e){return P(this.namespace,e)}};var O=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=p(e.fetch),this.host=l(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async inbox(e){let n=this.requireFetch(),r=`${this.host}/v1/messages?distinct_id=${encodeURIComponent(e)}`,i=await this.request(n,r,{headers:this.authHeaders(),method:"GET"});if(!i.ok)throw new d(`inbox request failed with status ${i.status}`,i.status);return JSON.parse(await i.text()).messages??[]}async markRead(e,n){let r=this.requireFetch(),i=`${this.host}/v1/messages/read`,s=await this.request(r,i,{body:JSON.stringify({distinct_id:n,message_id:e}),headers:{...this.authHeaders(),"content-type":"application/json"},method:"POST"});if(!s.ok)throw new d(`mark-read request failed with status ${s.status}`,s.status)}requireFetch(){if(!this.fetch)throw new d("no fetch implementation available in this runtime");return this.fetch}authHeaders(){return {authorization:`Bearer ${this.projectKey}`}}async request(e,n,r){let i=h(),s=i?setTimeout(()=>i.abort(),this.requestTimeoutMs):void 0;try{return await e(n,{...r,signal:i?.signal})}finally{s!==void 0&&clearTimeout(s);}}};var M=class{constructor(e,n){this.maxSize=e;this.onOverflow=n;o(this,"events",[]);}get size(){return this.events.length}enqueue(e){this.events.push(e),this.enforceCap();}restore(e){this.events.push(...e),this.enforceCap();}requeue(e){this.events.unshift(...e),this.enforceCap();}drain(e){let n=e===void 0?this.events.length:Math.min(e,this.events.length);return this.events.splice(0,n)}snapshot(){return [...this.events]}enforceCap(){if(this.events.length<=this.maxSize)return;let e=this.events.splice(0,this.events.length-this.maxSize);this.onOverflow?.({dropped:e});}};var Et={idleMs:18e5,maxMs:864e5,throttleMs:1e4};function $e(t){return `pdx.${t}.session`}function De(t,e,n,r){let i={id:n.id,lastActivityAt:r,startedAt:n.startedAt};t.setItem($e(e),JSON.stringify(i));}var $=class{constructor(e,n,r,i,s=Et){this.storage=e;this.ids=n;this.clock=r;this.namespace=i;this.options=s;}current(){return this.touch().id}startedAt(){return this.touch().startedAt}reset(){this.storage.removeItem(this.key());}touch(){let e=this.clock.now().getTime(),n=this.live(this.read(),e);if(n===void 0)return this.write({id:this.ids.uuid(),lastActivityAt:e,startedAt:e});if(e-n.lastActivityAt<=this.options.throttleMs)return n;let r=this.live(this.read(),e),i=r!==void 0&&r.id!==n.id?r:n;return this.write({...i,lastActivityAt:e})}live(e,n){if(e!==void 0&&!(n-e.lastActivityAt>this.options.idleMs||n-e.startedAt>this.options.maxMs))return e}write(e){return this.storage.setItem(this.key(),JSON.stringify(e)),e}read(){let e=this.storage.getItem(this.key());if(e)try{let n=JSON.parse(e);return typeof n.id=="string"&&typeof n.startedAt=="number"&&typeof n.lastActivityAt=="number"?{id:n.id,lastActivityAt:n.lastActivityAt,startedAt:n.startedAt}:void 0}catch{return}}key(){return $e(this.namespace)}};function qe(t){return t>=400&&t<500&&t!==429}var b=class{constructor(e={}){o(this,"fetch");o(this,"maxRetries");o(this,"requestTimeoutMs");o(this,"baseDelayMs");o(this,"maxDelayMs");o(this,"sleep");o(this,"random");this.fetch=p(e.fetch),this.maxRetries=e.maxRetries??3,this.requestTimeoutMs=e.requestTimeoutMs??1e4,this.baseDelayMs=e.baseDelayMs??500,this.maxDelayMs=e.maxDelayMs??3e4,this.sleep=e.sleep??fe,this.random=e.random??Math.random;}async send(e){let n=this.fetch;if(!n)throw new d("no fetch implementation available in this runtime");let r=JSON.stringify(e.body),i;for(let s=0;s<=this.maxRetries;s+=1){try{let a=await this.attempt(n,e,r);if(a.ok)return;if(qe(a.status))throw new d(`ingest rejected batch with status ${a.status}`,a.status);i=new d(`ingest transient status ${a.status}`,a.status);}catch(a){if(a instanceof d&&a.status!==void 0&&qe(a.status))throw a;i=a;}s<this.maxRetries&&await this.sleep(this.backoff(s));}throw new d("ingest delivery failed after retries",void 0,{cause:i})}async attempt(e,n,r){let i=h(),s=i?setTimeout(()=>i.abort(),this.requestTimeoutMs):void 0;try{return await e(n.url,{body:r,headers:{authorization:`Bearer ${n.projectKey}`,"content-type":"application/json"},method:"POST",signal:i?.signal})}finally{s!==void 0&&clearTimeout(s);}}backoff(e){return Math.min(this.maxDelayMs,this.baseDelayMs*2**e)+this.random()*this.baseDelayMs}};var It="queue",Ct=1e3,Ke=3e4,ee=t=>{let e={};return t.avatar!==void 0&&(e.$avatar=t.avatar),t.email!==void 0&&(e.$email=t.email),t.name!==void 0&&(e.$name=t.name),t.phone!==void 0&&(e.$phone=t.phone),e},D=class{constructor(e){o(this,"config");o(this,"identity");o(this,"session");o(this,"queue");o(this,"transport");o(this,"flagsClient");o(this,"messagesClient");o(this,"context");o(this,"flushTimer");o(this,"flushing",false);o(this,"cachedFlags");o(this,"cachedSnapshot");o(this,"membershipCache");o(this,"stream");o(this,"shutDown",false);o(this,"exposures",new Set);this.config=Se(e),this.identity=new R(this.config.storage,this.config.sharedStorage,this.config.ids,this.config.namespace),this.config.consent!==void 0&&this.identity.setConsent(this.config.consent),this.session=this.config.sessionTracking?new $(this.config.sharedStorage,this.config.ids,this.config.clock,this.config.namespace):void 0,this.queue=new M(this.config.maxQueueSize,({dropped:n})=>{this.config.onError(new g("queue_overflow",`event queue overflow: dropped ${n.length} oldest event(s)`));}),this.transport=this.config.transport??new b({maxRetries:this.config.maxRetries,requestTimeoutMs:this.config.requestTimeoutMs}),this.flagsClient=new L({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.messagesClient=new O({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.context={sdk:this.config.sdkName,sdk_version:this.config.sdkVersion},this.config.os&&(this.context.os=this.config.os),this.config.locale&&(this.context.locale=this.config.locale),this.restoreQueue(),this.startTimer();}get distinctId(){return this.identity.getDistinctId()}get anonymousId(){return this.identity.getAnonymousId()}get isIdentified(){return this.identity.isIdentified()}get sessionId(){return this.session?.current()}get sessionStartedAt(){return this.session?.startedAt()}capture(e,n={}){try{this.identity.refresh();let r={...this.config.defaultProperties(),...n.properties??{}},i=Ee({context:this.context,distinctId:n.distinctId??this.identity.getDistinctId(),eventName:e,properties:r,sessionId:n.sessionId??this.session?.current(),timestamp:n.timestamp},this.config.clock,this.config.ids);this.enqueue(i);}catch(r){this.config.onError(r);}}identify(e,n={}){this.identity.refresh();let r=this.identity.identify(e),i={};r.anonymousToLink!==void 0&&(i.$anon_distinct_id=r.anonymousToLink);let s={...ee(n.traits??{}),...n.set??{}};Object.keys(s).length>0&&(i.$set=s),this.capture("$identify",{properties:i});}link(e,n,r){let i={$anon_distinct_id:n},s=ee(r??{});Object.keys(s).length>0&&(i.$set=s),this.capture("$identify",{distinctId:e,properties:i});}setConsent(e){this.identity.setConsent(e);}consent(){return this.identity.consent()}alias(e){this.capture("$create_alias",{properties:{alias:e}});}group(e,n,r){let i={$group_key:n,$group_type:e};r&&(i.$set=r),this.capture("$group",{properties:i});}setPersonProperties(e,n){let r={};e&&(r.$set=e),n&&(r.$set_once=n),this.capture("$set",{properties:r});}setPersonTraits(e){let n=ee(e);Object.keys(n).length!==0&&this.capture("$set",{properties:{$set:n}});}async getAllFlags(){let e=this.identity.getDistinctId(),n=await this.flagsClient.fetchDecisions(e);return this.cachedFlags={distinctId:e,flags:n.flags,variants:n.variants??{}},n.flags}async isFeatureEnabled(e){let r=(await this.getAllFlags())[e]??false;return this.recordExposure(e,this.cachedFlags?.variants[e]?.key??String(r)),r}async getVariant(e){let n=await this.getAllFlags(),r=this.cachedFlags?.variants[e]??null;return this.recordExposure(e,r?.key??String(n[e]??false)),r}async getVariantLocal(e,n={}){let r=await this.flagSnapshot(),i=r.flags.find(u=>u.key===e),s=await this.localContext(n,r.flags),a=i?Y(i,r.flags,s):null,c=i?F(i,r.flags,s).enabled:false;return this.recordExposure(e,a?.key??String(c)),a?{key:a.key,value:a.value}:null}recordExposure(e,n){let r=`${this.identity.getDistinctId()} ${e} ${n}`;this.exposures.has(r)||(this.exposures.add(r),this.capture("$feature_flag_called",{properties:{$feature_flag:e,$feature_flag_response:n}}));}getCachedFlag(e){if(!(!this.cachedFlags||this.cachedFlags.distinctId!==this.distinctId))return this.cachedFlags.flags[e]}async getLocalFlags(e={}){let n=await this.flagSnapshot();return Fe(n.flags,await this.localContext(e,n.flags))}async isFeatureEnabledLocal(e,n={}){let r=await this.flagSnapshot(),i=r.flags.find(c=>c.key===e),s=await this.localContext(n,r.flags),a=i?F(i,r.flags,s).enabled:false;return this.recordExposure(e,(i?Y(i,r.flags,s)?.key:void 0)??String(a)),a}async localContext(e,n){let r=this.identity.getDistinctId(),i=e.cohorts;if(i===void 0&&Ne(n)){let s=this.config.clock.now().getTime();this.membershipCache&&this.membershipCache.distinctId===r&&s-this.membershipCache.fetchedAt<Ke?i=this.membershipCache.cohorts:(i=await this.flagsClient.memberships(r),this.membershipCache={cohorts:i,distinctId:r,fetchedAt:s});}return {attributes:e.attributes,cohorts:i,distinctId:r,properties:e.properties}}async flagSnapshot(){let e=this.config.clock.now().getTime();if(this.cachedSnapshot&&e-this.cachedSnapshot.fetchedAt<Ke)return this.cachedSnapshot.snapshot;let n=await this.flagsClient.snapshot();return this.cachedSnapshot={fetchedAt:e,snapshot:n},this.maybeStream(n),n}maybeStream(e){if(!this.config.streamFlags||this.shutDown||this.stream||!e.socketUrl)return;let n=new N({host:e.socketUrl,onChange:()=>{this.cachedSnapshot=void 0,this.flagSnapshot().catch(r=>this.config.onError(r));},onClosed:r=>{this.stream=void 0,r&&this.maybeStream(e);},projectKey:this.config.apiKey,socketFactory:this.config.socketFactory});this.stream=n,n.open();}async getInbox(){return this.messagesClient.inbox(this.identity.getDistinctId())}async markMessageRead(e){await this.messagesClient.markRead(e,this.identity.getDistinctId());}async flush(){if(this.flushing||this.queue.size===0)return;this.flushing=true;let e=this.queue.drain(Ct);try{await this.transport.send({body:{events:e,sent_at:T(this.config.clock.now())},projectKey:this.config.apiKey,url:`${this.config.host}/v1/events`}),this.persistQueue();}catch(n){this.queue.requeue(e),this.persistQueue(),this.config.onError(n);}finally{this.flushing=false;}}reset(){this.session?.reset(),this.identity.reset(),this.cachedFlags=void 0,this.cachedSnapshot=void 0,this.membershipCache=void 0;}async shutdown(){this.shutDown=true,this.stopTimer(),this.stream?.close(),this.stream=void 0,await this.flush();}enqueue(e){this.queue.enqueue(e),this.persistQueue(),this.queue.size>=this.config.flushAt&&this.flush();}persistQueue(){try{this.config.storage.setItem(this.persistKey(),JSON.stringify(this.queue.snapshot()));}catch(e){this.config.onError(e);}}restoreQueue(){try{let e=this.config.storage.getItem(this.persistKey());if(!e)return;let n=JSON.parse(e);Array.isArray(n)&&this.queue.restore(n);}catch(e){this.config.onError(e);}}startTimer(){if(this.config.flushIntervalMs<=0)return;let e=setInterval(()=>{this.flush();},this.config.flushIntervalMs),n=e;typeof n.unref=="function"&&n.unref(),this.flushTimer=e;}stopTimer(){this.flushTimer!==void 0&&(clearInterval(this.flushTimer),this.flushTimer=void 0);}persistKey(){return `pdx.${this.config.namespace}.${It}`}};function Ve(){return globalThis.location}function je(){return globalThis.document}function Tt(){return globalThis.window??globalThis}function wt(t){return typeof t=="object"&&t!==null&&typeof t.tagName=="string"}function He(){let t=Ve(),e=je(),n={};return t&&(n.$current_url=t.href,n.$pathname=t.pathname,n.$host=t.host),e&&(e.title&&(n.$title=e.title),e.referrer&&(n.$referrer=e.referrer)),n}function At(t){let e={$el_tag:t.tagName.toLowerCase(),$event_type:"click"},n=t.textContent?.trim();n&&(e.$el_text=n.slice(0,255)),t.id&&(e.$el_id=t.id),typeof t.className=="string"&&t.className&&(e.$el_classes=t.className);let r=t.getAttribute("href");return r&&(e.$el_href=r),e}function _t(t){let e=globalThis.history,n=Tt(),r="",i=()=>{let c=Ve(),u=c?`${c.pathname}${c.search}`:"";u!==r&&(r=u,t.capture("$pageview",{properties:He()}));};if(i(),!e||!n)return ()=>{};let s=e.pushState.bind(e),a=e.replaceState.bind(e);return e.pushState=(...c)=>{s(...c),i();},e.replaceState=(...c)=>{a(...c),i();},n.addEventListener("popstate",i),()=>{e.pushState=s,e.replaceState=a,n.removeEventListener("popstate",i);}}function Ft(t){let e=je();if(!e)return ()=>{};let n=r=>{let i=r.target;wt(i)&&t.capture("$autocapture",{properties:{...He(),...At(i)}});};return e.addEventListener("click",n,true),()=>e.removeEventListener("click",n,true)}function Ue(t,e={}){let n=[];return (e.pageviews??true)&&n.push(_t(t)),(e.clicks??true)&&n.push(Ft(t)),()=>{for(let r of n)r();}}function Nt(){return globalThis.document?.visibilityState==="hidden"}function Lt(t){let e=globalThis.navigator,n=globalThis.Blob;if(!e?.sendBeacon||!n)return false;let r=JSON.stringify({...t.body,api_key:t.projectKey});try{let i=new n([r],{type:"application/json"});return e.sendBeacon(t.url,i)}catch{return false}}var q=class{constructor(e={}){o(this,"fetchTransport");this.fetchTransport=new b(e);}async send(e){Nt()&&Lt(e)||await this.fetchTransport.send(e);}};var Rt=/^\d{1,3}(\.\d{1,3}){3}$/,Pt=/^[a-z0-9.-]+$/i;function Je(){return Math.random().toString(36).slice(2,12)}function K(t,e){let n=`${e}=`,r=[];for(let i of t.cookie.split(";")){let s=i.trim();s.startsWith(n)&&r.push(s.slice(n.length));}return r}function E(t,e,n){let r=["Path=/",`Max-Age=${e}`,"SameSite=Lax"];return t&&r.push(`Domain=${t}`),n&&r.push("Secure"),r.join("; ")}function ze(t,e,n,r){try{let i=`pdx_probe_${r()}`,s=r();t.cookie=`${i}=${s}; ${E(e,60,n)}`;let a=K(t,i).includes(s);t.cookie=`${i}=; ${E(e,0,n)}`;let c=K(t,i).includes(s);return a&&!c}catch{return false}}function ne(t){let e=t.replace(/^\[|\]$/g,"").toLowerCase();if(e.includes(":")||Rt.test(e)||!e.includes("."))return [];let n=e.split("."),r=[];for(let i=n.length-2;i>=0;i-=1)r.push(n.slice(i).join("."));return r}function Ge(t,e,n,r=Je){for(let i of ne(t))if(ze(e,i,n,r))return i}function Ot(t){let e=new Map,n=JSON.parse(decodeURIComponent(t));if(n===null||typeof n!="object"||Array.isArray(n))return e;for(let[r,i]of Object.entries(n))typeof i=="string"&&e.set(r,i);return e}var te=class{constructor(e,n,r,i){this.jar=e;this.name=n;this.domain=r;this.secure=i;}getItem(e){return this.read().get(e)??null}setItem(e,n){let r=this.read();r.set(e,n),this.write(r);}removeItem(e){let n=this.read();n.delete(e)&&this.write(n);}read(){try{let e=K(this.jar,this.name);e.length>1&&this.domain&&(this.jar.cookie=`${this.name}=; ${E(void 0,0,this.secure)}`,e=K(this.jar,this.name));let n=e[0];return n?Ot(n):new Map}catch{return new Map}}write(e){try{if(e.size===0){this.jar.cookie=`${this.name}=; ${E(this.domain,0,this.secure)}`;return}let n=encodeURIComponent(JSON.stringify(Object.fromEntries(e)));this.jar.cookie=`${this.name}=${n}; ${E(this.domain,31536e3,this.secure)}`;}catch{return}}};function Mt(){return globalThis.document}function $t(){return globalThis.location?.hostname??""}function Dt(){return globalThis.location?.protocol==="https:"}function qt(t){if(t===void 0)return;let e=t.startsWith(".")?t.slice(1):t;return Pt.test(e)?e.toLowerCase():void 0}function re(t){let e="jar"in t?t.jar:Mt();if(!e||globalThis.navigator?.cookieEnabled===false)return null;let r=t.random??Je,i=t.secure??Dt(),s=t.hostname??$t();try{let a=qt(t.domain)??Ge(s,e,i,r);return ze(e,a,i,r)?new te(e,t.name,a,i):null}catch{return null}}var Qe="_pdx",Xe="~",Kt=200,Vt=/^\d+$/;function Ye(t,e,n,r){let i=Ht(t.href);if(i===void 0||se(i.search).some(oe))return;let s=Be(i.hostname,n);s===void 0||s===Be(r,n)||(i.search=`${i.search}${i.search?"&":"?"}${Qe}=${jt(e)}`,t.href=i.href);}function jt(t){return [t.anonymousId,t.sessionId,String(t.sessionStartedAt)].map(Jt).join(Xe)}function Ze(t){let e=se(t).find(oe);if(e===void 0)return;let n=Ut(e).split(Xe);if(n.length!==3)return;let r=V(n[0]),i=V(n[1]),s=V(n[2]);if(!(!We(r)||!We(i)||!zt(s)))return {anonymousId:r,sessionId:i,sessionStartedAt:Number(s)}}function et(t,e){let n=se(e.search),r=n.filter(s=>!oe(s));if(r.length===n.length)return;let i=r.length>0?`?${r.join("&")}`:"";t.replaceState(t.state,"",`${e.pathname}${i}${e.hash}`);}function tt(t){if(t.location===void 0||typeof t.location.search!="string")return;let e=Ze(t.location.search);if(e===void 0)return;let n=Me(t.storage,t.shared,t.namespace,e.anonymousId);return De(t.shared,t.namespace,{id:e.sessionId,startedAt:e.sessionStartedAt},t.now),t.history!==void 0&&et(t.history,t.location),n}function ie(t,e,n){if(n.length===0)return ()=>{};let r=i=>{let s=Wt(i.target);if(s===void 0)return;let a=Gt(e);a!==void 0&&Ye(s,a,n,t.location?.hostname??"");};return t.addEventListener("click",r,true),t.addEventListener("auxclick",r,true),()=>{t.removeEventListener("click",r,true),t.removeEventListener("auxclick",r,true);}}function Ht(t){try{let e=new URL(t);return e.protocol==="http:"||e.protocol==="https:"?e:void 0}catch{return}}function Be(t,e){let n=e.map(r=>r.replace(/^\./,"").toLowerCase());return ne(t).find(r=>n.includes(r))}function se(t){return t.replace(/^\?/,"").split("&").filter(e=>e!=="")}function oe(t){let e=t.indexOf("=");return V(e===-1?t:t.slice(0,e))===Qe}function Ut(t){let e=t.indexOf("=");return e===-1?"":t.slice(e+1)}function Jt(t){return encodeURIComponent(t).replace(/~/g,"%7E")}function V(t){try{return decodeURIComponent(t)}catch{return}}function We(t){if(t===void 0)return false;let e=w(t);return e>=1&&e<=Kt}function zt(t){return t!==void 0&&Vt.test(t)&&Number.isSafeInteger(Number(t))}function Gt(t){if(t.consent?.()?.identityLink===false)return;let e=t.sessionId,n=t.sessionStartedAt;if(!(e===void 0||n===void 0))return {anonymousId:t.anonymousId,sessionId:e,sessionStartedAt:n}}function Bt(t){return typeof t.tagName=="string"&&t.tagName.toUpperCase()==="A"&&typeof t.href=="string"}function Wt(t){let e=typeof t=="object"?t:null;for(;e;){if(Bt(e))return e;e=e.parentElement??null;}}var nt={maskAllInputs:true,maskAllText:false},Qt=new Set(["email","password","tel"]);function rt(t){return t.replace(/\S/g,"*")}function j(t,e,n){return Xt(e)||n.maskAllInputs?rt(t):t}function H(t,e){return e.maskAllText?rt(t):t}function Xt(t){return Qt.has((t??"").toLowerCase())}var Yt=5e3,U=class{constructor(e){this.options=e;o(this,"buffer",[]);o(this,"seq",0);o(this,"maxEvents");this.maxEvents=Math.min(Math.max(1,e.maxEvents),Yt);}add(e){return this.buffer.push(e),this.buffer.length>=this.maxEvents?this.flush():null}flush(){if(this.buffer.length===0)return null;let e=this.buffer;this.buffer=[];let n={distinct_id:this.options.distinctId(),events:e,masked:this.options.masked,schema_version:1,seq:this.seq,session_id:this.options.sessionId,timestamp:new Date(this.options.now()).toISOString()};return this.seq+=1,n}};var ae=1,ce=3,Zt=9,J=class{constructor(){o(this,"next",1);}allocate(){let e=this.next;return this.next+=1,e}},en=new Set(["NOSCRIPT","SCRIPT"]);function z(t,e,n,r){if(t.nodeType===ce){let i=e.allocate();return r?.(t,i),{id:i,textContent:H(t.textValue??"",n),type:"text"}}if(t.nodeType===Zt){let i=e.allocate();return r?.(t,i),{childNodes:it(t,e,n,r),id:i,type:"document"}}if(t.nodeType===ae){let i=t.tagName??"";if(en.has(i))return null;let s=e.allocate();return r?.(t,s),{attributes:tn(t,n),childNodes:it(t,e,n,r),id:s,tagName:i,type:"element"}}return null}function it(t,e,n,r){let i=[];for(let s of t.childNodes??[]){let a=z(s,e,n,r);a&&i.push(a);}return i}function tn(t,e){let n={};for(let r of t.attributes??[])n[r.name]=r.value;return t.inputValue!==void 0&&(n.value=j(t.inputValue,t.inputType,e)),n}async function st(t,e){let n=`${l(e.replayHost)}/v1/replay`;return (await e.fetch(n,{body:JSON.stringify(t),headers:{authorization:`Bearer ${e.apiKey}`,"content-type":"application/json"},method:"POST"})).ok}var ot=new Set(["INPUT","SELECT","TEXTAREA"]),G=class{constructor(e){this.options=e;o(this,"allocator",new J);o(this,"mirror",new Map);o(this,"chunker");o(this,"fetchImpl");o(this,"observer");o(this,"timer");o(this,"started",false);this.chunker=new U({distinctId:e.distinctId,masked:e.mask.maskAllInputs,maxEvents:e.maxEvents,now:e.now,sessionId:e.sessionId}),this.fetchImpl=p(e.fetch);}start(){if(this.started)return;let e=nn(),n=e?.documentElement;!e||!n||!this.fetchImpl||(this.started=true,this.captureFullSnapshot(n),this.observeMutations(n),this.observeInteractions(e),this.timer=setInterval(()=>this.upload(this.chunker.flush()),this.options.flushIntervalMs));}stop(){this.started&&(this.started=false,this.observer?.disconnect(),this.timer&&clearInterval(this.timer),this.upload(this.chunker.flush()));}captureFullSnapshot(e){let n=z(this.adapt(e),this.allocator,this.options.mask,(r,i)=>{let s=r.ref;s&&this.mirror.set(s,i);});n&&this.push(2,{node:n});}observeMutations(e){let n=globalThis.MutationObserver;n&&(this.observer=new n(r=>{for(let i of r)this.handleMutation(i);}),this.observer.observe(e,{attributes:true,characterData:true,childList:true,subtree:true}));}handleMutation(e){if(e.type==="characterData"){let n=this.mirror.get(e.target);n!==void 0&&this.push(3,{texts:[{id:n,value:H(e.target.textContent??"",this.options.mask)}]});return}if(e.type==="attributes"&&e.attributeName){let n=this.mirror.get(e.target),r=e.target;n!==void 0&&this.push(3,{attributes:[{attributes:{[e.attributeName]:r.getAttribute(e.attributeName)??""},id:n}]});return}if(e.type==="childList"){let n=this.mirror.get(e.target);if(n===void 0)return;for(let r of Array.from(e.addedNodes)){let i=z(this.adapt(r),this.allocator,this.options.mask,(s,a)=>{let c=s.ref;c&&this.mirror.set(c,a);});i&&this.push(3,{adds:[{node:i,parentId:n}]});}for(let r of Array.from(e.removedNodes)){let i=this.mirror.get(r);i!==void 0&&(this.push(3,{removes:[{id:i,parentId:n}]}),this.mirror.delete(r));}}}observeInteractions(e){e.addEventListener("input",n=>{let r=n.target;if(!r||!ot.has(r.tagName))return;let i=this.mirror.get(r);i!==void 0&&this.push(3,{input:{id:i,value:j(r.value??"",r.type,this.options.mask)}});},true),e.addEventListener("scroll",n=>{let r=n.target,i=r?this.mirror.get(r):void 0;this.push(3,{scroll:{id:i??0,x:r?.scrollLeft??0,y:r?.scrollTop??0}});},true);}adapt(e){let n={childNodes:[],nodeType:e.nodeType,ref:e};if(e.nodeType===ce)return n.textValue=e.textContent??"",n;if(e.nodeType===ae){let r=e;if(n.tagName=r.tagName,n.attributes=Array.from(r.attributes).map(i=>({name:i.name,value:i.value})),ot.has(r.tagName)){let i=r;n.inputType=i.type,n.inputValue=i.value??"";}}return n.childNodes=Array.from(e.childNodes).map(r=>this.adapt(r)),n}push(e,n){let r=this.chunker.add({data:n,timestamp:this.options.now(),type:e});r&&this.upload(r);}upload(e){!e||!this.fetchImpl||st(e,{apiKey:this.options.apiKey,fetch:this.fetchImpl,replayHost:this.options.replayHost}).catch(n=>this.options.onError?.(n));}};function nn(){return globalThis.document}function at(t){let e=new G({apiKey:t.apiKey,distinctId:t.distinctId,flushIntervalMs:t.flushIntervalMs??5e3,mask:{...nt,...t.mask},maxEvents:t.maxEvents??200,now:t.now??(()=>Date.now()),onError:t.onError,replayHost:t.replayHost,sessionId:t.sessionId??W()});return e.start(),e}function rn(){return globalThis.navigator}function sn(){return globalThis.document}function on(){return globalThis.history}function an(){return globalThis.location}function cn(t){let e=t?.userAgentData?.platform??t?.platform;return e?e.slice(0,50):void 0}function dn(t){let e=()=>{t.flush();};globalThis.document?.addEventListener?.("visibilitychange",e),globalThis.addEventListener?.("pagehide",e);}function ln(t,e,n){try{return re({domain:e,name:`pdx_${A(t)}`})??n}catch{return n}}function ri(t){let{autocaptureOptions:e,cookieDomain:n,linkedDomains:r,replayHost:i,sessionReplay:s,sessionReplayOptions:a,...c}=t,u=rn(),de=ge(),le=c.storage??de,ue=c.sharedStorage??ln(c.apiKey,n,de),pe=tt({history:on(),location:an(),namespace:A(c.apiKey),now:(c.clock??C).now().getTime(),shared:ue,storage:le}),B={...c,locale:c.locale??(u?.language?u.language.slice(0,20):void 0),os:c.os??cn(u),sessionTracking:c.sessionTracking??true,sharedStorage:ue,storage:le,transport:c.transport??new q({maxRetries:c.maxRetries,requestTimeoutMs:c.requestTimeoutMs})},f=new D(B);pe!==void 0&&f.alias(pe),dn(f),(t.autocapture??true)&&Ue(f,e);let he=sn();return he&&r&&ie(he,f,r),s&&i&&at({apiKey:B.apiKey,distinctId:()=>f.distinctId,onError:B.onError,replayHost:i,...a,sessionId:a?.sessionId??f.sessionId}),f}exports.WebTransport=q;exports.createCookieStorage=re;exports.createWebClient=ri;exports.decorateLink=Ye;exports.installAutocapture=Ue;exports.installLinkCarry=ie;exports.installSessionReplay=at;exports.readCarry=Ze;exports.resolveCookieDomain=Ge;exports.stripCarry=et;//# sourceMappingURL=web.cjs.map
2
2
  //# sourceMappingURL=web.cjs.map
package/dist/web.d.cts CHANGED
@@ -1,6 +1,6 @@
1
- import { P as ProdantixClient } from './client-y1xyVF6C.cjs';
2
- import { T as Transport, h as TransportRequest, P as ProdantixConfig } from './types-68Sc11g8.cjs';
3
- import { a as FetchTransportOptions } from './transport-Bj4nXmgt.cjs';
1
+ import { P as ProdantixClient } from './client-BO7f6q5k.cjs';
2
+ import { T as Transport, i as TransportRequest, a as StorageAdapter, b as Consent, P as ProdantixConfig } from './types-DjMXp6Wg.cjs';
3
+ import { a as FetchTransportOptions } from './transport-Cy42FY5A.cjs';
4
4
  import { F as FetchLike } from './http-BCh716Vs.cjs';
5
5
 
6
6
  interface AutocaptureOptions {
@@ -81,11 +81,67 @@ interface SessionReplayOptions {
81
81
  * `stop()` it. A missing `sessionId` gets a fresh v4 uuid. */
82
82
  declare function installSessionReplay(options: SessionReplayOptions): SessionRecorder;
83
83
 
84
+ interface CookieJar {
85
+ cookie: string;
86
+ }
87
+ interface CookieStorageOptions {
88
+ domain?: string;
89
+ hostname?: string;
90
+ jar?: CookieJar;
91
+ name: string;
92
+ random?: () => string;
93
+ secure?: boolean;
94
+ }
95
+ declare function resolveCookieDomain(hostname: string, jar: CookieJar, secure: boolean, random?: () => string): string | undefined;
96
+ declare function createCookieStorage(options: CookieStorageOptions): StorageAdapter | null;
97
+
98
+ interface Carry {
99
+ anonymousId: string;
100
+ sessionId: string;
101
+ sessionStartedAt: number;
102
+ }
103
+ interface AnchorLike {
104
+ href: string;
105
+ }
106
+ interface LocationLike {
107
+ hash: string;
108
+ hostname: string;
109
+ pathname: string;
110
+ search: string;
111
+ }
112
+ interface HistoryLike {
113
+ readonly state: unknown;
114
+ replaceState(data: unknown, unused: string, url?: string | null): void;
115
+ }
116
+ interface DocumentLike {
117
+ addEventListener(type: string, listener: (event: unknown) => void, capture?: boolean): void;
118
+ location?: {
119
+ hostname: string;
120
+ } | null;
121
+ removeEventListener(type: string, listener: (event: unknown) => void, capture?: boolean): void;
122
+ }
123
+ interface CarryClient {
124
+ readonly anonymousId: string;
125
+ consent?(): Consent | null;
126
+ readonly sessionId: string | undefined;
127
+ readonly sessionStartedAt: number | undefined;
128
+ }
129
+ declare function decorateLink(anchor: AnchorLike, carry: Carry, linkedDomains: readonly string[], currentHost: string): void;
130
+ declare function readCarry(search: string): Carry | undefined;
131
+ declare function stripCarry(history: HistoryLike, location: LocationLike): void;
132
+ declare function installLinkCarry(doc: DocumentLike, client: CarryClient, linkedDomains: readonly string[]): () => void;
133
+
84
134
  /** Tunables for the built-in session replay, minus the identity fields
85
135
  * `createWebClient` fills in (apiKey, distinctId, replayHost). */
86
136
  type WebSessionReplayOptions = Pick<SessionReplayOptions, 'flushIntervalMs' | 'mask' | 'maxEvents' | 'sessionId'>;
87
137
  interface WebClientOptions extends ProdantixConfig {
88
138
  autocaptureOptions?: AutocaptureOptions;
139
+ cookieDomain?: string;
140
+ /** Registrable domains whose links carry the visitor's anonymous id and
141
+ * session in a `_pdx` query parameter, because a cookie cannot cross a
142
+ * registrable domain. Empty by default. Readonly so a caller hands over the
143
+ * shared platform list as it is, rather than copying it to satisfy a type. */
144
+ linkedDomains?: readonly string[];
89
145
  /** Host of the recorder service (`eu.replay.prodantix.com`). Required to enable
90
146
  * session replay. */
91
147
  replayHost?: string;
@@ -96,4 +152,4 @@ interface WebClientOptions extends ProdantixConfig {
96
152
  }
97
153
  declare function createWebClient(options: WebClientOptions): ProdantixClient;
98
154
 
99
- export { type AutocaptureOptions, type MaskOptions, type SessionReplayOptions, type WebClientOptions, type WebSessionReplayOptions, WebTransport, createWebClient, installAutocapture, installSessionReplay };
155
+ export { type AutocaptureOptions, type Carry, Consent, type CookieJar, type CookieStorageOptions, type MaskOptions, type SessionReplayOptions, type WebClientOptions, type WebSessionReplayOptions, WebTransport, createCookieStorage, createWebClient, decorateLink, installAutocapture, installLinkCarry, installSessionReplay, readCarry, resolveCookieDomain, stripCarry };