@prodantix/sdk 0.1.0 → 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/README.md +36 -3
- package/dist/chat.cjs +5 -2
- package/dist/chat.d.cts +5 -15
- package/dist/chat.d.ts +5 -15
- package/dist/chat.js +7 -4
- package/dist/chunk-5CBVQAZ2.js +2 -0
- package/dist/chunk-V77KYPOF.js +2 -0
- package/dist/client-BO7f6q5k.d.cts +134 -0
- package/dist/client-BQlU_3Dc.d.ts +134 -0
- package/dist/{config-OP9Csae6.d.cts → config-CWmtX8Gl.d.cts} +40 -9
- package/dist/{config-B-cTz9n1.d.ts → config-DDlHv52p.d.ts} +40 -9
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +17 -5
- package/dist/index.d.ts +17 -5
- package/dist/index.js +1 -1
- package/dist/messenger.cjs +1 -1
- package/dist/messenger.d.cts +1 -1
- package/dist/messenger.d.ts +1 -1
- package/dist/messenger.iife.js +5 -2
- package/dist/messenger.js +1 -1
- package/dist/node.cjs +1 -1
- package/dist/node.d.cts +18 -2
- package/dist/node.d.ts +18 -2
- package/dist/node.js +1 -1
- package/dist/{transport-dWp3NUMj.d.ts → transport-CqAmRbpQ.d.ts} +1 -1
- package/dist/{transport-DhhzvwpV.d.cts → transport-Cy42FY5A.d.cts} +1 -1
- package/dist/types-DjMXp6Wg.d.cts +118 -0
- package/dist/types-DjMXp6Wg.d.ts +118 -0
- package/dist/web.cjs +1 -1
- package/dist/web.d.cts +60 -3
- package/dist/web.d.ts +60 -3
- package/dist/web.js +1 -1
- package/package.json +13 -13
- package/dist/chunk-7J6AQICL.js +0 -2
- package/dist/client-BBUAoQg2.d.cts +0 -160
- package/dist/client-BBUAoQg2.d.ts +0 -160
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
type JsonPrimitive = string | number | boolean | null;
|
|
2
|
+
type JsonValue = JsonPrimitive | JsonValue[] | {
|
|
3
|
+
[key: string]: JsonValue;
|
|
4
|
+
};
|
|
5
|
+
type EventProperties = Record<string, JsonValue>;
|
|
6
|
+
interface EventContext {
|
|
7
|
+
locale?: string;
|
|
8
|
+
os?: string;
|
|
9
|
+
sdk?: string;
|
|
10
|
+
sdk_version?: string;
|
|
11
|
+
}
|
|
12
|
+
interface EventEnvelope {
|
|
13
|
+
context?: EventContext;
|
|
14
|
+
distinct_id: string;
|
|
15
|
+
event_id: string;
|
|
16
|
+
event_name: string;
|
|
17
|
+
properties: EventProperties;
|
|
18
|
+
schema_version: 1;
|
|
19
|
+
session_id?: string;
|
|
20
|
+
timestamp: string;
|
|
21
|
+
}
|
|
22
|
+
interface EventBatch {
|
|
23
|
+
api_key?: string;
|
|
24
|
+
events: EventEnvelope[];
|
|
25
|
+
sent_at: string;
|
|
26
|
+
}
|
|
27
|
+
interface FlagVariant {
|
|
28
|
+
key: string;
|
|
29
|
+
value: unknown;
|
|
30
|
+
}
|
|
31
|
+
interface FlagsResponse {
|
|
32
|
+
flags: Record<string, boolean>;
|
|
33
|
+
variants?: Record<string, FlagVariant>;
|
|
34
|
+
}
|
|
35
|
+
interface InboxMessage {
|
|
36
|
+
body: string;
|
|
37
|
+
createdAt: string;
|
|
38
|
+
id: string;
|
|
39
|
+
read: boolean;
|
|
40
|
+
title: string;
|
|
41
|
+
}
|
|
42
|
+
interface InboxResponse {
|
|
43
|
+
messages: InboxMessage[];
|
|
44
|
+
}
|
|
45
|
+
interface Clock {
|
|
46
|
+
now(): Date;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
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
|
+
}
|
|
56
|
+
interface IdFactory {
|
|
57
|
+
uuid(): string;
|
|
58
|
+
}
|
|
59
|
+
interface StorageAdapter {
|
|
60
|
+
getItem(key: string): string | null;
|
|
61
|
+
removeItem(key: string): void;
|
|
62
|
+
setItem(key: string, value: string): void;
|
|
63
|
+
}
|
|
64
|
+
interface TransportRequest {
|
|
65
|
+
body: EventBatch;
|
|
66
|
+
projectKey: string;
|
|
67
|
+
url: string;
|
|
68
|
+
}
|
|
69
|
+
interface Transport {
|
|
70
|
+
send(request: TransportRequest): Promise<void>;
|
|
71
|
+
}
|
|
72
|
+
/** The browser's `WebSocket`, narrowed to what the SDK uses so a test can hand
|
|
73
|
+
* in a fake without a DOM. Assigning the handlers rather than using
|
|
74
|
+
* `addEventListener` keeps the surface to four properties. */
|
|
75
|
+
interface SocketLike {
|
|
76
|
+
send(data: string): void;
|
|
77
|
+
close(): void;
|
|
78
|
+
onopen: (() => void) | null;
|
|
79
|
+
onclose: (() => void) | null;
|
|
80
|
+
onerror: (() => void) | null;
|
|
81
|
+
onmessage: ((event: {
|
|
82
|
+
data: string;
|
|
83
|
+
}) => void) | null;
|
|
84
|
+
}
|
|
85
|
+
type SocketFactory = (url: string) => SocketLike;
|
|
86
|
+
interface ProdantixConfig {
|
|
87
|
+
apiKey: string;
|
|
88
|
+
autocapture?: boolean;
|
|
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;
|
|
93
|
+
defaultProperties?: EventProperties | (() => EventProperties);
|
|
94
|
+
flagsHost?: string;
|
|
95
|
+
flushAt?: number;
|
|
96
|
+
flushIntervalMs?: number;
|
|
97
|
+
host: string;
|
|
98
|
+
ids?: IdFactory;
|
|
99
|
+
locale?: string;
|
|
100
|
+
maxQueueSize?: number;
|
|
101
|
+
maxRetries?: number;
|
|
102
|
+
onError?: (error: unknown) => void;
|
|
103
|
+
os?: string;
|
|
104
|
+
requestTimeoutMs?: number;
|
|
105
|
+
sdkName?: string;
|
|
106
|
+
sdkVersion?: string;
|
|
107
|
+
sessionTracking?: boolean;
|
|
108
|
+
sharedStorage?: StorageAdapter;
|
|
109
|
+
/** The socket constructor the flag stream uses; the test seam. */
|
|
110
|
+
socketFactory?: SocketFactory;
|
|
111
|
+
storage?: StorageAdapter;
|
|
112
|
+
/** Hold a Socket.IO subscription to flag changes and refetch the snapshot on
|
|
113
|
+
* push. Off unless asked; the node entry turns it on. */
|
|
114
|
+
streamFlags?: boolean;
|
|
115
|
+
transport?: Transport;
|
|
116
|
+
}
|
|
117
|
+
|
|
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 fe=Object.defineProperty;var me=(t,e,n)=>e in t?fe(t,e,{enumerable:true,configurable:true,writable:true,value:n}):t[e]=n;var i=(t,e,n)=>me(t,typeof e!="symbol"?e+"":e,n);var h=class extends Error{constructor(n,r,s){super(r,s);i(this,"code");this.code=n,this.name="ProdantixError";}},x=class extends h{constructor(e){super("config",e),this.name="ConfigError";}},y=class extends h{constructor(n,r){super("validation",r);i(this,"field");this.field=n,this.name="ValidationError";}},u=class extends h{constructor(n,r,s){super("transport",n,s);i(this,"status");this.status=r,this.name="TransportError";}};function c(t){if(t)return t;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function f(){let t=globalThis.AbortController;return t?new t:void 0}var D=t=>new Promise(e=>{setTimeout(e,t);});function p(t){return t.replace(/\/+$/,"")}var v=class{constructor(){i(this,"store",new Map);}getItem(e){return this.store.get(e)??null}removeItem(e){this.store.delete(e);}setItem(e,n){this.store.set(e,n);}};function K(){try{let t=globalThis.localStorage;if(t){let e="__pdx_probe__";return t.setItem(e,"1"),t.removeItem(e),t}}catch{return new v}return new v}var V={now:()=>new Date};function E(t){return t.toISOString()}function ge(){return globalThis.crypto}function ye(t){t[6]=t[6]&15|64,t[8]=t[8]&63|128;let e=[];for(let n=0;n<16;n+=1)e.push(t[n].toString(16).padStart(2,"0"));return `${e[0]}${e[1]}${e[2]}${e[3]}-${e[4]}${e[5]}-${e[6]}${e[7]}-${e[8]}${e[9]}-${e[10]}${e[11]}${e[12]}${e[13]}${e[14]}${e[15]}`}function O(){let t=ge();if(t?.randomUUID)return t.randomUUID();let e=new Uint8Array(16);if(t?.getRandomValues)t.getRandomValues(e);else for(let n=0;n<16;n+=1)e[n]=Math.floor(Math.random()*256);return ye(e)}var j={uuid:O};var ve=/^pdx_pub_(?:(?:live|test)_)?[a-z0-9]{32}$/;var be=/^(?:\$|[a-z])[a-z0-9_.]*$/;function z(t){let e=0;for(let n of t)e+=1;return e}function H(t){return ve.test(t)}function xe(t){return be.test(t)}function B(t){let e=z(t);if(e<1||e>200)throw new y("distinct_id","distinct_id must be between 1 and 200 characters")}function U(t){let e=z(t);if(e<1||e>200)throw new y("event_name","event_name must be between 1 and 200 characters");if(!xe(t))throw new y("event_name","event_name must match /^(\\$|[a-z])[a-z0-9_.]*$/")}var J="prodantix-js",Q="0.0.1";var ke=t=>{};function W(t){if(!t.apiKey||!H(t.apiKey))throw new x("apiKey must be a public project key of the form pdx_pub_<32 lowercase alphanumerics>");if(!t.host)throw new x("host is required (the ingest base URL)");let e=p(t.host),n=t.defaultProperties;return {apiKey:t.apiKey,autocapture:t.autocapture??false,clock:t.clock??V,defaultProperties:typeof n=="function"?n:()=>n??{},flagsHost:t.flagsHost?p(t.flagsHost):e,flushAt:t.flushAt??20,flushIntervalMs:t.flushIntervalMs??1e4,host:e,ids:t.ids??j,locale:t.locale,maxQueueSize:t.maxQueueSize??1e3,maxRetries:t.maxRetries??3,namespace:t.apiKey.slice(0,16),onError:t.onError??ke,os:t.os,requestTimeoutMs:t.requestTimeoutMs??1e4,sdkName:t.sdkName??J,sdkVersion:t.sdkVersion??Q,storage:t.storage??new v,transport:t.transport}}function G(t,e,n){U(t.eventName),B(t.distinctId);let r={distinct_id:t.distinctId,event_id:t.eventId??n.uuid(),event_name:t.eventName,properties:t.properties??{},schema_version:1,timestamp:E(t.timestamp??e.now())};return t.context&&(r.context=t.context),t.sessionId&&(r.session_id=t.sessionId),r}var g=Symbol("absent");function Ee(t,e){if(t==="distinct_id")return e.distinctId;let n=e.properties??{};if(Object.prototype.hasOwnProperty.call(n,t))return n[t];let r=e.attributes??{};return Object.prototype.hasOwnProperty.call(r,t)?r[t]:g}function m(t){return t===g?"undefined":String(t)}function X(t){return t===g?Number.NaN:Number(t)}function Y(t){return t!==g&&t!==null&&t!==""}function Z(t,e){if(!Array.isArray(e))return false;let n=m(t);return e.map(r=>String(r)).includes(n)}function ee(t,e){let n=Ee(t.attribute,e),r=t.value;switch(t.op){case "is_set":return Y(n);case "is_not_set":return !Y(n);case "eq":return m(n)===m(r===void 0?g:r);case "neq":return m(n)!==m(r===void 0?g:r);case "contains":return m(n).includes(m(r===void 0?g:r));case "in":return Z(n,r);case "not_in":return Array.isArray(r)?!Z(n,r):false;case "gt":return I(n,r,(s,o)=>s>o);case "gte":return I(n,r,(s,o)=>s>=o);case "lt":return I(n,r,(s,o)=>s<o);case "lte":return I(n,r,(s,o)=>s<=o);default:return false}}function I(t,e,n){let r=X(t),s=e===void 0?Number.NaN:X(e);return Number.isNaN(r)||Number.isNaN(s)?false:n(r,s)}function Ie(t,e){let n=`${t}:${e}`,r=2166136261;for(let s=0;s<n.length;s++)r^=n.charCodeAt(s),r=Math.imul(r,16777619);return (r>>>0)%100}function Te(t,e){return t.enabled?t.targeting.length>0&&!t.targeting.every(n=>ee(n,e))?{enabled:false,reason:"targeting"}:t.rolloutPercentage>=100?{enabled:true,reason:"rollout_full"}:Ie(t.key,e.distinctId)<t.rolloutPercentage?{enabled:true,reason:"rollout"}:{enabled:false,reason:"rollout_excluded"}:{enabled:false,reason:"disabled"}}function te(t,e){let n={};for(let r of t)n[r.key]=Te(r,e).enabled;return n}var T=class{constructor(e){i(this,"fetch");i(this,"host");i(this,"projectKey");i(this,"requestTimeoutMs");this.fetch=c(e.fetch),this.host=p(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async fetchAll(e){let n=this.fetch;if(!n)throw new u("no fetch implementation available in this runtime");let r=`${this.host}/v1/flags?distinct_id=${encodeURIComponent(e)}`,s=f(),o=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{let a=await n(r,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:s?.signal});if(!a.ok)throw new u(`flags request failed with status ${a.status}`,a.status);return JSON.parse(await a.text()).flags??{}}finally{o!==void 0&&clearTimeout(o);}}async snapshot(){let e=this.fetch;if(!e)throw new u("no fetch implementation available in this runtime");let n=`${this.host}/v1/flags/snapshot`,r=f(),s=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let o=await e(n,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!o.ok)throw new u(`flag snapshot request failed with status ${o.status}`,o.status);let a=JSON.parse(await o.text());return {flags:a.flags??[],generatedAt:a.generatedAt}}finally{s!==void 0&&clearTimeout(s);}}};var w=class{constructor(e,n,r){this.storage=e;this.ids=n;this.namespace=r;i(this,"anonymousId");i(this,"distinctId");i(this,"identified");let s=e.getItem(this.key("anonymous_id"));s?this.anonymousId=s:(this.anonymousId=n.uuid(),e.setItem(this.key("anonymous_id"),this.anonymousId));let o=e.getItem(this.key("distinct_id"));o?(this.distinctId=o,this.identified=true):(this.distinctId=this.anonymousId,this.identified=false);}getAnonymousId(){return this.anonymousId}getDistinctId(){return this.distinctId}isIdentified(){return this.identified}snapshot(){return {anonymousId:this.anonymousId,distinctId:this.distinctId,identified:this.identified}}identify(e){return this.identified&&this.distinctId===e?{changed:false}:(this.distinctId=e,this.identified=true,this.storage.setItem(this.key("distinct_id"),e),{changed:true})}reset(){this.anonymousId=this.ids.uuid(),this.distinctId=this.anonymousId,this.identified=false,this.storage.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.removeItem(this.key("distinct_id"));}key(e){return `pdx.${this.namespace}.${e}`}};var S=class{constructor(e){i(this,"fetch");i(this,"host");i(this,"projectKey");i(this,"requestTimeoutMs");this.fetch=c(e.fetch),this.host=p(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async inbox(e){let n=this.requireFetch(),r=`${this.host}/v1/messages?distinct_id=${encodeURIComponent(e)}`,s=await this.request(n,r,{headers:this.authHeaders(),method:"GET"});if(!s.ok)throw new u(`inbox request failed with status ${s.status}`,s.status);return JSON.parse(await s.text()).messages??[]}async markRead(e,n){let r=this.requireFetch(),s=`${this.host}/v1/messages/read`,o=await this.request(r,s,{body:JSON.stringify({distinct_id:n,message_id:e}),headers:{...this.authHeaders(),"content-type":"application/json"},method:"POST"});if(!o.ok)throw new u(`mark-read request failed with status ${o.status}`,o.status)}requireFetch(){if(!this.fetch)throw new u("no fetch implementation available in this runtime");return this.fetch}authHeaders(){return {authorization:`Bearer ${this.projectKey}`}}async request(e,n,r){let s=f(),o=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{return await e(n,{...r,signal:s?.signal})}finally{o!==void 0&&clearTimeout(o);}}};var P=class{constructor(e,n){this.maxSize=e;this.onOverflow=n;i(this,"events",[]);}get size(){return this.events.length}enqueue(e){this.events.push(e),this.enforceCap();}restore(e){this.events.push(...e),this.enforceCap();}requeue(e){this.events.unshift(...e),this.enforceCap();}drain(e){let n=e===void 0?this.events.length:Math.min(e,this.events.length);return this.events.splice(0,n)}snapshot(){return [...this.events]}enforceCap(){if(this.events.length<=this.maxSize)return;let e=this.events.splice(0,this.events.length-this.maxSize);this.onOverflow?.({dropped:e});}};function ne(t){return t>=400&&t<500&&t!==429}var b=class{constructor(e={}){i(this,"fetch");i(this,"maxRetries");i(this,"requestTimeoutMs");i(this,"baseDelayMs");i(this,"maxDelayMs");i(this,"sleep");i(this,"random");this.fetch=c(e.fetch),this.maxRetries=e.maxRetries??3,this.requestTimeoutMs=e.requestTimeoutMs??1e4,this.baseDelayMs=e.baseDelayMs??500,this.maxDelayMs=e.maxDelayMs??3e4,this.sleep=e.sleep??D,this.random=e.random??Math.random;}async send(e){let n=this.fetch;if(!n)throw new u("no fetch implementation available in this runtime");let r=JSON.stringify(e.body),s;for(let o=0;o<=this.maxRetries;o+=1){try{let a=await this.attempt(n,e,r);if(a.ok)return;if(ne(a.status))throw new u(`ingest rejected batch with status ${a.status}`,a.status);s=new u(`ingest transient status ${a.status}`,a.status);}catch(a){if(a instanceof u&&a.status!==void 0&&ne(a.status))throw a;s=a;}o<this.maxRetries&&await this.sleep(this.backoff(o));}throw new u("ingest delivery failed after retries",void 0,{cause:s})}async attempt(e,n,r){let s=f(),o=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{return await e(n.url,{body:r,headers:{authorization:`Bearer ${n.projectKey}`,"content-type":"application/json"},method:"POST",signal:s?.signal})}finally{o!==void 0&&clearTimeout(o);}}backoff(e){return Math.min(this.maxDelayMs,this.baseDelayMs*2**e)+this.random()*this.baseDelayMs}};var we="queue",Se=1e3,Pe=3e4,re=t=>{let e={};return t.avatar!==void 0&&(e.$avatar=t.avatar),t.email!==void 0&&(e.$email=t.email),t.name!==void 0&&(e.$name=t.name),t.phone!==void 0&&(e.$phone=t.phone),e},C=class{constructor(e){i(this,"config");i(this,"identity");i(this,"queue");i(this,"transport");i(this,"flagsClient");i(this,"messagesClient");i(this,"context");i(this,"flushTimer");i(this,"flushing",false);i(this,"cachedFlags");i(this,"cachedSnapshot");this.config=W(e),this.identity=new w(this.config.storage,this.config.ids,this.config.namespace),this.queue=new P(this.config.maxQueueSize,({dropped:n})=>{this.config.onError(new h("queue_overflow",`event queue overflow: dropped ${n.length} oldest event(s)`));}),this.transport=this.config.transport??new b({maxRetries:this.config.maxRetries,requestTimeoutMs:this.config.requestTimeoutMs}),this.flagsClient=new T({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.messagesClient=new S({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.context={sdk:this.config.sdkName,sdk_version:this.config.sdkVersion},this.config.os&&(this.context.os=this.config.os),this.config.locale&&(this.context.locale=this.config.locale),this.restoreQueue(),this.startTimer();}get distinctId(){return this.identity.getDistinctId()}get anonymousId(){return this.identity.getAnonymousId()}capture(e,n={}){try{let r={...this.config.defaultProperties(),...n.properties??{}},s=G({context:this.context,distinctId:this.identity.getDistinctId(),eventName:e,properties:r,sessionId:n.sessionId,timestamp:n.timestamp},this.config.clock,this.config.ids);this.enqueue(s);}catch(r){this.config.onError(r);}}identify(e,n={}){let r=this.identity.getAnonymousId(),s=!this.identity.isIdentified(),o=this.identity.identify(e),a={};s&&o.changed&&(a.$anon_distinct_id=r);let l={...re(n.traits??{}),...n.set??{}};Object.keys(l).length>0&&(a.$set=l),this.capture("$identify",{properties:a});}alias(e){this.capture("$create_alias",{properties:{alias:e}});}group(e,n,r){let s={$group_key:n,$group_type:e};r&&(s.$set=r),this.capture("$group",{properties:s});}setPersonProperties(e,n){let r={};e&&(r.$set=e),n&&(r.$set_once=n),this.capture("$set",{properties:r});}setPersonTraits(e){let n=re(e);Object.keys(n).length!==0&&this.capture("$set",{properties:{$set:n}});}async getAllFlags(){let e=this.identity.getDistinctId(),n=await this.flagsClient.fetchAll(e);return this.cachedFlags={distinctId:e,flags:n},n}async isFeatureEnabled(e){return (await this.getAllFlags())[e]??false}getCachedFlag(e){if(!(!this.cachedFlags||this.cachedFlags.distinctId!==this.distinctId))return this.cachedFlags.flags[e]}async getLocalFlags(e={}){let n=await this.flagSnapshot();return te(n.flags,{attributes:e.attributes,distinctId:this.identity.getDistinctId(),properties:e.properties})}async isFeatureEnabledLocal(e,n){return (await this.getLocalFlags(n))[e]??false}async flagSnapshot(){let e=this.config.clock.now().getTime();if(this.cachedSnapshot&&e-this.cachedSnapshot.fetchedAt<Pe)return this.cachedSnapshot.snapshot;let n=await this.flagsClient.snapshot();return this.cachedSnapshot={fetchedAt:e,snapshot:n},n}async getInbox(){return this.messagesClient.inbox(this.identity.getDistinctId())}async markMessageRead(e){await this.messagesClient.markRead(e,this.identity.getDistinctId());}async flush(){if(this.flushing||this.queue.size===0)return;this.flushing=true;let e=this.queue.drain(Se);try{await this.transport.send({body:{events:e,sent_at:E(this.config.clock.now())},projectKey:this.config.apiKey,url:`${this.config.host}/v1/events`}),this.persistQueue();}catch(n){this.queue.requeue(e),this.persistQueue(),this.config.onError(n);}finally{this.flushing=false;}}reset(){this.identity.reset(),this.cachedFlags=void 0,this.cachedSnapshot=void 0;}async shutdown(){this.stopTimer(),await this.flush();}enqueue(e){this.queue.enqueue(e),this.persistQueue(),this.queue.size>=this.config.flushAt&&this.flush();}persistQueue(){try{this.config.storage.setItem(this.persistKey(),JSON.stringify(this.queue.snapshot()));}catch(e){this.config.onError(e);}}restoreQueue(){try{let e=this.config.storage.getItem(this.persistKey());if(!e)return;let n=JSON.parse(e);Array.isArray(n)&&this.queue.restore(n);}catch(e){this.config.onError(e);}}startTimer(){if(this.config.flushIntervalMs<=0)return;let e=setInterval(()=>{this.flush();},this.config.flushIntervalMs),n=e;typeof n.unref=="function"&&n.unref(),this.flushTimer=e;}stopTimer(){this.flushTimer!==void 0&&(clearInterval(this.flushTimer),this.flushTimer=void 0);}persistKey(){return `pdx.${this.config.namespace}.${we}`}};function se(){return globalThis.location}function ie(){return globalThis.document}function Ce(){return globalThis.window??globalThis}function Fe(t){return typeof t=="object"&&t!==null&&typeof t.tagName=="string"}function oe(){let t=se(),e=ie(),n={};return t&&(n.$current_url=t.href,n.$pathname=t.pathname,n.$host=t.host),e&&(e.title&&(n.$title=e.title),e.referrer&&(n.$referrer=e.referrer)),n}function Re(t){let e={$el_tag:t.tagName.toLowerCase(),$event_type:"click"},n=t.textContent?.trim();n&&(e.$el_text=n.slice(0,255)),t.id&&(e.$el_id=t.id),typeof t.className=="string"&&t.className&&(e.$el_classes=t.className);let r=t.getAttribute("href");return r&&(e.$el_href=r),e}function Ne(t){let e=globalThis.history,n=Ce(),r="",s=()=>{let l=se(),d=l?`${l.pathname}${l.search}`:"";d!==r&&(r=d,t.capture("$pageview",{properties:oe()}));};if(s(),!e||!n)return ()=>{};let o=e.pushState.bind(e),a=e.replaceState.bind(e);return e.pushState=(...l)=>{o(...l),s();},e.replaceState=(...l)=>{a(...l),s();},n.addEventListener("popstate",s),()=>{e.pushState=o,e.replaceState=a,n.removeEventListener("popstate",s);}}function _e(t){let e=ie();if(!e)return ()=>{};let n=r=>{let s=r.target;Fe(s)&&t.capture("$autocapture",{properties:{...oe(),...Re(s)}});};return e.addEventListener("click",n,true),()=>e.removeEventListener("click",n,true)}function ae(t,e={}){let n=[];return (e.pageviews??true)&&n.push(Ne(t)),(e.clicks??true)&&n.push(_e(t)),()=>{for(let r of n)r();}}function Me(){return globalThis.document?.visibilityState==="hidden"}function Ae(t){let e=globalThis.navigator,n=globalThis.Blob;if(!e?.sendBeacon||!n)return false;let r=JSON.stringify({...t.body,api_key:t.projectKey});try{let s=new n([r],{type:"application/json"});return e.sendBeacon(t.url,s)}catch{return false}}var F=class{constructor(e={}){i(this,"fetchTransport");this.fetchTransport=new b(e);}async send(e){Me()&&Ae(e)||await this.fetchTransport.send(e);}};var le={maskAllInputs:true,maskAllText:false},Le=new Set(["email","password","tel"]);function ue(t){return t.replace(/\S/g,"*")}function R(t,e,n){return Oe(e)||n.maskAllInputs?ue(t):t}function N(t,e){return e.maskAllText?ue(t):t}function Oe(t){return Le.has((t??"").toLowerCase())}var $e=5e3,_=class{constructor(e){this.options=e;i(this,"buffer",[]);i(this,"seq",0);i(this,"maxEvents");this.maxEvents=Math.min(Math.max(1,e.maxEvents),$e);}add(e){return this.buffer.push(e),this.buffer.length>=this.maxEvents?this.flush():null}flush(){if(this.buffer.length===0)return null;let e=this.buffer;this.buffer=[];let n={distinct_id:this.options.distinctId(),events:e,masked:this.options.masked,schema_version:1,seq:this.seq,session_id:this.options.sessionId,timestamp:new Date(this.options.now()).toISOString()};return this.seq+=1,n}};var $=1,q=3,qe=9,M=class{constructor(){i(this,"next",1);}allocate(){let e=this.next;return this.next+=1,e}},De=new Set(["NOSCRIPT","SCRIPT"]);function A(t,e,n,r){if(t.nodeType===q){let s=e.allocate();return r?.(t,s),{id:s,textContent:N(t.textValue??"",n),type:"text"}}if(t.nodeType===qe){let s=e.allocate();return r?.(t,s),{childNodes:pe(t,e,n,r),id:s,type:"document"}}if(t.nodeType===$){let s=t.tagName??"";if(De.has(s))return null;let o=e.allocate();return r?.(t,o),{attributes:Ke(t,n),childNodes:pe(t,e,n,r),id:o,tagName:s,type:"element"}}return null}function pe(t,e,n,r){let s=[];for(let o of t.childNodes??[]){let a=A(o,e,n,r);a&&s.push(a);}return s}function Ke(t,e){let n={};for(let r of t.attributes??[])n[r.name]=r.value;return t.inputValue!==void 0&&(n.value=R(t.inputValue,t.inputType,e)),n}async function ce(t,e){let n=`${p(e.replayHost)}/v1/replay`;return (await e.fetch(n,{body:JSON.stringify(t),headers:{authorization:`Bearer ${e.apiKey}`,"content-type":"application/json"},method:"POST"})).ok}var de=new Set(["INPUT","SELECT","TEXTAREA"]),L=class{constructor(e){this.options=e;i(this,"allocator",new M);i(this,"mirror",new Map);i(this,"chunker");i(this,"fetchImpl");i(this,"observer");i(this,"timer");i(this,"started",false);this.chunker=new _({distinctId:e.distinctId,masked:e.mask.maskAllInputs,maxEvents:e.maxEvents,now:e.now,sessionId:e.sessionId}),this.fetchImpl=c(e.fetch);}start(){if(this.started)return;let e=Ve(),n=e?.documentElement;!e||!n||!this.fetchImpl||(this.started=true,this.captureFullSnapshot(n),this.observeMutations(n),this.observeInteractions(e),this.timer=setInterval(()=>this.upload(this.chunker.flush()),this.options.flushIntervalMs));}stop(){this.started&&(this.started=false,this.observer?.disconnect(),this.timer&&clearInterval(this.timer),this.upload(this.chunker.flush()));}captureFullSnapshot(e){let n=A(this.adapt(e),this.allocator,this.options.mask,(r,s)=>{let o=r.ref;o&&this.mirror.set(o,s);});n&&this.push(2,{node:n});}observeMutations(e){let n=globalThis.MutationObserver;n&&(this.observer=new n(r=>{for(let s of r)this.handleMutation(s);}),this.observer.observe(e,{attributes:true,characterData:true,childList:true,subtree:true}));}handleMutation(e){if(e.type==="characterData"){let n=this.mirror.get(e.target);n!==void 0&&this.push(3,{texts:[{id:n,value:N(e.target.textContent??"",this.options.mask)}]});return}if(e.type==="attributes"&&e.attributeName){let n=this.mirror.get(e.target),r=e.target;n!==void 0&&this.push(3,{attributes:[{attributes:{[e.attributeName]:r.getAttribute(e.attributeName)??""},id:n}]});return}if(e.type==="childList"){let n=this.mirror.get(e.target);if(n===void 0)return;for(let r of Array.from(e.addedNodes)){let s=A(this.adapt(r),this.allocator,this.options.mask,(o,a)=>{let l=o.ref;l&&this.mirror.set(l,a);});s&&this.push(3,{adds:[{node:s,parentId:n}]});}for(let r of Array.from(e.removedNodes)){let s=this.mirror.get(r);s!==void 0&&(this.push(3,{removes:[{id:s,parentId:n}]}),this.mirror.delete(r));}}}observeInteractions(e){e.addEventListener("input",n=>{let r=n.target;if(!r||!de.has(r.tagName))return;let s=this.mirror.get(r);s!==void 0&&this.push(3,{input:{id:s,value:R(r.value??"",r.type,this.options.mask)}});},true),e.addEventListener("scroll",n=>{let r=n.target,s=r?this.mirror.get(r):void 0;this.push(3,{scroll:{id:s??0,x:r?.scrollLeft??0,y:r?.scrollTop??0}});},true);}adapt(e){let n={childNodes:[],nodeType:e.nodeType,ref:e};if(e.nodeType===q)return n.textValue=e.textContent??"",n;if(e.nodeType===$){let r=e;if(n.tagName=r.tagName,n.attributes=Array.from(r.attributes).map(s=>({name:s.name,value:s.value})),de.has(r.tagName)){let s=r;n.inputType=s.type,n.inputValue=s.value??"";}}return n.childNodes=Array.from(e.childNodes).map(r=>this.adapt(r)),n}push(e,n){let r=this.chunker.add({data:n,timestamp:this.options.now(),type:e});r&&this.upload(r);}upload(e){!e||!this.fetchImpl||ce(e,{apiKey:this.options.apiKey,fetch:this.fetchImpl,replayHost:this.options.replayHost}).catch(n=>this.options.onError?.(n));}};function Ve(){return globalThis.document}function he(t){let e=new L({apiKey:t.apiKey,distinctId:t.distinctId,flushIntervalMs:t.flushIntervalMs??5e3,mask:{...le,...t.mask},maxEvents:t.maxEvents??200,now:t.now??(()=>Date.now()),onError:t.onError,replayHost:t.replayHost,sessionId:t.sessionId??O()});return e.start(),e}function je(){return globalThis.navigator}function ze(t){let e=t?.userAgentData?.platform??t?.platform;return e?e.slice(0,50):void 0}function He(t){let e=()=>{t.flush();};globalThis.document?.addEventListener?.("visibilitychange",e),globalThis.addEventListener?.("pagehide",e);}function kn(t){let{autocaptureOptions:e,replayHost:n,sessionReplay:r,sessionReplayOptions:s,...o}=t,a=je(),l={...o,locale:o.locale??(a?.language?a.language.slice(0,20):void 0),os:o.os??ze(a),storage:o.storage??K(),transport:o.transport??new F({maxRetries:o.maxRetries,requestTimeoutMs:o.requestTimeoutMs})},d=new C(l);return He(d),(t.autocapture??true)&&ae(d,e),r&&n&&he({apiKey:l.apiKey,distinctId:()=>d.distinctId,onError:l.onError,replayHost:n,...s}),d}exports.WebTransport=F;exports.createWebClient=kn;exports.installAutocapture=ae;exports.installSessionReplay=he;//# sourceMappingURL=web.cjs.map
|
|
1
|
+
'use strict';var 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,5 +1,6 @@
|
|
|
1
|
-
import { P as ProdantixClient
|
|
2
|
-
import { a as
|
|
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';
|
|
3
4
|
import { F as FetchLike } from './http-BCh716Vs.cjs';
|
|
4
5
|
|
|
5
6
|
interface AutocaptureOptions {
|
|
@@ -80,11 +81,67 @@ interface SessionReplayOptions {
|
|
|
80
81
|
* `stop()` it. A missing `sessionId` gets a fresh v4 uuid. */
|
|
81
82
|
declare function installSessionReplay(options: SessionReplayOptions): SessionRecorder;
|
|
82
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
|
+
|
|
83
134
|
/** Tunables for the built-in session replay, minus the identity fields
|
|
84
135
|
* `createWebClient` fills in (apiKey, distinctId, replayHost). */
|
|
85
136
|
type WebSessionReplayOptions = Pick<SessionReplayOptions, 'flushIntervalMs' | 'mask' | 'maxEvents' | 'sessionId'>;
|
|
86
137
|
interface WebClientOptions extends ProdantixConfig {
|
|
87
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[];
|
|
88
145
|
/** Host of the recorder service (`eu.replay.prodantix.com`). Required to enable
|
|
89
146
|
* session replay. */
|
|
90
147
|
replayHost?: string;
|
|
@@ -95,4 +152,4 @@ interface WebClientOptions extends ProdantixConfig {
|
|
|
95
152
|
}
|
|
96
153
|
declare function createWebClient(options: WebClientOptions): ProdantixClient;
|
|
97
154
|
|
|
98
|
-
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 };
|
package/dist/web.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { P as ProdantixClient
|
|
2
|
-
import { a as
|
|
1
|
+
import { P as ProdantixClient } from './client-BQlU_3Dc.js';
|
|
2
|
+
import { T as Transport, i as TransportRequest, a as StorageAdapter, b as Consent, P as ProdantixConfig } from './types-DjMXp6Wg.js';
|
|
3
|
+
import { a as FetchTransportOptions } from './transport-CqAmRbpQ.js';
|
|
3
4
|
import { F as FetchLike } from './http-BCh716Vs.js';
|
|
4
5
|
|
|
5
6
|
interface AutocaptureOptions {
|
|
@@ -80,11 +81,67 @@ interface SessionReplayOptions {
|
|
|
80
81
|
* `stop()` it. A missing `sessionId` gets a fresh v4 uuid. */
|
|
81
82
|
declare function installSessionReplay(options: SessionReplayOptions): SessionRecorder;
|
|
82
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
|
+
|
|
83
134
|
/** Tunables for the built-in session replay, minus the identity fields
|
|
84
135
|
* `createWebClient` fills in (apiKey, distinctId, replayHost). */
|
|
85
136
|
type WebSessionReplayOptions = Pick<SessionReplayOptions, 'flushIntervalMs' | 'mask' | 'maxEvents' | 'sessionId'>;
|
|
86
137
|
interface WebClientOptions extends ProdantixConfig {
|
|
87
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[];
|
|
88
145
|
/** Host of the recorder service (`eu.replay.prodantix.com`). Required to enable
|
|
89
146
|
* session replay. */
|
|
90
147
|
replayHost?: string;
|
|
@@ -95,4 +152,4 @@ interface WebClientOptions extends ProdantixConfig {
|
|
|
95
152
|
}
|
|
96
153
|
declare function createWebClient(options: WebClientOptions): ProdantixClient;
|
|
97
154
|
|
|
98
|
-
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 };
|
package/dist/web.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {r,g as g$1,f as f$1,s}from'./chunk-7J6AQICL.js';import {a as a$1,d as d$1}from'./chunk-VG77TYVX.js';import {a}from'./chunk-5XGN7UAV.js';function w(){return globalThis.location}function S(){return globalThis.document}function D(){return globalThis.window??globalThis}function V(e){return typeof e=="object"&&e!==null&&typeof e.tagName=="string"}function O(){let e=w(),t=S(),n={};return e&&(n.$current_url=e.href,n.$pathname=e.pathname,n.$host=e.host),t&&(t.title&&(n.$title=t.title),t.referrer&&(n.$referrer=t.referrer)),n}function H(e){let t={$el_tag:e.tagName.toLowerCase(),$event_type:"click"},n=e.textContent?.trim();n&&(t.$el_text=n.slice(0,255)),e.id&&(t.$el_id=e.id),typeof e.className=="string"&&e.className&&(t.$el_classes=e.className);let i=e.getAttribute("href");return i&&(t.$el_href=i),t}function $(e){let t=globalThis.history,n=D(),i="",r=()=>{let a=w(),l=a?`${a.pathname}${a.search}`:"";l!==i&&(i=l,e.capture("$pageview",{properties:O()}));};if(r(),!t||!n)return ()=>{};let s=t.pushState.bind(t),p=t.replaceState.bind(t);return t.pushState=(...a)=>{s(...a),r();},t.replaceState=(...a)=>{p(...a),r();},n.addEventListener("popstate",r),()=>{t.pushState=s,t.replaceState=p,n.removeEventListener("popstate",r);}}function K(e){let t=S();if(!t)return ()=>{};let n=i=>{let r=i.target;V(r)&&e.capture("$autocapture",{properties:{...O(),...H(r)}});};return t.addEventListener("click",n,true),()=>t.removeEventListener("click",n,true)}function I(e,t={}){let n=[];return (t.pageviews??true)&&n.push($(e)),(t.clicks??true)&&n.push(K(e)),()=>{for(let i of n)i();}}function F(){return globalThis.document?.visibilityState==="hidden"}function B(e){let t=globalThis.navigator,n=globalThis.Blob;if(!t?.sendBeacon||!n)return false;let i=JSON.stringify({...e.body,api_key:e.projectKey});try{let r=new n([i],{type:"application/json"});return t.sendBeacon(e.url,r)}catch{return false}}var c=class{constructor(t={}){a(this,"fetchTransport");this.fetchTransport=new r(t);}async send(t){F()&&B(t)||await this.fetchTransport.send(t);}};var R={maskAllInputs:true,maskAllText:false},W=new Set(["email","password","tel"]);function A(e){return e.replace(/\S/g,"*")}function d(e,t,n){return z(t)||n.maskAllInputs?A(e):e}function f(e,t){return t.maskAllText?A(e):e}function z(e){return W.has((e??"").toLowerCase())}var U=5e3,m=class{constructor(t){this.options=t;a(this,"buffer",[]);a(this,"seq",0);a(this,"maxEvents");this.maxEvents=Math.min(Math.max(1,t.maxEvents),U);}add(t){return this.buffer.push(t),this.buffer.length>=this.maxEvents?this.flush():null}flush(){if(this.buffer.length===0)return null;let t=this.buffer;this.buffer=[];let n={distinct_id:this.options.distinctId(),events:t,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 v=1,k=3,q=9,h=class{constructor(){a(this,"next",1);}allocate(){let t=this.next;return this.next+=1,t}},j=new Set(["NOSCRIPT","SCRIPT"]);function g(e,t,n,i){if(e.nodeType===k){let r=t.allocate();return i?.(e,r),{id:r,textContent:f(e.textValue??"",n),type:"text"}}if(e.nodeType===q){let r=t.allocate();return i?.(e,r),{childNodes:M(e,t,n,i),id:r,type:"document"}}if(e.nodeType===v){let r=e.tagName??"";if(j.has(r))return null;let s=t.allocate();return i?.(e,s),{attributes:X(e,n),childNodes:M(e,t,n,i),id:s,tagName:r,type:"element"}}return null}function M(e,t,n,i){let r=[];for(let s of e.childNodes??[]){let p=g(s,t,n,i);p&&r.push(p);}return r}function X(e,t){let n={};for(let i of e.attributes??[])n[i.name]=i.value;return e.inputValue!==void 0&&(n.value=d(e.inputValue,e.inputType,t)),n}async function P(e,t){let n=`${d$1(t.replayHost)}/v1/replay`;return (await t.fetch(n,{body:JSON.stringify(e),headers:{authorization:`Bearer ${t.apiKey}`,"content-type":"application/json"},method:"POST"})).ok}var C=new Set(["INPUT","SELECT","TEXTAREA"]),y=class{constructor(t){this.options=t;a(this,"allocator",new h);a(this,"mirror",new Map);a(this,"chunker");a(this,"fetchImpl");a(this,"observer");a(this,"timer");a(this,"started",false);this.chunker=new m({distinctId:t.distinctId,masked:t.mask.maskAllInputs,maxEvents:t.maxEvents,now:t.now,sessionId:t.sessionId}),this.fetchImpl=a$1(t.fetch);}start(){if(this.started)return;let t=Y(),n=t?.documentElement;!t||!n||!this.fetchImpl||(this.started=true,this.captureFullSnapshot(n),this.observeMutations(n),this.observeInteractions(t),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(t){let n=g(this.adapt(t),this.allocator,this.options.mask,(i,r)=>{let s=i.ref;s&&this.mirror.set(s,r);});n&&this.push(2,{node:n});}observeMutations(t){let n=globalThis.MutationObserver;n&&(this.observer=new n(i=>{for(let r of i)this.handleMutation(r);}),this.observer.observe(t,{attributes:true,characterData:true,childList:true,subtree:true}));}handleMutation(t){if(t.type==="characterData"){let n=this.mirror.get(t.target);n!==void 0&&this.push(3,{texts:[{id:n,value:f(t.target.textContent??"",this.options.mask)}]});return}if(t.type==="attributes"&&t.attributeName){let n=this.mirror.get(t.target),i=t.target;n!==void 0&&this.push(3,{attributes:[{attributes:{[t.attributeName]:i.getAttribute(t.attributeName)??""},id:n}]});return}if(t.type==="childList"){let n=this.mirror.get(t.target);if(n===void 0)return;for(let i of Array.from(t.addedNodes)){let r=g(this.adapt(i),this.allocator,this.options.mask,(s,p)=>{let a=s.ref;a&&this.mirror.set(a,p);});r&&this.push(3,{adds:[{node:r,parentId:n}]});}for(let i of Array.from(t.removedNodes)){let r=this.mirror.get(i);r!==void 0&&(this.push(3,{removes:[{id:r,parentId:n}]}),this.mirror.delete(i));}}}observeInteractions(t){t.addEventListener("input",n=>{let i=n.target;if(!i||!C.has(i.tagName))return;let r=this.mirror.get(i);r!==void 0&&this.push(3,{input:{id:r,value:d(i.value??"",i.type,this.options.mask)}});},true),t.addEventListener("scroll",n=>{let i=n.target,r=i?this.mirror.get(i):void 0;this.push(3,{scroll:{id:r??0,x:i?.scrollLeft??0,y:i?.scrollTop??0}});},true);}adapt(t){let n={childNodes:[],nodeType:t.nodeType,ref:t};if(t.nodeType===k)return n.textValue=t.textContent??"",n;if(t.nodeType===v){let i=t;if(n.tagName=i.tagName,n.attributes=Array.from(i.attributes).map(r=>({name:r.name,value:r.value})),C.has(i.tagName)){let r=i;n.inputType=r.type,n.inputValue=r.value??"";}}return n.childNodes=Array.from(t.childNodes).map(i=>this.adapt(i)),n}push(t,n){let i=this.chunker.add({data:n,timestamp:this.options.now(),type:t});i&&this.upload(i);}upload(t){!t||!this.fetchImpl||P(t,{apiKey:this.options.apiKey,fetch:this.fetchImpl,replayHost:this.options.replayHost}).catch(n=>this.options.onError?.(n));}};function Y(){return globalThis.document}function _(e){let t=new y({apiKey:e.apiKey,distinctId:e.distinctId,flushIntervalMs:e.flushIntervalMs??5e3,mask:{...R,...e.mask},maxEvents:e.maxEvents??200,now:e.now??(()=>Date.now()),onError:e.onError,replayHost:e.replayHost,sessionId:e.sessionId??g$1()});return t.start(),t}function G(){return globalThis.navigator}function J(e){let t=e?.userAgentData?.platform??e?.platform;return t?t.slice(0,50):void 0}function Q(e){let t=()=>{e.flush();};globalThis.document?.addEventListener?.("visibilitychange",t),globalThis.addEventListener?.("pagehide",t);}function It(e){let{autocaptureOptions:t,replayHost:n,sessionReplay:i,sessionReplayOptions:r,...s$1}=e,p=G(),a={...s$1,locale:s$1.locale??(p?.language?p.language.slice(0,20):void 0),os:s$1.os??J(p),storage:s$1.storage??f$1(),transport:s$1.transport??new c({maxRetries:s$1.maxRetries,requestTimeoutMs:s$1.requestTimeoutMs})},l=new s(a);return Q(l),(e.autocapture??true)&&I(l,t),i&&n&&_({apiKey:a.apiKey,distinctId:()=>l.distinctId,onError:a.onError,replayHost:n,...r}),l}export{c as WebTransport,It as createWebClient,I as installAutocapture,_ as installSessionReplay};//# sourceMappingURL=web.js.map
|
|
1
|
+
import {x as x$1,i,h as h$1,f as f$1,g as g$1,l as l$1,y as y$1,u,w as w$1}from'./chunk-5CBVQAZ2.js';import'./chunk-V77KYPOF.js';import {a as a$1,d}from'./chunk-VG77TYVX.js';import {a}from'./chunk-5XGN7UAV.js';function B(){return globalThis.location}function q(){return globalThis.document}function me(){return globalThis.window??globalThis}function he(t){return typeof t=="object"&&t!==null&&typeof t.tagName=="string"}function X(){let t=B(),e=q(),n={};return t&&(n.$current_url=t.href,n.$pathname=t.pathname,n.$host=t.host),e&&(e.title&&(n.$title=e.title),e.referrer&&(n.$referrer=e.referrer)),n}function ge(t){let e={$el_tag:t.tagName.toLowerCase(),$event_type:"click"},n=t.textContent?.trim();n&&(e.$el_text=n.slice(0,255)),t.id&&(e.$el_id=t.id),typeof t.className=="string"&&t.className&&(e.$el_classes=t.className);let r=t.getAttribute("href");return r&&(e.$el_href=r),e}function ye(t){let e=globalThis.history,n=me(),r="",i=()=>{let s=B(),c=s?`${s.pathname}${s.search}`:"";c!==r&&(r=c,t.capture("$pageview",{properties:X()}));};if(i(),!e||!n)return ()=>{};let o=e.pushState.bind(e),a=e.replaceState.bind(e);return e.pushState=(...s)=>{o(...s),i();},e.replaceState=(...s)=>{a(...s),i();},n.addEventListener("popstate",i),()=>{e.pushState=o,e.replaceState=a,n.removeEventListener("popstate",i);}}function ke(t){let e=q();if(!e)return ()=>{};let n=r=>{let i=r.target;he(i)&&t.capture("$autocapture",{properties:{...X(),...ge(i)}});};return e.addEventListener("click",n,true),()=>e.removeEventListener("click",n,true)}function G(t,e={}){let n=[];return (e.pageviews??true)&&n.push(ye(t)),(e.clicks??true)&&n.push(ke(t)),()=>{for(let r of n)r();}}function ve(){return globalThis.document?.visibilityState==="hidden"}function be(t){let e=globalThis.navigator,n=globalThis.Blob;if(!e?.sendBeacon||!n)return false;let r=JSON.stringify({...t.body,api_key:t.projectKey});try{let i=new n([r],{type:"application/json"});return e.sendBeacon(t.url,i)}catch{return false}}var f=class{constructor(e={}){a(this,"fetchTransport");this.fetchTransport=new x$1(e);}async send(e){ve()&&be(e)||await this.fetchTransport.send(e);}};var xe=/^\d{1,3}(\.\d{1,3}){3}$/,Le=/^[a-z0-9.-]+$/i;function Y(){return Math.random().toString(36).slice(2,12)}function m(t,e){let n=`${e}=`,r=[];for(let i of t.cookie.split(";")){let o=i.trim();o.startsWith(n)&&r.push(o.slice(n.length));}return r}function l(t,e,n){let r=["Path=/",`Max-Age=${e}`,"SameSite=Lax"];return t&&r.push(`Domain=${t}`),n&&r.push("Secure"),r.join("; ")}function Q(t,e,n,r){try{let i=`pdx_probe_${r()}`,o=r();t.cookie=`${i}=${o}; ${l(e,60,n)}`;let a=m(t,i).includes(o);t.cookie=`${i}=; ${l(e,0,n)}`;let s=m(t,i).includes(o);return a&&!s}catch{return false}}function C(t){let e=t.replace(/^\[|\]$/g,"").toLowerCase();if(e.includes(":")||xe.test(e)||!e.includes("."))return [];let n=e.split("."),r=[];for(let i=n.length-2;i>=0;i-=1)r.push(n.slice(i).join("."));return r}function Z(t,e,n,r=Y){for(let i of C(t))if(Q(e,i,n,r))return i}function Ee(t){let e=new Map,n=JSON.parse(decodeURIComponent(t));if(n===null||typeof n!="object"||Array.isArray(n))return e;for(let[r,i]of Object.entries(n))typeof i=="string"&&e.set(r,i);return e}var S=class{constructor(e,n,r,i){this.jar=e;this.name=n;this.domain=r;this.secure=i;}getItem(e){return this.read().get(e)??null}setItem(e,n){let r=this.read();r.set(e,n),this.write(r);}removeItem(e){let n=this.read();n.delete(e)&&this.write(n);}read(){try{let e=m(this.jar,this.name);e.length>1&&this.domain&&(this.jar.cookie=`${this.name}=; ${l(void 0,0,this.secure)}`,e=m(this.jar,this.name));let n=e[0];return n?Ee(n):new Map}catch{return new Map}}write(e){try{if(e.size===0){this.jar.cookie=`${this.name}=; ${l(this.domain,0,this.secure)}`;return}let n=encodeURIComponent(JSON.stringify(Object.fromEntries(e)));this.jar.cookie=`${this.name}=${n}; ${l(this.domain,31536e3,this.secure)}`;}catch{return}}};function Se(){return globalThis.document}function Ce(){return globalThis.location?.hostname??""}function we(){return globalThis.location?.protocol==="https:"}function Te(t){if(t===void 0)return;let e=t.startsWith(".")?t.slice(1):t;return Le.test(e)?e.toLowerCase():void 0}function w(t){let e="jar"in t?t.jar:Se();if(!e||globalThis.navigator?.cookieEnabled===false)return null;let r=t.random??Y,i=t.secure??we(),o=t.hostname??Ce();try{let a=Te(t.domain)??Z(o,e,i,r);return Q(e,a,i,r)?new S(e,t.name,a,i):null}catch{return null}}var ne="_pdx",re="~",Ae=200,Ne=/^\d+$/;function ie(t,e,n,r){let i=Oe(t.href);if(i===void 0||A(i.search).some(N))return;let o=ee(i.hostname,n);o===void 0||o===ee(r,n)||(i.search=`${i.search}${i.search?"&":"?"}${ne}=${Ie(e)}`,t.href=i.href);}function Ie(t){return [t.anonymousId,t.sessionId,String(t.sessionStartedAt)].map(Pe).join(re)}function oe(t){let e=A(t).find(N);if(e===void 0)return;let n=Re(e).split(re);if(n.length!==3)return;let r=h(n[0]),i=h(n[1]),o=h(n[2]);if(!(!te(r)||!te(i)||!Me(o)))return {anonymousId:r,sessionId:i,sessionStartedAt:Number(o)}}function se(t,e){let n=A(e.search),r=n.filter(o=>!N(o));if(r.length===n.length)return;let i=r.length>0?`?${r.join("&")}`:"";t.replaceState(t.state,"",`${e.pathname}${i}${e.hash}`);}function ae(t){if(t.location===void 0||typeof t.location.search!="string")return;let e=oe(t.location.search);if(e===void 0)return;let n=u(t.storage,t.shared,t.namespace,e.anonymousId);return w$1(t.shared,t.namespace,{id:e.sessionId,startedAt:e.sessionStartedAt},t.now),t.history!==void 0&&se(t.history,t.location),n}function T(t,e,n){if(n.length===0)return ()=>{};let r=i=>{let o=De(i.target);if(o===void 0)return;let a=_e(e);a!==void 0&&ie(o,a,n,t.location?.hostname??"");};return t.addEventListener("click",r,true),t.addEventListener("auxclick",r,true),()=>{t.removeEventListener("click",r,true),t.removeEventListener("auxclick",r,true);}}function Oe(t){try{let e=new URL(t);return e.protocol==="http:"||e.protocol==="https:"?e:void 0}catch{return}}function ee(t,e){let n=e.map(r=>r.replace(/^\./,"").toLowerCase());return C(t).find(r=>n.includes(r))}function A(t){return t.replace(/^\?/,"").split("&").filter(e=>e!=="")}function N(t){let e=t.indexOf("=");return h(e===-1?t:t.slice(0,e))===ne}function Re(t){let e=t.indexOf("=");return e===-1?"":t.slice(e+1)}function Pe(t){return encodeURIComponent(t).replace(/~/g,"%7E")}function h(t){try{return decodeURIComponent(t)}catch{return}}function te(t){if(t===void 0)return false;let e=i(t);return e>=1&&e<=Ae}function Me(t){return t!==void 0&&Ne.test(t)&&Number.isSafeInteger(Number(t))}function _e(t){if(t.consent?.()?.identityLink===false)return;let e=t.sessionId,n=t.sessionStartedAt;if(!(e===void 0||n===void 0))return {anonymousId:t.anonymousId,sessionId:e,sessionStartedAt:n}}function $e(t){return typeof t.tagName=="string"&&t.tagName.toUpperCase()==="A"&&typeof t.href=="string"}function De(t){let e=typeof t=="object"?t:null;for(;e;){if($e(e))return e;e=e.parentElement??null;}}var ue={maskAllInputs:true,maskAllText:false},He=new Set(["email","password","tel"]);function de(t){return t.replace(/\S/g,"*")}function g(t,e,n){return je(e)||n.maskAllInputs?de(t):t}function y(t,e){return e.maskAllText?de(t):t}function je(t){return He.has((t??"").toLowerCase())}var Ve=5e3,k=class{constructor(e){this.options=e;a(this,"buffer",[]);a(this,"seq",0);a(this,"maxEvents");this.maxEvents=Math.min(Math.max(1,e.maxEvents),Ve);}add(e){return this.buffer.push(e),this.buffer.length>=this.maxEvents?this.flush():null}flush(){if(this.buffer.length===0)return null;let e=this.buffer;this.buffer=[];let n={distinct_id:this.options.distinctId(),events:e,masked:this.options.masked,schema_version:1,seq:this.seq,session_id:this.options.sessionId,timestamp:new Date(this.options.now()).toISOString()};return this.seq+=1,n}};var I=1,O=3,Ke=9,v=class{constructor(){a(this,"next",1);}allocate(){let e=this.next;return this.next+=1,e}},Fe=new Set(["NOSCRIPT","SCRIPT"]);function b(t,e,n,r){if(t.nodeType===O){let i=e.allocate();return r?.(t,i),{id:i,textContent:y(t.textValue??"",n),type:"text"}}if(t.nodeType===Ke){let i=e.allocate();return r?.(t,i),{childNodes:ce(t,e,n,r),id:i,type:"document"}}if(t.nodeType===I){let i=t.tagName??"";if(Fe.has(i))return null;let o=e.allocate();return r?.(t,o),{attributes:Ue(t,n),childNodes:ce(t,e,n,r),id:o,tagName:i,type:"element"}}return null}function ce(t,e,n,r){let i=[];for(let o of t.childNodes??[]){let a=b(o,e,n,r);a&&i.push(a);}return i}function Ue(t,e){let n={};for(let r of t.attributes??[])n[r.name]=r.value;return t.inputValue!==void 0&&(n.value=g(t.inputValue,t.inputType,e)),n}async function le(t,e){let n=`${d(e.replayHost)}/v1/replay`;return (await e.fetch(n,{body:JSON.stringify(t),headers:{authorization:`Bearer ${e.apiKey}`,"content-type":"application/json"},method:"POST"})).ok}var pe=new Set(["INPUT","SELECT","TEXTAREA"]),x=class{constructor(e){this.options=e;a(this,"allocator",new v);a(this,"mirror",new Map);a(this,"chunker");a(this,"fetchImpl");a(this,"observer");a(this,"timer");a(this,"started",false);this.chunker=new k({distinctId:e.distinctId,masked:e.mask.maskAllInputs,maxEvents:e.maxEvents,now:e.now,sessionId:e.sessionId}),this.fetchImpl=a$1(e.fetch);}start(){if(this.started)return;let e=Je(),n=e?.documentElement;!e||!n||!this.fetchImpl||(this.started=true,this.captureFullSnapshot(n),this.observeMutations(n),this.observeInteractions(e),this.timer=setInterval(()=>this.upload(this.chunker.flush()),this.options.flushIntervalMs));}stop(){this.started&&(this.started=false,this.observer?.disconnect(),this.timer&&clearInterval(this.timer),this.upload(this.chunker.flush()));}captureFullSnapshot(e){let n=b(this.adapt(e),this.allocator,this.options.mask,(r,i)=>{let o=r.ref;o&&this.mirror.set(o,i);});n&&this.push(2,{node:n});}observeMutations(e){let n=globalThis.MutationObserver;n&&(this.observer=new n(r=>{for(let i of r)this.handleMutation(i);}),this.observer.observe(e,{attributes:true,characterData:true,childList:true,subtree:true}));}handleMutation(e){if(e.type==="characterData"){let n=this.mirror.get(e.target);n!==void 0&&this.push(3,{texts:[{id:n,value:y(e.target.textContent??"",this.options.mask)}]});return}if(e.type==="attributes"&&e.attributeName){let n=this.mirror.get(e.target),r=e.target;n!==void 0&&this.push(3,{attributes:[{attributes:{[e.attributeName]:r.getAttribute(e.attributeName)??""},id:n}]});return}if(e.type==="childList"){let n=this.mirror.get(e.target);if(n===void 0)return;for(let r of Array.from(e.addedNodes)){let i=b(this.adapt(r),this.allocator,this.options.mask,(o,a)=>{let s=o.ref;s&&this.mirror.set(s,a);});i&&this.push(3,{adds:[{node:i,parentId:n}]});}for(let r of Array.from(e.removedNodes)){let i=this.mirror.get(r);i!==void 0&&(this.push(3,{removes:[{id:i,parentId:n}]}),this.mirror.delete(r));}}}observeInteractions(e){e.addEventListener("input",n=>{let r=n.target;if(!r||!pe.has(r.tagName))return;let i=this.mirror.get(r);i!==void 0&&this.push(3,{input:{id:i,value:g(r.value??"",r.type,this.options.mask)}});},true),e.addEventListener("scroll",n=>{let r=n.target,i=r?this.mirror.get(r):void 0;this.push(3,{scroll:{id:i??0,x:r?.scrollLeft??0,y:r?.scrollTop??0}});},true);}adapt(e){let n={childNodes:[],nodeType:e.nodeType,ref:e};if(e.nodeType===O)return n.textValue=e.textContent??"",n;if(e.nodeType===I){let r=e;if(n.tagName=r.tagName,n.attributes=Array.from(r.attributes).map(i=>({name:i.name,value:i.value})),pe.has(r.tagName)){let i=r;n.inputType=i.type,n.inputValue=i.value??"";}}return n.childNodes=Array.from(e.childNodes).map(r=>this.adapt(r)),n}push(e,n){let r=this.chunker.add({data:n,timestamp:this.options.now(),type:e});r&&this.upload(r);}upload(e){!e||!this.fetchImpl||le(e,{apiKey:this.options.apiKey,fetch:this.fetchImpl,replayHost:this.options.replayHost}).catch(n=>this.options.onError?.(n));}};function Je(){return globalThis.document}function fe(t){let e=new x({apiKey:t.apiKey,distinctId:t.distinctId,flushIntervalMs:t.flushIntervalMs??5e3,mask:{...ue,...t.mask},maxEvents:t.maxEvents??200,now:t.now??(()=>Date.now()),onError:t.onError,replayHost:t.replayHost,sessionId:t.sessionId??h$1()});return e.start(),e}function We(){return globalThis.navigator}function ze(){return globalThis.document}function Be(){return globalThis.history}function qe(){return globalThis.location}function Xe(t){let e=t?.userAgentData?.platform??t?.platform;return e?e.slice(0,50):void 0}function Ge(t){let e=()=>{t.flush();};globalThis.document?.addEventListener?.("visibilitychange",e),globalThis.addEventListener?.("pagehide",e);}function Ye(t,e,n){try{return w({domain:e,name:`pdx_${l$1(t)}`})??n}catch{return n}}function Ht(t){let{autocaptureOptions:e,cookieDomain:n,linkedDomains:r,replayHost:i,sessionReplay:o,sessionReplayOptions:a,...s}=t,c=We(),R=f$1(),P=s.storage??R,M=s.sharedStorage??Ye(s.apiKey,n,R),_=ae({history:Be(),location:qe(),namespace:l$1(s.apiKey),now:(s.clock??g$1).now().getTime(),shared:M,storage:P}),L={...s,locale:s.locale??(c?.language?c.language.slice(0,20):void 0),os:s.os??Xe(c),sessionTracking:s.sessionTracking??true,sharedStorage:M,storage:P,transport:s.transport??new f({maxRetries:s.maxRetries,requestTimeoutMs:s.requestTimeoutMs})},d=new y$1(L);_!==void 0&&d.alias(_),Ge(d),(t.autocapture??true)&&G(d,e);let $=ze();return $&&r&&T($,d,r),o&&i&&fe({apiKey:L.apiKey,distinctId:()=>d.distinctId,onError:L.onError,replayHost:i,...a,sessionId:a?.sessionId??d.sessionId}),d}export{f as WebTransport,w as createCookieStorage,Ht as createWebClient,ie as decorateLink,G as installAutocapture,T as installLinkCarry,fe as installSessionReplay,oe as readCarry,Z as resolveCookieDomain,se as stripCarry};//# sourceMappingURL=web.js.map
|
|
2
2
|
//# sourceMappingURL=web.js.map
|
package/package.json
CHANGED
|
@@ -10,35 +10,35 @@
|
|
|
10
10
|
},
|
|
11
11
|
"exports": {
|
|
12
12
|
".": {
|
|
13
|
+
"types": "./dist/index.d.ts",
|
|
13
14
|
"import": "./dist/index.js",
|
|
14
|
-
"require": "./dist/index.cjs"
|
|
15
|
-
"types": "./dist/index.d.ts"
|
|
15
|
+
"require": "./dist/index.cjs"
|
|
16
16
|
},
|
|
17
17
|
"./chat": {
|
|
18
|
+
"types": "./dist/chat.d.ts",
|
|
18
19
|
"import": "./dist/chat.js",
|
|
19
|
-
"require": "./dist/chat.cjs"
|
|
20
|
-
"types": "./dist/chat.d.ts"
|
|
20
|
+
"require": "./dist/chat.cjs"
|
|
21
21
|
},
|
|
22
22
|
"./csp": {
|
|
23
|
+
"types": "./dist/csp.d.ts",
|
|
23
24
|
"import": "./dist/csp.js",
|
|
24
|
-
"require": "./dist/csp.cjs"
|
|
25
|
-
"types": "./dist/csp.d.ts"
|
|
25
|
+
"require": "./dist/csp.cjs"
|
|
26
26
|
},
|
|
27
27
|
"./messenger": {
|
|
28
|
+
"types": "./dist/messenger.d.ts",
|
|
28
29
|
"import": "./dist/messenger.js",
|
|
29
|
-
"require": "./dist/messenger.cjs"
|
|
30
|
-
"types": "./dist/messenger.d.ts"
|
|
30
|
+
"require": "./dist/messenger.cjs"
|
|
31
31
|
},
|
|
32
32
|
"./node": {
|
|
33
|
+
"types": "./dist/node.d.ts",
|
|
33
34
|
"import": "./dist/node.js",
|
|
34
|
-
"require": "./dist/node.cjs"
|
|
35
|
-
"types": "./dist/node.d.ts"
|
|
35
|
+
"require": "./dist/node.cjs"
|
|
36
36
|
},
|
|
37
37
|
"./package.json": "./package.json",
|
|
38
38
|
"./web": {
|
|
39
|
+
"types": "./dist/web.d.ts",
|
|
39
40
|
"import": "./dist/web.js",
|
|
40
|
-
"require": "./dist/web.cjs"
|
|
41
|
-
"types": "./dist/web.d.ts"
|
|
41
|
+
"require": "./dist/web.cjs"
|
|
42
42
|
}
|
|
43
43
|
},
|
|
44
44
|
"files": ["dist", "!dist/**/*.map"],
|
|
@@ -63,5 +63,5 @@
|
|
|
63
63
|
"sideEffects": false,
|
|
64
64
|
"type": "module",
|
|
65
65
|
"types": "./dist/index.d.ts",
|
|
66
|
-
"version": "0.
|
|
66
|
+
"version": "0.2.0-beta.357"
|
|
67
67
|
}
|
package/dist/chunk-7J6AQICL.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import {a as a$1,d,b as b$1,c as c$1}from'./chunk-VG77TYVX.js';import {a}from'./chunk-5XGN7UAV.js';var c=class extends Error{constructor(s,r,n){super(r,n);a(this,"code");this.code=s,this.name="ProdantixError";}},y=class extends c{constructor(e){super("config",e),this.name="ConfigError";}},m=class extends c{constructor(s,r){super("validation",r);a(this,"field");this.field=s,this.name="ValidationError";}},l=class extends c{constructor(s,r,n){super("transport",s,n);a(this,"status");this.status=r,this.name="TransportError";}};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,s){this.store.set(e,s);}};function ae(){try{let t=globalThis.localStorage;if(t){let e="__pdx_probe__";return t.setItem(e,"1"),t.removeItem(e),t}}catch{return new g}return new g}var _="prodantix-js",C="0.0.1";var h=Symbol("absent");function U(t,e){if(t==="distinct_id")return e.distinctId;let s=e.properties??{};if(Object.prototype.hasOwnProperty.call(s,t))return s[t];let r=e.attributes??{};return Object.prototype.hasOwnProperty.call(r,t)?r[t]:h}function p(t){return t===h?"undefined":String(t)}function R(t){return t===h?Number.NaN:Number(t)}function $(t){return t!==h&&t!==null&&t!==""}function M(t,e){if(!Array.isArray(e))return false;let s=p(t);return e.map(r=>String(r)).includes(s)}function k(t,e){let s=U(t.attribute,e),r=t.value;switch(t.op){case "is_set":return $(s);case "is_not_set":return !$(s);case "eq":return p(s)===p(r===void 0?h:r);case "neq":return p(s)!==p(r===void 0?h:r);case "contains":return p(s).includes(p(r===void 0?h:r));case "in":return M(s,r);case "not_in":return Array.isArray(r)?!M(s,r):false;case "gt":return v(s,r,(n,o)=>n>o);case "gte":return v(s,r,(n,o)=>n>=o);case "lt":return v(s,r,(n,o)=>n<o);case "lte":return v(s,r,(n,o)=>n<=o);default:return false}}function v(t,e,s){let r=R(t),n=e===void 0?Number.NaN:R(e);return Number.isNaN(r)||Number.isNaN(n)?false:s(r,n)}function q(t,e){let s=`${t}:${e}`,r=2166136261;for(let n=0;n<s.length;n++)r^=s.charCodeAt(n),r=Math.imul(r,16777619);return (r>>>0)%100}function B(t,e){return t.enabled?t.targeting.length>0&&!t.targeting.every(s=>k(s,e))?{enabled:false,reason:"targeting"}:t.rolloutPercentage>=100?{enabled:true,reason:"rollout_full"}:q(t.key,e.distinctId)<t.rolloutPercentage?{enabled:true,reason:"rollout"}:{enabled:false,reason:"rollout_excluded"}:{enabled:false,reason:"disabled"}}function A(t,e){let s={};for(let r of t)s[r.key]=B(r,e).enabled;return s}function H(t,e){let s=t.variations??[],r=s[0];if(!r)return null;if(!t.enabled||t.targeting.length>0&&!t.targeting.every(a=>k(a,e)))return r;let n=q(t.key,e.distinctId),o=0;for(let a=s.length-1;a>=0;a--)if(o+=s[a].weight,n<o)return s[a];return r}function he(t,e,s){let r=t.find(n=>n.key===e);return r?H(r,s)?.value??null:null}var x=class{constructor(e){a(this,"fetch");a(this,"host");a(this,"projectKey");a(this,"requestTimeoutMs");this.fetch=a$1(e.fetch),this.host=d(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async fetchAll(e){let s=this.fetch;if(!s)throw new l("no fetch implementation available in this runtime");let r=`${this.host}/v1/flags?distinct_id=${encodeURIComponent(e)}`,n=b$1(),o=n?setTimeout(()=>n.abort(),this.requestTimeoutMs):void 0;try{let a=await s(r,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:n?.signal});if(!a.ok)throw new l(`flags request failed with status ${a.status}`,a.status);return JSON.parse(await a.text()).flags??{}}finally{o!==void 0&&clearTimeout(o);}}async snapshot(){let e=this.fetch;if(!e)throw new l("no fetch implementation available in this runtime");let s=`${this.host}/v1/flags/snapshot`,r=b$1(),n=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let o=await e(s,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!o.ok)throw new l(`flag snapshot request failed with status ${o.status}`,o.status);let a=JSON.parse(await o.text());return {flags:a.flags??[],generatedAt:a.generatedAt}}finally{n!==void 0&&clearTimeout(n);}}};var b=class{constructor(e){a(this,"fetch");a(this,"host");a(this,"projectKey");a(this,"requestTimeoutMs");this.fetch=a$1(e.fetch),this.host=d(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async inbox(e){let s=this.requireFetch(),r=`${this.host}/v1/messages?distinct_id=${encodeURIComponent(e)}`,n=await this.request(s,r,{headers:this.authHeaders(),method:"GET"});if(!n.ok)throw new l(`inbox request failed with status ${n.status}`,n.status);return JSON.parse(await n.text()).messages??[]}async markRead(e,s){let r=this.requireFetch(),n=`${this.host}/v1/messages/read`,o=await this.request(r,n,{body:JSON.stringify({distinct_id:s,message_id:e}),headers:{...this.authHeaders(),"content-type":"application/json"},method:"POST"});if(!o.ok)throw new l(`mark-read request failed with status ${o.status}`,o.status)}requireFetch(){if(!this.fetch)throw new l("no fetch implementation available in this runtime");return this.fetch}authHeaders(){return {authorization:`Bearer ${this.projectKey}`}}async request(e,s,r){let n=b$1(),o=n?setTimeout(()=>n.abort(),this.requestTimeoutMs):void 0;try{return await e(s,{...r,signal:n?.signal})}finally{o!==void 0&&clearTimeout(o);}}};function N(t){return t>=400&&t<500&&t!==429}var I=class{constructor(e={}){a(this,"fetch");a(this,"maxRetries");a(this,"requestTimeoutMs");a(this,"baseDelayMs");a(this,"maxDelayMs");a(this,"sleep");a(this,"random");this.fetch=a$1(e.fetch),this.maxRetries=e.maxRetries??3,this.requestTimeoutMs=e.requestTimeoutMs??1e4,this.baseDelayMs=e.baseDelayMs??500,this.maxDelayMs=e.maxDelayMs??3e4,this.sleep=e.sleep??c$1,this.random=e.random??Math.random;}async send(e){let s=this.fetch;if(!s)throw new l("no fetch implementation available in this runtime");let r=JSON.stringify(e.body),n;for(let o=0;o<=this.maxRetries;o+=1){try{let a=await this.attempt(s,e,r);if(a.ok)return;if(N(a.status))throw new l(`ingest rejected batch with status ${a.status}`,a.status);n=new l(`ingest transient status ${a.status}`,a.status);}catch(a){if(a instanceof l&&a.status!==void 0&&N(a.status))throw a;n=a;}o<this.maxRetries&&await this.sleep(this.backoff(o));}throw new l("ingest delivery failed after retries",void 0,{cause:n})}async attempt(e,s,r){let n=b$1(),o=n?setTimeout(()=>n.abort(),this.requestTimeoutMs):void 0;try{return await e(s.url,{body:r,headers:{authorization:`Bearer ${s.projectKey}`,"content-type":"application/json"},method:"POST",signal:n?.signal})}finally{o!==void 0&&clearTimeout(o);}}backoff(e){return Math.min(this.maxDelayMs,this.baseDelayMs*2**e)+this.random()*this.baseDelayMs}};var O={now:()=>new Date};function E(t){return t.toISOString()}function G(){return globalThis.crypto}function X(t){t[6]=t[6]&15|64,t[8]=t[8]&63|128;let e=[];for(let s=0;s<16;s+=1)e.push(t[s].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 Y(){let t=G();if(t?.randomUUID)return t.randomUUID();let e=new Uint8Array(16);if(t?.getRandomValues)t.getRandomValues(e);else for(let s=0;s<16;s+=1)e[s]=Math.floor(Math.random()*256);return X(e)}var D={uuid:Y};var Z=/^pdx_pub_(?:(?:live|test)_)?[a-z0-9]{32}$/;var W=/^(?:\$|[a-z])[a-z0-9_.]*$/;function K(t){let e=0;for(let s of t)e+=1;return e}function L(t){return Z.test(t)}function ee(t){return W.test(t)}function j(t){let e=K(t);if(e<1||e>200)throw new m("distinct_id","distinct_id must be between 1 and 200 characters")}function V(t){let e=K(t);if(e<1||e>200)throw new m("event_name","event_name must be between 1 and 200 characters");if(!ee(t))throw new m("event_name","event_name must match /^(\\$|[a-z])[a-z0-9_.]*$/")}var te=t=>{};function z(t){if(!t.apiKey||!L(t.apiKey))throw new y("apiKey must be a public project key of the form pdx_pub_<32 lowercase alphanumerics>");if(!t.host)throw new y("host is required (the ingest base URL)");let e=d(t.host),s=t.defaultProperties;return {apiKey:t.apiKey,autocapture:t.autocapture??false,clock:t.clock??O,defaultProperties:typeof s=="function"?s:()=>s??{},flagsHost:t.flagsHost?d(t.flagsHost):e,flushAt:t.flushAt??20,flushIntervalMs:t.flushIntervalMs??1e4,host:e,ids:t.ids??D,locale:t.locale,maxQueueSize:t.maxQueueSize??1e3,maxRetries:t.maxRetries??3,namespace:t.apiKey.slice(0,16),onError:t.onError??te,os:t.os,requestTimeoutMs:t.requestTimeoutMs??1e4,sdkName:t.sdkName??_,sdkVersion:t.sdkVersion??C,storage:t.storage??new g,transport:t.transport}}function J(t,e,s){V(t.eventName),j(t.distinctId);let r={distinct_id:t.distinctId,event_id:t.eventId??s.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 w=class{constructor(e,s,r){this.storage=e;this.ids=s;this.namespace=r;a(this,"anonymousId");a(this,"distinctId");a(this,"identified");let n=e.getItem(this.key("anonymous_id"));n?this.anonymousId=n:(this.anonymousId=s.uuid(),e.setItem(this.key("anonymous_id"),this.anonymousId));let o=e.getItem(this.key("distinct_id"));o?(this.distinctId=o,this.identified=true):(this.distinctId=this.anonymousId,this.identified=false);}getAnonymousId(){return this.anonymousId}getDistinctId(){return this.distinctId}isIdentified(){return this.identified}snapshot(){return {anonymousId:this.anonymousId,distinctId:this.distinctId,identified:this.identified}}identify(e){return this.identified&&this.distinctId===e?{changed:false}:(this.distinctId=e,this.identified=true,this.storage.setItem(this.key("distinct_id"),e),{changed:true})}reset(){this.anonymousId=this.ids.uuid(),this.distinctId=this.anonymousId,this.identified=false,this.storage.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.removeItem(this.key("distinct_id"));}key(e){return `pdx.${this.namespace}.${e}`}};var F=class{constructor(e,s){this.maxSize=e;this.onOverflow=s;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 s=e===void 0?this.events.length:Math.min(e,this.events.length);return this.events.splice(0,s)}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 se="queue",re=1e3,ne=3e4,Q=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},S=class{constructor(e){a(this,"config");a(this,"identity");a(this,"queue");a(this,"transport");a(this,"flagsClient");a(this,"messagesClient");a(this,"context");a(this,"flushTimer");a(this,"flushing",false);a(this,"cachedFlags");a(this,"cachedSnapshot");this.config=z(e),this.identity=new w(this.config.storage,this.config.ids,this.config.namespace),this.queue=new F(this.config.maxQueueSize,({dropped:s})=>{this.config.onError(new c("queue_overflow",`event queue overflow: dropped ${s.length} oldest event(s)`));}),this.transport=this.config.transport??new I({maxRetries:this.config.maxRetries,requestTimeoutMs:this.config.requestTimeoutMs}),this.flagsClient=new x({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.messagesClient=new b({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,s={}){try{let r={...this.config.defaultProperties(),...s.properties??{}},n=J({context:this.context,distinctId:this.identity.getDistinctId(),eventName:e,properties:r,sessionId:s.sessionId,timestamp:s.timestamp},this.config.clock,this.config.ids);this.enqueue(n);}catch(r){this.config.onError(r);}}identify(e,s={}){let r=this.identity.getAnonymousId(),n=!this.identity.isIdentified(),o=this.identity.identify(e),a={};n&&o.changed&&(a.$anon_distinct_id=r);let T={...Q(s.traits??{}),...s.set??{}};Object.keys(T).length>0&&(a.$set=T),this.capture("$identify",{properties:a});}alias(e){this.capture("$create_alias",{properties:{alias:e}});}group(e,s,r){let n={$group_key:s,$group_type:e};r&&(n.$set=r),this.capture("$group",{properties:n});}setPersonProperties(e,s){let r={};e&&(r.$set=e),s&&(r.$set_once=s),this.capture("$set",{properties:r});}setPersonTraits(e){let s=Q(e);Object.keys(s).length!==0&&this.capture("$set",{properties:{$set:s}});}async getAllFlags(){let e=this.identity.getDistinctId(),s=await this.flagsClient.fetchAll(e);return this.cachedFlags={distinctId:e,flags:s},s}async isFeatureEnabled(e){return (await this.getAllFlags())[e]??false}getCachedFlag(e){if(!(!this.cachedFlags||this.cachedFlags.distinctId!==this.distinctId))return this.cachedFlags.flags[e]}async getLocalFlags(e={}){let s=await this.flagSnapshot();return A(s.flags,{attributes:e.attributes,distinctId:this.identity.getDistinctId(),properties:e.properties})}async isFeatureEnabledLocal(e,s){return (await this.getLocalFlags(s))[e]??false}async flagSnapshot(){let e=this.config.clock.now().getTime();if(this.cachedSnapshot&&e-this.cachedSnapshot.fetchedAt<ne)return this.cachedSnapshot.snapshot;let s=await this.flagsClient.snapshot();return this.cachedSnapshot={fetchedAt:e,snapshot:s},s}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(re);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(s){this.queue.requeue(e),this.persistQueue(),this.config.onError(s);}finally{this.flushing=false;}}reset(){this.identity.reset(),this.cachedFlags=void 0,this.cachedSnapshot=void 0;}async shutdown(){this.stopTimer(),await this.flush();}enqueue(e){this.queue.enqueue(e),this.persistQueue(),this.queue.size>=this.config.flushAt&&this.flush();}persistQueue(){try{this.config.storage.setItem(this.persistKey(),JSON.stringify(this.queue.snapshot()));}catch(e){this.config.onError(e);}}restoreQueue(){try{let e=this.config.storage.getItem(this.persistKey());if(!e)return;let s=JSON.parse(e);Array.isArray(s)&&this.queue.restore(s);}catch(e){this.config.onError(e);}}startTimer(){if(this.config.flushIntervalMs<=0)return;let e=setInterval(()=>{this.flush();},this.config.flushIntervalMs),s=e;typeof s.unref=="function"&&s.unref(),this.flushTimer=e;}stopTimer(){this.flushTimer!==void 0&&(clearInterval(this.flushTimer),this.flushTimer=void 0);}persistKey(){return `pdx.${this.config.namespace}.${se}`}};function st(t){return new S(t)}export{c as a,y as b,m as c,l as d,g as e,ae as f,Y as g,_ as h,C as i,k as j,q as k,B as l,A as m,H as n,he as o,x as p,b as q,I as r,S as s,st as t};//# sourceMappingURL=chunk-7J6AQICL.js.map
|
|
2
|
-
//# sourceMappingURL=chunk-7J6AQICL.js.map
|