@prodantix/sdk 0.0.1 → 0.1.0-beta.348
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 +64 -0
- package/dist/chat.d.ts +64 -0
- package/dist/chat.js +65 -0
- package/dist/chunk-5XGN7UAV.js +2 -0
- package/dist/chunk-CSIP3PZ7.js +2 -0
- package/dist/chunk-V77KYPOF.js +2 -0
- package/dist/chunk-VG77TYVX.js +2 -0
- package/dist/client-Ca6xJESF.d.ts +105 -0
- package/dist/client-y1xyVF6C.d.cts +105 -0
- 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 +28 -6
- package/dist/index.d.ts +28 -6
- 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 +2 -1
- package/dist/node.d.ts +2 -1
- package/dist/node.js +1 -1
- package/dist/{transport-By6wsdny.d.ts → transport-Bj4nXmgt.d.cts} +3 -15
- package/dist/{transport-B3PxeUxW.d.cts → transport-CTPih3Jj.d.ts} +3 -15
- package/dist/types-68Sc11g8.d.cts +105 -0
- package/dist/types-68Sc11g8.d.ts +105 -0
- package/dist/web.cjs +1 -1
- package/dist/web.d.cts +4 -2
- package/dist/web.d.ts +4 -2
- package/dist/web.js +1 -1
- package/package.json +19 -3
- package/dist/chunk-FIZWZVZG.js +0 -2
- package/dist/client-B1bcIuD8.d.cts +0 -133
- package/dist/client-B1bcIuD8.d.ts +0 -133
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
1
|
+
export { C as CaptureOptions, I as IdentifyOptions, L as LocalFlagContext, P as ProdantixClient, c as createClient } from './client-Ca6xJESF.js';
|
|
2
|
+
import { J as JsonValue, F as FlagsResponse, I as InboxMessage, a as StorageAdapter } from './types-68Sc11g8.js';
|
|
3
|
+
export { C as Clock, E as EventBatch, b as EventContext, c as EventEnvelope, d as EventProperties, e as FlagVariant, f as IdFactory, g as InboxResponse, P as ProdantixConfig, T as Transport, h as TransportRequest } from './types-68Sc11g8.js';
|
|
4
|
+
import { F as FetchLike } from './http-BCh716Vs.js';
|
|
5
|
+
export { F as FetchTransport } from './transport-CTPih3Jj.js';
|
|
5
6
|
|
|
6
7
|
type ProdantixErrorCode = 'config' | 'queue_overflow' | 'transport' | 'validation';
|
|
7
8
|
declare class ProdantixError extends Error {
|
|
@@ -20,7 +21,7 @@ declare class TransportError extends ProdantixError {
|
|
|
20
21
|
constructor(message: string, status?: number, options?: ErrorOptions);
|
|
21
22
|
}
|
|
22
23
|
|
|
23
|
-
type FlagOp = 'eq' | 'neq' | 'in' | 'not_in' | 'contains' | 'gt' | 'gte' | 'lt' | 'lte' | 'is_set' | 'is_not_set';
|
|
24
|
+
type FlagOp = 'eq' | 'neq' | 'in' | 'not_in' | 'contains' | 'gt' | 'gte' | 'lt' | 'lte' | 'is_set' | 'is_not_set' | 'in_cohort' | 'not_in_cohort';
|
|
24
25
|
interface FlagCondition {
|
|
25
26
|
attribute: string;
|
|
26
27
|
op: FlagOp;
|
|
@@ -28,21 +29,36 @@ interface FlagCondition {
|
|
|
28
29
|
}
|
|
29
30
|
interface FlagEvalContext {
|
|
30
31
|
attributes?: Record<string, JsonValue>;
|
|
32
|
+
cohorts?: string[];
|
|
31
33
|
distinctId: string;
|
|
32
34
|
properties?: Record<string, JsonValue>;
|
|
33
35
|
}
|
|
34
36
|
declare function matches(condition: FlagCondition, ctx: FlagEvalContext): boolean;
|
|
35
37
|
|
|
38
|
+
interface FlagVariation {
|
|
39
|
+
key: string;
|
|
40
|
+
value: unknown;
|
|
41
|
+
weight: number;
|
|
42
|
+
}
|
|
43
|
+
interface FlagPrerequisite {
|
|
44
|
+
flagKey: string;
|
|
45
|
+
variationKey: string;
|
|
46
|
+
}
|
|
36
47
|
interface FlagRule {
|
|
37
48
|
description?: string;
|
|
38
49
|
enabled: boolean;
|
|
50
|
+
intent?: string;
|
|
39
51
|
key: string;
|
|
52
|
+
prerequisites?: FlagPrerequisite[];
|
|
40
53
|
rolloutPercentage: number;
|
|
41
54
|
targeting: FlagCondition[];
|
|
55
|
+
type?: string;
|
|
56
|
+
variations?: FlagVariation[];
|
|
42
57
|
}
|
|
43
58
|
interface FlagSnapshot {
|
|
44
59
|
flags: FlagRule[];
|
|
45
60
|
generatedAt: string;
|
|
61
|
+
socketUrl?: string;
|
|
46
62
|
}
|
|
47
63
|
interface FlagDecision {
|
|
48
64
|
enabled: boolean;
|
|
@@ -51,6 +67,8 @@ interface FlagDecision {
|
|
|
51
67
|
declare function bucket(key: string, distinctId: string): number;
|
|
52
68
|
declare function evaluateFlag(rule: FlagRule, ctx: FlagEvalContext): FlagDecision;
|
|
53
69
|
declare function evaluateAll(rules: FlagRule[], ctx: FlagEvalContext): Record<string, boolean>;
|
|
70
|
+
declare function assignVariant(rule: FlagRule, ctx: FlagEvalContext): FlagVariation | null;
|
|
71
|
+
declare function getVariant(rules: FlagRule[], key: string, ctx: FlagEvalContext): unknown;
|
|
54
72
|
|
|
55
73
|
interface FlagsClientOptions {
|
|
56
74
|
fetch?: FetchLike;
|
|
@@ -65,7 +83,11 @@ declare class FlagsClient {
|
|
|
65
83
|
private readonly requestTimeoutMs;
|
|
66
84
|
constructor(options: FlagsClientOptions);
|
|
67
85
|
fetchAll(distinctId: string): Promise<Record<string, boolean>>;
|
|
86
|
+
fetchDecisions(distinctId: string): Promise<FlagsResponse>;
|
|
68
87
|
snapshot(): Promise<FlagSnapshot>;
|
|
88
|
+
/** The cohorts a distinct id belongs to, for local evaluation of cohort
|
|
89
|
+
* conditions against the same membership store the server reads. */
|
|
90
|
+
memberships(distinctId: string): Promise<string[]>;
|
|
69
91
|
}
|
|
70
92
|
|
|
71
93
|
interface MessagesClientOptions {
|
|
@@ -97,4 +119,4 @@ declare class MemoryStorage implements StorageAdapter {
|
|
|
97
119
|
declare const SDK_NAME = "prodantix-js";
|
|
98
120
|
declare const SDK_VERSION = "0.0.1";
|
|
99
121
|
|
|
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 };
|
|
122
|
+
export { ConfigError, type FlagCondition, type FlagDecision, type FlagEvalContext, type FlagOp, type FlagRule, type FlagSnapshot, type FlagVariation, FlagsClient, FlagsResponse, 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-CSIP3PZ7.js';import'./chunk-V77KYPOF.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 oe=Object.defineProperty;var ae=(n,e,t)=>e in n?oe(n,e,{enumerable:true,configurable:true,writable:true,value:t}):n[e]=t;var o=(n,e,t)=>ae(n,typeof e!="symbol"?e+"":e,t);var d=class extends Error{constructor(t,r,s){super(r,s);o(this,"code");this.code=t,this.name="ProdantixError";}},y=class extends d{constructor(e){super("config",e),this.name="ConfigError";}},g=class extends d{constructor(t,r){super("validation",r);o(this,"field");this.field=t,this.name="ValidationError";}},c=class extends d{constructor(t,r,s){super("transport",t,s);o(this,"status");this.status=r,this.name="TransportError";}};function m(n){if(n)return n;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function u(){let n=globalThis.AbortController;return n?new n:void 0}var $=n=>new Promise(e=>{setTimeout(e,n);});function h(n){return n.replace(/\/+$/,"")}var v=class{constructor(){o(this,"store",new Map);}getItem(e){return this.store.get(e)??null}removeItem(e){this.store.delete(e);}setItem(e,t){this.store.set(e,t);}};var A={now:()=>new Date};function b(n){return n.toISOString()}function ce(){return globalThis.crypto}function le(n){n[6]=n[6]&15|64,n[8]=n[8]&63|128;let e=[];for(let t=0;t<16;t+=1)e.push(n[t].toString(16).padStart(2,"0"));return `${e[0]}${e[1]}${e[2]}${e[3]}-${e[4]}${e[5]}-${e[6]}${e[7]}-${e[8]}${e[9]}-${e[10]}${e[11]}${e[12]}${e[13]}${e[14]}${e[15]}`}function ue(){let n=ce();if(n?.randomUUID)return n.randomUUID();let e=new Uint8Array(16);if(n?.getRandomValues)n.getRandomValues(e);else for(let t=0;t<16;t+=1)e[t]=Math.floor(Math.random()*256);return le(e)}var O={uuid:ue};var de=/^pdx_pub_(?:(?:live|test)_)?[a-z0-9]{32}$/;var he=/^(?:\$|[a-z])[a-z0-9_.]*$/;function q(n){let e=0;for(let t of n)e+=1;return e}function M(n){return de.test(n)}function pe(n){return he.test(n)}function K(n){let e=q(n);if(e<1||e>200)throw new g("distinct_id","distinct_id must be between 1 and 200 characters")}function L(n){let e=q(n);if(e<1||e>200)throw new g("event_name","event_name must be between 1 and 200 characters");if(!pe(n))throw new g("event_name","event_name must match /^(\\$|[a-z])[a-z0-9_.]*$/")}var D="prodantix-js",V="0.0.1";var fe=n=>{};function j(n){if(!n.apiKey||!M(n.apiKey))throw new y("apiKey must be a public project key of the form pdx_pub_<32 lowercase alphanumerics>");if(!n.host)throw new y("host is required (the ingest base URL)");let e=h(n.host),t=n.defaultProperties;return {apiKey:n.apiKey,autocapture:n.autocapture??false,clock:n.clock??A,defaultProperties:typeof t=="function"?t:()=>t??{},flagsHost:n.flagsHost?h(n.flagsHost):e,flushAt:n.flushAt??20,flushIntervalMs:n.flushIntervalMs??1e4,host:e,ids:n.ids??O,locale:n.locale,maxQueueSize:n.maxQueueSize??1e3,maxRetries:n.maxRetries??3,namespace:n.apiKey.slice(0,16),onError:n.onError??fe,os:n.os,requestTimeoutMs:n.requestTimeoutMs??1e4,sdkName:n.sdkName??D,sdkVersion:n.sdkVersion??V,socketFactory:n.socketFactory,storage:n.storage??new v,streamFlags:n.streamFlags??false,transport:n.transport}}function G(n,e,t){L(n.eventName),K(n.distinctId);let r={distinct_id:n.distinctId,event_id:n.eventId??t.uuid(),event_name:n.eventName,properties:n.properties??{},schema_version:1,timestamp:b(n.timestamp??e.now())};return n.context&&(r.context=n.context),n.sessionId&&(r.session_id=n.sessionId),r}var f=Symbol("absent");function ge(n,e){if(n==="distinct_id")return e.distinctId;let t=e.properties??{};if(Object.prototype.hasOwnProperty.call(t,n))return t[n];let r=e.attributes??{};return Object.prototype.hasOwnProperty.call(r,n)?r[n]:f}function p(n){return n===f?"undefined":String(n)}function U(n){return n===f?Number.NaN:Number(n)}function z(n){return n!==f&&n!==null&&n!==""}function H(n,e){if(!Array.isArray(e))return false;let t=p(n);return e.map(r=>String(r)).includes(t)}function J(n,e){let t=ge(n.attribute,e),r=n.value;switch(n.op){case "is_set":return z(t);case "is_not_set":return !z(t);case "eq":return p(t)===p(r===void 0?f:r);case "neq":return p(t)!==p(r===void 0?f:r);case "contains":return p(t).includes(p(r===void 0?f:r));case "in":return H(t,r);case "not_in":return Array.isArray(r)?!H(t,r):false;case "gt":return k(t,r,(s,i)=>s>i);case "gte":return k(t,r,(s,i)=>s>=i);case "lt":return k(t,r,(s,i)=>s<i);case "lte":return k(t,r,(s,i)=>s<=i);case "in_cohort":return typeof r=="string"&&r!==""&&(e.cohorts??[]).includes(r);case "not_in_cohort":return typeof r=="string"&&r!==""&&!(e.cohorts??[]).includes(r);default:return false}}function k(n,e,t){let r=U(n),s=e===void 0?Number.NaN:U(e);return Number.isNaN(r)||Number.isNaN(s)?false:t(r,s)}function Q(n,e){let t=`${n}:${e}`,r=2166136261;for(let s=0;s<t.length;s++)r^=t.charCodeAt(s),r=Math.imul(r,16777619);return (r>>>0)%100}function _(n,e){return n.targeting.length===0||n.targeting.every(t=>J(t,e))}function B(n,e){let t=Q(n.key,e.distinctId),r=n.variations??[];if(r.length===0)return n.rolloutPercentage>=100||t<n.rolloutPercentage?"true":"false";let s=0;for(let i=r.length-1;i>=0;i--)if(s+=r[i].weight,t<s)return r[i].key;return r[0].key}function P(n,e,t,r){for(let s of n.prerequisites??[]){if(r.includes(s.flagKey))return false;let i=e.find(l=>l.key===s.flagKey);if(!i||!i.enabled)return false;r.push(i.key);let a=P(i,e,t,r)&&_(i,t)&&B(i,t)===s.variationKey;if(r.pop(),!a)return false}return true}function x(n,e,t){return n.enabled?P(n,e,t,[n.key])?_(n,t)?n.rolloutPercentage>=100?{enabled:true,reason:"rollout_full"}:Q(n.key,t.distinctId)<n.rolloutPercentage?{enabled:true,reason:"rollout"}:{enabled:false,reason:"rollout_excluded"}:{enabled:false,reason:"targeting"}:{enabled:false,reason:"prerequisite"}:{enabled:false,reason:"disabled"}}function W(n,e){let t={};for(let r of n)t[r.key]=x(r,n,e).enabled;return t}function R(n,e,t){let r=n.variations??[],s=r[0];if(!s)return null;if(!n.enabled||!P(n,e,t,[n.key])||!_(n,t))return s;let i=B(n,t);return r.find(a=>a.key===i)??s}function X(n){return n.some(e=>e.targeting.some(t=>t.op==="in_cohort"||t.op==="not_in_cohort"))}function Y(n){return `40${JSON.stringify(n)}`}function Z(){return "3"}function ee(n){let e=n.charAt(0),t=n.slice(1);if(e==="2")return {kind:"ping"};if(e==="1")return {kind:"disconnect"};if(e==="0"){let a=N(t);return {kind:"open",pingInterval:typeof a?.pingInterval=="number"?a.pingInterval:25e3,pingTimeout:typeof a?.pingTimeout=="number"?a.pingTimeout:2e4}}if(e!=="4")return {kind:"other"};let r=t.charAt(0),s=t.slice(1);if(r==="0")return {kind:"connected"};if(r==="1")return {kind:"disconnect"};if(r==="4"){let a=N(s);return {kind:"connectError",message:typeof a?.message=="string"?a.message:"refused"}}if(r!=="2")return {kind:"other"};let i=N(s);return !Array.isArray(i)||typeof i[0]!="string"?{kind:"other"}:{kind:"event",name:i[0],payload:i[1]}}function N(n){try{return JSON.parse(n)}catch{return null}}var me="/socket.io/?EIO=4&transport=websocket",ye=250,E=class{constructor(e){this.options=e;o(this,"socket",null);o(this,"heartbeat",null);o(this,"pending",null);o(this,"lastKey","");o(this,"ready",false);o(this,"closed",false);o(this,"heartbeatWindow",45e3);o(this,"factory");o(this,"setTimer");o(this,"clearTimer");this.factory=e.socketFactory??ve,this.setTimer=e.setTimer??((t,r)=>setTimeout(t,r)),this.clearTimer=e.clearTimer??(t=>clearTimeout(t));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${me}`,t;try{t=this.factory(e);}catch{this.options.onClosed(false);return}this.socket=t,t.onmessage=r=>this.receive(String(r.data)),t.onerror=()=>t.close(),t.onclose=()=>this.fell();}close(){this.closed=true,this.stopHeartbeat(),this.pending!==null&&this.clearTimer(this.pending),this.pending=null;let e=this.socket;this.socket=null,e?.close();}receive(e){let t=ee(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),this.socket?.send(Y({projectKey:this.options.projectKey}));return}if(t.kind==="ping"){this.armHeartbeat(),this.socket?.send(Z());return}if(t.kind==="connectError"||t.kind==="disconnect"){this.stopHeartbeat(),this.socket?.close();return}if(t.kind==="event"){if(t.name==="ready"){this.ready=true;return}if(t.name==="flagChange"){let r=t.payload?.key;this.lastKey=typeof r=="string"?r:"",this.pending===null&&(this.pending=this.setTimer(()=>{this.pending=null,this.options.onChange(this.lastKey);},ye));}}}fell(){this.stopHeartbeat();let e=this.ready;this.socket=null,this.ready=false,this.closed||this.options.onClosed(e);}armHeartbeat(e){e!==void 0&&(this.heartbeatWindow=e),this.stopHeartbeat(),this.heartbeat=this.setTimer(()=>this.socket?.close(),this.heartbeatWindow);}stopHeartbeat(){this.heartbeat!==null&&this.clearTimer(this.heartbeat),this.heartbeat=null;}};function ve(n){let e=globalThis.WebSocket;if(!e)throw new Error("no WebSocket");return new e(n)}var F=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=m(e.fetch),this.host=h(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async fetchAll(e){return (await this.fetchDecisions(e)).flags}async fetchDecisions(e){let t=this.fetch;if(!t)throw new c("no fetch implementation available in this runtime");let r=`${this.host}/v1/flags?distinct_id=${encodeURIComponent(e)}`,s=u(),i=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{let a=await t(r,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:s?.signal});if(!a.ok)throw new c(`flags request failed with status ${a.status}`,a.status);let l=JSON.parse(await a.text());return {flags:l.flags??{},variants:l.variants??{}}}finally{i!==void 0&&clearTimeout(i);}}async snapshot(){let e=this.fetch;if(!e)throw new c("no fetch implementation available in this runtime");let t=`${this.host}/v1/flags/snapshot`,r=u(),s=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let i=await e(t,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!i.ok)throw new c(`flag snapshot request failed with status ${i.status}`,i.status);let a=JSON.parse(await i.text()),l={flags:a.flags??[],generatedAt:a.generatedAt};return typeof a.socketUrl=="string"&&a.socketUrl!==""&&(l.socketUrl=a.socketUrl),l}finally{s!==void 0&&clearTimeout(s);}}async memberships(e){let t=this.fetch;if(!t)throw new c("no fetch implementation available in this runtime");let r=`${this.host}/v1/flags/memberships?distinct_id=${encodeURIComponent(e)}`,s=u(),i=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{let a=await t(r,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:s?.signal});if(!a.ok)throw new c(`memberships request failed with status ${a.status}`,a.status);return JSON.parse(await a.text()).cohorts??[]}finally{i!==void 0&&clearTimeout(i);}}};var I=class{constructor(e,t,r){this.storage=e;this.ids=t;this.namespace=r;o(this,"anonymousId");o(this,"distinctId");o(this,"identified");let s=e.getItem(this.key("anonymous_id"));s?this.anonymousId=s:(this.anonymousId=t.uuid(),e.setItem(this.key("anonymous_id"),this.anonymousId));let i=e.getItem(this.key("distinct_id"));i?(this.distinctId=i,this.identified=true):(this.distinctId=this.anonymousId,this.identified=false);}getAnonymousId(){return this.anonymousId}getDistinctId(){return this.distinctId}isIdentified(){return this.identified}snapshot(){return {anonymousId:this.anonymousId,distinctId:this.distinctId,identified:this.identified}}identify(e){return this.identified&&this.distinctId===e?{changed:false}:(this.distinctId=e,this.identified=true,this.storage.setItem(this.key("distinct_id"),e),{changed:true})}reset(){this.anonymousId=this.ids.uuid(),this.distinctId=this.anonymousId,this.identified=false,this.storage.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.removeItem(this.key("distinct_id"));}key(e){return `pdx.${this.namespace}.${e}`}};var C=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=m(e.fetch),this.host=h(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async inbox(e){let t=this.requireFetch(),r=`${this.host}/v1/messages?distinct_id=${encodeURIComponent(e)}`,s=await this.request(t,r,{headers:this.authHeaders(),method:"GET"});if(!s.ok)throw new c(`inbox request failed with status ${s.status}`,s.status);return JSON.parse(await s.text()).messages??[]}async markRead(e,t){let r=this.requireFetch(),s=`${this.host}/v1/messages/read`,i=await this.request(r,s,{body:JSON.stringify({distinct_id:t,message_id:e}),headers:{...this.authHeaders(),"content-type":"application/json"},method:"POST"});if(!i.ok)throw new c(`mark-read request failed with status ${i.status}`,i.status)}requireFetch(){if(!this.fetch)throw new c("no fetch implementation available in this runtime");return this.fetch}authHeaders(){return {authorization:`Bearer ${this.projectKey}`}}async request(e,t,r){let s=u(),i=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{return await e(t,{...r,signal:s?.signal})}finally{i!==void 0&&clearTimeout(i);}}};var S=class{constructor(e,t){this.maxSize=e;this.onOverflow=t;o(this,"events",[]);}get size(){return this.events.length}enqueue(e){this.events.push(e),this.enforceCap();}restore(e){this.events.push(...e),this.enforceCap();}requeue(e){this.events.unshift(...e),this.enforceCap();}drain(e){let t=e===void 0?this.events.length:Math.min(e,this.events.length);return this.events.splice(0,t)}snapshot(){return [...this.events]}enforceCap(){if(this.events.length<=this.maxSize)return;let e=this.events.splice(0,this.events.length-this.maxSize);this.onOverflow?.({dropped:e});}};function te(n){return n>=400&&n<500&&n!==429}var w=class{constructor(e={}){o(this,"fetch");o(this,"maxRetries");o(this,"requestTimeoutMs");o(this,"baseDelayMs");o(this,"maxDelayMs");o(this,"sleep");o(this,"random");this.fetch=m(e.fetch),this.maxRetries=e.maxRetries??3,this.requestTimeoutMs=e.requestTimeoutMs??1e4,this.baseDelayMs=e.baseDelayMs??500,this.maxDelayMs=e.maxDelayMs??3e4,this.sleep=e.sleep??$,this.random=e.random??Math.random;}async send(e){let t=this.fetch;if(!t)throw new c("no fetch implementation available in this runtime");let r=JSON.stringify(e.body),s;for(let i=0;i<=this.maxRetries;i+=1){try{let a=await this.attempt(t,e,r);if(a.ok)return;if(te(a.status))throw new c(`ingest rejected batch with status ${a.status}`,a.status);s=new c(`ingest transient status ${a.status}`,a.status);}catch(a){if(a instanceof c&&a.status!==void 0&&te(a.status))throw a;s=a;}i<this.maxRetries&&await this.sleep(this.backoff(i));}throw new c("ingest delivery failed after retries",void 0,{cause:s})}async attempt(e,t,r){let s=u(),i=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{return await e(t.url,{body:r,headers:{authorization:`Bearer ${t.projectKey}`,"content-type":"application/json"},method:"POST",signal:s?.signal})}finally{i!==void 0&&clearTimeout(i);}}backoff(e){return Math.min(this.maxDelayMs,this.baseDelayMs*2**e)+this.random()*this.baseDelayMs}};var be="queue",ke=1e3,ne=3e4,re=n=>{let e={};return n.avatar!==void 0&&(e.$avatar=n.avatar),n.email!==void 0&&(e.$email=n.email),n.name!==void 0&&(e.$name=n.name),n.phone!==void 0&&(e.$phone=n.phone),e},T=class{constructor(e){o(this,"config");o(this,"identity");o(this,"queue");o(this,"transport");o(this,"flagsClient");o(this,"messagesClient");o(this,"context");o(this,"flushTimer");o(this,"flushing",false);o(this,"cachedFlags");o(this,"cachedSnapshot");o(this,"membershipCache");o(this,"stream");o(this,"shutDown",false);o(this,"exposures",new Set);this.config=j(e),this.identity=new I(this.config.storage,this.config.ids,this.config.namespace),this.queue=new S(this.config.maxQueueSize,({dropped:t})=>{this.config.onError(new d("queue_overflow",`event queue overflow: dropped ${t.length} oldest event(s)`));}),this.transport=this.config.transport??new w({maxRetries:this.config.maxRetries,requestTimeoutMs:this.config.requestTimeoutMs}),this.flagsClient=new F({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.messagesClient=new C({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.context={sdk:this.config.sdkName,sdk_version:this.config.sdkVersion},this.config.os&&(this.context.os=this.config.os),this.config.locale&&(this.context.locale=this.config.locale),this.restoreQueue(),this.startTimer();}get distinctId(){return this.identity.getDistinctId()}get anonymousId(){return this.identity.getAnonymousId()}capture(e,t={}){try{let r={...this.config.defaultProperties(),...t.properties??{}},s=G({context:this.context,distinctId:this.identity.getDistinctId(),eventName:e,properties:r,sessionId:t.sessionId,timestamp:t.timestamp},this.config.clock,this.config.ids);this.enqueue(s);}catch(r){this.config.onError(r);}}identify(e,t={}){let r=this.identity.getAnonymousId(),s=!this.identity.isIdentified(),i=this.identity.identify(e),a={};s&&i.changed&&(a.$anon_distinct_id=r);let l={...re(t.traits??{}),...t.set??{}};Object.keys(l).length>0&&(a.$set=l),this.capture("$identify",{properties:a});}alias(e){this.capture("$create_alias",{properties:{alias:e}});}group(e,t,r){let s={$group_key:t,$group_type:e};r&&(s.$set=r),this.capture("$group",{properties:s});}setPersonProperties(e,t){let r={};e&&(r.$set=e),t&&(r.$set_once=t),this.capture("$set",{properties:r});}setPersonTraits(e){let t=re(e);Object.keys(t).length!==0&&this.capture("$set",{properties:{$set:t}});}async getAllFlags(){let e=this.identity.getDistinctId(),t=await this.flagsClient.fetchDecisions(e);return this.cachedFlags={distinctId:e,flags:t.flags,variants:t.variants??{}},t.flags}async isFeatureEnabled(e){let r=(await this.getAllFlags())[e]??false;return this.recordExposure(e,this.cachedFlags?.variants[e]?.key??String(r)),r}async getVariant(e){let t=await this.getAllFlags(),r=this.cachedFlags?.variants[e]??null;return this.recordExposure(e,r?.key??String(t[e]??false)),r}async getVariantLocal(e,t={}){let r=await this.flagSnapshot(),s=r.flags.find(ie=>ie.key===e),i=await this.localContext(t,r.flags),a=s?R(s,r.flags,i):null,l=s?x(s,r.flags,i).enabled:false;return this.recordExposure(e,a?.key??String(l)),a?{key:a.key,value:a.value}:null}recordExposure(e,t){let r=`${this.identity.getDistinctId()} ${e} ${t}`;this.exposures.has(r)||(this.exposures.add(r),this.capture("$feature_flag_called",{properties:{$feature_flag:e,$feature_flag_response:t}}));}getCachedFlag(e){if(!(!this.cachedFlags||this.cachedFlags.distinctId!==this.distinctId))return this.cachedFlags.flags[e]}async getLocalFlags(e={}){let t=await this.flagSnapshot();return W(t.flags,await this.localContext(e,t.flags))}async isFeatureEnabledLocal(e,t={}){let r=await this.flagSnapshot(),s=r.flags.find(l=>l.key===e),i=await this.localContext(t,r.flags),a=s?x(s,r.flags,i).enabled:false;return this.recordExposure(e,(s?R(s,r.flags,i)?.key:void 0)??String(a)),a}async localContext(e,t){let r=this.identity.getDistinctId(),s=e.cohorts;if(s===void 0&&X(t)){let i=this.config.clock.now().getTime();this.membershipCache&&this.membershipCache.distinctId===r&&i-this.membershipCache.fetchedAt<ne?s=this.membershipCache.cohorts:(s=await this.flagsClient.memberships(r),this.membershipCache={cohorts:s,distinctId:r,fetchedAt:i});}return {attributes:e.attributes,cohorts:s,distinctId:r,properties:e.properties}}async flagSnapshot(){let e=this.config.clock.now().getTime();if(this.cachedSnapshot&&e-this.cachedSnapshot.fetchedAt<ne)return this.cachedSnapshot.snapshot;let t=await this.flagsClient.snapshot();return this.cachedSnapshot={fetchedAt:e,snapshot:t},this.maybeStream(t),t}maybeStream(e){if(!this.config.streamFlags||this.shutDown||this.stream||!e.socketUrl)return;let t=new E({host:e.socketUrl,onChange:()=>{this.cachedSnapshot=void 0,this.flagSnapshot().catch(r=>this.config.onError(r));},onClosed:r=>{this.stream=void 0,r&&this.maybeStream(e);},projectKey:this.config.apiKey,socketFactory:this.config.socketFactory});this.stream=t,t.open();}async getInbox(){return this.messagesClient.inbox(this.identity.getDistinctId())}async markMessageRead(e){await this.messagesClient.markRead(e,this.identity.getDistinctId());}async flush(){if(this.flushing||this.queue.size===0)return;this.flushing=true;let e=this.queue.drain(ke);try{await this.transport.send({body:{events:e,sent_at:b(this.config.clock.now())},projectKey:this.config.apiKey,url:`${this.config.host}/v1/events`}),this.persistQueue();}catch(t){this.queue.requeue(e),this.persistQueue(),this.config.onError(t);}finally{this.flushing=false;}}reset(){this.identity.reset(),this.cachedFlags=void 0,this.cachedSnapshot=void 0,this.membershipCache=void 0;}async shutdown(){this.shutDown=true,this.stopTimer(),this.stream?.close(),this.stream=void 0,await this.flush();}enqueue(e){this.queue.enqueue(e),this.persistQueue(),this.queue.size>=this.config.flushAt&&this.flush();}persistQueue(){try{this.config.storage.setItem(this.persistKey(),JSON.stringify(this.queue.snapshot()));}catch(e){this.config.onError(e);}}restoreQueue(){try{let e=this.config.storage.getItem(this.persistKey());if(!e)return;let t=JSON.parse(e);Array.isArray(t)&&this.queue.restore(t);}catch(e){this.config.onError(e);}}startTimer(){if(this.config.flushIntervalMs<=0)return;let e=setInterval(()=>{this.flush();},this.config.flushIntervalMs),t=e;typeof t.unref=="function"&&t.unref(),this.flushTimer=e;}stopTimer(){this.flushTimer!==void 0&&(clearInterval(this.flushTimer),this.flushTimer=void 0);}persistKey(){return `pdx.${this.config.namespace}.${be}`}};function se(){return globalThis.process}function xe(n){se()?.on("beforeExit",()=>{n.flush();});}function wt(n){let e=se(),t={...n,os:n.os??(e?.platform?e.platform.slice(0,50):void 0),streamFlags:n.streamFlags??true},r=new T(t);return xe(r),r}exports.createNodeClient=wt;//# sourceMappingURL=node.cjs.map
|
|
2
2
|
//# sourceMappingURL=node.cjs.map
|
package/dist/node.d.cts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { P as ProdantixClient } from './client-y1xyVF6C.cjs';
|
|
2
|
+
import { P as ProdantixConfig } from './types-68Sc11g8.cjs';
|
|
2
3
|
|
|
3
4
|
declare function createNodeClient(options: ProdantixConfig): ProdantixClient;
|
|
4
5
|
|
package/dist/node.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { P as ProdantixClient } from './client-Ca6xJESF.js';
|
|
2
|
+
import { P as ProdantixConfig } from './types-68Sc11g8.js';
|
|
2
3
|
|
|
3
4
|
declare function createNodeClient(options: ProdantixConfig): ProdantixClient;
|
|
4
5
|
|
package/dist/node.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {s as s$1}from'./chunk-CSIP3PZ7.js';import'./chunk-V77KYPOF.js';import'./chunk-VG77TYVX.js';import'./chunk-5XGN7UAV.js';function r(){return globalThis.process}function s(e){r()?.on("beforeExit",()=>{e.flush();});}function a(e){let o=r(),i={...e,os:e.os??(o?.platform?o.platform.slice(0,50):void 0),streamFlags:e.streamFlags??true},n=new s$1(i);return s(n),n}export{a as createNodeClient};//# sourceMappingURL=node.js.map
|
|
2
2
|
//# sourceMappingURL=node.js.map
|
|
@@ -1,17 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
interface FetchResponseLike {
|
|
4
|
-
ok: boolean;
|
|
5
|
-
status: number;
|
|
6
|
-
text(): Promise<string>;
|
|
7
|
-
}
|
|
8
|
-
interface FetchInit {
|
|
9
|
-
body?: string;
|
|
10
|
-
headers: Record<string, string>;
|
|
11
|
-
method: string;
|
|
12
|
-
signal?: AbortSignal;
|
|
13
|
-
}
|
|
14
|
-
type FetchLike = (url: string, init: FetchInit) => Promise<FetchResponseLike>;
|
|
1
|
+
import { F as FetchLike } from './http-BCh716Vs.cjs';
|
|
2
|
+
import { T as Transport, h as TransportRequest } from './types-68Sc11g8.cjs';
|
|
15
3
|
|
|
16
4
|
interface FetchTransportOptions {
|
|
17
5
|
baseDelayMs?: number;
|
|
@@ -36,4 +24,4 @@ declare class FetchTransport implements Transport {
|
|
|
36
24
|
private backoff;
|
|
37
25
|
}
|
|
38
26
|
|
|
39
|
-
export {
|
|
27
|
+
export { FetchTransport as F, type FetchTransportOptions as a };
|
|
@@ -1,17 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
interface FetchResponseLike {
|
|
4
|
-
ok: boolean;
|
|
5
|
-
status: number;
|
|
6
|
-
text(): Promise<string>;
|
|
7
|
-
}
|
|
8
|
-
interface FetchInit {
|
|
9
|
-
body?: string;
|
|
10
|
-
headers: Record<string, string>;
|
|
11
|
-
method: string;
|
|
12
|
-
signal?: AbortSignal;
|
|
13
|
-
}
|
|
14
|
-
type FetchLike = (url: string, init: FetchInit) => Promise<FetchResponseLike>;
|
|
1
|
+
import { F as FetchLike } from './http-BCh716Vs.js';
|
|
2
|
+
import { T as Transport, h as TransportRequest } from './types-68Sc11g8.js';
|
|
15
3
|
|
|
16
4
|
interface FetchTransportOptions {
|
|
17
5
|
baseDelayMs?: number;
|
|
@@ -36,4 +24,4 @@ declare class FetchTransport implements Transport {
|
|
|
36
24
|
private backoff;
|
|
37
25
|
}
|
|
38
26
|
|
|
39
|
-
export {
|
|
27
|
+
export { FetchTransport as F, type FetchTransportOptions as a };
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
type JsonPrimitive = string | number | boolean | null;
|
|
2
|
+
type JsonValue = JsonPrimitive | JsonValue[] | {
|
|
3
|
+
[key: string]: JsonValue;
|
|
4
|
+
};
|
|
5
|
+
type EventProperties = Record<string, JsonValue>;
|
|
6
|
+
interface EventContext {
|
|
7
|
+
locale?: string;
|
|
8
|
+
os?: string;
|
|
9
|
+
sdk?: string;
|
|
10
|
+
sdk_version?: string;
|
|
11
|
+
}
|
|
12
|
+
interface EventEnvelope {
|
|
13
|
+
context?: EventContext;
|
|
14
|
+
distinct_id: string;
|
|
15
|
+
event_id: string;
|
|
16
|
+
event_name: string;
|
|
17
|
+
properties: EventProperties;
|
|
18
|
+
schema_version: 1;
|
|
19
|
+
session_id?: string;
|
|
20
|
+
timestamp: string;
|
|
21
|
+
}
|
|
22
|
+
interface EventBatch {
|
|
23
|
+
api_key?: string;
|
|
24
|
+
events: EventEnvelope[];
|
|
25
|
+
sent_at: string;
|
|
26
|
+
}
|
|
27
|
+
interface FlagVariant {
|
|
28
|
+
key: string;
|
|
29
|
+
value: unknown;
|
|
30
|
+
}
|
|
31
|
+
interface FlagsResponse {
|
|
32
|
+
flags: Record<string, boolean>;
|
|
33
|
+
variants?: Record<string, FlagVariant>;
|
|
34
|
+
}
|
|
35
|
+
interface InboxMessage {
|
|
36
|
+
body: string;
|
|
37
|
+
createdAt: string;
|
|
38
|
+
id: string;
|
|
39
|
+
read: boolean;
|
|
40
|
+
title: string;
|
|
41
|
+
}
|
|
42
|
+
interface InboxResponse {
|
|
43
|
+
messages: InboxMessage[];
|
|
44
|
+
}
|
|
45
|
+
interface Clock {
|
|
46
|
+
now(): Date;
|
|
47
|
+
}
|
|
48
|
+
interface IdFactory {
|
|
49
|
+
uuid(): string;
|
|
50
|
+
}
|
|
51
|
+
interface StorageAdapter {
|
|
52
|
+
getItem(key: string): string | null;
|
|
53
|
+
removeItem(key: string): void;
|
|
54
|
+
setItem(key: string, value: string): void;
|
|
55
|
+
}
|
|
56
|
+
interface TransportRequest {
|
|
57
|
+
body: EventBatch;
|
|
58
|
+
projectKey: string;
|
|
59
|
+
url: string;
|
|
60
|
+
}
|
|
61
|
+
interface Transport {
|
|
62
|
+
send(request: TransportRequest): Promise<void>;
|
|
63
|
+
}
|
|
64
|
+
/** The browser's `WebSocket`, narrowed to what the SDK uses so a test can hand
|
|
65
|
+
* in a fake without a DOM. Assigning the handlers rather than using
|
|
66
|
+
* `addEventListener` keeps the surface to four properties. */
|
|
67
|
+
interface SocketLike {
|
|
68
|
+
send(data: string): void;
|
|
69
|
+
close(): void;
|
|
70
|
+
onopen: (() => void) | null;
|
|
71
|
+
onclose: (() => void) | null;
|
|
72
|
+
onerror: (() => void) | null;
|
|
73
|
+
onmessage: ((event: {
|
|
74
|
+
data: string;
|
|
75
|
+
}) => void) | null;
|
|
76
|
+
}
|
|
77
|
+
type SocketFactory = (url: string) => SocketLike;
|
|
78
|
+
interface ProdantixConfig {
|
|
79
|
+
apiKey: string;
|
|
80
|
+
autocapture?: boolean;
|
|
81
|
+
clock?: Clock;
|
|
82
|
+
defaultProperties?: EventProperties | (() => EventProperties);
|
|
83
|
+
flagsHost?: string;
|
|
84
|
+
flushAt?: number;
|
|
85
|
+
flushIntervalMs?: number;
|
|
86
|
+
host: string;
|
|
87
|
+
ids?: IdFactory;
|
|
88
|
+
locale?: string;
|
|
89
|
+
maxQueueSize?: number;
|
|
90
|
+
maxRetries?: number;
|
|
91
|
+
onError?: (error: unknown) => void;
|
|
92
|
+
os?: string;
|
|
93
|
+
requestTimeoutMs?: number;
|
|
94
|
+
sdkName?: string;
|
|
95
|
+
sdkVersion?: string;
|
|
96
|
+
/** The socket constructor the flag stream uses; the test seam. */
|
|
97
|
+
socketFactory?: SocketFactory;
|
|
98
|
+
storage?: StorageAdapter;
|
|
99
|
+
/** Hold a Socket.IO subscription to flag changes and refetch the snapshot on
|
|
100
|
+
* push. Off unless asked; the node entry turns it on. */
|
|
101
|
+
streamFlags?: boolean;
|
|
102
|
+
transport?: Transport;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export type { Clock as C, EventBatch as E, FlagsResponse as F, InboxMessage as I, JsonValue as J, ProdantixConfig as P, SocketFactory as S, Transport as T, StorageAdapter as a, EventContext as b, EventEnvelope as c, EventProperties as d, FlagVariant as e, IdFactory as f, InboxResponse as g, TransportRequest as h };
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
type JsonPrimitive = string | number | boolean | null;
|
|
2
|
+
type JsonValue = JsonPrimitive | JsonValue[] | {
|
|
3
|
+
[key: string]: JsonValue;
|
|
4
|
+
};
|
|
5
|
+
type EventProperties = Record<string, JsonValue>;
|
|
6
|
+
interface EventContext {
|
|
7
|
+
locale?: string;
|
|
8
|
+
os?: string;
|
|
9
|
+
sdk?: string;
|
|
10
|
+
sdk_version?: string;
|
|
11
|
+
}
|
|
12
|
+
interface EventEnvelope {
|
|
13
|
+
context?: EventContext;
|
|
14
|
+
distinct_id: string;
|
|
15
|
+
event_id: string;
|
|
16
|
+
event_name: string;
|
|
17
|
+
properties: EventProperties;
|
|
18
|
+
schema_version: 1;
|
|
19
|
+
session_id?: string;
|
|
20
|
+
timestamp: string;
|
|
21
|
+
}
|
|
22
|
+
interface EventBatch {
|
|
23
|
+
api_key?: string;
|
|
24
|
+
events: EventEnvelope[];
|
|
25
|
+
sent_at: string;
|
|
26
|
+
}
|
|
27
|
+
interface FlagVariant {
|
|
28
|
+
key: string;
|
|
29
|
+
value: unknown;
|
|
30
|
+
}
|
|
31
|
+
interface FlagsResponse {
|
|
32
|
+
flags: Record<string, boolean>;
|
|
33
|
+
variants?: Record<string, FlagVariant>;
|
|
34
|
+
}
|
|
35
|
+
interface InboxMessage {
|
|
36
|
+
body: string;
|
|
37
|
+
createdAt: string;
|
|
38
|
+
id: string;
|
|
39
|
+
read: boolean;
|
|
40
|
+
title: string;
|
|
41
|
+
}
|
|
42
|
+
interface InboxResponse {
|
|
43
|
+
messages: InboxMessage[];
|
|
44
|
+
}
|
|
45
|
+
interface Clock {
|
|
46
|
+
now(): Date;
|
|
47
|
+
}
|
|
48
|
+
interface IdFactory {
|
|
49
|
+
uuid(): string;
|
|
50
|
+
}
|
|
51
|
+
interface StorageAdapter {
|
|
52
|
+
getItem(key: string): string | null;
|
|
53
|
+
removeItem(key: string): void;
|
|
54
|
+
setItem(key: string, value: string): void;
|
|
55
|
+
}
|
|
56
|
+
interface TransportRequest {
|
|
57
|
+
body: EventBatch;
|
|
58
|
+
projectKey: string;
|
|
59
|
+
url: string;
|
|
60
|
+
}
|
|
61
|
+
interface Transport {
|
|
62
|
+
send(request: TransportRequest): Promise<void>;
|
|
63
|
+
}
|
|
64
|
+
/** The browser's `WebSocket`, narrowed to what the SDK uses so a test can hand
|
|
65
|
+
* in a fake without a DOM. Assigning the handlers rather than using
|
|
66
|
+
* `addEventListener` keeps the surface to four properties. */
|
|
67
|
+
interface SocketLike {
|
|
68
|
+
send(data: string): void;
|
|
69
|
+
close(): void;
|
|
70
|
+
onopen: (() => void) | null;
|
|
71
|
+
onclose: (() => void) | null;
|
|
72
|
+
onerror: (() => void) | null;
|
|
73
|
+
onmessage: ((event: {
|
|
74
|
+
data: string;
|
|
75
|
+
}) => void) | null;
|
|
76
|
+
}
|
|
77
|
+
type SocketFactory = (url: string) => SocketLike;
|
|
78
|
+
interface ProdantixConfig {
|
|
79
|
+
apiKey: string;
|
|
80
|
+
autocapture?: boolean;
|
|
81
|
+
clock?: Clock;
|
|
82
|
+
defaultProperties?: EventProperties | (() => EventProperties);
|
|
83
|
+
flagsHost?: string;
|
|
84
|
+
flushAt?: number;
|
|
85
|
+
flushIntervalMs?: number;
|
|
86
|
+
host: string;
|
|
87
|
+
ids?: IdFactory;
|
|
88
|
+
locale?: string;
|
|
89
|
+
maxQueueSize?: number;
|
|
90
|
+
maxRetries?: number;
|
|
91
|
+
onError?: (error: unknown) => void;
|
|
92
|
+
os?: string;
|
|
93
|
+
requestTimeoutMs?: number;
|
|
94
|
+
sdkName?: string;
|
|
95
|
+
sdkVersion?: string;
|
|
96
|
+
/** The socket constructor the flag stream uses; the test seam. */
|
|
97
|
+
socketFactory?: SocketFactory;
|
|
98
|
+
storage?: StorageAdapter;
|
|
99
|
+
/** Hold a Socket.IO subscription to flag changes and refetch the snapshot on
|
|
100
|
+
* push. Off unless asked; the node entry turns it on. */
|
|
101
|
+
streamFlags?: boolean;
|
|
102
|
+
transport?: Transport;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export type { Clock as C, EventBatch as E, FlagsResponse as F, InboxMessage as I, JsonValue as J, ProdantixConfig as P, SocketFactory as S, Transport as T, StorageAdapter as a, EventContext as b, EventEnvelope as c, EventProperties as d, FlagVariant as e, IdFactory as f, InboxResponse as g, TransportRequest as h };
|