@prodantix/sdk 0.7.0-beta.438 → 0.7.0-beta.440

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.
Files changed (43) hide show
  1. package/dist/chat.cjs +5 -107
  2. package/dist/chat.d.cts +93 -8
  3. package/dist/chat.d.ts +93 -8
  4. package/dist/chat.js +5 -107
  5. package/dist/chunk-L4P6GMBC.js +2 -0
  6. package/dist/client-Cz7M6XJC.d.ts +477 -0
  7. package/dist/client-vogZuHfD.d.cts +477 -0
  8. package/dist/{config-C9Njc6-j.d.ts → config-Dmk59mPh.d.ts} +40 -2
  9. package/dist/{config-CpfUyEw8.d.cts → config-Dxf1vAMu.d.cts} +40 -2
  10. package/dist/consent.iife.js +20 -0
  11. package/dist/ctas.iife.js +37 -0
  12. package/dist/forms.iife.js +16 -0
  13. package/dist/guides.iife.js +3 -0
  14. package/dist/index.cjs +1 -1
  15. package/dist/index.d.cts +5 -4
  16. package/dist/index.d.ts +5 -4
  17. package/dist/index.js +1 -1
  18. package/dist/messenger-help.iife.js +1 -1
  19. package/dist/messenger-tickets.iife.js +3 -0
  20. package/dist/messenger.cjs +1 -1
  21. package/dist/messenger.d.cts +1 -1
  22. package/dist/messenger.d.ts +1 -1
  23. package/dist/messenger.iife.js +5 -107
  24. package/dist/messenger.js +1 -1
  25. package/dist/node.cjs +1 -1
  26. package/dist/node.d.cts +3 -2
  27. package/dist/node.d.ts +3 -2
  28. package/dist/node.js +1 -1
  29. package/dist/pages.iife.js +2 -0
  30. package/dist/prodantix-push-sw.js +3 -0
  31. package/dist/surveys.iife.js +2 -0
  32. package/dist/{transport-DKFvkfX4.d.ts → transport-C4mkCaix.d.ts} +1 -1
  33. package/dist/{transport-DN9pXyrX.d.cts → transport-C9C4hqlF.d.cts} +1 -1
  34. package/dist/{types-Q2VNlJbG.d.cts → types-BUXFV_aE.d.cts} +11 -0
  35. package/dist/{types-Q2VNlJbG.d.ts → types-BUXFV_aE.d.ts} +11 -0
  36. package/dist/web.cjs +36 -1
  37. package/dist/web.d.cts +185 -4
  38. package/dist/web.d.ts +185 -4
  39. package/dist/web.js +36 -1
  40. package/package.json +1 -1
  41. package/dist/chunk-D6PMLUYA.js +0 -2
  42. package/dist/client-CL6Xvhay.d.cts +0 -135
  43. package/dist/client-QyKW0LFW.d.ts +0 -135
@@ -0,0 +1,2 @@
1
+ import {c,a as a$2,b as b$2}from'./chunk-V77KYPOF.js';import {e,h,d as d$1,f as f$1,g as g$1,a as a$1,b as b$1,c as c$1}from'./chunk-ODN4ZELX.js';import {a}from'./chunk-5XGN7UAV.js';var g=class{constructor(){a(this,"store",new Map);}getItem(e){return this.store.get(e)??null}removeItem(e){this.store.delete(e);}setItem(e,t){this.store.set(e,t);}},y=class{constructor(e,t=()=>false){this.real=e;this.passes=t;a(this,"held",new g);a(this,"opened",false);}get isOpen(){return this.opened}open(){this.opened=true;}close(){this.opened=false;}target(e){return this.opened||this.passes(e)?this.real:this.held}getItem(e){return this.target(e).getItem(e)}removeItem(e){this.target(e).removeItem(e);}setItem(e,t){this.target(e).setItem(e,t);}};function Ye(){try{let s=globalThis.localStorage;if(s){let e="__pdx_probe__";return s.setItem(e,"1"),s.removeItem(e),s}}catch{return new g}return new g}var X={now:()=>new Date};function x(s){return s.toISOString()}function Z(){if(typeof window>"u"||typeof Intl>"u")return null;let s=Intl.DateTimeFormat().resolvedOptions().timeZone;return typeof s=="string"&&s!==""?s:null}var Te=/^pdx_pub_(?:(?:live|test)_)?[a-z0-9]{32}$/;var Ee=/^(?:\$|[a-z])[a-z0-9_.]*$/;function ee(s){let e=0;for(let t of s)e+=1;return e}function te(s){return Te.test(s)}function $e(s){return Ee.test(s)}function se(s){let e=ee(s);if(e<1||e>200)throw new c$1("distinct_id","distinct_id must be between 1 and 200 characters")}function ne(s){let e=ee(s);if(e<1||e>200)throw new c$1("event_name","event_name must be between 1 and 200 characters");if(!$e(s))throw new c$1("event_name","event_name must match /^(\\$|[a-z])[a-z0-9_.]*$/")}var re="prodantix-js",ie="0.7.0";function Ae(){return globalThis.crypto}function Pe(s){s[6]=s[6]&15|64,s[8]=s[8]&63|128;let e=[];for(let t=0;t<16;t+=1)e.push(s[t].toString(16).padStart(2,"0"));return `${e[0]}${e[1]}${e[2]}${e[3]}-${e[4]}${e[5]}-${e[6]}${e[7]}-${e[8]}${e[9]}-${e[10]}${e[11]}${e[12]}${e[13]}${e[14]}${e[15]}`}function Re(){let s=Ae();if(s?.randomUUID)return s.randomUUID();let e=new Uint8Array(16);if(s?.getRandomValues)s.getRandomValues(e);else for(let t=0;t<16;t+=1)e[t]=Math.floor(Math.random()*256);return Pe(e)}var oe={uuid:Re};var Me=s=>{};function ae(s){if(!s.apiKey||!te(s.apiKey))throw new b$1("apiKey must be a public project key of the form pdx_pub_<32 lowercase alphanumerics>");if(!s.host)throw new b$1("host is required (the ingest base URL)");let e=h(s.host),t=s.defaultProperties,n=s.storage??new g;return {apiKey:s.apiKey,autocapture:s.autocapture??false,clock:s.clock??X,consent:s.consent,consentMode:s.consentMode,defaultProperties:typeof t=="function"?t:()=>t??{},describeElement:s.describeElement,flagsHost:s.flagsHost?h(s.flagsHost):e,flushAt:s.flushAt??20,flushIntervalMs:s.flushIntervalMs??1e4,host:e,ids:s.ids??oe,locale:s.locale,maxQueueSize:s.maxQueueSize??1e3,maxRetries:s.maxRetries??3,namespace:qe(s.apiKey),onError:s.onError??Me,os:s.os,requestTimeoutMs:s.requestTimeoutMs??1e4,sdkName:s.sdkName??re,sdkVersion:s.sdkVersion??ie,sessionTracking:s.sessionTracking??false,sharedStorage:s.sharedStorage??n,socketFactory:s.socketFactory,storage:n,streamFlags:s.streamFlags??false,transport:s.transport}}function qe(s){return s.slice(0,16)}var f=Symbol("absent");function Ke(s,e){if(s==="distinct_id")return e.distinctId;let t=e.properties??{};if(Object.prototype.hasOwnProperty.call(t,s))return t[s];let n=e.attributes??{};return Object.prototype.hasOwnProperty.call(n,s)?n[s]:f}function m(s){return s===f?"undefined":String(s)}function le(s){return s===f?Number.NaN:Number(s)}function ce(s){return s!==f&&s!==null&&s!==""}function de(s,e){if(!Array.isArray(e))return false;let t=m(s);return e.map(n=>String(n)).includes(t)}function ue(s,e){let t=Ke(s.attribute,e),n=s.value;switch(s.op){case "is_set":return ce(t);case "is_not_set":return !ce(t);case "eq":return m(t)===m(n===void 0?f:n);case "neq":return m(t)!==m(n===void 0?f:n);case "contains":return m(t).includes(m(n===void 0?f:n));case "in":return de(t,n);case "not_in":return Array.isArray(n)?!de(t,n):false;case "gt":return w(t,n,(r,i)=>r>i);case "gte":return w(t,n,(r,i)=>r>=i);case "lt":return w(t,n,(r,i)=>r<i);case "lte":return w(t,n,(r,i)=>r<=i);case "in_cohort":return typeof n=="string"&&n!==""&&(e.cohorts??[]).includes(n);case "not_in_cohort":return typeof n=="string"&&n!==""&&!(e.cohorts??[]).includes(n);default:return false}}function w(s,e,t){let n=le(s),r=e===void 0?Number.NaN:le(e);return Number.isNaN(n)||Number.isNaN(r)?false:t(n,r)}function pe(s,e){let t=`${s}:${e}`,n=2166136261;for(let r=0;r<t.length;r++)n^=t.charCodeAt(r),n=Math.imul(n,16777619);return (n>>>0)%100}function N(s,e){return s.targeting.length===0||s.targeting.every(t=>ue(t,e))}function he(s,e){let t=pe(s.key,e.distinctId),n=s.variations??[];if(n.length===0)return s.rolloutPercentage>=100||t<s.rolloutPercentage?"true":"false";let r=0;for(let i=n.length-1;i>=0;i--)if(r+=n[i].weight,t<r)return n[i].key;return n[0].key}function L(s,e,t,n){for(let r of s.prerequisites??[]){if(n.includes(r.flagKey))return false;let i=e.find(c=>c.key===r.flagKey);if(!i||!i.enabled)return false;n.push(i.key);let a=L(i,e,t,n)&&N(i,t)&&he(i,t)===r.variationKey;if(n.pop(),!a)return false}return true}function v(s,e,t){return s.enabled?L(s,e,t,[s.key])?N(s,t)?s.rolloutPercentage>=100?{enabled:true,reason:"rollout_full"}:pe(s.key,t.distinctId)<s.rolloutPercentage?{enabled:true,reason:"rollout"}:{enabled:false,reason:"rollout_excluded"}:{enabled:false,reason:"targeting"}:{enabled:false,reason:"prerequisite"}:{enabled:false,reason:"disabled"}}function mt(s,e){return v(s,[],e)}function ge(s,e){let t={};for(let n of s)t[n.key]=v(n,s,e).enabled;return t}function b(s,e,t){let n=s.variations??[],r=n[0];if(!r)return null;if(!s.enabled||!L(s,e,t,[s.key])||!N(s,t))return r;let i=he(s,t);return n.find(a=>a.key===i)??r}function ft(s,e){return b(s,[],e)}function yt(s,e,t){let n=s.find(r=>r.key===e);return n?b(n,s,t)?.value??null:null}function me(s){return s.some(e=>e.targeting.some(t=>t.op==="in_cohort"||t.op==="not_in_cohort"))}var _=class{constructor(e$1){a(this,"fetch");a(this,"host");a(this,"projectKey");a(this,"requestTimeoutMs");this.fetch=e(e$1.fetch),this.host=h(e$1.host),this.projectKey=e$1.projectKey,this.requestTimeoutMs=e$1.requestTimeoutMs??1e4;}async fetchAll(e){return (await this.fetchDecisions(e)).flags}async fetchDecisions(e){let t=this.fetch;if(!t)throw new d$1("no fetch implementation available in this runtime");let n=`${this.host}/v1/flags?distinct_id=${encodeURIComponent(e)}`,r=f$1(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let a=await t(n,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!a.ok)throw new d$1(`flags request failed with status ${a.status}`,a.status);let c=JSON.parse(await a.text());return {flags:c.flags??{},variants:c.variants??{}}}finally{i!==void 0&&clearTimeout(i);}}async snapshot(){let e=this.fetch;if(!e)throw new d$1("no fetch implementation available in this runtime");let t=`${this.host}/v1/flags/snapshot`,n=f$1(),r=n?setTimeout(()=>n.abort(),this.requestTimeoutMs):void 0;try{let i=await e(t,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:n?.signal});if(!i.ok)throw new d$1(`flag snapshot request failed with status ${i.status}`,i.status);let a=JSON.parse(await i.text()),c={flags:a.flags??[],generatedAt:a.generatedAt};return typeof a.socketUrl=="string"&&a.socketUrl!==""&&(c.socketUrl=a.socketUrl),c}finally{r!==void 0&&clearTimeout(r);}}async memberships(e){let t=this.fetch;if(!t)throw new d$1("no fetch implementation available in this runtime");let n=`${this.host}/v1/flags/memberships?distinct_id=${encodeURIComponent(e)}`,r=f$1(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let a=await t(n,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!a.ok)throw new d$1(`memberships request failed with status ${a.status}`,a.status);return JSON.parse(await a.text()).cohorts??[]}finally{i!==void 0&&clearTimeout(i);}}};var fe="$survey_shown",ye="$survey_dismissed",ve="$survey_sent",F=class{constructor(e$1){a(this,"fetch");a(this,"host");a(this,"projectKey");a(this,"requestTimeoutMs");this.fetch=e(e$1.fetch),this.host=h(e$1.host),this.projectKey=e$1.projectKey,this.requestTimeoutMs=e$1.requestTimeoutMs??1e4;}async surveys(e,t){let n=this.fetch;if(!n)throw new d$1("no fetch implementation available in this runtime");let r=f$1(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let a=await n(`${this.host}/v1/surveys?distinct_id=${encodeURIComponent(e)}${t?`&lang=${encodeURIComponent(t)}`:""}`,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!a.ok)throw new d$1(`surveys request failed with status ${a.status}`,a.status);return JSON.parse(await a.text()).surveys??[]}finally{i!==void 0&&clearTimeout(i);}}},Oe=864e5,De=s=>`${s.id}:${s.iteration}`;function j(s,e){return s.length===0?true:s.some(t=>{switch(t.matches){case "exact":return e===t.value;case "starts_with":return e.startsWith(t.value);default:return e.includes(t.value)}})}function Ft(s,e,t,n,r){return s.kind!=="popover"||e.settled.includes(De(s))||s.showOnce&&e.settled.some(i=>i.startsWith(`${s.id}:`))||s.waitDays>0&&e.lastShownAt!==void 0&&n-e.lastShownAt<s.waitDays*Oe||s.event&&s.event!==r?false:j(s.urls,t)}function Ne(s,e,t){return s>=(e.minScore??0)&&s<=(e.maxScore??t)}function Ct(s,e,t){let n=e.kind==="nps"?10:e.scale??5,r=e.branches.find(a=>a.choice!=null?t===a.choice:typeof t=="number"&&Ne(t,a,n));if(r)return r.next??null;let i=s.questions.findIndex(a=>a.id===e.id);return s.questions[i+1]?.id??null}function C(s,e){let t={$survey_id:s.id,$survey_iteration:s.iteration,$survey_name:s.name};for(let[n,r]of Object.entries(e))t[`$survey_response_${n}`]=r;return t}var Pt="$guide_shown",Rt="$guide_step_viewed",Mt="$guide_step_missed",qt="$guide_completed",Kt="$guide_dismissed",Ot="$checklist_task_done",I=class{constructor(e$1){a(this,"fetch");a(this,"host");a(this,"projectKey");a(this,"requestTimeoutMs");this.fetch=e(e$1.fetch),this.host=h(e$1.host),this.projectKey=e$1.projectKey,this.requestTimeoutMs=e$1.requestTimeoutMs??1e4;}async guides(e){let t=this.fetch;if(!t)throw new d$1("no fetch implementation available in this runtime");let n=f$1(),r=n?setTimeout(()=>n.abort(),this.requestTimeoutMs):void 0;try{let i=await t(`${this.host}/v1/guides?distinct_id=${encodeURIComponent(e)}`,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:n?.signal});if(!i.ok)throw new d$1(`guides request failed with status ${i.status}`,i.status);return JSON.parse(await i.text()).guides??[]}finally{r!==void 0&&clearTimeout(r);}}},Le=864e5,be=s=>`${s.id}:${s.iteration}`,je=(s,e)=>`${be(s)}:${e}`;function Dt(s,e,t,n,r){return e.settled.includes(be(s))||s.showOnce&&e.settled.some(i=>i.startsWith(`${s.id}:`))||s.kind!=="checklist"&&s.waitDays>0&&e.lastShownAt!==void 0&&n-e.lastShownAt<s.waitDays*Le||s.event&&s.event!==r?false:j(s.urls,t)}var Nt=(s,e)=>s.steps.filter(t=>e.done.includes(je(s,t.id))).map(t=>t.id),Lt=(s,e)=>s.kind==="checklist"?s.steps.find(t=>t.event===e):void 0;function Se(s,e){let t={$guide_id:s.id,$guide_iteration:s.iteration,$guide_name:s.name};return e!==void 0&&(t.$guide_step_id=e),t}function S(s){if(typeof s!="string")return;let e=Array.from(s).length;return e>=1&&e<=200?s:void 0}function E(s,e){return `pdx.${s}.${e}`}var G="consent",Ve=["identityLink","analytics","marketing","functional"];function V(s){if(typeof s!="string")return null;try{let e=JSON.parse(s);if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e,n={};for(let r of Ve){let i=t[r];typeof i=="boolean"&&(n[r]=i);}return typeof t.version=="number"&&Number.isInteger(t.version)&&(n.version=t.version),Array.isArray(t.categories)&&t.categories.every(r=>typeof r=="string")&&(n.categories=t.categories),Object.keys(n).length===0?null:n}catch{return null}}var ke=s=>s.endsWith(`.${G}`);function $(s,e){return V(s.getItem(E(e,G)))}function Ge(s,e,t){let n=E(e,G),r=V(JSON.stringify(t)),i=r===null?null:V(JSON.stringify({...$(s,e)??{},...r}));if(i===null){s.removeItem(n);return}s.setItem(n,JSON.stringify(i));}function Gt(s,e,t,n){let r=E(t,"anonymous_id"),i=S(e.getItem(r))??S(s.getItem(r));return e.setItem(r,n),s.setItem(r,n),i!==void 0&&i!==n?i:void 0}var T=class{constructor(e,t,n,r){this.storage=e;this.shared=t;this.ids=n;this.namespace=r;a(this,"anonymousId");a(this,"distinctId");a(this,"identified");this.refresh();}refresh(){let e=S(this.shared.getItem(this.key("anonymous_id"))),t=S(this.storage.getItem(this.key("anonymous_id")));e?(this.anonymousId=e,t!==e&&this.storage.setItem(this.key("anonymous_id"),e)):t?(this.anonymousId=t,this.shared.setItem(this.key("anonymous_id"),t)):(this.anonymousId=this.ids.uuid(),this.shared.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.setItem(this.key("anonymous_id"),this.anonymousId));let n=S(this.storage.getItem(this.key("distinct_id")));n?(this.distinctId=n,this.identified=true):(this.distinctId=this.anonymousId,this.identified=false);}getAnonymousId(){return this.anonymousId}getDistinctId(){return this.distinctId}isIdentified(){return this.identified}snapshot(){return {anonymousId:this.anonymousId,distinctId:this.distinctId,identified:this.identified}}consent(){return $(this.shared,this.namespace)}setConsent(e){Ge(this.shared,this.namespace,e);}assumeAnonymousId(e){this.anonymousId=e,this.shared.setItem(this.key("anonymous_id"),e),this.storage.setItem(this.key("anonymous_id"),e),this.identified||(this.distinctId=e);}identify(e){let t=!this.identified||this.distinctId!==e,n=this.storage.getItem(this.key("linked_anonymous_id")),r=t||n!==this.anonymousId;return this.distinctId=e,this.identified=true,t&&this.storage.setItem(this.key("distinct_id"),e),!r||this.consent()?.identityLink===false?{changed:t}:(this.storage.setItem(this.key("linked_anonymous_id"),this.anonymousId),{anonymousToLink:this.anonymousId,changed:t})}reset(){this.anonymousId=this.ids.uuid(),this.distinctId=this.anonymousId,this.identified=false,this.shared.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.removeItem(this.key("distinct_id")),this.storage.removeItem(this.key("linked_anonymous_id"));}key(e){return E(this.namespace,e)}};var A=class{constructor(e$1){a(this,"fetch");a(this,"host");a(this,"projectKey");a(this,"requestTimeoutMs");this.fetch=e(e$1.fetch),this.host=h(e$1.host),this.projectKey=e$1.projectKey,this.requestTimeoutMs=e$1.requestTimeoutMs??1e4;}async inbox(e){let t=this.requireFetch(),n=`${this.host}/v1/messages?distinct_id=${encodeURIComponent(e)}`,r=await this.request(t,n,{headers:this.authHeaders(),method:"GET"});if(!r.ok)throw new d$1(`inbox request failed with status ${r.status}`,r.status);return JSON.parse(await r.text()).messages??[]}async markRead(e,t){let n=this.requireFetch(),r=`${this.host}/v1/messages/read`,i=await this.request(n,r,{body:JSON.stringify({distinct_id:t,message_id:e}),headers:{...this.authHeaders(),"content-type":"application/json"},method:"POST"});if(!i.ok)throw new d$1(`mark-read request failed with status ${i.status}`,i.status)}requireFetch(){if(!this.fetch)throw new d$1("no fetch implementation available in this runtime");return this.fetch}authHeaders(){return {authorization:`Bearer ${this.projectKey}`}}async request(e,t,n){let r=f$1(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{return await e(t,{...n,signal:r?.signal})}finally{i!==void 0&&clearTimeout(i);}}};var d={autocapture:"$autocapture",createAlias:"$create_alias",featureFlagCalled:"$feature_flag_called",group:"$group",identify:"$identify",pageleave:"$pageleave",pageview:"$pageview",screen:"$screen",set:"$set"},Ue=[{emittedBy:"web",meaning:"A click anywhere on the page, with the element that was clicked. The web SDK sends it by default; autocapture: false or autocaptureOptions.clicks: false turns it off.",name:d.autocapture,properties:["$event_type","$el_description","$el_description_source","$el_action","$el_tag","$el_text","$el_id","$el_classes","$el_href","$current_url","$pathname","$host","$title","$referrer"]},{emittedBy:"web",meaning:"A page shown, including every client-side navigation the History API makes: one per distinct path and query.",name:d.pageview,properties:["$current_url","$pathname","$host","$title","$referrer"]},{emittedBy:"web",meaning:"A landing page left the visitor's sight, by a tab switch, a closed tab or a navigation away, with the seconds it was in front of them so far. A page returned to and left again sends it again with the larger total.",name:d.pageleave,properties:["$engaged_seconds","$page_id","$page_view_id","$page_variant"]},{emittedBy:"flutter",meaning:"A named route pushed or replaced in a Flutter app, the mobile counterpart of $pageview.",name:d.screen,properties:["screen"]},{emittedBy:"every",meaning:"A person becomes known by a distinct id. The anonymous trail before it is joined to them, and any traits ride along under $set.",name:d.identify,properties:["$anon_distinct_id","$set"]},{emittedBy:"every",meaning:"A second id for the same person, so events sent under either resolve to one profile.",name:d.createAlias,properties:["alias"]},{emittedBy:"every",meaning:"The person is placed in a group such as a company or a team; group properties ride along under $set.",name:d.group,properties:["$group_type","$group_key","$set"]},{emittedBy:"every",meaning:"Person properties written without an identify: $set overwrites, $set_once fills only what is still empty.",name:d.set,properties:["$set","$set_once"]},{emittedBy:"every",meaning:"A flag was evaluated for this person, sent once per distinct answer. Experiments attribute exposure from it.",name:d.featureFlagCalled,properties:["$feature_flag","$feature_flag_response"]}],Wt=s=>s.startsWith("$"),Yt=s=>Ue.find(e=>e.name===s);function xe(s){return s>=400&&s<500&&s!==429}var P=class{constructor(e$1={}){a(this,"fetch");a(this,"maxRetries");a(this,"requestTimeoutMs");a(this,"baseDelayMs");a(this,"maxDelayMs");a(this,"sleep");a(this,"random");this.fetch=e(e$1.fetch),this.maxRetries=e$1.maxRetries??3,this.requestTimeoutMs=e$1.requestTimeoutMs??1e4,this.baseDelayMs=e$1.baseDelayMs??500,this.maxDelayMs=e$1.maxDelayMs??3e4,this.sleep=e$1.sleep??g$1,this.random=e$1.random??Math.random;}async send(e){let t=this.fetch;if(!t)throw new d$1("no fetch implementation available in this runtime");let n=JSON.stringify(e.body),r;for(let i=0;i<=this.maxRetries;i+=1){try{let a=await this.attempt(t,e,n);if(a.ok)return;if(xe(a.status))throw new d$1(`ingest rejected batch with status ${a.status}`,a.status);r=new d$1(`ingest transient status ${a.status}`,a.status);}catch(a){if(a instanceof d$1&&a.status!==void 0&&xe(a.status))throw a;r=a;}i<this.maxRetries&&await this.sleep(this.backoff(i));}throw new d$1("ingest delivery failed after retries",void 0,{cause:r})}async attempt(e,t,n){let r=f$1(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{return await e(t.url,{body:n,headers:{authorization:`Bearer ${t.projectKey}`,"content-type":"application/json"},method:"POST",signal:r?.signal})}finally{i!==void 0&&clearTimeout(i);}}backoff(e){return Math.min(this.maxDelayMs,this.baseDelayMs*2**e)+this.random()*this.baseDelayMs}};var is="$cta_viewed",os="$cta_clicked",as="$cta_dismissed",we=(s,e)=>{let t={$cta_id:s.id,$cta_kind:s.kind,$cta_variant:s.variant.key,$cta_version:s.version},n=e===void 0?void 0:s.variant.content.buttons[e];return n&&e!==void 0&&(t.$cta_button=e,t.$cta_button_label=n.label,n.action.kind==="form"&&(t.$cta_form_id=n.action.value)),t},R=class{constructor(e$1){a(this,"fetch");a(this,"host");a(this,"projectKey");a(this,"requestTimeoutMs");this.fetch=e(e$1.fetch),this.host=h(e$1.host),this.projectKey=e$1.projectKey,this.requestTimeoutMs=e$1.requestTimeoutMs??1e4;}async ctas(e){let t=this.fetch;if(!t)throw new d$1("no fetch implementation available in this runtime");let n=new URLSearchParams({anonymous:String(e.anonymous),device:e.device,distinct_id:e.distinctId,language:e.language,url:e.url}),r=f$1(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let a=await t(`${this.host}/v1/ctas?${n.toString()}`,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(a.status<200||a.status>=300)throw new d$1(`ctas request failed with status ${a.status}`,a.status);return JSON.parse(await a.text()).ctas}finally{i!==void 0&&clearTimeout(i);}}};function _e(s,e,t){ne(s.eventName),se(s.distinctId);let n={distinct_id:s.distinctId,event_id:s.eventId??t.uuid(),event_name:s.eventName,properties:s.properties??{},schema_version:1,timestamp:x(s.timestamp??e.now())};return s.context&&(n.context=s.context),s.sessionId&&(n.session_id=s.sessionId),n}var Be="/socket.io/?EIO=4&transport=websocket",He=250,M=class{constructor(e){this.options=e;a(this,"socket",null);a(this,"heartbeat",null);a(this,"pending",null);a(this,"lastKey","");a(this,"ready",false);a(this,"closed",false);a(this,"heartbeatWindow",45e3);a(this,"factory");a(this,"setTimer");a(this,"clearTimer");this.factory=e.socketFactory??Je,this.setTimer=e.setTimer??((t,n)=>setTimeout(t,n)),this.clearTimer=e.clearTimer??(t=>clearTimeout(t));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${Be}`,t;try{t=this.factory(e);}catch{this.options.onClosed(false);return}this.socket=t,t.onmessage=n=>this.receive(String(n.data)),t.onerror=()=>t.close(),t.onclose=()=>this.fell();}close(){this.closed=true,this.stopHeartbeat(),this.pending!==null&&this.clearTimer(this.pending),this.pending=null;let e=this.socket;this.socket=null,e?.close();}receive(e){let t=c(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),this.socket?.send(a$2({projectKey:this.options.projectKey}));return}if(t.kind==="ping"){this.armHeartbeat(),this.socket?.send(b$2());return}if(t.kind==="connectError"||t.kind==="disconnect"){this.stopHeartbeat(),this.socket?.close();return}if(t.kind==="event"){if(t.name==="ready"){this.ready=true;return}if(t.name==="flagChange"){let n=t.payload?.key;this.lastKey=typeof n=="string"?n:"",this.pending===null&&(this.pending=this.setTimer(()=>{this.pending=null,this.options.onChange(this.lastKey);},He));}}}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 Je(s){let e=globalThis.WebSocket;if(!e)throw new d$1("no WebSocket");return new e(s)}var bs="$form_viewed",Ss="$form_started",U=class extends Error{constructor(t,n,r){super(r);a(this,"fields");a(this,"status");this.name="FormRefusedError",this.status=t,this.fields=n;}},q=class{constructor(e$1){a(this,"fetch");a(this,"host");a(this,"projectKey");a(this,"requestTimeoutMs");this.fetch=e(e$1.fetch),this.host=h(e$1.host),this.projectKey=e$1.projectKey,this.requestTimeoutMs=e$1.requestTimeoutMs??1e4;}async request(e,t){let n=this.fetch;if(!n)throw new d$1("no fetch implementation available in this runtime");let r=f$1(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let a={authorization:`Bearer ${this.projectKey}`};t.body!==void 0&&(a["content-type"]="application/json");let c=await n(`${this.host}${e}`,{body:t.body,headers:a,method:t.method,signal:r?.signal});return {status:c.status,text:await c.text()}}finally{i!==void 0&&clearTimeout(i);}}async form(e,t){let{status:n,text:r}=await this.request(`/v1/forms/${encodeURIComponent(e)}?distinct_id=${encodeURIComponent(t)}`,{method:"GET"});if(n<200||n>=300)throw new d$1(`form request failed with status ${n}`,n);return JSON.parse(r)}async submit(e,t){let{status:n,text:r}=await this.request(`/v1/forms/${encodeURIComponent(e)}/submissions`,{body:JSON.stringify(t),method:"POST"});if(n>=200&&n<300)return JSON.parse(r).afterSubmit;let i=[],a=`form submission failed with status ${n}`;try{let c=JSON.parse(r);i=c.error?.fields??[],a=c.error?.message??a;}catch{i=[];}throw new U(n,i,a)}};var K=class{constructor(e,t){this.maxSize=e;this.onOverflow=t;a(this,"events",[]);}get size(){return this.events.length}enqueue(e){this.events.push(e),this.enforceCap();}restore(e){this.events.push(...e),this.enforceCap();}requeue(e){this.events.unshift(...e),this.enforceCap();}drain(e){let t=e===void 0?this.events.length:Math.min(e,this.events.length);return this.events.splice(0,t)}snapshot(){return [...this.events]}enforceCap(){if(this.events.length<=this.maxSize)return;let e=this.events.splice(0,this.events.length-this.maxSize);this.onOverflow?.({dropped:e});}};var ze={idleMs:18e5,maxMs:864e5,throttleMs:1e4};function Fe(s){return `pdx.${s}.session`}function Fs(s,e,t,n){let r={id:t.id,lastActivityAt:n,startedAt:t.startedAt};s.setItem(Fe(e),JSON.stringify(r));}var O=class{constructor(e,t,n,r,i=ze){this.storage=e;this.ids=t;this.clock=n;this.namespace=r;this.options=i;}current(){return this.touch().id}startedAt(){return this.touch().startedAt}reset(){this.storage.removeItem(this.key());}touch(){let e=this.clock.now().getTime(),t=this.live(this.read(),e);if(t===void 0)return this.write({id:this.ids.uuid(),lastActivityAt:e,startedAt:e});if(e-t.lastActivityAt<=this.options.throttleMs)return t;let n=this.live(this.read(),e),r=n!==void 0&&n.id!==t.id?n:t;return this.write({...r,lastActivityAt:e})}live(e,t){if(e!==void 0&&!(t-e.lastActivityAt>this.options.idleMs||t-e.startedAt>this.options.maxMs))return e}write(e){return this.storage.setItem(this.key(),JSON.stringify(e)),e}read(){let e=this.storage.getItem(this.key());if(e)try{let t=JSON.parse(e);return typeof t.id=="string"&&typeof t.startedAt=="number"&&typeof t.lastActivityAt=="number"?{id:t.id,lastActivityAt:t.lastActivityAt,startedAt:t.startedAt}:void 0}catch{return}}key(){return Fe(this.namespace)}};var Qe="queue",We=1e3,Ce=3e4,B=s=>{let e={};return s.avatar!==void 0&&(e.$avatar=s.avatar),s.email!==void 0&&(e.$email=s.email),s.name!==void 0&&(e.$name=s.name),s.phone!==void 0&&(e.$phone=s.phone),e},H=class{constructor(e){a(this,"config");a(this,"identity");a(this,"session");a(this,"queue");a(this,"transport");a(this,"flagsClient");a(this,"messagesClient");a(this,"surveysClient");a(this,"guidesClient");a(this,"captureListeners",new Set);a(this,"formsClient");a(this,"ctasClient");a(this,"context");a(this,"flushTimer");a(this,"flushing",false);a(this,"cachedFlags");a(this,"cachedSnapshot");a(this,"membershipCache");a(this,"stream");a(this,"shutDown",false);a(this,"exposures",new Set);a(this,"gates");a(this,"cookielessId");a(this,"storageListeners",new Set);let t=ae(e),n=$(t.sharedStorage,t.namespace)??t.consent??null;if(this.gates=[new y(t.storage),new y(t.sharedStorage,ke)],t.consentMode!=="banner"||n?.analytics===true)for(let a of this.gates)a.open();let[r,i]=this.gates;this.config={...t,sharedStorage:i,storage:r},this.identity=new T(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 O(this.config.sharedStorage,this.config.ids,this.config.clock,this.config.namespace):void 0,this.queue=new K(this.config.maxQueueSize,({dropped:a})=>{this.config.onError(new a$1("queue_overflow",`event queue overflow: dropped ${a.length} oldest event(s)`));}),this.transport=this.config.transport??new P({maxRetries:this.config.maxRetries,requestTimeoutMs:this.config.requestTimeoutMs}),this.flagsClient=new _({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.messagesClient=new A({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.surveysClient=new F({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.guidesClient=new I({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.formsClient=new q({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.ctasClient=new R({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.context={sdk:this.config.sdkName,sdk_version:this.config.sdkVersion},this.config.os&&(this.context.os=this.config.os),this.config.locale&&(this.context.locale=this.config.locale),this.restoreQueue(),this.startTimer();}get distinctId(){return this.identity.getDistinctId()}get anonymousId(){return this.identity.getAnonymousId()}get isIdentified(){return this.identity.isIdentified()}get sessionId(){return this.session?.current()}get sessionStartedAt(){return this.session?.startedAt()}capture(e,t={}){try{this.identity.refresh();let n={...this.config.defaultProperties(),...t.element===void 0?{}:this.config.describeElement?.(t.element)??{},...t.properties??{}},r=_e({context:this.context,distinctId:t.distinctId??this.identity.getDistinctId(),eventName:e,properties:n,sessionId:t.sessionId??this.session?.current(),timestamp:t.timestamp},this.config.clock,this.config.ids);this.enqueue(r);}catch(n){this.config.onError(n);}for(let n of this.captureListeners)try{n(e);}catch(r){this.config.onError(r);}}onCapture(e){return this.captureListeners.add(e),()=>{this.captureListeners.delete(e);}}identify(e,t={}){if(this.isCookieless())return;this.identity.refresh();let n=this.identity.identify(e),r={};n.anonymousToLink!==void 0&&(r.$anon_distinct_id=n.anonymousToLink);let i=Z(),a={...i===null?{}:{$timezone:i},...B(t.traits??{}),...t.set??{}};Object.keys(a).length>0&&(r.$set=a),this.capture(d.identify,{properties:r});}link(e,t,n){if(this.isCookieless())return;let r={$anon_distinct_id:t},i=B(n??{});Object.keys(i).length>0&&(r.$set=i),this.capture(d.identify,{distinctId:e,properties:r});}setConsent(e){this.identity.setConsent(e),e.analytics===true&&this.allowStorage(),e.analytics===false&&this.config.consentMode==="banner"&&this.forbidStorage();}isCookieless(){return !this.gates[0].isOpen}takeCookielessId(e){this.cookielessId=e,this.isCookieless()&&this.identity.assumeAnonymousId(e);}allowStorage(){if(this.isCookieless()){for(let e of this.gates)e.open();this.identity.refresh();for(let e of [...this.storageListeners])e();}}onStorageAllowed(e){return this.storageListeners.add(e),()=>{this.storageListeners.delete(e);}}forbidStorage(){if(!this.isCookieless()){for(let e of ["anonymous_id","distinct_id","linked_anonymous_id","session"])this.config.storage.removeItem(`pdx.${this.config.namespace}.${e}`),this.config.sharedStorage.removeItem(`pdx.${this.config.namespace}.${e}`);for(let e of this.gates)e.close();this.identity.refresh(),this.cookielessId!==void 0&&this.identity.assumeAnonymousId(this.cookielessId);}}consent(){return this.identity.consent()}alias(e){this.capture(d.createAlias,{properties:{alias:e}});}group(e,t,n){let r={$group_key:t,$group_type:e};n&&(r.$set=n),this.capture(d.group,{properties:r});}setPersonProperties(e,t){if(this.isCookieless())return;let n={};e&&(n.$set=e),t&&(n.$set_once=t),this.capture(d.set,{properties:n});}setPersonTraits(e){if(this.isCookieless())return;let t=B(e);Object.keys(t).length!==0&&this.capture(d.set,{properties:{$set:t}});}async getAllFlags(){let e=this.identity.getDistinctId(),t=await this.flagsClient.fetchDecisions(e);return this.cachedFlags={distinctId:e,flags:t.flags,variants:t.variants??{}},t.flags}async isFeatureEnabled(e){let n=(await this.getAllFlags())[e]??false;return this.recordExposure(e,this.cachedFlags?.variants[e]?.key??String(n)),n}async getVariant(e){let t=await this.getAllFlags(),n=this.cachedFlags?.variants[e]??null;return this.recordExposure(e,n?.key??String(t[e]??false)),n}async getVariantLocal(e,t={}){let n=await this.flagSnapshot(),r=n.flags.find(Ie=>Ie.key===e),i=await this.localContext(t,n.flags),a=r?b(r,n.flags,i):null,c=r?v(r,n.flags,i).enabled:false;return this.recordExposure(e,a?.key??String(c)),a?{key:a.key,value:a.value}:null}recordExposure(e,t){let n=`${this.identity.getDistinctId()} ${e} ${t}`;this.exposures.has(n)||(this.exposures.add(n),this.capture(d.featureFlagCalled,{properties:{$feature_flag:e,$feature_flag_response:t}}));}getCachedFlag(e){if(!(!this.cachedFlags||this.cachedFlags.distinctId!==this.distinctId))return this.cachedFlags.flags[e]}async getLocalFlags(e={}){let t=await this.flagSnapshot();return ge(t.flags,await this.localContext(e,t.flags))}async isFeatureEnabledLocal(e,t={}){let n=await this.flagSnapshot(),r=n.flags.find(c=>c.key===e),i=await this.localContext(t,n.flags),a=r?v(r,n.flags,i).enabled:false;return this.recordExposure(e,(r?b(r,n.flags,i)?.key:void 0)??String(a)),a}async localContext(e,t){let n=this.identity.getDistinctId(),r=e.cohorts;if(r===void 0&&me(t)){let i=this.config.clock.now().getTime();this.membershipCache&&this.membershipCache.distinctId===n&&i-this.membershipCache.fetchedAt<Ce?r=this.membershipCache.cohorts:(r=await this.flagsClient.memberships(n),this.membershipCache={cohorts:r,distinctId:n,fetchedAt:i});}return {attributes:e.attributes,cohorts:r,distinctId:n,properties:e.properties}}async flagSnapshot(){let e=this.config.clock.now().getTime();if(this.cachedSnapshot&&e-this.cachedSnapshot.fetchedAt<Ce)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 M({host:e.socketUrl,onChange:()=>{this.cachedSnapshot=void 0,this.flagSnapshot().catch(n=>this.config.onError(n));},onClosed:n=>{this.stream=void 0,n&&this.maybeStream(e);},projectKey:this.config.apiKey,socketFactory:this.config.socketFactory});this.stream=t,t.open();}async getInbox(){return this.messagesClient.inbox(this.identity.getDistinctId())}async markMessageRead(e){await this.messagesClient.markRead(e,this.identity.getDistinctId());}async getSurveys(e){return this.surveysClient.surveys(this.identity.getDistinctId(),e??this.config.locale)}captureSurveyShown(e){this.capture(fe,{properties:C(e,{})});}captureSurveyDismissed(e){this.capture(ye,{properties:C(e,{})});}captureSurveySent(e,t){this.capture(ve,{properties:C(e,t)});}async getGuides(){return this.guidesClient.guides(this.identity.getDistinctId())}captureGuide(e,t,n){this.capture(e,{properties:Se(t,n)});}async getForm(e){return this.formsClient.form(e,this.identity.getDistinctId())}async submitForm(e,t,n,r){let{$page_id:i,$page_variant:a}=this.config.defaultProperties();return this.formsClient.submit(e,{answers:t,challenge:n,distinctId:this.identity.getDistinctId(),isAnonymous:!this.identity.isIdentified(),pageUrl:typeof window>"u"?"":window.location.href,solution:r,...typeof i=="string"&&typeof a=="string"?{pageId:i,pageVariant:a}:{}})}async getCtas(e){return this.ctasClient.ctas({...e,anonymous:!this.identity.isIdentified(),distinctId:this.identity.getDistinctId()})}captureCta(e,t,n){this.capture(e,{properties:we(t,n)});}async flush(){if(this.flushing||this.queue.size===0)return;this.flushing=true;let e=this.queue.drain(We);try{await this.transport.send({body:{events:e,sent_at:x(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}.${Qe}`}};function Bs(s){return new H(s)}export{Bs as $,j as A,Ft as B,Ct as C,C as D,Pt as E,Rt as F,Mt as G,qt as H,Kt as I,Ot as J,I as K,be as L,je as M,Dt as N,Nt as O,Lt as P,Se as Q,V as R,Gt as S,A as T,Fs as U,d as V,Ue as W,Wt as X,Yt as Y,P as Z,H as _,g as a,Ye as b,X as c,Re as d,ee as e,re as f,ie as g,qe as h,is as i,os as j,as as k,ue as l,pe as m,mt as n,ge as o,ft as p,yt as q,_ as r,bs as s,Ss as t,U as u,fe as v,ye as w,ve as x,F as y,De as z};//# sourceMappingURL=chunk-L4P6GMBC.js.map
2
+ //# sourceMappingURL=chunk-L4P6GMBC.js.map
@@ -0,0 +1,477 @@
1
+ import { F as FetchLike } from './http-BCh716Vs.js';
2
+ import { e as EventProperties, P as ProdantixConfig, b as Consent, f as FlagVariant, I as InboxMessage } from './types-BUXFV_aE.js';
3
+
4
+ type CtaKind = 'banner' | 'embedded' | 'popup' | 'slide_in';
5
+ type CtaPlacement = 'bottom' | 'bottom_left' | 'bottom_right' | 'top';
6
+ type CtaButtonAction = {
7
+ kind: 'dismiss';
8
+ } | {
9
+ kind: 'form';
10
+ value: string;
11
+ } | {
12
+ kind: 'messenger';
13
+ } | {
14
+ kind: 'url';
15
+ value: string;
16
+ };
17
+ interface CtaButton {
18
+ action: CtaButtonAction;
19
+ label: string;
20
+ }
21
+ interface CtaContent {
22
+ body: string;
23
+ buttons: CtaButton[];
24
+ heading: string;
25
+ image: string;
26
+ imageAlt: string;
27
+ }
28
+ interface CtaStyle {
29
+ background: string;
30
+ button: string;
31
+ buttonText: string;
32
+ radius: number;
33
+ text: string;
34
+ }
35
+ type CtaTrigger = {
36
+ kind: 'click';
37
+ value: string;
38
+ } | {
39
+ kind: 'delay';
40
+ value: number;
41
+ } | {
42
+ kind: 'exit';
43
+ } | {
44
+ kind: 'load';
45
+ } | {
46
+ kind: 'scroll';
47
+ value: number;
48
+ };
49
+ type CtaFrequency = {
50
+ kind: 'days';
51
+ value: number;
52
+ } | {
53
+ kind: 'once';
54
+ } | {
55
+ kind: 'session';
56
+ };
57
+ interface ServedCta {
58
+ flag: {
59
+ key: string;
60
+ variant?: string | null;
61
+ } | null;
62
+ frequency: CtaFrequency;
63
+ goalEvent: string | null;
64
+ id: string;
65
+ kind: CtaKind;
66
+ placement: CtaPlacement;
67
+ /** Whether the CTA carries the "Powered by Prodantix" line. */
68
+ poweredBy: boolean;
69
+ trigger: CtaTrigger;
70
+ /** The one variant this visitor is shown. */
71
+ variant: {
72
+ content: CtaContent;
73
+ key: string;
74
+ style: CtaStyle;
75
+ };
76
+ version: number;
77
+ }
78
+ type CtaDevice = 'desktop' | 'mobile' | 'tablet';
79
+
80
+ type FormFieldKind = 'checkbox' | 'checkboxes' | 'date' | 'dropdown' | 'email' | 'file' | 'hidden' | 'number' | 'phone' | 'radio' | 'rich_text' | 'text' | 'textarea';
81
+ interface FormOption {
82
+ archived?: boolean;
83
+ label: string;
84
+ value: string;
85
+ }
86
+ interface FormCondition {
87
+ field: string;
88
+ op: 'equals' | 'is_set' | 'one_of';
89
+ values: string[];
90
+ }
91
+ interface FormFieldRules {
92
+ maxLength?: number | null;
93
+ maximum?: number | null;
94
+ minLength?: number | null;
95
+ minimum?: number | null;
96
+ }
97
+ type FormHidden = {
98
+ source: 'cookie';
99
+ value: string;
100
+ } | {
101
+ source: 'fixed';
102
+ value: string;
103
+ } | {
104
+ source: 'query';
105
+ value: string;
106
+ };
107
+ interface FormField {
108
+ condition?: FormCondition | null;
109
+ help: string;
110
+ hidden?: FormHidden | null;
111
+ key: string;
112
+ kind: FormFieldKind;
113
+ label: string;
114
+ options: FormOption[];
115
+ placeholder: string;
116
+ required: boolean;
117
+ rules: FormFieldRules;
118
+ }
119
+ interface FormStep {
120
+ fields: FormField[];
121
+ title: string;
122
+ }
123
+ type FormAfterSubmit = {
124
+ kind: 'message';
125
+ value: string;
126
+ } | {
127
+ kind: 'redirect';
128
+ value: string;
129
+ };
130
+ interface FormConsentPurpose {
131
+ key: string;
132
+ label: string;
133
+ notice: string;
134
+ }
135
+ interface FormConsent {
136
+ processing?: string | null;
137
+ purposes: FormConsentPurpose[];
138
+ }
139
+ interface FormStyle {
140
+ background: string;
141
+ button: string;
142
+ buttonText: string;
143
+ fieldBackground: string;
144
+ fieldText: string;
145
+ font: string;
146
+ radius: number;
147
+ text: string;
148
+ width: number;
149
+ }
150
+ interface FormChallenge {
151
+ difficulty: number;
152
+ issuedAt: number;
153
+ nonce: string;
154
+ signature: string;
155
+ }
156
+ interface ServedForm {
157
+ /** Whether the form takes responses this month under the plan. */
158
+ accepting: boolean;
159
+ afterSubmit: FormAfterSubmit;
160
+ challenge: FormChallenge | null;
161
+ consent: FormConsent;
162
+ honeypot: string;
163
+ id: string;
164
+ /** Whether the form carries the "Powered by Prodantix" line. */
165
+ poweredBy: boolean;
166
+ steps: FormStep[];
167
+ style: FormStyle;
168
+ version: number;
169
+ }
170
+
171
+ declare const SURVEY_SHOWN = "$survey_shown";
172
+ declare const SURVEY_DISMISSED = "$survey_dismissed";
173
+ declare const SURVEY_SENT = "$survey_sent";
174
+ type SurveyQuestionKind = 'emoji' | 'link' | 'multiple' | 'nps' | 'open' | 'rating' | 'single';
175
+ interface SurveyBranch {
176
+ choice?: string | null;
177
+ maxScore?: number | null;
178
+ minScore?: number | null;
179
+ next?: string | null;
180
+ }
181
+ interface SurveyQuestion {
182
+ branches: SurveyBranch[];
183
+ choices: string[];
184
+ description?: string | null;
185
+ highLabel?: string | null;
186
+ id: string;
187
+ kind: SurveyQuestionKind;
188
+ link?: string | null;
189
+ lowLabel?: string | null;
190
+ optional: boolean;
191
+ prompt: string;
192
+ scale?: number | null;
193
+ }
194
+ interface SurveyUrlRule {
195
+ matches: 'contains' | 'exact' | 'starts_with';
196
+ value: string;
197
+ }
198
+ interface SurveyAppearance {
199
+ accent?: string | null;
200
+ placement: 'bottom_center' | 'bottom_left' | 'bottom_right';
201
+ submitLabel?: string | null;
202
+ thankYou?: string | null;
203
+ }
204
+ interface Survey {
205
+ appearance: SurveyAppearance;
206
+ choiceLabels?: Record<string, string[]>;
207
+ event?: string | null;
208
+ id: string;
209
+ iteration: number;
210
+ kind: 'api' | 'popover';
211
+ name: string;
212
+ questions: SurveyQuestion[];
213
+ showOnce: boolean;
214
+ urls: SurveyUrlRule[];
215
+ waitDays: number;
216
+ }
217
+ type SurveyAnswer = number | string | string[];
218
+ interface SurveyMemory {
219
+ lastShownAt?: number;
220
+ settled: string[];
221
+ }
222
+ interface SurveysClientOptions {
223
+ fetch?: FetchLike;
224
+ host: string;
225
+ projectKey: string;
226
+ requestTimeoutMs?: number;
227
+ }
228
+ declare class SurveysClient {
229
+ private readonly fetch?;
230
+ private readonly host;
231
+ private readonly projectKey;
232
+ private readonly requestTimeoutMs;
233
+ constructor(options: SurveysClientOptions);
234
+ surveys(distinctId: string, language?: string): Promise<Survey[]>;
235
+ }
236
+ declare const settledKey: (survey: Pick<Survey, "id" | "iteration">) => string;
237
+ declare function urlMatches(rules: SurveyUrlRule[], href: string): boolean;
238
+ declare function isDue(survey: Survey, memory: SurveyMemory, href: string, now: number, event?: string): boolean;
239
+ declare function nextQuestion(survey: Survey, question: SurveyQuestion, answer: SurveyAnswer | undefined): string | null;
240
+ declare function responseProperties(survey: Survey, answers: Record<string, SurveyAnswer>): EventProperties;
241
+
242
+ declare const GUIDE_SHOWN = "$guide_shown";
243
+ declare const GUIDE_STEP_VIEWED = "$guide_step_viewed";
244
+ declare const GUIDE_STEP_MISSED = "$guide_step_missed";
245
+ declare const GUIDE_COMPLETED = "$guide_completed";
246
+ declare const GUIDE_DISMISSED = "$guide_dismissed";
247
+ declare const CHECKLIST_TASK_DONE = "$checklist_task_done";
248
+ type GuideKind = 'checklist' | 'tooltip' | 'tour';
249
+ type GuideStepPlacement = 'auto' | 'bottom' | 'center' | 'left' | 'right' | 'top';
250
+ interface GuideStep {
251
+ anchor?: string | null;
252
+ body?: string | null;
253
+ event?: string | null;
254
+ id: string;
255
+ image?: string | null;
256
+ link?: string | null;
257
+ placement: GuideStepPlacement;
258
+ selector?: string | null;
259
+ title: string;
260
+ }
261
+ interface GuideAppearance {
262
+ accent?: string | null;
263
+ doneLabel?: string | null;
264
+ launcher: 'bottom_left' | 'bottom_right';
265
+ nextLabel?: string | null;
266
+ }
267
+ interface Guide {
268
+ appearance: GuideAppearance;
269
+ event?: string | null;
270
+ id: string;
271
+ iteration: number;
272
+ kind: GuideKind;
273
+ name: string;
274
+ showOnce: boolean;
275
+ steps: GuideStep[];
276
+ urls: SurveyUrlRule[];
277
+ waitDays: number;
278
+ }
279
+ interface GuideMemory {
280
+ done: string[];
281
+ lastShownAt?: number;
282
+ settled: string[];
283
+ }
284
+ interface GuidesClientOptions {
285
+ fetch?: FetchLike;
286
+ host: string;
287
+ projectKey: string;
288
+ requestTimeoutMs?: number;
289
+ }
290
+ declare class GuidesClient {
291
+ private readonly fetch?;
292
+ private readonly host;
293
+ private readonly projectKey;
294
+ private readonly requestTimeoutMs;
295
+ constructor(options: GuidesClientOptions);
296
+ guides(distinctId: string): Promise<Guide[]>;
297
+ }
298
+ declare const guideKey: (guide: Pick<Guide, "id" | "iteration">) => string;
299
+ declare const taskKey: (guide: Pick<Guide, "id" | "iteration">, stepId: string) => string;
300
+ declare function isGuideDue(guide: Guide, memory: GuideMemory, href: string, now: number, event?: string): boolean;
301
+ declare const tasksDone: (guide: Guide, memory: GuideMemory) => string[];
302
+ declare const taskFor: (guide: Guide, eventName: string) => GuideStep | undefined;
303
+ declare function guideProperties(guide: Guide, stepId?: string): EventProperties;
304
+
305
+ interface LocalFlagContext {
306
+ attributes?: EventProperties;
307
+ /** The cohorts the current distinct id belongs to. When omitted and the
308
+ * snapshot names a cohort, the client fetches them once per distinct id. */
309
+ cohorts?: string[];
310
+ properties?: EventProperties;
311
+ }
312
+ interface CaptureOptions {
313
+ /** Speak for someone other than this client's own identity. A server has no
314
+ * visitor of its own to lend an event, so an event it sends on a browser's
315
+ * behalf names the person directly. */
316
+ distinctId?: string;
317
+ element?: unknown;
318
+ properties?: EventProperties;
319
+ sessionId?: string;
320
+ timestamp?: Date;
321
+ }
322
+ /**
323
+ * The profile keys the platform itself understands.
324
+ *
325
+ * They are ordinary properties on the wire; the only thing that makes them
326
+ * special is the `$` prefix, which is how this platform marks a name it owns
327
+ * rather than one the caller chose. Passing them through `traits` means never
328
+ * having to remember whether the console reads `email` or `$email`: an
329
+ * unprefixed `email` is a property of your own and stays one, and would never
330
+ * reach the Email column.
331
+ */
332
+ interface PersonTraits {
333
+ avatar?: string;
334
+ email?: string;
335
+ name?: string;
336
+ phone?: string;
337
+ }
338
+ interface IdentifyOptions {
339
+ /** Arbitrary profile properties your own code defines. */
340
+ set?: EventProperties;
341
+ /** The reserved traits the console renders as fields. */
342
+ traits?: PersonTraits;
343
+ }
344
+ declare class ProdantixClient {
345
+ private readonly config;
346
+ private readonly identity;
347
+ private readonly session?;
348
+ private readonly queue;
349
+ private readonly transport;
350
+ private readonly flagsClient;
351
+ private readonly messagesClient;
352
+ private readonly surveysClient;
353
+ private readonly guidesClient;
354
+ private readonly captureListeners;
355
+ private readonly formsClient;
356
+ private readonly ctasClient;
357
+ private readonly context;
358
+ private flushTimer?;
359
+ private flushing;
360
+ private cachedFlags?;
361
+ private cachedSnapshot?;
362
+ private membershipCache?;
363
+ private stream?;
364
+ private shutDown;
365
+ /** One `$feature_flag_called` per (distinct id, flag, response) per client
366
+ * lifetime: the experiment engine attributes on the FIRST exposure, so a
367
+ * second event for the same answer would only cost the project an event. */
368
+ private readonly exposures;
369
+ private readonly gates;
370
+ private cookielessId?;
371
+ private readonly storageListeners;
372
+ constructor(config: ProdantixConfig);
373
+ get distinctId(): string;
374
+ get anonymousId(): string;
375
+ /** Whether this client still holds a person, from the persisted distinct id,
376
+ * so a fresh page load answers the same as the load that identified them.
377
+ * Public because a surface that has resolved to nobody must reset the client
378
+ * only when there is someone to reset: a sign-out is a hard navigation on a
379
+ * BFF surface, so no value-to-null transition ever renders. */
380
+ get isIdentified(): boolean;
381
+ get sessionId(): string | undefined;
382
+ get sessionStartedAt(): number | undefined;
383
+ capture(eventName: string, options?: CaptureOptions): void;
384
+ onCapture(listener: (eventName: string) => void): () => void;
385
+ identify(distinctId: string, options?: IdentifyOptions): void;
386
+ /**
387
+ * Join a browser's anonymous trail to a person from a server. A sign-in that
388
+ * completes in a redirect renders no page, so the browser's own `identify`
389
+ * never runs there; this sends the one `$identify` it would have sent, for
390
+ * the ids given, and leaves this client's own identity as it was.
391
+ */
392
+ link(distinctId: string, anonymousId: string, traits?: PersonTraits): void;
393
+ /**
394
+ * Record the visitor's answer about the join. It rides the shared store, so
395
+ * every subdomain and the login's server read the same one, and it takes
396
+ * effect on the next identify and the next decorated click; nothing already
397
+ * joined is unjoined.
398
+ */
399
+ setConsent(consent: Consent): void;
400
+ /** Whether the visitor is counted without anything kept on the device. */
401
+ isCookieless(): boolean;
402
+ /** Counts a cookieless visitor under the edge's id for the day. */
403
+ takeCookielessId(anonymousId: string): void;
404
+ /** Keeps the visitor's id on the device from now on, under a new id, so
405
+ * nothing counted before is joined to them. */
406
+ allowStorage(): void;
407
+ /** Calls `listener` once storage is allowed, for what waits on consent. */
408
+ onStorageAllowed(listener: () => void): () => void;
409
+ /** Stops keeping anything on the device and counts the visitor under the
410
+ * day's cookieless id again. */
411
+ forbidStorage(): void;
412
+ /** The visitor's answer, or null when they have not been asked. */
413
+ consent(): Consent | null;
414
+ alias(alias: string): void;
415
+ group(groupType: string, groupKey: string, properties?: EventProperties): void;
416
+ setPersonProperties(set?: EventProperties, setOnce?: EventProperties): void;
417
+ /**
418
+ * Attach the reserved traits to whoever is current, without an identify.
419
+ *
420
+ * This does NOT make the person identified: only `identify()` does that, so a
421
+ * trait set on an anonymous visitor leaves them anonymous and carrying an
422
+ * address, which is exactly what a newsletter signup before login looks like.
423
+ */
424
+ setPersonTraits(traits: PersonTraits): void;
425
+ getAllFlags(): Promise<Record<string, boolean>>;
426
+ isFeatureEnabled(key: string): Promise<boolean>;
427
+ /** The assigned variation for one flag, or null when the flag is unknown or
428
+ * carries no variations. Records the exposure either way. */
429
+ getVariant(key: string): Promise<FlagVariant | null>;
430
+ getVariantLocal(key: string, context?: LocalFlagContext): Promise<FlagVariant | null>;
431
+ private recordExposure;
432
+ getCachedFlag(key: string): boolean | undefined;
433
+ getLocalFlags(context?: LocalFlagContext): Promise<Record<string, boolean>>;
434
+ isFeatureEnabledLocal(key: string, context?: LocalFlagContext): Promise<boolean>;
435
+ /** The evaluation context for a local read. Memberships come from the caller
436
+ * when supplied, else from the server once per distinct id per snapshot
437
+ * TTL, and only when the snapshot names a cohort at all. */
438
+ private localContext;
439
+ private flagSnapshot;
440
+ /** Opens the flag stream once, when streaming was asked for and the snapshot
441
+ * names a gateway. A pushed change drops the cached snapshot and refetches
442
+ * it; a refused handshake stays closed, a dropped one reopens. */
443
+ private maybeStream;
444
+ getInbox(): Promise<InboxMessage[]>;
445
+ markMessageRead(messageId: string): Promise<void>;
446
+ getSurveys(language?: string): Promise<Survey[]>;
447
+ captureSurveyShown(survey: Survey): void;
448
+ captureSurveyDismissed(survey: Survey): void;
449
+ captureSurveySent(survey: Survey, answers: Record<string, SurveyAnswer>): void;
450
+ getGuides(): Promise<Guide[]>;
451
+ captureGuide(eventName: string, guide: Guide, stepId?: string): void;
452
+ /** A published form, resolved for this visitor's known properties. */
453
+ getForm(formId: string): Promise<ServedForm>;
454
+ /** Submits a form's answers as this visitor, identifying them by the email
455
+ * answered while they are anonymous. */
456
+ submitForm(formId: string, answers: Record<string, unknown>, challenge: FormChallenge, solution: string): Promise<FormAfterSubmit>;
457
+ /** The live CTAs a page may show this visitor, each with their variant. */
458
+ getCtas(page: {
459
+ device: CtaDevice;
460
+ language: string;
461
+ url: string;
462
+ }): Promise<ServedCta[]>;
463
+ /** Sends a CTA's view, click or dismiss, with the button for a click. */
464
+ captureCta(eventName: string, cta: ServedCta, button?: number): void;
465
+ flush(): Promise<void>;
466
+ reset(): void;
467
+ shutdown(): Promise<void>;
468
+ private enqueue;
469
+ private persistQueue;
470
+ private restoreQueue;
471
+ private startTimer;
472
+ private stopTimer;
473
+ private persistKey;
474
+ }
475
+ declare function createClient(config: ProdantixConfig): ProdantixClient;
476
+
477
+ export { isDue as A, isGuideDue as B, CHECKLIST_TASK_DONE as C, nextQuestion as D, responseProperties as E, settledKey as F, GUIDE_COMPLETED as G, taskFor as H, type IdentifyOptions as I, taskKey as J, tasksDone as K, type LocalFlagContext as L, urlMatches as M, type ServedForm as N, type FormChallenge as O, ProdantixClient as P, type FormAfterSubmit as Q, type ServedCta as R, SURVEY_DISMISSED as S, type CtaDevice as T, type CaptureOptions as a, GUIDE_DISMISSED as b, GUIDE_SHOWN as c, GUIDE_STEP_MISSED as d, GUIDE_STEP_VIEWED as e, type Guide as f, type GuideAppearance as g, type GuideKind as h, type GuideMemory as i, type GuideStep as j, type GuideStepPlacement as k, GuidesClient as l, SURVEY_SENT as m, SURVEY_SHOWN as n, type Survey as o, type SurveyAnswer as p, type SurveyAppearance as q, type SurveyBranch as r, type SurveyMemory as s, type SurveyQuestion as t, type SurveyQuestionKind as u, type SurveyUrlRule as v, SurveysClient as w, createClient as x, guideKey as y, guideProperties as z };