@flipswitch-io/sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Flipswitch
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,193 @@
1
+ # @flipswitch-io/sdk
2
+
3
+ [![CI](https://github.com/flipswitch-io/js-sdk/actions/workflows/ci.yml/badge.svg)](https://github.com/flipswitch-io/js-sdk/actions/workflows/ci.yml)
4
+ [![npm](https://img.shields.io/npm/v/@flipswitch-io/sdk.svg)](https://www.npmjs.com/package/@flipswitch-io/sdk)
5
+
6
+ Flipswitch SDK for JavaScript/TypeScript with real-time SSE support for OpenFeature.
7
+
8
+ This SDK provides an OpenFeature-compatible provider that wraps OFREP flag evaluation with automatic cache invalidation
9
+ via Server-Sent Events (SSE). When flags change in your Flipswitch dashboard, connected clients receive updates in
10
+ real-time.
11
+
12
+ ## Installation
13
+
14
+ ```bash
15
+ npm install @flipswitch-io/sdk @openfeature/web-sdk
16
+ # or
17
+ npm install @flipswitch-io/sdk @openfeature/server-sdk
18
+ ```
19
+
20
+ ## Quick Start
21
+
22
+ ### Browser (React, Vue, etc.)
23
+
24
+ ```typescript
25
+ import { FlipswitchProvider } from '@flipswitch-io/sdk';
26
+ import { OpenFeature } from '@openfeature/web-sdk';
27
+
28
+ // Only API key is required
29
+ const provider = new FlipswitchProvider({
30
+ apiKey: 'your-environment-api-key'
31
+ });
32
+
33
+ // Register with OpenFeature
34
+ await OpenFeature.setProviderAndWait(provider);
35
+
36
+ // Get a client and evaluate flags
37
+ const client = OpenFeature.getClient();
38
+ const darkMode = await client.getBooleanValue('dark-mode', false);
39
+ const welcomeMessage = await client.getStringValue('welcome-message', 'Hello!');
40
+ ```
41
+
42
+ ### Node.js (Server)
43
+
44
+ ```typescript
45
+ import { FlipswitchProvider } from '@flipswitch-io/sdk';
46
+ import { OpenFeature } from '@openfeature/server-sdk';
47
+
48
+ const provider = new FlipswitchProvider({
49
+ apiKey: 'your-environment-api-key'
50
+ });
51
+
52
+ await OpenFeature.setProviderAndWait(provider);
53
+ const client = OpenFeature.getClient();
54
+
55
+ // Evaluate with context
56
+ const context = {
57
+ targetingKey: 'user-123',
58
+ email: 'user@example.com',
59
+ plan: 'premium',
60
+ };
61
+
62
+ const showFeature = await client.getBooleanValue('new-feature', false, context);
63
+ ```
64
+
65
+ ## Configuration Options
66
+
67
+ | Option | Type | Default | Description |
68
+ |--------|------|---------|-------------|
69
+ | `apiKey` | `string` | *required* | Environment API key from dashboard |
70
+ | `baseUrl` | `string` | `https://api.flipswitch.io` | Your Flipswitch server URL |
71
+ | `enableRealtime` | `boolean` | `true` | Enable SSE for real-time flag updates |
72
+ | `pollingInterval` | `number` | `30000` | Cache TTL in milliseconds |
73
+ | `fetchImplementation` | `typeof fetch` | `fetch` | Custom fetch function |
74
+
75
+ ## Real-Time Updates
76
+
77
+ When `enableRealtime` is enabled, the SDK maintains a Server-Sent Events (SSE) connection to receive instant flag change notifications. When a flag changes:
78
+
79
+ 1. The SSE client receives a `flag-change` event
80
+ 2. The local cache is immediately invalidated
81
+ 3. Next flag evaluation fetches the fresh value
82
+ 4. OpenFeature emits a `PROVIDER_CONFIGURATION_CHANGED` event
83
+
84
+ ### Event Handlers
85
+
86
+ ```typescript
87
+ const provider = new FlipswitchProvider(
88
+ { apiKey: 'your-api-key' },
89
+ {
90
+ onFlagChange: (event) => {
91
+ console.log(`Flag changed: ${event.flagKey}`);
92
+ },
93
+ onConnectionStatusChange: (status) => {
94
+ console.log(`SSE status: ${status}`);
95
+ },
96
+ }
97
+ );
98
+ ```
99
+
100
+ ### Connection Status
101
+
102
+ ```typescript
103
+ // Check current SSE status
104
+ const status = provider.getSseStatus();
105
+ // 'connecting' | 'connected' | 'disconnected' | 'error'
106
+
107
+ // Force reconnect
108
+ provider.reconnectSse();
109
+ ```
110
+
111
+ ## React Integration
112
+
113
+ ```tsx
114
+ import { OpenFeature, OpenFeatureProvider, useFlag } from '@openfeature/react-sdk';
115
+ import { FlipswitchProvider } from '@flipswitch-io/sdk';
116
+
117
+ // Initialize provider
118
+ const provider = new FlipswitchProvider({
119
+ baseUrl: 'https://api.flipswitch.io',
120
+ apiKey: 'your-api-key',
121
+ });
122
+
123
+ await OpenFeature.setProviderAndWait(provider);
124
+
125
+ function App() {
126
+ return (
127
+ <OpenFeatureProvider>
128
+ <MyComponent />
129
+ </OpenFeatureProvider>
130
+ );
131
+ }
132
+
133
+ function MyComponent() {
134
+ const { value: darkMode } = useFlag('dark-mode', false);
135
+
136
+ return (
137
+ <div className={darkMode ? 'dark' : 'light'}>
138
+ Dark mode is {darkMode ? 'enabled' : 'disabled'}
139
+ </div>
140
+ );
141
+ }
142
+ ```
143
+
144
+ ## Bulk Flag Evaluation
145
+
146
+ Evaluate all flags at once or get detailed evaluation results:
147
+
148
+ ```typescript
149
+ // Evaluate all flags
150
+ const flags = await provider.evaluateAllFlags(context);
151
+ for (const flag of flags) {
152
+ console.log(`${flag.key} (${flag.valueType}): ${flag.value}`);
153
+ }
154
+
155
+ // Evaluate a single flag with full details
156
+ const flag = await provider.evaluateFlag('dark-mode', context);
157
+ if (flag) {
158
+ console.log(`Value: ${flag.value}, Reason: ${flag.reason}, Variant: ${flag.variant}`);
159
+ }
160
+ ```
161
+
162
+ ## Reconnection Strategy
163
+
164
+ The SSE client automatically reconnects with exponential backoff:
165
+ - Initial delay: 1 second
166
+ - Maximum delay: 30 seconds
167
+ - Backoff multiplier: 2x
168
+
169
+ When reconnected, the provider status changes from `STALE` back to `READY`.
170
+
171
+ ## Demo
172
+
173
+ A complete working demo is included. To run it:
174
+
175
+ ```bash
176
+ npm install
177
+ npm run demo -- <your-api-key>
178
+ ```
179
+
180
+ The demo will:
181
+ 1. Connect to Flipswitch and validate your API key
182
+ 2. Load and display all flags with their types and values
183
+ 3. Listen for real-time flag changes and display updates
184
+
185
+ See [examples/demo.ts](./examples/demo.ts) for the full source.
186
+
187
+ ## Contributing
188
+
189
+ See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.
190
+
191
+ ## License
192
+
193
+ MIT - see [LICENSE](LICENSE) for details.
@@ -0,0 +1,305 @@
1
+ import { ProviderMetadata, EvaluationContext, ResolutionDetails, JsonValue } from '@openfeature/core';
2
+
3
+ /**
4
+ * Configuration options for the Flipswitch provider.
5
+ */
6
+ interface FlipswitchOptions {
7
+ /**
8
+ * The API key for your environment.
9
+ * Obtain this from your Flipswitch dashboard.
10
+ */
11
+ apiKey: string;
12
+ /**
13
+ * The base URL of your Flipswitch server.
14
+ * @default 'https://api.flipswitch.io'
15
+ */
16
+ baseUrl?: string;
17
+ /**
18
+ * Enable real-time flag updates via SSE.
19
+ * When enabled, the provider will connect to the SSE endpoint
20
+ * and automatically invalidate cached flags when changes occur.
21
+ * @default true
22
+ */
23
+ enableRealtime?: boolean;
24
+ /**
25
+ * Enable telemetry collection.
26
+ * When enabled, the SDK sends usage statistics (SDK version, runtime version,
27
+ * OS, architecture) to help improve the service. No personal data is collected.
28
+ * @default true
29
+ */
30
+ enableTelemetry?: boolean;
31
+ /**
32
+ * Custom fetch function for making HTTP requests.
33
+ * Useful for testing or custom networking needs.
34
+ */
35
+ fetchImplementation?: typeof fetch;
36
+ }
37
+ /**
38
+ * Event emitted when a flag changes.
39
+ */
40
+ interface FlagChangeEvent {
41
+ /**
42
+ * The ID of the environment where the change occurred.
43
+ */
44
+ environmentId: number;
45
+ /**
46
+ * The key of the flag that changed, or null for bulk invalidation.
47
+ */
48
+ flagKey: string | null;
49
+ /**
50
+ * ISO timestamp of when the change occurred.
51
+ */
52
+ timestamp: string;
53
+ }
54
+ /**
55
+ * SSE connection status.
56
+ */
57
+ type SseConnectionStatus = 'connecting' | 'connected' | 'disconnected' | 'error';
58
+ /**
59
+ * Event handler types for the provider.
60
+ */
61
+ interface FlipswitchEventHandlers {
62
+ /**
63
+ * Called when a flag changes.
64
+ */
65
+ onFlagChange?: (event: FlagChangeEvent) => void;
66
+ /**
67
+ * Called when the SSE connection status changes.
68
+ */
69
+ onConnectionStatusChange?: (status: SseConnectionStatus) => void;
70
+ }
71
+ /**
72
+ * Represents the result of evaluating a single flag.
73
+ */
74
+ interface FlagEvaluation {
75
+ /**
76
+ * The flag key.
77
+ */
78
+ key: string;
79
+ /**
80
+ * The evaluated value.
81
+ */
82
+ value: unknown;
83
+ /**
84
+ * The inferred type of the value.
85
+ */
86
+ valueType: 'boolean' | 'string' | 'number' | 'object' | 'array' | 'null' | 'unknown';
87
+ /**
88
+ * The reason for this evaluation result.
89
+ */
90
+ reason: string | null;
91
+ /**
92
+ * The variant that matched, if applicable.
93
+ */
94
+ variant: string | null;
95
+ }
96
+
97
+ type ProviderStatus = 'NOT_READY' | 'READY' | 'ERROR' | 'STALE';
98
+ type ProviderEvent = 'PROVIDER_READY' | 'PROVIDER_ERROR' | 'PROVIDER_STALE' | 'PROVIDER_CONFIGURATION_CHANGED';
99
+ type EventHandler = () => void;
100
+ /**
101
+ * Flipswitch OpenFeature provider with real-time SSE support.
102
+ *
103
+ * This provider wraps the OFREP provider for flag evaluation and adds
104
+ * real-time updates via Server-Sent Events (SSE).
105
+ *
106
+ * @example
107
+ * ```typescript
108
+ * import { FlipswitchProvider } from '@flipswitch-io/sdk';
109
+ * import { OpenFeature } from '@openfeature/web-sdk';
110
+ *
111
+ * // Only API key is required - defaults to https://api.flipswitch.io
112
+ * const provider = new FlipswitchProvider({
113
+ * apiKey: 'your-api-key'
114
+ * });
115
+ *
116
+ * await OpenFeature.setProviderAndWait(provider);
117
+ * const client = OpenFeature.getClient();
118
+ * const darkMode = await client.getBooleanValue('dark-mode', false);
119
+ * ```
120
+ */
121
+ declare class FlipswitchProvider {
122
+ readonly metadata: ProviderMetadata;
123
+ readonly rulesFromFlagValue = false;
124
+ private readonly baseUrl;
125
+ private readonly apiKey;
126
+ private readonly enableRealtime;
127
+ private readonly enableTelemetry;
128
+ private readonly fetchImpl;
129
+ private readonly ofrepProvider;
130
+ private sseClient;
131
+ private _status;
132
+ private eventHandlers;
133
+ private userEventHandlers;
134
+ constructor(options: FlipswitchOptions, eventHandlers?: FlipswitchEventHandlers);
135
+ private getTelemetrySdkHeader;
136
+ private getTelemetryRuntimeHeader;
137
+ private getTelemetryOsHeader;
138
+ private getTelemetryFeaturesHeader;
139
+ private getTelemetryHeaders;
140
+ get status(): ProviderStatus;
141
+ /**
142
+ * Initialize the provider.
143
+ * Validates the API key and starts SSE connection if real-time is enabled.
144
+ */
145
+ initialize(context?: EvaluationContext): Promise<void>;
146
+ /**
147
+ * Called when the provider is shut down.
148
+ */
149
+ onClose(): Promise<void>;
150
+ /**
151
+ * Start the SSE connection for real-time updates.
152
+ */
153
+ private startSseConnection;
154
+ /**
155
+ * Get telemetry headers as a map.
156
+ */
157
+ private getTelemetryHeadersMap;
158
+ /**
159
+ * Handle a flag change event from SSE.
160
+ * Emits PROVIDER_CONFIGURATION_CHANGED to trigger re-evaluation.
161
+ */
162
+ private handleFlagChange;
163
+ /**
164
+ * Emit an event to registered handlers.
165
+ */
166
+ private emit;
167
+ /**
168
+ * Register an event handler.
169
+ */
170
+ onProviderEvent?(event: ProviderEvent, handler: EventHandler): void;
171
+ resolveBooleanEvaluation(flagKey: string, defaultValue: boolean, context: EvaluationContext): ResolutionDetails<boolean>;
172
+ resolveStringEvaluation(flagKey: string, defaultValue: string, context: EvaluationContext): ResolutionDetails<string>;
173
+ resolveNumberEvaluation(flagKey: string, defaultValue: number, context: EvaluationContext): ResolutionDetails<number>;
174
+ resolveObjectEvaluation<T extends JsonValue>(flagKey: string, defaultValue: T, context: EvaluationContext): ResolutionDetails<T>;
175
+ /**
176
+ * Get SSE connection status.
177
+ */
178
+ getSseStatus(): SseConnectionStatus;
179
+ /**
180
+ * Force reconnect SSE connection.
181
+ */
182
+ reconnectSse(): void;
183
+ /**
184
+ * Transform OpenFeature context to OFREP context format.
185
+ */
186
+ private transformContext;
187
+ /**
188
+ * Infer the type of a value.
189
+ */
190
+ private inferType;
191
+ /**
192
+ * Get flag type from metadata or infer from value.
193
+ */
194
+ private getFlagType;
195
+ /**
196
+ * Format a value for display.
197
+ */
198
+ formatValue(value: unknown): string;
199
+ /**
200
+ * Evaluate all flags for the given context.
201
+ * Returns a list of all flag evaluations with their keys, values, types, and reasons.
202
+ *
203
+ * Note: This method makes direct HTTP calls since OFREP providers don't expose
204
+ * the bulk evaluation API.
205
+ *
206
+ * @param context The evaluation context
207
+ * @returns List of flag evaluations
208
+ */
209
+ evaluateAllFlags(context: EvaluationContext): Promise<FlagEvaluation[]>;
210
+ /**
211
+ * Evaluate a single flag and return its evaluation result.
212
+ *
213
+ * Note: This method makes direct HTTP calls for demo purposes.
214
+ * For standard flag evaluation, use the OpenFeature client methods.
215
+ *
216
+ * @param flagKey The flag key to evaluate
217
+ * @param context The evaluation context
218
+ * @returns The flag evaluation, or null if the flag doesn't exist
219
+ */
220
+ evaluateFlag(flagKey: string, context: EvaluationContext): Promise<FlagEvaluation | null>;
221
+ }
222
+
223
+ /**
224
+ * SSE client for real-time flag change notifications.
225
+ * Handles automatic reconnection with exponential backoff.
226
+ */
227
+ declare class SseClient {
228
+ private readonly baseUrl;
229
+ private readonly apiKey;
230
+ private readonly onFlagChange;
231
+ private readonly onStatusChange?;
232
+ private readonly telemetryHeaders?;
233
+ private eventSource;
234
+ private retryDelay;
235
+ private reconnectTimeout;
236
+ private closed;
237
+ private status;
238
+ constructor(baseUrl: string, apiKey: string, onFlagChange: (event: FlagChangeEvent) => void, onStatusChange?: ((status: SseConnectionStatus) => void) | undefined, telemetryHeaders?: Record<string, string> | undefined);
239
+ /**
240
+ * Start the SSE connection.
241
+ */
242
+ connect(): void;
243
+ /**
244
+ * Connect using fetch-based SSE (supports custom headers).
245
+ */
246
+ private connectWithFetch;
247
+ /**
248
+ * Connect using native EventSource (for environments that support it).
249
+ * Note: This requires server-side support for API key in query params.
250
+ */
251
+ private connectWithPolyfill;
252
+ /**
253
+ * Handle incoming SSE events.
254
+ */
255
+ private handleEvent;
256
+ /**
257
+ * Schedule a reconnection attempt with exponential backoff.
258
+ */
259
+ private scheduleReconnect;
260
+ /**
261
+ * Update and broadcast connection status.
262
+ */
263
+ private updateStatus;
264
+ /**
265
+ * Get current connection status.
266
+ */
267
+ getStatus(): SseConnectionStatus;
268
+ /**
269
+ * Close the SSE connection and stop reconnection attempts.
270
+ */
271
+ close(): void;
272
+ }
273
+
274
+ /**
275
+ * Simple in-memory cache for flag values with TTL support.
276
+ */
277
+ declare class FlagCache {
278
+ private cache;
279
+ private readonly ttlMs;
280
+ /**
281
+ * Create a new FlagCache.
282
+ * @param ttlMs Time-to-live in milliseconds (default: 5 minutes)
283
+ */
284
+ constructor(ttlMs?: number);
285
+ /**
286
+ * Get a value from the cache.
287
+ * Returns undefined if the key doesn't exist or has expired.
288
+ */
289
+ get<T>(key: string): T | undefined;
290
+ /**
291
+ * Set a value in the cache.
292
+ */
293
+ set<T>(key: string, value: T): void;
294
+ /**
295
+ * Invalidate a specific key or all keys if no key is provided.
296
+ */
297
+ invalidate(key?: string): void;
298
+ /**
299
+ * Handle a flag change event from SSE.
300
+ * Invalidates the specific flag or all flags if flagKey is null.
301
+ */
302
+ handleFlagChange(event: FlagChangeEvent): void;
303
+ }
304
+
305
+ export { FlagCache, type FlagChangeEvent, type FlagEvaluation, type FlipswitchEventHandlers, type FlipswitchOptions, FlipswitchProvider, SseClient, type SseConnectionStatus };