@prodantix/sdk 0.0.1 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -4
- package/dist/chat.cjs +65 -0
- package/dist/chat.d.cts +75 -0
- package/dist/chat.d.ts +75 -0
- package/dist/chat.js +65 -0
- package/dist/chunk-5XGN7UAV.js +2 -0
- package/dist/chunk-7J6AQICL.js +2 -0
- package/dist/chunk-VG77TYVX.js +2 -0
- package/dist/{client-B1bcIuD8.d.cts → client-BBUAoQg2.d.cts} +28 -1
- package/dist/{client-B1bcIuD8.d.ts → client-BBUAoQg2.d.ts} +28 -1
- package/dist/config-B-cTz9n1.d.ts +94 -0
- package/dist/config-OP9Csae6.d.cts +94 -0
- package/dist/csp.cjs +3 -0
- package/dist/csp.d.cts +37 -0
- package/dist/csp.d.ts +37 -0
- package/dist/csp.js +3 -0
- package/dist/http-BCh716Vs.d.cts +14 -0
- package/dist/http-BCh716Vs.d.ts +14 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +15 -5
- package/dist/index.d.ts +15 -5
- package/dist/index.js +1 -1
- package/dist/messenger.cjs +2 -0
- package/dist/messenger.d.cts +2 -0
- package/dist/messenger.d.ts +2 -0
- package/dist/messenger.iife.js +65 -0
- package/dist/messenger.js +2 -0
- package/dist/node.cjs +1 -1
- package/dist/node.d.cts +1 -1
- package/dist/node.d.ts +1 -1
- package/dist/node.js +1 -1
- package/dist/{transport-By6wsdny.d.ts → transport-DhhzvwpV.d.cts} +3 -15
- package/dist/{transport-B3PxeUxW.d.cts → transport-dWp3NUMj.d.ts} +3 -15
- package/dist/web.cjs +1 -1
- package/dist/web.d.cts +3 -2
- package/dist/web.d.ts +3 -2
- package/dist/web.js +1 -1
- package/package.json +19 -3
- package/dist/chunk-FIZWZVZG.js +0 -2
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { F as FetchLike } from './http-BCh716Vs.cjs';
|
|
2
|
+
|
|
3
|
+
interface ChatTurn {
|
|
4
|
+
id: string;
|
|
5
|
+
authorKind: 'end_user' | 'agent' | 'ai';
|
|
6
|
+
authorId: string | null;
|
|
7
|
+
body: string;
|
|
8
|
+
createdAt: string;
|
|
9
|
+
}
|
|
10
|
+
interface ChatThread {
|
|
11
|
+
id: string;
|
|
12
|
+
status: string;
|
|
13
|
+
turns: ChatTurn[];
|
|
14
|
+
}
|
|
15
|
+
interface ChatClientOptions {
|
|
16
|
+
apiKey: string;
|
|
17
|
+
host: string;
|
|
18
|
+
distinctId: string;
|
|
19
|
+
storage?: ChatStorage;
|
|
20
|
+
fetchImpl?: FetchLike;
|
|
21
|
+
onError?: (error: unknown) => void;
|
|
22
|
+
}
|
|
23
|
+
interface ChatIdentity {
|
|
24
|
+
userId: string;
|
|
25
|
+
userHash: string;
|
|
26
|
+
}
|
|
27
|
+
interface ChatStorage {
|
|
28
|
+
get(key: string): string | null;
|
|
29
|
+
set(key: string, value: string): void;
|
|
30
|
+
remove(key: string): void;
|
|
31
|
+
}
|
|
32
|
+
declare class ChatClient {
|
|
33
|
+
private readonly options;
|
|
34
|
+
private readonly fetchImpl?;
|
|
35
|
+
private readonly host;
|
|
36
|
+
private readonly storage?;
|
|
37
|
+
private handle;
|
|
38
|
+
private identity;
|
|
39
|
+
constructor(options: ChatClientOptions);
|
|
40
|
+
get hasThread(): boolean;
|
|
41
|
+
get socketAuth(): {
|
|
42
|
+
conversationId: string;
|
|
43
|
+
conversationToken: string;
|
|
44
|
+
projectKey: string;
|
|
45
|
+
} | null;
|
|
46
|
+
identify(identity: ChatIdentity): void;
|
|
47
|
+
ensureThread(subject?: string): Promise<boolean>;
|
|
48
|
+
send(body: string): Promise<ChatTurn | null>;
|
|
49
|
+
load(): Promise<ChatThread | null>;
|
|
50
|
+
private readHandle;
|
|
51
|
+
private request;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
type MessengerSkin = 'concierge' | 'console' | 'quiet';
|
|
55
|
+
type LauncherStyle = 'avatar_circle' | 'circle_filled' | 'circle_outlined' | 'pill_labelled' | 'pill_team' | 'squircle_filled';
|
|
56
|
+
type BubbleStyle = 'hairline' | 'outlined' | 'rounded' | 'tailed';
|
|
57
|
+
type NamePlacement = 'above' | 'avatar_only' | 'gutter' | 'hidden' | 'inline';
|
|
58
|
+
type TimestampStyle = 'cluster' | 'latency' | 'none' | 'trailing' | 'with_name';
|
|
59
|
+
interface AppearanceSettings {
|
|
60
|
+
bubbleStyle: BubbleStyle;
|
|
61
|
+
launcherStyle: LauncherStyle;
|
|
62
|
+
namePlacement: NamePlacement;
|
|
63
|
+
skin: MessengerSkin;
|
|
64
|
+
timestampStyle: TimestampStyle;
|
|
65
|
+
}
|
|
66
|
+
declare const DEFAULT_APPEARANCE_SETTINGS: AppearanceSettings;
|
|
67
|
+
declare function resolveAppearance(config: Partial<AppearanceSettings> | null | undefined): AppearanceSettings;
|
|
68
|
+
|
|
69
|
+
interface MessengerConfig extends AppearanceSettings {
|
|
70
|
+
enabled: boolean;
|
|
71
|
+
launcherPosition: 'bottom_left' | 'bottom_right';
|
|
72
|
+
launcherOffsetX: number;
|
|
73
|
+
launcherOffsetY: number;
|
|
74
|
+
accentColor: string;
|
|
75
|
+
greeting: string;
|
|
76
|
+
awayMessage: string;
|
|
77
|
+
availability: unknown;
|
|
78
|
+
version: string;
|
|
79
|
+
starterPrompts: string[];
|
|
80
|
+
socketUrl: string;
|
|
81
|
+
}
|
|
82
|
+
interface MessengerConfigOptions {
|
|
83
|
+
apiKey: string;
|
|
84
|
+
host: string;
|
|
85
|
+
locale?: string;
|
|
86
|
+
storage?: ChatStorage;
|
|
87
|
+
fetchImpl?: FetchLike;
|
|
88
|
+
onError?: (error: unknown) => void;
|
|
89
|
+
}
|
|
90
|
+
declare const MESSENGER_CACHE_KEY = "prodantix.messenger.config";
|
|
91
|
+
declare function cachedMessengerConfig(storage: ChatStorage | undefined, apiKey: string): MessengerConfig | null;
|
|
92
|
+
declare function fetchMessengerConfig(options: MessengerConfigOptions): Promise<MessengerConfig | null>;
|
|
93
|
+
|
|
94
|
+
export { type AppearanceSettings as A, type BubbleStyle as B, ChatClient as C, DEFAULT_APPEARANCE_SETTINGS as D, type LauncherStyle as L, type MessengerConfig as M, type NamePlacement as N, type TimestampStyle as T, type ChatTurn as a, type ChatIdentity as b, type ChatClientOptions as c, type ChatStorage as d, type ChatThread as e, type MessengerSkin as f, MESSENGER_CACHE_KEY as g, type MessengerConfigOptions as h, cachedMessengerConfig as i, fetchMessengerConfig as j, resolveAppearance as r };
|
package/dist/csp.cjs
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
'use strict';function r(n){let t=n?.trim()??"";if(t==="")return null;try{return new URL(t).origin}catch{return null}}function s(n){return n.startsWith("https://")?`wss://${n.slice(8)}`:n.startsWith("http://")?`ws://${n.slice(7)}`:null}function i(n){return [...new Set(["'self'",...n.filter(t=>t!==null)])].join(" ")}function l(n,t=[]){let e=r(n.edge);return i([...t,r(n.ingest),e,e===null?null:s(e),r(n.replay)])}function o(n,t=[]){return i([...t,r(n.edge)])}
|
|
2
|
+
exports.prodantixConnectSrc=l;exports.prodantixScriptSrc=o;//# sourceMappingURL=csp.cjs.map
|
|
3
|
+
//# sourceMappingURL=csp.cjs.map
|
package/dist/csp.d.cts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/** The content-security-policy sources an app needs to reach prodantix.
|
|
2
|
+
*
|
|
3
|
+
* Imported by `next.config.ts`, so this module must stay free of React and of
|
|
4
|
+
* anything that only resolves in the browser. A browser-only import here breaks
|
|
5
|
+
* the BUILD rather than the page, which is at least loud.
|
|
6
|
+
*
|
|
7
|
+
* Moved out of `@bomdisoft/analytics` when that package was retired, and
|
|
8
|
+
* extended. The original emitted the analytics host alone, which was correct
|
|
9
|
+
* while events were the only thing the SDK sent. The messenger adds a websocket
|
|
10
|
+
* and a script, and a policy that is too narrow fails only in a visitor's
|
|
11
|
+
* browser console: nine sites permitted the analytics host and would have
|
|
12
|
+
* blocked the messenger with nothing on our side to show for it.
|
|
13
|
+
*
|
|
14
|
+
* Every app that installs the SDK posts to `${host}/v1/…`, and a policy of
|
|
15
|
+
* `'self'` blocks that in every environment, not only locally: these hosts are
|
|
16
|
+
* different origins from the site in staging and production too. Analytics
|
|
17
|
+
* never worked from any of these apps until that was derived from the same env
|
|
18
|
+
* var the component reads.
|
|
19
|
+
*/
|
|
20
|
+
interface ProdantixHosts {
|
|
21
|
+
/** Event ingest, e.g. `https://eu.api.prodantix.com`. */
|
|
22
|
+
ingest?: string;
|
|
23
|
+
/** The public browser edge: flags, messages, conversations, the messenger. */
|
|
24
|
+
edge?: string;
|
|
25
|
+
/** Session replay, when the app enables it. */
|
|
26
|
+
replay?: string;
|
|
27
|
+
}
|
|
28
|
+
/** Everything the SDK CONNECTS to: ingest, the edge, replay, and the edge's
|
|
29
|
+
* websocket. */
|
|
30
|
+
declare function prodantixConnectSrc(hosts: ProdantixHosts, extra?: readonly string[]): string;
|
|
31
|
+
/** Where a SCRIPT may be fetched from, which is the edge alone: it serves
|
|
32
|
+
* `/messenger.js` and the other hosts serve no script at all. Emitting them
|
|
33
|
+
* here would widen the policy for nothing, and a needlessly wide script-src is
|
|
34
|
+
* the one direction of CSP error that never announces itself. */
|
|
35
|
+
declare function prodantixScriptSrc(hosts: ProdantixHosts, extra?: readonly string[]): string;
|
|
36
|
+
|
|
37
|
+
export { type ProdantixHosts, prodantixConnectSrc, prodantixScriptSrc };
|
package/dist/csp.d.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/** The content-security-policy sources an app needs to reach prodantix.
|
|
2
|
+
*
|
|
3
|
+
* Imported by `next.config.ts`, so this module must stay free of React and of
|
|
4
|
+
* anything that only resolves in the browser. A browser-only import here breaks
|
|
5
|
+
* the BUILD rather than the page, which is at least loud.
|
|
6
|
+
*
|
|
7
|
+
* Moved out of `@bomdisoft/analytics` when that package was retired, and
|
|
8
|
+
* extended. The original emitted the analytics host alone, which was correct
|
|
9
|
+
* while events were the only thing the SDK sent. The messenger adds a websocket
|
|
10
|
+
* and a script, and a policy that is too narrow fails only in a visitor's
|
|
11
|
+
* browser console: nine sites permitted the analytics host and would have
|
|
12
|
+
* blocked the messenger with nothing on our side to show for it.
|
|
13
|
+
*
|
|
14
|
+
* Every app that installs the SDK posts to `${host}/v1/…`, and a policy of
|
|
15
|
+
* `'self'` blocks that in every environment, not only locally: these hosts are
|
|
16
|
+
* different origins from the site in staging and production too. Analytics
|
|
17
|
+
* never worked from any of these apps until that was derived from the same env
|
|
18
|
+
* var the component reads.
|
|
19
|
+
*/
|
|
20
|
+
interface ProdantixHosts {
|
|
21
|
+
/** Event ingest, e.g. `https://eu.api.prodantix.com`. */
|
|
22
|
+
ingest?: string;
|
|
23
|
+
/** The public browser edge: flags, messages, conversations, the messenger. */
|
|
24
|
+
edge?: string;
|
|
25
|
+
/** Session replay, when the app enables it. */
|
|
26
|
+
replay?: string;
|
|
27
|
+
}
|
|
28
|
+
/** Everything the SDK CONNECTS to: ingest, the edge, replay, and the edge's
|
|
29
|
+
* websocket. */
|
|
30
|
+
declare function prodantixConnectSrc(hosts: ProdantixHosts, extra?: readonly string[]): string;
|
|
31
|
+
/** Where a SCRIPT may be fetched from, which is the edge alone: it serves
|
|
32
|
+
* `/messenger.js` and the other hosts serve no script at all. Emitting them
|
|
33
|
+
* here would widen the policy for nothing, and a needlessly wide script-src is
|
|
34
|
+
* the one direction of CSP error that never announces itself. */
|
|
35
|
+
declare function prodantixScriptSrc(hosts: ProdantixHosts, extra?: readonly string[]): string;
|
|
36
|
+
|
|
37
|
+
export { type ProdantixHosts, prodantixConnectSrc, prodantixScriptSrc };
|
package/dist/csp.js
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import'./chunk-5XGN7UAV.js';function r(n){let t=n?.trim()??"";if(t==="")return null;try{return new URL(t).origin}catch{return null}}function s(n){return n.startsWith("https://")?`wss://${n.slice(8)}`:n.startsWith("http://")?`ws://${n.slice(7)}`:null}function i(n){return [...new Set(["'self'",...n.filter(t=>t!==null)])].join(" ")}function l(n,t=[]){let e=r(n.edge);return i([...t,r(n.ingest),e,e===null?null:s(e),r(n.replay)])}function o(n,t=[]){return i([...t,r(n.edge)])}
|
|
2
|
+
export{l as prodantixConnectSrc,o as prodantixScriptSrc};//# sourceMappingURL=csp.js.map
|
|
3
|
+
//# sourceMappingURL=csp.js.map
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
interface FetchResponseLike {
|
|
2
|
+
ok: boolean;
|
|
3
|
+
status: number;
|
|
4
|
+
text(): Promise<string>;
|
|
5
|
+
}
|
|
6
|
+
interface FetchInit {
|
|
7
|
+
body?: string;
|
|
8
|
+
headers: Record<string, string>;
|
|
9
|
+
method: string;
|
|
10
|
+
signal?: AbortSignal;
|
|
11
|
+
}
|
|
12
|
+
type FetchLike = (url: string, init: FetchInit) => Promise<FetchResponseLike>;
|
|
13
|
+
|
|
14
|
+
export type { FetchLike as F };
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
interface FetchResponseLike {
|
|
2
|
+
ok: boolean;
|
|
3
|
+
status: number;
|
|
4
|
+
text(): Promise<string>;
|
|
5
|
+
}
|
|
6
|
+
interface FetchInit {
|
|
7
|
+
body?: string;
|
|
8
|
+
headers: Record<string, string>;
|
|
9
|
+
method: string;
|
|
10
|
+
signal?: AbortSignal;
|
|
11
|
+
}
|
|
12
|
+
type FetchLike = (url: string, init: FetchInit) => Promise<FetchResponseLike>;
|
|
13
|
+
|
|
14
|
+
export type { FetchLike as F };
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var Q=Object.defineProperty;var U=(t,e,r)=>e in t?Q(t,e,{enumerable:true,configurable:true,writable:true,value:r}):t[e]=r;var i=(t,e,r)=>U(t,typeof e!="symbol"?e+"":e,r);var d=class extends Error{constructor(r,s,n){super(s,n);i(this,"code");this.code=r,this.name="ProdantixError";}},m=class extends d{constructor(e){super("config",e),this.name="ConfigError";}},c=class extends d{constructor(r,s){super("validation",s);i(this,"field");this.field=r,this.name="ValidationError";}},l=class extends d{constructor(r,s,n){super("transport",r,n);i(this,"status");this.status=s,this.name="TransportError";}};function g(t){if(t)return t;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function u(){let t=globalThis.AbortController;return t?new t:void 0}var _=t=>new Promise(e=>{setTimeout(e,t);});function p(t){return t.replace(/\/+$/,"")}var y=class{constructor(){i(this,"store",new Map);}getItem(e){return this.store.get(e)??null}removeItem(e){this.store.delete(e);}setItem(e,r){this.store.set(e,r);}};var R={now:()=>new Date};function I(t){return t.toISOString()}function B(){return globalThis.crypto}function H(t){t[6]=t[6]&15|64,t[8]=t[8]&63|128;let e=[];for(let r=0;r<16;r+=1)e.push(t[r].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 G(){let t=B();if(t?.randomUUID)return t.randomUUID();let e=new Uint8Array(16);if(t?.getRandomValues)t.getRandomValues(e);else for(let r=0;r<16;r+=1)e[r]=Math.floor(Math.random()*256);return H(e)}var M={uuid:G};var X=/^pdx_pub_(?:(?:live|test)_)?[a-z0-9]{32}$/;var Y=/^(?:\$|[a-z])[a-z0-9_.]*$/;function A(t){let e=0;for(let r of t)e+=1;return e}function q(t){return X.test(t)}function Z(t){return Y.test(t)}function $(t){let e=A(t);if(e<1||e>200)throw new c("distinct_id","distinct_id must be between 1 and 200 characters")}function N(t){let e=A(t);if(e<1||e>200)throw new c("event_name","event_name must be between 1 and 200 characters");if(!Z(t))throw new c("event_name","event_name must match /^(\\$|[a-z])[a-z0-9_.]*$/")}var k="prodantix-js",T="0.0.1";var W=t=>{};function O(t){if(!t.apiKey||!q(t.apiKey))throw new m("apiKey must be a public project key of the form pdx_pub_<32 lowercase alphanumerics>");if(!t.host)throw new m("host is required (the ingest base URL)");let e=p(t.host),r=t.defaultProperties;return {apiKey:t.apiKey,autocapture:t.autocapture??false,clock:t.clock??R,defaultProperties:typeof r=="function"?r:()=>r??{},flagsHost:t.flagsHost?p(t.flagsHost):e,flushAt:t.flushAt??20,flushIntervalMs:t.flushIntervalMs??1e4,host:e,ids:t.ids??M,locale:t.locale,maxQueueSize:t.maxQueueSize??1e3,maxRetries:t.maxRetries??3,namespace:t.apiKey.slice(0,16),onError:t.onError??W,os:t.os,requestTimeoutMs:t.requestTimeoutMs??1e4,sdkName:t.sdkName??k,sdkVersion:t.sdkVersion??T,storage:t.storage??new y,transport:t.transport}}function D(t,e,r){N(t.eventName),$(t.distinctId);let s={distinct_id:t.distinctId,event_id:t.eventId??r.uuid(),event_name:t.eventName,properties:t.properties??{},schema_version:1,timestamp:I(t.timestamp??e.now())};return t.context&&(s.context=t.context),t.sessionId&&(s.session_id=t.sessionId),s}var f=Symbol("absent");function ee(t,e){if(t==="distinct_id")return e.distinctId;let r=e.properties??{};if(Object.prototype.hasOwnProperty.call(r,t))return r[t];let s=e.attributes??{};return Object.prototype.hasOwnProperty.call(s,t)?s[t]:f}function h(t){return t===f?"undefined":String(t)}function K(t){return t===f?Number.NaN:Number(t)}function L(t){return t!==f&&t!==null&&t!==""}function j(t,e){if(!Array.isArray(e))return false;let r=h(t);return e.map(s=>String(s)).includes(r)}function C(t,e){let r=ee(t.attribute,e),s=t.value;switch(t.op){case "is_set":return L(r);case "is_not_set":return !L(r);case "eq":return h(r)===h(s===void 0?f:s);case "neq":return h(r)!==h(s===void 0?f:s);case "contains":return h(r).includes(h(s===void 0?f:s));case "in":return j(r,s);case "not_in":return Array.isArray(s)?!j(r,s):false;case "gt":return E(r,s,(n,o)=>n>o);case "gte":return E(r,s,(n,o)=>n>=o);case "lt":return E(r,s,(n,o)=>n<o);case "lte":return E(r,s,(n,o)=>n<=o);default:return false}}function E(t,e,r){let s=K(t),n=e===void 0?Number.NaN:K(e);return Number.isNaN(s)||Number.isNaN(n)?false:r(s,n)}function V(t,e){let r=`${t}:${e}`,s=2166136261;for(let n=0;n<r.length;n++)s^=r.charCodeAt(n),s=Math.imul(s,16777619);return (s>>>0)%100}function z(t,e){return t.enabled?t.targeting.length>0&&!t.targeting.every(r=>C(r,e))?{enabled:false,reason:"targeting"}:t.rolloutPercentage>=100?{enabled:true,reason:"rollout_full"}:V(t.key,e.distinctId)<t.rolloutPercentage?{enabled:true,reason:"rollout"}:{enabled:false,reason:"rollout_excluded"}:{enabled:false,reason:"disabled"}}function P(t,e){let r={};for(let s of t)r[s.key]=z(s,e).enabled;return r}var v=class{constructor(e){i(this,"fetch");i(this,"host");i(this,"projectKey");i(this,"requestTimeoutMs");this.fetch=g(e.fetch),this.host=p(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async fetchAll(e){let r=this.fetch;if(!r)throw new l("no fetch implementation available in this runtime");let s=`${this.host}/v1/flags?distinct_id=${encodeURIComponent(e)}`,n=u(),o=n?setTimeout(()=>n.abort(),this.requestTimeoutMs):void 0;try{let a=await r(s,{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 r=`${this.host}/v1/flags/snapshot`,s=u(),n=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{let o=await e(r,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:s?.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 F=class{constructor(e,r,s){this.storage=e;this.ids=r;this.namespace=s;i(this,"anonymousId");i(this,"distinctId");i(this,"identified");let n=e.getItem(this.key("anonymous_id"));n?this.anonymousId=n:(this.anonymousId=r.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 x=class{constructor(e){i(this,"fetch");i(this,"host");i(this,"projectKey");i(this,"requestTimeoutMs");this.fetch=g(e.fetch),this.host=p(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async inbox(e){let r=this.requireFetch(),s=`${this.host}/v1/messages?distinct_id=${encodeURIComponent(e)}`,n=await this.request(r,s,{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,r){let s=this.requireFetch(),n=`${this.host}/v1/messages/read`,o=await this.request(s,n,{body:JSON.stringify({distinct_id:r,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,r,s){let n=u(),o=n?setTimeout(()=>n.abort(),this.requestTimeoutMs):void 0;try{return await e(r,{...s,signal:n?.signal})}finally{o!==void 0&&clearTimeout(o);}}};var w=class{constructor(e,r){this.maxSize=e;this.onOverflow=r;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 r=e===void 0?this.events.length:Math.min(e,this.events.length);return this.events.splice(0,r)}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 J(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=g(e.fetch),this.maxRetries=e.maxRetries??3,this.requestTimeoutMs=e.requestTimeoutMs??1e4,this.baseDelayMs=e.baseDelayMs??500,this.maxDelayMs=e.maxDelayMs??3e4,this.sleep=e.sleep??_,this.random=e.random??Math.random;}async send(e){let r=this.fetch;if(!r)throw new l("no fetch implementation available in this runtime");let s=JSON.stringify(e.body),n;for(let o=0;o<=this.maxRetries;o+=1){try{let a=await this.attempt(r,e,s);if(a.ok)return;if(J(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&&J(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,r,s){let n=u(),o=n?setTimeout(()=>n.abort(),this.requestTimeoutMs):void 0;try{return await e(r.url,{body:s,headers:{authorization:`Bearer ${r.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 te="queue",re=1e3,se=3e4,S=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=O(e),this.identity=new F(this.config.storage,this.config.ids,this.config.namespace),this.queue=new w(this.config.maxQueueSize,({dropped:r})=>{this.config.onError(new d("queue_overflow",`event queue overflow: dropped ${r.length} oldest event(s)`));}),this.transport=this.config.transport??new b({maxRetries:this.config.maxRetries,requestTimeoutMs:this.config.requestTimeoutMs}),this.flagsClient=new v({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.messagesClient=new x({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,r={}){try{let s={...this.config.defaultProperties(),...r.properties??{}},n=D({context:this.context,distinctId:this.identity.getDistinctId(),eventName:e,properties:s,sessionId:r.sessionId,timestamp:r.timestamp},this.config.clock,this.config.ids);this.enqueue(n);}catch(s){this.config.onError(s);}}identify(e,r={}){let s=this.identity.getAnonymousId(),n=!this.identity.isIdentified(),o=this.identity.identify(e),a={};n&&o.changed&&(a.$anon_distinct_id=s),r.set&&(a.$set=r.set),this.capture("$identify",{properties:a});}alias(e){this.capture("$create_alias",{properties:{alias:e}});}group(e,r,s){let n={$group_key:r,$group_type:e};s&&(n.$set=s),this.capture("$group",{properties:n});}setPersonProperties(e,r){let s={};e&&(s.$set=e),r&&(s.$set_once=r),this.capture("$set",{properties:s});}async getAllFlags(){let e=this.identity.getDistinctId(),r=await this.flagsClient.fetchAll(e);return this.cachedFlags={distinctId:e,flags:r},r}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 r=await this.flagSnapshot();return P(r.flags,{attributes:e.attributes,distinctId:this.identity.getDistinctId(),properties:e.properties})}async isFeatureEnabledLocal(e,r){return (await this.getLocalFlags(r))[e]??false}async flagSnapshot(){let e=this.config.clock.now().getTime();if(this.cachedSnapshot&&e-this.cachedSnapshot.fetchedAt<se)return this.cachedSnapshot.snapshot;let r=await this.flagsClient.snapshot();return this.cachedSnapshot={fetchedAt:e,snapshot:r},r}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:I(this.config.clock.now())},projectKey:this.config.apiKey,url:`${this.config.host}/v1/events`}),this.persistQueue();}catch(r){this.queue.requeue(e),this.persistQueue(),this.config.onError(r);}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 r=JSON.parse(e);Array.isArray(r)&&this.queue.restore(r);}catch(e){this.config.onError(e);}}startTimer(){if(this.config.flushIntervalMs<=0)return;let e=setInterval(()=>{this.flush();},this.config.flushIntervalMs),r=e;typeof r.unref=="function"&&r.unref(),this.flushTimer=e;}stopTimer(){this.flushTimer!==void 0&&(clearInterval(this.flushTimer),this.flushTimer=void 0);}persistKey(){return `pdx.${this.config.namespace}.${te}`}};function ne(t){return new S(t)}exports.ConfigError=m;exports.FetchTransport=b;exports.FlagsClient=v;exports.MemoryStorage=y;exports.MessagesClient=x;exports.ProdantixClient=S;exports.ProdantixError=d;exports.SDK_NAME=k;exports.SDK_VERSION=T;exports.TransportError=l;exports.ValidationError=c;exports.bucket=V;exports.createClient=ne;exports.evaluateAll=P;exports.evaluateFlag=z;exports.matches=C;//# sourceMappingURL=index.cjs.map
|
|
1
|
+
'use strict';var H=Object.defineProperty;var G=(t,e,r)=>e in t?H(t,e,{enumerable:true,configurable:true,writable:true,value:r}):t[e]=r;var i=(t,e,r)=>G(t,typeof e!="symbol"?e+"":e,r);var d=class extends Error{constructor(r,s,n){super(s,n);i(this,"code");this.code=r,this.name="ProdantixError";}},m=class extends d{constructor(e){super("config",e),this.name="ConfigError";}},u=class extends d{constructor(r,s){super("validation",s);i(this,"field");this.field=r,this.name="ValidationError";}},l=class extends d{constructor(r,s,n){super("transport",r,n);i(this,"status");this.status=s,this.name="TransportError";}};function g(t){if(t)return t;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function c(){let t=globalThis.AbortController;return t?new t:void 0}var M=t=>new Promise(e=>{setTimeout(e,t);});function p(t){return t.replace(/\/+$/,"")}var y=class{constructor(){i(this,"store",new Map);}getItem(e){return this.store.get(e)??null}removeItem(e){this.store.delete(e);}setItem(e,r){this.store.set(e,r);}};var $={now:()=>new Date};function I(t){return t.toISOString()}function X(){return globalThis.crypto}function Y(t){t[6]=t[6]&15|64,t[8]=t[8]&63|128;let e=[];for(let r=0;r<16;r+=1)e.push(t[r].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 Z(){let t=X();if(t?.randomUUID)return t.randomUUID();let e=new Uint8Array(16);if(t?.getRandomValues)t.getRandomValues(e);else for(let r=0;r<16;r+=1)e[r]=Math.floor(Math.random()*256);return Y(e)}var A={uuid:Z};var W=/^pdx_pub_(?:(?:live|test)_)?[a-z0-9]{32}$/;var ee=/^(?:\$|[a-z])[a-z0-9_.]*$/;function q(t){let e=0;for(let r of t)e+=1;return e}function O(t){return W.test(t)}function te(t){return ee.test(t)}function N(t){let e=q(t);if(e<1||e>200)throw new u("distinct_id","distinct_id must be between 1 and 200 characters")}function D(t){let e=q(t);if(e<1||e>200)throw new u("event_name","event_name must be between 1 and 200 characters");if(!te(t))throw new u("event_name","event_name must match /^(\\$|[a-z])[a-z0-9_.]*$/")}var C="prodantix-js",P="0.0.1";var re=t=>{};function K(t){if(!t.apiKey||!O(t.apiKey))throw new m("apiKey must be a public project key of the form pdx_pub_<32 lowercase alphanumerics>");if(!t.host)throw new m("host is required (the ingest base URL)");let e=p(t.host),r=t.defaultProperties;return {apiKey:t.apiKey,autocapture:t.autocapture??false,clock:t.clock??$,defaultProperties:typeof r=="function"?r:()=>r??{},flagsHost:t.flagsHost?p(t.flagsHost):e,flushAt:t.flushAt??20,flushIntervalMs:t.flushIntervalMs??1e4,host:e,ids:t.ids??A,locale:t.locale,maxQueueSize:t.maxQueueSize??1e3,maxRetries:t.maxRetries??3,namespace:t.apiKey.slice(0,16),onError:t.onError??re,os:t.os,requestTimeoutMs:t.requestTimeoutMs??1e4,sdkName:t.sdkName??C,sdkVersion:t.sdkVersion??P,storage:t.storage??new y,transport:t.transport}}function L(t,e,r){D(t.eventName),N(t.distinctId);let s={distinct_id:t.distinctId,event_id:t.eventId??r.uuid(),event_name:t.eventName,properties:t.properties??{},schema_version:1,timestamp:I(t.timestamp??e.now())};return t.context&&(s.context=t.context),t.sessionId&&(s.session_id=t.sessionId),s}var f=Symbol("absent");function se(t,e){if(t==="distinct_id")return e.distinctId;let r=e.properties??{};if(Object.prototype.hasOwnProperty.call(r,t))return r[t];let s=e.attributes??{};return Object.prototype.hasOwnProperty.call(s,t)?s[t]:f}function h(t){return t===f?"undefined":String(t)}function V(t){return t===f?Number.NaN:Number(t)}function j(t){return t!==f&&t!==null&&t!==""}function z(t,e){if(!Array.isArray(e))return false;let r=h(t);return e.map(s=>String(s)).includes(r)}function F(t,e){let r=se(t.attribute,e),s=t.value;switch(t.op){case "is_set":return j(r);case "is_not_set":return !j(r);case "eq":return h(r)===h(s===void 0?f:s);case "neq":return h(r)!==h(s===void 0?f:s);case "contains":return h(r).includes(h(s===void 0?f:s));case "in":return z(r,s);case "not_in":return Array.isArray(s)?!z(r,s):false;case "gt":return E(r,s,(n,o)=>n>o);case "gte":return E(r,s,(n,o)=>n>=o);case "lt":return E(r,s,(n,o)=>n<o);case "lte":return E(r,s,(n,o)=>n<=o);default:return false}}function E(t,e,r){let s=V(t),n=e===void 0?Number.NaN:V(e);return Number.isNaN(s)||Number.isNaN(n)?false:r(s,n)}function _(t,e){let r=`${t}:${e}`,s=2166136261;for(let n=0;n<r.length;n++)s^=r.charCodeAt(n),s=Math.imul(s,16777619);return (s>>>0)%100}function J(t,e){return t.enabled?t.targeting.length>0&&!t.targeting.every(r=>F(r,e))?{enabled:false,reason:"targeting"}:t.rolloutPercentage>=100?{enabled:true,reason:"rollout_full"}:_(t.key,e.distinctId)<t.rolloutPercentage?{enabled:true,reason:"rollout"}:{enabled:false,reason:"rollout_excluded"}:{enabled:false,reason:"disabled"}}function R(t,e){let r={};for(let s of t)r[s.key]=J(s,e).enabled;return r}function Q(t,e){let r=t.variations??[],s=r[0];if(!s)return null;if(!t.enabled||t.targeting.length>0&&!t.targeting.every(a=>F(a,e)))return s;let n=_(t.key,e.distinctId),o=0;for(let a=r.length-1;a>=0;a--)if(o+=r[a].weight,n<o)return r[a];return s}function ne(t,e,r){let s=t.find(n=>n.key===e);return s?Q(s,r)?.value??null:null}var v=class{constructor(e){i(this,"fetch");i(this,"host");i(this,"projectKey");i(this,"requestTimeoutMs");this.fetch=g(e.fetch),this.host=p(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async fetchAll(e){let r=this.fetch;if(!r)throw new l("no fetch implementation available in this runtime");let s=`${this.host}/v1/flags?distinct_id=${encodeURIComponent(e)}`,n=c(),o=n?setTimeout(()=>n.abort(),this.requestTimeoutMs):void 0;try{let a=await r(s,{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 r=`${this.host}/v1/flags/snapshot`,s=c(),n=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{let o=await e(r,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:s?.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 k=class{constructor(e,r,s){this.storage=e;this.ids=r;this.namespace=s;i(this,"anonymousId");i(this,"distinctId");i(this,"identified");let n=e.getItem(this.key("anonymous_id"));n?this.anonymousId=n:(this.anonymousId=r.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 x=class{constructor(e){i(this,"fetch");i(this,"host");i(this,"projectKey");i(this,"requestTimeoutMs");this.fetch=g(e.fetch),this.host=p(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async inbox(e){let r=this.requireFetch(),s=`${this.host}/v1/messages?distinct_id=${encodeURIComponent(e)}`,n=await this.request(r,s,{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,r){let s=this.requireFetch(),n=`${this.host}/v1/messages/read`,o=await this.request(s,n,{body:JSON.stringify({distinct_id:r,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,r,s){let n=c(),o=n?setTimeout(()=>n.abort(),this.requestTimeoutMs):void 0;try{return await e(r,{...s,signal:n?.signal})}finally{o!==void 0&&clearTimeout(o);}}};var w=class{constructor(e,r){this.maxSize=e;this.onOverflow=r;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 r=e===void 0?this.events.length:Math.min(e,this.events.length);return this.events.splice(0,r)}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 U(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=g(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??M,this.random=e.random??Math.random;}async send(e){let r=this.fetch;if(!r)throw new l("no fetch implementation available in this runtime");let s=JSON.stringify(e.body),n;for(let o=0;o<=this.maxRetries;o+=1){try{let a=await this.attempt(r,e,s);if(a.ok)return;if(U(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&&U(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,r,s){let n=c(),o=n?setTimeout(()=>n.abort(),this.requestTimeoutMs):void 0;try{return await e(r.url,{body:s,headers:{authorization:`Bearer ${r.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 ie="queue",oe=1e3,ae=3e4,B=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},T=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=K(e),this.identity=new k(this.config.storage,this.config.ids,this.config.namespace),this.queue=new w(this.config.maxQueueSize,({dropped:r})=>{this.config.onError(new d("queue_overflow",`event queue overflow: dropped ${r.length} oldest event(s)`));}),this.transport=this.config.transport??new b({maxRetries:this.config.maxRetries,requestTimeoutMs:this.config.requestTimeoutMs}),this.flagsClient=new v({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.messagesClient=new x({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,r={}){try{let s={...this.config.defaultProperties(),...r.properties??{}},n=L({context:this.context,distinctId:this.identity.getDistinctId(),eventName:e,properties:s,sessionId:r.sessionId,timestamp:r.timestamp},this.config.clock,this.config.ids);this.enqueue(n);}catch(s){this.config.onError(s);}}identify(e,r={}){let s=this.identity.getAnonymousId(),n=!this.identity.isIdentified(),o=this.identity.identify(e),a={};n&&o.changed&&(a.$anon_distinct_id=s);let S={...B(r.traits??{}),...r.set??{}};Object.keys(S).length>0&&(a.$set=S),this.capture("$identify",{properties:a});}alias(e){this.capture("$create_alias",{properties:{alias:e}});}group(e,r,s){let n={$group_key:r,$group_type:e};s&&(n.$set=s),this.capture("$group",{properties:n});}setPersonProperties(e,r){let s={};e&&(s.$set=e),r&&(s.$set_once=r),this.capture("$set",{properties:s});}setPersonTraits(e){let r=B(e);Object.keys(r).length!==0&&this.capture("$set",{properties:{$set:r}});}async getAllFlags(){let e=this.identity.getDistinctId(),r=await this.flagsClient.fetchAll(e);return this.cachedFlags={distinctId:e,flags:r},r}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 r=await this.flagSnapshot();return R(r.flags,{attributes:e.attributes,distinctId:this.identity.getDistinctId(),properties:e.properties})}async isFeatureEnabledLocal(e,r){return (await this.getLocalFlags(r))[e]??false}async flagSnapshot(){let e=this.config.clock.now().getTime();if(this.cachedSnapshot&&e-this.cachedSnapshot.fetchedAt<ae)return this.cachedSnapshot.snapshot;let r=await this.flagsClient.snapshot();return this.cachedSnapshot={fetchedAt:e,snapshot:r},r}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(oe);try{await this.transport.send({body:{events:e,sent_at:I(this.config.clock.now())},projectKey:this.config.apiKey,url:`${this.config.host}/v1/events`}),this.persistQueue();}catch(r){this.queue.requeue(e),this.persistQueue(),this.config.onError(r);}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 r=JSON.parse(e);Array.isArray(r)&&this.queue.restore(r);}catch(e){this.config.onError(e);}}startTimer(){if(this.config.flushIntervalMs<=0)return;let e=setInterval(()=>{this.flush();},this.config.flushIntervalMs),r=e;typeof r.unref=="function"&&r.unref(),this.flushTimer=e;}stopTimer(){this.flushTimer!==void 0&&(clearInterval(this.flushTimer),this.flushTimer=void 0);}persistKey(){return `pdx.${this.config.namespace}.${ie}`}};function le(t){return new T(t)}exports.ConfigError=m;exports.FetchTransport=b;exports.FlagsClient=v;exports.MemoryStorage=y;exports.MessagesClient=x;exports.ProdantixClient=T;exports.ProdantixError=d;exports.SDK_NAME=C;exports.SDK_VERSION=P;exports.TransportError=l;exports.ValidationError=u;exports.assignVariant=Q;exports.bucket=_;exports.createClient=le;exports.evaluateAll=R;exports.evaluateFlag=J;exports.getVariant=ne;exports.matches=F;//# sourceMappingURL=index.cjs.map
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.d.cts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { J as JsonValue,
|
|
2
|
-
export { C as CaptureOptions, a as Clock, E as EventBatch, b as EventContext, c as EventEnvelope, d as EventProperties, F as FlagsResponse,
|
|
3
|
-
import { F as FetchLike } from './
|
|
4
|
-
export {
|
|
1
|
+
import { J as JsonValue, I as InboxMessage, S as StorageAdapter } from './client-BBUAoQg2.cjs';
|
|
2
|
+
export { C as CaptureOptions, a as Clock, E as EventBatch, b as EventContext, c as EventEnvelope, d as EventProperties, F as FlagsResponse, e as IdFactory, f as IdentifyOptions, g as InboxResponse, L as LocalFlagContext, P as ProdantixClient, h as ProdantixConfig, T as Transport, i as TransportRequest, j as createClient } from './client-BBUAoQg2.cjs';
|
|
3
|
+
import { F as FetchLike } from './http-BCh716Vs.cjs';
|
|
4
|
+
export { F as FetchTransport } from './transport-DhhzvwpV.cjs';
|
|
5
5
|
|
|
6
6
|
type ProdantixErrorCode = 'config' | 'queue_overflow' | 'transport' | 'validation';
|
|
7
7
|
declare class ProdantixError extends Error {
|
|
@@ -33,12 +33,20 @@ interface FlagEvalContext {
|
|
|
33
33
|
}
|
|
34
34
|
declare function matches(condition: FlagCondition, ctx: FlagEvalContext): boolean;
|
|
35
35
|
|
|
36
|
+
interface FlagVariation {
|
|
37
|
+
key: string;
|
|
38
|
+
value: unknown;
|
|
39
|
+
weight: number;
|
|
40
|
+
}
|
|
36
41
|
interface FlagRule {
|
|
37
42
|
description?: string;
|
|
38
43
|
enabled: boolean;
|
|
44
|
+
intent?: string;
|
|
39
45
|
key: string;
|
|
40
46
|
rolloutPercentage: number;
|
|
41
47
|
targeting: FlagCondition[];
|
|
48
|
+
type?: string;
|
|
49
|
+
variations?: FlagVariation[];
|
|
42
50
|
}
|
|
43
51
|
interface FlagSnapshot {
|
|
44
52
|
flags: FlagRule[];
|
|
@@ -51,6 +59,8 @@ interface FlagDecision {
|
|
|
51
59
|
declare function bucket(key: string, distinctId: string): number;
|
|
52
60
|
declare function evaluateFlag(rule: FlagRule, ctx: FlagEvalContext): FlagDecision;
|
|
53
61
|
declare function evaluateAll(rules: FlagRule[], ctx: FlagEvalContext): Record<string, boolean>;
|
|
62
|
+
declare function assignVariant(rule: FlagRule, ctx: FlagEvalContext): FlagVariation | null;
|
|
63
|
+
declare function getVariant(rules: FlagRule[], key: string, ctx: FlagEvalContext): unknown;
|
|
54
64
|
|
|
55
65
|
interface FlagsClientOptions {
|
|
56
66
|
fetch?: FetchLike;
|
|
@@ -97,4 +107,4 @@ declare class MemoryStorage implements StorageAdapter {
|
|
|
97
107
|
declare const SDK_NAME = "prodantix-js";
|
|
98
108
|
declare const SDK_VERSION = "0.0.1";
|
|
99
109
|
|
|
100
|
-
export { ConfigError, type FlagCondition, type FlagDecision, type FlagEvalContext, type FlagOp, type FlagRule, type FlagSnapshot, FlagsClient, InboxMessage, JsonValue, MemoryStorage, MessagesClient, ProdantixError, type ProdantixErrorCode, SDK_NAME, SDK_VERSION, StorageAdapter, TransportError, ValidationError, bucket, evaluateAll, evaluateFlag, matches };
|
|
110
|
+
export { ConfigError, type FlagCondition, type FlagDecision, type FlagEvalContext, type FlagOp, type FlagRule, type FlagSnapshot, type FlagVariation, FlagsClient, InboxMessage, JsonValue, MemoryStorage, MessagesClient, ProdantixError, type ProdantixErrorCode, SDK_NAME, SDK_VERSION, StorageAdapter, TransportError, ValidationError, assignVariant, bucket, evaluateAll, evaluateFlag, getVariant, matches };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { J as JsonValue,
|
|
2
|
-
export { C as CaptureOptions, a as Clock, E as EventBatch, b as EventContext, c as EventEnvelope, d as EventProperties, F as FlagsResponse,
|
|
3
|
-
import { F as FetchLike } from './
|
|
4
|
-
export {
|
|
1
|
+
import { J as JsonValue, I as InboxMessage, S as StorageAdapter } from './client-BBUAoQg2.js';
|
|
2
|
+
export { C as CaptureOptions, a as Clock, E as EventBatch, b as EventContext, c as EventEnvelope, d as EventProperties, F as FlagsResponse, e as IdFactory, f as IdentifyOptions, g as InboxResponse, L as LocalFlagContext, P as ProdantixClient, h as ProdantixConfig, T as Transport, i as TransportRequest, j as createClient } from './client-BBUAoQg2.js';
|
|
3
|
+
import { F as FetchLike } from './http-BCh716Vs.js';
|
|
4
|
+
export { F as FetchTransport } from './transport-dWp3NUMj.js';
|
|
5
5
|
|
|
6
6
|
type ProdantixErrorCode = 'config' | 'queue_overflow' | 'transport' | 'validation';
|
|
7
7
|
declare class ProdantixError extends Error {
|
|
@@ -33,12 +33,20 @@ interface FlagEvalContext {
|
|
|
33
33
|
}
|
|
34
34
|
declare function matches(condition: FlagCondition, ctx: FlagEvalContext): boolean;
|
|
35
35
|
|
|
36
|
+
interface FlagVariation {
|
|
37
|
+
key: string;
|
|
38
|
+
value: unknown;
|
|
39
|
+
weight: number;
|
|
40
|
+
}
|
|
36
41
|
interface FlagRule {
|
|
37
42
|
description?: string;
|
|
38
43
|
enabled: boolean;
|
|
44
|
+
intent?: string;
|
|
39
45
|
key: string;
|
|
40
46
|
rolloutPercentage: number;
|
|
41
47
|
targeting: FlagCondition[];
|
|
48
|
+
type?: string;
|
|
49
|
+
variations?: FlagVariation[];
|
|
42
50
|
}
|
|
43
51
|
interface FlagSnapshot {
|
|
44
52
|
flags: FlagRule[];
|
|
@@ -51,6 +59,8 @@ interface FlagDecision {
|
|
|
51
59
|
declare function bucket(key: string, distinctId: string): number;
|
|
52
60
|
declare function evaluateFlag(rule: FlagRule, ctx: FlagEvalContext): FlagDecision;
|
|
53
61
|
declare function evaluateAll(rules: FlagRule[], ctx: FlagEvalContext): Record<string, boolean>;
|
|
62
|
+
declare function assignVariant(rule: FlagRule, ctx: FlagEvalContext): FlagVariation | null;
|
|
63
|
+
declare function getVariant(rules: FlagRule[], key: string, ctx: FlagEvalContext): unknown;
|
|
54
64
|
|
|
55
65
|
interface FlagsClientOptions {
|
|
56
66
|
fetch?: FetchLike;
|
|
@@ -97,4 +107,4 @@ declare class MemoryStorage implements StorageAdapter {
|
|
|
97
107
|
declare const SDK_NAME = "prodantix-js";
|
|
98
108
|
declare const SDK_VERSION = "0.0.1";
|
|
99
109
|
|
|
100
|
-
export { ConfigError, type FlagCondition, type FlagDecision, type FlagEvalContext, type FlagOp, type FlagRule, type FlagSnapshot, FlagsClient, InboxMessage, JsonValue, MemoryStorage, MessagesClient, ProdantixError, type ProdantixErrorCode, SDK_NAME, SDK_VERSION, StorageAdapter, TransportError, ValidationError, bucket, evaluateAll, evaluateFlag, matches };
|
|
110
|
+
export { ConfigError, type FlagCondition, type FlagDecision, type FlagEvalContext, type FlagOp, type FlagRule, type FlagSnapshot, type FlagVariation, FlagsClient, InboxMessage, JsonValue, MemoryStorage, MessagesClient, ProdantixError, type ProdantixErrorCode, SDK_NAME, SDK_VERSION, StorageAdapter, TransportError, ValidationError, assignVariant, bucket, evaluateAll, evaluateFlag, getVariant, matches };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{
|
|
1
|
+
export{b as ConfigError,r as FetchTransport,p as FlagsClient,e as MemoryStorage,q as MessagesClient,s as ProdantixClient,a as ProdantixError,h as SDK_NAME,i as SDK_VERSION,d as TransportError,c as ValidationError,n as assignVariant,k as bucket,t as createClient,m as evaluateAll,l as evaluateFlag,o as getVariant,j as matches}from'./chunk-7J6AQICL.js';import'./chunk-VG77TYVX.js';import'./chunk-5XGN7UAV.js';//# sourceMappingURL=index.js.map
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';function a(e){if(e)return e;let r=globalThis.fetch;if(typeof r=="function")return r.bind(globalThis)}function c(e){return e.replace(/\/+$/,"")}var s="prodantix.messenger.config";function f(e,r){let n=e?.get(s);if(!n)return null;try{let o=JSON.parse(n);return o?.apiKey===r?o.config:null}catch{return null}}async function h(e){let r=a(e.fetchImpl);if(!r)return e.onError?.(new Error("no fetch available for the prodantix messenger")),null;let n=c(e.host),o=e.locale?`?locale=${encodeURIComponent(e.locale)}`:"";try{let t=await r(`${n}/v1/messenger/config${o}`,{headers:{authorization:`Bearer ${e.apiKey}`},method:"GET"});if(!t.ok)return e.onError?.(new Error(`prodantix messenger config: ${t.status}`)),null;let i=JSON.parse(await t.text());return i.enabled?(e.storage?.set(s,JSON.stringify({apiKey:e.apiKey,config:i})),i):(e.storage?.remove(s),i)}catch(t){return e.onError?.(t),null}}exports.MESSENGER_CACHE_KEY=s;exports.cachedMessengerConfig=f;exports.fetchMessengerConfig=h;//# sourceMappingURL=messenger.cjs.map
|
|
2
|
+
//# sourceMappingURL=messenger.cjs.map
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
(function(){'use strict';var D=Object.defineProperty;var B=(n,e,t)=>e in n?D(n,e,{enumerable:true,configurable:true,writable:true,value:t}):n[e]=t;var l=(n,e,t)=>B(n,typeof e!="symbol"?e+"":e,t);function S(n){if(n)return n;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function C(n){return n.replace(/\/+$/,"")}var U="X-Prodantix-Conversation-Token",N="prodantix.chat.handle";function q(){let n=globalThis.localStorage;if(n)return {get:e=>n.getItem(e),remove:e=>n.removeItem(e),set:(e,t)=>n.setItem(e,t)}}var E=class{constructor(e){this.options=e;l(this,"fetchImpl");l(this,"host");l(this,"storage");l(this,"handle");l(this,"identity",null);var t;this.fetchImpl=S(e.fetchImpl),this.host=C(e.host),this.storage=(t=e.storage)!=null?t:q(),this.handle=this.readHandle();}get hasThread(){return this.handle!==null}get socketAuth(){return this.handle?{conversationId:this.handle.conversationId,conversationToken:this.handle.token,projectKey:this.options.apiKey}:null}identify(e){this.identity=e;}async ensureThread(e){var r,i,o;if(this.handle)return true;let t=await this.request("POST","/v1/conversations",{body:{distinctId:this.options.distinctId,subject:e,userHash:(r=this.identity)==null?void 0:r.userHash,userId:(i=this.identity)==null?void 0:i.userId}});return !(t!=null&&t.conversationId)||!t.token?false:(this.handle={conversationId:t.conversationId,token:t.token},(o=this.storage)==null||o.set(N,JSON.stringify(this.handle)),true)}async send(e){var i;if(!await this.ensureThread())return null;let t=this.handle;if(!t)return null;let r=await this.request("POST",`/v1/conversations/${encodeURIComponent(t.conversationId)}/turns`,{body:{body:e},token:t.token});return (i=r==null?void 0:r.turn)!=null?i:null}async load(){let e=this.handle;return e?this.request("GET",`/v1/conversations/${encodeURIComponent(e.conversationId)}`,{token:e.token}):null}readHandle(){var t,r;let e=(t=this.storage)==null?void 0:t.get(N);if(!e)return null;try{let i=JSON.parse(e);if(typeof i.conversationId=="string"&&typeof i.token=="string")return {conversationId:i.conversationId,token:i.token}}catch(i){}return (r=this.storage)==null||r.remove(N),null}async request(e,t,r={}){var a,s,u,c,d,p;let i=this.fetchImpl;if(!i)return (s=(a=this.options).onError)==null||s.call(a,new Error("no fetch available for prodantix chat")),null;let o={authorization:`Bearer ${this.options.apiKey}`,"content-type":"application/json"};r.token&&(o[U]=r.token);try{let m=await i(`${this.host}${t}`,{body:r.body===void 0?void 0:JSON.stringify(r.body),headers:o,method:e}),f=await m.text();return m.ok?f?JSON.parse(f):{}:((c=(u=this.options).onError)==null||c.call(u,new Error(`prodantix chat ${t}: ${m.status}`)),null)}catch(m){return (p=(d=this.options).onError)==null||p.call(d,m),null}}};var b={bubbleStyle:"tailed",launcherStyle:"circle_outlined",namePlacement:"avatar_only",skin:"concierge",timestampStyle:"cluster"},j=["concierge","console","quiet"],W=["avatar_circle","circle_filled","circle_outlined","pill_labelled","pill_team","squircle_filled"],Y=["hairline","outlined","rounded","tailed"],J=["above","avatar_only","gutter","hidden","inline"],X=["cluster","latency","none","trailing","with_name"],v=(n,e,t)=>typeof n=="string"&&e.includes(n)?n:t;function I(n){let e={bubbleStyle:v(n==null?void 0:n.bubbleStyle,Y,b.bubbleStyle),launcherStyle:v(n==null?void 0:n.launcherStyle,W,b.launcherStyle),namePlacement:v(n==null?void 0:n.namePlacement,J,b.namePlacement),skin:v(n==null?void 0:n.skin,j,b.skin),timestampStyle:v(n==null?void 0:n.timestampStyle,X,b.timestampStyle)};return (e.namePlacement==="avatar_only"||e.namePlacement==="hidden")&&(e.timestampStyle==="with_name"||e.timestampStyle==="latency")&&(e.timestampStyle="trailing"),e.namePlacement==="inline"&&e.bubbleStyle==="hairline"&&(e.namePlacement="above"),e}var Q={agentLabel:"Agent",aiLabel:"AI",closeLabel:"Close chat",emptyBody:"We usually reply within a few minutes.",emptyTitle:"Ask us anything.",inputPlaceholder:"Type a message",launcherLabel:"Open support chat",sendLabel:"Send",timeLabel:n=>{let e=new Date(n);return Number.isNaN(e.getTime())?"":`${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`},title:"Support",unreadLabel:n=>`${n} unread`},_={accentColor:"#5b5bff",greeting:"",launcherOffsetX:20,launcherOffsetY:20,launcherPosition:"bottom_right",starterPrompts:[],...b},V={concierge:".panel{border-radius:16px;box-shadow:0 16px 40px rgba(0,0,0,.2)}.header{background:var(--a);color:#fff;flex-direction:column;align-items:flex-start;gap:14px;padding:18px 14px 20px 20px}.header h2{font-size:19px;font-weight:640}.composer{padding:12px 12px 14px;gap:8px}.composer input{border:0;background:var(--fill);height:46px;border-radius:23px;padding:0 16px}.composer button{width:46px;min-width:46px;height:46px;padding:0;border-radius:23px}.composer button .sendglyph{display:block}.composer button .sendtext{display:none}",console:".panel{border-radius:12px;box-shadow:0 8px 24px rgba(0,0,0,.16)}.header{background:var(--paper);color:var(--ink);border-bottom:1px solid var(--hairline)}.close{color:var(--ink-2)}",quiet:".composer{position:relative;padding:10px 12px 12px}.composer input{height:42px;padding-right:42px}.composer button{position:absolute;top:50%;right:16px;width:34px;min-width:34px;height:34px;padding:0;background:transparent;color:var(--ink);border-radius:7px;transform:translateY(-50%)}.composer button .sendglyph{display:block;width:18px;height:18px}.composer button .sendtext{display:none}.panel{border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,.12)}.header{background:var(--paper);color:var(--ink);height:44px;padding:0 8px 0 16px;border-bottom:1px solid var(--hairline)}.header h2{font-size:11px;letter-spacing:.11em;text-transform:uppercase;color:var(--ink-3)}.close{color:var(--ink-2)}"},Z={avatar_circle:".launcher{width:60px;height:60px;border-radius:30px;background:var(--paper);border:1px solid var(--hairline);color:var(--ink-2)}",circle_filled:".launcher{width:56px;height:56px;border-radius:28px;background:var(--a);color:#fff}",circle_outlined:".launcher{width:46px;height:46px;border-radius:23px;background:var(--paper);border:1px solid var(--hairline);color:var(--ink-2);box-shadow:0 1px 2px rgba(0,0,0,.08);font-size:21px}.badge{background:var(--a);top:-7px;right:-7px;min-width:19px;height:19px;border-radius:10px;font-size:11.5px}",pill_labelled:".launcher{width:auto;height:52px;border-radius:26px;padding:0 22px;gap:10px;background:var(--a);color:#fff;font-size:14.5px;font-weight:600}",pill_team:".launcher{width:auto;height:54px;border-radius:27px;padding:0 20px 0 8px;gap:10px;background:var(--paper);border:1px solid var(--hairline);color:var(--ink);font-size:14px;font-weight:600}.badge{position:static;background:var(--a)}",squircle_filled:".launcher{width:56px;height:56px;border-radius:16px;background:var(--a);color:#fff}"},ee={hairline:".turn{max-width:100%;padding:13px 0;border-top:1px solid var(--hairline);background:none;border-radius:0}.log>.turn:first-child{border-top:0}.turn.end_user{align-self:stretch;display:flex;flex-direction:column;align-items:flex-end}.turn.end_user .body{background:var(--fill);color:var(--ink);border-radius:8px;padding:9px 12px;max-width:85%}",outlined:".turn{background:none;border:1px solid var(--hairline);border-radius:12px}.turn.end_user{background:none;border-color:var(--a);color:var(--ink)}",rounded:".turn{border-radius:18px;padding:10px 15px}",tailed:".turn.agent,.turn.ai{border-radius:12px 12px 12px 4px}.turn.end_user{border-radius:12px 12px 4px 12px}"},te={above:"",avatar_only:".turn.agent,.turn.ai{display:flex;gap:10px;max-width:100%;background:none;padding:0}.turn .body{background:var(--fill);padding:9px 13px;border-radius:inherit}",gutter:".turn.agent,.turn.ai{display:flex;gap:10px;max-width:100%;background:none;padding:0}.turn .body{background:var(--fill);padding:9px 13px;border-radius:inherit}.author{text-transform:none;letter-spacing:0;font-size:12.5px;font-weight:600;opacity:1}",hidden:".turn.agent .author,.turn.ai .author:not(.ai){display:none}",inline:".author{display:inline;margin-right:6px;font-weight:650}"},ne={cluster:'.divider{display:flex;align-items:center;gap:10px;margin:0;font-size:11px;opacity:.6}.divider:before,.divider:after{content:"";flex:1;height:1px;background:var(--hairline)}',latency:".stamp{font-size:11px;opacity:.7;margin-left:6px}.lat{font-size:11px;opacity:.7;margin-left:6px}",none:"",trailing:".stamp{display:block;font-size:11px;opacity:.7;margin-top:4px}.turn.end_user .stamp{text-align:right}",with_name:".stamp{font-size:11px;opacity:.7;margin-left:6px}"};function re(n){let e=I(n),t=n.launcherPosition==="bottom_left"?"left":"right",r=n.accentColor;return `${`
|
|
2
|
+
:host {
|
|
3
|
+
all: initial; --a: ${r};
|
|
4
|
+
--paper: #fff; --ink: #0f172a; --ink-3: var(--ink-3);
|
|
5
|
+
--fill: #f1f5f9; --hairline: #e2e8f0; --field: #cbd5e1; --ink-2: rgba(0,0,0,.72);
|
|
6
|
+
color-scheme: light dark;
|
|
7
|
+
}
|
|
8
|
+
@media (prefers-color-scheme: dark) {
|
|
9
|
+
:host {
|
|
10
|
+
--paper: oklch(24.6% 0.015 257); --ink: #fff; --ink-3: rgba(255,255,255,.55);
|
|
11
|
+
--fill: rgba(255,255,255,.06); --hairline: rgba(255,255,255,.13); --field: rgba(255,255,255,.22); --ink-2: rgba(255,255,255,.70);
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
* { box-sizing: border-box; font-family: system-ui, sans-serif; }
|
|
15
|
+
.launcher {
|
|
16
|
+
position: fixed; ${t}: ${n.launcherOffsetX}px; bottom: ${n.launcherOffsetY}px; width: 56px; height: 56px;
|
|
17
|
+
border-radius: 28px; border: none; cursor: pointer;
|
|
18
|
+
display: inline-flex; align-items: center; justify-content: center;
|
|
19
|
+
background: ${r}; color: #fff; font-size: 24px;
|
|
20
|
+
box-shadow: 0 4px 12px rgba(0,0,0,.2);
|
|
21
|
+
}
|
|
22
|
+
.launcher:focus-visible { outline: 3px solid #0b0e14; outline-offset: 2px; }
|
|
23
|
+
.badge {
|
|
24
|
+
position: absolute; top: -4px; right: -4px; min-width: 20px; height: 20px;
|
|
25
|
+
border-radius: 10px; background: #dc2626; color: #fff; font-size: 12px;
|
|
26
|
+
display: flex; align-items: center; justify-content: center; padding: 0 4px;
|
|
27
|
+
}
|
|
28
|
+
.panel {
|
|
29
|
+
position: fixed; ${t}: ${n.launcherOffsetX}px; bottom: ${n.launcherOffsetY+68}px; width: 360px; max-width: calc(100vw - 40px);
|
|
30
|
+
height: 520px; max-height: calc(100vh - 120px); background: var(--paper); color: var(--ink);
|
|
31
|
+
border-radius: 12px; box-shadow: 0 8px 32px rgba(0,0,0,.24);
|
|
32
|
+
display: flex; flex-direction: column; overflow: hidden;
|
|
33
|
+
}
|
|
34
|
+
.header { padding: 14px 16px; background: #0b0e14; color: #fff; display: flex; align-items: center; justify-content: space-between; }
|
|
35
|
+
.header h2 { margin: 0; font-size: 15px; }
|
|
36
|
+
.close { background: none; border: none; color: #fff; cursor: pointer; font-size: 18px; }
|
|
37
|
+
.close:focus-visible { outline: 2px solid #fff; }
|
|
38
|
+
.log { flex: 1; overflow-y: auto; padding: 12px; display: flex; flex-direction: column; gap: 8px; }
|
|
39
|
+
.turn { max-width: 80%; padding: 8px 12px; border-radius: 12px; font-size: 14px; }
|
|
40
|
+
.turn.end_user { align-self: flex-end; background: ${r}; color: #fff; }
|
|
41
|
+
.turn.agent, .turn.ai { align-self: flex-start; background: var(--fill); color: var(--ink); }
|
|
42
|
+
.author { font-size: 11px; opacity: .7; margin-bottom: 2px; }
|
|
43
|
+
.empty { display: flex; flex-direction: column; gap: 8px; padding: 20px 16px; }
|
|
44
|
+
.empty h3 { margin: 0; font-size: 18px; font-weight: 640; letter-spacing: -.015em; }
|
|
45
|
+
.empty p { margin: 0 0 8px; font-size: 13.5px; color: var(--ink-2); }
|
|
46
|
+
.prompt {
|
|
47
|
+
display: flex; align-items: center; min-height: 44px; padding: 0 14px; text-align: left;
|
|
48
|
+
font-family: inherit; font-size: 13.5px; font-weight: 500; color: var(--ink);
|
|
49
|
+
background: none; border: 1px solid var(--hairline); border-radius: 8px; cursor: pointer;
|
|
50
|
+
}
|
|
51
|
+
.prompt:focus-visible { outline: 2px solid ${r}; outline-offset: 2px; }
|
|
52
|
+
.av { width: 30px; height: 30px; border-radius: 50%; flex: none; display: inline-flex; align-items: center; justify-content: center; font-size: 11.5px; font-weight: 650; color: #fff; background: #7c3f3f; }
|
|
53
|
+
.av.bot { border-radius: 9px; background: var(--fill); color: var(--ink); }
|
|
54
|
+
.composer { display: flex; gap: 8px; padding: 12px; border-top: 1px solid var(--hairline); }
|
|
55
|
+
.composer input { flex: 1; padding: 8px 10px; border: 1px solid var(--field); border-radius: 8px; font-size: 14px; background: transparent; color: var(--ink); }
|
|
56
|
+
.composer input:focus-visible { outline: 2px solid ${r}; }
|
|
57
|
+
.composer button { display: inline-flex; align-items: center; justify-content: center; gap: 0; min-width: 64px; height: 44px; padding: 0 16px; background: ${r}; color: #fff; border: none; border-radius: 8px; cursor: pointer; font-family: inherit; font-size: 14.5px; font-weight: 550; }
|
|
58
|
+
.composer button .sendglyph { display: none; width: 19px; height: 19px; }
|
|
59
|
+
.composer button:focus-visible { outline: 2px solid #0b0e14; }
|
|
60
|
+
@media (prefers-reduced-motion: no-preference) {
|
|
61
|
+
.panel { animation: rise 180ms ease-out; }
|
|
62
|
+
@keyframes rise { from { transform: translateY(8px); opacity: 0; } to { transform: none; opacity: 1; } }
|
|
63
|
+
}
|
|
64
|
+
`}${V[e.skin]}${Z[e.launcherStyle]}${ee[e.bubbleStyle]}${te[e.namePlacement]}${ne[e.timestampStyle]}`}var ie=["end_user","agent","ai"],T=class{constructor(e,t,r={},i={}){this.host=e;this.client=t;l(this,"root");l(this,"strings");l(this,"settings");l(this,"appearance");l(this,"launcher");l(this,"badge");l(this,"panel",null);l(this,"lastFocused",null);l(this,"unread",0);this.strings={...Q,...r},this.appearance={..._,...i},this.settings=I({..._,...i}),this.root=e.attachShadow({mode:"closed"});let o=document.createElement("style");o.textContent=re({..._,...i}),this.root.append(o),this.launcher=document.createElement("button"),this.launcher.className="launcher",this.launcher.type="button",this.launcher.setAttribute("aria-haspopup","dialog"),this.launcher.setAttribute("aria-label",this.strings.launcherLabel),this.launcher.textContent="\u{1F4AC}",this.launcher.addEventListener("click",()=>this.toggle()),this.badge=document.createElement("span"),this.badge.className="badge",this.badge.hidden=true,this.launcher.append(this.badge),this.root.append(this.launcher);}toggle(){this.panel?this.close():this.open();}async open(){if(this.panel)return;this.lastFocused=this.host.ownerDocument.activeElement,this.unread=0,this.renderBadge();let e=document.createElement("section");e.className="panel",e.setAttribute("role","dialog"),e.setAttribute("aria-modal","true"),e.setAttribute("aria-label",this.strings.title);let t=document.createElement("div");t.className="header";let r=document.createElement("h2");r.textContent=this.strings.title;let i=document.createElement("button");i.className="close",i.type="button",i.setAttribute("aria-label",this.strings.closeLabel),i.textContent="\xD7",i.addEventListener("click",()=>this.close()),t.append(r,i);let o=document.createElement("div");o.className="log",o.setAttribute("role","log"),o.setAttribute("aria-live","polite"),o.setAttribute("aria-label",this.strings.title);let a=document.createElement("form");a.className="composer";let s=document.createElement("input");s.type="text",s.setAttribute("aria-label",this.strings.inputPlaceholder),s.placeholder=this.strings.inputPlaceholder;let u=document.createElement("button");u.type="submit",u.setAttribute("aria-label",this.strings.sendLabel),u.innerHTML='<svg class="sendglyph" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4.5 12 20 4.5 15 20l-3.6-5.4L4.5 12Z"/></svg>';let c=document.createElement("span");c.className="sendtext",c.textContent=this.strings.sendLabel,u.append(c),a.append(s,u),a.addEventListener("submit",p=>{p.preventDefault(),this.submit(s,o);}),e.append(t,o,a),e.addEventListener("keydown",p=>this.onKeydown(p,e,i)),this.root.append(e),this.panel=e,s.focus();let d=await this.client.load();d&&d.turns.length>0?this.renderThread(o,d):this.renderFirstRun(o,s);}renderFirstRun(e,t){let r=document.createElement("div");r.className="empty";let i=document.createElement("h3");i.textContent=this.appearance.greeting.trim()||this.strings.emptyTitle;let o=document.createElement("p");o.textContent=this.strings.emptyBody,r.append(i,o);for(let a of this.appearance.starterPrompts){let s=document.createElement("button");s.className="prompt",s.type="button",s.textContent=a,s.addEventListener("click",()=>{t.value=a,this.submit(t,e);}),r.append(s);}e.replaceChildren(r);}close(){this.panel&&(this.panel.remove(),this.panel=null,this.lastFocused instanceof HTMLElement?this.lastFocused.focus():this.launcher.focus());}onIncomingTurn(e){if(this.panel){let t=this.panel.querySelector(".log");t instanceof HTMLElement&&this.appendTurn(t,e);return}e.authorKind!=="end_user"&&(this.unread+=1,this.renderBadge());}async submit(e,t){var o;let r=e.value.trim();if(!r)return;e.value="",(o=t.querySelector(".empty"))==null||o.remove();let i=await this.client.send(r);i&&this.appendTurn(t,i);}renderThread(e,t){e.replaceChildren();for(let r of t.turns)this.appendTurn(e,r);}appendTurn(e,t){var d;(d=e.querySelector(".empty"))==null||d.remove();let r=ie.includes(t.authorKind)?t.authorKind:"agent",i=this.settings,o=document.createElement("div");if(o.className=`turn ${r}`,r!=="end_user"&&(i.namePlacement==="avatar_only"||i.namePlacement==="gutter")){let p=document.createElement("span");p.className=r==="ai"?"av bot":"av",p.textContent=r==="ai"?this.strings.aiLabel:this.strings.agentLabel.slice(0,2).toUpperCase(),p.setAttribute("aria-hidden","true"),o.append(p);}let s=document.createElement("div");if(s.className="body",r!=="end_user"&&i.namePlacement!=="hidden"&&!(i.namePlacement==="avatar_only"&&r==="agent")||r==="ai"&&i.namePlacement==="hidden"){let p=document.createElement("div");p.className=r==="ai"?"author ai":"author",p.textContent=r==="ai"?this.strings.aiLabel:this.strings.agentLabel,(i.timestampStyle==="with_name"||i.timestampStyle==="latency")&&p.append(this.stamp(t)),s.append(p);}let c=document.createElement("div");c.textContent=t.body,s.append(c),i.timestampStyle==="trailing"&&s.append(this.stamp(t)),o.append(s),e.append(o),e.scrollTop=e.scrollHeight;}stamp(e){let t=document.createElement("span");return t.className="stamp",t.textContent=this.strings.timeLabel(e.createdAt),t}onKeydown(e,t,r){if(e.key==="Escape"){e.preventDefault(),this.close();return}if(e.key!=="Tab")return;let i=t.querySelectorAll('button, input, [tabindex]:not([tabindex="-1"])');if(i.length===0)return;let o=i[0],a=i[i.length-1],s=this.root.activeElement;e.shiftKey&&s===o?(e.preventDefault(),a.focus()):!e.shiftKey&&s===a?(e.preventDefault(),o.focus()):s===null&&(e.preventDefault(),r.focus());}renderBadge(){this.unread>0?(this.badge.hidden=false,this.badge.textContent=String(this.unread),this.launcher.setAttribute("aria-label",`${this.strings.launcherLabel}, ${this.strings.unreadLabel(this.unread)}`)):(this.badge.hidden=true,this.badge.textContent="",this.launcher.setAttribute("aria-label",this.strings.launcherLabel));}};function O(n){return `40${JSON.stringify(n)}`}function H(){return "3"}function $(n){let e=n.charAt(0),t=n.slice(1);if(e==="2")return {kind:"ping"};if(e==="1")return {kind:"disconnect"};if(e==="0"){let a=P(t);return {kind:"open",pingInterval:typeof(a==null?void 0:a.pingInterval)=="number"?a.pingInterval:25e3,pingTimeout:typeof(a==null?void 0:a.pingTimeout)=="number"?a.pingTimeout:2e4}}if(e!=="4")return {kind:"other"};let r=t.charAt(0),i=t.slice(1);if(r==="0")return {kind:"connected"};if(r==="1")return {kind:"disconnect"};if(r==="4"){let a=P(i);return {kind:"connectError",message:typeof(a==null?void 0:a.message)=="string"?a.message:"refused"}}if(r!=="2")return {kind:"other"};let o=P(i);return !Array.isArray(o)||typeof o[0]!="string"?{kind:"other"}:{kind:"event",name:o[0],payload:o[1]}}function P(n){try{return JSON.parse(n)}catch(e){return null}}var oe="/socket.io/?EIO=4&transport=websocket",w=class{constructor(e){this.options=e;l(this,"socket",null);l(this,"heartbeat",null);l(this,"ready",false);l(this,"closed",false);l(this,"heartbeatWindow",45e3);l(this,"factory");l(this,"setTimer");l(this,"clearTimer");var t,r,i;this.factory=(t=e.socketFactory)!=null?t:ae,this.setTimer=(r=e.setTimer)!=null?r:((o,a)=>setTimeout(o,a)),this.clearTimer=(i=e.clearTimer)!=null?i:(o=>clearTimeout(o));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${oe}`,t;try{t=this.factory(e);}catch(r){this.options.onClosed(false);return}this.socket=t,t.onmessage=r=>this.receive(String(r.data)),t.onerror=()=>t.close(),t.onclose=()=>this.fell();}close(){this.closed=true,this.stopHeartbeat();let e=this.socket;this.socket=null,e==null||e.close();}receive(e){var r,i,o,a;let t=$(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),(r=this.socket)==null||r.send(O(this.options.auth));return}if(t.kind==="ping"){this.armHeartbeat(),(i=this.socket)==null||i.send(H());return}if(t.kind==="connectError"||t.kind==="disconnect"){this.stopHeartbeat(),(o=this.socket)==null||o.close();return}if(t.kind==="event"){if(t.name==="ready"){this.ready=true,this.options.onReady();return}if(t.name==="conversation.turn"){let s=(a=t.payload)==null?void 0:a.turn;s&&this.options.onTurn(s);}}}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(()=>{var t;return (t=this.socket)==null?void 0:t.close()},this.heartbeatWindow);}stopHeartbeat(){this.heartbeat!==null&&this.clearTimer(this.heartbeat),this.heartbeat=null;}};function ae(n){let e=globalThis.WebSocket;if(!e)throw new Error("no WebSocket");return new e(n)}function F(n){var x,y;let e=globalThis.document;if(!e)throw new Error("prodantix chat requires a document; mount it in the browser");let t=(x=n.mountPoint)!=null?x:e.createElement("div");n.mountPoint||e.body.append(t);let r=new E(n),i=new T(t,r,n.strings,n.appearance),o=new Set,a,s=null,u=(y=n.pollIntervalMs)!=null?y:15e3,c=g=>{o.has(g.id)||g.authorKind==="end_user"||(o.add(g.id),i.onIncomingTurn(g));},d=async()=>{if(!r.hasThread)return;let g=await r.load();if(g){for(let h of g.turns)c(h);o=new Set(g.turns.map(h=>h.id));}},p=()=>{a||u<=0||(a=setInterval(()=>void d(),u));},m=()=>{a&&clearInterval(a),a=void 0;},f=()=>{if(s||!n.socketHost)return;let g=r.socketAuth;g&&(s=new w({auth:g,host:n.socketHost,onClosed:h=>{s=null,p(),h&&f();},onReady:m,onTurn:c,socketFactory:n.socketFactory}),s.open());};return p(),f(),{close:()=>i.close(),destroy:()=>{m(),s==null||s.close(),s=null,i.close(),t.remove();},identify:g=>r.identify(g),open:()=>{i.open().then(f);}}}var L="prodantix.messenger.config";function R(n,e){let t=n==null?void 0:n.get(L);if(!t)return null;try{let r=JSON.parse(t);return (r==null?void 0:r.apiKey)===e?r.config:null}catch(r){return null}}async function K(n){var i,o,a,s,u;let e=S(n.fetchImpl);if(!e)return (i=n.onError)==null||i.call(n,new Error("no fetch available for the prodantix messenger")),null;let t=C(n.host),r=n.locale?`?locale=${encodeURIComponent(n.locale)}`:"";try{let c=await e(`${t}/v1/messenger/config${r}`,{headers:{authorization:`Bearer ${n.apiKey}`},method:"GET"});if(!c.ok)return (o=n.onError)==null||o.call(n,new Error(`prodantix messenger config: ${c.status}`)),null;let d=JSON.parse(await c.text());return d.enabled?((s=n.storage)==null||s.set(L,JSON.stringify({apiKey:n.apiKey,config:d})),d):((a=n.storage)==null||a.remove(L),d)}catch(c){return (u=n.onError)==null||u.call(n,c),null}}var se=["close","identify","open","shutdown","toggle"],k="[prodantix/messenger]";function le(n,e){for(let t of n){let[r,...i]=t!=null?t:[];typeof r!="string"||!se.includes(r)||e(r,...i);}}function ce(n){if(!n)return null;try{return new URL(n).origin}catch(e){return null}}async function G(n,e={}){var m,f,x,y,g;let t=(m=e.warn)!=null?m:(h=>console.warn(h)),r=n.prodantix,i=r==null?void 0:r.k;if(!i)return t(`${k} no project key on the install snippet; nothing will load.`),null;let o=ce((f=e.scriptSrc)!=null?f:de(n));if(!o)return t(`${k} could not tell which host served this script; nothing will load.`),null;let a=pe(n),s=R(a,i),u=await K({apiKey:i,host:o,locale:((y=(x=n.document)==null?void 0:x.documentElement)==null?void 0:y.lang)||void 0,onError:h=>t(`${k} settings could not be read: ${String(h)}`),storage:a}),c=u!=null?u:s;if(!c)return t(`${k} no settings available; the messenger will not render.`),null;if(!c.enabled)return null;let d=F({apiKey:i,appearance:c,distinctId:he(n,a),host:o,socketHost:c.socketUrl||void 0}),p=(h,...A)=>{if((h==="open"||h==="toggle")&&d.open(),h==="close"&&d.close(),h==="shutdown"&&d.destroy(),h==="identify"){let M=ue(A[0]);if(!M){console.error(`${k} identify needs { userId, userHash }: the hash is HMAC-SHA256 of the user id under the project signing secret, computed on your server. Without it the visitor stays anonymous.`);return}d.identify(M);}};return le((g=r==null?void 0:r.q)!=null?g:[],p),n.prodantix=Object.assign((h,...A)=>p(h,...A),{k:i,q:[]}),d}function de(n){var t;let e=(t=n.document)==null?void 0:t.currentScript;return e==null?void 0:e.src}function pe(n){let e=n.localStorage;if(e)return {get:t=>e.getItem(t),remove:t=>e.removeItem(t),set:(t,r)=>e.setItem(t,r)}}function ue(n){if(typeof n!="object"||n===null)return null;let{userHash:e,userId:t}=n;return typeof t!="string"||typeof e!="string"||t.trim()===""||e.trim()===""?null:{userHash:e,userId:t}}var z="prodantix.messenger.anon";function he(n,e){var i,o,a;let t=e==null?void 0:e.get(z);if(t)return t;let r=`anon_${(a=(o=(i=n.crypto)==null?void 0:i.randomUUID)==null?void 0:o.call(i))!=null?a:Math.random().toString(36).slice(2)}`;return e==null||e.set(z,r),r}G(globalThis);})();//# sourceMappingURL=messenger.iife.js.map
|
|
65
|
+
//# sourceMappingURL=messenger.iife.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a,d}from'./chunk-VG77TYVX.js';import'./chunk-5XGN7UAV.js';var s="prodantix.messenger.config";function l(e,n){let t=e?.get(s);if(!t)return null;try{let a=JSON.parse(t);return a?.apiKey===n?a.config:null}catch{return null}}async function f(e){let n=a(e.fetchImpl);if(!n)return e.onError?.(new Error("no fetch available for the prodantix messenger")),null;let t=d(e.host),a$1=e.locale?`?locale=${encodeURIComponent(e.locale)}`:"";try{let r=await n(`${t}/v1/messenger/config${a$1}`,{headers:{authorization:`Bearer ${e.apiKey}`},method:"GET"});if(!r.ok)return e.onError?.(new Error(`prodantix messenger config: ${r.status}`)),null;let o=JSON.parse(await r.text());return o.enabled?(e.storage?.set(s,JSON.stringify({apiKey:e.apiKey,config:o})),o):(e.storage?.remove(s),o)}catch(r){return e.onError?.(r),null}}export{s as MESSENGER_CACHE_KEY,l as cachedMessengerConfig,f as fetchMessengerConfig};//# sourceMappingURL=messenger.js.map
|
|
2
|
+
//# sourceMappingURL=messenger.js.map
|
package/dist/node.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var J=Object.defineProperty;var Q=(t,e,s)=>e in t?J(t,e,{enumerable:true,configurable:true,writable:true,value:s}):t[e]=s;var i=(t,e,s)=>Q(t,typeof e!="symbol"?e+"":e,s);var l=class extends Error{constructor(s,r,n){super(r,n);i(this,"code");this.code=s,this.name="ProdantixError";}},g=class extends l{constructor(e){super("config",e),this.name="ConfigError";}},f=class extends l{constructor(s,r){super("validation",r);i(this,"field");this.field=s,this.name="ValidationError";}},c=class extends l{constructor(s,r,n){super("transport",s,n);i(this,"status");this.status=r,this.name="TransportError";}};function m(t){if(t)return t;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function d(){let t=globalThis.AbortController;return t?new t:void 0}var T=t=>new Promise(e=>{setTimeout(e,t);});function u(t){return t.replace(/\/+$/,"")}var y=class{constructor(){i(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);}};var S={now:()=>new Date};function v(t){return t.toISOString()}function U(){return globalThis.crypto}function B(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 H(){let t=U();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 B(e)}var P={uuid:H};var G=/^pdx_pub_(?:(?:live|test)_)?[a-z0-9]{32}$/;var X=/^(?:\$|[a-z])[a-z0-9_.]*$/;function C(t){let e=0;for(let s of t)e+=1;return e}function _(t){return G.test(t)}function Y(t){return X.test(t)}function R(t){let e=C(t);if(e<1||e>200)throw new f("distinct_id","distinct_id must be between 1 and 200 characters")}function M(t){let e=C(t);if(e<1||e>200)throw new f("event_name","event_name must be between 1 and 200 characters");if(!Y(t))throw new f("event_name","event_name must match /^(\\$|[a-z])[a-z0-9_.]*$/")}var A="prodantix-js",q="0.0.1";var Z=t=>{};function $(t){if(!t.apiKey||!_(t.apiKey))throw new g("apiKey must be a public project key of the form pdx_pub_<32 lowercase alphanumerics>");if(!t.host)throw new g("host is required (the ingest base URL)");let e=u(t.host),s=t.defaultProperties;return {apiKey:t.apiKey,autocapture:t.autocapture??false,clock:t.clock??S,defaultProperties:typeof s=="function"?s:()=>s??{},flagsHost:t.flagsHost?u(t.flagsHost):e,flushAt:t.flushAt??20,flushIntervalMs:t.flushIntervalMs??1e4,host:e,ids:t.ids??P,locale:t.locale,maxQueueSize:t.maxQueueSize??1e3,maxRetries:t.maxRetries??3,namespace:t.apiKey.slice(0,16),onError:t.onError??Z,os:t.os,requestTimeoutMs:t.requestTimeoutMs??1e4,sdkName:t.sdkName??A,sdkVersion:t.sdkVersion??q,storage:t.storage??new y,transport:t.transport}}function N(t,e,s){M(t.eventName),R(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:v(t.timestamp??e.now())};return t.context&&(r.context=t.context),t.sessionId&&(r.session_id=t.sessionId),r}var h=Symbol("absent");function W(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 L(t){return t===h?Number.NaN:Number(t)}function O(t){return t!==h&&t!==null&&t!==""}function D(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=W(t.attribute,e),r=t.value;switch(t.op){case "is_set":return O(s);case "is_not_set":return !O(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 D(s,r);case "not_in":return Array.isArray(r)?!D(s,r):false;case "gt":return x(s,r,(n,o)=>n>o);case "gte":return x(s,r,(n,o)=>n>=o);case "lt":return x(s,r,(n,o)=>n<o);case "lte":return x(s,r,(n,o)=>n<=o);default:return false}}function x(t,e,s){let r=L(t),n=e===void 0?Number.NaN:L(e);return Number.isNaN(r)||Number.isNaN(n)?false:s(r,n)}function ee(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 te(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"}:ee(t.key,e.distinctId)<t.rolloutPercentage?{enabled:true,reason:"rollout"}:{enabled:false,reason:"rollout_excluded"}:{enabled:false,reason:"disabled"}}function j(t,e){let s={};for(let r of t)s[r.key]=te(r,e).enabled;return s}var b=class{constructor(e){i(this,"fetch");i(this,"host");i(this,"projectKey");i(this,"requestTimeoutMs");this.fetch=m(e.fetch),this.host=u(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async fetchAll(e){let s=this.fetch;if(!s)throw new c("no fetch implementation available in this runtime");let r=`${this.host}/v1/flags?distinct_id=${encodeURIComponent(e)}`,n=d(),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 c(`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 c("no fetch implementation available in this runtime");let s=`${this.host}/v1/flags/snapshot`,r=d(),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 c(`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 I=class{constructor(e,s,r){this.storage=e;this.ids=s;this.namespace=r;i(this,"anonymousId");i(this,"distinctId");i(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 E=class{constructor(e){i(this,"fetch");i(this,"host");i(this,"projectKey");i(this,"requestTimeoutMs");this.fetch=m(e.fetch),this.host=u(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 c(`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 c(`mark-read request failed with status ${o.status}`,o.status)}requireFetch(){if(!this.fetch)throw new c("no fetch implementation available in this runtime");return this.fetch}authHeaders(){return {authorization:`Bearer ${this.projectKey}`}}async request(e,s,r){let n=d(),o=n?setTimeout(()=>n.abort(),this.requestTimeoutMs):void 0;try{return await e(s,{...r,signal:n?.signal})}finally{o!==void 0&&clearTimeout(o);}}};var w=class{constructor(e,s){this.maxSize=e;this.onOverflow=s;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 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});}};function V(t){return t>=400&&t<500&&t!==429}var F=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=m(e.fetch),this.maxRetries=e.maxRetries??3,this.requestTimeoutMs=e.requestTimeoutMs??1e4,this.baseDelayMs=e.baseDelayMs??500,this.maxDelayMs=e.maxDelayMs??3e4,this.sleep=e.sleep??T,this.random=e.random??Math.random;}async send(e){let s=this.fetch;if(!s)throw new c("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(V(a.status))throw new c(`ingest rejected batch with status ${a.status}`,a.status);n=new c(`ingest transient status ${a.status}`,a.status);}catch(a){if(a instanceof c&&a.status!==void 0&&V(a.status))throw a;n=a;}o<this.maxRetries&&await this.sleep(this.backoff(o));}throw new c("ingest delivery failed after retries",void 0,{cause:n})}async attempt(e,s,r){let n=d(),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 se="queue",re=1e3,ne=3e4,k=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=$(e),this.identity=new I(this.config.storage,this.config.ids,this.config.namespace),this.queue=new w(this.config.maxQueueSize,({dropped:s})=>{this.config.onError(new l("queue_overflow",`event queue overflow: dropped ${s.length} oldest event(s)`));}),this.transport=this.config.transport??new F({maxRetries:this.config.maxRetries,requestTimeoutMs:this.config.requestTimeoutMs}),this.flagsClient=new b({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.messagesClient=new E({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=N({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),s.set&&(a.$set=s.set),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});}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 j(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:v(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 z(){return globalThis.process}function ie(t){z()?.on("beforeExit",()=>{t.flush();});}function at(t){let e=z(),s={...t,os:t.os??(e?.platform?e.platform.slice(0,50):void 0)},r=new k(s);return ie(r),r}exports.createNodeClient=at;//# sourceMappingURL=node.cjs.map
|
|
1
|
+
'use strict';var U=Object.defineProperty;var B=(t,e,r)=>e in t?U(t,e,{enumerable:true,configurable:true,writable:true,value:r}):t[e]=r;var i=(t,e,r)=>B(t,typeof e!="symbol"?e+"":e,r);var c=class extends Error{constructor(r,s,n){super(s,n);i(this,"code");this.code=r,this.name="ProdantixError";}},g=class extends c{constructor(e){super("config",e),this.name="ConfigError";}},f=class extends c{constructor(r,s){super("validation",s);i(this,"field");this.field=r,this.name="ValidationError";}},l=class extends c{constructor(r,s,n){super("transport",r,n);i(this,"status");this.status=s,this.name="TransportError";}};function m(t){if(t)return t;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function d(){let t=globalThis.AbortController;return t?new t:void 0}var P=t=>new Promise(e=>{setTimeout(e,t);});function u(t){return t.replace(/\/+$/,"")}var y=class{constructor(){i(this,"store",new Map);}getItem(e){return this.store.get(e)??null}removeItem(e){this.store.delete(e);}setItem(e,r){this.store.set(e,r);}};var S={now:()=>new Date};function v(t){return t.toISOString()}function H(){return globalThis.crypto}function G(t){t[6]=t[6]&15|64,t[8]=t[8]&63|128;let e=[];for(let r=0;r<16;r+=1)e.push(t[r].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 X(){let t=H();if(t?.randomUUID)return t.randomUUID();let e=new Uint8Array(16);if(t?.getRandomValues)t.getRandomValues(e);else for(let r=0;r<16;r+=1)e[r]=Math.floor(Math.random()*256);return G(e)}var C={uuid:X};var Y=/^pdx_pub_(?:(?:live|test)_)?[a-z0-9]{32}$/;var Z=/^(?:\$|[a-z])[a-z0-9_.]*$/;function _(t){let e=0;for(let r of t)e+=1;return e}function R(t){return Y.test(t)}function W(t){return Z.test(t)}function $(t){let e=_(t);if(e<1||e>200)throw new f("distinct_id","distinct_id must be between 1 and 200 characters")}function M(t){let e=_(t);if(e<1||e>200)throw new f("event_name","event_name must be between 1 and 200 characters");if(!W(t))throw new f("event_name","event_name must match /^(\\$|[a-z])[a-z0-9_.]*$/")}var A="prodantix-js",q="0.0.1";var ee=t=>{};function N(t){if(!t.apiKey||!R(t.apiKey))throw new g("apiKey must be a public project key of the form pdx_pub_<32 lowercase alphanumerics>");if(!t.host)throw new g("host is required (the ingest base URL)");let e=u(t.host),r=t.defaultProperties;return {apiKey:t.apiKey,autocapture:t.autocapture??false,clock:t.clock??S,defaultProperties:typeof r=="function"?r:()=>r??{},flagsHost:t.flagsHost?u(t.flagsHost):e,flushAt:t.flushAt??20,flushIntervalMs:t.flushIntervalMs??1e4,host:e,ids:t.ids??C,locale:t.locale,maxQueueSize:t.maxQueueSize??1e3,maxRetries:t.maxRetries??3,namespace:t.apiKey.slice(0,16),onError:t.onError??ee,os:t.os,requestTimeoutMs:t.requestTimeoutMs??1e4,sdkName:t.sdkName??A,sdkVersion:t.sdkVersion??q,storage:t.storage??new y,transport:t.transport}}function O(t,e,r){M(t.eventName),$(t.distinctId);let s={distinct_id:t.distinctId,event_id:t.eventId??r.uuid(),event_name:t.eventName,properties:t.properties??{},schema_version:1,timestamp:v(t.timestamp??e.now())};return t.context&&(s.context=t.context),t.sessionId&&(s.session_id=t.sessionId),s}var h=Symbol("absent");function te(t,e){if(t==="distinct_id")return e.distinctId;let r=e.properties??{};if(Object.prototype.hasOwnProperty.call(r,t))return r[t];let s=e.attributes??{};return Object.prototype.hasOwnProperty.call(s,t)?s[t]:h}function p(t){return t===h?"undefined":String(t)}function L(t){return t===h?Number.NaN:Number(t)}function D(t){return t!==h&&t!==null&&t!==""}function K(t,e){if(!Array.isArray(e))return false;let r=p(t);return e.map(s=>String(s)).includes(r)}function j(t,e){let r=te(t.attribute,e),s=t.value;switch(t.op){case "is_set":return D(r);case "is_not_set":return !D(r);case "eq":return p(r)===p(s===void 0?h:s);case "neq":return p(r)!==p(s===void 0?h:s);case "contains":return p(r).includes(p(s===void 0?h:s));case "in":return K(r,s);case "not_in":return Array.isArray(s)?!K(r,s):false;case "gt":return x(r,s,(n,o)=>n>o);case "gte":return x(r,s,(n,o)=>n>=o);case "lt":return x(r,s,(n,o)=>n<o);case "lte":return x(r,s,(n,o)=>n<=o);default:return false}}function x(t,e,r){let s=L(t),n=e===void 0?Number.NaN:L(e);return Number.isNaN(s)||Number.isNaN(n)?false:r(s,n)}function re(t,e){let r=`${t}:${e}`,s=2166136261;for(let n=0;n<r.length;n++)s^=r.charCodeAt(n),s=Math.imul(s,16777619);return (s>>>0)%100}function se(t,e){return t.enabled?t.targeting.length>0&&!t.targeting.every(r=>j(r,e))?{enabled:false,reason:"targeting"}:t.rolloutPercentage>=100?{enabled:true,reason:"rollout_full"}:re(t.key,e.distinctId)<t.rolloutPercentage?{enabled:true,reason:"rollout"}:{enabled:false,reason:"rollout_excluded"}:{enabled:false,reason:"disabled"}}function V(t,e){let r={};for(let s of t)r[s.key]=se(s,e).enabled;return r}var b=class{constructor(e){i(this,"fetch");i(this,"host");i(this,"projectKey");i(this,"requestTimeoutMs");this.fetch=m(e.fetch),this.host=u(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async fetchAll(e){let r=this.fetch;if(!r)throw new l("no fetch implementation available in this runtime");let s=`${this.host}/v1/flags?distinct_id=${encodeURIComponent(e)}`,n=d(),o=n?setTimeout(()=>n.abort(),this.requestTimeoutMs):void 0;try{let a=await r(s,{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 r=`${this.host}/v1/flags/snapshot`,s=d(),n=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{let o=await e(r,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:s?.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 I=class{constructor(e,r,s){this.storage=e;this.ids=r;this.namespace=s;i(this,"anonymousId");i(this,"distinctId");i(this,"identified");let n=e.getItem(this.key("anonymous_id"));n?this.anonymousId=n:(this.anonymousId=r.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 E=class{constructor(e){i(this,"fetch");i(this,"host");i(this,"projectKey");i(this,"requestTimeoutMs");this.fetch=m(e.fetch),this.host=u(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async inbox(e){let r=this.requireFetch(),s=`${this.host}/v1/messages?distinct_id=${encodeURIComponent(e)}`,n=await this.request(r,s,{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,r){let s=this.requireFetch(),n=`${this.host}/v1/messages/read`,o=await this.request(s,n,{body:JSON.stringify({distinct_id:r,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,r,s){let n=d(),o=n?setTimeout(()=>n.abort(),this.requestTimeoutMs):void 0;try{return await e(r,{...s,signal:n?.signal})}finally{o!==void 0&&clearTimeout(o);}}};var F=class{constructor(e,r){this.maxSize=e;this.onOverflow=r;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 r=e===void 0?this.events.length:Math.min(e,this.events.length);return this.events.splice(0,r)}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 z(t){return t>=400&&t<500&&t!==429}var k=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=m(e.fetch),this.maxRetries=e.maxRetries??3,this.requestTimeoutMs=e.requestTimeoutMs??1e4,this.baseDelayMs=e.baseDelayMs??500,this.maxDelayMs=e.maxDelayMs??3e4,this.sleep=e.sleep??P,this.random=e.random??Math.random;}async send(e){let r=this.fetch;if(!r)throw new l("no fetch implementation available in this runtime");let s=JSON.stringify(e.body),n;for(let o=0;o<=this.maxRetries;o+=1){try{let a=await this.attempt(r,e,s);if(a.ok)return;if(z(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&&z(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,r,s){let n=d(),o=n?setTimeout(()=>n.abort(),this.requestTimeoutMs):void 0;try{return await e(r.url,{body:s,headers:{authorization:`Bearer ${r.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 ne="queue",ie=1e3,oe=3e4,J=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},w=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=N(e),this.identity=new I(this.config.storage,this.config.ids,this.config.namespace),this.queue=new F(this.config.maxQueueSize,({dropped:r})=>{this.config.onError(new c("queue_overflow",`event queue overflow: dropped ${r.length} oldest event(s)`));}),this.transport=this.config.transport??new k({maxRetries:this.config.maxRetries,requestTimeoutMs:this.config.requestTimeoutMs}),this.flagsClient=new b({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.messagesClient=new E({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,r={}){try{let s={...this.config.defaultProperties(),...r.properties??{}},n=O({context:this.context,distinctId:this.identity.getDistinctId(),eventName:e,properties:s,sessionId:r.sessionId,timestamp:r.timestamp},this.config.clock,this.config.ids);this.enqueue(n);}catch(s){this.config.onError(s);}}identify(e,r={}){let s=this.identity.getAnonymousId(),n=!this.identity.isIdentified(),o=this.identity.identify(e),a={};n&&o.changed&&(a.$anon_distinct_id=s);let T={...J(r.traits??{}),...r.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,r,s){let n={$group_key:r,$group_type:e};s&&(n.$set=s),this.capture("$group",{properties:n});}setPersonProperties(e,r){let s={};e&&(s.$set=e),r&&(s.$set_once=r),this.capture("$set",{properties:s});}setPersonTraits(e){let r=J(e);Object.keys(r).length!==0&&this.capture("$set",{properties:{$set:r}});}async getAllFlags(){let e=this.identity.getDistinctId(),r=await this.flagsClient.fetchAll(e);return this.cachedFlags={distinctId:e,flags:r},r}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 r=await this.flagSnapshot();return V(r.flags,{attributes:e.attributes,distinctId:this.identity.getDistinctId(),properties:e.properties})}async isFeatureEnabledLocal(e,r){return (await this.getLocalFlags(r))[e]??false}async flagSnapshot(){let e=this.config.clock.now().getTime();if(this.cachedSnapshot&&e-this.cachedSnapshot.fetchedAt<oe)return this.cachedSnapshot.snapshot;let r=await this.flagsClient.snapshot();return this.cachedSnapshot={fetchedAt:e,snapshot:r},r}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(ie);try{await this.transport.send({body:{events:e,sent_at:v(this.config.clock.now())},projectKey:this.config.apiKey,url:`${this.config.host}/v1/events`}),this.persistQueue();}catch(r){this.queue.requeue(e),this.persistQueue(),this.config.onError(r);}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 r=JSON.parse(e);Array.isArray(r)&&this.queue.restore(r);}catch(e){this.config.onError(e);}}startTimer(){if(this.config.flushIntervalMs<=0)return;let e=setInterval(()=>{this.flush();},this.config.flushIntervalMs),r=e;typeof r.unref=="function"&&r.unref(),this.flushTimer=e;}stopTimer(){this.flushTimer!==void 0&&(clearInterval(this.flushTimer),this.flushTimer=void 0);}persistKey(){return `pdx.${this.config.namespace}.${ne}`}};function Q(){return globalThis.process}function ae(t){Q()?.on("beforeExit",()=>{t.flush();});}function lt(t){let e=Q(),r={...t,os:t.os??(e?.platform?e.platform.slice(0,50):void 0)},s=new w(r);return ae(s),s}exports.createNodeClient=lt;//# sourceMappingURL=node.cjs.map
|
|
2
2
|
//# sourceMappingURL=node.cjs.map
|