@applicaster/zapp-react-native-utils 17.0.0-alpha.3352797522 → 17.0.0-alpha.9147048829

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,495 @@
1
+ import { DeviceEventEmitter, NativeModules } from "react-native";
2
+ import { localStorage } from "@applicaster/zapp-react-native-bridge/ZappStorage/LocalStorage";
3
+ import { getBoolFromConfigValue } from "../configurationUtils";
4
+ import { createLogger } from "../logger";
5
+
6
+ const logger = createLogger({
7
+ category: "DebugFeatures",
8
+ subsystem: "react_native/bridge",
9
+ });
10
+
11
+ export type FeatureFlag = {
12
+ id: string;
13
+ group?: string;
14
+ description?: string;
15
+ initialState?: boolean;
16
+ };
17
+
18
+ export type RegisteredFeatureFlag = {
19
+ id: string;
20
+ group: string;
21
+ description: string;
22
+ initialState: boolean;
23
+ enabled: boolean;
24
+ value: string | null;
25
+ };
26
+
27
+ export type FeatureFlagChangeEvent = {
28
+ id: string;
29
+ value: string | null;
30
+ enabled: boolean;
31
+ };
32
+
33
+ export type FeatureFlagChangeListener = (event: FeatureFlagChangeEvent) => void;
34
+
35
+ type NormalizedFeatureFlag = {
36
+ id: string;
37
+ group: string;
38
+ description: string;
39
+ initialState: boolean;
40
+ };
41
+
42
+ type NativeDebugFeaturesBridge = {
43
+ registerFeatureFlag?: (flag: NormalizedFeatureFlag) => Promise<boolean>;
44
+ getFeatures?: () => Promise<RegisteredFeatureFlag[]>;
45
+ isFeatureFlagEnabled?: (featureId: string) => Promise<boolean>;
46
+ toggleFeatureFlag?: (featureId: string, enabled: boolean) => Promise<boolean>;
47
+ getStringValue?: (key: string) => Promise<string | null>;
48
+ setStringValue?: (
49
+ key: string,
50
+ value: string | null
51
+ ) => Promise<string | null>;
52
+ };
53
+
54
+ interface DebugFeaturesBackend {
55
+ registerFeatureFlag(flag: NormalizedFeatureFlag): Promise<boolean>;
56
+ getFeatures(): Promise<RegisteredFeatureFlag[]>;
57
+ isFeatureFlagEnabled(featureId: string): Promise<boolean>;
58
+ toggleFeatureFlag(featureId: string, enabled: boolean): Promise<boolean>;
59
+ getStringValue(key: string): Promise<string | null>;
60
+ setStringValue(key: string, value: string | null): Promise<string | null>;
61
+ onSubscribed?(): void;
62
+ }
63
+
64
+ type DebugFeaturesState = {
65
+ features: Map<string, NormalizedFeatureFlag>;
66
+ listeners: Set<FeatureFlagChangeListener>;
67
+ keyListeners: Map<string, Set<FeatureFlagChangeListener>>;
68
+ nativeSubscribed: boolean;
69
+ notify: (event: FeatureFlagChangeEvent) => void;
70
+ };
71
+
72
+ const MODULE_NAME = "DebugFeaturesBridge";
73
+ const EVENT_CHANGED = "DebugFeatures.changed";
74
+ const STATE_KEY = "__applicasterDebugFeatures";
75
+
76
+ export const DEBUG_TOOLS_NAMESPACE = "debug_tools";
77
+
78
+ const notifyListeners = (
79
+ state: DebugFeaturesState,
80
+ event: FeatureFlagChangeEvent
81
+ ) => {
82
+ const globalListeners = Array.from(state.listeners);
83
+
84
+ const targetedListeners = Array.from(state.keyListeners.get(event.id) ?? []);
85
+
86
+ [...globalListeners, ...targetedListeners].forEach((listener) => {
87
+ try {
88
+ listener(event);
89
+ } catch (_error) {
90
+ // Isolate failing subscribers so other listeners still receive updates.
91
+ }
92
+ });
93
+ };
94
+
95
+ const getState = (): DebugFeaturesState => {
96
+ const globalObj = globalThis as any;
97
+
98
+ if (!globalObj[STATE_KEY]) {
99
+ const state: DebugFeaturesState = {
100
+ features: new Map<string, NormalizedFeatureFlag>(),
101
+ listeners: new Set<FeatureFlagChangeListener>(),
102
+ keyListeners: new Map<string, Set<FeatureFlagChangeListener>>(),
103
+ nativeSubscribed: false,
104
+ notify: (event: FeatureFlagChangeEvent) => notifyListeners(state, event),
105
+ };
106
+
107
+ globalObj[STATE_KEY] = state;
108
+ }
109
+
110
+ return globalObj[STATE_KEY];
111
+ };
112
+
113
+ const ensureNativeListener = () => {
114
+ const state = getState();
115
+
116
+ if (state.nativeSubscribed || !DeviceEventEmitter?.addListener) {
117
+ return;
118
+ }
119
+
120
+ state.nativeSubscribed = true;
121
+
122
+ DeviceEventEmitter.addListener(
123
+ EVENT_CHANGED,
124
+ (payload?: Partial<FeatureFlagChangeEvent>) => {
125
+ if (!payload?.id) {
126
+ return;
127
+ }
128
+
129
+ const value =
130
+ payload.value === undefined ? null : (payload.value as string | null);
131
+
132
+ const enabled =
133
+ typeof payload.enabled === "boolean"
134
+ ? payload.enabled
135
+ : value === "true";
136
+
137
+ state.notify({
138
+ id: payload.id,
139
+ value,
140
+ enabled,
141
+ });
142
+ }
143
+ );
144
+ };
145
+
146
+ const checkedCall = async <T>(
147
+ bridge: NativeDebugFeaturesBridge,
148
+ methodName: keyof NativeDebugFeaturesBridge,
149
+ fallback: T,
150
+ ...args: any[]
151
+ ): Promise<T> => {
152
+ const fn = bridge[methodName] as
153
+ | ((...fnArgs: any[]) => Promise<T>)
154
+ | undefined;
155
+
156
+ if (typeof fn !== "function") {
157
+ logger.log_error(
158
+ `${MODULE_NAME}.${String(methodName)} is missing on native module`
159
+ );
160
+
161
+ return fallback;
162
+ }
163
+
164
+ return await fn(...args);
165
+ };
166
+
167
+ class NativeDebugFeaturesBackend implements DebugFeaturesBackend {
168
+ private readonly bridge: NativeDebugFeaturesBridge;
169
+
170
+ constructor(bridge: NativeDebugFeaturesBridge) {
171
+ this.bridge = bridge;
172
+ }
173
+
174
+ public onSubscribed = () => {
175
+ ensureNativeListener();
176
+ };
177
+
178
+ public registerFeatureFlag = async (
179
+ flag: NormalizedFeatureFlag
180
+ ): Promise<boolean> =>
181
+ Boolean(await checkedCall(this.bridge, "registerFeatureFlag", false, flag));
182
+
183
+ public getFeatures = async (): Promise<RegisteredFeatureFlag[]> => {
184
+ const list = await checkedCall<RegisteredFeatureFlag[]>(
185
+ this.bridge,
186
+ "getFeatures",
187
+ []
188
+ );
189
+
190
+ return (list ?? []).map((item) => ({
191
+ id: item.id,
192
+ group: item.group ?? "",
193
+ description: item.description ?? "",
194
+ initialState: Boolean(item.initialState),
195
+ enabled: Boolean(item.enabled),
196
+ value: item.value ?? null,
197
+ }));
198
+ };
199
+
200
+ public isFeatureFlagEnabled = async (featureId: string): Promise<boolean> =>
201
+ Boolean(
202
+ await checkedCall(this.bridge, "isFeatureFlagEnabled", false, featureId)
203
+ );
204
+
205
+ public toggleFeatureFlag = async (
206
+ featureId: string,
207
+ enabled: boolean
208
+ ): Promise<boolean> => {
209
+ ensureNativeListener();
210
+
211
+ return Boolean(
212
+ await checkedCall(
213
+ this.bridge,
214
+ "toggleFeatureFlag",
215
+ false,
216
+ featureId,
217
+ enabled
218
+ )
219
+ );
220
+ };
221
+
222
+ public getStringValue = async (key: string): Promise<string | null> => {
223
+ const result = await checkedCall<string | null>(
224
+ this.bridge,
225
+ "getStringValue",
226
+ null,
227
+ key
228
+ );
229
+
230
+ return result ?? null;
231
+ };
232
+
233
+ public setStringValue = async (
234
+ key: string,
235
+ value: string | null
236
+ ): Promise<string | null> => {
237
+ ensureNativeListener();
238
+
239
+ const result = await checkedCall<string | null>(
240
+ this.bridge,
241
+ "setStringValue",
242
+ null,
243
+ key,
244
+ value
245
+ );
246
+
247
+ return result ?? null;
248
+ };
249
+ }
250
+
251
+ class StorageDebugFeaturesBackend implements DebugFeaturesBackend {
252
+ private readonly namespace: string;
253
+
254
+ constructor(namespace: string) {
255
+ this.namespace = namespace;
256
+ }
257
+
258
+ public registerFeatureFlag = async (
259
+ flag: NormalizedFeatureFlag
260
+ ): Promise<boolean> => {
261
+ const raw = await localStorage.getItem(flag.id, this.namespace, true);
262
+
263
+ if ((raw === null || raw === undefined) && flag.initialState) {
264
+ await this.toggleFeatureFlag(flag.id, true);
265
+
266
+ return true;
267
+ }
268
+
269
+ return Boolean(raw && getBoolFromConfigValue(raw));
270
+ };
271
+
272
+ public getFeatures = async (): Promise<RegisteredFeatureFlag[]> => {
273
+ const state = getState();
274
+
275
+ const entries = Array.from(state.features.values()).sort((a, b) =>
276
+ a.group === b.group
277
+ ? a.id.localeCompare(b.id)
278
+ : a.group.localeCompare(b.group)
279
+ );
280
+
281
+ return Promise.all(
282
+ entries.map(async (entry) => {
283
+ const value = await this.getStringValue(entry.id);
284
+
285
+ const enabled =
286
+ value !== null ? Boolean(getBoolFromConfigValue(value)) : false;
287
+
288
+ return {
289
+ ...entry,
290
+ enabled,
291
+ value,
292
+ };
293
+ })
294
+ );
295
+ };
296
+
297
+ public isFeatureFlagEnabled = async (featureId: string): Promise<boolean> => {
298
+ const result = await localStorage.getItem(featureId, this.namespace);
299
+
300
+ return Boolean(result && getBoolFromConfigValue(result));
301
+ };
302
+
303
+ public toggleFeatureFlag = async (
304
+ featureId: string,
305
+ enabled: boolean
306
+ ): Promise<boolean> => {
307
+ const strVal = enabled ? "true" : "false";
308
+ await localStorage.setItem(featureId, strVal, this.namespace);
309
+ getState().notify({ id: featureId, value: strVal, enabled });
310
+
311
+ return enabled;
312
+ };
313
+
314
+ public getStringValue = async (key: string): Promise<string | null> => {
315
+ const result = await localStorage.getItem(key, this.namespace, true);
316
+
317
+ if (result === null || result === undefined) {
318
+ return null;
319
+ }
320
+
321
+ if (typeof result === "string") {
322
+ return result;
323
+ }
324
+
325
+ return typeof result === "object" ? JSON.stringify(result) : String(result);
326
+ };
327
+
328
+ public setStringValue = async (
329
+ key: string,
330
+ value: string | null
331
+ ): Promise<string | null> => {
332
+ if (value === null) {
333
+ await localStorage.removeItem(key, this.namespace);
334
+ getState().notify({ id: key, value: null, enabled: false });
335
+
336
+ return null;
337
+ }
338
+
339
+ await localStorage.setItem(key, value, this.namespace);
340
+
341
+ getState().notify({
342
+ id: key,
343
+ value,
344
+ enabled: Boolean(getBoolFromConfigValue(value)),
345
+ });
346
+
347
+ return value;
348
+ };
349
+ }
350
+
351
+ const createBackend = (namespace: string): DebugFeaturesBackend => {
352
+ const bridge = NativeModules?.[MODULE_NAME] as
353
+ | NativeDebugFeaturesBridge
354
+ | undefined;
355
+
356
+ return bridge
357
+ ? new NativeDebugFeaturesBackend(bridge)
358
+ : new StorageDebugFeaturesBackend(namespace);
359
+ };
360
+
361
+ class DebugFeatures {
362
+ debugToolsNamespace = DEBUG_TOOLS_NAMESPACE;
363
+
364
+ private readonly backend: DebugFeaturesBackend;
365
+ private static instance: DebugFeatures;
366
+
367
+ constructor() {
368
+ this.backend = createBackend(this.debugToolsNamespace);
369
+ }
370
+
371
+ public static getInstance() {
372
+ if (!DebugFeatures.instance) {
373
+ DebugFeatures.instance = new DebugFeatures();
374
+ }
375
+
376
+ return DebugFeatures.instance;
377
+ }
378
+
379
+ public registerFeatureFlag = async (
380
+ featureFlag: FeatureFlag
381
+ ): Promise<boolean> => {
382
+ const id = featureFlag?.id?.trim();
383
+
384
+ if (!id) {
385
+ return false;
386
+ }
387
+
388
+ const normalized: NormalizedFeatureFlag = {
389
+ id,
390
+ group: featureFlag.group ?? "",
391
+ description: featureFlag.description ?? "",
392
+ initialState: Boolean(featureFlag.initialState),
393
+ };
394
+
395
+ getState().features.set(id, normalized);
396
+
397
+ return this.backend.registerFeatureFlag(normalized);
398
+ };
399
+
400
+ public getFeatures = async (): Promise<RegisteredFeatureFlag[]> =>
401
+ this.backend.getFeatures();
402
+
403
+ public isFeatureFlagEnabled = async (featureId: string): Promise<boolean> =>
404
+ this.backend.isFeatureFlagEnabled(featureId);
405
+
406
+ public toggleFeatureFlag = async (
407
+ featureId: string,
408
+ enabled: boolean
409
+ ): Promise<boolean> => this.backend.toggleFeatureFlag(featureId, enabled);
410
+
411
+ public getStringValue = async (key: string): Promise<string | null> =>
412
+ this.backend.getStringValue(key);
413
+
414
+ public setStringValue = async (
415
+ key: string,
416
+ value: string | null | undefined
417
+ ): Promise<string | null> => {
418
+ const normalizedValue = value && value.length > 0 ? value : null;
419
+
420
+ return this.backend.setStringValue(key, normalizedValue);
421
+ };
422
+
423
+ public subscribe = (
424
+ listener: FeatureFlagChangeListener,
425
+ featureId?: string
426
+ ): (() => void) => {
427
+ this.backend.onSubscribed?.();
428
+ const state = getState();
429
+
430
+ if (featureId) {
431
+ let listenersForKey = state.keyListeners.get(featureId);
432
+
433
+ if (!listenersForKey) {
434
+ listenersForKey = new Set<FeatureFlagChangeListener>();
435
+ state.keyListeners.set(featureId, listenersForKey);
436
+ }
437
+
438
+ listenersForKey.add(listener);
439
+
440
+ return () => {
441
+ listenersForKey?.delete(listener);
442
+
443
+ if (listenersForKey?.size === 0) {
444
+ state.keyListeners.delete(featureId);
445
+ }
446
+ };
447
+ }
448
+
449
+ state.listeners.add(listener);
450
+
451
+ return () => {
452
+ state.listeners.delete(listener);
453
+ };
454
+ };
455
+
456
+ public addListener = (
457
+ listener: FeatureFlagChangeListener,
458
+ featureId?: string
459
+ ): (() => void) => this.subscribe(listener, featureId);
460
+ }
461
+
462
+ export const registerFeatureFlag = (
463
+ featureFlag: FeatureFlag
464
+ ): Promise<boolean> =>
465
+ DebugFeatures.getInstance().registerFeatureFlag(featureFlag);
466
+
467
+ export const getFeatures = (): Promise<RegisteredFeatureFlag[]> =>
468
+ DebugFeatures.getInstance().getFeatures();
469
+
470
+ export const isFeatureFlagEnabled = (featureId: string): Promise<boolean> =>
471
+ DebugFeatures.getInstance().isFeatureFlagEnabled(featureId);
472
+
473
+ export const toggleFeatureFlag = (
474
+ featureId: string,
475
+ enabled: boolean
476
+ ): Promise<boolean> =>
477
+ DebugFeatures.getInstance().toggleFeatureFlag(featureId, enabled);
478
+
479
+ export const getStringValue = (key: string): Promise<string | null> =>
480
+ DebugFeatures.getInstance().getStringValue(key);
481
+
482
+ export const setStringValue = (
483
+ key: string,
484
+ value: string | null | undefined
485
+ ): Promise<string | null> =>
486
+ DebugFeatures.getInstance().setStringValue(key, value);
487
+
488
+ export const subscribe = (
489
+ listener: FeatureFlagChangeListener,
490
+ featureId?: string
491
+ ): (() => void) => DebugFeatures.getInstance().subscribe(listener, featureId);
492
+
493
+ export const addListener = subscribe;
494
+
495
+ export default DebugFeatures;