-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathReactNativeLDClient.ts
More file actions
337 lines (313 loc) · 10.7 KB
/
ReactNativeLDClient.ts
File metadata and controls
337 lines (313 loc) · 10.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
/* eslint-disable max-classes-per-file */
import {
AutoEnvAttributes,
BasicLogger,
type Configuration,
ConnectionMode,
createDefaultSourceFactoryProvider,
createFDv2DataManagerBase,
FDv2ConnectionMode,
type FDv2DataManagerControl,
FlagManager,
internal,
type LDClientDataSystemOptions,
LDClientImpl,
LDClientInternalOptions,
type LDContext,
LDEmitter,
LDHeaders,
type LDIdentifyOptions,
type LDIdentifyResult,
LDPluginEnvironmentMetadata,
LDTimeoutError,
MOBILE_DATA_SYSTEM_DEFAULTS,
MOBILE_TRANSITION_TABLE,
mobileFdv1Endpoints,
MODE_TABLE,
resolveForegroundMode,
} from '@launchdarkly/js-client-sdk-common';
import MobileDataManager from './MobileDataManager';
import validateOptions, { filterToBaseOptions } from './options';
import createPlatform from './platform';
import {
ApplicationState,
ConnectionDestination,
ConnectionManager,
NetworkState,
} from './platform/ConnectionManager';
import LDOptions from './RNOptions';
import RNStateDetector from './RNStateDetector';
/**
* The React Native LaunchDarkly client. Instantiate this class to create an
* instance of the ReactNativeLDClient and pass it to the {@link LDProvider}.
*
* @example
* ```tsx
* const featureClient = new ReactNativeLDClient(MOBILE_KEY, AutoEnvAttributes.Enabled);
*
* <LDProvider client={featureClient}>
* <Welcome />
* </LDProvider>
* ```
*/
function shouldAutoSwitchLifecycle(
config: LDClientDataSystemOptions['automaticModeSwitching'],
): boolean {
if (config === true) {
return true;
}
if (typeof config === 'object' && config.type === 'automatic') {
return config.lifecycle ?? true;
}
return false;
}
function shouldAutoSwitchNetwork(
config: LDClientDataSystemOptions['automaticModeSwitching'],
): boolean {
if (config === true) {
return true;
}
if (typeof config === 'object' && config.type === 'automatic') {
return config.network ?? true;
}
return false;
}
export default class ReactNativeLDClient extends LDClientImpl {
private _connectionManager?: ConnectionManager;
private _stateDetector?: RNStateDetector;
/**
* Creates an instance of the LaunchDarkly client.
*
* @param sdkKey The LaunchDarkly mobile key.
* @param autoEnvAttributes Enable / disable Auto environment attributes. When enabled, the SDK will automatically
* provide data about the mobile environment where the application is running. To learn more,
* read [Automatic environment attributes](https://docs.launchdarkly.com/sdk/features/environment-attributes).
* for more documentation.
* @param options {@link LDOptions} to initialize the client with.
*/
constructor(sdkKey: string, autoEnvAttributes: AutoEnvAttributes, options: LDOptions = {}) {
const { logger: customLogger, debug } = options;
const logger =
customLogger ??
new BasicLogger({
level: debug ? 'debug' : 'info',
// eslint-disable-next-line no-console
destination: console.log,
});
const validatedRnOptions = validateOptions(options, logger);
const internalOptions: LDClientInternalOptions = {
analyticsEventPath: `/mobile`,
diagnosticEventPath: `/mobile/events/diagnostic`,
highTimeoutThreshold: 15,
getImplementationHooks: (_environmentMetadata: LDPluginEnvironmentMetadata) =>
internal.safeGetHooks(logger, _environmentMetadata, validatedRnOptions.plugins),
credentialType: 'mobileKey',
dataSystemDefaults: MOBILE_DATA_SYSTEM_DEFAULTS,
};
const platform = createPlatform(logger, options, validatedRnOptions.storage);
const endpoints = mobileFdv1Endpoints();
const dataManagerFactory = (
flagManager: FlagManager,
configuration: Configuration,
baseHeaders: LDHeaders,
emitter: LDEmitter,
diagnosticsManager?: internal.DiagnosticsManager,
) => {
if (configuration.dataSystem) {
return createFDv2DataManagerBase({
platform,
flagManager,
credential: sdkKey,
config: configuration,
baseHeaders,
emitter,
transitionTable: MOBILE_TRANSITION_TABLE,
foregroundMode: resolveForegroundMode(
configuration.dataSystem,
MOBILE_DATA_SYSTEM_DEFAULTS,
),
backgroundMode: configuration.dataSystem.backgroundConnectionMode ?? 'background',
modeTable: MODE_TABLE,
sourceFactoryProvider: createDefaultSourceFactoryProvider(),
fdv1Endpoints: mobileFdv1Endpoints(),
buildQueryParams: () => [], // Mobile uses Authorization header, not query params
});
}
return new MobileDataManager(
platform,
flagManager,
sdkKey,
configuration,
validatedRnOptions,
endpoints.polling,
endpoints.streaming,
baseHeaders,
emitter,
diagnosticsManager,
);
};
super(
sdkKey,
autoEnvAttributes,
platform,
{ ...filterToBaseOptions(options), logger },
dataManagerFactory,
internalOptions,
);
if (this.isFDv2) {
const fdv2DataManager = this.dataManager as FDv2DataManagerControl;
this.setEventSendingEnabled(true, false);
fdv2DataManager.setFlushCallback(() => this.flush());
// Wire state detection directly to FDv2 data manager using the
// validated automaticModeSwitching config from the data system.
const { automaticModeSwitching } = this.dataSystemConfig ?? {};
const stateDetector = new RNStateDetector();
this._stateDetector = stateDetector;
if (shouldAutoSwitchLifecycle(automaticModeSwitching)) {
stateDetector.setApplicationStateListener((state) => {
fdv2DataManager.setLifecycleState(
state === ApplicationState.Foreground ? 'foreground' : 'background',
);
});
}
if (shouldAutoSwitchNetwork(automaticModeSwitching)) {
stateDetector.setNetworkStateListener((state) => {
fdv2DataManager.setNetworkState(
state === NetworkState.Available ? 'available' : 'unavailable',
);
});
}
} else {
const initialConnectionMode = options.initialConnectionMode ?? 'streaming';
this.setEventSendingEnabled(initialConnectionMode !== 'offline', false);
const dataManager = this.dataManager as MobileDataManager;
const destination: ConnectionDestination = {
setNetworkAvailability: (available: boolean) => {
dataManager.setNetworkAvailability(available);
},
setEventSendingEnabled: (enabled: boolean, flush: boolean) => {
this.setEventSendingEnabled(enabled, flush);
},
setConnectionMode: async (mode: ConnectionMode) => {
dataManager.setConnectionMode(mode);
},
};
this._connectionManager = new ConnectionManager(
logger,
{
initialConnectionMode,
automaticNetworkHandling: validatedRnOptions.automaticNetworkHandling,
automaticBackgroundHandling: validatedRnOptions.automaticBackgroundHandling,
runInBackground: validatedRnOptions.runInBackground,
},
destination,
new RNStateDetector(),
);
}
internal.safeRegisterPlugins(
logger,
this.environmentMetadata,
this,
validatedRnOptions.plugins,
);
}
/**
* Identifies a context to LaunchDarkly.
*
* This override preserves backward compatibility by throwing on error or timeout,
* matching the behavior consumers expect from the React Native SDK.
*
* @param context The LDContext object.
* @param identifyOptions Optional configuration. See {@link LDIdentifyOptions}.
*/
override async identify(
context: LDContext,
identifyOptions?: LDIdentifyOptions,
): Promise<LDIdentifyResult> {
const result = await super.identify(context, identifyOptions);
if (result.status === 'error') {
throw result.error;
} else if (result.status === 'timeout') {
const timeoutError = new LDTimeoutError(
`identify timed out after ${result.timeout} seconds.`,
);
this.logger.error(timeoutError.message);
throw timeoutError;
}
return result;
}
override async close(): Promise<void> {
this._stateDetector?.stopListening();
this._connectionManager?.close();
return super.close();
}
/**
* Sets the SDK connection mode.
*
* @param mode The connection mode to use (`'streaming'`, `'polling'`, or `'offline'`).
*/
async setConnectionMode(mode: ConnectionMode): Promise<void>;
/**
* @internal
*
* This overload is experimental and should NOT be considered ready for
* production use. It may change or be removed without notice and is not
* subject to backwards compatibility guarantees.
*
* Sets the connection mode for the FDv2 data system.
*
* When the FDv2 data system is enabled (`dataSystem` option), this method
* additionally accepts `'one-shot'` and `'background'` modes. Pass
* `undefined` to clear an explicit override and return to automatic mode
* selection.
*
* @param mode The connection mode to use, or `undefined` to clear the
* override (FDv2 only).
*/
async setConnectionMode(mode?: FDv2ConnectionMode): Promise<void>;
async setConnectionMode(mode?: ConnectionMode | FDv2ConnectionMode): Promise<void> {
if (this.isFDv2) {
// FDv2 path
if (mode !== undefined && !(mode in MODE_TABLE)) {
this.logger.warn(
`setConnectionMode called with invalid mode '${mode}'. ` +
`Valid modes: ${Object.keys(MODE_TABLE).join(', ')}.`,
);
return;
}
(this.dataManager as FDv2DataManagerControl).setConnectionMode(
mode as FDv2ConnectionMode | undefined,
);
} else {
// FDv1 path
if (mode === undefined || mode === 'one-shot' || mode === 'background') {
this.logger.warn(
`setConnectionMode('${mode}') is only supported with the FDv2 data system (dataSystem option).`,
);
return;
}
this._connectionManager?.setConnectionMode(mode as ConnectionMode);
this._connectionManager?.setOffline(mode === 'offline');
}
}
/**
* Gets the SDK connection mode.
*/
getConnectionMode(): ConnectionMode;
/**
* @internal
*/
getConnectionMode(): FDv2ConnectionMode;
getConnectionMode(): ConnectionMode | FDv2ConnectionMode {
if (this.isFDv2) {
return (this.dataManager as FDv2DataManagerControl).getCurrentMode();
}
return (this.dataManager as MobileDataManager).getConnectionMode();
}
isOffline() {
if (this.isFDv2) {
return (this.dataManager as FDv2DataManagerControl).getCurrentMode() === 'offline';
}
return (this.dataManager as MobileDataManager).getConnectionMode() === 'offline';
}
}