@nexussdk/flags 0.0.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,26 @@
1
+
2
+ > @nexussdk/flags@0.0.1 build /home/runner/work/NexusSDK/NexusSDK/packages/sdk-flags
3
+ > tsup
4
+
5
+ CLI Building entry: src/index.ts
6
+ CLI Using tsconfig: tsconfig.json
7
+ CLI tsup v8.5.1
8
+ CLI Using tsup config: /home/runner/work/NexusSDK/NexusSDK/packages/sdk-flags/tsup.config.ts
9
+ CLI Target: es2022
10
+ CLI Cleaning output folder
11
+ ESM Build start
12
+ CJS Build start
13
+ IIFE Build start
14
+ IIFE dist/index.global.js 10.14 KB
15
+ IIFE dist/index.global.js.map 56.35 KB
16
+ IIFE ⚡️ Build success in 543ms
17
+ ESM dist/index.mjs 7.85 KB
18
+ ESM dist/index.mjs.map 40.53 KB
19
+ ESM ⚡️ Build success in 543ms
20
+ CJS dist/index.cjs 7.85 KB
21
+ CJS dist/index.cjs.map 40.54 KB
22
+ CJS ⚡️ Build success in 543ms
23
+ DTS Build start
24
+ DTS ⚡️ Build success in 1501ms
25
+ DTS dist/index.d.mts 11.63 KB
26
+ DTS dist/index.d.ts 11.63 KB
package/dist/index.cjs ADDED
@@ -0,0 +1,2 @@
1
+ 'use strict';var core=require('@nexussdk/core');function p(r,e=0){let t=e>>>0,s=3432918353,n=461845907,a=0,f=Math.floor(r.length/4)*4;for(;a<f;){let o=r.charCodeAt(a)&255|(r.charCodeAt(a+1)&255)<<8|(r.charCodeAt(a+2)&255)<<16|(r.charCodeAt(a+3)&255)<<24;o=Math.imul(o,s),o=o<<15|o>>>17,o=Math.imul(o,n),t^=o,t=t<<13|t>>>19,t=Math.imul(t,5)+3864292196>>>0,a+=4;}let i=0,h=r.length&3;return h>=3&&(i^=(r.charCodeAt(a+2)&255)<<16),h>=2&&(i^=(r.charCodeAt(a+1)&255)<<8),h>=1&&(i^=r.charCodeAt(a)&255,i=Math.imul(i,s),i=i<<15|i>>>17,i=Math.imul(i,n),t^=i),t^=r.length,t^=t>>>16,t=Math.imul(t,2246822507),t^=t>>>13,t=Math.imul(t,3266489909),t^=t>>>16,t>>>0}function v(r,e){let t=`${r}:${e}`;return p(t)%100}function g(r,e){let t=r.replace(/^v/,"").split(".").map(Number),s=e.replace(/^v/,"").split(".").map(Number);for(let n=0;n<3;n++){let a=(t[n]??0)-(s[n]??0);if(a!==0)return a}return 0}function y(r,e){let t=e.split("."),s=r;for(let n of t){if(s==null||typeof s!="object")return;s=s[n];}return s}function b(r,e){let t=y(e,r.attribute),s=r.values;switch(r.operator){case "EQUALS":return t===s[0];case "NOT_EQUALS":return t!==s[0];case "IN":return s.includes(t);case "NOT_IN":return !s.includes(t);case "CONTAINS":return typeof t=="string"&&t.includes(String(s[0]));case "NOT_CONTAINS":return typeof t=="string"&&!t.includes(String(s[0]));case "STARTS_WITH":return typeof t=="string"&&t.startsWith(String(s[0]));case "ENDS_WITH":return typeof t=="string"&&t.endsWith(String(s[0]));case "GREATER_THAN":return typeof t=="number"&&t>Number(s[0]);case "LESS_THAN":return typeof t=="number"&&t<Number(s[0]);case "SEMVER_GTE":return typeof t=="string"&&typeof s[0]=="string"&&g(t,String(s[0]))>=0;case "SEMVER_LTE":return typeof t=="string"&&typeof s[0]=="string"&&g(t,String(s[0]))<=0;default:return false}}function u(r,e){if(!r.isEnabled)return {key:r.key,enabled:false,variants:{},reason:"KILL_SWITCH",version:r.version};if(r.targetingRules.length>0){if(!r.targetingRules.every(s=>b(s,e)))return {key:r.key,enabled:false,variants:{},reason:"FALLBACK",version:r.version};if(r.rolloutPercentage>=100)return {key:r.key,enabled:true,variants:r.variants,reason:"TARGETING_MATCH",version:r.version}}if(r.rolloutPercentage>0){let t=e.id??"anon";return v(t,r.key)<r.rolloutPercentage?{key:r.key,enabled:true,variants:r.variants,reason:r.targetingRules.length>0?"TARGETING_MATCH":"ROLLOUT_MATCH",version:r.version}:{key:r.key,enabled:false,variants:{},reason:"FALLBACK",version:r.version}}return {key:r.key,enabled:false,variants:{},reason:"KILL_SWITCH",version:r.version}}var l=class{options;eventSource=null;connected=false;destroyed=false;reconnectAttempt=0;reconnectTimer=null;maxReconnects;constructor(e){this.options=e,this.maxReconnects=e.maxReconnects??1/0;}get isConnected(){return this.connected}connect(){this.destroyed||this.connected||this.eventSource||this.openConnection();}disconnect(){this.destroyed=true,this.cleanup();}openConnection(){if(!this.destroyed)try{let e=new URL(this.options.url);e.searchParams.set("apiKey",this.options.apiKey),this.eventSource=new EventSource(e.toString()),this.eventSource.addEventListener("open",()=>{this.connected=!0,this.reconnectAttempt=0,this.options.onStateChange?.(!0);}),this.eventSource.addEventListener("message",t=>{this.handleMessage(t.data);}),this.eventSource.addEventListener("flag_update",t=>{this.handleMessage(t.data);}),this.eventSource.addEventListener("error",()=>{this.connected=!1,this.options.onStateChange?.(!1),this.cleanup(),this.scheduleReconnect();});}catch{this.scheduleReconnect();}}handleMessage(e){try{let t=JSON.parse(e);this.options.onEvent(t);}catch{}}cleanup(){this.eventSource&&(this.eventSource.close(),this.eventSource=null),this.reconnectTimer!==null&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null);}scheduleReconnect(){if(this.destroyed||this.reconnectAttempt>=this.maxReconnects)return;let e=core.computeBackoffMs(this.reconnectAttempt,1e3,3e4);this.reconnectAttempt++,this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.destroyed||this.openConnection();},e);}};var E="nexus_flags_",m="nexus_anon_id",c=class{memory=new Map;storageKey;localStorageAvailable;broadcastChannel=null;constructor(e){this.storageKey=`${E}${e}`,this.localStorageAvailable=this.testLocalStorage(),this.hydrate(),this.setupBroadcastChannel();}set(e,t){this.memory.set(e,t),this.persist(),this.broadcastUpdate(e,t);}get(e){return this.memory.get(e)}setAll(e){for(let[t,s]of Object.entries(e))this.memory.set(t,s);this.persist();}delete(e){this.memory.delete(e),this.persist();}getAll(){return Object.fromEntries(this.memory.entries())}clear(){if(this.memory.clear(),this.localStorageAvailable)try{window.localStorage.removeItem(this.storageKey);}catch{}this.broadcastChannel?.close();}getOrCreateAnonymousId(){if(typeof window>"u")return "anon-ssr-node";if(this.localStorageAvailable)try{let e=window.localStorage.getItem(m);return e||(e=`anon_${Math.random().toString(36).substring(2,11)}`,window.localStorage.setItem(m,e)),e}catch{}return `anon_${Math.random().toString(36).substring(2,11)}`}testLocalStorage(){try{if(typeof window>"u")return !1;let e="__nexus_test__";return window.localStorage.setItem(e,"1"),window.localStorage.removeItem(e),!0}catch{return false}}hydrate(){if(this.localStorageAvailable)try{let e=window.localStorage.getItem(this.storageKey);if(e){let t=JSON.parse(e);for(let[s,n]of Object.entries(t))this.memory.set(s,n);}}catch{}}persist(){if(this.localStorageAvailable)try{window.localStorage.setItem(this.storageKey,JSON.stringify(Object.fromEntries(this.memory.entries())));}catch{}}setupBroadcastChannel(){try{typeof BroadcastChannel<"u"&&(this.broadcastChannel=new BroadcastChannel(`nexus_flags_${this.storageKey}`),this.broadcastChannel.onmessage=e=>{e.data?.key&&e.data?.result&&this.memory.set(e.data.key,e.data.result);});}catch{}}broadcastUpdate(e,t){try{this.broadcastChannel?.postMessage({key:e,result:t});}catch{}}};var d=class{apiKey;baseUrl;timeoutMs;user;storage;listeners=new Map;sseManager;flagDefinitions=new Map;constructor(e={}){this.apiKey=core.resolveApiKey(e.apiKey),this.baseUrl=core.resolveBaseUrl(e.baseUrl),this.timeoutMs=e.timeoutMs??3e3,this.storage=new c(this.apiKey.substring(0,16)),this.user=e.user??{id:this.storage.getOrCreateAnonymousId()},e.bootstrap&&this.storage.setAll(e.bootstrap),e.realtime!==false&&this.initRealtimeSync(),this.refreshFlags();}isEnabled(e,t=false){let s=this.storage.get(e);return s!==void 0?s.enabled:t}getVariant(e,t,s){let n=this.storage.get(e);if(!n?.enabled||!n.variants)return s;let a=n.variants[t];return a!==void 0?a:s}async identify(e){this.user={...this.user,...e},await this.refreshFlags();}reset(){this.user={id:this.storage.getOrCreateAnonymousId()},this.refreshFlags();}onFlagChange(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>this.listeners.get(e)?.delete(t)}destroy(){this.sseManager?.disconnect(),this.listeners.clear(),this.storage.clear();}initRealtimeSync(){this.sseManager=new l({url:`${this.baseUrl}/api/v1/flags/stream`,apiKey:this.apiKey,onEvent:e=>{if(e.type==="FLAG_UPDATE"&&e.data){let t=this.flagDefinitions.get(e.key),s=t?u(t,this.user):e.data;this.storage.set(e.key,s),this.listeners.get(e.key)?.forEach(n=>n(s));}else e.type==="FLAG_DELETE"&&(this.storage.delete(e.key),this.flagDefinitions.delete(e.key));}}),this.sseManager.connect();}async refreshFlags(){try{let e=await core.fetchWithRetry({url:`${this.baseUrl}/api/v1/flags/eval`,method:"GET",headers:{Authorization:`Bearer ${this.apiKey}`,"X-Nexus-User-Id":this.user.id??"anon","X-Nexus-Country":this.user.country??""},timeoutMs:this.timeoutMs,maxRetries:2});for(let[t,s]of Object.entries(e.data)){this.flagDefinitions.set(t,s);let n=u(s,this.user);this.storage.set(t,n),this.listeners.get(t)?.forEach(a=>a(n));}}catch{}}};exports.FlagStorage=c;exports.NexusFlagsClient=d;exports.SSEManager=l;exports.computeRolloutBucket=v;exports.evaluateFlag=u;exports.murmur3=p;//# sourceMappingURL=index.cjs.map
2
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/evaluator.ts","../src/sse-manager.ts","../src/storage.ts","../src/client.ts"],"names":["murmur3","key","seed","h","c1","c2","i","length4","k","k2","rem","computeRolloutBucket","userId","flagKey","hashInput","compareSemver","a","b","partsA","partsB","diff","resolveAttribute","ctx","attributePath","parts","current","part","evaluateSingleRule","rule","userCtx","userValue","targets","evaluateFlag","flag","SSEManager","options","url","evt","data","event","delay","computeBackoffMs","STORAGE_KEY_PREFIX","ANON_ID_KEY","FlagStorage","apiKeyPrefix","result","flags","value","id","testKey","raw","parsed","NexusFlagsClient","resolveApiKey","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A,CAAQa,CAAAA,CAAO,IAAI,CAAA,CAAG,CACrD,KAAK,eAAA,CAAgB,GAAA,CAAI7C,EAAKgC,CAAI,CAAA,CAClC,IAAM+B,CAAAA,CAAYhC,CAAAA,CAAaC,CAAAA,CAAM,KAAK,IAAI,CAAA,CAC9C,KAAK,OAAA,CAAQ,GAAA,CAAIhC,EAAK+D,CAAS,CAAA,CAC/B,IAAA,CAAK,SAAA,CAAU,GAAA,CAAI/D,CAAG,GAAG,OAAA,CAAS6D,CAAAA,EAAOA,EAAGE,CAAS,CAAC,EACxD,CACF,CAAA,KAAQ,CAGR,CACF,CACF","file":"index.cjs","sourcesContent":["/**\n * @fileoverview MurmurHash3 32-bit implementation and ABAC rule evaluator.\n * Pure TypeScript — no external dependencies. Implements deterministic rollout bucketing.\n * @module @nexus/sdk-flags/evaluator\n */\n\nimport type { FeatureFlag, FlagEvaluationResult, TargetingRule, UserContext } from '@nexussdk/contracts';\n\n// ---------------------------------------------------------------------------\n// MurmurHash3 32-bit Implementation (Pure TypeScript)\n// Used for deterministic user-to-bucket mapping without server round-trips.\n// ---------------------------------------------------------------------------\n\n/**\n * Converts a string to a Uint32 MurmurHash3 hash.\n * Implements the MurmurHash3 32-bit algorithm (x86 variant).\n *\n * @param key - Input string to hash.\n * @param seed - Optional seed value. Defaults to 0.\n * @returns Unsigned 32-bit integer hash value.\n *\n * @example\n * const hash = murmur3('user123:checkout_v2', 0);\n * const bucket = hash % 100; // 0-99 deterministic bucket\n */\nexport function murmur3(key: string, seed = 0): number {\n let h = seed >>> 0;\n const c1 = 0xcc9e2d51;\n const c2 = 0x1b873593;\n\n let i = 0;\n // Process 4-byte chunks\n const length4 = Math.floor(key.length / 4) * 4;\n while (i < length4) {\n let k =\n ((key.charCodeAt(i) & 0xff)) |\n ((key.charCodeAt(i + 1) & 0xff) << 8) |\n ((key.charCodeAt(i + 2) & 0xff) << 16) |\n ((key.charCodeAt(i + 3) & 0xff) << 24);\n\n k = Math.imul(k, c1);\n k = (k << 15) | (k >>> 17);\n k = Math.imul(k, c2);\n\n h ^= k;\n h = (h << 13) | (h >>> 19);\n h = (Math.imul(h, 5) + 0xe6546b64) >>> 0;\n i += 4;\n }\n\n // Process remaining bytes\n let k2 = 0;\n const rem = key.length & 3;\n if (rem >= 3) k2 ^= (key.charCodeAt(i + 2) & 0xff) << 16;\n if (rem >= 2) k2 ^= (key.charCodeAt(i + 1) & 0xff) << 8;\n if (rem >= 1) {\n k2 ^= key.charCodeAt(i) & 0xff;\n k2 = Math.imul(k2, c1);\n k2 = (k2 << 15) | (k2 >>> 17);\n k2 = Math.imul(k2, c2);\n h ^= k2;\n }\n\n // Finalization mix\n h ^= key.length;\n h ^= h >>> 16;\n h = Math.imul(h, 0x85ebca6b);\n h ^= h >>> 13;\n h = Math.imul(h, 0xc2b2ae35);\n h ^= h >>> 16;\n\n return h >>> 0; // Ensure unsigned\n}\n\n/**\n * Computes the deterministic rollout bucket (0-99) for a given user+flag combination.\n * Uses MurmurHash3 for even distribution without server state.\n *\n * @param userId - User's unique identifier (anonymous ID if not authenticated).\n * @param flagKey - Flag programmatic key.\n * @returns Bucket value between 0 and 99 (inclusive).\n *\n * @example\n * const bucket = computeRolloutBucket('usr_12345', 'checkout_v2');\n * // isEnabled = bucket < flag.rolloutPercentage\n */\nexport function computeRolloutBucket(userId: string, flagKey: string): number {\n const hashInput = `${userId}:${flagKey}`;\n return murmur3(hashInput) % 100;\n}\n\n// ---------------------------------------------------------------------------\n// ABAC Rule Evaluator\n// ---------------------------------------------------------------------------\n\n/**\n * Performs a simple semantic version comparison.\n * Compares two semver strings in \"MAJOR.MINOR.PATCH\" format.\n *\n * @param a - First version string.\n * @param b - Second version string.\n * @returns Positive if a > b, negative if a < b, 0 if equal.\n */\nfunction compareSemver(a: string, b: string): number {\n const partsA = a.replace(/^v/, '').split('.').map(Number);\n const partsB = b.replace(/^v/, '').split('.').map(Number);\n for (let i = 0; i < 3; i++) {\n const diff = (partsA[i] ?? 0) - (partsB[i] ?? 0);\n if (diff !== 0) return diff;\n }\n return 0;\n}\n\n/**\n * Extracts a nested attribute value from the UserContext by dot-notation path.\n *\n * @param ctx - UserContext object.\n * @param attributePath - Dot-separated path (e.g. \"custom.tier\", \"country\").\n * @returns The attribute value or `undefined` if not found.\n */\nfunction resolveAttribute(ctx: UserContext, attributePath: string): unknown {\n const parts = attributePath.split('.');\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let current: any = ctx;\n for (const part of parts) {\n if (current == null || typeof current !== 'object') return undefined;\n current = current[part];\n }\n return current;\n}\n\n/**\n * Evaluates a single targeting rule against the user context.\n *\n * @param rule - The ABAC targeting rule to evaluate.\n * @param userCtx - The current user context.\n * @returns `true` if the rule passes for this user.\n */\nfunction evaluateSingleRule(rule: TargetingRule, userCtx: UserContext): boolean {\n const userValue = resolveAttribute(userCtx, rule.attribute);\n const targets = rule.values;\n\n switch (rule.operator) {\n case 'EQUALS':\n return userValue === targets[0];\n case 'NOT_EQUALS':\n return userValue !== targets[0];\n case 'IN':\n return targets.includes(userValue as string | number | boolean);\n case 'NOT_IN':\n return !targets.includes(userValue as string | number | boolean);\n case 'CONTAINS':\n return typeof userValue === 'string' && userValue.includes(String(targets[0]));\n case 'NOT_CONTAINS':\n return typeof userValue === 'string' && !userValue.includes(String(targets[0]));\n case 'STARTS_WITH':\n return typeof userValue === 'string' && userValue.startsWith(String(targets[0]));\n case 'ENDS_WITH':\n return typeof userValue === 'string' && userValue.endsWith(String(targets[0]));\n case 'GREATER_THAN':\n return typeof userValue === 'number' && userValue > Number(targets[0]);\n case 'LESS_THAN':\n return typeof userValue === 'number' && userValue < Number(targets[0]);\n case 'SEMVER_GTE':\n return (\n typeof userValue === 'string' &&\n typeof targets[0] === 'string' &&\n compareSemver(userValue, String(targets[0])) >= 0\n );\n case 'SEMVER_LTE':\n return (\n typeof userValue === 'string' &&\n typeof targets[0] === 'string' &&\n compareSemver(userValue, String(targets[0])) <= 0\n );\n default:\n return false;\n }\n}\n\n/**\n * Evaluates a FeatureFlag against a UserContext using the full ABAC + rollout engine.\n *\n * Evaluation Order:\n * 1. Kill-switch check (`isEnabled === false` → KILL_SWITCH)\n * 2. All targeting rules must pass (ABAC evaluation)\n * 3. Percentage rollout via MurmurHash3 bucketing\n * 4. Default enabled state\n *\n * @param flag - The feature flag definition from the cache.\n * @param userCtx - Current user context for targeting evaluation.\n * @returns Full {@link FlagEvaluationResult} with reason explanation.\n *\n * @example\n * const result = evaluateFlag(flag, { id: 'usr_12345', country: 'VN' });\n * if (result.enabled) {\n * console.log(result.variants.discount_rate); // 20\n * }\n */\nexport function evaluateFlag(flag: FeatureFlag, userCtx: UserContext): FlagEvaluationResult {\n // Step 1: Kill-switch\n if (!flag.isEnabled) {\n return {\n key: flag.key,\n enabled: false,\n variants: {},\n reason: 'KILL_SWITCH',\n version: flag.version,\n };\n }\n\n // Step 2: ABAC targeting rules — all must pass (AND logic)\n if (flag.targetingRules.length > 0) {\n const allRulesPass = flag.targetingRules.every((rule) =>\n evaluateSingleRule(rule, userCtx),\n );\n if (!allRulesPass) {\n return {\n key: flag.key,\n enabled: false,\n variants: {},\n reason: 'FALLBACK',\n version: flag.version,\n };\n }\n // All targeting rules matched\n if (flag.rolloutPercentage >= 100) {\n return {\n key: flag.key,\n enabled: true,\n variants: flag.variants,\n reason: 'TARGETING_MATCH',\n version: flag.version,\n };\n }\n }\n\n // Step 3: Percentage rollout (MurmurHash3)\n if (flag.rolloutPercentage > 0) {\n const userId = userCtx.id ?? 'anon';\n const bucket = computeRolloutBucket(userId, flag.key);\n if (bucket < flag.rolloutPercentage) {\n return {\n key: flag.key,\n enabled: true,\n variants: flag.variants,\n reason: flag.targetingRules.length > 0 ? 'TARGETING_MATCH' : 'ROLLOUT_MATCH',\n version: flag.version,\n };\n }\n return {\n key: flag.key,\n enabled: false,\n variants: {},\n reason: 'FALLBACK',\n version: flag.version,\n };\n }\n\n // Step 4: Full kill-switch off (rolloutPercentage === 0 with no rules)\n return {\n key: flag.key,\n enabled: false,\n variants: {},\n reason: 'KILL_SWITCH',\n version: flag.version,\n };\n}\n","/**\n * @fileoverview Singleton SSE Manager with ref-counting and auto-reconnect.\n * Ensures exactly one EventSource connection per API key across all flag subscribers.\n * @module @nexus/sdk-flags/sse-manager\n */\n\nimport type { FlagStreamEvent } from '@nexussdk/contracts';\nimport { computeBackoffMs } from '@nexussdk/core';\n\n/**\n * Options for creating an SSE connection.\n */\nexport interface SSEManagerOptions {\n /** Full SSE stream URL (e.g. \"http://localhost:8080/api/v1/flags/stream\"). */\n url: string;\n /** Public API key for authentication. */\n apiKey: string;\n /** Callback invoked for each received flag stream event. */\n onEvent: (event: FlagStreamEvent) => void;\n /** Callback invoked on connection state changes (optional). */\n onStateChange?: (connected: boolean) => void;\n /** Maximum reconnect attempts. Defaults to Infinity. */\n maxReconnects?: number;\n}\n\n/**\n * Ref-counted Singleton SSE Manager.\n *\n * Multiple consumers sharing the same `apiKey` receive updates\n * from a single shared SSE connection. Connection is torn down when all\n * consumers have called `disconnect()`.\n *\n * Connection lifecycle:\n * 1. `connect()` → opens EventSource or streaming fetch\n * 2. On disconnect: exponential backoff reconnect (max 30s)\n * 3. `disconnect()` → decrements ref count; tears down on 0\n *\n * @example\n * const manager = new SSEManager({\n * url: 'http://localhost:8080/api/v1/flags/stream',\n * apiKey: 'pk_live_...',\n * onEvent: (event) => updateCache(event),\n * });\n * manager.connect();\n * // Later:\n * manager.disconnect();\n */\nexport class SSEManager {\n private readonly options: SSEManagerOptions;\n private eventSource: EventSource | null = null;\n private connected = false;\n private destroyed = false;\n private reconnectAttempt = 0;\n private reconnectTimer: ReturnType<typeof setTimeout> | null = null;\n private readonly maxReconnects: number;\n\n constructor(options: SSEManagerOptions) {\n this.options = options;\n this.maxReconnects = options.maxReconnects ?? Infinity;\n }\n\n /**\n * Returns whether the SSE connection is currently active.\n *\n * @returns `true` if EventSource is open and receiving events.\n */\n get isConnected(): boolean {\n return this.connected;\n }\n\n /**\n * Opens the SSE connection to the Go-Gin stream endpoint.\n * Safe to call multiple times — no-op if already connected.\n *\n * @example\n * manager.connect();\n */\n connect(): void {\n if (this.destroyed || this.connected || this.eventSource) return;\n this.openConnection();\n }\n\n /**\n * Closes the SSE connection and cancels any pending reconnect timers.\n *\n * @example\n * manager.disconnect();\n */\n disconnect(): void {\n this.destroyed = true;\n this.cleanup();\n }\n\n private openConnection(): void {\n if (this.destroyed) return;\n\n try {\n // Append API key as query parameter for SSE (EventSource doesn't support custom headers)\n const url = new URL(this.options.url);\n url.searchParams.set('apiKey', this.options.apiKey);\n\n this.eventSource = new EventSource(url.toString());\n\n this.eventSource.addEventListener('open', () => {\n this.connected = true;\n this.reconnectAttempt = 0;\n this.options.onStateChange?.(true);\n });\n\n this.eventSource.addEventListener('message', (evt: MessageEvent<string>) => {\n this.handleMessage(evt.data);\n });\n\n // Go-Gin sends events with event type 'message' by default\n // Also listen for explicitly typed events\n this.eventSource.addEventListener('flag_update', (evt: MessageEvent<string>) => {\n this.handleMessage(evt.data);\n });\n\n this.eventSource.addEventListener('error', () => {\n this.connected = false;\n this.options.onStateChange?.(false);\n this.cleanup();\n this.scheduleReconnect();\n });\n } catch {\n this.scheduleReconnect();\n }\n }\n\n private handleMessage(data: string): void {\n try {\n const event = JSON.parse(data) as FlagStreamEvent;\n this.options.onEvent(event);\n } catch {\n // Ignore malformed SSE payloads — never crash the host application\n }\n }\n\n private cleanup(): void {\n if (this.eventSource) {\n this.eventSource.close();\n this.eventSource = null;\n }\n if (this.reconnectTimer !== null) {\n clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n }\n }\n\n private scheduleReconnect(): void {\n if (this.destroyed) return;\n if (this.reconnectAttempt >= this.maxReconnects) return;\n\n const delay = computeBackoffMs(this.reconnectAttempt, 1000, 30_000);\n this.reconnectAttempt++;\n\n this.reconnectTimer = setTimeout(() => {\n this.reconnectTimer = null;\n if (!this.destroyed) {\n this.openConnection();\n }\n }, delay);\n }\n}\n","/**\n * @fileoverview In-memory flag storage with LocalStorage sync and incognito fallback.\n * @module @nexus/sdk-flags/storage\n */\n\nimport type { FlagEvaluationResult } from '@nexussdk/contracts';\n\nconst STORAGE_KEY_PREFIX = 'nexus_flags_';\nconst ANON_ID_KEY = 'nexus_anon_id';\n\n/**\n * In-memory flag cache with optional LocalStorage persistence.\n * Falls back to pure in-memory storage in SSR / Incognito / Worker contexts.\n *\n * @example\n * const store = new FlagStorage('pk_live_abc123');\n * store.set('checkout_v2', { key: 'checkout_v2', enabled: true, variants: {}, reason: 'ROLLOUT_MATCH', version: 3 });\n * const result = store.get('checkout_v2');\n */\nexport class FlagStorage {\n private readonly memory = new Map<string, FlagEvaluationResult>();\n private readonly storageKey: string;\n private readonly localStorageAvailable: boolean;\n private broadcastChannel: BroadcastChannel | null = null;\n\n constructor(apiKeyPrefix: string) {\n this.storageKey = `${STORAGE_KEY_PREFIX}${apiKeyPrefix}`;\n this.localStorageAvailable = this.testLocalStorage();\n this.hydrate();\n this.setupBroadcastChannel();\n }\n\n /**\n * Stores a flag evaluation result in memory (and localStorage if available).\n *\n * @param key - Flag programmatic key.\n * @param result - Evaluation result to persist.\n */\n set(key: string, result: FlagEvaluationResult): void {\n this.memory.set(key, result);\n this.persist();\n this.broadcastUpdate(key, result);\n }\n\n /**\n * Retrieves a flag evaluation result by key.\n *\n * @param key - Flag programmatic key.\n * @returns The cached evaluation result or `undefined`.\n */\n get(key: string): FlagEvaluationResult | undefined {\n return this.memory.get(key);\n }\n\n /**\n * Bulk-sets multiple flag results (e.g. after a batch fetch).\n *\n * @param flags - Record of flag key → evaluation result.\n */\n setAll(flags: Record<string, FlagEvaluationResult>): void {\n for (const [key, value] of Object.entries(flags)) {\n this.memory.set(key, value);\n }\n this.persist();\n }\n\n /**\n * Removes a single flag from storage (e.g. on FLAG_DELETE SSE event).\n *\n * @param key - Flag programmatic key.\n */\n delete(key: string): void {\n this.memory.delete(key);\n this.persist();\n }\n\n /**\n * Returns all cached flag results.\n *\n * @returns All stored flag results as a record.\n */\n getAll(): Record<string, FlagEvaluationResult> {\n return Object.fromEntries(this.memory.entries());\n }\n\n /**\n * Clears all cached flags from memory and localStorage.\n */\n clear(): void {\n this.memory.clear();\n if (this.localStorageAvailable) {\n try {\n window.localStorage.removeItem(this.storageKey);\n } catch {\n // Storage access denied\n }\n }\n this.broadcastChannel?.close();\n }\n\n /**\n * Retrieves or creates a persistent anonymous user ID.\n *\n * @returns Anonymous ID string (e.g. \"anon_xyz123abc\").\n */\n getOrCreateAnonymousId(): string {\n if (typeof window === 'undefined') return 'anon-ssr-node';\n\n if (this.localStorageAvailable) {\n try {\n let id = window.localStorage.getItem(ANON_ID_KEY);\n if (!id) {\n id = `anon_${Math.random().toString(36).substring(2, 11)}`;\n window.localStorage.setItem(ANON_ID_KEY, id);\n }\n return id;\n } catch {\n // Incognito / locked storage\n }\n }\n\n return `anon_${Math.random().toString(36).substring(2, 11)}`;\n }\n\n private testLocalStorage(): boolean {\n try {\n if (typeof window === 'undefined') return false;\n const testKey = '__nexus_test__';\n window.localStorage.setItem(testKey, '1');\n window.localStorage.removeItem(testKey);\n return true;\n } catch {\n return false;\n }\n }\n\n private hydrate(): void {\n if (!this.localStorageAvailable) return;\n try {\n const raw = window.localStorage.getItem(this.storageKey);\n if (raw) {\n const parsed = JSON.parse(raw) as Record<string, FlagEvaluationResult>;\n for (const [key, value] of Object.entries(parsed)) {\n this.memory.set(key, value);\n }\n }\n } catch {\n // Corrupt storage — start fresh\n }\n }\n\n private persist(): void {\n if (!this.localStorageAvailable) return;\n try {\n window.localStorage.setItem(\n this.storageKey,\n JSON.stringify(Object.fromEntries(this.memory.entries())),\n );\n } catch {\n // Storage quota exceeded — in-memory only\n }\n }\n\n private setupBroadcastChannel(): void {\n try {\n if (typeof BroadcastChannel !== 'undefined') {\n this.broadcastChannel = new BroadcastChannel(`nexus_flags_${this.storageKey}`);\n this.broadcastChannel.onmessage = (evt: MessageEvent<{ key: string; result: FlagEvaluationResult }>) => {\n // Sync updates from other tabs into local memory cache\n if (evt.data?.key && evt.data?.result) {\n this.memory.set(evt.data.key, evt.data.result);\n }\n };\n }\n } catch {\n // BroadcastChannel unavailable (e.g. Worker context)\n }\n }\n\n private broadcastUpdate(key: string, result: FlagEvaluationResult): void {\n try {\n this.broadcastChannel?.postMessage({ key, result });\n } catch {\n // Broadcast failed — no-op\n }\n }\n}\n","/**\n * @fileoverview NexusFlagsClient — Full-featured feature flags SDK client.\n * In-memory evaluation, SSE real-time sync, ABAC targeting, and MurmurHash3 rollout.\n * @module @nexus/sdk-flags/client\n */\n\nimport type {\n FlagEvaluationResult,\n FlagVariants,\n FeatureFlag,\n UserContext,\n} from '@nexussdk/contracts';\nimport { resolveApiKey, resolveBaseUrl, fetchWithRetry } from '@nexussdk/core';\nimport { evaluateFlag } from './evaluator.js';\nimport { SSEManager } from './sse-manager.js';\nimport { FlagStorage } from './storage.js';\n\n/**\n * Options for initializing the NexusFlagsClient.\n *\n * @example\n * const client = new NexusFlagsClient({\n * apiKey: 'pk_live_...',\n * baseUrl: 'http://localhost:8080',\n * user: { id: 'usr_12345', country: 'VN' },\n * realtime: true,\n * });\n */\nexport interface NexusFlagsOptions {\n /**\n * Public API Key ('pk_live_...' or 'pk_test_...').\n * If omitted, resolved automatically via env variables.\n */\n apiKey?: string;\n /**\n * Base ingestion URL. Defaults to 'https://api.nexus.dev'.\n */\n baseUrl?: string;\n /**\n * Initial user identity context for targeting and percentage rollouts.\n */\n user?: UserContext;\n /**\n * Pre-hydrated flags evaluated on the server (SSR) to prevent client-side UI flicker.\n */\n bootstrap?: Record<string, FlagEvaluationResult>;\n /**\n * Toggle real-time SSE updates. Defaults to true.\n */\n realtime?: boolean;\n /**\n * Network timeout in milliseconds for evaluation fetch. Defaults to 3000ms.\n */\n timeoutMs?: number;\n}\n\n/**\n * Public interface for the NexusFlagsClient.\n */\nexport interface INexusFlagsClient {\n /**\n * Synchronously checks if a flag is active for the current user.\n *\n * @param key - Unique flag identifier.\n * @param defaultValue - Fallback returned if flag is absent or evaluating.\n * @returns `true` if the flag is enabled.\n *\n * @example\n * const showBanner = client.isEnabled('promo_banner_v2', false);\n */\n isEnabled(key: string, defaultValue?: boolean): boolean;\n\n /**\n * Synchronously retrieves a specific dynamic configuration variant.\n *\n * @param key - Unique flag identifier.\n * @param variantKey - Property inside the variant object.\n * @param defaultValue - Fallback returned if flag/variant is missing.\n * @returns The variant value cast to type T.\n *\n * @example\n * const rate = client.getVariant<number>('promo_banner_v2', 'discount_rate', 10);\n */\n getVariant<T = unknown>(key: string, variantKey: string, defaultValue?: T): T;\n\n /**\n * Updates current user context and re-evaluates all flags.\n *\n * @param user - New user context to apply.\n * @returns Promise that resolves after flags are refreshed.\n *\n * @example\n * await client.identify({ id: 'usr_99', country: 'SG' });\n */\n identify(user: UserContext): Promise<void>;\n\n /**\n * Resets user context to an anonymous persistent device identifier.\n *\n * @example\n * client.reset(); // called on logout\n */\n reset(): void;\n\n /**\n * Subscribes to runtime flag changes triggered by SSE updates.\n *\n * @param key - Flag key to observe.\n * @param callback - Called with new evaluation result when the flag changes.\n * @returns Unsubscribe function — call to remove the listener.\n *\n * @example\n * const unsub = client.onFlagChange('checkout_v2', (result) => {\n * setCheckoutEnabled(result.enabled);\n * });\n * // On component unmount:\n * unsub();\n */\n onFlagChange(key: string, callback: (result: FlagEvaluationResult) => void): () => void;\n\n /**\n * Gracefully shuts down active SSE connections and observers.\n *\n * @example\n * client.destroy();\n */\n destroy(): void;\n}\n\n/**\n * Feature Flags Client — the primary SDK entry point for flag evaluation.\n *\n * @implements {INexusFlagsClient}\n *\n * @example\n * const client = new NexusFlagsClient({ apiKey: 'pk_live_...' });\n * const enabled = client.isEnabled('new_checkout', false);\n */\nexport class NexusFlagsClient implements INexusFlagsClient {\n private readonly apiKey: string;\n private readonly baseUrl: string;\n private readonly timeoutMs: number;\n private user: UserContext;\n private readonly storage: FlagStorage;\n private readonly listeners = new Map<string, Set<(res: FlagEvaluationResult) => void>>();\n private sseManager?: SSEManager;\n private flagDefinitions = new Map<string, FeatureFlag>();\n\n constructor(options: NexusFlagsOptions = {}) {\n this.apiKey = resolveApiKey(options.apiKey);\n this.baseUrl = resolveBaseUrl(options.baseUrl);\n this.timeoutMs = options.timeoutMs ?? 3_000;\n this.storage = new FlagStorage(this.apiKey.substring(0, 16));\n this.user = options.user ?? { id: this.storage.getOrCreateAnonymousId() };\n\n // Hydrate bootstrap flags (SSR pre-evaluation)\n if (options.bootstrap) {\n this.storage.setAll(options.bootstrap);\n }\n\n if (options.realtime !== false) {\n this.initRealtimeSync();\n }\n\n // Prefetch flags asynchronously on init\n void this.refreshFlags();\n }\n\n /**\n * Evaluates whether a given feature flag is enabled for the current context.\n */\n public isEnabled(key: string, defaultValue = false): boolean {\n const cached = this.storage.get(key);\n return cached !== undefined ? cached.enabled : defaultValue;\n }\n\n /**\n * Retrieves a typed variant configuration for an active feature flag.\n */\n public getVariant<T = unknown>(key: string, variantKey: string, defaultValue?: T): T {\n const cached = this.storage.get(key);\n if (!cached?.enabled || !cached.variants) {\n return defaultValue as T;\n }\n const value = (cached.variants as FlagVariants)[variantKey];\n return value !== undefined ? (value as T) : (defaultValue as T);\n }\n\n /**\n * Identifies an authenticated user and triggers a flag evaluation refresh.\n */\n public async identify(user: UserContext): Promise<void> {\n this.user = { ...this.user, ...user };\n await this.refreshFlags();\n }\n\n /**\n * Resets the active user context to a new anonymous identifier.\n */\n public reset(): void {\n this.user = { id: this.storage.getOrCreateAnonymousId() };\n void this.refreshFlags();\n }\n\n /**\n * Registers a listener callback invoked when a flag's evaluation state changes.\n */\n public onFlagChange(key: string, callback: (result: FlagEvaluationResult) => void): () => void {\n if (!this.listeners.has(key)) {\n this.listeners.set(key, new Set());\n }\n this.listeners.get(key)!.add(callback);\n return () => this.listeners.get(key)?.delete(callback);\n }\n\n /**\n * Destroys the client, terminating SSE connections and clearing listeners.\n */\n public destroy(): void {\n this.sseManager?.disconnect();\n this.listeners.clear();\n this.storage.clear();\n }\n\n private initRealtimeSync(): void {\n this.sseManager = new SSEManager({\n url: `${this.baseUrl}/api/v1/flags/stream`,\n apiKey: this.apiKey,\n onEvent: (event) => {\n if (event.type === 'FLAG_UPDATE' && event.data) {\n // Use locally evaluated result if we have the flag definition\n const flagDef = this.flagDefinitions.get(event.key);\n const result = flagDef\n ? evaluateFlag(flagDef, this.user)\n : event.data;\n\n this.storage.set(event.key, result);\n this.listeners.get(event.key)?.forEach((cb) => cb(result));\n } else if (event.type === 'FLAG_DELETE') {\n this.storage.delete(event.key);\n this.flagDefinitions.delete(event.key);\n }\n },\n });\n this.sseManager.connect();\n }\n\n private async refreshFlags(): Promise<void> {\n try {\n const result = await fetchWithRetry<Record<string, FeatureFlag>>({\n url: `${this.baseUrl}/api/v1/flags/eval`,\n method: 'GET',\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n 'X-Nexus-User-Id': this.user.id ?? 'anon',\n 'X-Nexus-Country': this.user.country ?? '',\n },\n timeoutMs: this.timeoutMs,\n maxRetries: 2,\n });\n\n for (const [key, flag] of Object.entries(result.data)) {\n this.flagDefinitions.set(key, flag);\n const evaluated = evaluateFlag(flag, this.user);\n this.storage.set(key, evaluated);\n this.listeners.get(key)?.forEach((cb) => cb(evaluated));\n }\n } catch {\n // Offline fallback: retain existing in-memory cache silently\n // Never throw from a background refresh — host app must not be affected\n }\n }\n}\n"]}
@@ -0,0 +1,362 @@
1
+ import { UserContext, FlagEvaluationResult, FeatureFlag, FlagStreamEvent } from '@nexussdk/contracts';
2
+
3
+ /**
4
+ * @fileoverview NexusFlagsClient — Full-featured feature flags SDK client.
5
+ * In-memory evaluation, SSE real-time sync, ABAC targeting, and MurmurHash3 rollout.
6
+ * @module @nexus/sdk-flags/client
7
+ */
8
+
9
+ /**
10
+ * Options for initializing the NexusFlagsClient.
11
+ *
12
+ * @example
13
+ * const client = new NexusFlagsClient({
14
+ * apiKey: 'pk_live_...',
15
+ * baseUrl: 'http://localhost:8080',
16
+ * user: { id: 'usr_12345', country: 'VN' },
17
+ * realtime: true,
18
+ * });
19
+ */
20
+ interface NexusFlagsOptions {
21
+ /**
22
+ * Public API Key ('pk_live_...' or 'pk_test_...').
23
+ * If omitted, resolved automatically via env variables.
24
+ */
25
+ apiKey?: string;
26
+ /**
27
+ * Base ingestion URL. Defaults to 'https://api.nexus.dev'.
28
+ */
29
+ baseUrl?: string;
30
+ /**
31
+ * Initial user identity context for targeting and percentage rollouts.
32
+ */
33
+ user?: UserContext;
34
+ /**
35
+ * Pre-hydrated flags evaluated on the server (SSR) to prevent client-side UI flicker.
36
+ */
37
+ bootstrap?: Record<string, FlagEvaluationResult>;
38
+ /**
39
+ * Toggle real-time SSE updates. Defaults to true.
40
+ */
41
+ realtime?: boolean;
42
+ /**
43
+ * Network timeout in milliseconds for evaluation fetch. Defaults to 3000ms.
44
+ */
45
+ timeoutMs?: number;
46
+ }
47
+ /**
48
+ * Public interface for the NexusFlagsClient.
49
+ */
50
+ interface INexusFlagsClient {
51
+ /**
52
+ * Synchronously checks if a flag is active for the current user.
53
+ *
54
+ * @param key - Unique flag identifier.
55
+ * @param defaultValue - Fallback returned if flag is absent or evaluating.
56
+ * @returns `true` if the flag is enabled.
57
+ *
58
+ * @example
59
+ * const showBanner = client.isEnabled('promo_banner_v2', false);
60
+ */
61
+ isEnabled(key: string, defaultValue?: boolean): boolean;
62
+ /**
63
+ * Synchronously retrieves a specific dynamic configuration variant.
64
+ *
65
+ * @param key - Unique flag identifier.
66
+ * @param variantKey - Property inside the variant object.
67
+ * @param defaultValue - Fallback returned if flag/variant is missing.
68
+ * @returns The variant value cast to type T.
69
+ *
70
+ * @example
71
+ * const rate = client.getVariant<number>('promo_banner_v2', 'discount_rate', 10);
72
+ */
73
+ getVariant<T = unknown>(key: string, variantKey: string, defaultValue?: T): T;
74
+ /**
75
+ * Updates current user context and re-evaluates all flags.
76
+ *
77
+ * @param user - New user context to apply.
78
+ * @returns Promise that resolves after flags are refreshed.
79
+ *
80
+ * @example
81
+ * await client.identify({ id: 'usr_99', country: 'SG' });
82
+ */
83
+ identify(user: UserContext): Promise<void>;
84
+ /**
85
+ * Resets user context to an anonymous persistent device identifier.
86
+ *
87
+ * @example
88
+ * client.reset(); // called on logout
89
+ */
90
+ reset(): void;
91
+ /**
92
+ * Subscribes to runtime flag changes triggered by SSE updates.
93
+ *
94
+ * @param key - Flag key to observe.
95
+ * @param callback - Called with new evaluation result when the flag changes.
96
+ * @returns Unsubscribe function — call to remove the listener.
97
+ *
98
+ * @example
99
+ * const unsub = client.onFlagChange('checkout_v2', (result) => {
100
+ * setCheckoutEnabled(result.enabled);
101
+ * });
102
+ * // On component unmount:
103
+ * unsub();
104
+ */
105
+ onFlagChange(key: string, callback: (result: FlagEvaluationResult) => void): () => void;
106
+ /**
107
+ * Gracefully shuts down active SSE connections and observers.
108
+ *
109
+ * @example
110
+ * client.destroy();
111
+ */
112
+ destroy(): void;
113
+ }
114
+ /**
115
+ * Feature Flags Client — the primary SDK entry point for flag evaluation.
116
+ *
117
+ * @implements {INexusFlagsClient}
118
+ *
119
+ * @example
120
+ * const client = new NexusFlagsClient({ apiKey: 'pk_live_...' });
121
+ * const enabled = client.isEnabled('new_checkout', false);
122
+ */
123
+ declare class NexusFlagsClient implements INexusFlagsClient {
124
+ private readonly apiKey;
125
+ private readonly baseUrl;
126
+ private readonly timeoutMs;
127
+ private user;
128
+ private readonly storage;
129
+ private readonly listeners;
130
+ private sseManager?;
131
+ private flagDefinitions;
132
+ constructor(options?: NexusFlagsOptions);
133
+ /**
134
+ * Evaluates whether a given feature flag is enabled for the current context.
135
+ */
136
+ isEnabled(key: string, defaultValue?: boolean): boolean;
137
+ /**
138
+ * Retrieves a typed variant configuration for an active feature flag.
139
+ */
140
+ getVariant<T = unknown>(key: string, variantKey: string, defaultValue?: T): T;
141
+ /**
142
+ * Identifies an authenticated user and triggers a flag evaluation refresh.
143
+ */
144
+ identify(user: UserContext): Promise<void>;
145
+ /**
146
+ * Resets the active user context to a new anonymous identifier.
147
+ */
148
+ reset(): void;
149
+ /**
150
+ * Registers a listener callback invoked when a flag's evaluation state changes.
151
+ */
152
+ onFlagChange(key: string, callback: (result: FlagEvaluationResult) => void): () => void;
153
+ /**
154
+ * Destroys the client, terminating SSE connections and clearing listeners.
155
+ */
156
+ destroy(): void;
157
+ private initRealtimeSync;
158
+ private refreshFlags;
159
+ }
160
+
161
+ /**
162
+ * @fileoverview MurmurHash3 32-bit implementation and ABAC rule evaluator.
163
+ * Pure TypeScript — no external dependencies. Implements deterministic rollout bucketing.
164
+ * @module @nexus/sdk-flags/evaluator
165
+ */
166
+
167
+ /**
168
+ * Converts a string to a Uint32 MurmurHash3 hash.
169
+ * Implements the MurmurHash3 32-bit algorithm (x86 variant).
170
+ *
171
+ * @param key - Input string to hash.
172
+ * @param seed - Optional seed value. Defaults to 0.
173
+ * @returns Unsigned 32-bit integer hash value.
174
+ *
175
+ * @example
176
+ * const hash = murmur3('user123:checkout_v2', 0);
177
+ * const bucket = hash % 100; // 0-99 deterministic bucket
178
+ */
179
+ declare function murmur3(key: string, seed?: number): number;
180
+ /**
181
+ * Computes the deterministic rollout bucket (0-99) for a given user+flag combination.
182
+ * Uses MurmurHash3 for even distribution without server state.
183
+ *
184
+ * @param userId - User's unique identifier (anonymous ID if not authenticated).
185
+ * @param flagKey - Flag programmatic key.
186
+ * @returns Bucket value between 0 and 99 (inclusive).
187
+ *
188
+ * @example
189
+ * const bucket = computeRolloutBucket('usr_12345', 'checkout_v2');
190
+ * // isEnabled = bucket < flag.rolloutPercentage
191
+ */
192
+ declare function computeRolloutBucket(userId: string, flagKey: string): number;
193
+ /**
194
+ * Evaluates a FeatureFlag against a UserContext using the full ABAC + rollout engine.
195
+ *
196
+ * Evaluation Order:
197
+ * 1. Kill-switch check (`isEnabled === false` → KILL_SWITCH)
198
+ * 2. All targeting rules must pass (ABAC evaluation)
199
+ * 3. Percentage rollout via MurmurHash3 bucketing
200
+ * 4. Default enabled state
201
+ *
202
+ * @param flag - The feature flag definition from the cache.
203
+ * @param userCtx - Current user context for targeting evaluation.
204
+ * @returns Full {@link FlagEvaluationResult} with reason explanation.
205
+ *
206
+ * @example
207
+ * const result = evaluateFlag(flag, { id: 'usr_12345', country: 'VN' });
208
+ * if (result.enabled) {
209
+ * console.log(result.variants.discount_rate); // 20
210
+ * }
211
+ */
212
+ declare function evaluateFlag(flag: FeatureFlag, userCtx: UserContext): FlagEvaluationResult;
213
+
214
+ /**
215
+ * @fileoverview Singleton SSE Manager with ref-counting and auto-reconnect.
216
+ * Ensures exactly one EventSource connection per API key across all flag subscribers.
217
+ * @module @nexus/sdk-flags/sse-manager
218
+ */
219
+
220
+ /**
221
+ * Options for creating an SSE connection.
222
+ */
223
+ interface SSEManagerOptions {
224
+ /** Full SSE stream URL (e.g. "http://localhost:8080/api/v1/flags/stream"). */
225
+ url: string;
226
+ /** Public API key for authentication. */
227
+ apiKey: string;
228
+ /** Callback invoked for each received flag stream event. */
229
+ onEvent: (event: FlagStreamEvent) => void;
230
+ /** Callback invoked on connection state changes (optional). */
231
+ onStateChange?: (connected: boolean) => void;
232
+ /** Maximum reconnect attempts. Defaults to Infinity. */
233
+ maxReconnects?: number;
234
+ }
235
+ /**
236
+ * Ref-counted Singleton SSE Manager.
237
+ *
238
+ * Multiple consumers sharing the same `apiKey` receive updates
239
+ * from a single shared SSE connection. Connection is torn down when all
240
+ * consumers have called `disconnect()`.
241
+ *
242
+ * Connection lifecycle:
243
+ * 1. `connect()` → opens EventSource or streaming fetch
244
+ * 2. On disconnect: exponential backoff reconnect (max 30s)
245
+ * 3. `disconnect()` → decrements ref count; tears down on 0
246
+ *
247
+ * @example
248
+ * const manager = new SSEManager({
249
+ * url: 'http://localhost:8080/api/v1/flags/stream',
250
+ * apiKey: 'pk_live_...',
251
+ * onEvent: (event) => updateCache(event),
252
+ * });
253
+ * manager.connect();
254
+ * // Later:
255
+ * manager.disconnect();
256
+ */
257
+ declare class SSEManager {
258
+ private readonly options;
259
+ private eventSource;
260
+ private connected;
261
+ private destroyed;
262
+ private reconnectAttempt;
263
+ private reconnectTimer;
264
+ private readonly maxReconnects;
265
+ constructor(options: SSEManagerOptions);
266
+ /**
267
+ * Returns whether the SSE connection is currently active.
268
+ *
269
+ * @returns `true` if EventSource is open and receiving events.
270
+ */
271
+ get isConnected(): boolean;
272
+ /**
273
+ * Opens the SSE connection to the Go-Gin stream endpoint.
274
+ * Safe to call multiple times — no-op if already connected.
275
+ *
276
+ * @example
277
+ * manager.connect();
278
+ */
279
+ connect(): void;
280
+ /**
281
+ * Closes the SSE connection and cancels any pending reconnect timers.
282
+ *
283
+ * @example
284
+ * manager.disconnect();
285
+ */
286
+ disconnect(): void;
287
+ private openConnection;
288
+ private handleMessage;
289
+ private cleanup;
290
+ private scheduleReconnect;
291
+ }
292
+
293
+ /**
294
+ * @fileoverview In-memory flag storage with LocalStorage sync and incognito fallback.
295
+ * @module @nexus/sdk-flags/storage
296
+ */
297
+
298
+ /**
299
+ * In-memory flag cache with optional LocalStorage persistence.
300
+ * Falls back to pure in-memory storage in SSR / Incognito / Worker contexts.
301
+ *
302
+ * @example
303
+ * const store = new FlagStorage('pk_live_abc123');
304
+ * store.set('checkout_v2', { key: 'checkout_v2', enabled: true, variants: {}, reason: 'ROLLOUT_MATCH', version: 3 });
305
+ * const result = store.get('checkout_v2');
306
+ */
307
+ declare class FlagStorage {
308
+ private readonly memory;
309
+ private readonly storageKey;
310
+ private readonly localStorageAvailable;
311
+ private broadcastChannel;
312
+ constructor(apiKeyPrefix: string);
313
+ /**
314
+ * Stores a flag evaluation result in memory (and localStorage if available).
315
+ *
316
+ * @param key - Flag programmatic key.
317
+ * @param result - Evaluation result to persist.
318
+ */
319
+ set(key: string, result: FlagEvaluationResult): void;
320
+ /**
321
+ * Retrieves a flag evaluation result by key.
322
+ *
323
+ * @param key - Flag programmatic key.
324
+ * @returns The cached evaluation result or `undefined`.
325
+ */
326
+ get(key: string): FlagEvaluationResult | undefined;
327
+ /**
328
+ * Bulk-sets multiple flag results (e.g. after a batch fetch).
329
+ *
330
+ * @param flags - Record of flag key → evaluation result.
331
+ */
332
+ setAll(flags: Record<string, FlagEvaluationResult>): void;
333
+ /**
334
+ * Removes a single flag from storage (e.g. on FLAG_DELETE SSE event).
335
+ *
336
+ * @param key - Flag programmatic key.
337
+ */
338
+ delete(key: string): void;
339
+ /**
340
+ * Returns all cached flag results.
341
+ *
342
+ * @returns All stored flag results as a record.
343
+ */
344
+ getAll(): Record<string, FlagEvaluationResult>;
345
+ /**
346
+ * Clears all cached flags from memory and localStorage.
347
+ */
348
+ clear(): void;
349
+ /**
350
+ * Retrieves or creates a persistent anonymous user ID.
351
+ *
352
+ * @returns Anonymous ID string (e.g. "anon_xyz123abc").
353
+ */
354
+ getOrCreateAnonymousId(): string;
355
+ private testLocalStorage;
356
+ private hydrate;
357
+ private persist;
358
+ private setupBroadcastChannel;
359
+ private broadcastUpdate;
360
+ }
361
+
362
+ export { FlagStorage, type INexusFlagsClient, NexusFlagsClient, type NexusFlagsOptions, SSEManager, type SSEManagerOptions, computeRolloutBucket, evaluateFlag, murmur3 };