@prodantix/sdk 0.1.0 → 0.2.0-beta.357

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,134 @@
1
+ import { e as EventProperties, P as ProdantixConfig, b as Consent, f as FlagVariant, I as InboxMessage } from './types-DjMXp6Wg.cjs';
2
+
3
+ interface LocalFlagContext {
4
+ attributes?: EventProperties;
5
+ /** The cohorts the current distinct id belongs to. When omitted and the
6
+ * snapshot names a cohort, the client fetches them once per distinct id. */
7
+ cohorts?: string[];
8
+ properties?: EventProperties;
9
+ }
10
+ interface CaptureOptions {
11
+ /** Speak for someone other than this client's own identity. A server has no
12
+ * visitor of its own to lend an event, so an event it sends on a browser's
13
+ * behalf names the person directly. */
14
+ distinctId?: string;
15
+ properties?: EventProperties;
16
+ sessionId?: string;
17
+ timestamp?: Date;
18
+ }
19
+ /**
20
+ * The profile keys the platform itself understands.
21
+ *
22
+ * They are ordinary properties on the wire; the only thing that makes them
23
+ * special is the `$` prefix, which is how this platform marks a name it owns
24
+ * rather than one the caller chose. Passing them through `traits` means never
25
+ * having to remember whether the console reads `email` or `$email`: an
26
+ * unprefixed `email` is a property of your own and stays one, and would never
27
+ * reach the Email column.
28
+ */
29
+ interface PersonTraits {
30
+ avatar?: string;
31
+ email?: string;
32
+ name?: string;
33
+ phone?: string;
34
+ }
35
+ interface IdentifyOptions {
36
+ /** Arbitrary profile properties your own code defines. */
37
+ set?: EventProperties;
38
+ /** The reserved traits the console renders as fields. */
39
+ traits?: PersonTraits;
40
+ }
41
+ declare class ProdantixClient {
42
+ private readonly config;
43
+ private readonly identity;
44
+ private readonly session?;
45
+ private readonly queue;
46
+ private readonly transport;
47
+ private readonly flagsClient;
48
+ private readonly messagesClient;
49
+ private readonly context;
50
+ private flushTimer?;
51
+ private flushing;
52
+ private cachedFlags?;
53
+ private cachedSnapshot?;
54
+ private membershipCache?;
55
+ private stream?;
56
+ private shutDown;
57
+ /** One `$feature_flag_called` per (distinct id, flag, response) per client
58
+ * lifetime: the experiment engine attributes on the FIRST exposure, so a
59
+ * second event for the same answer would only cost the project an event. */
60
+ private readonly exposures;
61
+ constructor(config: ProdantixConfig);
62
+ get distinctId(): string;
63
+ get anonymousId(): string;
64
+ /** Whether this client still holds a person, from the persisted distinct id,
65
+ * so a fresh page load answers the same as the load that identified them.
66
+ * Public because a surface that has resolved to nobody must reset the client
67
+ * only when there is someone to reset: a sign-out is a hard navigation on a
68
+ * BFF surface, so no value-to-null transition ever renders. */
69
+ get isIdentified(): boolean;
70
+ get sessionId(): string | undefined;
71
+ get sessionStartedAt(): number | undefined;
72
+ capture(eventName: string, options?: CaptureOptions): void;
73
+ identify(distinctId: string, options?: IdentifyOptions): void;
74
+ /**
75
+ * Join a browser's anonymous trail to a person from a server. A sign-in that
76
+ * completes in a redirect renders no page, so the browser's own `identify`
77
+ * never runs there; this sends the one `$identify` it would have sent, for
78
+ * the ids given, and leaves this client's own identity as it was.
79
+ */
80
+ link(distinctId: string, anonymousId: string, traits?: PersonTraits): void;
81
+ /**
82
+ * Record the visitor's answer about the join. It rides the shared store, so
83
+ * every subdomain and the login's server read the same one, and it takes
84
+ * effect on the next identify and the next decorated click; nothing already
85
+ * joined is unjoined.
86
+ */
87
+ setConsent(consent: Consent): void;
88
+ /** The visitor's answer, or null when they have not been asked. */
89
+ consent(): Consent | null;
90
+ alias(alias: string): void;
91
+ group(groupType: string, groupKey: string, properties?: EventProperties): void;
92
+ setPersonProperties(set?: EventProperties, setOnce?: EventProperties): void;
93
+ /**
94
+ * Attach the reserved traits to whoever is current, without an identify.
95
+ *
96
+ * This does NOT make the person identified: only `identify()` does that, so a
97
+ * trait set on an anonymous visitor leaves them anonymous and carrying an
98
+ * address, which is exactly what a newsletter signup before login looks like.
99
+ */
100
+ setPersonTraits(traits: PersonTraits): void;
101
+ getAllFlags(): Promise<Record<string, boolean>>;
102
+ isFeatureEnabled(key: string): Promise<boolean>;
103
+ /** The assigned variation for one flag, or null when the flag is unknown or
104
+ * carries no variations. Records the exposure either way. */
105
+ getVariant(key: string): Promise<FlagVariant | null>;
106
+ getVariantLocal(key: string, context?: LocalFlagContext): Promise<FlagVariant | null>;
107
+ private recordExposure;
108
+ getCachedFlag(key: string): boolean | undefined;
109
+ getLocalFlags(context?: LocalFlagContext): Promise<Record<string, boolean>>;
110
+ isFeatureEnabledLocal(key: string, context?: LocalFlagContext): Promise<boolean>;
111
+ /** The evaluation context for a local read. Memberships come from the caller
112
+ * when supplied, else from the server once per distinct id per snapshot
113
+ * TTL, and only when the snapshot names a cohort at all. */
114
+ private localContext;
115
+ private flagSnapshot;
116
+ /** Opens the flag stream once, when streaming was asked for and the snapshot
117
+ * names a gateway. A pushed change drops the cached snapshot and refetches
118
+ * it; a refused handshake stays closed, a dropped one reopens. */
119
+ private maybeStream;
120
+ getInbox(): Promise<InboxMessage[]>;
121
+ markMessageRead(messageId: string): Promise<void>;
122
+ flush(): Promise<void>;
123
+ reset(): void;
124
+ shutdown(): Promise<void>;
125
+ private enqueue;
126
+ private persistQueue;
127
+ private restoreQueue;
128
+ private startTimer;
129
+ private stopTimer;
130
+ private persistKey;
131
+ }
132
+ declare function createClient(config: ProdantixConfig): ProdantixClient;
133
+
134
+ export { type CaptureOptions as C, type IdentifyOptions as I, type LocalFlagContext as L, ProdantixClient as P, createClient as c };
@@ -0,0 +1,134 @@
1
+ import { e as EventProperties, P as ProdantixConfig, b as Consent, f as FlagVariant, I as InboxMessage } from './types-DjMXp6Wg.js';
2
+
3
+ interface LocalFlagContext {
4
+ attributes?: EventProperties;
5
+ /** The cohorts the current distinct id belongs to. When omitted and the
6
+ * snapshot names a cohort, the client fetches them once per distinct id. */
7
+ cohorts?: string[];
8
+ properties?: EventProperties;
9
+ }
10
+ interface CaptureOptions {
11
+ /** Speak for someone other than this client's own identity. A server has no
12
+ * visitor of its own to lend an event, so an event it sends on a browser's
13
+ * behalf names the person directly. */
14
+ distinctId?: string;
15
+ properties?: EventProperties;
16
+ sessionId?: string;
17
+ timestamp?: Date;
18
+ }
19
+ /**
20
+ * The profile keys the platform itself understands.
21
+ *
22
+ * They are ordinary properties on the wire; the only thing that makes them
23
+ * special is the `$` prefix, which is how this platform marks a name it owns
24
+ * rather than one the caller chose. Passing them through `traits` means never
25
+ * having to remember whether the console reads `email` or `$email`: an
26
+ * unprefixed `email` is a property of your own and stays one, and would never
27
+ * reach the Email column.
28
+ */
29
+ interface PersonTraits {
30
+ avatar?: string;
31
+ email?: string;
32
+ name?: string;
33
+ phone?: string;
34
+ }
35
+ interface IdentifyOptions {
36
+ /** Arbitrary profile properties your own code defines. */
37
+ set?: EventProperties;
38
+ /** The reserved traits the console renders as fields. */
39
+ traits?: PersonTraits;
40
+ }
41
+ declare class ProdantixClient {
42
+ private readonly config;
43
+ private readonly identity;
44
+ private readonly session?;
45
+ private readonly queue;
46
+ private readonly transport;
47
+ private readonly flagsClient;
48
+ private readonly messagesClient;
49
+ private readonly context;
50
+ private flushTimer?;
51
+ private flushing;
52
+ private cachedFlags?;
53
+ private cachedSnapshot?;
54
+ private membershipCache?;
55
+ private stream?;
56
+ private shutDown;
57
+ /** One `$feature_flag_called` per (distinct id, flag, response) per client
58
+ * lifetime: the experiment engine attributes on the FIRST exposure, so a
59
+ * second event for the same answer would only cost the project an event. */
60
+ private readonly exposures;
61
+ constructor(config: ProdantixConfig);
62
+ get distinctId(): string;
63
+ get anonymousId(): string;
64
+ /** Whether this client still holds a person, from the persisted distinct id,
65
+ * so a fresh page load answers the same as the load that identified them.
66
+ * Public because a surface that has resolved to nobody must reset the client
67
+ * only when there is someone to reset: a sign-out is a hard navigation on a
68
+ * BFF surface, so no value-to-null transition ever renders. */
69
+ get isIdentified(): boolean;
70
+ get sessionId(): string | undefined;
71
+ get sessionStartedAt(): number | undefined;
72
+ capture(eventName: string, options?: CaptureOptions): void;
73
+ identify(distinctId: string, options?: IdentifyOptions): void;
74
+ /**
75
+ * Join a browser's anonymous trail to a person from a server. A sign-in that
76
+ * completes in a redirect renders no page, so the browser's own `identify`
77
+ * never runs there; this sends the one `$identify` it would have sent, for
78
+ * the ids given, and leaves this client's own identity as it was.
79
+ */
80
+ link(distinctId: string, anonymousId: string, traits?: PersonTraits): void;
81
+ /**
82
+ * Record the visitor's answer about the join. It rides the shared store, so
83
+ * every subdomain and the login's server read the same one, and it takes
84
+ * effect on the next identify and the next decorated click; nothing already
85
+ * joined is unjoined.
86
+ */
87
+ setConsent(consent: Consent): void;
88
+ /** The visitor's answer, or null when they have not been asked. */
89
+ consent(): Consent | null;
90
+ alias(alias: string): void;
91
+ group(groupType: string, groupKey: string, properties?: EventProperties): void;
92
+ setPersonProperties(set?: EventProperties, setOnce?: EventProperties): void;
93
+ /**
94
+ * Attach the reserved traits to whoever is current, without an identify.
95
+ *
96
+ * This does NOT make the person identified: only `identify()` does that, so a
97
+ * trait set on an anonymous visitor leaves them anonymous and carrying an
98
+ * address, which is exactly what a newsletter signup before login looks like.
99
+ */
100
+ setPersonTraits(traits: PersonTraits): void;
101
+ getAllFlags(): Promise<Record<string, boolean>>;
102
+ isFeatureEnabled(key: string): Promise<boolean>;
103
+ /** The assigned variation for one flag, or null when the flag is unknown or
104
+ * carries no variations. Records the exposure either way. */
105
+ getVariant(key: string): Promise<FlagVariant | null>;
106
+ getVariantLocal(key: string, context?: LocalFlagContext): Promise<FlagVariant | null>;
107
+ private recordExposure;
108
+ getCachedFlag(key: string): boolean | undefined;
109
+ getLocalFlags(context?: LocalFlagContext): Promise<Record<string, boolean>>;
110
+ isFeatureEnabledLocal(key: string, context?: LocalFlagContext): Promise<boolean>;
111
+ /** The evaluation context for a local read. Memberships come from the caller
112
+ * when supplied, else from the server once per distinct id per snapshot
113
+ * TTL, and only when the snapshot names a cohort at all. */
114
+ private localContext;
115
+ private flagSnapshot;
116
+ /** Opens the flag stream once, when streaming was asked for and the snapshot
117
+ * names a gateway. A pushed change drops the cached snapshot and refetches
118
+ * it; a refused handshake stays closed, a dropped one reopens. */
119
+ private maybeStream;
120
+ getInbox(): Promise<InboxMessage[]>;
121
+ markMessageRead(messageId: string): Promise<void>;
122
+ flush(): Promise<void>;
123
+ reset(): void;
124
+ shutdown(): Promise<void>;
125
+ private enqueue;
126
+ private persistQueue;
127
+ private restoreQueue;
128
+ private startTimer;
129
+ private stopTimer;
130
+ private persistKey;
131
+ }
132
+ declare function createClient(config: ProdantixConfig): ProdantixClient;
133
+
134
+ export { type CaptureOptions as C, type IdentifyOptions as I, type LocalFlagContext as L, ProdantixClient as P, createClient as c };
@@ -29,6 +29,11 @@ interface ChatStorage {
29
29
  set(key: string, value: string): void;
30
30
  remove(key: string): void;
31
31
  }
32
+ interface PageContext {
33
+ host: string;
34
+ path: string;
35
+ title: string;
36
+ }
32
37
  declare class ChatClient {
33
38
  private readonly options;
34
39
  private readonly fetchImpl?;
@@ -45,26 +50,51 @@ declare class ChatClient {
45
50
  } | null;
46
51
  identify(identity: ChatIdentity): void;
47
52
  ensureThread(subject?: string): Promise<boolean>;
48
- send(body: string): Promise<ChatTurn | null>;
53
+ send(body: string, pageContext?: PageContext): Promise<ChatTurn | null>;
49
54
  load(): Promise<ChatThread | null>;
50
55
  private readHandle;
51
56
  private request;
52
57
  }
53
58
 
54
59
  type MessengerSkin = 'concierge' | 'console' | 'quiet';
55
- type LauncherStyle = 'avatar_circle' | 'circle_filled' | 'circle_outlined' | 'pill_labelled' | 'pill_team' | 'squircle_filled';
56
60
  type BubbleStyle = 'hairline' | 'outlined' | 'rounded' | 'tailed';
57
- type NamePlacement = 'above' | 'avatar_only' | 'gutter' | 'hidden' | 'inline';
58
- type TimestampStyle = 'cluster' | 'latency' | 'none' | 'trailing' | 'with_name';
61
+ type LauncherShape = 'circle' | 'pill' | 'squircle';
62
+ type LauncherFill = 'filled' | 'outlined';
63
+ type LauncherContent = 'avatar' | 'glyph' | 'team_faces';
64
+ type LauncherSize = 'large' | 'medium' | 'small';
65
+ type NamePlacement = 'above' | 'hidden' | 'inline';
66
+ type StampPlacement = 'beside_name' | 'none' | 'under_turn';
67
+ type StampContent = 'time' | 'time_and_latency';
59
68
  interface AppearanceSettings {
60
69
  bubbleStyle: BubbleStyle;
61
- launcherStyle: LauncherStyle;
70
+ dayDividers: boolean;
71
+ launcherContent: LauncherContent;
72
+ launcherFill: LauncherFill;
73
+ launcherShape: LauncherShape;
74
+ launcherSize: LauncherSize;
75
+ nameAvatar: boolean;
62
76
  namePlacement: NamePlacement;
63
77
  skin: MessengerSkin;
64
- timestampStyle: TimestampStyle;
78
+ stampContent: StampContent;
79
+ stampPlacement: StampPlacement;
65
80
  }
66
81
  declare const DEFAULT_APPEARANCE_SETTINGS: AppearanceSettings;
67
- declare function resolveAppearance(config: Partial<AppearanceSettings> | null | undefined): AppearanceSettings;
82
+ declare function resolveAppearance(config: unknown): AppearanceSettings;
83
+
84
+ type Weekday = 'mon' | 'tue' | 'wed' | 'thu' | 'fri' | 'sat' | 'sun';
85
+ type Availability = {
86
+ timezone: string;
87
+ windows: readonly {
88
+ close: string;
89
+ days: readonly Weekday[];
90
+ open: string;
91
+ }[];
92
+ };
93
+
94
+ interface TeamFace {
95
+ initials: string;
96
+ tone: string;
97
+ }
68
98
 
69
99
  interface MessengerConfig extends AppearanceSettings {
70
100
  enabled: boolean;
@@ -74,9 +104,10 @@ interface MessengerConfig extends AppearanceSettings {
74
104
  accentColor: string;
75
105
  greeting: string;
76
106
  awayMessage: string;
77
- availability: unknown;
107
+ availability: Availability;
78
108
  version: string;
79
109
  starterPrompts: string[];
110
+ teamFaces: TeamFace[];
80
111
  socketUrl: string;
81
112
  }
82
113
  interface MessengerConfigOptions {
@@ -91,4 +122,4 @@ declare const MESSENGER_CACHE_KEY = "prodantix.messenger.config";
91
122
  declare function cachedMessengerConfig(storage: ChatStorage | undefined, apiKey: string): MessengerConfig | null;
92
123
  declare function fetchMessengerConfig(options: MessengerConfigOptions): Promise<MessengerConfig | null>;
93
124
 
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 };
125
+ export { type AppearanceSettings as A, type BubbleStyle as B, ChatClient as C, DEFAULT_APPEARANCE_SETTINGS as D, type LauncherContent as L, type MessengerConfig as M, type NamePlacement as N, type StampContent as S, type ChatTurn as a, type ChatIdentity as b, type ChatClientOptions as c, type ChatStorage as d, type ChatThread as e, type LauncherFill as f, type LauncherShape as g, type LauncherSize as h, type MessengerSkin as i, type StampPlacement as j, MESSENGER_CACHE_KEY as k, type MessengerConfigOptions as l, cachedMessengerConfig as m, fetchMessengerConfig as n, resolveAppearance as r };
@@ -29,6 +29,11 @@ interface ChatStorage {
29
29
  set(key: string, value: string): void;
30
30
  remove(key: string): void;
31
31
  }
32
+ interface PageContext {
33
+ host: string;
34
+ path: string;
35
+ title: string;
36
+ }
32
37
  declare class ChatClient {
33
38
  private readonly options;
34
39
  private readonly fetchImpl?;
@@ -45,26 +50,51 @@ declare class ChatClient {
45
50
  } | null;
46
51
  identify(identity: ChatIdentity): void;
47
52
  ensureThread(subject?: string): Promise<boolean>;
48
- send(body: string): Promise<ChatTurn | null>;
53
+ send(body: string, pageContext?: PageContext): Promise<ChatTurn | null>;
49
54
  load(): Promise<ChatThread | null>;
50
55
  private readHandle;
51
56
  private request;
52
57
  }
53
58
 
54
59
  type MessengerSkin = 'concierge' | 'console' | 'quiet';
55
- type LauncherStyle = 'avatar_circle' | 'circle_filled' | 'circle_outlined' | 'pill_labelled' | 'pill_team' | 'squircle_filled';
56
60
  type BubbleStyle = 'hairline' | 'outlined' | 'rounded' | 'tailed';
57
- type NamePlacement = 'above' | 'avatar_only' | 'gutter' | 'hidden' | 'inline';
58
- type TimestampStyle = 'cluster' | 'latency' | 'none' | 'trailing' | 'with_name';
61
+ type LauncherShape = 'circle' | 'pill' | 'squircle';
62
+ type LauncherFill = 'filled' | 'outlined';
63
+ type LauncherContent = 'avatar' | 'glyph' | 'team_faces';
64
+ type LauncherSize = 'large' | 'medium' | 'small';
65
+ type NamePlacement = 'above' | 'hidden' | 'inline';
66
+ type StampPlacement = 'beside_name' | 'none' | 'under_turn';
67
+ type StampContent = 'time' | 'time_and_latency';
59
68
  interface AppearanceSettings {
60
69
  bubbleStyle: BubbleStyle;
61
- launcherStyle: LauncherStyle;
70
+ dayDividers: boolean;
71
+ launcherContent: LauncherContent;
72
+ launcherFill: LauncherFill;
73
+ launcherShape: LauncherShape;
74
+ launcherSize: LauncherSize;
75
+ nameAvatar: boolean;
62
76
  namePlacement: NamePlacement;
63
77
  skin: MessengerSkin;
64
- timestampStyle: TimestampStyle;
78
+ stampContent: StampContent;
79
+ stampPlacement: StampPlacement;
65
80
  }
66
81
  declare const DEFAULT_APPEARANCE_SETTINGS: AppearanceSettings;
67
- declare function resolveAppearance(config: Partial<AppearanceSettings> | null | undefined): AppearanceSettings;
82
+ declare function resolveAppearance(config: unknown): AppearanceSettings;
83
+
84
+ type Weekday = 'mon' | 'tue' | 'wed' | 'thu' | 'fri' | 'sat' | 'sun';
85
+ type Availability = {
86
+ timezone: string;
87
+ windows: readonly {
88
+ close: string;
89
+ days: readonly Weekday[];
90
+ open: string;
91
+ }[];
92
+ };
93
+
94
+ interface TeamFace {
95
+ initials: string;
96
+ tone: string;
97
+ }
68
98
 
69
99
  interface MessengerConfig extends AppearanceSettings {
70
100
  enabled: boolean;
@@ -74,9 +104,10 @@ interface MessengerConfig extends AppearanceSettings {
74
104
  accentColor: string;
75
105
  greeting: string;
76
106
  awayMessage: string;
77
- availability: unknown;
107
+ availability: Availability;
78
108
  version: string;
79
109
  starterPrompts: string[];
110
+ teamFaces: TeamFace[];
80
111
  socketUrl: string;
81
112
  }
82
113
  interface MessengerConfigOptions {
@@ -91,4 +122,4 @@ declare const MESSENGER_CACHE_KEY = "prodantix.messenger.config";
91
122
  declare function cachedMessengerConfig(storage: ChatStorage | undefined, apiKey: string): MessengerConfig | null;
92
123
  declare function fetchMessengerConfig(options: MessengerConfigOptions): Promise<MessengerConfig | null>;
93
124
 
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 };
125
+ export { type AppearanceSettings as A, type BubbleStyle as B, ChatClient as C, DEFAULT_APPEARANCE_SETTINGS as D, type LauncherContent as L, type MessengerConfig as M, type NamePlacement as N, type StampContent as S, type ChatTurn as a, type ChatIdentity as b, type ChatClientOptions as c, type ChatStorage as d, type ChatThread as e, type LauncherFill as f, type LauncherShape as g, type LauncherSize as h, type MessengerSkin as i, type StampPlacement as j, MESSENGER_CACHE_KEY as k, type MessengerConfigOptions as l, cachedMessengerConfig as m, fetchMessengerConfig as n, resolveAppearance as r };
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
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
1
+ 'use strict';var le=Object.defineProperty;var de=(n,e,t)=>e in n?le(n,e,{enumerable:true,configurable:true,writable:true,value:t}):n[e]=t;var o=(n,e,t)=>de(n,typeof e!="symbol"?e+"":e,t);var d=class extends Error{constructor(t,s,r){super(s,r);o(this,"code");this.code=t,this.name="ProdantixError";}},m=class extends d{constructor(e){super("config",e),this.name="ConfigError";}},h=class extends d{constructor(t,s){super("validation",s);o(this,"field");this.field=t,this.name="ValidationError";}},c=class extends d{constructor(t,s,r){super("transport",t,r);o(this,"status");this.status=s,this.name="TransportError";}};function y(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 j=n=>new Promise(e=>{setTimeout(e,n);});function p(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 G={now:()=>new Date};function I(n){return n.toISOString()}function ue(){return globalThis.crypto}function he(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 pe(){let n=ue();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 he(e)}var J={uuid:pe};var fe=/^pdx_pub_(?:(?:live|test)_)?[a-z0-9]{32}$/;var ge=/^(?:\$|[a-z])[a-z0-9_.]*$/;function U(n){let e=0;for(let t of n)e+=1;return e}function H(n){return fe.test(n)}function me(n){return ge.test(n)}function z(n){let e=U(n);if(e<1||e>200)throw new h("distinct_id","distinct_id must be between 1 and 200 characters")}function B(n){let e=U(n);if(e<1||e>200)throw new h("event_name","event_name must be between 1 and 200 characters");if(!me(n))throw new h("event_name","event_name must match /^(\\$|[a-z])[a-z0-9_.]*$/")}var P="prodantix-js",R="0.0.1";var ye=n=>{};function Q(n){if(!n.apiKey||!H(n.apiKey))throw new m("apiKey must be a public project key of the form pdx_pub_<32 lowercase alphanumerics>");if(!n.host)throw new m("host is required (the ingest base URL)");let e=p(n.host),t=n.defaultProperties,s=n.storage??new v;return {apiKey:n.apiKey,autocapture:n.autocapture??false,clock:n.clock??G,consent:n.consent,defaultProperties:typeof t=="function"?t:()=>t??{},flagsHost:n.flagsHost?p(n.flagsHost):e,flushAt:n.flushAt??20,flushIntervalMs:n.flushIntervalMs??1e4,host:e,ids:n.ids??J,locale:n.locale,maxQueueSize:n.maxQueueSize??1e3,maxRetries:n.maxRetries??3,namespace:ve(n.apiKey),onError:n.onError??ye,os:n.os,requestTimeoutMs:n.requestTimeoutMs??1e4,sdkName:n.sdkName??P,sdkVersion:n.sdkVersion??R,sessionTracking:n.sessionTracking??false,sharedStorage:n.sharedStorage??s,socketFactory:n.socketFactory,storage:s,streamFlags:n.streamFlags??false,transport:n.transport}}function ve(n){return n.slice(0,16)}function W(n,e,t){B(n.eventName),z(n.distinctId);let s={distinct_id:n.distinctId,event_id:n.eventId??t.uuid(),event_name:n.eventName,properties:n.properties??{},schema_version:1,timestamp:I(n.timestamp??e.now())};return n.context&&(s.context=n.context),n.sessionId&&(s.session_id=n.sessionId),s}var g=Symbol("absent");function ke(n,e){if(n==="distinct_id")return e.distinctId;let t=e.properties??{};if(Object.prototype.hasOwnProperty.call(t,n))return t[n];let s=e.attributes??{};return Object.prototype.hasOwnProperty.call(s,n)?s[n]:g}function f(n){return n===g?"undefined":String(n)}function X(n){return n===g?Number.NaN:Number(n)}function Y(n){return n!==g&&n!==null&&n!==""}function Z(n,e){if(!Array.isArray(e))return false;let t=f(n);return e.map(s=>String(s)).includes(t)}function N(n,e){let t=ke(n.attribute,e),s=n.value;switch(n.op){case "is_set":return Y(t);case "is_not_set":return !Y(t);case "eq":return f(t)===f(s===void 0?g:s);case "neq":return f(t)!==f(s===void 0?g:s);case "contains":return f(t).includes(f(s===void 0?g:s));case "in":return Z(t,s);case "not_in":return Array.isArray(s)?!Z(t,s):false;case "gt":return F(t,s,(r,i)=>r>i);case "gte":return F(t,s,(r,i)=>r>=i);case "lt":return F(t,s,(r,i)=>r<i);case "lte":return F(t,s,(r,i)=>r<=i);case "in_cohort":return typeof s=="string"&&s!==""&&(e.cohorts??[]).includes(s);case "not_in_cohort":return typeof s=="string"&&s!==""&&!(e.cohorts??[]).includes(s);default:return false}}function F(n,e,t){let s=X(n),r=e===void 0?Number.NaN:X(e);return Number.isNaN(s)||Number.isNaN(r)?false:t(s,r)}function O(n,e){let t=`${n}:${e}`,s=2166136261;for(let r=0;r<t.length;r++)s^=t.charCodeAt(r),s=Math.imul(s,16777619);return (s>>>0)%100}function M(n,e){return n.targeting.length===0||n.targeting.every(t=>N(t,e))}function ee(n,e){let t=O(n.key,e.distinctId),s=n.variations??[];if(s.length===0)return n.rolloutPercentage>=100||t<n.rolloutPercentage?"true":"false";let r=0;for(let i=s.length-1;i>=0;i--)if(r+=s[i].weight,t<r)return s[i].key;return s[0].key}function $(n,e,t,s){for(let r of n.prerequisites??[]){if(s.includes(r.flagKey))return false;let i=e.find(l=>l.key===r.flagKey);if(!i||!i.enabled)return false;s.push(i.key);let a=$(i,e,t,s)&&M(i,t)&&ee(i,t)===r.variationKey;if(s.pop(),!a)return false}return true}function k(n,e,t){return n.enabled?$(n,e,t,[n.key])?M(n,t)?n.rolloutPercentage>=100?{enabled:true,reason:"rollout_full"}:O(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 be(n,e){return k(n,[],e)}function q(n,e){let t={};for(let s of n)t[s.key]=k(s,n,e).enabled;return t}function b(n,e,t){let s=n.variations??[],r=s[0];if(!r)return null;if(!n.enabled||!$(n,e,t,[n.key])||!M(n,t))return r;let i=ee(n,t);return s.find(a=>a.key===i)??r}function xe(n,e){return b(n,[],e)}function Ee(n,e,t){let s=n.find(r=>r.key===e);return s?b(s,n,t)?.value??null:null}function te(n){return n.some(e=>e.targeting.some(t=>t.op==="in_cohort"||t.op==="not_in_cohort"))}function ne(n){return `40${JSON.stringify(n)}`}function se(){return "3"}function re(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=K(t);return {kind:"open",pingInterval:typeof a?.pingInterval=="number"?a.pingInterval:25e3,pingTimeout:typeof a?.pingTimeout=="number"?a.pingTimeout:2e4}}if(e!=="4")return {kind:"other"};let s=t.charAt(0),r=t.slice(1);if(s==="0")return {kind:"connected"};if(s==="1")return {kind:"disconnect"};if(s==="4"){let a=K(r);return {kind:"connectError",message:typeof a?.message=="string"?a.message:"refused"}}if(s!=="2")return {kind:"other"};let i=K(r);return !Array.isArray(i)||typeof i[0]!="string"?{kind:"other"}:{kind:"event",name:i[0],payload:i[1]}}function K(n){try{return JSON.parse(n)}catch{return null}}var Se="/socket.io/?EIO=4&transport=websocket",Ie=250,C=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??Fe,this.setTimer=e.setTimer??((t,s)=>setTimeout(t,s)),this.clearTimer=e.clearTimer??(t=>clearTimeout(t));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${Se}`,t;try{t=this.factory(e);}catch{this.options.onClosed(false);return}this.socket=t,t.onmessage=s=>this.receive(String(s.data)),t.onerror=()=>t.close(),t.onclose=()=>this.fell();}close(){this.closed=true,this.stopHeartbeat(),this.pending!==null&&this.clearTimer(this.pending),this.pending=null;let e=this.socket;this.socket=null,e?.close();}receive(e){let t=re(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),this.socket?.send(ne({projectKey:this.options.projectKey}));return}if(t.kind==="ping"){this.armHeartbeat(),this.socket?.send(se());return}if(t.kind==="connectError"||t.kind==="disconnect"){this.stopHeartbeat(),this.socket?.close();return}if(t.kind==="event"){if(t.name==="ready"){this.ready=true;return}if(t.name==="flagChange"){let s=t.payload?.key;this.lastKey=typeof s=="string"?s:"",this.pending===null&&(this.pending=this.setTimer(()=>{this.pending=null,this.options.onChange(this.lastKey);},Ie));}}}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 Fe(n){let e=globalThis.WebSocket;if(!e)throw new Error("no WebSocket");return new e(n)}var x=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=y(e.fetch),this.host=p(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async fetchAll(e){return (await this.fetchDecisions(e)).flags}async fetchDecisions(e){let t=this.fetch;if(!t)throw new c("no fetch implementation available in this runtime");let s=`${this.host}/v1/flags?distinct_id=${encodeURIComponent(e)}`,r=u(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let a=await t(s,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!a.ok)throw new c(`flags request failed with status ${a.status}`,a.status);let 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`,s=u(),r=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{let i=await e(t,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:s?.signal});if(!i.ok)throw new c(`flag snapshot request failed with status ${i.status}`,i.status);let a=JSON.parse(await i.text()),l={flags:a.flags??[],generatedAt:a.generatedAt};return typeof a.socketUrl=="string"&&a.socketUrl!==""&&(l.socketUrl=a.socketUrl),l}finally{r!==void 0&&clearTimeout(r);}}async memberships(e){let t=this.fetch;if(!t)throw new c("no fetch implementation available in this runtime");let s=`${this.host}/v1/flags/memberships?distinct_id=${encodeURIComponent(e)}`,r=u(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let a=await t(s,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!a.ok)throw new c(`memberships request failed with status ${a.status}`,a.status);return JSON.parse(await a.text()).cohorts??[]}finally{i!==void 0&&clearTimeout(i);}}};function L(n){if(typeof n!="string")return;let e=Array.from(n).length;return e>=1&&e<=200?n:void 0}function D(n,e){return `pdx.${n}.${e}`}var ie="consent";function Ce(n){if(typeof n!="string")return null;try{let e=JSON.parse(n);if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e.identityLink;return typeof t=="boolean"?{identityLink:t}:null}catch{return null}}function Te(n,e){return Ce(n.getItem(D(e,ie)))}function we(n,e,t){let s=D(e,ie);if(typeof t.identityLink!="boolean"){n.removeItem(s);return}n.setItem(s,JSON.stringify({identityLink:t.identityLink}));}var T=class{constructor(e,t,s,r){this.storage=e;this.shared=t;this.ids=s;this.namespace=r;o(this,"anonymousId");o(this,"distinctId");o(this,"identified");this.refresh();}refresh(){let e=L(this.shared.getItem(this.key("anonymous_id"))),t=L(this.storage.getItem(this.key("anonymous_id")));e?(this.anonymousId=e,t!==e&&this.storage.setItem(this.key("anonymous_id"),e)):t?(this.anonymousId=t,this.shared.setItem(this.key("anonymous_id"),t)):(this.anonymousId=this.ids.uuid(),this.shared.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.setItem(this.key("anonymous_id"),this.anonymousId));let s=L(this.storage.getItem(this.key("distinct_id")));s?(this.distinctId=s,this.identified=true):(this.distinctId=this.anonymousId,this.identified=false);}getAnonymousId(){return this.anonymousId}getDistinctId(){return this.distinctId}isIdentified(){return this.identified}snapshot(){return {anonymousId:this.anonymousId,distinctId:this.distinctId,identified:this.identified}}consent(){return Te(this.shared,this.namespace)}setConsent(e){we(this.shared,this.namespace,e);}identify(e){let t=!this.identified||this.distinctId!==e,s=this.storage.getItem(this.key("linked_anonymous_id")),r=t||s!==this.anonymousId;return this.distinctId=e,this.identified=true,t&&this.storage.setItem(this.key("distinct_id"),e),!r||this.consent()?.identityLink===false?{changed:t}:(this.storage.setItem(this.key("linked_anonymous_id"),this.anonymousId),{anonymousToLink:this.anonymousId,changed:t})}reset(){this.anonymousId=this.ids.uuid(),this.distinctId=this.anonymousId,this.identified=false,this.shared.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.removeItem(this.key("distinct_id")),this.storage.removeItem(this.key("linked_anonymous_id"));}key(e){return D(this.namespace,e)}};var E=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=y(e.fetch),this.host=p(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async inbox(e){let t=this.requireFetch(),s=`${this.host}/v1/messages?distinct_id=${encodeURIComponent(e)}`,r=await this.request(t,s,{headers:this.authHeaders(),method:"GET"});if(!r.ok)throw new c(`inbox request failed with status ${r.status}`,r.status);return JSON.parse(await r.text()).messages??[]}async markRead(e,t){let s=this.requireFetch(),r=`${this.host}/v1/messages/read`,i=await this.request(s,r,{body:JSON.stringify({distinct_id:t,message_id:e}),headers:{...this.authHeaders(),"content-type":"application/json"},method:"POST"});if(!i.ok)throw new c(`mark-read request failed with status ${i.status}`,i.status)}requireFetch(){if(!this.fetch)throw new c("no fetch implementation available in this runtime");return this.fetch}authHeaders(){return {authorization:`Bearer ${this.projectKey}`}}async request(e,t,s){let r=u(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{return await e(t,{...s,signal:r?.signal})}finally{i!==void 0&&clearTimeout(i);}}};var w=class{constructor(e,t){this.maxSize=e;this.onOverflow=t;o(this,"events",[]);}get size(){return this.events.length}enqueue(e){this.events.push(e),this.enforceCap();}restore(e){this.events.push(...e),this.enforceCap();}requeue(e){this.events.unshift(...e),this.enforceCap();}drain(e){let t=e===void 0?this.events.length:Math.min(e,this.events.length);return this.events.splice(0,t)}snapshot(){return [...this.events]}enforceCap(){if(this.events.length<=this.maxSize)return;let e=this.events.splice(0,this.events.length-this.maxSize);this.onOverflow?.({dropped:e});}};var _e={idleMs:18e5,maxMs:864e5,throttleMs:1e4};function Ae(n){return `pdx.${n}.session`}var _=class{constructor(e,t,s,r,i=_e){this.storage=e;this.ids=t;this.clock=s;this.namespace=r;this.options=i;}current(){return this.touch().id}startedAt(){return this.touch().startedAt}reset(){this.storage.removeItem(this.key());}touch(){let e=this.clock.now().getTime(),t=this.live(this.read(),e);if(t===void 0)return this.write({id:this.ids.uuid(),lastActivityAt:e,startedAt:e});if(e-t.lastActivityAt<=this.options.throttleMs)return t;let s=this.live(this.read(),e),r=s!==void 0&&s.id!==t.id?s:t;return this.write({...r,lastActivityAt:e})}live(e,t){if(e!==void 0&&!(t-e.lastActivityAt>this.options.idleMs||t-e.startedAt>this.options.maxMs))return e}write(e){return this.storage.setItem(this.key(),JSON.stringify(e)),e}read(){let e=this.storage.getItem(this.key());if(e)try{let t=JSON.parse(e);return typeof t.id=="string"&&typeof t.startedAt=="number"&&typeof t.lastActivityAt=="number"?{id:t.id,lastActivityAt:t.lastActivityAt,startedAt:t.startedAt}:void 0}catch{return}}key(){return Ae(this.namespace)}};function oe(n){return n>=400&&n<500&&n!==429}var S=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=y(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??j,this.random=e.random??Math.random;}async send(e){let t=this.fetch;if(!t)throw new c("no fetch implementation available in this runtime");let s=JSON.stringify(e.body),r;for(let i=0;i<=this.maxRetries;i+=1){try{let a=await this.attempt(t,e,s);if(a.ok)return;if(oe(a.status))throw new c(`ingest rejected batch with status ${a.status}`,a.status);r=new c(`ingest transient status ${a.status}`,a.status);}catch(a){if(a instanceof c&&a.status!==void 0&&oe(a.status))throw a;r=a;}i<this.maxRetries&&await this.sleep(this.backoff(i));}throw new c("ingest delivery failed after retries",void 0,{cause:r})}async attempt(e,t,s){let r=u(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{return await e(t.url,{body:s,headers:{authorization:`Bearer ${t.projectKey}`,"content-type":"application/json"},method:"POST",signal:r?.signal})}finally{i!==void 0&&clearTimeout(i);}}backoff(e){return Math.min(this.maxDelayMs,this.baseDelayMs*2**e)+this.random()*this.baseDelayMs}};var Pe="queue",Re=1e3,ae=3e4,V=n=>{let e={};return n.avatar!==void 0&&(e.$avatar=n.avatar),n.email!==void 0&&(e.$email=n.email),n.name!==void 0&&(e.$name=n.name),n.phone!==void 0&&(e.$phone=n.phone),e},A=class{constructor(e){o(this,"config");o(this,"identity");o(this,"session");o(this,"queue");o(this,"transport");o(this,"flagsClient");o(this,"messagesClient");o(this,"context");o(this,"flushTimer");o(this,"flushing",false);o(this,"cachedFlags");o(this,"cachedSnapshot");o(this,"membershipCache");o(this,"stream");o(this,"shutDown",false);o(this,"exposures",new Set);this.config=Q(e),this.identity=new T(this.config.storage,this.config.sharedStorage,this.config.ids,this.config.namespace),this.config.consent!==void 0&&this.identity.setConsent(this.config.consent),this.session=this.config.sessionTracking?new _(this.config.sharedStorage,this.config.ids,this.config.clock,this.config.namespace):void 0,this.queue=new w(this.config.maxQueueSize,({dropped:t})=>{this.config.onError(new d("queue_overflow",`event queue overflow: dropped ${t.length} oldest event(s)`));}),this.transport=this.config.transport??new S({maxRetries:this.config.maxRetries,requestTimeoutMs:this.config.requestTimeoutMs}),this.flagsClient=new x({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.messagesClient=new 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()}get isIdentified(){return this.identity.isIdentified()}get sessionId(){return this.session?.current()}get sessionStartedAt(){return this.session?.startedAt()}capture(e,t={}){try{this.identity.refresh();let s={...this.config.defaultProperties(),...t.properties??{}},r=W({context:this.context,distinctId:t.distinctId??this.identity.getDistinctId(),eventName:e,properties:s,sessionId:t.sessionId??this.session?.current(),timestamp:t.timestamp},this.config.clock,this.config.ids);this.enqueue(r);}catch(s){this.config.onError(s);}}identify(e,t={}){this.identity.refresh();let s=this.identity.identify(e),r={};s.anonymousToLink!==void 0&&(r.$anon_distinct_id=s.anonymousToLink);let i={...V(t.traits??{}),...t.set??{}};Object.keys(i).length>0&&(r.$set=i),this.capture("$identify",{properties:r});}link(e,t,s){let r={$anon_distinct_id:t},i=V(s??{});Object.keys(i).length>0&&(r.$set=i),this.capture("$identify",{distinctId:e,properties:r});}setConsent(e){this.identity.setConsent(e);}consent(){return this.identity.consent()}alias(e){this.capture("$create_alias",{properties:{alias:e}});}group(e,t,s){let r={$group_key:t,$group_type:e};s&&(r.$set=s),this.capture("$group",{properties:r});}setPersonProperties(e,t){let s={};e&&(s.$set=e),t&&(s.$set_once=t),this.capture("$set",{properties:s});}setPersonTraits(e){let t=V(e);Object.keys(t).length!==0&&this.capture("$set",{properties:{$set:t}});}async getAllFlags(){let e=this.identity.getDistinctId(),t=await this.flagsClient.fetchDecisions(e);return this.cachedFlags={distinctId:e,flags:t.flags,variants:t.variants??{}},t.flags}async isFeatureEnabled(e){let s=(await this.getAllFlags())[e]??false;return this.recordExposure(e,this.cachedFlags?.variants[e]?.key??String(s)),s}async getVariant(e){let t=await this.getAllFlags(),s=this.cachedFlags?.variants[e]??null;return this.recordExposure(e,s?.key??String(t[e]??false)),s}async getVariantLocal(e,t={}){let s=await this.flagSnapshot(),r=s.flags.find(ce=>ce.key===e),i=await this.localContext(t,s.flags),a=r?b(r,s.flags,i):null,l=r?k(r,s.flags,i).enabled:false;return this.recordExposure(e,a?.key??String(l)),a?{key:a.key,value:a.value}:null}recordExposure(e,t){let s=`${this.identity.getDistinctId()} ${e} ${t}`;this.exposures.has(s)||(this.exposures.add(s),this.capture("$feature_flag_called",{properties:{$feature_flag:e,$feature_flag_response:t}}));}getCachedFlag(e){if(!(!this.cachedFlags||this.cachedFlags.distinctId!==this.distinctId))return this.cachedFlags.flags[e]}async getLocalFlags(e={}){let t=await this.flagSnapshot();return q(t.flags,await this.localContext(e,t.flags))}async isFeatureEnabledLocal(e,t={}){let s=await this.flagSnapshot(),r=s.flags.find(l=>l.key===e),i=await this.localContext(t,s.flags),a=r?k(r,s.flags,i).enabled:false;return this.recordExposure(e,(r?b(r,s.flags,i)?.key:void 0)??String(a)),a}async localContext(e,t){let s=this.identity.getDistinctId(),r=e.cohorts;if(r===void 0&&te(t)){let i=this.config.clock.now().getTime();this.membershipCache&&this.membershipCache.distinctId===s&&i-this.membershipCache.fetchedAt<ae?r=this.membershipCache.cohorts:(r=await this.flagsClient.memberships(s),this.membershipCache={cohorts:r,distinctId:s,fetchedAt:i});}return {attributes:e.attributes,cohorts:r,distinctId:s,properties:e.properties}}async flagSnapshot(){let e=this.config.clock.now().getTime();if(this.cachedSnapshot&&e-this.cachedSnapshot.fetchedAt<ae)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 C({host:e.socketUrl,onChange:()=>{this.cachedSnapshot=void 0,this.flagSnapshot().catch(s=>this.config.onError(s));},onClosed:s=>{this.stream=void 0,s&&this.maybeStream(e);},projectKey:this.config.apiKey,socketFactory:this.config.socketFactory});this.stream=t,t.open();}async getInbox(){return this.messagesClient.inbox(this.identity.getDistinctId())}async markMessageRead(e){await this.messagesClient.markRead(e,this.identity.getDistinctId());}async flush(){if(this.flushing||this.queue.size===0)return;this.flushing=true;let e=this.queue.drain(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(t){this.queue.requeue(e),this.persistQueue(),this.config.onError(t);}finally{this.flushing=false;}}reset(){this.session?.reset(),this.identity.reset(),this.cachedFlags=void 0,this.cachedSnapshot=void 0,this.membershipCache=void 0;}async shutdown(){this.shutDown=true,this.stopTimer(),this.stream?.close(),this.stream=void 0,await this.flush();}enqueue(e){this.queue.enqueue(e),this.persistQueue(),this.queue.size>=this.config.flushAt&&this.flush();}persistQueue(){try{this.config.storage.setItem(this.persistKey(),JSON.stringify(this.queue.snapshot()));}catch(e){this.config.onError(e);}}restoreQueue(){try{let e=this.config.storage.getItem(this.persistKey());if(!e)return;let t=JSON.parse(e);Array.isArray(t)&&this.queue.restore(t);}catch(e){this.config.onError(e);}}startTimer(){if(this.config.flushIntervalMs<=0)return;let e=setInterval(()=>{this.flush();},this.config.flushIntervalMs),t=e;typeof t.unref=="function"&&t.unref(),this.flushTimer=e;}stopTimer(){this.flushTimer!==void 0&&(clearInterval(this.flushTimer),this.flushTimer=void 0);}persistKey(){return `pdx.${this.config.namespace}.${Pe}`}};function Ne(n){return new A(n)}exports.ConfigError=m;exports.FetchTransport=S;exports.FlagsClient=x;exports.MemoryStorage=v;exports.MessagesClient=E;exports.ProdantixClient=A;exports.ProdantixError=d;exports.SDK_NAME=P;exports.SDK_VERSION=R;exports.TransportError=c;exports.ValidationError=h;exports.assignVariant=xe;exports.bucket=O;exports.createClient=Ne;exports.evaluateAll=q;exports.evaluateFlag=be;exports.getVariant=Ee;exports.matches=N;//# sourceMappingURL=index.cjs.map
2
2
  //# sourceMappingURL=index.cjs.map
package/dist/index.d.cts CHANGED
@@ -1,7 +1,8 @@
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';
1
+ export { C as CaptureOptions, I as IdentifyOptions, L as LocalFlagContext, P as ProdantixClient, c as createClient } from './client-BO7f6q5k.cjs';
2
+ import { J as JsonValue, F as FlagsResponse, I as InboxMessage, a as StorageAdapter } from './types-DjMXp6Wg.cjs';
3
+ export { C as Clock, b as Consent, E as EventBatch, c as EventContext, d as EventEnvelope, e as EventProperties, f as FlagVariant, g as IdFactory, h as InboxResponse, P as ProdantixConfig, T as Transport, i as TransportRequest } from './types-DjMXp6Wg.cjs';
3
4
  import { F as FetchLike } from './http-BCh716Vs.cjs';
4
- export { F as FetchTransport } from './transport-DhhzvwpV.cjs';
5
+ export { F as FetchTransport } from './transport-Cy42FY5A.cjs';
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,6 +29,7 @@ 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
  }
@@ -38,11 +40,16 @@ interface FlagVariation {
38
40
  value: unknown;
39
41
  weight: number;
40
42
  }
43
+ interface FlagPrerequisite {
44
+ flagKey: string;
45
+ variationKey: string;
46
+ }
41
47
  interface FlagRule {
42
48
  description?: string;
43
49
  enabled: boolean;
44
50
  intent?: string;
45
51
  key: string;
52
+ prerequisites?: FlagPrerequisite[];
46
53
  rolloutPercentage: number;
47
54
  targeting: FlagCondition[];
48
55
  type?: string;
@@ -51,6 +58,7 @@ interface FlagRule {
51
58
  interface FlagSnapshot {
52
59
  flags: FlagRule[];
53
60
  generatedAt: string;
61
+ socketUrl?: string;
54
62
  }
55
63
  interface FlagDecision {
56
64
  enabled: boolean;
@@ -75,7 +83,11 @@ declare class FlagsClient {
75
83
  private readonly requestTimeoutMs;
76
84
  constructor(options: FlagsClientOptions);
77
85
  fetchAll(distinctId: string): Promise<Record<string, boolean>>;
86
+ fetchDecisions(distinctId: string): Promise<FlagsResponse>;
78
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[]>;
79
91
  }
80
92
 
81
93
  interface MessagesClientOptions {
@@ -107,4 +119,4 @@ declare class MemoryStorage implements StorageAdapter {
107
119
  declare const SDK_NAME = "prodantix-js";
108
120
  declare const SDK_VERSION = "0.0.1";
109
121
 
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 };
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 };