flagmint-js-sdk 2.0.0 → 2.2.1

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,60 @@
1
+ import type { ConfigSyncPayload, DeltaConfigPayload, DeltasCatchUpPayload, FullConfigPayload, LeasePayload, RulesCacheSnapshot, SdkFlagConfig, SdkSegment } from './types';
2
+ export type RulesState = {
3
+ version: number;
4
+ expiresAt: number;
5
+ flags: Map<string, SdkFlagConfig>;
6
+ segments: Map<string, SdkSegment>;
7
+ /** false when lease expired offline — fail closed (defaults only). */
8
+ ready: boolean;
9
+ /** Set when a delta's fromVersion does not match — reconnect with fullConfig. */
10
+ needsFullConfig: boolean;
11
+ };
12
+ export type ApplyResult = {
13
+ ok: true;
14
+ state: RulesState;
15
+ } | {
16
+ ok: false;
17
+ reason: 'bad_signature' | 'version_gap' | 'stale' | 'expired' | 'invalid_payload';
18
+ state: RulesState;
19
+ };
20
+ export declare function createEmptyRulesState(): RulesState;
21
+ /**
22
+ * Pure reducer for config-sync actions (signatures already verified).
23
+ */
24
+ export declare function reduceRules(state: RulesState, action: ConfigSyncPayload, now?: number): ApplyResult;
25
+ /**
26
+ * In-memory rules store: verify MAC → reduce → optional localCache snapshot.
27
+ */
28
+ export declare class RulesStore {
29
+ private state;
30
+ private macKey;
31
+ constructor(macKey?: Uint8Array | null, initial?: RulesState);
32
+ setMacKey(macKey: Uint8Array | null): void;
33
+ getMacKey(): Uint8Array | null;
34
+ getState(): RulesState;
35
+ /**
36
+ * Fail-closed readiness: lease not expired and store marked ready.
37
+ */
38
+ isReady(now?: number): boolean;
39
+ /**
40
+ * Mark the store fail-closed after wall-clock lease expiry.
41
+ * Next reconnect must request fullConfig (or a fresh lease + catch-up).
42
+ */
43
+ markExpired(): void;
44
+ getFlag(key: string): SdkFlagConfig | undefined;
45
+ /**
46
+ * Fail-closed default for a flag key (last-known `default_value` only).
47
+ */
48
+ getFailClosedDefault(key: string): unknown;
49
+ wantsFullConfig(now?: number): boolean;
50
+ sinceVersion(now?: number): number | undefined;
51
+ /**
52
+ * Verify signature with the session MAC key, then apply the reducer.
53
+ */
54
+ applySigned(payload: ConfigSyncPayload, now?: number): ApplyResult;
55
+ /** Apply without MAC (unit tests / already-verified payloads). */
56
+ applyTrusted(payload: ConfigSyncPayload, now?: number): ApplyResult;
57
+ toSnapshot(): RulesCacheSnapshot;
58
+ hydrateFromSnapshot(snapshot: RulesCacheSnapshot, now?: number): void;
59
+ }
60
+ export type { LeasePayload, FullConfigPayload, DeltaConfigPayload, DeltasCatchUpPayload };
@@ -0,0 +1,17 @@
1
+ import type { SignableConfigBody } from './types';
2
+ /**
3
+ * Stable JSON for HMAC: sort object keys recursively so field order cannot
4
+ * invalidate signatures across language runtimes.
5
+ * Must match FF-EU `canonicalizeForSigning`.
6
+ */
7
+ export declare function canonicalizeForSigning(value: unknown): string;
8
+ /**
9
+ * HMAC-SHA256 hex digest over the payload with `signature` omitted.
10
+ */
11
+ export declare function signConfigPayload(body: SignableConfigBody, secret: Uint8Array | string): string;
12
+ /**
13
+ * Verify HMAC-SHA256 hex `signature` on a config-sync payload.
14
+ * Prefer the ASL ECDH-derived session MAC key.
15
+ */
16
+ export declare function verifyConfigPayloadSignature(body: SignableConfigBody, secret: Uint8Array | string): boolean;
17
+ export declare function isConfigPayloadExpired(expiresAt: number, now?: number): boolean;
@@ -0,0 +1,7 @@
1
+ /**
2
+ * djb2 variant matching npm `string-hash` (and Go `evaluate.StringHash`).
3
+ * Iterates right-to-left with XOR — required for rollout bucket parity.
4
+ */
5
+ export declare function stringHash(input: string): number;
6
+ /** Stable bucket in [0, 99] for percentage / variant rollouts. */
7
+ export declare function hashPercent(input: string): number;
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Wire types for SSE config-sync (aligned with FF-EU `modules/evaluator/config-sync.ts`).
3
+ */
4
+ export type SdkFlagConfig = {
5
+ key: string;
6
+ type: 'boolean' | 'string' | 'number' | 'json';
7
+ is_active: boolean;
8
+ default_value: unknown;
9
+ off_variation_id?: string | null;
10
+ targeting_rules: unknown[];
11
+ variations: Array<{
12
+ id: string;
13
+ value: unknown;
14
+ key?: string;
15
+ name?: string;
16
+ }>;
17
+ rollouts: Record<string, unknown>;
18
+ analytics_enabled: boolean;
19
+ };
20
+ export type SdkSegment = {
21
+ id: string;
22
+ rules: unknown[];
23
+ logical_op?: string;
24
+ force?: boolean;
25
+ };
26
+ export type SignableConfigBody = Record<string, unknown> & {
27
+ signature?: string;
28
+ };
29
+ export type LeasePayload = {
30
+ type: 'lease';
31
+ version: number;
32
+ serverNow: number;
33
+ expiresAt: number;
34
+ signature: string;
35
+ };
36
+ export type FullConfigPayload = {
37
+ type: 'fullConfig';
38
+ version: number;
39
+ compiledAt: number;
40
+ expiresAt: number;
41
+ flags: SdkFlagConfig[];
42
+ segments: Record<string, SdkSegment>;
43
+ warnings?: string[];
44
+ signature: string;
45
+ };
46
+ export type DeltaConfigPayload = {
47
+ type: 'delta';
48
+ fromVersion: number;
49
+ toVersion: number;
50
+ compiledAt: number;
51
+ expiresAt: number;
52
+ upserts: SdkFlagConfig[];
53
+ deletes: string[];
54
+ segments: Record<string, SdkSegment>;
55
+ signature: string;
56
+ };
57
+ export type DeltasCatchUpPayload = {
58
+ type: 'deltas';
59
+ fromVersion: number;
60
+ toVersion: number;
61
+ expiresAt: number;
62
+ items: DeltaConfigPayload[];
63
+ signature: string;
64
+ };
65
+ export type ConfigSyncPayload = LeasePayload | FullConfigPayload | DeltaConfigPayload | DeltasCatchUpPayload;
66
+ /** Persisted cache for reconnect (`fullConfig` vs `sinceVersion`). */
67
+ export type RulesCacheSnapshot = {
68
+ version: number;
69
+ expiresAt: number;
70
+ flags: SdkFlagConfig[];
71
+ segments: Record<string, SdkSegment>;
72
+ };
@@ -1,16 +1,27 @@
1
1
  export declare const MAX_EVENT_BATCH = 20;
2
2
  export declare const EVENT_FLUSH_MS = 2000;
3
- export type ApplicationEventKind = 'error' | 'custom';
3
+ /** Debounce window for coalescing getFlag call-site evaluation reports. */
4
+ export declare const EVAL_REPORT_FLUSH_MS = 2000;
5
+ export type ApplicationEventKind = 'error' | 'custom' | 'evaluation';
4
6
  export interface ApplicationEvent {
5
7
  flagKey: string;
6
8
  kind: ApplicationEventKind;
7
9
  eventName?: string;
8
10
  variationValue?: unknown;
9
11
  userKey?: string;
12
+ /** Coalesced getFlag hits (evaluation kind only). */
13
+ count?: number;
10
14
  timestamp: string;
11
15
  extra?: Record<string, unknown>;
12
16
  }
13
17
  export declare function eventsUrlFromRestEndpoint(restEndpoint: string): string;
18
+ /**
19
+ * API base for `POST …/context` (and similar) from the REST evaluate URL.
20
+ * Stream hosts may be SSE-only (`STREAM_HOSTS`); context must stay on the API host.
21
+ *
22
+ * `https://api…/evaluator/evaluate` → `https://api…/evaluator/v2/flags`
23
+ */
24
+ export declare function flagsBaseFromRestEndpoint(restEndpoint: string): string;
14
25
  export declare function userKeyFromContext(context: Record<string, unknown> | undefined): string | undefined;
15
26
  export declare function extraFromError(error: unknown, extra?: Record<string, unknown>): Record<string, unknown> | undefined;
16
27
  /**
@@ -1,4 +1,5 @@
1
1
  import { FeatureFlags } from '../../core/helpers/types';
2
+ import type { RulesCacheSnapshot } from '../../core/config-sync/types';
2
3
  export interface AsyncStorageAdapter {
3
4
  getItem(key: string): Promise<string | null>;
4
5
  setItem(key: string, value: string): Promise<void>;
@@ -9,3 +10,6 @@ export declare function loadCachedFlags<T>(apiKey: string, ttl: number): Promise
9
10
  export declare function saveCachedFlags<T>(apiKey: string, data: FeatureFlags<T>): Promise<void>;
10
11
  export declare function loadCachedContext<C>(apiKey: string): Promise<C | null>;
11
12
  export declare function saveCachedContext<C>(apiKey: string, context: C): Promise<void>;
13
+ export declare function loadCachedRulesSnapshot(apiKey: string): Promise<RulesCacheSnapshot | null>;
14
+ export declare function saveCachedRulesSnapshot(apiKey: string, snapshot: RulesCacheSnapshot): Promise<void>;
15
+ export declare function clearCachedRulesSnapshot(apiKey: string): Promise<void>;
@@ -1,4 +1,5 @@
1
1
  import { FeatureFlags } from '../../core/helpers/types';
2
+ import type { RulesCacheSnapshot } from '../../core/config-sync/types';
2
3
  export interface StorageAdapter {
3
4
  getItem(key: string): string | null;
4
5
  setItem(key: string, value: string): void;
@@ -9,3 +10,7 @@ export declare function loadCachedFlags<T>(apiKey: string, ttl: number): Feature
9
10
  export declare function saveCachedFlags<T>(apiKey: string, data: FeatureFlags<T>): void;
10
11
  export declare function loadCachedContext<C>(apiKey: string): C | null;
11
12
  export declare function saveCachedContext<C>(apiKey: string, context: C): void;
13
+ /** Config-sync rules localCache — no wall-clock TTL; lease `expiresAt` gates reuse. */
14
+ export declare function loadCachedRulesSnapshot(apiKey: string): RulesCacheSnapshot | null;
15
+ export declare function saveCachedRulesSnapshot(apiKey: string, snapshot: RulesCacheSnapshot): void;
16
+ export declare function clearCachedRulesSnapshot(apiKey: string): void;
@@ -100,6 +100,7 @@ export declare class ConnectionShareHub<C = Record<string, unknown>, T = unknown
100
100
  private closed;
101
101
  private latestFlags;
102
102
  private flagsWaiters;
103
+ private flagsTimeouts;
103
104
  private contextWaiters;
104
105
  private onPromoteCallback?;
105
106
  private leaderContextHandler?;
@@ -167,6 +168,12 @@ export declare class ConnectionShareHub<C = Record<string, unknown>, T = unknown
167
168
  destroy(): void;
168
169
  private bindUnloadListener;
169
170
  private unbindUnloadListener;
171
+ /**
172
+ * JSON-clone then post. Native `BroadcastChannel` structured-clones the
173
+ * payload; Vue reactive Proxies and similar host objects throw
174
+ * `DataCloneError`. JSON.stringify can walk those Proxies.
175
+ */
176
+ private post;
170
177
  /** Open the BroadcastChannel for this API key, or a test factory channel. */
171
178
  private openChannel;
172
179
  /** Mark this member leader and start lock heartbeat + `alive` pings. */
@@ -0,0 +1,2 @@
1
+ export declare const ERR_CONTEXT_NOT_CLONEABLE = "ERR_CONTEXT_NOT_CLONEABLE";
2
+ export declare function toJsonCloneable<T>(value: T): T;
@@ -1,7 +1,14 @@
1
+ import type { RulesCacheSnapshot } from '../../core/config-sync/types';
1
2
  export type FeatureFlags<T = unknown> = Record<string, T>;
2
3
  export interface CacheAdapter<C extends Record<string, any> = any> {
3
4
  loadFlags(apiKey: string, ttl: number): Promise<FeatureFlags> | FeatureFlags | null;
4
5
  saveFlags(apiKey: string, data: FeatureFlags): Promise<void> | void;
5
6
  loadContext(apiKey: string): Promise<C | null> | C | null;
6
7
  saveContext(apiKey: string, ctx: C): Promise<void> | void;
8
+ /**
9
+ * Config-sync localCache (optional). When omitted, rules are not persisted
10
+ * across reloads — every boot is a cold start (`fullConfig=true`).
11
+ */
12
+ loadRulesSnapshot?(apiKey: string): Promise<RulesCacheSnapshot | null> | RulesCacheSnapshot | null;
13
+ saveRulesSnapshot?(apiKey: string, snapshot: RulesCacheSnapshot): Promise<void> | void;
7
14
  }
@@ -27,6 +27,7 @@ export declare class LongPollingTransport<C, T> implements Transport<C, T> {
27
27
  fetchFlags(context: C, options?: {
28
28
  persist?: boolean;
29
29
  }): Promise<Record<string, T>>;
30
+ private readQuotaPayload;
30
31
  onFlagsUpdated(callback: (flags: Record<string, T>) => void): void;
31
32
  onAnalyticsUpdated(callback: (analytics: Record<string, boolean>) => void): void;
32
33
  destroy(): void;
@@ -1,5 +1,5 @@
1
1
  import type { Transport } from './Transport';
2
- export interface SseTransportConfig {
2
+ export interface SseTransportConfig<C = unknown, T = unknown> {
3
3
  endpoint: string;
4
4
  apiKey: string;
5
5
  context: any;
@@ -8,6 +8,37 @@ export interface SseTransportConfig {
8
8
  version: string;
9
9
  };
10
10
  EventSourceImpl?: any;
11
+ /**
12
+ * When true, stream uses config-sync (`fullConfig` / `sinceVersion`) and
13
+ * listens for lease / fullConfig / delta / deltas instead of evaluated `flags`.
14
+ */
15
+ configSync?: boolean;
16
+ /** Build config-mode query params for each connect/reconnect. */
17
+ getConfigSyncParams?: () => {
18
+ wantFullConfig: boolean;
19
+ sinceVersion?: number;
20
+ };
21
+ /**
22
+ * Apply a signed config-sync payload (verify + reduce). Return whether the
23
+ * rules store is ready enough to publish evaluated flags.
24
+ */
25
+ onConfigSyncEvent?: (eventName: 'lease' | 'fullConfig' | 'delta' | 'deltas', payload: Record<string, unknown>) => {
26
+ publish: boolean;
27
+ };
28
+ /** Evaluate current rules store against the given (or last) context. */
29
+ getEvaluatedFlags?: (context: C) => Record<string, T>;
30
+ /** Analytics map from the rules store (flag key → analytics_enabled). */
31
+ getAnalyticsMap?: () => Record<string, boolean>;
32
+ /**
33
+ * When true (config sync), POST /context is fire-and-forget telemetry —
34
+ * flags are re-evaluated locally and returned immediately.
35
+ */
36
+ contextAsTelemetry?: boolean;
37
+ /**
38
+ * API base for `POST …/context` (defaults to `endpoint`). Use the API host
39
+ * when `endpoint` is a stream-only hostname.
40
+ */
41
+ contextEndpoint?: string;
11
42
  }
12
43
  /**
13
44
  * A Server-Sent Events (SSE) transport implementation responsible for
@@ -17,8 +48,9 @@ export interface SseTransportConfig {
17
48
  * Stream: `GET {endpoint}/stream?sessionId&context&sdkVersion&platform&wrapper*`
18
49
  * emits `connected` then `flags`. Heartbeats are SSE comments (`: heartbeat`)
19
50
  * and are not visible to EventSource — they only keep the TCP connection alive.
20
- * Context: `POST {endpoint}/context` with `x-api-key` returns 202 and the
51
+ * Context: `POST {contextEndpoint|endpoint}/context` with `x-api-key` returns 202 and the
21
52
  * re-evaluated flags arrive on the existing stream after a 400ms debounce.
53
+ * Prefer the API host when `endpoint` is stream-only (`STREAM_HOSTS`).
22
54
  *
23
55
  * @template C The shape of the evaluation context sent to the Flagmint server.
24
56
  * @template T The feature flag value type returned by the platform.
@@ -33,6 +65,7 @@ export declare class SseTransport<C, T> implements Transport<C, T> {
33
65
  private eventSource;
34
66
  private flags;
35
67
  private context;
68
+ private lastSentContext;
36
69
  private connectionId;
37
70
  private onFlagsUpdatedCallback?;
38
71
  private onAnalyticsUpdatedCallback?;
@@ -46,13 +79,20 @@ export declare class SseTransport<C, T> implements Transport<C, T> {
46
79
  private connectReject;
47
80
  private connectionListener?;
48
81
  private flagsListener?;
82
+ private leaseListener?;
83
+ private fullConfigListener?;
84
+ private deltaListener?;
85
+ private deltasListener?;
49
86
  private quotaListener?;
50
87
  private errorListener?;
51
88
  private reconnectTimeoutId;
52
89
  private reconnectAttempts;
53
90
  private terminalClose;
54
91
  private contextUpdateQueue;
55
- constructor(endpoint: string, sessionId: string, initialContext: C, refreshTokenCallback?: (() => Promise<string>) | undefined, configOptions?: Partial<SseTransportConfig> | undefined);
92
+ /** Wall time when the current SSE `connected` event was received (debug lifecycle). */
93
+ private connectedAtMs;
94
+ constructor(endpoint: string, sessionId: string, initialContext: C, refreshTokenCallback?: (() => Promise<string>) | undefined, configOptions?: Partial<SseTransportConfig<C, T>> | undefined);
95
+ private get configSyncEnabled();
56
96
  init(): Promise<void>;
57
97
  /**
58
98
  * POST /v2/flags/context. FF-EU always returns 202 and pushes the next
@@ -66,10 +106,28 @@ export declare class SseTransport<C, T> implements Transport<C, T> {
66
106
  onAnalyticsUpdated(callback: (analytics: Record<string, boolean>) => void): void;
67
107
  onError(callback: (error: Error) => void): void;
68
108
  destroy(): void;
109
+ /**
110
+ * Drop the live stream and reconnect (fresh ASL ticket).
111
+ * Used when the config-sync lease expires so the next open can request fullConfig.
112
+ *
113
+ * @param reason Lifecycle reason for debug logs
114
+ */
115
+ requestReconnect(reason?: string): void;
116
+ /**
117
+ * Opt-in SSE lifecycle lines (`FlagClient` `debugLog: true`).
118
+ * Example: `[SseTransport] disconnected connectionId=… upMs=900012 reason=network_error retryInMs=1500`
119
+ */
120
+ private logLifecycle;
121
+ private logLifecycleConnected;
122
+ private logLifecycleDisconnected;
69
123
  private get apiKey();
124
+ /** Host for POST /context — API when stream host is SSE-only. */
125
+ private get contextBase();
70
126
  private applyFlags;
71
127
  private emitError;
72
128
  private performContextUpdate;
129
+ /** Fire-and-forget observed-context telemetry for config-sync mode. */
130
+ private postContextTelemetry;
73
131
  private safeReadJson;
74
132
  private quotaExtra;
75
133
  private handleQuotaPayload;
@@ -79,6 +137,7 @@ export declare class SseTransport<C, T> implements Transport<C, T> {
79
137
  private scheduleActiveReconnection;
80
138
  private createConnectionListener;
81
139
  private createFlagsListener;
140
+ private createConfigSyncListener;
82
141
  private createQuotaListener;
83
142
  /**
84
143
  * Named `error` events from FF-EU (`event: error`) after the stream is hijacked.
@@ -4,6 +4,8 @@ export interface Transport<C, T> {
4
4
  persist?: boolean;
5
5
  }): Promise<Record<string, T>>;
6
6
  destroy(): void;
7
+ /** Optional: drop + reconnect (SSE). Used for config-sync lease renewal. */
8
+ requestReconnect?(reason?: string): void;
7
9
  onFlagsUpdated?: (callback: (flags: Record<string, T>) => void) => void;
8
10
  onAnalyticsUpdated?: (callback: (analytics: Record<string, boolean>) => void) => void;
9
11
  onContextUpdated?: (callback: (context: C) => void) => void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "flagmint-js-sdk",
3
- "version": "2.0.0",
3
+ "version": "2.2.1",
4
4
  "description": "Framework-agnostic JavaScript SDK for managing feature flags in Flagmint applications.",
5
5
  "author": "Flagmint Team",
6
6
  "license": "BSD 3-Clause",