-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathBrowserClient.ts
More file actions
346 lines (319 loc) · 12.4 KB
/
BrowserClient.ts
File metadata and controls
346 lines (319 loc) · 12.4 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
338
339
340
341
342
343
344
345
346
import {
AutoEnvAttributes,
BasicLogger,
BROWSER_DATA_SYSTEM_DEFAULTS,
BROWSER_TRANSITION_TABLE,
browserFdv1Endpoints,
Configuration,
createDefaultSourceFactoryProvider,
createFDv2DataManagerBase,
FDv2ConnectionMode,
FlagManager,
Hook,
internal,
LDIdentifyOptions as LDBaseIdentifyOptions,
LDClientImpl,
LDContext,
LDEmitter,
LDEmitterEventName,
LDFlagValue,
LDHeaders,
LDIdentifyResult,
LDPluginEnvironmentMetadata,
LDWaitForInitializationOptions,
MODE_TABLE,
Platform,
resolveForegroundMode,
safeRegisterDebugOverridePlugins,
} from '@launchdarkly/js-client-sdk-common';
import { getHref } from './BrowserApi';
import BrowserDataManager from './BrowserDataManager';
import { BrowserIdentifyOptions as LDIdentifyOptions } from './BrowserIdentifyOptions';
import { registerStateDetection } from './BrowserStateDetector';
import GoalManager from './goals/GoalManager';
import { Goal, isClick } from './goals/Goals';
import { LDClient, LDStartOptions } from './LDClient';
import { LDPlugin } from './LDPlugin';
import validateBrowserOptions, { BrowserOptions, filterToBaseOptionsWithDefaults } from './options';
import BrowserPlatform from './platform/BrowserPlatform';
import { getAllStorageKeys } from './platform/LocalStorage';
class BrowserClientImpl extends LDClientImpl {
private readonly _goalManager?: GoalManager;
private readonly _plugins?: LDPlugin[];
constructor(
clientSideId: string,
initialContext: LDContext,
autoEnvAttributes: AutoEnvAttributes,
options: BrowserOptions = {},
overridePlatform?: Platform,
) {
const { logger: customLogger, debug } = options;
// Overrides the default logger from the common implementation.
const logger =
customLogger ??
new BasicLogger({
destination: {
// eslint-disable-next-line no-console
debug: console.debug,
// eslint-disable-next-line no-console
info: console.info,
// eslint-disable-next-line no-console
warn: console.warn,
// eslint-disable-next-line no-console
error: console.error,
},
level: debug ? 'debug' : 'info',
});
// TODO: Use the already-configured baseUri from the SDK config. SDK-560
const baseUrl = options.baseUri ?? 'https://clientsdk.launchdarkly.com';
const platform = overridePlatform ?? new BrowserPlatform(logger, options);
// Only the browser-specific options are in validatedBrowserOptions.
const validatedBrowserOptions = validateBrowserOptions(options, logger);
// The base options are in baseOptionsWithDefaults.
const baseOptionsWithDefaults = filterToBaseOptionsWithDefaults({ ...options, logger });
const { eventUrlTransformer } = validatedBrowserOptions;
const endpoints = browserFdv1Endpoints(clientSideId);
const dataManagerFactory = (
flagManager: FlagManager,
configuration: Configuration,
baseHeaders: LDHeaders,
emitter: LDEmitter,
diagnosticsManager?: internal.DiagnosticsManager,
) => {
if (configuration.dataSystem) {
return createFDv2DataManagerBase({
platform,
flagManager,
credential: clientSideId,
config: configuration,
baseHeaders,
emitter,
transitionTable: BROWSER_TRANSITION_TABLE,
foregroundMode: resolveForegroundMode(
configuration.dataSystem,
BROWSER_DATA_SYSTEM_DEFAULTS,
),
backgroundMode: undefined,
modeTable: MODE_TABLE,
sourceFactoryProvider: createDefaultSourceFactoryProvider(),
fdv1Endpoints: browserFdv1Endpoints(clientSideId),
buildQueryParams: (identifyOptions?: LDBaseIdentifyOptions) => {
const params: { key: string; value: string }[] = [{ key: 'auth', value: clientSideId }];
const browserOpts = identifyOptions as LDIdentifyOptions | undefined;
if (browserOpts?.hash) {
params.push({ key: 'h', value: browserOpts.hash });
}
return params;
},
});
}
return new BrowserDataManager(
platform,
flagManager,
clientSideId,
configuration,
validatedBrowserOptions,
endpoints.polling,
endpoints.streaming,
baseHeaders,
emitter,
diagnosticsManager,
);
};
super(clientSideId, autoEnvAttributes, platform, baseOptionsWithDefaults, dataManagerFactory, {
// This logic is derived from https://github.com/launchdarkly/js-sdk-common/blob/main/src/PersistentFlagStore.js
getLegacyStorageKeys: () =>
getAllStorageKeys().filter((key) => key.startsWith(`ld:${clientSideId}:`)),
analyticsEventPath: `/events/bulk/${clientSideId}`,
diagnosticEventPath: `/events/diagnostic/${clientSideId}`,
includeAuthorizationHeader: false,
highTimeoutThreshold: 5,
userAgentHeaderName: 'x-launchdarkly-user-agent',
dataSystemDefaults: BROWSER_DATA_SYSTEM_DEFAULTS,
trackEventModifier: (event: internal.InputCustomEvent) =>
new internal.InputCustomEvent(
event.context,
event.key,
event.data,
event.metricValue,
event.samplingRatio,
eventUrlTransformer(getHref()),
),
getImplementationHooks: (environmentMetadata: LDPluginEnvironmentMetadata) =>
internal.safeGetHooks(logger, environmentMetadata, validatedBrowserOptions.plugins),
credentialType: 'clientSideId',
requiresStart: true,
initialContext,
});
this.setEventSendingEnabled(true, false);
// Forward the browser streaming option to the FDv2 data manager so that
// an explicit streaming: false prevents auto-promotion to streaming.
if (validatedBrowserOptions.streaming !== undefined) {
this.dataManager.setForcedStreaming?.(validatedBrowserOptions.streaming);
}
this.dataManager.setFlushCallback?.(() => this.flush());
this._plugins = validatedBrowserOptions.plugins;
if (validatedBrowserOptions.fetchGoals) {
this._goalManager = new GoalManager(
clientSideId,
platform.requests,
baseUrl,
(err) => {
// TODO: May need to emit. SDK-561
logger.error(err.message);
},
(url: string, goal: Goal) => {
const context = this.getInternalContext();
if (!context) {
return;
}
const transformedUrl = eventUrlTransformer(url);
if (isClick(goal)) {
this.sendEvent({
kind: 'click',
url: transformedUrl,
samplingRatio: 1,
key: goal.key,
creationDate: Date.now(),
context,
selector: goal.selector,
});
} else {
this.sendEvent({
kind: 'pageview',
url: transformedUrl,
samplingRatio: 1,
key: goal.key,
creationDate: Date.now(),
context,
});
}
},
);
// This is intentionally not awaited. If we want to add a "goalsready" event, or
// "waitForGoalsReady", then we would make an async immediately invoked function expression
// which emits the event, and assign its promise to a member. The "waitForGoalsReady" function
// would return that promise.
this._goalManager.initialize();
if (validatedBrowserOptions.automaticBackgroundHandling) {
registerStateDetection(() => this.flush());
}
}
}
registerPlugins(client: LDClient): void {
internal.safeRegisterPlugins(
this.logger,
this.environmentMetadata,
client,
this._plugins || [],
);
const override = this.getDebugOverrides();
if (override) {
safeRegisterDebugOverridePlugins(this.logger, override, this._plugins || []);
}
}
override async identify(
context: LDContext,
identifyOptions?: LDIdentifyOptions,
): Promise<LDIdentifyResult> {
const options =
identifyOptions?.sheddable === undefined
? { ...identifyOptions, sheddable: true }
: identifyOptions;
const res = await super.identify(context, options);
// Ensure that we do not start the goal manager if start() is not called.
if (this.startPromise) {
this._goalManager?.startTracking();
}
return res;
}
setConnectionMode(mode?: FDv2ConnectionMode): void {
if (!this.dataManager.setConnectionMode) {
this.logger.warn(
'setConnectionMode requires the FDv2 data system (dataSystem option). ' +
'The call has no effect without it.',
);
return;
}
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.setConnectionMode(mode);
}
setStreaming(streaming?: boolean): void {
this.dataManager.setForcedStreaming?.(streaming);
}
private _updateAutomaticStreamingState() {
const hasListeners = this.emitter
.eventNames()
.some((name) => name.startsWith('change:') || name === 'change');
this.dataManager.setAutomaticStreamingState?.(hasListeners);
}
override on(eventName: LDEmitterEventName, listener: Function): void {
super.on(eventName, listener);
this._updateAutomaticStreamingState();
}
override off(eventName: LDEmitterEventName, listener: Function): void {
super.off(eventName, listener);
this._updateAutomaticStreamingState();
}
}
export function makeClient(
clientSideId: string,
initialContext: LDContext,
autoEnvAttributes: AutoEnvAttributes,
options: BrowserOptions = {},
overridePlatform?: Platform,
): LDClient {
const impl = new BrowserClientImpl(
clientSideId,
initialContext,
autoEnvAttributes,
options,
overridePlatform,
);
// Return a PIMPL style implementation. This decouples the interface from the interface of the implementation.
// In the future we should consider updating the common SDK code to not use inheritance and instead compose
// the leaf-implementation.
// Using an object with PIMPL here also allows us to completely hide the underlying implementation, where with a class
// it is trivial to access what should be protected (or even private) fields.
const client: LDClient = {
variation: (key: string, defaultValue?: LDFlagValue) => impl.variation(key, defaultValue),
variationDetail: (key: string, defaultValue?: LDFlagValue) =>
impl.variationDetail(key, defaultValue),
boolVariation: (key: string, defaultValue: boolean) => impl.boolVariation(key, defaultValue),
boolVariationDetail: (key: string, defaultValue: boolean) =>
impl.boolVariationDetail(key, defaultValue),
numberVariation: (key: string, defaultValue: number) => impl.numberVariation(key, defaultValue),
numberVariationDetail: (key: string, defaultValue: number) =>
impl.numberVariationDetail(key, defaultValue),
stringVariation: (key: string, defaultValue: string) => impl.stringVariation(key, defaultValue),
stringVariationDetail: (key: string, defaultValue: string) =>
impl.stringVariationDetail(key, defaultValue),
jsonVariation: (key: string, defaultValue: unknown) => impl.jsonVariation(key, defaultValue),
jsonVariationDetail: (key: string, defaultValue: unknown) =>
impl.jsonVariationDetail(key, defaultValue),
track: (key: string, data?: any, metricValue?: number) => impl.track(key, data, metricValue),
on: (key: LDEmitterEventName, callback: (...args: any[]) => void) => impl.on(key, callback),
off: (key: LDEmitterEventName, callback: (...args: any[]) => void) => impl.off(key, callback),
flush: () => impl.flush(),
setConnectionMode: (mode?: FDv2ConnectionMode) => impl.setConnectionMode(mode),
setStreaming: (streaming?: boolean) => impl.setStreaming(streaming),
identify: (pristineContext: LDContext, identifyOptions?: LDIdentifyOptions) =>
impl.identify(pristineContext, identifyOptions),
getContext: () => impl.getContext(),
close: () => impl.close(),
allFlags: () => impl.allFlags(),
addHook: (hook: Hook) => impl.addHook(hook),
waitForInitialization: (waitOptions?: LDWaitForInitializationOptions) =>
impl.waitForInitialization(waitOptions),
logger: impl.logger,
start: (startOptions?: LDStartOptions) => impl.start(startOptions),
};
impl.registerPlugins(client);
return client;
}