-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsplitio_web.dart
More file actions
556 lines (483 loc) · 19.2 KB
/
splitio_web.dart
File metadata and controls
556 lines (483 loc) · 19.2 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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
import 'dart:async';
import 'dart:js_interop';
import 'dart:js_interop_unsafe';
import 'package:flutter_web_plugins/flutter_web_plugins.dart' show Registrar;
import 'package:splitio_platform_interface/splitio_platform_interface.dart';
import 'package:splitio_web/src/js_interop.dart';
import 'package:web/web.dart';
extension on Window {
@JS()
external JS_BrowserSDKPackage? splitio;
}
/// Web implementation of [SplitioPlatform].
class SplitioWeb extends SplitioPlatform {
/// Registers this class as the default platform implementation.
static void registerWith(Registrar registrar) {
SplitioPlatform.instance = SplitioWeb();
}
// Future to queue method calls until SDK is initialized
Future<void>? _initFuture;
late JS_IBrowserSDK _factory;
String? _trafficType;
bool _impressionListener = false;
final Map<String, JS_IBrowserClient> _clients = {};
@override
Future<void> init({
required String apiKey,
required String matchingKey,
required String? bucketingKey,
SplitConfiguration? sdkConfiguration,
}) async {
if (_initFuture == null) {
_initFuture = this._init(
apiKey: apiKey,
matchingKey: matchingKey,
bucketingKey: bucketingKey,
sdkConfiguration: sdkConfiguration);
}
return _initFuture;
}
Future<void> _init({
required String apiKey,
required String matchingKey,
required String? bucketingKey,
SplitConfiguration? sdkConfiguration,
}) async {
await _loadSplitSdk();
final config =
_buildConfig(apiKey, matchingKey, bucketingKey, sdkConfiguration);
// Create factory instance
this._factory = window.splitio!.SplitFactory.callAsFunction(null, config)
as JS_IBrowserSDK;
if (sdkConfiguration != null) {
if (sdkConfiguration.configurationMap['trafficType'] is String) {
this._trafficType = sdkConfiguration.configurationMap['trafficType'];
}
if (sdkConfiguration.configurationMap['impressionListener'] is bool) {
this._impressionListener =
sdkConfiguration.configurationMap['impressionListener'];
}
// Log warnings regarding unsupported configs. Not done in _buildConfig to reuse the factory logger
final unsupportedConfigs = [
'certificatePinningConfiguration',
'encryptionEnabled',
'eventsPerPush',
'persistentAttributesEnabled'
];
for (final configName in unsupportedConfigs) {
if (sdkConfiguration.configurationMap[configName] != null) {
this._factory.settings.log.warn.callAsFunction(
this._factory.settings.log,
'Config $configName is not supported by the Web package. This config will be ignored.'
.toJS);
}
}
}
return;
}
// Checks whether the Split Browser SDK was manually loaded (`window.splitio != null`).
// If not, loads it by injecting a script tag.
static Future<void> _loadSplitSdk() async {
if (window.splitio != null) {
return; // Already loaded
}
// Create and inject script tag
final script = document.createElement('script') as HTMLScriptElement;
script.type = 'text/javascript';
script.src = 'packages/splitio_web/web/split-browser-1.6.0.full.min.js';
// Wait for script to load
final completer = Completer<void>();
script.onload = (Event event) {
completer.complete();
}.toJS;
script.onerror = (Event event) {
completer.completeError(
Exception('Failed to load Split SDK, with error: $event'));
}.toJS;
document.head!.appendChild(script);
await completer.future;
if (window.splitio == null) {
throw Exception('Split Browser SDK failed to initialize after loading');
}
}
// Map SplitConfiguration to JS equivalent object
static JSObject _buildConfig(String apiKey, String matchingKey,
String? bucketingKey, SplitConfiguration? configuration) {
final config = JSObject();
final core = JSObject();
core.setProperty('authorizationKey'.toJS, apiKey.toJS);
core.setProperty('key'.toJS, _buildKey(matchingKey, bucketingKey));
config.setProperty('core'.toJS, core);
if (configuration != null) {
final scheduler = JSObject();
if (configuration.configurationMap.containsKey('featuresRefreshRate'))
scheduler.setProperty(
'featuresRefreshRate'.toJS,
(configuration.configurationMap['featuresRefreshRate'] as int)
.toJS);
if (configuration.configurationMap.containsKey('segmentsRefreshRate'))
scheduler.setProperty(
'segmentsRefreshRate'.toJS,
(configuration.configurationMap['segmentsRefreshRate'] as int)
.toJS);
if (configuration.configurationMap.containsKey('impressionsRefreshRate'))
scheduler.setProperty(
'impressionsRefreshRate'.toJS,
(configuration.configurationMap['impressionsRefreshRate'] as int)
.toJS);
if (configuration.configurationMap.containsKey('telemetryRefreshRate'))
scheduler.setProperty(
'telemetryRefreshRate'.toJS,
(configuration.configurationMap['telemetryRefreshRate'] as int)
.toJS);
if (configuration.configurationMap.containsKey('eventsQueueSize'))
scheduler.setProperty('eventsQueueSize'.toJS,
(configuration.configurationMap['eventsQueueSize'] as int).toJS);
if (configuration.configurationMap.containsKey('impressionsQueueSize'))
scheduler.setProperty(
'impressionsQueueSize'.toJS,
(configuration.configurationMap['impressionsQueueSize'] as int)
.toJS);
if (configuration.configurationMap.containsKey('eventFlushInterval'))
scheduler.setProperty('eventsPushRate'.toJS,
(configuration.configurationMap['eventFlushInterval'] as int).toJS);
config.setProperty('scheduler'.toJS, scheduler);
if (configuration.configurationMap.containsKey('streamingEnabled'))
config.setProperty('streamingEnabled'.toJS,
(configuration.configurationMap['streamingEnabled'] as bool).toJS);
final urls = JSObject();
if (configuration.configurationMap.containsKey('sdkEndpoint'))
urls.setProperty('sdk'.toJS,
(configuration.configurationMap['sdkEndpoint'] as String).toJS);
if (configuration.configurationMap.containsKey('eventsEndpoint'))
urls.setProperty('events'.toJS,
(configuration.configurationMap['eventsEndpoint'] as String).toJS);
if (configuration.configurationMap.containsKey('authServiceEndpoint'))
urls.setProperty(
'auth'.toJS,
(configuration.configurationMap['authServiceEndpoint'] as String)
.toJS);
if (configuration.configurationMap
.containsKey('streamingServiceEndpoint'))
urls.setProperty(
'streaming'.toJS,
(configuration.configurationMap['streamingServiceEndpoint']
as String)
.toJS);
if (configuration.configurationMap
.containsKey('telemetryServiceEndpoint'))
urls.setProperty(
'telemetry'.toJS,
(configuration.configurationMap['telemetryServiceEndpoint']
as String)
.toJS);
config.setProperty('urls'.toJS, urls);
final sync = JSObject();
if (configuration.configurationMap['impressionsMode'] != null) {
sync.setProperty(
'impressionsMode'.toJS,
(configuration.configurationMap['impressionsMode'] as String)
.toUpperCase()
.toJS);
}
if (configuration.configurationMap['syncEnabled'] != null) {
sync.setProperty('enabled'.toJS,
(configuration.configurationMap['syncEnabled'] as bool).toJS);
}
if (configuration.configurationMap['syncConfig'] != null) {
final syncConfig = configuration.configurationMap['syncConfig']
as Map<String, List<String>>;
final List<Map<String, dynamic>> splitFilters = [];
if (syncConfig['syncConfigNames'] != null &&
syncConfig['syncConfigNames']!.isNotEmpty) {
splitFilters
.add({'type': 'byName', 'values': syncConfig['syncConfigNames']});
}
if (syncConfig['syncConfigPrefixes'] != null &&
syncConfig['syncConfigPrefixes']!.isNotEmpty) {
splitFilters.add(
{'type': 'byPrefix', 'values': syncConfig['syncConfigPrefixes']});
}
if (syncConfig['syncConfigFlagSets'] != null &&
syncConfig['syncConfigFlagSets']!.isNotEmpty) {
splitFilters.add(
{'type': 'bySet', 'values': syncConfig['syncConfigFlagSets']});
}
sync.setProperty('splitFilters'.toJS, splitFilters.jsify());
}
config.setProperty('sync'.toJS, sync);
if (configuration.configurationMap['userConsent'] != null) {
config.setProperty(
'userConsent'.toJS,
(configuration.configurationMap['userConsent'] as String)
.toUpperCase()
.toJS);
}
final logLevel = configuration.configurationMap['logLevel'];
if (logLevel is String) {
final logger = logLevel == SplitLogLevel.verbose.toString() ||
logLevel == SplitLogLevel.debug.toString()
? window.splitio!.DebugLogger?.callAsFunction(null)
: logLevel == SplitLogLevel.info.toString()
? window.splitio!.InfoLogger?.callAsFunction(null)
: logLevel == SplitLogLevel.warning.toString()
? window.splitio!.WarnLogger?.callAsFunction(null)
: logLevel == SplitLogLevel.error.toString()
? window.splitio!.ErrorLogger?.callAsFunction(null)
: null;
if (logger != null) {
config.setProperty('debug'.toJS, logger); // Browser SDK
} else {
config.setProperty(
'debug'.toJS, logLevel.toUpperCase().toJS); // JS SDK
}
} else if (configuration.configurationMap['enableDebug'] == true) {
config.setProperty(
'debug'.toJS, window.splitio!.DebugLogger?.callAsFunction(null));
}
if (configuration.configurationMap['readyTimeout'] != null) {
final startup = JSObject();
startup.setProperty('readyTimeout'.toJS,
(configuration.configurationMap['readyTimeout'] as int).toJS);
config.setProperty('startup'.toJS, startup);
}
final storageOptions = JSObject();
storageOptions.setProperty('type'.toJS, 'LOCALSTORAGE'.toJS);
if (configuration.configurationMap['rolloutCacheConfiguration'] != null) {
final rolloutCacheConfiguration =
configuration.configurationMap['rolloutCacheConfiguration']
as Map<String, dynamic>;
if (rolloutCacheConfiguration['expirationDays'] != null) {
storageOptions.setProperty('expirationDays'.toJS,
(rolloutCacheConfiguration['expirationDays'] as int).toJS);
}
if (rolloutCacheConfiguration['clearOnInit'] != null) {
storageOptions.setProperty('clearOnInit'.toJS,
(rolloutCacheConfiguration['clearOnInit'] as bool).toJS);
}
}
if (window.splitio!.InLocalStorage != null) {
config.setProperty(
'storage'.toJS,
window.splitio!.InLocalStorage
?.callAsFunction(null, storageOptions)); // Browser SDK
} else {
config.setProperty('storage'.toJS, storageOptions); // JS SDK
}
}
return config;
}
static JSAny _buildKey(String matchingKey, String? bucketingKey) {
if (bucketingKey != null) {
final splitKey = JSObject();
splitKey.setProperty('matchingKey'.toJS, matchingKey.toJS);
splitKey.setProperty('bucketingKey'.toJS, bucketingKey.toJS);
return splitKey;
}
return matchingKey.toJS;
}
static String _buildKeyString(String matchingKey, String? bucketingKey) {
return bucketingKey == null ? matchingKey : '${matchingKey}_$bucketingKey';
}
@override
Future<void> getClient({
required String matchingKey,
required String? bucketingKey,
}) async {
await this._initFuture;
final key = _buildKeyString(matchingKey, bucketingKey);
if (_clients.containsKey(key)) {
return;
}
final client = this._factory.client.callAsFunction(
null, _buildKey(matchingKey, bucketingKey)) as JS_IBrowserClient;
_clients[key] = client;
}
Future<JS_IBrowserClient> _getClient({
required String matchingKey,
required String? bucketingKey,
}) async {
await getClient(matchingKey: matchingKey, bucketingKey: bucketingKey);
final key = _buildKeyString(matchingKey, bucketingKey);
return _clients[key]!;
}
JSAny? _convertValue(dynamic value, bool isAttributes) {
if (value is bool) return value.toJS;
if (value is num) return value.toJS; // covers int + double
if (value is String) return value.toJS;
// properties do not support lists and sets
if (isAttributes) {
if (value is List) return value.jsify();
if (value is Set) return value.jsify();
}
return null;
}
JSObject _convertMap(Map<String, dynamic> dartMap, bool isAttributes) {
final jsMap = JSObject();
dartMap.forEach((key, value) {
final jsValue = _convertValue(value, isAttributes);
if (jsValue != null) {
jsMap.setProperty(key.toJS, jsValue);
} else {
this._factory.settings.log.warn.callAsFunction(
null,
'Invalid ${isAttributes ? 'attribute' : 'property'} value: $value, for key: $key, will be ignored'
.toJS);
}
});
return jsMap;
}
JSObject _convertEvaluationOptions(EvaluationOptions evaluationOptions) {
final jsEvalOptions = JSObject();
if (evaluationOptions.properties.isNotEmpty) {
jsEvalOptions.setProperty(
'properties'.toJS, _convertMap(evaluationOptions.properties, false));
}
return jsEvalOptions;
}
@override
Future<String> getTreatment({
required String matchingKey,
required String? bucketingKey,
required String splitName,
Map<String, dynamic> attributes = const {},
EvaluationOptions evaluationOptions = const EvaluationOptions.empty(),
}) async {
final client = await _getClient(
matchingKey: matchingKey,
bucketingKey: bucketingKey,
);
final result = client.getTreatment.callAsFunction(
null,
splitName.toJS,
_convertMap(attributes, true),
_convertEvaluationOptions(evaluationOptions)) as JSString;
return result.toDart;
}
@override
Future<Map<String, String>> getTreatments({
required String matchingKey,
required String? bucketingKey,
required List<String> splitNames,
Map<String, dynamic> attributes = const {},
EvaluationOptions evaluationOptions = const EvaluationOptions.empty(),
}) async {
final client = await _getClient(
matchingKey: matchingKey,
bucketingKey: bucketingKey,
);
final result = client.getTreatments.callAsFunction(
null,
splitNames.jsify(),
_convertMap(attributes, true),
_convertEvaluationOptions(evaluationOptions)) as JSObject;
return jsTreatmentsToMap(result);
}
@override
Future<SplitResult> getTreatmentWithConfig({
required String matchingKey,
required String? bucketingKey,
required String splitName,
Map<String, dynamic> attributes = const {},
EvaluationOptions evaluationOptions = const EvaluationOptions.empty(),
}) async {
await this._initFuture;
final client = await _getClient(
matchingKey: matchingKey,
bucketingKey: bucketingKey,
);
final result = client.getTreatmentWithConfig.callAsFunction(
null,
splitName.toJS,
_convertMap(attributes, true),
_convertEvaluationOptions(evaluationOptions)) as JSObject;
return jsTreatmentWithConfigToSplitResult(result);
}
@override
Future<Map<String, SplitResult>> getTreatmentsWithConfig({
required String matchingKey,
required String? bucketingKey,
required List<String> splitNames,
Map<String, dynamic> attributes = const {},
EvaluationOptions evaluationOptions = const EvaluationOptions.empty(),
}) async {
final client = await _getClient(
matchingKey: matchingKey,
bucketingKey: bucketingKey,
);
final result = client.getTreatmentsWithConfig.callAsFunction(
null,
splitNames.jsify(),
_convertMap(attributes, true),
_convertEvaluationOptions(evaluationOptions)) as JSObject;
return jsTreatmentsWithConfigToMap(result);
}
Future<Map<String, String>> getTreatmentsByFlagSet(
{required String matchingKey,
required String? bucketingKey,
required String flagSet,
Map<String, dynamic> attributes = const {},
EvaluationOptions evaluationOptions = const EvaluationOptions.empty()}) async {
final client = await _getClient(
matchingKey: matchingKey,
bucketingKey: bucketingKey,
);
final result = client.getTreatmentsByFlagSet.callAsFunction(
null,
flagSet.toJS,
_convertMap(attributes, true),
_convertEvaluationOptions(evaluationOptions)) as JSObject;
return jsTreatmentsToMap(result);
}
Future<Map<String, String>> getTreatmentsByFlagSets(
{required String matchingKey,
required String? bucketingKey,
required List<String> flagSets,
Map<String, dynamic> attributes = const {},
EvaluationOptions evaluationOptions = const EvaluationOptions.empty()}) async {
final client = await _getClient(
matchingKey: matchingKey,
bucketingKey: bucketingKey,
);
final result = client.getTreatmentsByFlagSets.callAsFunction(
null,
flagSets.jsify(),
_convertMap(attributes, true),
_convertEvaluationOptions(evaluationOptions)) as JSObject;
return jsTreatmentsToMap(result);
}
Future<Map<String, SplitResult>> getTreatmentsWithConfigByFlagSet(
{required String matchingKey,
required String? bucketingKey,
required String flagSet,
Map<String, dynamic> attributes = const {},
EvaluationOptions evaluationOptions = const EvaluationOptions.empty()}) async {
final client = await _getClient(
matchingKey: matchingKey,
bucketingKey: bucketingKey,
);
final result = client.getTreatmentsWithConfigByFlagSet.callAsFunction(
null,
flagSet.toJS,
_convertMap(attributes, true),
_convertEvaluationOptions(evaluationOptions)) as JSObject;
return jsTreatmentsWithConfigToMap(result);
}
Future<Map<String, SplitResult>> getTreatmentsWithConfigByFlagSets(
{required String matchingKey,
required String? bucketingKey,
required List<String> flagSets,
Map<String, dynamic> attributes = const {},
EvaluationOptions evaluationOptions = const EvaluationOptions.empty()}) async {
final client = await _getClient(
matchingKey: matchingKey,
bucketingKey: bucketingKey,
);
final result = client.getTreatmentsWithConfigByFlagSets.callAsFunction(
null,
flagSets.jsify(),
_convertMap(attributes, true),
_convertEvaluationOptions(evaluationOptions)) as JSObject;
return jsTreatmentsWithConfigToMap(result);
}
}