flipflag-sdk 1.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.
Files changed (97) hide show
  1. package/README.md +713 -0
  2. package/dist/core/FlipFlagSDK.js +379 -0
  3. package/dist/index.js +384 -0
  4. package/dist/index.js.map +1 -0
  5. package/dist/index.mjs +382 -0
  6. package/dist/index.mjs.map +1 -0
  7. package/dist/js/featureFlagManager.js +172 -0
  8. package/dist/js/identifyUser.js +15 -0
  9. package/dist/js/index.js +3 -0
  10. package/dist/js.js +565 -0
  11. package/dist/js.js.map +1 -0
  12. package/dist/js.mjs +561 -0
  13. package/dist/js.mjs.map +1 -0
  14. package/dist/next/FlipflagProvider.js +27 -0
  15. package/dist/next/identifyUser.js +9 -0
  16. package/dist/next/index.js +6 -0
  17. package/dist/next/server-utils.js +70 -0
  18. package/dist/next/types.js +1 -0
  19. package/dist/next/useABTest.js +53 -0
  20. package/dist/next/useFeatureFlag.js +55 -0
  21. package/dist/next/useFeatureFlags.js +69 -0
  22. package/dist/next.js +657 -0
  23. package/dist/next.js.map +1 -0
  24. package/dist/next.mjs +650 -0
  25. package/dist/next.mjs.map +1 -0
  26. package/dist/react/FeatureFlagProvider.js +19 -0
  27. package/dist/react/identifyUser.js +9 -0
  28. package/dist/react/index.js +5 -0
  29. package/dist/react/types.js +1 -0
  30. package/dist/react/useABTest.js +64 -0
  31. package/dist/react/useFeatureFlag.js +84 -0
  32. package/dist/react/useFeatureFlags.js +74 -0
  33. package/dist/react-native/FeatureFlagProvider.js +19 -0
  34. package/dist/react-native/identifyUser.js +9 -0
  35. package/dist/react-native/index.js +8 -0
  36. package/dist/react-native/offlineStorage.js +39 -0
  37. package/dist/react-native/types.js +1 -0
  38. package/dist/react-native/useABTest.js +87 -0
  39. package/dist/react-native/useFeatureFlag.js +82 -0
  40. package/dist/react-native/useFeatureFlags.js +115 -0
  41. package/dist/react-native.js +732 -0
  42. package/dist/react-native.js.map +1 -0
  43. package/dist/react-native.mjs +723 -0
  44. package/dist/react-native.mjs.map +1 -0
  45. package/dist/react.js +634 -0
  46. package/dist/react.js.map +1 -0
  47. package/dist/react.mjs +627 -0
  48. package/dist/react.mjs.map +1 -0
  49. package/dist/types/core/FlipFlagSDK.d.ts +94 -0
  50. package/dist/types/index.d.ts +2 -0
  51. package/dist/types/index.js +1 -0
  52. package/dist/types/js/featureFlagManager.d.ts +59 -0
  53. package/dist/types/js/identifyUser.d.ts +11 -0
  54. package/dist/types/js/index.d.ts +4 -0
  55. package/dist/types/next/FlipflagProvider.d.ts +18 -0
  56. package/dist/types/next/identifyUser.d.ts +6 -0
  57. package/dist/types/next/index.d.ts +7 -0
  58. package/dist/types/next/server-utils.d.ts +15 -0
  59. package/dist/types/next/types.d.ts +24 -0
  60. package/dist/types/next/useABTest.d.ts +10 -0
  61. package/dist/types/next/useFeatureFlag.d.ts +10 -0
  62. package/dist/types/next/useFeatureFlags.d.ts +10 -0
  63. package/dist/types/react/FeatureFlagProvider.d.ts +14 -0
  64. package/dist/types/react/identifyUser.d.ts +6 -0
  65. package/dist/types/react/index.d.ts +6 -0
  66. package/dist/types/react/types.d.ts +20 -0
  67. package/dist/types/react/useABTest.d.ts +10 -0
  68. package/dist/types/react/useFeatureFlag.d.ts +10 -0
  69. package/dist/types/react/useFeatureFlags.d.ts +10 -0
  70. package/dist/types/react-native/FeatureFlagProvider.d.ts +14 -0
  71. package/dist/types/react-native/identifyUser.d.ts +6 -0
  72. package/dist/types/react-native/index.d.ts +9 -0
  73. package/dist/types/react-native/offlineStorage.d.ts +9 -0
  74. package/dist/types/react-native/types.d.ts +25 -0
  75. package/dist/types/react-native/useABTest.d.ts +10 -0
  76. package/dist/types/react-native/useFeatureFlag.d.ts +10 -0
  77. package/dist/types/react-native/useFeatureFlags.d.ts +10 -0
  78. package/dist/types/types/index.d.ts +86 -0
  79. package/dist/types/vue/identifyUser.d.ts +6 -0
  80. package/dist/types/vue/index.d.ts +8 -0
  81. package/dist/types/vue/plugin.d.ts +19 -0
  82. package/dist/types/vue/types.d.ts +20 -0
  83. package/dist/types/vue/useABTest.d.ts +10 -0
  84. package/dist/types/vue/useFeatureFlag.d.ts +10 -0
  85. package/dist/types/vue/useFeatureFlags.d.ts +10 -0
  86. package/dist/vue/identifyUser.js +13 -0
  87. package/dist/vue/index.js +7 -0
  88. package/dist/vue/plugin.js +30 -0
  89. package/dist/vue/types.js +1 -0
  90. package/dist/vue/useABTest.js +93 -0
  91. package/dist/vue/useFeatureFlag.js +87 -0
  92. package/dist/vue/useFeatureFlags.js +120 -0
  93. package/dist/vue.js +718 -0
  94. package/dist/vue.js.map +1 -0
  95. package/dist/vue.mjs +710 -0
  96. package/dist/vue.mjs.map +1 -0
  97. package/package.json +125 -0
package/dist/react.js ADDED
@@ -0,0 +1,634 @@
1
+ 'use strict';
2
+
3
+ var react = require('react');
4
+ var jsxRuntime = require('react/jsx-runtime');
5
+
6
+ class FlipFlagSDK {
7
+ constructor(config) {
8
+ this.cache = new Map();
9
+ this.defaultBaseUrl = "https://app.flipflag.ru/api";
10
+ this.stateListeners = new Set();
11
+ this.config = {
12
+ baseUrl: this.defaultBaseUrl,
13
+ cacheTimeout: 30000, // 30 seconds
14
+ retryAttempts: 3,
15
+ retryDelay: 1000, // 1 second
16
+ pullInterval: 60000, // 1 minute
17
+ ...config,
18
+ };
19
+ this.state = {
20
+ flags: {},
21
+ abTests: {},
22
+ lastFetch: null,
23
+ isLoading: false,
24
+ error: null,
25
+ };
26
+ // Start automatic pulling if pullInterval is set
27
+ if (this.config.pullInterval && this.config.pullInterval > 0) {
28
+ this.startPulling();
29
+ }
30
+ }
31
+ /**
32
+ * Identify user for A/B testing and user-specific flags
33
+ */
34
+ identifyUser(options) {
35
+ this.config.userId = options.userId;
36
+ // Clear A/B test cache since user changed
37
+ this.clearABTestCache();
38
+ // If we have a user, we might want to refresh immediately
39
+ if (this.config.pullInterval && this.config.pullInterval > 0) {
40
+ this.pullData();
41
+ }
42
+ }
43
+ /**
44
+ * Get current SDK state
45
+ */
46
+ getState() {
47
+ return { ...this.state };
48
+ }
49
+ /**
50
+ * Subscribe to state changes
51
+ */
52
+ subscribe(callback) {
53
+ this.stateListeners.add(callback);
54
+ // Return unsubscribe function
55
+ return () => {
56
+ this.stateListeners.delete(callback);
57
+ };
58
+ }
59
+ /**
60
+ * Get a feature flag value from current state
61
+ */
62
+ getFlagValue(flagName) {
63
+ var _a;
64
+ return (_a = this.state.flags[flagName]) !== null && _a !== void 0 ? _a : false;
65
+ }
66
+ /**
67
+ * Get A/B test variant from current state
68
+ */
69
+ getABTestVariant(testName) {
70
+ return this.state.abTests[testName] || null;
71
+ }
72
+ /**
73
+ * Start automatic data pulling
74
+ */
75
+ startPulling() {
76
+ if (this.pullIntervalId) {
77
+ clearInterval(this.pullIntervalId);
78
+ }
79
+ this.pullIntervalId = setInterval(() => {
80
+ this.pullData();
81
+ }, this.config.pullInterval);
82
+ // Initial pull
83
+ this.pullData();
84
+ }
85
+ /**
86
+ * Stop automatic data pulling
87
+ */
88
+ stopPulling() {
89
+ if (this.pullIntervalId) {
90
+ clearInterval(this.pullIntervalId);
91
+ this.pullIntervalId = undefined;
92
+ }
93
+ }
94
+ /**
95
+ * Pull fresh data from API
96
+ */
97
+ async pullData() {
98
+ try {
99
+ this.updateState({ isLoading: true, error: null });
100
+ // Pull flags
101
+ const flagsResponse = await this.fetchAllFlags();
102
+ // Pull A/B tests if user is identified
103
+ let abTestsResponse = null;
104
+ if (this.config.userId) {
105
+ try {
106
+ abTestsResponse = await this.fetchAllABTests();
107
+ }
108
+ catch (error) {
109
+ console.warn("Failed to fetch A/B tests:", error);
110
+ }
111
+ }
112
+ const newState = {
113
+ flags: (flagsResponse === null || flagsResponse === void 0 ? void 0 : flagsResponse.flags) || {},
114
+ lastFetch: new Date(),
115
+ isLoading: false,
116
+ error: null,
117
+ };
118
+ if (abTestsResponse) {
119
+ const abTestsMap = {};
120
+ abTestsResponse.abTests.forEach((test) => {
121
+ // For each test, get the variant for current user
122
+ if (this.config.userId) {
123
+ // This would normally fetch the variant, but for demo we'll simulate
124
+ abTestsMap[test.name] = {
125
+ testName: test.name,
126
+ testId: test.id,
127
+ variantId: "variant_a", // Default variant
128
+ variant: test.variants[0] || {
129
+ id: "default",
130
+ name: "Default",
131
+ value: null,
132
+ weight: 100,
133
+ },
134
+ timestamp: new Date().toISOString(),
135
+ };
136
+ }
137
+ });
138
+ newState.abTests = abTestsMap;
139
+ }
140
+ this.updateState(newState);
141
+ }
142
+ catch (error) {
143
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
144
+ this.updateState({
145
+ isLoading: false,
146
+ error: errorMessage,
147
+ });
148
+ console.error("Failed to pull data:", error);
149
+ }
150
+ }
151
+ /**
152
+ * Update state and notify listeners
153
+ */
154
+ updateState(newState) {
155
+ this.state = { ...this.state, ...newState };
156
+ // Notify all listeners
157
+ this.stateListeners.forEach((callback) => {
158
+ try {
159
+ callback(this.state);
160
+ }
161
+ catch (error) {
162
+ console.error("State listener error:", error);
163
+ }
164
+ });
165
+ }
166
+ /**
167
+ * Fetch all flags from API
168
+ */
169
+ async fetchAllFlags() {
170
+ try {
171
+ return await this.makeRequest(`/sdk/flags/${this.config.projectId}`);
172
+ }
173
+ catch (error) {
174
+ console.error("Failed to fetch flags:", error);
175
+ return null;
176
+ }
177
+ }
178
+ /**
179
+ * Fetch all A/B tests from API
180
+ */
181
+ async fetchAllABTests() {
182
+ try {
183
+ return await this.makeRequest(`/sdk/ab-tests/${this.config.projectId}`);
184
+ }
185
+ catch (error) {
186
+ console.error("Failed to fetch A/B tests:", error);
187
+ return null;
188
+ }
189
+ }
190
+ /**
191
+ * Clear A/B test cache
192
+ */
193
+ clearABTestCache() {
194
+ const abTestKeys = Array.from(this.cache.keys()).filter((key) => key.startsWith("abtest:"));
195
+ abTestKeys.forEach((key) => this.cache.delete(key));
196
+ }
197
+ /**
198
+ * Get all feature flags for a project
199
+ */
200
+ async getFlags(projectId = this.config.projectId, environment) {
201
+ const cacheKey = `flags:${projectId}:${environment || "all"}`;
202
+ const cached = this.getFromCache(cacheKey);
203
+ if (cached) {
204
+ return cached;
205
+ }
206
+ const url = new URL(`/sdk/flags/${projectId}`, this.config.baseUrl);
207
+ if (environment || this.config.environment) {
208
+ url.searchParams.set("environment", environment || this.config.environment);
209
+ }
210
+ const response = await this.makeRequest(url.toString());
211
+ this.setCache(cacheKey, response, this.config.cacheTimeout);
212
+ return response;
213
+ }
214
+ /**
215
+ * Get a specific feature flag value
216
+ */
217
+ async getFlag(flagName, projectId = this.config.projectId, environment) {
218
+ var _a;
219
+ // If we have the flag in state, return it immediately
220
+ if (this.state.flags[flagName] !== undefined) {
221
+ return {
222
+ projectId: this.config.projectId,
223
+ flagName,
224
+ environment: this.config.environment || "all",
225
+ value: this.state.flags[flagName],
226
+ timestamp: ((_a = this.state.lastFetch) === null || _a === void 0 ? void 0 : _a.toISOString()) || new Date().toISOString(),
227
+ };
228
+ }
229
+ const cacheKey = `flag:${projectId}:${flagName}:${environment || "all"}`;
230
+ const cached = this.getFromCache(cacheKey);
231
+ if (cached) {
232
+ return cached;
233
+ }
234
+ const url = new URL(`/sdk/flags/${projectId}/${flagName}`, this.config.baseUrl);
235
+ if (environment || this.config.environment) {
236
+ url.searchParams.set("environment", environment || this.config.environment);
237
+ }
238
+ const response = await this.makeRequest(url.toString());
239
+ this.setCache(cacheKey, response, this.config.cacheTimeout);
240
+ return response;
241
+ }
242
+ /**
243
+ * Get A/B test variant for a user
244
+ */
245
+ async getAbTestVariant(testName, userId, projectId = this.config.projectId) {
246
+ // If we have the A/B test in state, return it immediately
247
+ const stateVariant = this.state.abTests[testName];
248
+ if (stateVariant && stateVariant.testName === testName) {
249
+ return stateVariant;
250
+ }
251
+ const cacheKey = `abtest:${projectId}:${testName}:${userId}`;
252
+ const cached = this.getFromCache(cacheKey);
253
+ if (cached) {
254
+ return cached;
255
+ }
256
+ const url = `${this.config.baseUrl}/sdk/ab-test/${projectId}/${testName}`;
257
+ const response = await this.makeRequest(url, {
258
+ headers: {
259
+ "X-User-ID": userId,
260
+ },
261
+ });
262
+ // Cache A/B test variants for longer since they shouldn't change frequently for a user
263
+ this.setCache(cacheKey, response, this.config.cacheTimeout * 10);
264
+ return response;
265
+ }
266
+ /**
267
+ * Record an A/B test event
268
+ */
269
+ async recordAbTestEvent(testName, userId, event, variantId, eventData, projectId = this.config.projectId) {
270
+ const url = `${this.config.baseUrl}/sdk/ab-test/${projectId}/${testName}/event`;
271
+ return this.makeRequest(url, {
272
+ method: "POST",
273
+ headers: {
274
+ "X-User-ID": userId,
275
+ "Content-Type": "application/json",
276
+ },
277
+ body: JSON.stringify({
278
+ event,
279
+ variantId,
280
+ eventData,
281
+ }),
282
+ });
283
+ }
284
+ /**
285
+ * Get all A/B tests for a project
286
+ */
287
+ async getAbTests(projectId = this.config.projectId) {
288
+ const cacheKey = `abtests:${projectId}`;
289
+ const cached = this.getFromCache(cacheKey);
290
+ if (cached) {
291
+ return cached;
292
+ }
293
+ const url = `${this.config.baseUrl}/sdk/ab-tests/${projectId}`;
294
+ const response = await this.makeRequest(url);
295
+ this.setCache(cacheKey, response, this.config.cacheTimeout);
296
+ return response;
297
+ }
298
+ /**
299
+ * Clear cache for specific key or all cache
300
+ */
301
+ clearCache(key) {
302
+ if (key) {
303
+ this.cache.delete(key);
304
+ }
305
+ else {
306
+ this.cache.clear();
307
+ }
308
+ }
309
+ /**
310
+ * Update configuration
311
+ */
312
+ updateConfig(newConfig) {
313
+ this.config = { ...this.config, ...newConfig };
314
+ }
315
+ async makeRequest(url, options = {}) {
316
+ const headers = {
317
+ "X-API-Key": this.config.apiKey,
318
+ "Content-Type": "application/json",
319
+ ...options.headers,
320
+ };
321
+ const requestOptions = {
322
+ ...options,
323
+ headers,
324
+ };
325
+ return this.makeRequestWithRetry(url, requestOptions);
326
+ }
327
+ async makeRequestWithRetry(url, options, retryOptions = {
328
+ attempts: this.config.retryAttempts,
329
+ delay: this.config.retryDelay,
330
+ backoff: 2,
331
+ }) {
332
+ let lastError;
333
+ for (let attempt = 1; attempt <= retryOptions.attempts; attempt++) {
334
+ try {
335
+ const response = await fetch(url, options);
336
+ if (!response.ok) {
337
+ const errorData = await response.json().catch(() => ({}));
338
+ throw new Error(`HTTP ${response.status}: ${errorData.error || response.statusText}`);
339
+ }
340
+ return await response.json();
341
+ }
342
+ catch (error) {
343
+ lastError = error;
344
+ // Don't retry on client errors (4xx) except 429 (rate limit)
345
+ if (error instanceof Error && error.message.includes("HTTP 4")) {
346
+ if (!error.message.includes("HTTP 429")) {
347
+ throw error;
348
+ }
349
+ }
350
+ if (attempt < retryOptions.attempts) {
351
+ const delay = retryOptions.delay * Math.pow(retryOptions.backoff, attempt - 1);
352
+ await new Promise((resolve) => setTimeout(resolve, delay));
353
+ }
354
+ }
355
+ }
356
+ throw lastError;
357
+ }
358
+ getFromCache(key) {
359
+ const entry = this.cache.get(key);
360
+ if (!entry) {
361
+ return null;
362
+ }
363
+ if (Date.now() - entry.timestamp > entry.ttl) {
364
+ this.cache.delete(key);
365
+ return null;
366
+ }
367
+ return entry.data;
368
+ }
369
+ setCache(key, data, ttl) {
370
+ this.cache.set(key, {
371
+ data,
372
+ timestamp: Date.now(),
373
+ ttl,
374
+ });
375
+ }
376
+ /**
377
+ * Cleanup method - should be called when SDK is no longer needed
378
+ */
379
+ destroy() {
380
+ this.stopPulling();
381
+ this.stateListeners.clear();
382
+ this.cache.clear();
383
+ }
384
+ }
385
+
386
+ const FeatureFlagContext = react.createContext(null);
387
+ function FeatureFlagProvider({ children, config, }) {
388
+ const sdk = new FlipFlagSDK(config);
389
+ const contextValue = {
390
+ sdk,
391
+ config,
392
+ };
393
+ return (jsxRuntime.jsx(FeatureFlagContext.Provider, { value: contextValue, children: children }));
394
+ }
395
+ function useFeatureFlagContext() {
396
+ const context = react.useContext(FeatureFlagContext);
397
+ if (!context) {
398
+ throw new Error("useFeatureFlagContext must be used within a FeatureFlagProvider");
399
+ }
400
+ return context;
401
+ }
402
+
403
+ function useFeatureFlag(flagName, options = {}) {
404
+ var _a;
405
+ const [value, setValue] = react.useState((_a = options.fallbackValue) !== null && _a !== void 0 ? _a : false);
406
+ const [loading, setLoading] = react.useState(true);
407
+ const [error, setError] = react.useState(null);
408
+ // Try to get SDK from context, otherwise create new instance
409
+ let sdk;
410
+ try {
411
+ const context = useFeatureFlagContext();
412
+ sdk = context.sdk;
413
+ }
414
+ catch (_b) {
415
+ if (!options.config) {
416
+ throw new Error("useFeatureFlag must be used within FeatureFlagProvider or config must be provided");
417
+ }
418
+ sdk = new FlipFlagSDK(options.config);
419
+ }
420
+ const updateFromState = react.useCallback(() => {
421
+ if (!options.enabled && options.enabled !== undefined) {
422
+ return;
423
+ }
424
+ try {
425
+ const flagValue = sdk.getFlagValue(flagName);
426
+ setValue(flagValue);
427
+ setLoading(false);
428
+ setError(null);
429
+ }
430
+ catch (err) {
431
+ const errorMessage = err instanceof Error ? err.message : "Unknown error";
432
+ setError(errorMessage);
433
+ // Use fallback value if provided
434
+ if (options.fallbackValue !== undefined) {
435
+ setValue(options.fallbackValue);
436
+ }
437
+ setLoading(false);
438
+ }
439
+ }, [sdk, flagName, options.fallbackValue, options.enabled]);
440
+ const refetch = react.useCallback(async () => {
441
+ // Clear cache for this specific flag and force refresh
442
+ sdk.clearCache(`flag:${sdk["config"].projectId}:${flagName}:${sdk["config"].environment || "all"}`);
443
+ setLoading(true);
444
+ try {
445
+ const response = await sdk.getFlag(flagName);
446
+ setValue(response.value);
447
+ setError(null);
448
+ }
449
+ catch (err) {
450
+ const errorMessage = err instanceof Error ? err.message : "Unknown error";
451
+ setError(errorMessage);
452
+ if (options.fallbackValue !== undefined) {
453
+ setValue(options.fallbackValue);
454
+ }
455
+ }
456
+ finally {
457
+ setLoading(false);
458
+ }
459
+ }, [sdk, flagName, options.fallbackValue]);
460
+ react.useEffect(() => {
461
+ // Subscribe to state changes
462
+ const unsubscribe = sdk.subscribe((state) => {
463
+ if (!options.enabled && options.enabled !== undefined) {
464
+ return;
465
+ }
466
+ const flagValue = state.flags[flagName];
467
+ if (flagValue !== undefined) {
468
+ setValue(flagValue);
469
+ setLoading(false);
470
+ setError(state.error);
471
+ }
472
+ });
473
+ // Initial update from current state
474
+ updateFromState();
475
+ return unsubscribe;
476
+ }, [updateFromState, options.enabled]);
477
+ return {
478
+ value,
479
+ loading,
480
+ error,
481
+ refetch,
482
+ };
483
+ }
484
+
485
+ function useFeatureFlags(flagNames, options = {}) {
486
+ const [flags, setFlags] = react.useState(() => {
487
+ // Initialize with fallback values
488
+ const initialFlags = {};
489
+ flagNames.forEach((flagName) => {
490
+ var _a, _b;
491
+ initialFlags[flagName] = (_b = (_a = options.fallbackValues) === null || _a === void 0 ? void 0 : _a[flagName]) !== null && _b !== void 0 ? _b : false;
492
+ });
493
+ return initialFlags;
494
+ });
495
+ const [loading, setLoading] = react.useState(true);
496
+ const [error, setError] = react.useState(null);
497
+ // Try to get SDK from context, otherwise create new instance
498
+ let sdk;
499
+ try {
500
+ const context = useFeatureFlagContext();
501
+ sdk = context.sdk;
502
+ }
503
+ catch (_a) {
504
+ if (!options.config) {
505
+ throw new Error("useFeatureFlags must be used within FeatureFlagProvider or config must be provided");
506
+ }
507
+ sdk = new FlipFlagSDK(options.config);
508
+ }
509
+ const fetchFlags = react.useCallback(async () => {
510
+ if (!options.enabled && options.enabled !== undefined) {
511
+ return;
512
+ }
513
+ try {
514
+ setLoading(true);
515
+ setError(null);
516
+ const response = await sdk.getFlags();
517
+ const newFlags = { ...flags };
518
+ flagNames.forEach((flagName) => {
519
+ var _a, _b, _c;
520
+ // Use API value if available, otherwise fallback
521
+ newFlags[flagName] =
522
+ (_c = (_a = response.flags[flagName]) !== null && _a !== void 0 ? _a : (_b = options.fallbackValues) === null || _b === void 0 ? void 0 : _b[flagName]) !== null && _c !== void 0 ? _c : false;
523
+ });
524
+ setFlags(newFlags);
525
+ }
526
+ catch (err) {
527
+ const errorMessage = err instanceof Error ? err.message : "Unknown error";
528
+ setError(errorMessage);
529
+ // Use fallback values
530
+ const fallbackFlags = {};
531
+ flagNames.forEach((flagName) => {
532
+ var _a, _b;
533
+ fallbackFlags[flagName] = (_b = (_a = options.fallbackValues) === null || _a === void 0 ? void 0 : _a[flagName]) !== null && _b !== void 0 ? _b : false;
534
+ });
535
+ setFlags(fallbackFlags);
536
+ }
537
+ finally {
538
+ setLoading(false);
539
+ }
540
+ }, [sdk, flagNames, options.fallbackValues, options.enabled, flags]);
541
+ const refetch = react.useCallback(async () => {
542
+ // Clear cache for flags
543
+ sdk.clearCache(`flags:${sdk["config"].projectId}:${sdk["config"].environment || "all"}`);
544
+ await fetchFlags();
545
+ }, [sdk, fetchFlags]);
546
+ react.useEffect(() => {
547
+ fetchFlags();
548
+ }, [fetchFlags]);
549
+ return {
550
+ flags,
551
+ loading,
552
+ error,
553
+ refetch,
554
+ };
555
+ }
556
+
557
+ function useABTest(testName, options) {
558
+ const [variant, setVariant] = react.useState(null);
559
+ const [variantId, setVariantId] = react.useState(null);
560
+ const [loading, setLoading] = react.useState(true);
561
+ const [error, setError] = react.useState(null);
562
+ // Try to get SDK from context, otherwise create new instance
563
+ let sdk;
564
+ try {
565
+ const context = useFeatureFlagContext();
566
+ sdk = context.sdk;
567
+ }
568
+ catch (_a) {
569
+ if (!options.config) {
570
+ throw new Error("useABTest must be used within FeatureFlagProvider or config must be provided");
571
+ }
572
+ sdk = new FlipFlagSDK(options.config);
573
+ }
574
+ const fetchVariant = react.useCallback(async () => {
575
+ if (!options.enabled && options.enabled !== undefined) {
576
+ return;
577
+ }
578
+ try {
579
+ setLoading(true);
580
+ setError(null);
581
+ const response = await sdk.getAbTestVariant(testName, options.userId);
582
+ setVariant(response.variant.value);
583
+ setVariantId(response.variantId);
584
+ }
585
+ catch (err) {
586
+ const errorMessage = err instanceof Error ? err.message : "Unknown error";
587
+ setError(errorMessage);
588
+ setVariant(null);
589
+ setVariantId(null);
590
+ }
591
+ finally {
592
+ setLoading(false);
593
+ }
594
+ }, [sdk, testName, options.userId, options.enabled]);
595
+ const recordEvent = react.useCallback(async (event, eventData) => {
596
+ if (!variantId) {
597
+ console.warn("Cannot record event: no variant assigned yet");
598
+ return;
599
+ }
600
+ try {
601
+ await sdk.recordAbTestEvent(testName, options.userId, event, variantId, eventData);
602
+ }
603
+ catch (err) {
604
+ console.error("Failed to record A/B test event:", err);
605
+ }
606
+ }, [sdk, testName, options.userId, variantId]);
607
+ react.useEffect(() => {
608
+ fetchVariant();
609
+ }, [fetchVariant]);
610
+ return {
611
+ variant,
612
+ variantId,
613
+ loading,
614
+ error,
615
+ recordEvent,
616
+ };
617
+ }
618
+
619
+ /**
620
+ * Identify user for A/B testing and user-specific flags
621
+ * Must be called within FeatureFlagProvider
622
+ */
623
+ function identifyUser(options) {
624
+ const context = useFeatureFlagContext();
625
+ context.sdk.identifyUser(options);
626
+ }
627
+
628
+ exports.FeatureFlagProvider = FeatureFlagProvider;
629
+ exports.identifyUser = identifyUser;
630
+ exports.useABTest = useABTest;
631
+ exports.useFeatureFlag = useFeatureFlag;
632
+ exports.useFeatureFlagContext = useFeatureFlagContext;
633
+ exports.useFeatureFlags = useFeatureFlags;
634
+ //# sourceMappingURL=react.js.map