@launchdarkly/js-sdk-common 2.32.1 → 2.32.3

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.
@@ -1,102 +1,63 @@
1
- /**
2
- * Converts a literal to a ref string.
3
- * @param value
4
- * @returns An escaped literal which can be used as a ref.
5
- */
6
1
  function toRefString(value) {
7
- return `/${value.replace(/~/g, '~0').replace(/\//g, '~1')}`;
2
+ return `/${value.replace(/~/g, "~0").replace(/\//g, "~1")}`;
8
3
  }
9
- /**
10
- * Produce a literal from a ref component.
11
- * @param ref
12
- * @returns A literal version of the ref.
13
- */
4
+
14
5
  function unescape(ref) {
15
- return ref.indexOf('~') ? ref.replace(/~1/g, '/').replace(/~0/g, '~') : ref;
6
+ return ref.indexOf("~") ? ref.replace(/~1/g, "/").replace(/~0/g, "~") : ref;
16
7
  }
8
+
17
9
  function getComponents(reference) {
18
- const referenceWithoutPrefix = reference.startsWith('/') ? reference.substring(1) : reference;
19
- return referenceWithoutPrefix.split('/').map((component) => unescape(component));
10
+ const referenceWithoutPrefix = reference.startsWith("/") ? reference.substring(1) : reference;
11
+ return referenceWithoutPrefix.split("/").map(component => unescape(component));
20
12
  }
13
+
21
14
  function isLiteral(reference) {
22
- return !reference.startsWith('/');
15
+ return !reference.startsWith("/");
23
16
  }
17
+
24
18
  function validate(reference) {
25
19
  return !reference.match(/\/\/|(^\/.*~[^0|^1])|~$/);
26
20
  }
21
+
27
22
  class AttributeReference {
28
- /**
29
- * Take an attribute reference string, or literal string, and produce
30
- * an attribute reference.
31
- *
32
- * Legacy user objects would have been created with names not
33
- * references. So, in that case, we need to use them as a component
34
- * without escaping them.
35
- *
36
- * e.g. A user could contain a custom attribute of `/a` which would
37
- * become the literal `a` if treated as a reference. Which would cause
38
- * it to no longer be redacted.
39
- * @param refOrLiteral The attribute reference string or literal string.
40
- * @param literal it true the value should be treated as a literal.
41
- */
42
23
  constructor(refOrLiteral, literal = false) {
43
24
  if (!literal) {
44
25
  this.redactionName = refOrLiteral;
45
- if (refOrLiteral === '' || refOrLiteral === '/' || !validate(refOrLiteral)) {
26
+ if (refOrLiteral === "" || refOrLiteral === "/" || !validate(refOrLiteral)) {
46
27
  this.isValid = false;
47
28
  this._components = [];
48
29
  return;
49
30
  }
50
31
  if (isLiteral(refOrLiteral)) {
51
- this._components = [refOrLiteral];
52
- }
53
- else if (refOrLiteral.indexOf('/', 1) < 0) {
54
- this._components = [unescape(refOrLiteral.slice(1))];
55
- }
56
- else {
32
+ this._components = [ refOrLiteral ];
33
+ } else if (refOrLiteral.indexOf("/", 1) < 0) {
34
+ this._components = [ unescape(refOrLiteral.slice(1)) ];
35
+ } else {
57
36
  this._components = getComponents(refOrLiteral);
58
37
  }
59
- // The items inside of '_meta' are not intended to be addressable.
60
- // Excluding it as a valid reference means that we can make it non-addressable
61
- // without having to copy all the attributes out of the context object
62
- // provided by the user.
63
- if (this._components[0] === '_meta') {
38
+ if (this._components[0] === "_meta") {
64
39
  this.isValid = false;
65
- }
66
- else {
40
+ } else {
67
41
  this.isValid = true;
68
42
  }
69
- }
70
- else {
43
+ } else {
71
44
  const literalVal = refOrLiteral;
72
- this._components = [literalVal];
73
- this.isValid = literalVal !== '';
74
- // Literals which start with '/' need escaped to prevent ambiguity.
75
- this.redactionName = literalVal.startsWith('/') ? toRefString(literalVal) : literalVal;
45
+ this._components = [ literalVal ];
46
+ this.isValid = literalVal !== "";
47
+ this.redactionName = literalVal.startsWith("/") ? toRefString(literalVal) : literalVal;
76
48
  }
77
49
  }
78
50
  get(target) {
79
- const { _components: components, isValid } = this;
51
+ const {_components: components, isValid: isValid} = this;
80
52
  if (!isValid) {
81
53
  return undefined;
82
54
  }
83
55
  let current = target;
84
- // This doesn't use a range based for loops, because those use generators.
85
- // See `no-restricted-syntax`.
86
- // It also doesn't use a collection method because this logic is more
87
- // straightforward with a loop.
88
56
  for (let index = 0; index < components.length; index += 1) {
89
57
  const component = components[index];
90
- if (current !== null &&
91
- current !== undefined &&
92
- // See https://eslint.org/docs/rules/no-prototype-builtins
93
- Object.prototype.hasOwnProperty.call(current, component) &&
94
- typeof current === 'object' &&
95
- // We do not want to allow indexing into an array.
96
- !Array.isArray(current)) {
58
+ if (current !== null && current !== undefined && Object.prototype.hasOwnProperty.call(current, component) && typeof current === "object" && !Array.isArray(current)) {
97
59
  current = current[component];
98
- }
99
- else {
60
+ } else {
100
61
  return undefined;
101
62
  }
102
63
  }
@@ -109,27 +70,18 @@ class AttributeReference {
109
70
  return this._components.length;
110
71
  }
111
72
  get isKind() {
112
- return this._components.length === 1 && this._components[0] === 'kind';
73
+ return this._components.length === 1 && this._components[0] === "kind";
113
74
  }
114
75
  compare(other) {
115
- return (this.depth === other.depth &&
116
- this._components.every((value, index) => value === other.getComponent(index)));
76
+ return this.depth === other.depth && this._components.every((value, index) => value === other.getComponent(index));
117
77
  }
118
78
  get components() {
119
- return [...this._components];
79
+ return [ ...this._components ];
120
80
  }
121
81
  }
122
- /**
123
- * For use as invalid references when deserializing Flag/Segment data.
124
- */
125
- AttributeReference.InvalidReference = new AttributeReference('');
126
82
 
127
- // The classes here are static, but needs to be instantiated to
128
- // support the generic functionality. Which is why we do not care about using
129
- // `this`
130
- /**
131
- * Validate a factory or instance.
132
- */
83
+ AttributeReference.InvalidReference = new AttributeReference("");
84
+
133
85
  class FactoryOrInstance {
134
86
  is(factoryOrInstance) {
135
87
  if (Array.isArray(factoryOrInstance)) {
@@ -137,15 +89,13 @@ class FactoryOrInstance {
137
89
  }
138
90
  const anyFactory = factoryOrInstance;
139
91
  const typeOfFactory = typeof anyFactory;
140
- return typeOfFactory === 'function' || typeOfFactory === 'object';
92
+ return typeOfFactory === "function" || typeOfFactory === "object";
141
93
  }
142
94
  getType() {
143
- return 'factory method or object';
95
+ return "factory method or object";
144
96
  }
145
97
  }
146
- /**
147
- * Validate a basic type.
148
- */
98
+
149
99
  class Type {
150
100
  constructor(typeName, example) {
151
101
  this._typeName = typeName;
@@ -161,12 +111,7 @@ class Type {
161
111
  return this._typeName;
162
112
  }
163
113
  }
164
- /**
165
- * Validate an array of the specified type.
166
- *
167
- * This does not validate instances of types. All class instances
168
- * of classes will simply objects.
169
- */
114
+
170
115
  class TypeArray {
171
116
  constructor(typeName, example) {
172
117
  this._typeName = typeName;
@@ -175,7 +120,7 @@ class TypeArray {
175
120
  is(u) {
176
121
  if (Array.isArray(u)) {
177
122
  if (u.length > 0) {
178
- return u.every((val) => typeof val === this.typeOf);
123
+ return u.every(val => typeof val === this.typeOf);
179
124
  }
180
125
  return true;
181
126
  }
@@ -185,9 +130,7 @@ class TypeArray {
185
130
  return this._typeName;
186
131
  }
187
132
  }
188
- /**
189
- * Validate a value is a number and is greater or eval than a minimum.
190
- */
133
+
191
134
  class NumberWithMinimum extends Type {
192
135
  constructor(min) {
193
136
  super(`number with minimum value of ${min}`, 0);
@@ -197,94 +140,71 @@ class NumberWithMinimum extends Type {
197
140
  return typeof u === this.typeOf && u >= this.min;
198
141
  }
199
142
  }
200
- /**
201
- * Validate a value is a string and it matches the given expression.
202
- */
143
+
203
144
  class StringMatchingRegex extends Type {
204
145
  constructor(expression) {
205
- super(`string matching ${expression}`, '');
146
+ super(`string matching ${expression}`, "");
206
147
  this.expression = expression;
207
148
  }
208
149
  is(u) {
209
- return typeof u === 'string' && !!u.match(this.expression);
150
+ return typeof u === "string" && !!u.match(this.expression);
210
151
  }
211
152
  }
212
- /**
213
- * Validate a value is a function.
214
- */
153
+
215
154
  class Function {
216
155
  is(u) {
217
- // We cannot inspect the parameters and there isn't really
218
- // a generic function type we can instantiate.
219
- // So the type guard is here just to make TS comfortable
220
- // calling something after using this guard.
221
- return typeof u === 'function';
156
+ return typeof u === "function";
222
157
  }
223
158
  getType() {
224
- return 'function';
159
+ return "function";
225
160
  }
226
161
  }
162
+
227
163
  class NullableBoolean {
228
164
  is(u) {
229
- return typeof u === 'boolean' || typeof u === 'undefined' || u === null;
165
+ return typeof u === "boolean" || typeof u === "undefined" || u === null;
230
166
  }
231
167
  getType() {
232
- return 'boolean | undefined | null';
168
+ return "boolean | undefined | null";
233
169
  }
234
170
  }
235
- // Our reference SDK, Go, parses date/time strings with the time.RFC3339Nano format.
236
- // This regex should match strings that are valid in that format, and no others.
237
- // Acceptable:
238
- // 2019-10-31T23:59:59Z, 2019-10-31T23:59:59.100Z,
239
- // 2019-10-31T23:59:59-07, 2019-10-31T23:59:59-07:00, etc.
240
- // Unacceptable: no "T", no time zone designation
171
+
241
172
  const DATE_REGEX = /^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d\d*)?(Z|[-+]\d\d(:\d\d)?)/;
242
- /**
243
- * Validate a value is a date. Values which are numbers are treated as dates and any string
244
- * which if compliant with `time.RFC3339Nano` is a date.
245
- */
173
+
246
174
  class DateValidator {
247
175
  is(u) {
248
- return typeof u === 'number' || (typeof u === 'string' && DATE_REGEX.test(u));
176
+ return typeof u === "number" || typeof u === "string" && DATE_REGEX.test(u);
249
177
  }
250
178
  getType() {
251
- return 'date';
179
+ return "date";
252
180
  }
253
181
  }
254
- /**
255
- * Validates that a string is a valid kind.
256
- */
182
+
257
183
  class KindValidator extends StringMatchingRegex {
258
184
  constructor() {
259
185
  super(/^(\w|\.|-)+$/);
260
186
  }
261
187
  is(u) {
262
- return super.is(u) && u !== 'kind';
188
+ return super.is(u) && u !== "kind";
263
189
  }
264
190
  }
265
- /**
266
- * Validate a value is a string matching one of the allowed values.
267
- */
191
+
268
192
  class OneOf {
269
193
  constructor(values) {
270
194
  this._values = values;
271
195
  }
272
196
  is(u) {
273
- return typeof u === 'string' && this._values.includes(u);
197
+ return typeof u === "string" && this._values.includes(u);
274
198
  }
275
199
  getType() {
276
- return this._values.join(' | ');
200
+ return this._values.join(" | ");
277
201
  }
278
202
  }
279
- /**
280
- * Returns true if the value is null or undefined.
281
- */
203
+
282
204
  function isNullish(value) {
283
205
  return value === null || value === undefined;
284
206
  }
285
- /**
286
- * A set of standard type validators.
287
- */
207
+
288
208
  class TypeValidators {
289
209
  static createTypeArray(typeName, example) {
290
210
  return new TypeArray(typeName, example);
@@ -299,168 +219,104 @@ class TypeValidators {
299
219
  return new OneOf(values);
300
220
  }
301
221
  }
302
- TypeValidators.String = new Type('string', '');
303
- TypeValidators.Number = new Type('number', 0);
304
- TypeValidators.ObjectOrFactory = new FactoryOrInstance();
305
- TypeValidators.Object = new Type('object', {});
306
- TypeValidators.StringArray = new TypeArray('string[]', '');
307
- TypeValidators.Boolean = new Type('boolean', true);
308
- TypeValidators.Function = new Function();
309
- TypeValidators.Date = new DateValidator();
310
- TypeValidators.Kind = new KindValidator();
311
- TypeValidators.NullableBoolean = new NullableBoolean();
312
-
313
- /**
314
- * Check if a context is a single kind context.
315
- * @param context
316
- * @returns true if the context is a single kind context.
317
- */
222
+
223
+ TypeValidators.String = new Type("string", "");
224
+
225
+ TypeValidators.Number = new Type("number", 0);
226
+
227
+ TypeValidators.ObjectOrFactory = new FactoryOrInstance;
228
+
229
+ TypeValidators.Object = new Type("object", {});
230
+
231
+ TypeValidators.StringArray = new TypeArray("string[]", "");
232
+
233
+ TypeValidators.Boolean = new Type("boolean", true);
234
+
235
+ TypeValidators.Function = new Function;
236
+
237
+ TypeValidators.Date = new DateValidator;
238
+
239
+ TypeValidators.Kind = new KindValidator;
240
+
241
+ TypeValidators.NullableBoolean = new NullableBoolean;
242
+
318
243
  function isSingleKind(context) {
319
- if ('kind' in context) {
320
- return TypeValidators.String.is(context.kind) && context.kind !== 'multi';
244
+ if ("kind" in context) {
245
+ return TypeValidators.String.is(context.kind) && context.kind !== "multi";
321
246
  }
322
247
  return false;
323
248
  }
324
- /**
325
- * Check if a context is a multi-kind context.
326
- * @param context
327
- * @returns true if it is a multi-kind context.
328
- */
249
+
329
250
  function isMultiKind(context) {
330
- if ('kind' in context) {
331
- return TypeValidators.String.is(context.kind) && context.kind === 'multi';
251
+ if ("kind" in context) {
252
+ return TypeValidators.String.is(context.kind) && context.kind === "multi";
332
253
  }
333
254
  return false;
334
255
  }
335
- /**
336
- * Check if a context is a legacy user context.
337
- * @param context
338
- * @returns true if it is a legacy user context.
339
- */
256
+
340
257
  function isLegacyUser(context) {
341
- return !('kind' in context) || context.kind === null || context.kind === undefined;
258
+ return !("kind" in context) || context.kind === null || context.kind === undefined;
342
259
  }
343
260
 
344
- /**
345
- * Given some object to serialize product a canonicalized JSON string.
346
- * https://www.rfc-editor.org/rfc/rfc8785.html
347
- *
348
- * We do not support custom toJSON methods on objects. Objects should be limited to basic types.
349
- *
350
- * @param object The object to serialize.
351
- */
352
261
  function canonicalize(object, visited = []) {
353
- // For JavaScript the default JSON serialization will produce canonicalized output for basic types.
354
- if (object === null || typeof object !== 'object') {
262
+ if (object === null || typeof object !== "object") {
355
263
  return JSON.stringify(object);
356
264
  }
357
265
  if (visited.includes(object)) {
358
- throw new Error('Cycle detected');
266
+ throw new Error("Cycle detected");
359
267
  }
360
268
  if (Array.isArray(object)) {
361
- const values = object
362
- .map((item) => canonicalize(item, [...visited, object]))
363
- .map((item) => (item === undefined ? 'null' : item));
364
- return `[${values.join(',')}]`;
365
- }
366
- const values = Object.keys(object)
367
- .sort()
368
- .map((key) => {
369
- const value = canonicalize(object[key], [...visited, object]);
269
+ const values = object.map(item => canonicalize(item, [ ...visited, object ])).map(item => item === undefined ? "null" : item);
270
+ return `[${values.join(",")}]`;
271
+ }
272
+ const values = Object.keys(object).sort().map(key => {
273
+ const value = canonicalize(object[key], [ ...visited, object ]);
370
274
  if (value !== undefined) {
371
275
  return `${JSON.stringify(key)}:${value}`;
372
276
  }
373
277
  return undefined;
374
- })
375
- .filter((item) => item !== undefined);
376
- return `{${values.join(',')}}`;
377
- }
378
-
379
- // The general strategy for the context is to transform the passed in context
380
- // as little as possible. We do convert the legacy users to a single kind
381
- // context, but we do not translate all passed contexts into a rigid structure.
382
- // The context will have to be copied for events, but we want to avoid any
383
- // copying that we can.
384
- // So we validate that the information we are given is correct, and then we
385
- // just proxy calls with a nicely typed interface.
386
- // This is to reduce work on the hot-path. Later, for event processing, deeper
387
- // cloning of the context will be done.
388
- // When no kind is specified, then this kind will be used.
389
- const DEFAULT_KIND = 'user';
390
- // The API allows for calling with an `LDContext` which is
391
- // `LDUser | LDSingleKindContext | LDMultiKindContext`. When ingesting a context
392
- // first the type must be determined to allow us to put it into a consistent type.
393
- /**
394
- * The partial URL encoding is needed because : is a valid character in context keys.
395
- *
396
- * Partial encoding is the replacement of all colon (:) characters with the URL
397
- * encoded equivalent (%3A) and all percent (%) characters with the URL encoded
398
- * equivalent (%25).
399
- * @param key The key to encode.
400
- * @returns Partially URL encoded key.
401
- */
278
+ }).filter(item => item !== undefined);
279
+ return `{${values.join(",")}}`;
280
+ }
281
+
282
+ const DEFAULT_KIND = "user";
283
+
402
284
  function encodeKey(key) {
403
- if (key.includes('%') || key.includes(':')) {
404
- return key.replace(/%/g, '%25').replace(/:/g, '%3A');
285
+ if (key.includes("%") || key.includes(":")) {
286
+ return key.replace(/%/g, "%25").replace(/:/g, "%3A");
405
287
  }
406
288
  return key;
407
289
  }
408
- /**
409
- * Check if the given value is a LDContextCommon.
410
- * @param kindOrContext
411
- * @returns true if it is an LDContextCommon
412
- *
413
- * Due to a limitation in the expressiveness of these highly polymorphic types any field
414
- * in a multi-kind context can either be a context or 'kind'. So we need to re-assure
415
- * the compiler that it isn't the word multi.
416
- *
417
- * Because we do not allow top level values in a multi-kind context we can validate
418
- * that as well.
419
- */
290
+
420
291
  function isContextCommon(kindOrContext) {
421
292
  return kindOrContext && TypeValidators.Object.is(kindOrContext);
422
293
  }
423
- /**
424
- * Validate a context kind.
425
- * @param kind
426
- * @returns true if the kind is valid.
427
- */
294
+
428
295
  function validKind(kind) {
429
296
  return TypeValidators.Kind.is(kind);
430
297
  }
431
- /**
432
- * Validate a context key.
433
- * @param key
434
- * @returns true if the key is valid.
435
- */
298
+
436
299
  function validKey(key) {
437
- return TypeValidators.String.is(key) && key !== '';
300
+ return TypeValidators.String.is(key) && key !== "";
438
301
  }
302
+
439
303
  function processPrivateAttributes(privateAttributes, literals = false) {
440
304
  if (privateAttributes) {
441
- return privateAttributes.map((privateAttribute) => new AttributeReference(privateAttribute, literals));
305
+ return privateAttributes.map(privateAttribute => new AttributeReference(privateAttribute, literals));
442
306
  }
443
307
  return [];
444
308
  }
309
+
445
310
  function defined(value) {
446
311
  return value !== null && value !== undefined;
447
312
  }
448
- /**
449
- * Convert a legacy user to a single kind context.
450
- * @param user
451
- * @returns A single kind context.
452
- */
313
+
453
314
  function legacyToSingleKind(user) {
454
315
  const singleKindContext = {
455
- // Key was coerced to a string for eval and events, so we can do that up-front.
456
- ...(user.custom || []),
457
- kind: 'user',
458
- key: String(user.key),
316
+ ...user.custom || [],
317
+ kind: "user",
318
+ key: String(user.key)
459
319
  };
460
- // For legacy users we never established a difference between null
461
- // and undefined for inputs. Because anonymous can be used in evaluations
462
- // we would want it to not possibly match true/false unless defined.
463
- // Which is different than coercing a null/undefined anonymous as `false`.
464
320
  if (defined(user.anonymous)) {
465
321
  const anonymous = !!user.anonymous;
466
322
  delete singleKindContext.anonymous;
@@ -489,26 +345,13 @@ function legacyToSingleKind(user) {
489
345
  }
490
346
  if (user.privateAttributeNames !== null && user.privateAttributeNames !== undefined) {
491
347
  singleKindContext._meta = {
492
- privateAttributes: user.privateAttributeNames,
348
+ privateAttributes: user.privateAttributeNames
493
349
  };
494
350
  }
495
- // We are not pulling private attributes over because we will serialize
496
- // those from attribute references for events.
497
351
  return singleKindContext;
498
352
  }
499
- /**
500
- * Container for a context/contexts. Because contexts come from external code
501
- * they must be thoroughly validated and then formed to comply with
502
- * the type system.
503
- */
353
+
504
354
  class Context {
505
- /**
506
- * Contexts should be created using the static factory method {@link Context.fromLDContext}.
507
- * @param kind The kind of the context.
508
- *
509
- * The factory methods are static functions within the class because they access private
510
- * implementation details, so they cannot be free functions.
511
- */
512
355
  constructor(valid, kind, message) {
513
356
  this._isMulti = false;
514
357
  this._isUser = false;
@@ -525,7 +368,7 @@ class Context {
525
368
  if (!context || !reference.isValid) {
526
369
  return undefined;
527
370
  }
528
- if (reference.depth === 1 && reference.getComponent(0) === 'anonymous') {
371
+ if (reference.depth === 1 && reference.getComponent(0) === "anonymous") {
529
372
  return !!context?.anonymous;
530
373
  }
531
374
  return reference.get(context);
@@ -540,13 +383,13 @@ class Context {
540
383
  return undefined;
541
384
  }
542
385
  static _fromMultiKindContext(context) {
543
- const kinds = Object.keys(context).filter((key) => key !== 'kind');
386
+ const kinds = Object.keys(context).filter(key => key !== "kind");
544
387
  const kindsValid = kinds.every(validKind);
545
388
  if (!kinds.length) {
546
- return Context._contextForError('multi', 'A multi-kind context must contain at least one kind');
389
+ return Context._contextForError("multi", "A multi-kind context must contain at least one kind");
547
390
  }
548
391
  if (!kindsValid) {
549
- return Context._contextForError('multi', 'Context contains invalid kinds');
392
+ return Context._contextForError("multi", "Context contains invalid kinds");
550
393
  }
551
394
  const privateAttributes = {};
552
395
  let contextsAreObjects = true;
@@ -555,27 +398,26 @@ class Context {
555
398
  if (isContextCommon(singleContext)) {
556
399
  acc[kind] = singleContext;
557
400
  privateAttributes[kind] = processPrivateAttributes(singleContext._meta?.privateAttributes);
558
- }
559
- else {
560
- // No early break isn't the most efficient, but it is an error condition.
401
+ } else {
561
402
  contextsAreObjects = false;
562
403
  }
563
404
  return acc;
564
405
  }, {});
565
406
  if (!contextsAreObjects) {
566
- return Context._contextForError('multi', 'Context contained contexts that were not objects');
407
+ return Context._contextForError("multi", "Context contained contexts that were not objects");
567
408
  }
568
- if (!Object.values(contexts).every((part) => validKey(part.key))) {
569
- return Context._contextForError('multi', 'Context contained invalid keys');
409
+ if (!Object.values(contexts).every(part => validKey(part.key))) {
410
+ return Context._contextForError("multi", "Context contained invalid keys");
570
411
  }
571
- // There was only a single kind in the multi-kind context.
572
- // So we can just translate this to a single-kind context.
573
412
  if (kinds.length === 1) {
574
413
  const kind = kinds[0];
575
414
  const created = new Context(true, kind);
576
- created._context = { ...contexts[kind], kind };
415
+ created._context = {
416
+ ...contexts[kind],
417
+ kind: kind
418
+ };
577
419
  created._privateAttributeReferences = privateAttributes;
578
- created._isUser = kind === 'user';
420
+ created._isUser = kind === "user";
579
421
  return created;
580
422
  }
581
423
  const created = new Context(true, context.kind);
@@ -585,49 +427,41 @@ class Context {
585
427
  return created;
586
428
  }
587
429
  static _fromSingleKindContext(context) {
588
- const { key, kind } = context;
430
+ const {key: key, kind: kind} = context;
589
431
  const kindValid = validKind(kind);
590
432
  const keyValid = validKey(key);
591
433
  if (!kindValid) {
592
- return Context._contextForError(kind ?? 'unknown', 'The kind was not valid for the context');
434
+ return Context._contextForError(kind ?? "unknown", "The kind was not valid for the context");
593
435
  }
594
436
  if (!keyValid) {
595
- return Context._contextForError(kind, 'The key for the context was not valid');
437
+ return Context._contextForError(kind, "The key for the context was not valid");
596
438
  }
597
- // The JSON interfaces uses dangling _.
598
439
  const privateAttributeReferences = processPrivateAttributes(context._meta?.privateAttributes);
599
440
  const created = new Context(true, kind);
600
- created._isUser = kind === 'user';
441
+ created._isUser = kind === "user";
601
442
  created._context = context;
602
443
  created._privateAttributeReferences = {
603
- [kind]: privateAttributeReferences,
444
+ [kind]: privateAttributeReferences
604
445
  };
605
446
  return created;
606
447
  }
607
448
  static _fromLegacyUser(context) {
608
449
  const keyValid = context.key !== undefined && context.key !== null;
609
- // For legacy users we allow empty keys.
610
450
  if (!keyValid) {
611
- return Context._contextForError('user', 'The key for the context was not valid');
451
+ return Context._contextForError("user", "The key for the context was not valid");
612
452
  }
613
- const created = new Context(true, 'user');
453
+ const created = new Context(true, "user");
614
454
  created._isUser = true;
615
455
  created._wasLegacy = true;
616
456
  created._context = legacyToSingleKind(context);
617
457
  created._privateAttributeReferences = {
618
- user: processPrivateAttributes(context.privateAttributeNames, true),
458
+ user: processPrivateAttributes(context.privateAttributeNames, true)
619
459
  };
620
460
  return created;
621
461
  }
622
- /**
623
- * Attempt to create a {@link Context} from an {@link LDContext}.
624
- * @param context The input context to create a Context from.
625
- * @returns a {@link Context}, if the context was not valid, then the returned contexts `valid`
626
- * property will be false.
627
- */
628
462
  static fromLDContext(context) {
629
463
  if (!context) {
630
- return Context._contextForError('unknown', 'No context specified. Returning default value');
464
+ return Context._contextForError("unknown", "No context specified. Returning default value");
631
465
  }
632
466
  if (isSingleKind(context)) {
633
467
  return Context._fromSingleKindContext(context);
@@ -638,13 +472,8 @@ class Context {
638
472
  if (isLegacyUser(context)) {
639
473
  return Context._fromLegacyUser(context);
640
474
  }
641
- return Context._contextForError('unknown', 'Context was not of a valid kind');
475
+ return Context._contextForError("unknown", "Context was not of a valid kind");
642
476
  }
643
- /**
644
- * Creates a {@link LDContext} from a {@link Context}.
645
- * @param context to be converted
646
- * @returns an {@link LDContext} if input was valid, otherwise undefined
647
- */
648
477
  static toLDContext(context) {
649
478
  if (!context.valid) {
650
479
  return undefined;
@@ -654,68 +483,42 @@ class Context {
654
483
  return contexts[0][1];
655
484
  }
656
485
  const result = {
657
- kind: 'multi',
486
+ kind: "multi"
658
487
  };
659
- contexts.forEach((kindAndContext) => {
488
+ contexts.forEach(kindAndContext => {
660
489
  const kind = kindAndContext[0];
661
490
  const nestedContext = kindAndContext[1];
662
491
  result[kind] = nestedContext;
663
492
  });
664
493
  return result;
665
494
  }
666
- /**
667
- * Attempt to get a value for the given context kind using the given reference.
668
- * @param reference The reference to the value to get.
669
- * @param kind The kind of the context to get the value for.
670
- * @returns a value or `undefined` if one is not found.
671
- */
672
495
  valueForKind(reference, kind = DEFAULT_KIND) {
673
496
  if (reference.isKind) {
674
497
  return this.kinds;
675
498
  }
676
499
  return Context._getValueFromContext(reference, this._contextForKind(kind));
677
500
  }
678
- /**
679
- * Attempt to get a key for the specified kind.
680
- * @param kind The kind to get a key for.
681
- * @returns The key for the specified kind, or undefined.
682
- */
683
501
  key(kind = DEFAULT_KIND) {
684
502
  return this._contextForKind(kind)?.key;
685
503
  }
686
- /**
687
- * True if this is a multi-kind context.
688
- */
689
504
  get isMultiKind() {
690
505
  return this._isMulti;
691
506
  }
692
- /**
693
- * Get the canonical key for this context.
694
- */
695
507
  get canonicalKey() {
696
508
  if (this._isUser) {
697
509
  return this._context.key;
698
510
  }
699
511
  if (this._isMulti) {
700
- return Object.keys(this._contexts)
701
- .sort()
702
- .map((key) => `${key}:${encodeKey(this._contexts[key].key)}`)
703
- .join(':');
512
+ return Object.keys(this._contexts).sort().map(key => `${key}:${encodeKey(this._contexts[key].key)}`).join(":");
704
513
  }
705
514
  return `${this.kind}:${encodeKey(this._context.key)}`;
706
515
  }
707
- /**
708
- * Get the kinds of this context.
709
- */
710
516
  get kinds() {
711
517
  if (this._isMulti) {
712
518
  return Object.keys(this._contexts);
713
519
  }
714
- return [this.kind];
520
+ return [ this.kind ];
715
521
  }
716
- /**
717
- * Get the kinds, and their keys, for this context.
718
- */
719
522
  get kindsAndKeys() {
720
523
  if (this._isMulti) {
721
524
  return Object.entries(this._contexts).reduce((acc, [kind, context]) => {
@@ -723,39 +526,22 @@ class Context {
723
526
  return acc;
724
527
  }, {});
725
528
  }
726
- return { [this.kind]: this._context.key };
529
+ return {
530
+ [this.kind]: this._context.key
531
+ };
727
532
  }
728
- /**
729
- * Get the attribute references.
730
- *
731
- * @param kind
732
- */
733
533
  privateAttributes(kind) {
734
534
  return this._privateAttributeReferences?.[kind] || [];
735
535
  }
736
- /**
737
- * Get the underlying context objects from this context.
738
- *
739
- * This method is intended to be used in event generation.
740
- *
741
- * The returned objects should not be modified.
742
- */
743
536
  getContexts() {
744
537
  if (this._isMulti) {
745
538
  return Object.entries(this._contexts);
746
539
  }
747
- return [[this.kind, this._context]];
540
+ return [ [ this.kind, this._context ] ];
748
541
  }
749
542
  get legacy() {
750
543
  return this._wasLegacy;
751
544
  }
752
- /**
753
- * Get the serialized canonical JSON for this context. This is not filtered for use in events.
754
- *
755
- * This method will cache the result.
756
- *
757
- * @returns The serialized canonical JSON or undefined if it cannot be serialized.
758
- */
759
545
  canonicalUnfilteredJson() {
760
546
  if (!this.valid) {
761
547
  return undefined;
@@ -765,86 +551,65 @@ class Context {
765
551
  }
766
552
  try {
767
553
  this._cachedCanonicalJson = canonicalize(Context.toLDContext(this));
768
- }
769
- catch {
770
- // Indicated by undefined being returned.
771
- }
554
+ } catch {}
772
555
  return this._cachedCanonicalJson;
773
556
  }
774
557
  }
558
+
775
559
  Context.UserKind = DEFAULT_KIND;
776
560
 
777
- // _meta is part of the specification.
778
- // These attributes cannot be removed via a private attribute.
779
- const protectedAttributes = ['key', 'kind', '_meta', 'anonymous'].map((str) => new AttributeReference(str, true));
780
- // Attributes that should be stringified for legacy users.
781
- const legacyTopLevelCopyAttributes = [
782
- 'name',
783
- 'ip',
784
- 'firstName',
785
- 'lastName',
786
- 'email',
787
- 'avatar',
788
- 'country',
789
- ];
561
+ const protectedAttributes = [ "key", "kind", "_meta", "anonymous" ].map(str => new AttributeReference(str, true));
562
+
563
+ const legacyTopLevelCopyAttributes = [ "name", "ip", "firstName", "lastName", "email", "avatar", "country" ];
564
+
790
565
  function compare(a, b) {
791
566
  return a.depth === b.length && b.every((value, index) => value === a.getComponent(index));
792
567
  }
568
+
793
569
  function cloneWithRedactions(target, references) {
794
570
  const stack = [];
795
571
  const cloned = {};
796
572
  const excluded = [];
797
- stack.push(...Object.keys(target).map((key) => ({
798
- key,
799
- ptr: [key],
573
+ stack.push(...Object.keys(target).map(key => ({
574
+ key: key,
575
+ ptr: [ key ],
800
576
  source: target,
801
577
  parent: cloned,
802
- visited: [target],
578
+ visited: [ target ]
803
579
  })));
804
580
  while (stack.length) {
805
581
  const item = stack.pop();
806
- const redactRef = references.find((ref) => compare(ref, item.ptr));
582
+ const redactRef = references.find(ref => compare(ref, item.ptr));
807
583
  if (!redactRef) {
808
584
  const value = item.source[item.key];
809
- // Handle null because it overlaps with object, which we will want to handle later.
810
585
  if (value === null) {
811
586
  item.parent[item.key] = value;
812
- }
813
- else if (Array.isArray(value)) {
814
- item.parent[item.key] = [...value];
815
- }
816
- else if (typeof value === 'object') {
817
- // Arrays and null must already be handled.
818
- // Prevent cycles by not visiting the same object
819
- // with in the same branch. Different branches
820
- // may contain the same object.
821
- //
822
- // Same object visited twice in different branches.
823
- // A -> B -> D
824
- // -> C -> D
825
- // This is fine, which is why it doesn't just check if the object
826
- // was visited ever.
587
+ } else if (Array.isArray(value)) {
588
+ item.parent[item.key] = [ ...value ];
589
+ } else if (typeof value === "object") {
827
590
  if (!item.visited.includes(value)) {
828
591
  item.parent[item.key] = {};
829
- stack.push(...Object.keys(value).map((key) => ({
830
- key,
831
- ptr: [...item.ptr, key],
592
+ stack.push(...Object.keys(value).map(key => ({
593
+ key: key,
594
+ ptr: [ ...item.ptr, key ],
832
595
  source: value,
833
596
  parent: item.parent[item.key],
834
- visited: [...item.visited, value],
597
+ visited: [ ...item.visited, value ]
835
598
  })));
836
599
  }
837
- }
838
- else {
600
+ } else {
839
601
  item.parent[item.key] = value;
840
602
  }
841
- }
842
- else {
603
+ } else {
843
604
  excluded.push(redactRef.redactionName);
844
605
  }
845
606
  }
846
- return { cloned, excluded: excluded.sort() };
607
+ return {
608
+ cloned: cloned,
609
+ excluded: excluded.sort()
610
+ };
847
611
  }
612
+
848
613
  class ContextFilter {
849
614
  constructor(_allAttributesPrivate, _privateAttributes) {
850
615
  this._allAttributesPrivate = _allAttributesPrivate;
@@ -856,7 +621,7 @@ class ContextFilter {
856
621
  return this._filterSingleKind(context, contexts[0][1], contexts[0][0], redactAnonymousAttributes);
857
622
  }
858
623
  const filteredMulti = {
859
- kind: 'multi',
624
+ kind: "multi"
860
625
  };
861
626
  contexts.forEach(([kind, single]) => {
862
627
  filteredMulti[kind] = this._filterSingleKind(context, single, kind, redactAnonymousAttributes);
@@ -864,15 +629,13 @@ class ContextFilter {
864
629
  return filteredMulti;
865
630
  }
866
631
  _getAttributesToFilter(context, single, kind, redactAllAttributes) {
867
- return (redactAllAttributes
868
- ? Object.keys(single).map((k) => new AttributeReference(k, true))
869
- : [...this._privateAttributes, ...context.privateAttributes(kind)]).filter((attr) => !protectedAttributes.some((protectedAttr) => protectedAttr.compare(attr)));
632
+ return (redactAllAttributes ? Object.keys(single).map(k => new AttributeReference(k, true)) : [ ...this._privateAttributes, ...context.privateAttributes(kind) ]).filter(attr => !protectedAttributes.some(protectedAttr => protectedAttr.compare(attr)));
870
633
  }
871
634
  _filterSingleKind(context, single, kind, redactAnonymousAttributes) {
872
- const redactAllAttributes = this._allAttributesPrivate || (redactAnonymousAttributes && single.anonymous === true);
873
- const { cloned, excluded } = cloneWithRedactions(single, this._getAttributesToFilter(context, single, kind, redactAllAttributes));
635
+ const redactAllAttributes = this._allAttributesPrivate || redactAnonymousAttributes && single.anonymous === true;
636
+ const {cloned: cloned, excluded: excluded} = cloneWithRedactions(single, this._getAttributesToFilter(context, single, kind, redactAllAttributes));
874
637
  if (context.legacy) {
875
- legacyTopLevelCopyAttributes.forEach((name) => {
638
+ legacyTopLevelCopyAttributes.forEach(name => {
876
639
  if (name in cloned) {
877
640
  cloned[name] = String(cloned[name]);
878
641
  }
@@ -894,24 +657,15 @@ class ContextFilter {
894
657
  }
895
658
  }
896
659
 
897
- const MAX_RETRY_DELAY = 30 * 1000; // Maximum retry delay 30 seconds.
898
- const JITTER_RATIO = 0.5; // Delay should be 50%-100% of calculated time.
899
- /**
900
- * Implements exponential backoff and jitter. This class tracks successful connections and failures
901
- * and produces a retry delay.
902
- *
903
- * It does not start any timers or directly control a connection.
904
- *
905
- * The backoff follows an exponential backoff scheme with 50% jitter starting at
906
- * initialRetryDelayMillis and capping at MAX_RETRY_DELAY. If RESET_INTERVAL has elapsed after a
907
- * success, without an intervening faulure, then the backoff is reset to initialRetryDelayMillis.
908
- */
660
+ const MAX_RETRY_DELAY = 30 * 1e3;
661
+
662
+ const JITTER_RATIO = .5;
663
+
909
664
  class DefaultBackoff {
910
665
  constructor(initialRetryDelayMillis, _retryResetIntervalMillis, _random = Math.random) {
911
666
  this._retryResetIntervalMillis = _retryResetIntervalMillis;
912
667
  this._random = _random;
913
668
  this._retryCount = 0;
914
- // Initial retry delay cannot be 0.
915
669
  this._initialRetryDelayMillis = Math.max(1, initialRetryDelayMillis);
916
670
  this._maxExponent = Math.ceil(Math.log2(MAX_RETRY_DELAY / this._initialRetryDelayMillis));
917
671
  }
@@ -923,28 +677,11 @@ class DefaultBackoff {
923
677
  _jitter(computedDelayMillis) {
924
678
  return computedDelayMillis - Math.trunc(this._random() * JITTER_RATIO * computedDelayMillis);
925
679
  }
926
- /**
927
- * This function should be called when a connection attempt is successful.
928
- *
929
- * @param timeStampMs The time of the success. Used primarily for testing, when not provided
930
- * the current time is used.
931
- */
932
680
  success(timeStampMs = Date.now()) {
933
681
  this._activeSince = timeStampMs;
934
682
  }
935
- /**
936
- * This function should be called when a connection fails. It returns the a delay, in
937
- * milliseconds, after which a reconnection attempt should be made.
938
- *
939
- * @param timeStampMs The time of the success. Used primarily for testing, when not provided
940
- * the current time is used.
941
- * @returns The delay before the next connection attempt.
942
- */
943
683
  fail(timeStampMs = Date.now()) {
944
- // If the last successful connection was active for more than the RESET_INTERVAL, then we
945
- // return to the initial retry delay.
946
- if (this._activeSince !== undefined &&
947
- timeStampMs - this._activeSince > this._retryResetIntervalMillis) {
684
+ if (this._activeSince !== undefined && timeStampMs - this._activeSince > this._retryResetIntervalMillis) {
948
685
  this._retryCount = 0;
949
686
  }
950
687
  this._activeSince = undefined;
@@ -954,11 +691,6 @@ class DefaultBackoff {
954
691
  }
955
692
  }
956
693
 
957
- /**
958
- * Handler that connects the current {@link DataSource} to the {@link CompositeDataSource}. A single
959
- * {@link CallbackHandler} should only be given to one {@link DataSource}. Use {@link disable()} to
960
- * prevent additional callback events.
961
- */
962
694
  class CallbackHandler {
963
695
  constructor(_dataCallback, _statusCallback) {
964
696
  this._dataCallback = _dataCallback;
@@ -982,35 +714,21 @@ class CallbackHandler {
982
714
  }
983
715
  }
984
716
 
985
- // TODO: refactor client-sdk to use this enum
986
717
  var DataSourceState;
987
- (function (DataSourceState) {
988
- // Positive confirmation of connection/data receipt
718
+
719
+ (function(DataSourceState) {
989
720
  DataSourceState[DataSourceState["Valid"] = 0] = "Valid";
990
- // Spinning up to make first connection attempt
991
721
  DataSourceState[DataSourceState["Initializing"] = 1] = "Initializing";
992
- // Transient issue, automatic retry is expected
993
722
  DataSourceState[DataSourceState["Interrupted"] = 2] = "Interrupted";
994
- // Data source was closed and will not retry automatically.
995
723
  DataSourceState[DataSourceState["Closed"] = 3] = "Closed";
996
724
  })(DataSourceState || (DataSourceState = {}));
997
725
 
998
- /**
999
- * Helper class for {@link CompositeDataSource} to manage iterating on data sources and removing them on the fly.
1000
- */
1001
726
  class DataSourceList {
1002
- /**
1003
- * @param circular whether to loop off the end of the list back to the start
1004
- * @param initialList of content
1005
- */
1006
727
  constructor(circular, initialList) {
1007
- this._list = initialList ? [...initialList] : [];
728
+ this._list = initialList ? [ ...initialList ] : [];
1008
729
  this._circular = circular;
1009
730
  this._pos = 0;
1010
731
  }
1011
- /**
1012
- * Returns the current head and then iterates.
1013
- */
1014
732
  next() {
1015
733
  if (this._list.length <= 0 || this._pos >= this._list.length) {
1016
734
  return undefined;
@@ -1018,27 +736,15 @@ class DataSourceList {
1018
736
  const result = this._list[this._pos];
1019
737
  if (this._circular) {
1020
738
  this._pos = (this._pos + 1) % this._list.length;
1021
- }
1022
- else {
739
+ } else {
1023
740
  this._pos += 1;
1024
741
  }
1025
742
  return result;
1026
743
  }
1027
- /**
1028
- * Replaces all elements with the provided list and resets the position of head to the start.
1029
- *
1030
- * @param input that will replace existing list
1031
- */
1032
744
  replace(input) {
1033
- this._list = [...input];
745
+ this._list = [ ...input ];
1034
746
  this._pos = 0;
1035
747
  }
1036
- /**
1037
- * Removes the provided element from the list. If the removed element was the head, head moves to next. Consider head may be undefined if list is empty after removal.
1038
- *
1039
- * @param element to remove
1040
- * @returns true if element was removed
1041
- */
1042
748
  remove(element) {
1043
749
  const index = this._list.indexOf(element);
1044
750
  if (index < 0) {
@@ -1046,7 +752,6 @@ class DataSourceList {
1046
752
  }
1047
753
  this._list.splice(index, 1);
1048
754
  if (this._list.length > 0) {
1049
- // if removed item was before head, adjust head
1050
755
  if (index < this._pos) {
1051
756
  this._pos -= 1;
1052
757
  }
@@ -1056,27 +761,15 @@ class DataSourceList {
1056
761
  }
1057
762
  return true;
1058
763
  }
1059
- /**
1060
- * Reset the head position to the start of the list.
1061
- */
1062
764
  reset() {
1063
765
  this._pos = 0;
1064
766
  }
1065
- /**
1066
- * @returns the current head position in the list, 0 indexed.
1067
- */
1068
767
  pos() {
1069
768
  return this._pos;
1070
769
  }
1071
- /**
1072
- * @returns the current length of the list
1073
- */
1074
770
  length() {
1075
771
  return this._list.length;
1076
772
  }
1077
- /**
1078
- * Clears the list and resets head.
1079
- */
1080
773
  clear() {
1081
774
  this._list = [];
1082
775
  this._pos = 0;
@@ -1086,340 +779,285 @@ class DataSourceList {
1086
779
  class LDFileDataSourceError extends Error {
1087
780
  constructor(message) {
1088
781
  super(message);
1089
- this.name = 'LaunchDarklyFileDataSourceError';
782
+ this.name = "LaunchDarklyFileDataSourceError";
1090
783
  }
1091
784
  }
785
+
1092
786
  class LDPollingError extends Error {
1093
787
  constructor(kind, message, status, recoverable = true) {
1094
788
  super(message);
1095
789
  this.kind = kind;
1096
790
  this.status = status;
1097
- this.name = 'LaunchDarklyPollingError';
791
+ this.name = "LaunchDarklyPollingError";
1098
792
  this.recoverable = recoverable;
1099
793
  }
1100
794
  }
795
+
1101
796
  class LDStreamingError extends Error {
1102
797
  constructor(kind, message, code, recoverable = true) {
1103
798
  super(message);
1104
799
  this.kind = kind;
1105
800
  this.code = code;
1106
- this.name = 'LaunchDarklyStreamingError';
801
+ this.name = "LaunchDarklyStreamingError";
1107
802
  this.recoverable = recoverable;
1108
803
  }
1109
804
  }
1110
- /**
1111
- * This is a short term error and will be removed once FDv2 adoption is sufficient.
1112
- */
805
+
1113
806
  class LDFlagDeliveryFallbackError extends Error {
1114
807
  constructor(kind, message, code) {
1115
808
  super(message);
1116
809
  this.kind = kind;
1117
810
  this.code = code;
1118
- this.name = 'LDFlagDeliveryFallbackError';
811
+ this.name = "LDFlagDeliveryFallbackError";
1119
812
  this.recoverable = false;
1120
813
  }
1121
814
  }
1122
815
 
1123
- const DEFAULT_FALLBACK_TIME_MS = 2 * 60 * 1000;
1124
- const DEFAULT_RECOVERY_TIME_MS = 5 * 60 * 1000;
1125
- /**
1126
- * The {@link CompositeDataSource} can combine a number of {@link DataSystemInitializer}s and {@link DataSystemSynchronizer}s
1127
- * into a single {@link DataSource}, implementing fallback and recovery logic internally to choose where data is sourced from.
1128
- */
816
+ const DEFAULT_FALLBACK_TIME_MS = 2 * 60 * 1e3;
817
+
818
+ const DEFAULT_RECOVERY_TIME_MS = 5 * 60 * 1e3;
819
+
1129
820
  class CompositeDataSource {
1130
- /**
1131
- * @param initializers factories to create {@link DataSystemInitializer}s, in priority order.
1132
- * @param synchronizers factories to create {@link DataSystemSynchronizer}s, in priority order.
1133
- * @param fdv1Synchronizers factories to fallback to if we need to fallback to FDv1.
1134
- * @param _logger for logging
1135
- * @param _transitionConditions to control automated transition between datasources. Typically only used for testing.
1136
- * @param _backoff to control delay between transitions. Typically only used for testing.
1137
- */
1138
821
  constructor(initializers, synchronizers, fdv1Synchronizers, _logger, _transitionConditions = {
1139
822
  [DataSourceState.Valid]: {
1140
823
  durationMS: DEFAULT_RECOVERY_TIME_MS,
1141
- transition: 'recover',
824
+ transition: "recover"
1142
825
  },
1143
826
  [DataSourceState.Interrupted]: {
1144
827
  durationMS: DEFAULT_FALLBACK_TIME_MS,
1145
- transition: 'fallback',
1146
- },
1147
- }, _backoff = new DefaultBackoff(1000, 30000)) {
828
+ transition: "fallback"
829
+ }
830
+ }, _backoff = new DefaultBackoff(1e3, 3e4), _onInitializersExhausted) {
1148
831
  this._logger = _logger;
1149
832
  this._transitionConditions = _transitionConditions;
1150
833
  this._backoff = _backoff;
1151
- // Set after the server-directed FDv1 fallback has been engaged. The directive is
1152
- // one-way: subsequent fallback signals from the FDv1 synchronizer (e.g. if the FDv1
1153
- // endpoint were to echo `x-ld-fd-fallback`) are ignored so the data source does not
1154
- // loop replacing its synchronizer list with itself.
834
+ this._onInitializersExhausted = _onInitializersExhausted;
1155
835
  this._fdv1FallbackEngaged = false;
1156
836
  this._stopped = true;
1157
837
  this._cancelTokens = [];
1158
- this._cancellableDelay = (delayMS) => {
838
+ this._cancellableDelay = delayMS => {
1159
839
  let timeout;
1160
840
  const promise = new Promise((res, _) => {
1161
841
  timeout = setTimeout(res, delayMS);
1162
842
  });
1163
843
  return {
1164
- promise,
844
+ promise: promise,
1165
845
  cancel() {
1166
846
  if (timeout) {
1167
847
  clearTimeout(timeout);
1168
848
  timeout = undefined;
1169
849
  }
1170
- },
850
+ }
1171
851
  };
1172
852
  };
1173
- this._externalTransitionPromise = new Promise((resolveTransition) => {
853
+ this._externalTransitionPromise = new Promise(resolveTransition => {
1174
854
  this._externalTransitionResolve = resolveTransition;
1175
855
  });
1176
- this._initPhaseActive = initializers.length > 0; // init phase if we have initializers
856
+ this._initPhaseActive = initializers.length > 0;
1177
857
  this._initFactories = new DataSourceList(false, initializers);
1178
858
  this._syncFactories = new DataSourceList(true, synchronizers);
1179
859
  this._fdv1Synchronizers = new DataSourceList(true, fdv1Synchronizers);
1180
860
  }
861
+ get initializing() {
862
+ return this._initPhaseActive;
863
+ }
1181
864
  async start(dataCallback, statusCallback, selectorGetter) {
1182
865
  if (!this._stopped) {
1183
- // don't allow multiple simultaneous runs
1184
- this._logger?.info('CompositeDataSource already running. Ignoring call to start.');
866
+ this._logger?.info("CompositeDataSource already running. Ignoring call to start.");
1185
867
  return;
1186
868
  }
1187
869
  this._stopped = false;
1188
870
  this._logger?.debug(`CompositeDataSource starting with (${this._initFactories.length()} initializers, ${this._syncFactories.length()} synchronizers).`);
1189
- // this wrapper turns status updates from underlying data sources into a valid series of status updates for the consumer of this
1190
- // composite data source
1191
871
  const sanitizedStatusCallback = this._wrapStatusCallbackWithSanitizer(statusCallback);
1192
872
  sanitizedStatusCallback(DataSourceState.Initializing);
1193
873
  let lastTransition;
1194
874
  while (true) {
1195
- const { dataSource: currentDS, isPrimary, cullDSFactory, } = this._pickDataSource(lastTransition);
1196
- const internalTransitionPromise = new Promise((transitionResolve) => {
875
+ const {dataSource: currentDS, isPrimary: isPrimary, cullDSFactory: cullDSFactory} = this._pickDataSource(lastTransition);
876
+ const internalTransitionPromise = new Promise(transitionResolve => {
1197
877
  if (currentDS) {
1198
- // these local variables are used for handling automatic transition related to data source status (ex: recovering to primary after
1199
- // secondary has been valid for N many seconds)
1200
878
  let lastState;
1201
- let cancelScheduledTransition = () => { };
1202
- // Engages the FDv1 Fallback Directive: swaps the synchronizer list to FDv1 (or
1203
- // empties it when no FDv1 fallback is configured), reports the in-progress status
1204
- // through the sanitizer, cancels any pending scheduled transition, and resolves
1205
- // a switchToSync transition. The directive is one-way; the engagement flag is
1206
- // checked by the callers so we don't re-enter this branch on repeated signals.
879
+ let cancelScheduledTransition = () => {};
1207
880
  const engageFDv1Fallback = (statusToReport, err) => {
1208
881
  if (this._fdv1Synchronizers.length() > 0) {
1209
882
  this._logger?.warn(`Falling back to FDv1`);
1210
- }
1211
- else {
883
+ } else {
1212
884
  this._logger?.warn(`FDv1 fallback was requested but no FDv1 fallback synchronizer is configured; data source will terminate`);
1213
885
  }
1214
886
  this._fdv1FallbackEngaged = true;
1215
887
  this._syncFactories = this._fdv1Synchronizers;
1216
888
  sanitizedStatusCallback(statusToReport, err);
1217
889
  this._consumeCancelToken(cancelScheduledTransition);
1218
- transitionResolve({ transition: 'switchToSync', err: err });
890
+ transitionResolve({
891
+ transition: "switchToSync",
892
+ err: err
893
+ });
1219
894
  };
1220
- // this callback handler can be disabled and ensures only one transition request occurs
1221
895
  const callbackHandler = new CallbackHandler((basis, data) => {
1222
896
  this._backoff.success();
1223
897
  dataCallback(basis, data);
1224
- // The FDv1 fallback directive can ride along on the same data callback that
1225
- // delivers a payload, so the swap to FDv1 is atomic with payload application.
1226
- // Once engaged, the directive is one-way -- subsequent signals are ignored.
1227
898
  if (data?.fallbackToFDv1 && !this._fdv1FallbackEngaged) {
1228
899
  callbackHandler.disable();
1229
900
  engageFDv1Fallback(DataSourceState.Interrupted, undefined);
1230
901
  return;
1231
902
  }
1232
903
  if (basis && this._initPhaseActive) {
1233
- // transition to sync if we get basis during init
1234
904
  callbackHandler.disable();
1235
905
  this._consumeCancelToken(cancelScheduledTransition);
1236
906
  sanitizedStatusCallback(DataSourceState.Interrupted);
1237
- transitionResolve({ transition: 'switchToSync' });
907
+ transitionResolve({
908
+ transition: "switchToSync"
909
+ });
1238
910
  }
1239
911
  }, (state, err) => {
1240
- // When we get a status update, we want to fallback if it is an error. We also want to schedule a transition for some
1241
- // time in the future if this status remains for some duration (ex: Recover to primary synchronizer after the secondary
1242
- // synchronizer has been Valid for some time). These scheduled transitions are configurable in the constructor.
1243
912
  this._logger?.debug(`CompositeDataSource received state ${state} from underlying data source. Err is ${err}`);
1244
913
  if (err || state === DataSourceState.Closed) {
1245
914
  callbackHandler.disable();
1246
915
  if (err?.recoverable === false) {
1247
- // don't use this datasource's factory again
1248
916
  this._logger?.debug(`Culling data source due to err ${err}`);
1249
917
  cullDSFactory?.();
1250
918
  }
1251
- // Status-callback path for the FDv1 Fallback Directive (used when the
1252
- // server-directed signal arrives without an accompanying payload, e.g. on
1253
- // an HTTP error or a malformed body).
1254
919
  if (err instanceof LDFlagDeliveryFallbackError && !this._fdv1FallbackEngaged) {
1255
920
  engageFDv1Fallback(state, err);
1256
921
  return;
1257
922
  }
1258
923
  sanitizedStatusCallback(state, err);
1259
924
  this._consumeCancelToken(cancelScheduledTransition);
1260
- transitionResolve({ transition: 'fallback', err }); // unrecoverable error has occurred, so fallback
1261
- }
1262
- else {
925
+ transitionResolve({
926
+ transition: "fallback",
927
+ err: err
928
+ });
929
+ } else {
1263
930
  sanitizedStatusCallback(state);
1264
931
  if (state !== lastState) {
1265
932
  lastState = state;
1266
- this._consumeCancelToken(cancelScheduledTransition); // cancel previously scheduled status transition if one was scheduled
1267
- // primary source cannot recover to itself, so exclude it
933
+ this._consumeCancelToken(cancelScheduledTransition);
1268
934
  const condition = this._lookupTransitionCondition(state, isPrimary);
1269
935
  if (condition) {
1270
- const { promise, cancel } = this._cancellableDelay(condition.durationMS);
936
+ const {promise: promise, cancel: cancel} = this._cancellableDelay(condition.durationMS);
1271
937
  cancelScheduledTransition = cancel;
1272
938
  this._cancelTokens.push(cancelScheduledTransition);
1273
939
  promise.then(() => {
1274
940
  this._consumeCancelToken(cancel);
1275
941
  callbackHandler.disable();
1276
942
  sanitizedStatusCallback(DataSourceState.Interrupted);
1277
- transitionResolve({ transition: condition.transition });
943
+ transitionResolve({
944
+ transition: condition.transition
945
+ });
1278
946
  });
1279
947
  }
1280
948
  }
1281
949
  }
1282
950
  });
1283
951
  currentDS.start((basis, data) => callbackHandler.dataHandler(basis, data), (status, err) => callbackHandler.statusHandler(status, err), selectorGetter);
1284
- }
1285
- else {
1286
- // we don't have a data source to use!
952
+ } else {
1287
953
  transitionResolve({
1288
- transition: 'stop',
954
+ transition: "stop",
1289
955
  err: {
1290
- name: 'ExhaustedDataSources',
1291
- message: `CompositeDataSource has exhausted all configured initializers and synchronizers.`,
1292
- },
956
+ name: "ExhaustedDataSources",
957
+ message: `CompositeDataSource has exhausted all configured initializers and synchronizers.`
958
+ }
1293
959
  });
1294
960
  }
1295
961
  });
1296
- // await transition triggered by internal data source or an external stop request
1297
- // eslint-disable-next-line no-await-in-loop
1298
- let transitionRequest = await Promise.race([
1299
- internalTransitionPromise,
1300
- this._externalTransitionPromise,
1301
- ]);
1302
- // stop the underlying datasource before transitioning to next state
962
+ let transitionRequest = await Promise.race([ internalTransitionPromise, this._externalTransitionPromise ]);
1303
963
  currentDS?.stop();
1304
- // Skip backoff only on the initial server-directed FDv1 engagement (a `switchToSync`
1305
- // transition resolved by `engageFDv1Fallback` carries an `LDFlagDeliveryFallbackError`).
1306
- // Any subsequent `LDFlagDeliveryFallbackError` is an ordinary retry from the FDv1
1307
- // synchronizer (or a follow-up FDv1 factory) and must be throttled like any other
1308
- // error retry.
1309
- const isInitialFDv1Engagement = transitionRequest.transition === 'switchToSync' &&
1310
- transitionRequest.err instanceof LDFlagDeliveryFallbackError;
1311
- if (transitionRequest.err &&
1312
- transitionRequest.transition !== 'stop' &&
1313
- !isInitialFDv1Engagement) {
1314
- // if the transition was due to an error we're not in the initializer phase, throttle the transition. Fallback between initializers is not throttled.
964
+ const isInitialFDv1Engagement = transitionRequest.transition === "switchToSync" && transitionRequest.err instanceof LDFlagDeliveryFallbackError;
965
+ if (transitionRequest.err && transitionRequest.transition !== "stop" && !isInitialFDv1Engagement) {
1315
966
  const delay = this._initPhaseActive ? 0 : this._backoff.fail();
1316
- const { promise, cancel: cancelDelay } = this._cancellableDelay(delay);
967
+ const {promise: promise, cancel: cancelDelay} = this._cancellableDelay(delay);
1317
968
  this._cancelTokens.push(cancelDelay);
1318
969
  const delayedTransition = promise.then(() => {
1319
970
  this._consumeCancelToken(cancelDelay);
1320
971
  return transitionRequest;
1321
972
  });
1322
- // race the delayed transition and external transition requests to be responsive
1323
- // eslint-disable-next-line no-await-in-loop
1324
- transitionRequest = await Promise.race([
1325
- delayedTransition,
1326
- this._externalTransitionPromise,
1327
- ]);
1328
- // consume the delay cancel token (even if it resolved, need to stop tracking its token)
973
+ transitionRequest = await Promise.race([ delayedTransition, this._externalTransitionPromise ]);
1329
974
  this._consumeCancelToken(cancelDelay);
1330
975
  }
1331
976
  lastTransition = transitionRequest.transition;
1332
- if (transitionRequest.transition === 'stop') {
1333
- // exit the loop, this is intentionally not the sanitized status callback
977
+ if (transitionRequest.transition === "stop") {
1334
978
  statusCallback(DataSourceState.Closed, transitionRequest.err);
1335
979
  break;
1336
980
  }
1337
981
  }
1338
- // reset so that run can be called again in the future
1339
982
  this._reset();
1340
983
  }
1341
984
  async stop() {
1342
- this._cancelTokens.forEach((cancel) => cancel());
985
+ this._cancelTokens.forEach(cancel => cancel());
1343
986
  this._cancelTokens = [];
1344
- this._externalTransitionResolve?.({ transition: 'stop' });
987
+ this._externalTransitionResolve?.({
988
+ transition: "stop"
989
+ });
1345
990
  }
1346
991
  _reset() {
1347
992
  this._stopped = true;
1348
- this._initPhaseActive = this._initFactories.length() > 0; // init phase if we have initializers;
993
+ this._initPhaseActive = this._initFactories.length() > 0;
1349
994
  this._initFactories.reset();
1350
995
  this._syncFactories.reset();
1351
996
  this._fdv1Synchronizers.reset();
1352
997
  this._fdv1FallbackEngaged = false;
1353
- this._externalTransitionPromise = new Promise((tr) => {
998
+ this._externalTransitionPromise = new Promise(tr => {
1354
999
  this._externalTransitionResolve = tr;
1355
1000
  });
1356
- // intentionally not resetting the backoff to avoid a code path that could circumvent throttling
1357
1001
  }
1358
- /**
1359
- * Determines the next datasource and returns that datasource as well as a closure to cull the
1360
- * datasource from the datasource lists. One example where the cull closure is invoked is if the
1361
- * datasource has an unrecoverable error.
1362
- */
1363
1002
  _pickDataSource(transition) {
1364
1003
  let factory;
1365
1004
  let isPrimary;
1366
1005
  switch (transition) {
1367
- case 'switchToSync':
1368
- this._initPhaseActive = false; // one way toggle to false, unless this class is reset()
1006
+ case "switchToSync":
1007
+ this._initPhaseActive = false;
1008
+ this._syncFactories.reset();
1009
+ isPrimary = this._syncFactories.pos() === 0;
1010
+ factory = this._syncFactories.next();
1011
+ break;
1012
+
1013
+ case "recover":
1014
+ if (this._initPhaseActive) {
1015
+ this._initFactories.reset();
1016
+ isPrimary = this._initFactories.pos() === 0;
1017
+ factory = this._initFactories.next();
1018
+ } else {
1369
1019
  this._syncFactories.reset();
1370
1020
  isPrimary = this._syncFactories.pos() === 0;
1371
1021
  factory = this._syncFactories.next();
1372
- break;
1373
- case 'recover':
1374
- if (this._initPhaseActive) {
1375
- this._initFactories.reset();
1376
- isPrimary = this._initFactories.pos() === 0;
1377
- factory = this._initFactories.next();
1378
- }
1379
- else {
1380
- this._syncFactories.reset();
1381
- isPrimary = this._syncFactories.pos() === 0;
1382
- factory = this._syncFactories.next();
1383
- }
1384
- break;
1385
- case 'fallback':
1386
- default:
1387
- // if asked to fallback after using all init factories, switch to sync factories
1388
- if (this._initPhaseActive && this._initFactories.pos() >= this._initFactories.length()) {
1389
- this._initPhaseActive = false;
1390
- this._syncFactories.reset();
1391
- }
1392
- if (this._initPhaseActive) {
1393
- isPrimary = this._initFactories.pos() === 0;
1394
- factory = this._initFactories.next();
1395
- }
1396
- else {
1397
- isPrimary = this._syncFactories.pos() === 0;
1398
- factory = this._syncFactories.next();
1399
- }
1400
- break;
1022
+ }
1023
+ break;
1024
+
1025
+ case "fallback":
1026
+ default:
1027
+ if (this._initPhaseActive && this._initFactories.pos() >= this._initFactories.length()) {
1028
+ this._initPhaseActive = false;
1029
+ this._onInitializersExhausted?.();
1030
+ this._syncFactories.reset();
1031
+ }
1032
+ if (this._initPhaseActive) {
1033
+ isPrimary = this._initFactories.pos() === 0;
1034
+ factory = this._initFactories.next();
1035
+ } else {
1036
+ isPrimary = this._syncFactories.pos() === 0;
1037
+ factory = this._syncFactories.next();
1038
+ }
1039
+ break;
1401
1040
  }
1402
1041
  if (!factory) {
1403
- return { dataSource: undefined, isPrimary, cullDSFactory: undefined };
1042
+ return {
1043
+ dataSource: undefined,
1044
+ isPrimary: isPrimary,
1045
+ cullDSFactory: undefined
1046
+ };
1404
1047
  }
1405
1048
  return {
1406
1049
  dataSource: factory(),
1407
- isPrimary,
1050
+ isPrimary: isPrimary,
1408
1051
  cullDSFactory: () => {
1409
1052
  if (factory) {
1410
1053
  this._syncFactories.remove(factory);
1411
1054
  }
1412
- },
1055
+ }
1413
1056
  };
1414
1057
  }
1415
- /**
1416
- * @returns the transition condition for the provided data source state or undefined
1417
- * if there is no transition condition
1418
- */
1419
1058
  _lookupTransitionCondition(state, excludeRecover) {
1420
1059
  const condition = this._transitionConditions[state];
1421
- // exclude recovery can happen for certain initializers/synchronizers (ex: the primary synchronizer shouldn't recover to itself)
1422
- if (excludeRecover && condition?.transition === 'recover') {
1060
+ if (excludeRecover && condition?.transition === "recover") {
1423
1061
  return undefined;
1424
1062
  }
1425
1063
  return condition;
@@ -1431,29 +1069,19 @@ class CompositeDataSource {
1431
1069
  this._cancelTokens.splice(index, 1);
1432
1070
  }
1433
1071
  }
1434
- /**
1435
- * This wrapper will ensure the following:
1436
- *
1437
- * Don't report DataSourceState.Initializing except as first status callback.
1438
- * Map underlying DataSourceState.Closed to interrupted.
1439
- * Don't report the same status and error twice in a row.
1440
- */
1441
1072
  _wrapStatusCallbackWithSanitizer(statusCallback) {
1442
1073
  let alreadyReportedInitializing = false;
1443
1074
  let lastStatus;
1444
1075
  let lastErr;
1445
1076
  return (status, err) => {
1446
1077
  let sanitized = status;
1447
- // underlying errors, closed state, or off are masked as interrupted while we transition
1448
1078
  if (status === DataSourceState.Closed) {
1449
1079
  sanitized = DataSourceState.Interrupted;
1450
1080
  }
1451
- // don't report the same combination of values twice in a row
1452
1081
  if (sanitized === lastStatus && err === lastErr) {
1453
1082
  return;
1454
1083
  }
1455
1084
  if (sanitized === DataSourceState.Initializing) {
1456
- // don't report initializing again if that has already been reported
1457
1085
  if (alreadyReportedInitializing) {
1458
1086
  return;
1459
1087
  }
@@ -1467,87 +1095,52 @@ class CompositeDataSource {
1467
1095
  }
1468
1096
 
1469
1097
  var DataSourceErrorKind;
1470
- (function (DataSourceErrorKind) {
1471
- /// An unexpected error, such as an uncaught exception, further
1472
- /// described by the error message.
1098
+
1099
+ (function(DataSourceErrorKind) {
1473
1100
  DataSourceErrorKind["Unknown"] = "UNKNOWN";
1474
- /// An I/O error such as a dropped connection.
1475
1101
  DataSourceErrorKind["NetworkError"] = "NETWORK_ERROR";
1476
- /// The LaunchDarkly service returned an HTTP response with an error
1477
- /// status, available in the status code.
1478
1102
  DataSourceErrorKind["ErrorResponse"] = "ERROR_RESPONSE";
1479
- /// The SDK received malformed data from the LaunchDarkly service.
1480
1103
  DataSourceErrorKind["InvalidData"] = "INVALID_DATA";
1481
1104
  })(DataSourceErrorKind || (DataSourceErrorKind = {}));
1482
1105
 
1483
- // These classes are of trivial complexity. If they become
1484
- // more complex, then they could be independent files.
1485
1106
  class LDUnexpectedResponseError extends Error {
1486
1107
  constructor(message) {
1487
1108
  super(message);
1488
- this.name = 'LaunchDarklyUnexpectedResponseError';
1109
+ this.name = "LaunchDarklyUnexpectedResponseError";
1489
1110
  }
1490
1111
  }
1112
+
1491
1113
  class LDClientError extends Error {
1492
1114
  constructor(message) {
1493
1115
  super(message);
1494
- this.name = 'LaunchDarklyClientError';
1116
+ this.name = "LaunchDarklyClientError";
1495
1117
  }
1496
1118
  }
1119
+
1497
1120
  class LDTimeoutError extends Error {
1498
1121
  constructor(message) {
1499
1122
  super(message);
1500
- this.name = 'LaunchDarklyTimeoutError';
1501
- }
1502
- }
1503
- // HTTP statuses in the 4xx range that are still normal failures. Every other
1504
- // 4xx is unexpected.
1505
- const NORMAL_4XX_STATUSES = [400, 408, 429];
1506
- /**
1507
- * Classifies an HTTP status.
1508
- *
1509
- * 400, 408, and 429 are normal, as is any 5xx. Every other 4xx, including 401
1510
- * and 403, is unexpected. Anything outside the error ranges, including 0 for
1511
- * "no response", is normal.
1512
- */
1123
+ this.name = "LaunchDarklyTimeoutError";
1124
+ }
1125
+ }
1126
+
1127
+ const NORMAL_4XX_STATUSES = [ 400, 408, 429 ];
1128
+
1513
1129
  function classifyHttpStatus(status) {
1514
1130
  if (status >= 400 && status < 500 && !NORMAL_4XX_STATUSES.includes(status)) {
1515
- return 'unexpected';
1516
- }
1517
- return 'normal';
1518
- }
1519
- /**
1520
- * Classifies a transport-level failure (connection refused or dropped, DNS
1521
- * failure, timeout, TLS negotiation failure).
1522
- *
1523
- * Always normal: in an all-HTTPS system every transport error surfaces through
1524
- * the TLS layer, so a certificate misconfiguration cannot be reliably
1525
- * distinguished from a transient network fault, and treating transient faults
1526
- * as unexpected would hold ordinary recoveries to multi-minute waits.
1527
- */
1131
+ return "unexpected";
1132
+ }
1133
+ return "normal";
1134
+ }
1135
+
1528
1136
  function classifyTransportFailure() {
1529
- return 'normal';
1530
- }
1531
- /**
1532
- * Check if the HTTP error is recoverable. This will return false if a request
1533
- * made with any payload could not recover. If the reason for the failure
1534
- * is payload specific, for instance a payload that is too large, then
1535
- * it could recover with a different payload.
1536
- *
1537
- * Superseded by {@link classifyHttpStatus}, which this delegates to. It is
1538
- * retained for the event-delivery pathway and is expected to be deprecated
1539
- * once that pathway migrates to failure classification.
1540
- */
1137
+ return "normal";
1138
+ }
1139
+
1541
1140
  function isHttpRecoverable(status) {
1542
- return classifyHttpStatus(status) === 'normal';
1543
- }
1544
- /**
1545
- * Returns true if the status could recover for a different payload.
1546
- *
1547
- * When used with event processing this indicates that we should discard
1548
- * the payload, but that a subsequent payload may succeed. Therefore we should
1549
- * not stop event processing.
1550
- */
1141
+ return classifyHttpStatus(status) === "normal";
1142
+ }
1143
+
1551
1144
  function isHttpLocallyRecoverable(status) {
1552
1145
  if (status === 413) {
1553
1146
  return true;
@@ -1555,12 +1148,6 @@ function isHttpLocallyRecoverable(status) {
1555
1148
  return isHttpRecoverable(status);
1556
1149
  }
1557
1150
 
1558
- /**
1559
- * Returns a promise which errors after t seconds.
1560
- *
1561
- * @param t Timeout in seconds.
1562
- * @param taskName Name of task being timed for logging and error reporting.
1563
- */
1564
1151
  function cancelableTimedPromise(t, taskName) {
1565
1152
  let timeout;
1566
1153
  let resolve;
@@ -1569,14 +1156,14 @@ function cancelableTimedPromise(t, taskName) {
1569
1156
  timeout = setTimeout(() => {
1570
1157
  const e = `${taskName} timed out after ${t} seconds.`;
1571
1158
  reject(new LDTimeoutError(e));
1572
- }, t * 1000);
1159
+ }, t * 1e3);
1573
1160
  });
1574
1161
  return {
1575
- promise,
1162
+ promise: promise,
1576
1163
  cancel: () => {
1577
1164
  resolve();
1578
1165
  clearTimeout(timeout);
1579
- },
1166
+ }
1580
1167
  };
1581
1168
  }
1582
1169
 
@@ -1588,30 +1175,10 @@ function clone(obj) {
1588
1175
  }
1589
1176
 
1590
1177
  function secondsToMillis(sec) {
1591
- return Math.trunc(sec * 1000);
1592
- }
1593
-
1594
- /**
1595
- * Wait before calling the same function. Useful for expensive calls.
1596
- * Adapted from https://amitd.co/code/typescript/debounce.
1597
- *
1598
- * @return The debounced function.
1599
- *
1600
- * @example
1601
- *
1602
- * ```js
1603
- * const debouncedFunction = debounce(e => {
1604
- * console.log(e);
1605
- * }, 5000);
1606
- *
1607
- * // Console logs 'Hello world again ' after 5 seconds
1608
- * debouncedFunction('Hello world');
1609
- * debouncedFunction('Hello world again');
1610
- * ```
1611
- * @param fn The function to be debounced.
1612
- * @param delayMs Defaults to 5 seconds.
1613
- */
1614
- const debounce = (fn, delayMs = 5000) => {
1178
+ return Math.trunc(sec * 1e3);
1179
+ }
1180
+
1181
+ const debounce = (fn, delayMs = 5e3) => {
1615
1182
  let timer;
1616
1183
  return (...args) => {
1617
1184
  clearTimeout(timer);
@@ -1621,221 +1188,126 @@ const debounce = (fn, delayMs = 5000) => {
1621
1188
  };
1622
1189
  };
1623
1190
 
1624
- const isEmptyObject = (obj) => JSON.stringify(obj) === '{}';
1191
+ const isEmptyObject = obj => JSON.stringify(obj) === "{}";
1625
1192
 
1626
- /**
1627
- * Strips all falsy and empty {} from a given object. Returns a new object with only truthy values.
1628
- * Sourced from below but modified to include checks for empty object and ignoring keys.
1629
- * https://www.w3resource.com/javascript-exercises/javascript-array-exercise-47.php
1630
- *
1631
- * @param obj
1632
- * @param ignoreKeys
1633
- */
1634
1193
  const deepCompact = (obj, ignoreKeys) => {
1635
1194
  if (!obj) {
1636
1195
  return obj;
1637
1196
  }
1638
1197
  return Object.entries(obj).reduce((acc, [key, value]) => {
1639
1198
  if (Boolean(value) && !isEmptyObject(value) && !ignoreKeys?.includes(key)) {
1640
- acc[key] = typeof value === 'object' ? deepCompact(value, ignoreKeys) : value;
1199
+ acc[key] = typeof value === "object" ? deepCompact(value, ignoreKeys) : value;
1641
1200
  }
1642
1201
  return acc;
1643
1202
  }, {});
1644
1203
  };
1645
1204
 
1646
- /* eslint-disable */
1647
- // Ripped from https://github.com/epoberezkin/fast-deep-fastDeepEqual
1648
- // {{? it.es6 }}
1649
- // var envHasBigInt64Array = typeof BigInt64Array !== 'undefined';
1650
- // {{?}}
1651
1205
  function fastDeepEqual(a, b) {
1652
- if (a === b)
1653
- return true;
1654
- if (a && b && typeof a == 'object' && typeof b == 'object') {
1655
- if (a.constructor !== b.constructor)
1656
- return false;
1206
+ if (a === b) return true;
1207
+ if (a && b && typeof a == "object" && typeof b == "object") {
1208
+ if (a.constructor !== b.constructor) return false;
1657
1209
  var length, i, keys;
1658
1210
  if (Array.isArray(a)) {
1659
1211
  length = a.length;
1660
- if (length != b.length)
1661
- return false;
1662
- for (i = length; i-- !== 0;)
1663
- if (!fastDeepEqual(a[i], b[i]))
1664
- return false;
1212
+ if (length != b.length) return false;
1213
+ for (i = length; i-- !== 0; ) if (!fastDeepEqual(a[i], b[i])) return false;
1665
1214
  return true;
1666
1215
  }
1667
- // {{? it.es6 }}
1668
1216
  if (a instanceof Map && b instanceof Map) {
1669
- if (a.size !== b.size)
1670
- return false;
1671
- for (i of a.entries())
1672
- if (!b.has(i[0]))
1673
- return false;
1674
- for (i of a.entries())
1675
- if (!fastDeepEqual(i[1], b.get(i[0])))
1676
- return false;
1217
+ if (a.size !== b.size) return false;
1218
+ for (i of a.entries()) if (!b.has(i[0])) return false;
1219
+ for (i of a.entries()) if (!fastDeepEqual(i[1], b.get(i[0]))) return false;
1677
1220
  return true;
1678
1221
  }
1679
1222
  if (a instanceof Set && b instanceof Set) {
1680
- if (a.size !== b.size)
1681
- return false;
1682
- for (i of a.entries())
1683
- if (!b.has(i[0]))
1684
- return false;
1223
+ if (a.size !== b.size) return false;
1224
+ for (i of a.entries()) if (!b.has(i[0])) return false;
1685
1225
  return true;
1686
1226
  }
1687
1227
  if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {
1688
- // @ts-ignore
1689
1228
  length = a.length;
1690
- // @ts-ignore
1691
- if (length != b.length)
1692
- return false;
1693
- for (i = length; i-- !== 0;) {
1694
- // @ts-ignore
1695
- if (a[i] !== b[i])
1696
- return false;
1229
+ if (length != b.length) return false;
1230
+ for (i = length; i-- !== 0; ) {
1231
+ if (a[i] !== b[i]) return false;
1697
1232
  }
1698
1233
  return true;
1699
1234
  }
1700
- // {{?}}
1701
- if (a.constructor === RegExp)
1702
- return a.source === b.source && a.flags === b.flags;
1703
- if (a.valueOf !== Object.prototype.valueOf)
1704
- return a.valueOf() === b.valueOf();
1705
- if (a.toString !== Object.prototype.toString)
1706
- return a.toString() === b.toString();
1235
+ if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
1236
+ if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
1237
+ if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();
1707
1238
  keys = Object.keys(a);
1708
1239
  length = keys.length;
1709
- if (length !== Object.keys(b).length)
1710
- return false;
1711
- for (i = length; i-- !== 0;)
1712
- if (!Object.prototype.hasOwnProperty.call(b, keys[i]))
1713
- return false;
1714
- for (i = length; i-- !== 0;) {
1240
+ if (length !== Object.keys(b).length) return false;
1241
+ for (i = length; i-- !== 0; ) if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
1242
+ for (i = length; i-- !== 0; ) {
1715
1243
  var key = keys[i];
1716
- // {{? it.react }}
1717
- // if (key === '_owner' && a.$$typeof) {
1718
- // // React-specific: avoid traversing React elements' _owner.
1719
- // // _owner contains circular references
1720
- // // and is not needed when comparing the actual elements (and not their owners)
1721
- // continue;
1722
- // }
1723
- // {{?}}
1724
- if (!fastDeepEqual(a[key], b[key]))
1725
- return false;
1244
+ if (!fastDeepEqual(a[key], b[key])) return false;
1726
1245
  }
1727
1246
  return true;
1728
1247
  }
1729
- // true if both NaN, false otherwise
1730
1248
  return a !== a && b !== b;
1731
1249
  }
1732
1250
 
1733
- function defaultHeaders(sdkKey, info, tags, includeAuthorizationHeader = true, userAgentHeaderName = 'user-agent', instanceId) {
1734
- const { userAgentBase, version, wrapperName, wrapperVersion } = info.sdkData();
1251
+ function defaultHeaders(sdkKey, info, tags, includeAuthorizationHeader = true, userAgentHeaderName = "user-agent", instanceId) {
1252
+ const {userAgentBase: userAgentBase, version: version, wrapperName: wrapperName, wrapperVersion: wrapperVersion} = info.sdkData();
1735
1253
  const headers = {
1736
- [userAgentHeaderName]: `${userAgentBase ?? 'NodeJSClient'}/${version}`,
1254
+ [userAgentHeaderName]: `${userAgentBase ?? "NodeJSClient"}/${version}`
1737
1255
  };
1738
- // edge sdks sets this to false because they use the clientSideID
1739
- // and they don't need the authorization header
1740
1256
  if (includeAuthorizationHeader) {
1741
1257
  headers.authorization = sdkKey;
1742
1258
  }
1743
1259
  if (wrapperName) {
1744
- headers['x-launchdarkly-wrapper'] = wrapperVersion
1745
- ? `${wrapperName}/${wrapperVersion}`
1746
- : wrapperName;
1260
+ headers["x-launchdarkly-wrapper"] = wrapperVersion ? `${wrapperName}/${wrapperVersion}` : wrapperName;
1747
1261
  }
1748
1262
  if (tags?.value) {
1749
- headers['x-launchdarkly-tags'] = tags.value;
1263
+ headers["x-launchdarkly-tags"] = tags.value;
1750
1264
  }
1751
- // Per SCMP-server-connection-minutes-polling (spec section 1.1), server SDKs include a
1752
- // per-instance v4 GUID on every polling request. The caller (a server SDK) is responsible
1753
- // for generating the GUID once per SDK instance and passing it here, so that it rides on
1754
- // every outbound request via this shared default-headers map. Client/edge SDKs do not pass
1755
- // this value, so the header is omitted for them.
1756
1265
  if (instanceId) {
1757
- headers['x-launchdarkly-instance-id'] = instanceId;
1266
+ headers["x-launchdarkly-instance-id"] = instanceId;
1758
1267
  }
1759
1268
  return headers;
1760
1269
  }
1270
+
1761
1271
  function httpErrorMessage(err, context, retryMessage) {
1762
1272
  let desc;
1763
1273
  if (err.status) {
1764
- desc = `error ${err.status}${err.status === 401 ? ' (invalid SDK key)' : ''}`;
1765
- }
1766
- else {
1767
- desc = `I/O error (${err.message || 'unknown error'})`;
1274
+ desc = `error ${err.status}${err.status === 401 ? " (invalid SDK key)" : ""}`;
1275
+ } else {
1276
+ desc = `I/O error (${err.message || "unknown error"})`;
1768
1277
  }
1769
- const action = retryMessage ?? 'giving up permanently';
1278
+ const action = retryMessage ?? "giving up permanently";
1770
1279
  return `Received ${desc} for ${context} - ${action}`;
1771
1280
  }
1772
- function shouldRetry({ status }) {
1281
+
1282
+ function shouldRetry({status: status}) {
1773
1283
  return status ? isHttpRecoverable(status) : true;
1774
1284
  }
1775
- /**
1776
- * In react-native use base64-js to polyfill btoa. This is safe
1777
- * because the react-native repo uses it too. Set the global.btoa to the encode
1778
- * function of base64-js.
1779
- * https://github.com/beatgammit/base64-js
1780
- * https://github.com/axios/axios/issues/2235#issuecomment-512204616
1781
- *
1782
- * Ripped from https://thewoods.blog/base64url/
1783
- */
1784
- const base64UrlEncode = (s, encoding) => encoding.btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
1785
1285
 
1786
- var noop = () => { };
1286
+ const base64UrlEncode = (s, encoding) => encoding.btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
1787
1287
 
1788
- const sleep = async (delayMillis = 1000) => new Promise((resolve) => {
1288
+ var noop = () => {};
1289
+
1290
+ const sleep = async (delayMillis = 1e3) => new Promise(resolve => {
1789
1291
  setTimeout(resolve, delayMillis);
1790
1292
  });
1791
1293
 
1792
1294
  let useWallClock;
1793
- /**
1794
- * Milliseconds from a monotonic clock when the runtime provides one.
1795
- *
1796
- * Deadlines and embargoes compare differences of these values. A wall clock can
1797
- * step backward, for example through an NTP correction, and a deadline armed
1798
- * against it would then never pass. Values from this function are not epoch
1799
- * times and must only be compared with each other.
1800
- *
1801
- * The time source is selected on the first call and never changes after that.
1802
- * Monotonic values and wall-clock values have different origins, so a switch
1803
- * between sources would corrupt in-flight measurements. A runtime without a
1804
- * performance global at the first call uses the wall clock from then on, even
1805
- * if a polyfill appears later.
1806
- */
1807
- // eslint-disable-next-line import/prefer-default-export
1295
+
1808
1296
  function monotonicNow() {
1809
1297
  if (useWallClock === undefined) {
1810
1298
  const perf = globalThis?.performance;
1811
- useWallClock = !(perf && typeof perf.now === 'function');
1299
+ useWallClock = !(perf && typeof perf.now === "function");
1812
1300
  }
1813
1301
  return useWallClock ? Date.now() : globalThis.performance.now();
1814
1302
  }
1815
1303
 
1816
- /**
1817
- * Returns a promise which errors after t seconds.
1818
- *
1819
- * @param t Timeout in seconds.
1820
- * @param taskName Name of task being timed for logging and error reporting.
1821
- */
1822
1304
  const timedPromise = (t, taskName) => new Promise((_res, reject) => {
1823
1305
  setTimeout(() => {
1824
1306
  const e = `${taskName} timed out after ${t} seconds.`;
1825
1307
  reject(new LDTimeoutError(e));
1826
- }, t * 1000);
1308
+ }, t * 1e3);
1827
1309
  });
1828
1310
 
1829
- /**
1830
- * Creates a policy that resets once the component has operated without failing
1831
- * for the given duration. Repeated healthy reports do not move the starting
1832
- * point; only a failure clears it.
1833
- *
1834
- * @param healthyForMs How long the component must operate without failing,
1835
- * in milliseconds; must be a positive, finite number.
1836
- * @param clock The time source used to measure the healthy stretch; defaults
1837
- * to a monotonic clock. Primarily for testing.
1838
- */
1839
1311
  function createAfterHealthyFor(healthyForMs, clock = monotonicNow) {
1840
1312
  let healthySinceMs;
1841
1313
  return {
@@ -1849,16 +1321,10 @@ function createAfterHealthyFor(healthyForMs, clock = monotonicNow) {
1849
1321
  },
1850
1322
  isSatisfied() {
1851
1323
  return healthySinceMs !== undefined && clock() - healthySinceMs >= healthyForMs;
1852
- },
1324
+ }
1853
1325
  };
1854
1326
  }
1855
- /**
1856
- * Creates a policy that resets once the given number of operations in a row
1857
- * have succeeded.
1858
- *
1859
- * @param count How many operations in a row must succeed; must be a positive
1860
- * integer.
1861
- */
1327
+
1862
1328
  function createAfterConsecutiveSuccesses(count) {
1863
1329
  let successes = 0;
1864
1330
  return {
@@ -1870,47 +1336,45 @@ function createAfterConsecutiveSuccesses(count) {
1870
1336
  },
1871
1337
  isSatisfied() {
1872
1338
  return successes >= count;
1873
- },
1339
+ }
1874
1340
  };
1875
1341
  }
1876
1342
 
1877
- // The delay bounds of the extended regime, in milliseconds. A component enters
1878
- // the extended regime after an unexpected failure and leaves it when its reset
1879
- // policy is satisfied.
1880
- const EXTENDED_INITIAL_DELAY_MS = 5 * 60 * 1000;
1881
- const EXTENDED_CEILING_MS = 60 * 60 * 1000;
1882
- // The bounds, reset window, and default initial delay of streaming's normal regime.
1883
- const STREAMING_NORMAL_CEILING_MS = 30 * 1000;
1884
- const STREAMING_RESET_INTERVAL_MS = 60 * 1000;
1885
- const DEFAULT_STREAMING_INITIAL_DELAY_MS = 1000;
1886
- // Polling's reset condition and default cadence.
1343
+ const EXTENDED_INITIAL_DELAY_MS = 5 * 60 * 1e3;
1344
+
1345
+ const EXTENDED_CEILING_MS = 60 * 60 * 1e3;
1346
+
1347
+ const STREAMING_NORMAL_CEILING_MS = 30 * 1e3;
1348
+
1349
+ const STREAMING_RESET_INTERVAL_MS = 60 * 1e3;
1350
+
1351
+ const DEFAULT_STREAMING_INITIAL_DELAY_MS = 1e3;
1352
+
1887
1353
  const POLLING_RESET_SUCCESSES = 2;
1888
- const DEFAULT_POLL_INTERVAL_MS = 30 * 1000;
1354
+
1355
+ const DEFAULT_POLL_INTERVAL_MS = 30 * 1e3;
1356
+
1889
1357
  function positiveFiniteOrDefault(value, defaultValueMs, name, logger) {
1890
- if (typeof value === 'number' && Number.isFinite(value) && value > 0) {
1358
+ if (typeof value === "number" && Number.isFinite(value) && value > 0) {
1891
1359
  return value;
1892
1360
  }
1893
1361
  logger?.warn(`${name} must be a positive, finite number of milliseconds; using the default of ${defaultValueMs}`);
1894
1362
  return defaultValueMs;
1895
1363
  }
1896
- /**
1897
- * Builds a retry state from explicit bounds. See {@link RetryStateConfig} for
1898
- * the contract on the values.
1899
- */
1364
+
1900
1365
  function createRetryState(config) {
1901
1366
  const normalInitialDelayMs = config.normalInitialDelayMs;
1902
1367
  const normalCeilingMs = config.normalCeilingMs;
1903
1368
  const extendedInitialDelayMs = config.extendedInitialDelayMs;
1904
1369
  const extendedCeilingMs = config.extendedCeilingMs;
1905
1370
  const operatingCadenceMs = config.operatingCadenceMs ?? 0;
1906
- const { resetPolicy } = config;
1371
+ const {resetPolicy: resetPolicy} = config;
1907
1372
  const random = config.random ?? Math.random;
1908
1373
  let attempts = 0;
1909
1374
  let extended = false;
1910
1375
  let minDelayMs = normalInitialDelayMs;
1911
1376
  let maxDelayMs = normalCeilingMs;
1912
1377
  let serverDirectedBaseMs;
1913
- // Before any outcome is recorded, the next wait is the ordinary interval.
1914
1378
  let nextDelayMs = operatingCadenceMs;
1915
1379
  function resetIfDue() {
1916
1380
  if (!resetPolicy.isSatisfied()) {
@@ -1926,355 +1390,257 @@ function createRetryState(config) {
1926
1390
  return nextDelayMs;
1927
1391
  },
1928
1392
  recordFailure(kind) {
1929
- // A reset that fell due during healthy operation is applied before the
1930
- // new failure is counted, so the failure computes from a fresh sequence.
1931
1393
  resetIfDue();
1932
1394
  resetPolicy.noteFailure();
1933
- if (kind === 'unexpected' && !extended) {
1934
- // Moving to the extended regime raises both bounds and starts the delay
1935
- // sequence over. Only the move does this: a later unexpected failure
1936
- // keeps counting up rather than re-pinning the initial delay.
1395
+ if (kind === "unexpected" && !extended) {
1937
1396
  extended = true;
1938
1397
  minDelayMs = extendedInitialDelayMs;
1939
1398
  maxDelayMs = Math.max(extendedCeilingMs, extendedInitialDelayMs);
1940
1399
  attempts = 1;
1941
- }
1942
- else {
1400
+ } else {
1943
1401
  attempts += 1;
1944
1402
  }
1945
1403
  const base = serverDirectedBaseMs ?? minDelayMs;
1946
- // Compare against the ceiling scaled down rather than the base scaled up, so
1947
- // the computed value can never overflow the ceiling. A base of zero doubles
1948
- // to zero forever, so it short-circuits.
1949
1404
  let target = 0;
1950
1405
  if (base > 0) {
1951
1406
  const exponent = attempts - 1;
1952
1407
  target = base >= maxDelayMs / 2 ** exponent ? maxDelayMs : base * 2 ** exponent;
1953
1408
  }
1954
- const jitter = (random() * target) / 2;
1409
+ const jitter = random() * target / 2;
1955
1410
  nextDelayMs = Math.max(target - jitter, operatingCadenceMs);
1956
1411
  },
1957
1412
  recordSuccess() {
1958
1413
  resetPolicy.noteHealthy();
1959
1414
  resetIfDue();
1960
- // A backoff wait applies to a retry, not to every operation, so after a
1961
- // success the next wait is the ordinary interval even while the retry
1962
- // state is raised.
1963
1415
  nextDelayMs = operatingCadenceMs;
1964
1416
  },
1965
1417
  applyServerDirectedRetry(delayMs) {
1966
- if (typeof delayMs !== 'number' || !Number.isFinite(delayMs) || delayMs < 0) {
1418
+ if (typeof delayMs !== "number" || !Number.isFinite(delayMs) || delayMs < 0) {
1967
1419
  return;
1968
1420
  }
1969
1421
  serverDirectedBaseMs = delayMs;
1970
1422
  attempts = 0;
1971
- },
1423
+ }
1972
1424
  };
1973
1425
  }
1974
- /**
1975
- * Builds the retry state for a streaming data source: no wait during healthy
1976
- * operation, a normal regime running from the configured initial delay up to
1977
- * a 30 second ceiling, an extended regime of 5 minutes up to 1 hour, and a
1978
- * reset once a connection has been healthy for 60 seconds.
1979
- *
1980
- * The initial delay is validated here; the documented default of 1 second
1981
- * stands in for anything that is not a positive, finite number. A configured
1982
- * delay above the normal ceiling is clamped to it, while the extended regime
1983
- * never starts below the configured delay.
1984
- */
1426
+
1985
1427
  function forStreaming(initialReconnectDelayMs, logger) {
1986
- const validated = positiveFiniteOrDefault(initialReconnectDelayMs, DEFAULT_STREAMING_INITIAL_DELAY_MS, 'initialReconnectDelayMs', logger);
1428
+ const validated = positiveFiniteOrDefault(initialReconnectDelayMs, DEFAULT_STREAMING_INITIAL_DELAY_MS, "initialReconnectDelayMs", logger);
1987
1429
  return createRetryState({
1988
1430
  normalInitialDelayMs: validated,
1989
1431
  normalCeilingMs: STREAMING_NORMAL_CEILING_MS,
1990
1432
  extendedInitialDelayMs: Math.max(EXTENDED_INITIAL_DELAY_MS, validated),
1991
1433
  extendedCeilingMs: EXTENDED_CEILING_MS,
1992
1434
  resetPolicy: createAfterHealthyFor(STREAMING_RESET_INTERVAL_MS),
1993
- operatingCadenceMs: 0,
1435
+ operatingCadenceMs: 0
1994
1436
  });
1995
1437
  }
1996
- /**
1997
- * Builds the retry state for a polling data source: the poll interval is the
1998
- * operating cadence, so no wait is ever shorter than it; in the normal regime
1999
- * both bounds are the interval itself, so a normal failure simply polls again
2000
- * on schedule; the extended regime runs from 5 minutes (or the interval, if
2001
- * longer) up to 1 hour (or the interval, if longer); and the state resets
2002
- * after two successful polls in a row.
2003
- *
2004
- * The poll interval is validated here; the documented default of 30 seconds
2005
- * stands in for anything that is not a positive, finite number.
2006
- */
1438
+
2007
1439
  function forPolling(pollIntervalMs, logger) {
2008
- const validated = positiveFiniteOrDefault(pollIntervalMs, DEFAULT_POLL_INTERVAL_MS, 'pollIntervalMs', logger);
1440
+ const validated = positiveFiniteOrDefault(pollIntervalMs, DEFAULT_POLL_INTERVAL_MS, "pollIntervalMs", logger);
2009
1441
  return createRetryState({
2010
1442
  normalInitialDelayMs: validated,
2011
1443
  normalCeilingMs: validated,
2012
1444
  extendedInitialDelayMs: Math.max(EXTENDED_INITIAL_DELAY_MS, validated),
2013
1445
  extendedCeilingMs: EXTENDED_CEILING_MS,
2014
1446
  resetPolicy: createAfterConsecutiveSuccesses(POLLING_RESET_SUCCESSES),
2015
- operatingCadenceMs: validated,
1447
+ operatingCadenceMs: validated
2016
1448
  });
2017
1449
  }
2018
1450
 
2019
- /**
2020
- * Enable / disable Auto environment attributes. When enabled, the SDK will automatically
2021
- * provide data about the mobile environment where the application is running. This data makes it simpler to target
2022
- * your mobile customers based on application name or version, or on device characteristics including manufacturer,
2023
- * model, operating system, locale, and so on. We recommend enabling this when you configure the SDK. To learn more,
2024
- * read [Automatic environment attributes](https://docs.launchdarkly.com/sdk/features/environment-attributes).
2025
- * for more documentation.
2026
- */
2027
1451
  var AutoEnvAttributes;
2028
- (function (AutoEnvAttributes) {
1452
+
1453
+ (function(AutoEnvAttributes) {
2029
1454
  AutoEnvAttributes[AutoEnvAttributes["Disabled"] = 0] = "Disabled";
2030
1455
  AutoEnvAttributes[AutoEnvAttributes["Enabled"] = 1] = "Enabled";
2031
1456
  })(AutoEnvAttributes || (AutoEnvAttributes = {}));
2032
1457
 
2033
1458
  var LDEventType;
2034
- (function (LDEventType) {
1459
+
1460
+ (function(LDEventType) {
2035
1461
  LDEventType[LDEventType["AnalyticsEvents"] = 0] = "AnalyticsEvents";
2036
1462
  LDEventType[LDEventType["DiagnosticEvent"] = 1] = "DiagnosticEvent";
2037
1463
  })(LDEventType || (LDEventType = {}));
1464
+
2038
1465
  var LDDeliveryStatus;
2039
- (function (LDDeliveryStatus) {
1466
+
1467
+ (function(LDDeliveryStatus) {
2040
1468
  LDDeliveryStatus[LDDeliveryStatus["Succeeded"] = 0] = "Succeeded";
2041
1469
  LDDeliveryStatus[LDDeliveryStatus["Failed"] = 1] = "Failed";
2042
1470
  LDDeliveryStatus[LDDeliveryStatus["FailedAndMustShutDown"] = 2] = "FailedAndMustShutDown";
2043
1471
  })(LDDeliveryStatus || (LDDeliveryStatus = {}));
2044
1472
 
2045
- var index$1 = /*#__PURE__*/Object.freeze({
1473
+ var index$1 = Object.freeze({
2046
1474
  __proto__: null,
2047
- get DataSourceState () { return DataSourceState; },
2048
- get LDDeliveryStatus () { return LDDeliveryStatus; },
2049
- get LDEventType () { return LDEventType; }
1475
+ get DataSourceState() {
1476
+ return DataSourceState;
1477
+ },
1478
+ get LDDeliveryStatus() {
1479
+ return LDDeliveryStatus;
1480
+ },
1481
+ get LDEventType() {
1482
+ return LDEventType;
1483
+ }
2050
1484
  });
2051
1485
 
2052
- /**
2053
- * Attempt to produce a string representation of a value.
2054
- * The format should be roughly comparable to `util.format`
2055
- * aside from object which will be JSON versus the `util.inspect`
2056
- * format.
2057
- * @param val
2058
- * @returns A string representation of the value if possible.
2059
- */
2060
1486
  function tryStringify(val) {
2061
- if (typeof val === 'string') {
1487
+ if (typeof val === "string") {
2062
1488
  return val;
2063
1489
  }
2064
1490
  if (val === undefined) {
2065
- return 'undefined';
1491
+ return "undefined";
2066
1492
  }
2067
1493
  if (val === null) {
2068
- return 'null';
1494
+ return "null";
2069
1495
  }
2070
- if (Object.prototype.hasOwnProperty.call(val, 'toString')) {
1496
+ if (Object.prototype.hasOwnProperty.call(val, "toString")) {
2071
1497
  try {
2072
1498
  return val.toString();
2073
- }
2074
- catch {
2075
- /* Keep going */
2076
- }
1499
+ } catch {}
2077
1500
  }
2078
- if (typeof val === 'bigint') {
1501
+ if (typeof val === "bigint") {
2079
1502
  return `${val}n`;
2080
1503
  }
2081
1504
  try {
2082
1505
  return JSON.stringify(val);
2083
- }
2084
- catch (error) {
2085
- if (error instanceof TypeError && error.message.indexOf('circular') >= 0) {
2086
- return '[Circular]';
1506
+ } catch (error) {
1507
+ if (error instanceof TypeError && error.message.indexOf("circular") >= 0) {
1508
+ return "[Circular]";
2087
1509
  }
2088
- return '[Not Stringifiable]';
1510
+ return "[Not Stringifiable]";
2089
1511
  }
2090
1512
  }
2091
- /**
2092
- * Attempt to produce a numeric representation.
2093
- * BigInts have an `n` suffix.
2094
- * @param val
2095
- * @returns The numeric representation or 'NaN' if not numeric.
2096
- */
1513
+
2097
1514
  function toNumber(val) {
2098
- // Symbol has to be treated special because it will
2099
- // throw an exception if an attempt is made to convert it.
2100
- if (typeof val === 'symbol') {
2101
- return 'NaN';
1515
+ if (typeof val === "symbol") {
1516
+ return "NaN";
2102
1517
  }
2103
- if (typeof val === 'bigint') {
1518
+ if (typeof val === "bigint") {
2104
1519
  return `${val}n`;
2105
1520
  }
2106
1521
  return String(Number(val));
2107
1522
  }
2108
- /**
2109
- * Attempt to produce an integer representation.
2110
- * BigInts have an `n` suffix.
2111
- * @param val
2112
- * @returns The integer representation or 'NaN' if not numeric.
2113
- */
1523
+
2114
1524
  function toInt(val) {
2115
- if (typeof val === 'symbol') {
2116
- return 'NaN';
1525
+ if (typeof val === "symbol") {
1526
+ return "NaN";
2117
1527
  }
2118
- if (typeof val === 'bigint') {
1528
+ if (typeof val === "bigint") {
2119
1529
  return `${val}n`;
2120
1530
  }
2121
1531
  return String(parseInt(val, 10));
2122
1532
  }
2123
- /**
2124
- * Attempt to produce a float representation.
2125
- * BigInts have an `n` suffix.
2126
- * @param val
2127
- * @returns The integer representation or 'NaN' if not numeric.
2128
- */
1533
+
2129
1534
  function toFloat(val) {
2130
- if (typeof val === 'symbol') {
2131
- return 'NaN';
1535
+ if (typeof val === "symbol") {
1536
+ return "NaN";
2132
1537
  }
2133
1538
  return String(parseFloat(val));
2134
1539
  }
2135
- // Based on:
2136
- // https://nodejs.org/api/util.html#utilformatformat-args
2137
- // The result will not match node exactly, but it should get the
2138
- // right information through.
1540
+
2139
1541
  const escapes = {
2140
- s: (val) => tryStringify(val),
2141
- d: (val) => toNumber(val),
2142
- i: (val) => toInt(val),
2143
- f: (val) => toFloat(val),
2144
- j: (val) => tryStringify(val),
2145
- o: (val) => tryStringify(val),
2146
- // eslint-disable-next-line @typescript-eslint/naming-convention
2147
- O: (val) => tryStringify(val),
2148
- c: () => '',
1542
+ s: val => tryStringify(val),
1543
+ d: val => toNumber(val),
1544
+ i: val => toInt(val),
1545
+ f: val => toFloat(val),
1546
+ j: val => tryStringify(val),
1547
+ o: val => tryStringify(val),
1548
+ O: val => tryStringify(val),
1549
+ c: () => ""
2149
1550
  };
2150
- /**
2151
- * A basic formatted for use where `util.format` is not available.
2152
- * This will not be as performant, but it will produce formatted
2153
- * messages.
2154
- *
2155
- * @internal
2156
- *
2157
- * @param args
2158
- * @returns Formatted string.
2159
- */
1551
+
2160
1552
  function format(...args) {
2161
1553
  const formatString = args[0];
2162
1554
  if (TypeValidators.String.is(formatString)) {
2163
1555
  args.shift();
2164
- let out = '';
1556
+ let out = "";
2165
1557
  let i = 0;
2166
1558
  while (i < formatString.length) {
2167
1559
  const char = formatString.charAt(i);
2168
- if (char === '%') {
1560
+ if (char === "%") {
2169
1561
  const nextIndex = i + 1;
2170
1562
  if (nextIndex < formatString.length) {
2171
1563
  const nextChar = formatString.charAt(i + 1);
2172
1564
  if (nextChar in escapes && args.length) {
2173
1565
  const value = args.shift();
2174
- // This rule is for math.
2175
1566
  out += escapes[nextChar]?.(value);
2176
- }
2177
- else if (nextChar === '%') {
2178
- out += '%';
2179
- }
2180
- else {
1567
+ } else if (nextChar === "%") {
1568
+ out += "%";
1569
+ } else {
2181
1570
  out += `%${nextChar}`;
2182
1571
  }
2183
1572
  i += 2;
2184
- }
2185
- else {
2186
- // A trailing '%' has nothing to escape, so keep it as-is.
2187
- out += '%';
1573
+ } else {
1574
+ out += "%";
2188
1575
  i += 1;
2189
1576
  }
2190
- }
2191
- else {
1577
+ } else {
2192
1578
  out += char;
2193
1579
  i += 1;
2194
1580
  }
2195
1581
  }
2196
- // If there are any args left after we exhaust the format string
2197
- // then just stick those on the end.
2198
1582
  if (args.length) {
2199
1583
  if (out.length) {
2200
- out += ' ';
1584
+ out += " ";
2201
1585
  }
2202
- out += args.map(tryStringify).join(' ');
1586
+ out += args.map(tryStringify).join(" ");
2203
1587
  }
2204
1588
  return out;
2205
1589
  }
2206
- return args.map(tryStringify).join(' ');
1590
+ return args.map(tryStringify).join(" ");
2207
1591
  }
2208
1592
 
2209
1593
  var LogPriority;
2210
- (function (LogPriority) {
1594
+
1595
+ (function(LogPriority) {
2211
1596
  LogPriority[LogPriority["debug"] = 0] = "debug";
2212
1597
  LogPriority[LogPriority["info"] = 1] = "info";
2213
1598
  LogPriority[LogPriority["warn"] = 2] = "warn";
2214
1599
  LogPriority[LogPriority["error"] = 3] = "error";
2215
1600
  LogPriority[LogPriority["none"] = 4] = "none";
2216
1601
  })(LogPriority || (LogPriority = {}));
2217
- const LEVEL_NAMES = ['debug', 'info', 'warn', 'error', 'none'];
2218
- /**
2219
- * A basic logger which handles filtering by level.
2220
- *
2221
- * With the default options it will write to `console.error`
2222
- * and it will use the formatting provided by `console.error`.
2223
- * If the destination is overwritten, then it will use an included
2224
- * formatter similar to `util.format`.
2225
- *
2226
- * If a formatter is available, then that should be overridden
2227
- * as well for performance.
2228
- */
1602
+
1603
+ const LEVEL_NAMES = [ "debug", "info", "warn", "error", "none" ];
1604
+
2229
1605
  class BasicLogger {
2230
- /**
2231
- * This should only be used as a default fallback and not as a convenient
2232
- * solution. In most cases you should construct a new instance with the
2233
- * appropriate options for your specific needs.
2234
- */
2235
1606
  static get() {
2236
1607
  return new BasicLogger({});
2237
1608
  }
2238
1609
  constructor(options) {
2239
- this._logLevel = LogPriority[options.level ?? 'info'] ?? LogPriority.info;
2240
- this._name = options.name ?? 'LaunchDarkly';
1610
+ this._logLevel = LogPriority[options.level ?? "info"] ?? LogPriority.info;
1611
+ this._name = options.name ?? "LaunchDarkly";
2241
1612
  this._formatter = options.formatter;
2242
- if (typeof options.destination === 'object') {
1613
+ if (typeof options.destination === "object") {
2243
1614
  this._destinations = {
2244
1615
  [LogPriority.debug]: options.destination.debug,
2245
1616
  [LogPriority.info]: options.destination.info,
2246
1617
  [LogPriority.warn]: options.destination.warn,
2247
- [LogPriority.error]: options.destination.error,
1618
+ [LogPriority.error]: options.destination.error
2248
1619
  };
2249
- }
2250
- else if (typeof options.destination === 'function') {
2251
- const { destination } = options;
1620
+ } else if (typeof options.destination === "function") {
1621
+ const {destination: destination} = options;
2252
1622
  this._destinations = {
2253
1623
  [LogPriority.debug]: destination,
2254
1624
  [LogPriority.info]: destination,
2255
1625
  [LogPriority.warn]: destination,
2256
- [LogPriority.error]: destination,
1626
+ [LogPriority.error]: destination
2257
1627
  };
2258
1628
  }
2259
1629
  }
2260
1630
  _tryFormat(...args) {
2261
1631
  try {
2262
1632
  if (this._formatter) {
2263
- // In case the provided formatter fails.
2264
1633
  return this._formatter?.(...args);
2265
1634
  }
2266
1635
  return format(...args);
2267
- }
2268
- catch {
1636
+ } catch {
2269
1637
  return format(...args);
2270
1638
  }
2271
1639
  }
2272
1640
  _tryWrite(destination, msg) {
2273
1641
  try {
2274
1642
  destination(msg);
2275
- }
2276
- catch {
2277
- // eslint-disable-next-line no-console
1643
+ } catch {
2278
1644
  console.error(msg);
2279
1645
  }
2280
1646
  }
@@ -2285,17 +1651,10 @@ class BasicLogger {
2285
1651
  const destination = this._destinations?.[level];
2286
1652
  if (destination) {
2287
1653
  this._tryWrite(destination, `${prefix} ${this._tryFormat(...args)}`);
2288
- }
2289
- else {
2290
- // `console.error` has its own formatter.
2291
- // So we don't need to do anything.
2292
- // eslint-disable-next-line no-console
1654
+ } else {
2293
1655
  console.error(...args);
2294
1656
  }
2295
- }
2296
- catch {
2297
- // If all else fails do not break.
2298
- // eslint-disable-next-line no-console
1657
+ } catch {
2299
1658
  console.error(...args);
2300
1659
  }
2301
1660
  }
@@ -2318,33 +1677,14 @@ const loggerRequirements = {
2318
1677
  error: TypeValidators.Function,
2319
1678
  warn: TypeValidators.Function,
2320
1679
  info: TypeValidators.Function,
2321
- debug: TypeValidators.Function,
1680
+ debug: TypeValidators.Function
2322
1681
  };
2323
- /**
2324
- * The safeLogger logic exists because we allow the application to pass in a custom logger, but
2325
- * there is no guarantee that the logger works correctly and if it ever throws exceptions there
2326
- * could be serious consequences (e.g. an uncaught exception within an error event handler, due
2327
- * to the SDK trying to log the error, can terminate the application). An exception could result
2328
- * from faulty logic in the logger implementation, or it could be that this is not a logger at
2329
- * all but some other kind of object; the former is handled by a catch block that logs an error
2330
- * message to the SDK's default logger, and we can at least partly guard against the latter by
2331
- * checking for the presence of required methods at configuration time.
2332
- */
1682
+
2333
1683
  class SafeLogger {
2334
- /**
2335
- * Construct a safe logger with the specified logger.
2336
- * @param logger The logger to use.
2337
- * @param fallback A fallback logger to use in case an issue is encountered using
2338
- * the provided logger.
2339
- */
2340
1684
  constructor(logger, fallback) {
2341
1685
  Object.entries(loggerRequirements).forEach(([level, validator]) => {
2342
1686
  if (!validator.is(logger[level])) {
2343
1687
  throw new Error(`Provided logger instance must support logger.${level}(...) method`);
2344
- // Note that the SDK normally does not throw exceptions to the application, but that rule
2345
- // does not apply to LDClient.init() which will throw an exception if the parameters are so
2346
- // invalid that we cannot proceed with creating the client. An invalid logger meets those
2347
- // criteria since the SDK calls the logger during nearly all of its operations.
2348
1688
  }
2349
1689
  });
2350
1690
  this._logger = logger;
@@ -2353,39 +1693,33 @@ class SafeLogger {
2353
1693
  _log(level, args) {
2354
1694
  try {
2355
1695
  this._logger[level](...args);
2356
- }
2357
- catch {
2358
- // If all else fails do not break.
1696
+ } catch {
2359
1697
  this._fallback[level](...args);
2360
1698
  }
2361
1699
  }
2362
1700
  error(...args) {
2363
- this._log('error', args);
1701
+ this._log("error", args);
2364
1702
  }
2365
1703
  warn(...args) {
2366
- this._log('warn', args);
1704
+ this._log("warn", args);
2367
1705
  }
2368
1706
  info(...args) {
2369
- this._log('info', args);
1707
+ this._log("info", args);
2370
1708
  }
2371
1709
  debug(...args) {
2372
- this._log('debug', args);
1710
+ this._log("debug", args);
2373
1711
  }
2374
1712
  }
2375
1713
 
2376
- const createSafeLogger = (logger) => {
1714
+ const createSafeLogger = logger => {
2377
1715
  const basicLogger = new BasicLogger({
2378
- level: 'info',
2379
- // eslint-disable-next-line no-console
1716
+ level: "info",
2380
1717
  destination: console.error,
2381
- formatter: format,
1718
+ formatter: format
2382
1719
  });
2383
1720
  return logger ? new SafeLogger(logger, basicLogger) : basicLogger;
2384
1721
  };
2385
1722
 
2386
- /**
2387
- * Messages for issues which can be encountered from processing the configuration options.
2388
- */
2389
1723
  class OptionMessages {
2390
1724
  static deprecated(oldName, newName) {
2391
1725
  return `"${oldName}" is deprecated, please use "${newName}"`;
@@ -2413,25 +1747,30 @@ class OptionMessages {
2413
1747
  }
2414
1748
  }
2415
1749
 
2416
- /**
2417
- * Expression to validate characters that are allowed in tag keys and values.
2418
- */
2419
1750
  const allowedTagCharacters = /^(\w|\.|-)+$/;
1751
+
2420
1752
  const regexValidator = TypeValidators.stringMatchingRegex(allowedTagCharacters);
1753
+
2421
1754
  const tagValidator = {
2422
1755
  is: (u, name) => {
2423
1756
  if (regexValidator.is(u)) {
2424
1757
  if (u.length > 64) {
2425
- return { valid: false, message: OptionMessages.tagValueTooLong(name) };
1758
+ return {
1759
+ valid: false,
1760
+ message: OptionMessages.tagValueTooLong(name)
1761
+ };
2426
1762
  }
2427
- return { valid: true };
1763
+ return {
1764
+ valid: true
1765
+ };
2428
1766
  }
2429
- return { valid: false, message: OptionMessages.invalidTagValue(name) };
2430
- },
1767
+ return {
1768
+ valid: false,
1769
+ message: OptionMessages.invalidTagValue(name)
1770
+ };
1771
+ }
2431
1772
  };
2432
- /**
2433
- * Class for managing tags.
2434
- */
1773
+
2435
1774
  class ApplicationTags {
2436
1775
  constructor(options) {
2437
1776
  const tags = {};
@@ -2440,33 +1779,24 @@ class ApplicationTags {
2440
1779
  if (application) {
2441
1780
  Object.entries(application).forEach(([key, value]) => {
2442
1781
  if (value !== null && value !== undefined) {
2443
- const { valid, message } = tagValidator.is(value, `application.${key}`);
1782
+ const {valid: valid, message: message} = tagValidator.is(value, `application.${key}`);
2444
1783
  if (!valid) {
2445
1784
  logger?.warn(message);
2446
- }
2447
- else if (key === 'versionName') {
2448
- tags[`application-version-name`] = [value];
2449
- }
2450
- else {
2451
- tags[`application-${key}`] = [value];
1785
+ } else if (key === "versionName") {
1786
+ tags[`application-version-name`] = [ value ];
1787
+ } else {
1788
+ tags[`application-${key}`] = [ value ];
2452
1789
  }
2453
1790
  }
2454
1791
  });
2455
1792
  }
2456
1793
  const tagKeys = Object.keys(tags);
2457
1794
  if (tagKeys.length) {
2458
- this.value = tagKeys
2459
- .sort()
2460
- .flatMap((key) => tags[key].sort().map((value) => `${key}/${value}`))
2461
- .join(' ');
1795
+ this.value = tagKeys.sort().flatMap(key => tags[key].sort().map(value => `${key}/${value}`)).join(" ");
2462
1796
  }
2463
1797
  }
2464
1798
  }
2465
1799
 
2466
- /**
2467
- * The client context provides basic configuration and platform support which are required
2468
- * when building SDK components.
2469
- */
2470
1800
  class ClientContext {
2471
1801
  constructor(sdkKey, configuration, platform) {
2472
1802
  this.platform = platform;
@@ -2475,22 +1805,21 @@ class ClientContext {
2475
1805
  logger: configuration.logger,
2476
1806
  offline: configuration.offline,
2477
1807
  serviceEndpoints: configuration.serviceEndpoints,
2478
- sdkKey,
1808
+ sdkKey: sdkKey
2479
1809
  };
2480
1810
  }
2481
1811
  }
2482
1812
 
2483
1813
  function canonicalizeUri(uri) {
2484
- return uri.replace(/\/+$/, '');
1814
+ return uri.replace(/\/+$/, "");
2485
1815
  }
1816
+
2486
1817
  function canonicalizePath(path) {
2487
- return path.replace(/^\/+/, '').replace(/\?$/, '');
1818
+ return path.replace(/^\/+/, "").replace(/\?$/, "");
2488
1819
  }
2489
- /**
2490
- * Specifies the base service URIs used by SDK components.
2491
- */
1820
+
2492
1821
  class ServiceEndpoints {
2493
- constructor(streaming, polling, events = ServiceEndpoints.DEFAULT_EVENTS, analyticsEventPath = '/bulk', diagnosticEventPath = '/diagnostic', includeAuthorizationHeader = true, payloadFilterKey) {
1822
+ constructor(streaming, polling, events = ServiceEndpoints.DEFAULT_EVENTS, analyticsEventPath = "/bulk", diagnosticEventPath = "/diagnostic", includeAuthorizationHeader = true, payloadFilterKey) {
2494
1823
  this.streaming = canonicalizeUri(streaming);
2495
1824
  this.polling = canonicalizeUri(polling);
2496
1825
  this.events = canonicalizeUri(events);
@@ -2500,52 +1829,41 @@ class ServiceEndpoints {
2500
1829
  this.payloadFilterKey = payloadFilterKey;
2501
1830
  }
2502
1831
  }
2503
- // eslint-disable-next-line @typescript-eslint/naming-convention
2504
- ServiceEndpoints.DEFAULT_EVENTS = 'https://events.launchdarkly.com';
1832
+
1833
+ ServiceEndpoints.DEFAULT_EVENTS = "https://events.launchdarkly.com";
1834
+
2505
1835
  function getWithParams(uri, parameters = []) {
2506
1836
  if (parameters.length === 0) {
2507
1837
  return uri;
2508
1838
  }
2509
- const parts = parameters.map(({ key, value }) => `${key}=${value}`);
2510
- return `${uri}?${parts.join('&')}`;
1839
+ const parts = parameters.map(({key: key, value: value}) => `${key}=${value}`);
1840
+ return `${uri}?${parts.join("&")}`;
2511
1841
  }
2512
- /**
2513
- * Get the URI for the streaming endpoint.
2514
- *
2515
- * @param endpoints The service endpoints.
2516
- * @param path The path to the resource, devoid of any query parameters or hrefs.
2517
- * @param parameters The query parameters. These query parameters must already have the appropriate encoding applied. This function WILL NOT apply it for you.
2518
- */
1842
+
2519
1843
  function getStreamingUri(endpoints, path, parameters) {
2520
1844
  const canonicalizedPath = canonicalizePath(path);
2521
- const combinedParameters = [...parameters];
1845
+ const combinedParameters = [ ...parameters ];
2522
1846
  if (endpoints.payloadFilterKey) {
2523
- combinedParameters.push({ key: 'filter', value: endpoints.payloadFilterKey });
1847
+ combinedParameters.push({
1848
+ key: "filter",
1849
+ value: endpoints.payloadFilterKey
1850
+ });
2524
1851
  }
2525
1852
  return getWithParams(`${endpoints.streaming}/${canonicalizedPath}`, combinedParameters);
2526
1853
  }
2527
- /**
2528
- * Get the URI for the polling endpoint.
2529
- *
2530
- * @param endpoints The service endpoints.
2531
- * @param path The path to the resource, devoid of any query parameters or hrefs.
2532
- * @param parameters The query parameters. These query parameters must already have the appropriate encoding applied. This function WILL NOT apply it for you.
2533
- */
1854
+
2534
1855
  function getPollingUri(endpoints, path, parameters = []) {
2535
1856
  const canonicalizedPath = canonicalizePath(path);
2536
- const combinedParameters = [...parameters];
1857
+ const combinedParameters = [ ...parameters ];
2537
1858
  if (endpoints.payloadFilterKey) {
2538
- combinedParameters.push({ key: 'filter', value: endpoints.payloadFilterKey });
1859
+ combinedParameters.push({
1860
+ key: "filter",
1861
+ value: endpoints.payloadFilterKey
1862
+ });
2539
1863
  }
2540
1864
  return getWithParams(`${endpoints.polling}/${canonicalizedPath}`, combinedParameters);
2541
1865
  }
2542
- /**
2543
- * Get the URI for the events endpoint.
2544
- *
2545
- * @param endpoints The service endpoints.
2546
- * @param path The path to the resource, devoid of any query parameters or hrefs.
2547
- * @param parameters The query parameters. These query parameters must already have the appropriate encoding applied. This function WILL NOT apply it for you.
2548
- */
1866
+
2549
1867
  function getEventsUri(endpoints, path, parameters = []) {
2550
1868
  const canonicalizedPath = canonicalizePath(path);
2551
1869
  return getWithParams(`${endpoints.events}/${canonicalizedPath}`, parameters);
@@ -2560,18 +1878,14 @@ class DiagnosticsManager {
2560
1878
  this._dataSinceDate = this._startTime;
2561
1879
  this._id = {
2562
1880
  diagnosticId: _platform.crypto.randomUUID(),
2563
- sdkKeySuffix: sdkKey.length > 6 ? sdkKey.substring(sdkKey.length - 6) : sdkKey,
1881
+ sdkKeySuffix: sdkKey.length > 6 ? sdkKey.substring(sdkKey.length - 6) : sdkKey
2564
1882
  };
2565
1883
  }
2566
- /**
2567
- * Creates the initial event that is sent by the event processor when the SDK starts up. This will
2568
- * not be repeated during the lifetime of the SDK client.
2569
- */
2570
1884
  createInitEvent() {
2571
1885
  const sdkData = this._platform.info.sdkData();
2572
1886
  const platformData = this._platform.info.platformData();
2573
1887
  return {
2574
- kind: 'diagnostic-init',
1888
+ kind: "diagnostic-init",
2575
1889
  id: this._id,
2576
1890
  creationDate: this._startTime,
2577
1891
  sdk: sdkData,
@@ -2581,41 +1895,29 @@ class DiagnosticsManager {
2581
1895
  osArch: platformData.os?.arch,
2582
1896
  osName: platformData.os?.name,
2583
1897
  osVersion: platformData.os?.version,
2584
- ...(platformData.additional || {}),
2585
- },
1898
+ ...platformData.additional || {}
1899
+ }
2586
1900
  };
2587
1901
  }
2588
- /**
2589
- * Records a stream connection attempt (called by the stream processor).
2590
- *
2591
- * @param timestamp Time of the *beginning* of the connection attempt.
2592
- * @param failed True if the connection failed, or we got a read timeout before receiving a "put".
2593
- * @param durationMillis Elapsed time between starting timestamp and when we either gave up/lost
2594
- * the connection or received a successful "put".
2595
- */
2596
1902
  recordStreamInit(timestamp, failed, durationMillis) {
2597
- const item = { timestamp, failed, durationMillis };
1903
+ const item = {
1904
+ timestamp: timestamp,
1905
+ failed: failed,
1906
+ durationMillis: durationMillis
1907
+ };
2598
1908
  this._streamInits.push(item);
2599
1909
  }
2600
- /**
2601
- * Creates a periodic event containing time-dependent stats, and resets the state of the manager
2602
- * with regard to those stats.
2603
- *
2604
- * Note: the reason droppedEvents, deduplicatedUsers, and eventsInLastBatch are passed into this
2605
- * function, instead of being properties of the DiagnosticsManager, is that the event processor is
2606
- * the one who's calling this function and is also the one who's tracking those stats.
2607
- */
2608
1910
  createStatsEventAndReset(droppedEvents, deduplicatedUsers, eventsInLastBatch) {
2609
1911
  const currentTime = Date.now();
2610
1912
  const evt = {
2611
- kind: 'diagnostic',
1913
+ kind: "diagnostic",
2612
1914
  id: this._id,
2613
1915
  creationDate: currentTime,
2614
1916
  dataSinceDate: this._dataSinceDate,
2615
- droppedEvents,
2616
- deduplicatedUsers,
2617
- eventsInLastBatch,
2618
- streamInits: this._streamInits,
1917
+ droppedEvents: droppedEvents,
1918
+ deduplicatedUsers: deduplicatedUsers,
1919
+ eventsInLastBatch: eventsInLastBatch,
1920
+ streamInits: this._streamInits
2619
1921
  };
2620
1922
  this._streamInits = [];
2621
1923
  this._dataSinceDate = currentTime;
@@ -2623,42 +1925,36 @@ class DiagnosticsManager {
2623
1925
  }
2624
1926
  }
2625
1927
 
2626
- /**
2627
- * Different kinds of error which may be encountered during evaluation.
2628
- */
2629
1928
  var ErrorKinds;
2630
- (function (ErrorKinds) {
1929
+
1930
+ (function(ErrorKinds) {
2631
1931
  ErrorKinds["MalformedFlag"] = "MALFORMED_FLAG";
2632
1932
  ErrorKinds["UserNotSpecified"] = "USER_NOT_SPECIFIED";
2633
1933
  ErrorKinds["FlagNotFound"] = "FLAG_NOT_FOUND";
2634
1934
  ErrorKinds["ClientNotReady"] = "CLIENT_NOT_READY";
2635
1935
  ErrorKinds["WrongType"] = "WRONG_TYPE";
2636
1936
  })(ErrorKinds || (ErrorKinds = {}));
1937
+
2637
1938
  var ErrorKinds$1 = ErrorKinds;
2638
1939
 
2639
- /**
2640
- * Messages for issues which can be encountered processing client requests.
2641
- */
2642
1940
  class ClientMessages {
2643
1941
  static invalidMetricValue(badType) {
2644
- return ('The track function was called with a non-numeric "metricValue"' +
2645
- ` (${badType}), only numeric metric values are supported.`);
1942
+ return 'The track function was called with a non-numeric "metricValue"' + ` (${badType}), only numeric metric values are supported.`;
2646
1943
  }
2647
1944
  }
2648
- ClientMessages.MissingContextKeyNoEvent = 'Context was unspecified or had no key; event will not be sent';
2649
1945
 
2650
- /**
2651
- * The Fetch Standard caps the total body size of in-flight keepalive requests at 64 KiB. The
2652
- * body length is in UTF-16 code units, and each code unit is at least one byte, so a body over
2653
- * this length is always over the cap. A shorter body with non-ASCII text can still be over it.
2654
- */
1946
+ ClientMessages.MissingContextKeyNoEvent = "Context was unspecified or had no key; event will not be sent";
1947
+
2655
1948
  const KEEPALIVE_BODY_LIMIT = 64 * 1024;
1949
+
2656
1950
  class EventSender {
2657
1951
  constructor(clientContext, baseHeaders) {
2658
- const { basicConfiguration, platform } = clientContext;
2659
- const { serviceEndpoints: { analyticsEventPath, diagnosticEventPath }, } = basicConfiguration;
2660
- const { crypto, requests } = platform;
2661
- this._defaultHeaders = { ...baseHeaders };
1952
+ const {basicConfiguration: basicConfiguration, platform: platform} = clientContext;
1953
+ const {serviceEndpoints: {analyticsEventPath: analyticsEventPath, diagnosticEventPath: diagnosticEventPath}} = basicConfiguration;
1954
+ const {crypto: crypto, requests: requests} = platform;
1955
+ this._defaultHeaders = {
1956
+ ...baseHeaders
1957
+ };
2662
1958
  this._eventsUri = getEventsUri(basicConfiguration.serviceEndpoints, analyticsEventPath, []);
2663
1959
  this._diagnosticEventsUri = getEventsUri(basicConfiguration.serviceEndpoints, diagnosticEventPath, []);
2664
1960
  this._requests = requests;
@@ -2666,63 +1962,54 @@ class EventSender {
2666
1962
  }
2667
1963
  async _tryPostingEvents(events, uri, payloadId, canRetry) {
2668
1964
  const tryRes = {
2669
- status: LDDeliveryStatus.Succeeded,
1965
+ status: LDDeliveryStatus.Succeeded
2670
1966
  };
2671
1967
  const headers = {
2672
1968
  ...this._defaultHeaders,
2673
- 'content-type': 'application/json',
1969
+ "content-type": "application/json"
2674
1970
  };
2675
1971
  if (payloadId) {
2676
- headers['x-launchdarkly-payload-id'] = payloadId;
2677
- headers['x-launchDarkly-event-schema'] = '4';
1972
+ headers["x-launchdarkly-payload-id"] = payloadId;
1973
+ headers["x-launchDarkly-event-schema"] = "4";
2678
1974
  }
2679
1975
  let error;
2680
1976
  try {
2681
1977
  const body = JSON.stringify(events);
2682
- const { status, headers: resHeaders } = await this._requests.fetch(uri, {
2683
- headers,
2684
- body,
1978
+ const {status: status, headers: resHeaders} = await this._requests.fetch(uri, {
1979
+ headers: headers,
1980
+ body: body,
2685
1981
  compressBodyIfPossible: true,
2686
- method: 'POST',
2687
- // When sending events from browser environments the request should be completed even
2688
- // if the user is navigating away from the page. A browser rejects a keepalive request
2689
- // with a large body, so a large body is sent without it. The retry is the last attempt,
2690
- // so it never asks for keepalive. This lets a body the length check missed get through.
2691
- keepalive: canRetry && body.length <= KEEPALIVE_BODY_LIMIT,
1982
+ method: "POST",
1983
+ keepalive: canRetry && body.length <= KEEPALIVE_BODY_LIMIT
2692
1984
  });
2693
- const serverDate = Date.parse(resHeaders.get('date') || '');
1985
+ const serverDate = Date.parse(resHeaders.get("date") || "");
2694
1986
  if (serverDate) {
2695
1987
  tryRes.serverTime = serverDate;
2696
1988
  }
2697
1989
  if (status <= 204) {
2698
1990
  return tryRes;
2699
1991
  }
2700
- error = new LDUnexpectedResponseError(httpErrorMessage({ status, message: 'some events were dropped' }, 'event posting'));
1992
+ error = new LDUnexpectedResponseError(httpErrorMessage({
1993
+ status: status,
1994
+ message: "some events were dropped"
1995
+ }, "event posting"));
2701
1996
  if (!isHttpRecoverable(status)) {
2702
- // If the HTTP request isn't recoverable. Meaning if we made the same request it
2703
- // would not recover, then we check if a different request could recover.
2704
- // If a different request could not recover, then we shutdown. If a different request could
2705
- // recover, then we just don't retry this specific request.
2706
1997
  if (!isHttpLocallyRecoverable(status)) {
2707
1998
  tryRes.status = LDDeliveryStatus.FailedAndMustShutDown;
2708
- }
2709
- else {
1999
+ } else {
2710
2000
  tryRes.status = LDDeliveryStatus.Failed;
2711
2001
  }
2712
2002
  tryRes.error = error;
2713
2003
  return tryRes;
2714
2004
  }
2715
- }
2716
- catch (err) {
2005
+ } catch (err) {
2717
2006
  error = err;
2718
2007
  }
2719
- // recoverable but not retrying
2720
2008
  if (error && !canRetry) {
2721
2009
  tryRes.status = LDDeliveryStatus.Failed;
2722
2010
  tryRes.error = error;
2723
2011
  return tryRes;
2724
2012
  }
2725
- // wait 1 second before retrying
2726
2013
  await sleep();
2727
2014
  return this._tryPostingEvents(events, this._eventsUri, payloadId, false);
2728
2015
  }
@@ -2734,18 +2021,17 @@ class EventSender {
2734
2021
  }
2735
2022
 
2736
2023
  function isFeature(u) {
2737
- return u.kind === 'feature';
2024
+ return u.kind === "feature";
2738
2025
  }
2026
+
2739
2027
  function isIdentify(u) {
2740
- return u.kind === 'identify';
2028
+ return u.kind === "identify";
2741
2029
  }
2030
+
2742
2031
  function isMigration(u) {
2743
- return u.kind === 'migration_op';
2032
+ return u.kind === "migration_op";
2744
2033
  }
2745
2034
 
2746
- /**
2747
- * @internal
2748
- */
2749
2035
  class SummaryCounter {
2750
2036
  constructor(count, key, value, defValue, version, variation, overrideAffected) {
2751
2037
  this.count = count;
@@ -2761,22 +2047,18 @@ class SummaryCounter {
2761
2047
  }
2762
2048
  }
2763
2049
 
2764
- // The override marker is part of the key, so override-affected and other evaluations of the same
2765
- // flag, variation, and version accumulate into separate counters.
2766
2050
  function counterKey(event) {
2767
- return `${event.key}:${event.variation !== null && event.variation !== undefined ? event.variation : ''}:${event.version !== null && event.version !== undefined ? event.version : ''}:${event.overrideAffected ? 'overrideAffected' : ''}`;
2051
+ return `${event.key}:${event.variation !== null && event.variation !== undefined ? event.variation : ""}:${event.version !== null && event.version !== undefined ? event.version : ""}:${event.overrideAffected ? "overrideAffected" : ""}`;
2768
2052
  }
2769
- /**
2770
- * @internal
2771
- */
2053
+
2772
2054
  class EventSummarizer {
2773
2055
  constructor(_singleContext = false, _contextFilter) {
2774
2056
  this._singleContext = _singleContext;
2775
2057
  this._contextFilter = _contextFilter;
2776
2058
  this._startDate = 0;
2777
2059
  this._endDate = 0;
2778
- this._counters = {};
2779
- this._contextKinds = {};
2060
+ this._counters = new Map;
2061
+ this._contextKinds = new Map;
2780
2062
  }
2781
2063
  summarizeEvent(event) {
2782
2064
  if (isFeature(event) && !event.excludeFromSummaries) {
@@ -2784,18 +2066,17 @@ class EventSummarizer {
2784
2066
  this._context = event.context;
2785
2067
  }
2786
2068
  const countKey = counterKey(event);
2787
- const counter = this._counters[countKey];
2788
- let kinds = this._contextKinds[event.key];
2069
+ const counter = this._counters.get(countKey);
2070
+ let kinds = this._contextKinds.get(event.key);
2789
2071
  if (!kinds) {
2790
- kinds = new Set();
2791
- this._contextKinds[event.key] = kinds;
2072
+ kinds = new Set;
2073
+ this._contextKinds.set(event.key, kinds);
2792
2074
  }
2793
- event.context.kinds.forEach((kind) => kinds.add(kind));
2075
+ event.context.kinds.forEach(kind => kinds.add(kind));
2794
2076
  if (counter) {
2795
2077
  counter.increment();
2796
- }
2797
- else {
2798
- this._counters[countKey] = new SummaryCounter(1, event.key, event.value, event.default, event.version, event.variation, event.overrideAffected);
2078
+ } else {
2079
+ this._counters.set(countKey, new SummaryCounter(1, event.key, event.value, event.default, event.version, event.variation, event.overrideAffected));
2799
2080
  }
2800
2081
  if (this._startDate === 0 || event.creationDate < this._startDate) {
2801
2082
  this._startDate = event.creationDate;
@@ -2806,44 +2087,40 @@ class EventSummarizer {
2806
2087
  }
2807
2088
  }
2808
2089
  getSummary() {
2809
- const features = Object.values(this._counters).reduce((acc, counter) => {
2090
+ const features = [ ...this._counters.values() ].reduce((acc, counter) => {
2810
2091
  let flagSummary = acc[counter.key];
2811
2092
  if (!flagSummary) {
2812
2093
  flagSummary = {
2813
2094
  default: counter.default,
2814
2095
  counters: [],
2815
- contextKinds: [...this._contextKinds[counter.key]],
2096
+ contextKinds: [ ...this._contextKinds.get(counter.key) ?? [] ]
2816
2097
  };
2817
2098
  acc[counter.key] = flagSummary;
2818
2099
  }
2819
2100
  const counterOut = {
2820
2101
  value: counter.value,
2821
- count: counter.count,
2102
+ count: counter.count
2822
2103
  };
2823
2104
  if (counter.variation !== undefined && counter.variation !== null) {
2824
2105
  counterOut.variation = counter.variation;
2825
2106
  }
2826
2107
  if (counter.version !== undefined && counter.version !== null) {
2827
2108
  counterOut.version = counter.version;
2828
- }
2829
- else {
2109
+ } else {
2830
2110
  counterOut.unknown = true;
2831
2111
  }
2832
2112
  if (counter.overrideAffected) {
2833
- // The marker is present only when true, like the unknown marker.
2834
2113
  counterOut.overrideAffected = true;
2835
2114
  }
2836
2115
  flagSummary.counters.push(counterOut);
2837
2116
  return acc;
2838
- }, {});
2117
+ }, Object.create(null));
2839
2118
  const event = {
2840
2119
  startDate: this._startDate,
2841
2120
  endDate: this._endDate,
2842
- features,
2843
- kind: 'summary',
2844
- context: this._context !== undefined && this._singleContext
2845
- ? this._contextFilter?.filter(this._context)
2846
- : undefined,
2121
+ features: features,
2122
+ kind: "summary",
2123
+ context: this._context !== undefined && this._singleContext ? this._contextFilter?.filter(this._context) : undefined
2847
2124
  };
2848
2125
  this._clearSummary();
2849
2126
  return event;
@@ -2851,15 +2128,15 @@ class EventSummarizer {
2851
2128
  _clearSummary() {
2852
2129
  this._startDate = 0;
2853
2130
  this._endDate = 0;
2854
- this._counters = {};
2855
- this._contextKinds = {};
2131
+ this._counters = new Map;
2132
+ this._contextKinds = new Map;
2856
2133
  }
2857
2134
  }
2858
2135
 
2859
2136
  class LDInvalidSDKKeyError extends Error {
2860
2137
  constructor(message) {
2861
2138
  super(message);
2862
- this.name = 'LaunchDarklyInvalidSDKKeyError';
2139
+ this.name = "LaunchDarklyInvalidSDKKeyError";
2863
2140
  }
2864
2141
  }
2865
2142
 
@@ -2874,9 +2151,7 @@ class MultiEventSummarizer {
2874
2151
  const key = event.context.canonicalUnfilteredJson();
2875
2152
  if (!key) {
2876
2153
  if (event.context.valid) {
2877
- // The context appeared valid, but it could not be hashed.
2878
- // This is likely because of a cycle in the data.
2879
- this._logger?.error('Unable to serialize context, likely the context contains a cycle.');
2154
+ this._logger?.error("Unable to serialize context, likely the context contains a cycle.");
2880
2155
  }
2881
2156
  return;
2882
2157
  }
@@ -2891,33 +2166,25 @@ class MultiEventSummarizer {
2891
2166
  getSummaries() {
2892
2167
  const summarizersToFlush = this._summarizers;
2893
2168
  this._summarizers = {};
2894
- return Object.values(summarizersToFlush).map((summarizer) => summarizer.getSummary());
2169
+ return Object.values(summarizersToFlush).map(summarizer => summarizer.getSummary());
2895
2170
  }
2896
2171
  }
2897
2172
 
2898
- /**
2899
- * The contents of this file are for event sampling. They are not used for
2900
- * any purpose requiring cryptographic security.
2901
- * */
2902
2173
  function shouldSample(ratio) {
2903
2174
  const truncated = Math.trunc(ratio);
2904
- // A radio of 1 means 1 in 1. So that will always sample. No need
2905
- // to draw a random number.
2906
2175
  if (truncated === 1) {
2907
2176
  return true;
2908
2177
  }
2909
2178
  if (truncated === 0) {
2910
2179
  return false;
2911
2180
  }
2912
- // Math.random() * truncated) would return 0, 1, ... (ratio - 1).
2913
- // Checking for any number in the range will have approximately a 1 in X
2914
- // chance. So we check for 0 as it is part of any range.
2915
2181
  return Math.floor(Math.random() * truncated) === 0;
2916
2182
  }
2917
2183
 
2918
2184
  function isMultiEventSummarizer(summarizer) {
2919
2185
  return summarizer.getSummaries !== undefined;
2920
2186
  }
2187
+
2921
2188
  class EventProcessor {
2922
2189
  constructor(_config, clientContext, baseHeaders, _contextDeduplicator, _diagnosticsManager, start = true, summariesPerContext = false) {
2923
2190
  this._config = _config;
@@ -2934,12 +2201,11 @@ class EventProcessor {
2934
2201
  this._capacity = _config.eventsCapacity;
2935
2202
  this._logger = clientContext.basicConfiguration.logger;
2936
2203
  this._eventSender = new EventSender(clientContext, baseHeaders);
2937
- this._contextFilter = new ContextFilter(_config.allAttributesPrivate, _config.privateAttributes.map((ref) => new AttributeReference(ref)));
2204
+ this._contextFilter = new ContextFilter(_config.allAttributesPrivate, _config.privateAttributes.map(ref => new AttributeReference(ref)));
2938
2205
  if (summariesPerContext) {
2939
2206
  this._summarizer = new MultiEventSummarizer(this._contextFilter, this._logger);
2940
- }
2941
- else {
2942
- this._summarizer = new EventSummarizer();
2207
+ } else {
2208
+ this._summarizer = new EventSummarizer;
2943
2209
  }
2944
2210
  if (start) {
2945
2211
  this.start();
@@ -2949,17 +2215,15 @@ class EventProcessor {
2949
2215
  if (this._contextDeduplicator?.flushInterval !== undefined) {
2950
2216
  this._flushUsersTimer = setInterval(() => {
2951
2217
  this._contextDeduplicator?.flush();
2952
- }, this._contextDeduplicator.flushInterval * 1000);
2218
+ }, this._contextDeduplicator.flushInterval * 1e3);
2953
2219
  }
2954
2220
  this._flushTimer = setInterval(async () => {
2955
2221
  try {
2956
2222
  await this.flush();
2957
- }
2958
- catch (e) {
2959
- // Log errors and swallow them
2223
+ } catch (e) {
2960
2224
  this._logger?.debug(`Flush failed: ${e}`);
2961
2225
  }
2962
- }, this._config.flushInterval * 1000);
2226
+ }, this._config.flushInterval * 1e3);
2963
2227
  if (this._diagnosticsManager) {
2964
2228
  const initEvent = this._diagnosticsManager.createInitEvent();
2965
2229
  this._postDiagnosticEvent(initEvent);
@@ -2968,9 +2232,9 @@ class EventProcessor {
2968
2232
  this._droppedEvents = 0;
2969
2233
  this._deduplicatedUsers = 0;
2970
2234
  this._postDiagnosticEvent(statsEvent);
2971
- }, this._config.diagnosticRecordingInterval * 1000);
2235
+ }, this._config.diagnosticRecordingInterval * 1e3);
2972
2236
  }
2973
- this._logger?.debug('Started EventProcessor.');
2237
+ this._logger?.debug("Started EventProcessor.");
2974
2238
  }
2975
2239
  _postDiagnosticEvent(event) {
2976
2240
  this._eventSender.sendEventData(LDEventType.DiagnosticEvent, event);
@@ -2986,21 +2250,18 @@ class EventProcessor {
2986
2250
  }
2987
2251
  async flush() {
2988
2252
  if (this._shutdown) {
2989
- throw new LDInvalidSDKKeyError('Events cannot be posted because a permanent error has been encountered. ' +
2990
- 'This is most likely an invalid SDK key. The specific error information ' +
2991
- 'is logged independently.');
2253
+ throw new LDInvalidSDKKeyError("Events cannot be posted because a permanent error has been encountered. " + "This is most likely an invalid SDK key. The specific error information " + "is logged independently.");
2992
2254
  }
2993
2255
  const eventsToFlush = this._queue;
2994
2256
  this._queue = [];
2995
2257
  if (isMultiEventSummarizer(this._summarizer)) {
2996
2258
  const summaries = this._summarizer.getSummaries();
2997
- summaries.forEach((summary) => {
2259
+ summaries.forEach(summary => {
2998
2260
  if (Object.keys(summary.features).length) {
2999
2261
  eventsToFlush.push(summary);
3000
2262
  }
3001
2263
  });
3002
- }
3003
- else {
2264
+ } else {
3004
2265
  const summary = this._summarizer.getSummary();
3005
2266
  if (Object.keys(summary.features).length) {
3006
2267
  eventsToFlush.push(summary);
@@ -3010,7 +2271,7 @@ class EventProcessor {
3010
2271
  return;
3011
2272
  }
3012
2273
  this._eventsInLastBatch = eventsToFlush.length;
3013
- this._logger?.debug('Flushing %d events', eventsToFlush.length);
2274
+ this._logger?.debug("Flushing %d events", eventsToFlush.length);
3014
2275
  await this._tryPostingEvents(eventsToFlush);
3015
2276
  }
3016
2277
  sendEvent(inputEvent) {
@@ -3018,15 +2279,10 @@ class EventProcessor {
3018
2279
  return;
3019
2280
  }
3020
2281
  if (isMigration(inputEvent)) {
3021
- // These conditions are not combined, because we always want to stop
3022
- // processing at this point for a migration event. It cannot generate
3023
- // an index event or debug event.
3024
2282
  if (shouldSample(inputEvent.samplingRatio)) {
3025
2283
  const migrationEvent = {
3026
2284
  ...inputEvent,
3027
- context: inputEvent.context
3028
- ? this._contextFilter.filter(inputEvent.context, this._config.redactAnonymousAllEvents ?? false)
3029
- : undefined,
2285
+ context: inputEvent.context ? this._contextFilter.filter(inputEvent.context, this._config.redactAnonymousAllEvents ?? false) : undefined
3030
2286
  };
3031
2287
  if (migrationEvent.samplingRatio === 1) {
3032
2288
  delete migrationEvent.samplingRatio;
@@ -3037,14 +2293,11 @@ class EventProcessor {
3037
2293
  }
3038
2294
  this._summarizer.summarizeEvent(inputEvent);
3039
2295
  const isFeatureEvent = isFeature(inputEvent);
3040
- // An override-affected evaluation appears only in the summary counters. It produces no
3041
- // individual feature event and no debug event, even when the flag requests them.
3042
2296
  const overrideAffected = isFeatureEvent && !!inputEvent.overrideAffected;
3043
- const addFullEvent = (isFeatureEvent && inputEvent.trackEvents && !overrideAffected) || !isFeatureEvent;
2297
+ const addFullEvent = isFeatureEvent && inputEvent.trackEvents && !overrideAffected || !isFeatureEvent;
3044
2298
  const addDebugEvent = !overrideAffected && this._shouldDebugEvent(inputEvent);
3045
2299
  const isIdentifyEvent = isIdentify(inputEvent);
3046
2300
  const shouldNotDeduplicate = this._contextDeduplicator?.processContext(inputEvent.context);
3047
- // If there is no cache, then it will never be in the cache.
3048
2301
  if (!shouldNotDeduplicate) {
3049
2302
  if (!isIdentifyEvent) {
3050
2303
  this._deduplicatedUsers += 1;
@@ -3053,10 +2306,10 @@ class EventProcessor {
3053
2306
  const addIndexEvent = shouldNotDeduplicate && !isIdentifyEvent;
3054
2307
  if (addIndexEvent) {
3055
2308
  this._enqueue(this._makeOutputEvent({
3056
- kind: 'index',
2309
+ kind: "index",
3057
2310
  creationDate: inputEvent.creationDate,
3058
2311
  context: inputEvent.context,
3059
- samplingRatio: 1,
2312
+ samplingRatio: 1
3060
2313
  }, false));
3061
2314
  }
3062
2315
  if (addFullEvent && shouldSample(inputEvent.samplingRatio)) {
@@ -3068,14 +2321,15 @@ class EventProcessor {
3068
2321
  }
3069
2322
  _makeOutputEvent(event, debug) {
3070
2323
  switch (event.kind) {
3071
- case 'feature': {
2324
+ case "feature":
2325
+ {
3072
2326
  const out = {
3073
- kind: debug ? 'debug' : 'feature',
2327
+ kind: debug ? "debug" : "feature",
3074
2328
  creationDate: event.creationDate,
3075
2329
  context: this._contextFilter.filter(event.context, !debug),
3076
2330
  key: event.key,
3077
2331
  value: event.value,
3078
- default: event.default,
2332
+ default: event.default
3079
2333
  };
3080
2334
  if (event.samplingRatio !== 1) {
3081
2335
  out.samplingRatio = event.samplingRatio;
@@ -3094,24 +2348,28 @@ class EventProcessor {
3094
2348
  }
3095
2349
  return out;
3096
2350
  }
3097
- case 'index': // Intentional fallthrough.
3098
- case 'identify': {
2351
+
2352
+ case "index":
2353
+ case "identify":
2354
+ {
3099
2355
  const out = {
3100
2356
  kind: event.kind,
3101
2357
  creationDate: event.creationDate,
3102
- context: this._contextFilter.filter(event.context),
2358
+ context: this._contextFilter.filter(event.context)
3103
2359
  };
3104
2360
  if (event.samplingRatio !== 1) {
3105
2361
  out.samplingRatio = event.samplingRatio;
3106
2362
  }
3107
2363
  return out;
3108
2364
  }
3109
- case 'custom': {
2365
+
2366
+ case "custom":
2367
+ {
3110
2368
  const out = {
3111
- kind: 'custom',
2369
+ kind: "custom",
3112
2370
  creationDate: event.creationDate,
3113
2371
  key: event.key,
3114
- context: this._contextFilter.filter(event.context, this._config.redactAnonymousAllEvents ?? false),
2372
+ context: this._contextFilter.filter(event.context, this._config.redactAnonymousAllEvents ?? false)
3115
2373
  };
3116
2374
  if (event.samplingRatio !== 1) {
3117
2375
  out.samplingRatio = event.samplingRatio;
@@ -3127,50 +2385,50 @@ class EventProcessor {
3127
2385
  }
3128
2386
  return out;
3129
2387
  }
3130
- case 'click': {
2388
+
2389
+ case "click":
2390
+ {
3131
2391
  const out = {
3132
- kind: 'click',
2392
+ kind: "click",
3133
2393
  creationDate: event.creationDate,
3134
2394
  contextKeys: event.context.kindsAndKeys,
3135
2395
  key: event.key,
3136
2396
  url: event.url,
3137
- selector: event.selector,
2397
+ selector: event.selector
3138
2398
  };
3139
2399
  return out;
3140
2400
  }
3141
- case 'pageview': {
2401
+
2402
+ case "pageview":
2403
+ {
3142
2404
  const out = {
3143
- kind: 'pageview',
2405
+ kind: "pageview",
3144
2406
  creationDate: event.creationDate,
3145
2407
  contextKeys: event.context.kindsAndKeys,
3146
2408
  key: event.key,
3147
- url: event.url,
2409
+ url: event.url
3148
2410
  };
3149
2411
  return out;
3150
2412
  }
3151
- default:
3152
- // This would happen during the addition of a new event type to the SDK.
3153
- return event;
2413
+
2414
+ default:
2415
+ return event;
3154
2416
  }
3155
2417
  }
3156
2418
  _enqueue(event) {
3157
2419
  if (this._queue.length < this._capacity) {
3158
2420
  this._queue.push(event);
3159
2421
  this._exceededCapacity = false;
3160
- }
3161
- else {
2422
+ } else {
3162
2423
  if (!this._exceededCapacity) {
3163
2424
  this._exceededCapacity = true;
3164
- this._logger?.warn('Exceeded event queue capacity. Increase capacity to avoid dropping events.');
2425
+ this._logger?.warn("Exceeded event queue capacity. Increase capacity to avoid dropping events.");
3165
2426
  }
3166
2427
  this._droppedEvents += 1;
3167
2428
  }
3168
2429
  }
3169
2430
  _shouldDebugEvent(event) {
3170
- return (isFeature(event) &&
3171
- event.debugEventsUntilDate &&
3172
- event.debugEventsUntilDate > this._lastKnownPastTime &&
3173
- event.debugEventsUntilDate > Date.now());
2431
+ return isFeature(event) && event.debugEventsUntilDate && event.debugEventsUntilDate > this._lastKnownPastTime && event.debugEventsUntilDate > Date.now();
3174
2432
  }
3175
2433
  async _tryPostingEvents(events) {
3176
2434
  const res = await this._eventSender.sendEventData(LDEventType.AnalyticsEvents, events);
@@ -3187,32 +2445,26 @@ class EventProcessor {
3187
2445
  }
3188
2446
 
3189
2447
  class InputCustomEvent {
3190
- constructor(context, key, data, metricValue,
3191
- // Currently custom events are not sampled, but this is here to make the handling
3192
- // code more uniform.
3193
- samplingRatio = 1,
3194
- // Browser SDKs can include a URL for custom events.
3195
- url) {
2448
+ constructor(context, key, data, metricValue, samplingRatio = 1, url) {
3196
2449
  this.context = context;
3197
2450
  this.key = key;
3198
2451
  this.data = data;
3199
2452
  this.metricValue = metricValue;
3200
2453
  this.samplingRatio = samplingRatio;
3201
2454
  this.url = url;
3202
- this.kind = 'custom';
2455
+ this.kind = "custom";
3203
2456
  this.creationDate = Date.now();
3204
2457
  this.context = context;
3205
2458
  }
3206
2459
  }
3207
2460
 
3208
2461
  class InputEvalEvent {
3209
- constructor(withReasons, context, key, value, defValue, // default is a reserved keyword in this context.
3210
- version, variation, trackEvents, prereqOf, reason, debugEventsUntilDate, excludeFromSummaries, samplingRatio = 1, overrideAffected) {
2462
+ constructor(withReasons, context, key, value, defValue, version, variation, trackEvents, prereqOf, reason, debugEventsUntilDate, excludeFromSummaries, samplingRatio = 1, overrideAffected) {
3211
2463
  this.withReasons = withReasons;
3212
2464
  this.context = context;
3213
2465
  this.key = key;
3214
2466
  this.samplingRatio = samplingRatio;
3215
- this.kind = 'feature';
2467
+ this.kind = "feature";
3216
2468
  this.creationDate = Date.now();
3217
2469
  this.value = value;
3218
2470
  this.default = defValue;
@@ -3247,17 +2499,15 @@ class InputIdentifyEvent {
3247
2499
  constructor(context, samplingRatio = 1) {
3248
2500
  this.context = context;
3249
2501
  this.samplingRatio = samplingRatio;
3250
- this.kind = 'identify';
2502
+ this.kind = "identify";
3251
2503
  this.creationDate = Date.now();
3252
2504
  }
3253
2505
  }
3254
2506
 
3255
2507
  class NullEventProcessor {
3256
- close() { }
3257
- async flush() {
3258
- // empty comment to keep ts and eslint happy
3259
- }
3260
- sendEvent() { }
2508
+ close() {}
2509
+ async flush() {}
2510
+ sendEvent() {}
3261
2511
  }
3262
2512
 
3263
2513
  class EventFactoryBase {
@@ -3265,25 +2515,12 @@ class EventFactoryBase {
3265
2515
  this._withReasons = _withReasons;
3266
2516
  }
3267
2517
  evalEvent(e) {
3268
- return new InputEvalEvent(this._withReasons, e.context, e.flagKey, e.value, e.defaultVal, e.version,
3269
- // Exclude null as a possibility.
3270
- e.variation ?? undefined, e.trackEvents || e.addExperimentData, e.prereqOfFlagKey, this._withReasons || e.addExperimentData ? e.reason : undefined, e.debugEventsUntilDate, e.excludeFromSummaries, e.samplingRatio, e.overrideAffected);
2518
+ return new InputEvalEvent(this._withReasons, e.context, e.flagKey, e.value, e.defaultVal, e.version, e.variation ?? undefined, e.trackEvents || e.addExperimentData, e.prereqOfFlagKey, this._withReasons || e.addExperimentData ? e.reason : undefined, e.debugEventsUntilDate, e.excludeFromSummaries, e.samplingRatio, e.overrideAffected);
3271
2519
  }
3272
2520
  unknownFlagEvent(key, defVal, context) {
3273
- return new InputEvalEvent(this._withReasons, context, key, defVal, defVal,
3274
- // This isn't ideal, but the purpose of the factory is to at least
3275
- // handle this situation.
3276
- undefined, // version
3277
- undefined, // variation index
3278
- undefined, // track events
3279
- undefined, // prereqOf
3280
- undefined, // reason
3281
- undefined, // debugEventsUntilDate
3282
- undefined, // exclude from summaries
3283
- undefined);
2521
+ return new InputEvalEvent(this._withReasons, context, key, defVal, defVal, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined);
3284
2522
  }
3285
2523
  identifyEvent(context) {
3286
- // Currently sampling for identify events is always 1.
3287
2524
  return new InputIdentifyEvent(context, 1);
3288
2525
  }
3289
2526
  customEvent(key, context, data, metricValue, samplingRatio = 1) {
@@ -3291,124 +2528,109 @@ class EventFactoryBase {
3291
2528
  }
3292
2529
  }
3293
2530
 
3294
- /**
3295
- * Reads the FDv1 fallback directive from response headers. Returns
3296
- * `{ fdv1Fallback: false }` when `x-ld-fd-fallback` is absent or not `"true"`.
3297
- *
3298
- * @param headers Header accessor. The `get` method must accept header names
3299
- * in any casing; callers normalize to lowercase before calling this
3300
- * function.
3301
- */
3302
2531
  function readFallbackDirective(headers) {
3303
- const fallback = headers.get('x-ld-fd-fallback');
3304
- if (fallback === null || fallback.toLowerCase() !== 'true') {
3305
- return { fdv1Fallback: false };
2532
+ const fallback = headers.get("x-ld-fd-fallback");
2533
+ if (fallback === null || fallback.toLowerCase() !== "true") {
2534
+ return {
2535
+ fdv1Fallback: false
2536
+ };
3306
2537
  }
3307
- const raw = headers.get('x-ld-fd-fallback-ttl');
2538
+ const raw = headers.get("x-ld-fd-fallback-ttl");
3308
2539
  if (raw === null) {
3309
- return { fdv1Fallback: true };
2540
+ return {
2541
+ fdv1Fallback: true
2542
+ };
3310
2543
  }
3311
2544
  const seconds = parseInt(raw, 10);
3312
2545
  if (Number.isNaN(seconds)) {
3313
- return { fdv1Fallback: true };
3314
- }
3315
- // Clamp negative values to 0 (treated as indefinite, same as TTL=0).
3316
- // Prevents a malicious server from sending a large-negative TTL to trigger
3317
- // immediate recovery instead of the intended long wait.
3318
- return { fdv1Fallback: true, fdv1FallbackTtlMs: Math.max(0, seconds) * 1000 };
3319
- }
3320
- /**
3321
- * Reads the FDv1 fallback directive from an FDv2 `goodbye` event's data.
3322
- *
3323
- * SDKs that cannot read streaming response headers (e.g. browsers using the
3324
- * native `EventSource` API) receive the fallback directive in-band via the
3325
- * goodbye message's `protocolFallbackTTL` field.
3326
- * Presence of a finite numeric `protocolFallbackTTL` signals FDv1 fallback;
3327
- * the value carries the same semantics as the `x-ld-fd-fallback-ttl` header
3328
- * (`0` indicates indefinite fallback). A missing, non-numeric, or non-finite
3329
- * value is not a fallback signal and yields `{ fdv1Fallback: false }`.
3330
- *
3331
- * @param data The raw, parsed goodbye event data (typed `unknown` because the
3332
- * caller has not narrowed it).
3333
- */
2546
+ return {
2547
+ fdv1Fallback: true
2548
+ };
2549
+ }
2550
+ return {
2551
+ fdv1Fallback: true,
2552
+ fdv1FallbackTtlMs: Math.max(0, seconds) * 1e3
2553
+ };
2554
+ }
2555
+
3334
2556
  function readGoodbyeFallbackDirective(data) {
3335
- const rawTtl = data
3336
- ?.protocolFallbackTTL;
3337
- if (typeof rawTtl !== 'number' || !Number.isFinite(rawTtl)) {
3338
- return { fdv1Fallback: false };
2557
+ const rawTtl = data?.protocolFallbackTTL;
2558
+ if (typeof rawTtl !== "number" || !Number.isFinite(rawTtl)) {
2559
+ return {
2560
+ fdv1Fallback: false
2561
+ };
3339
2562
  }
3340
- return { fdv1Fallback: true, fdv1FallbackTtlMs: Math.max(0, rawTtl) * 1000 };
2563
+ return {
2564
+ fdv1Fallback: true,
2565
+ fdv1FallbackTtlMs: Math.max(0, rawTtl) * 1e3
2566
+ };
3341
2567
  }
3342
2568
 
3343
- const PAYLOAD_ID = 'FDv1Fallback';
2569
+ const PAYLOAD_ID = "FDv1Fallback";
2570
+
3344
2571
  function fdv1PayloadAdaptor(processor) {
3345
2572
  return {
3346
2573
  _processor: processor,
3347
- _selector: '',
2574
+ _selector: "",
3348
2575
  useSelector(selector) {
3349
2576
  this._selector = selector;
3350
2577
  return this;
3351
2578
  },
3352
2579
  processFullTransfer(data) {
3353
- const events = [
3354
- {
3355
- event: 'server-intent',
3356
- data: {
3357
- payloads: [
3358
- {
3359
- id: PAYLOAD_ID,
3360
- target: 1,
3361
- intentCode: 'xfer-full',
3362
- reason: 'payload-missing',
3363
- },
3364
- ],
3365
- },
3366
- },
3367
- ];
2580
+ const events = [ {
2581
+ event: "server-intent",
2582
+ data: {
2583
+ payloads: [ {
2584
+ id: PAYLOAD_ID,
2585
+ target: 1,
2586
+ intentCode: "xfer-full",
2587
+ reason: "payload-missing"
2588
+ } ]
2589
+ }
2590
+ } ];
3368
2591
  Object.entries(data?.flags || []).forEach(([key, flag]) => {
3369
2592
  events.push({
3370
- event: 'put-object',
2593
+ event: "put-object",
3371
2594
  data: {
3372
- kind: 'flag',
3373
- key,
2595
+ kind: "flag",
2596
+ key: key,
3374
2597
  version: flag.version || 1,
3375
- object: flag,
3376
- },
2598
+ object: flag
2599
+ }
3377
2600
  });
3378
2601
  });
3379
2602
  Object.entries(data?.segments || []).forEach(([key, segment]) => {
3380
2603
  events.push({
3381
- event: 'put-object',
2604
+ event: "put-object",
3382
2605
  data: {
3383
- kind: 'segment',
3384
- key,
2606
+ kind: "segment",
2607
+ key: key,
3385
2608
  version: segment.version || 1,
3386
- object: segment,
3387
- },
2609
+ object: segment
2610
+ }
3388
2611
  });
3389
2612
  });
3390
2613
  events.push({
3391
- event: 'payload-transferred',
2614
+ event: "payload-transferred",
3392
2615
  data: {
3393
- // IMPORTANT: the selector MUST be empty or "live" data synchronizers
3394
- // will not work as it would try to resume from a bogus state.
3395
2616
  state: this._selector,
3396
2617
  version: 1,
3397
- id: PAYLOAD_ID,
3398
- },
2618
+ id: PAYLOAD_ID
2619
+ }
3399
2620
  });
3400
2621
  this._processor.processEvents(events);
3401
- },
2622
+ }
3402
2623
  };
3403
2624
  }
3404
2625
 
3405
- const ACTION_NONE = { type: 'none' };
2626
+ const ACTION_NONE = {
2627
+ type: "none"
2628
+ };
2629
+
3406
2630
  function createProtocolHandler(objProcessors, logger) {
3407
- let protocolState = 'inactive';
3408
- let tempType = 'partial';
2631
+ let protocolState = "inactive";
2632
+ let tempType = "partial";
3409
2633
  let tempUpdates = [];
3410
- // Only kinds with a registered processor are supported. An own-property check keeps
3411
- // kinds such as 'constructor' from resolving to inherited members.
3412
2634
  function isSupportedKind(kind) {
3413
2635
  return Object.prototype.hasOwnProperty.call(objProcessors, kind);
3414
2636
  }
@@ -3416,13 +2638,13 @@ function createProtocolHandler(objProcessors, logger) {
3416
2638
  return objProcessors[kind]?.(jsonObj);
3417
2639
  }
3418
2640
  function resetAll() {
3419
- protocolState = 'inactive';
3420
- tempType = 'partial';
2641
+ protocolState = "inactive";
2642
+ tempType = "partial";
3421
2643
  tempUpdates = [];
3422
2644
  }
3423
2645
  function resetAfterEmission() {
3424
- protocolState = 'changes';
3425
- tempType = 'partial';
2646
+ protocolState = "changes";
2647
+ tempType = "partial";
3426
2648
  tempUpdates = [];
3427
2649
  }
3428
2650
  function resetAfterError() {
@@ -3434,56 +2656,56 @@ function createProtocolHandler(objProcessors, logger) {
3434
2656
  return ACTION_NONE;
3435
2657
  }
3436
2658
  return {
3437
- type: 'payload',
2659
+ type: "payload",
3438
2660
  payload: {
3439
2661
  version: intent.target,
3440
- type: 'none',
3441
- updates: [],
3442
- },
2662
+ type: "none",
2663
+ updates: []
2664
+ }
3443
2665
  };
3444
2666
  }
3445
2667
  function processServerIntent(data) {
3446
2668
  if (!data.payloads?.length) {
3447
2669
  return {
3448
- type: 'error',
3449
- kind: 'MISSING_PAYLOAD',
3450
- message: 'No payload present in server-intent',
2670
+ type: "error",
2671
+ kind: "MISSING_PAYLOAD",
2672
+ message: "No payload present in server-intent"
3451
2673
  };
3452
2674
  }
3453
- // Per spec 3.4.2: SDK uses only the first payload.
3454
2675
  const payload = data.payloads[0];
3455
2676
  switch (payload?.intentCode) {
3456
- case 'xfer-full':
3457
- protocolState = 'full';
3458
- tempUpdates = [];
3459
- tempType = 'full';
3460
- return ACTION_NONE;
3461
- case 'xfer-changes':
3462
- protocolState = 'changes';
3463
- tempUpdates = [];
3464
- tempType = 'partial';
3465
- return ACTION_NONE;
3466
- case 'none':
3467
- protocolState = 'changes';
3468
- tempUpdates = [];
3469
- tempType = 'partial';
3470
- return processIntentNone(payload);
3471
- default:
3472
- logger?.warn(`Unable to process intent code '${payload?.intentCode}'.`);
3473
- return ACTION_NONE;
2677
+ case "xfer-full":
2678
+ protocolState = "full";
2679
+ tempUpdates = [];
2680
+ tempType = "full";
2681
+ return ACTION_NONE;
2682
+
2683
+ case "xfer-changes":
2684
+ protocolState = "changes";
2685
+ tempUpdates = [];
2686
+ tempType = "partial";
2687
+ return ACTION_NONE;
2688
+
2689
+ case "none":
2690
+ protocolState = "changes";
2691
+ tempUpdates = [];
2692
+ tempType = "partial";
2693
+ return processIntentNone(payload);
2694
+
2695
+ default:
2696
+ logger?.warn(`Unable to process intent code '${payload?.intentCode}'.`);
2697
+ return ACTION_NONE;
3474
2698
  }
3475
2699
  }
3476
2700
  function processPutObject(data) {
3477
- if (protocolState === 'inactive') {
3478
- logger?.warn('Received put-object before server-intent was established. Ignoring.');
2701
+ if (protocolState === "inactive") {
2702
+ logger?.warn("Received put-object before server-intent was established. Ignoring.");
3479
2703
  return ACTION_NONE;
3480
2704
  }
3481
2705
  if (!data.kind || !data.key || isNullish(data.version) || !data.object) {
3482
2706
  logger?.warn(`Ignoring put-object with missing fields: kind=${data.kind}, key=${data.key}, version=${data.version}`);
3483
2707
  return ACTION_NONE;
3484
2708
  }
3485
- // Objects of unsupported kinds are dropped silently so the protocol can add new kinds
3486
- // without disrupting older SDKs.
3487
2709
  if (!isSupportedKind(data.kind)) {
3488
2710
  logger?.debug(`Ignoring put-object with unsupported kind: '${data.kind}'`);
3489
2711
  return ACTION_NONE;
@@ -3497,13 +2719,13 @@ function createProtocolHandler(objProcessors, logger) {
3497
2719
  kind: data.kind,
3498
2720
  key: data.key,
3499
2721
  version: data.version,
3500
- object: obj,
2722
+ object: obj
3501
2723
  });
3502
2724
  return ACTION_NONE;
3503
2725
  }
3504
2726
  function processDeleteObject(data) {
3505
- if (protocolState === 'inactive') {
3506
- logger?.warn('Received delete-object before server-intent was established. Ignoring.');
2727
+ if (protocolState === "inactive") {
2728
+ logger?.warn("Received delete-object before server-intent was established. Ignoring.");
3507
2729
  return ACTION_NONE;
3508
2730
  }
3509
2731
  if (!data.kind || !data.key || isNullish(data.version)) {
@@ -3518,16 +2740,16 @@ function createProtocolHandler(objProcessors, logger) {
3518
2740
  kind: data.kind,
3519
2741
  key: data.key,
3520
2742
  version: data.version,
3521
- deleted: true,
2743
+ deleted: true
3522
2744
  });
3523
2745
  return ACTION_NONE;
3524
2746
  }
3525
2747
  function processPayloadTransferred(data) {
3526
- if (protocolState === 'inactive') {
2748
+ if (protocolState === "inactive") {
3527
2749
  return {
3528
- type: 'error',
3529
- kind: 'PROTOCOL_ERROR',
3530
- message: 'A payload transferred has been received without an intent having been established.',
2750
+ type: "error",
2751
+ kind: "PROTOCOL_ERROR",
2752
+ message: "A payload transferred has been received without an intent having been established."
3531
2753
  };
3532
2754
  }
3533
2755
  if (isNullish(data.state) || isNullish(data.version)) {
@@ -3536,13 +2758,13 @@ function createProtocolHandler(objProcessors, logger) {
3536
2758
  return ACTION_NONE;
3537
2759
  }
3538
2760
  const result = {
3539
- type: 'payload',
2761
+ type: "payload",
3540
2762
  payload: {
3541
2763
  version: data.version,
3542
2764
  state: data.state,
3543
2765
  type: tempType,
3544
- updates: tempUpdates,
3545
- },
2766
+ updates: tempUpdates
2767
+ }
3546
2768
  };
3547
2769
  resetAfterEmission();
3548
2770
  return result;
@@ -3550,12 +2772,19 @@ function createProtocolHandler(objProcessors, logger) {
3550
2772
  function processGoodbye(data) {
3551
2773
  logger?.info(`Goodbye was received from the LaunchDarkly connection with reason: ${data.reason}.`);
3552
2774
  resetAll();
3553
- return { type: 'goodbye', reason: data.reason };
2775
+ return {
2776
+ type: "goodbye",
2777
+ reason: data.reason
2778
+ };
3554
2779
  }
3555
2780
  function processError(data) {
3556
2781
  logger?.info(`An issue was encountered receiving updates with reason: ${data.reason}.`);
3557
2782
  resetAfterError();
3558
- return { type: 'serverError', id: data.payload_id, reason: data.reason };
2783
+ return {
2784
+ type: "serverError",
2785
+ id: data.payload_id,
2786
+ reason: data.reason
2787
+ };
3559
2788
  }
3560
2789
  return {
3561
2790
  get state() {
@@ -3563,48 +2792,45 @@ function createProtocolHandler(objProcessors, logger) {
3563
2792
  },
3564
2793
  processEvent(event) {
3565
2794
  switch (event.event) {
3566
- case 'server-intent':
3567
- return processServerIntent(event.data);
3568
- case 'put-object':
3569
- return processPutObject(event.data);
3570
- case 'delete-object':
3571
- return processDeleteObject(event.data);
3572
- case 'payload-transferred':
3573
- return processPayloadTransferred(event.data);
3574
- case 'goodbye':
3575
- return processGoodbye(event.data);
3576
- case 'error':
3577
- return processError(event.data);
3578
- case 'heart-beat':
3579
- return ACTION_NONE;
3580
- default:
3581
- return {
3582
- type: 'error',
3583
- kind: 'UNKNOWN_EVENT',
3584
- message: `Received an unknown event of type '${event.event}'`,
3585
- };
2795
+ case "server-intent":
2796
+ return processServerIntent(event.data);
2797
+
2798
+ case "put-object":
2799
+ return processPutObject(event.data);
2800
+
2801
+ case "delete-object":
2802
+ return processDeleteObject(event.data);
2803
+
2804
+ case "payload-transferred":
2805
+ return processPayloadTransferred(event.data);
2806
+
2807
+ case "goodbye":
2808
+ return processGoodbye(event.data);
2809
+
2810
+ case "error":
2811
+ return processError(event.data);
2812
+
2813
+ case "heart-beat":
2814
+ return ACTION_NONE;
2815
+
2816
+ default:
2817
+ return {
2818
+ type: "error",
2819
+ kind: "UNKNOWN_EVENT",
2820
+ message: `Received an unknown event of type '${event.event}'`
2821
+ };
3586
2822
  }
3587
2823
  },
3588
2824
  reset() {
3589
2825
  resetAll();
3590
- },
2826
+ }
3591
2827
  };
3592
2828
  }
3593
2829
 
3594
- /**
3595
- * Errors that indicate a problem with the data or protocol flow and should
3596
- * be reported to the error handler. Informational errors like UNKNOWN_EVENT
3597
- * are intentionally excluded to preserve forward compatibility — older SDKs
3598
- * should silently ignore new event types added to the protocol.
3599
- */
3600
2830
  function isActionableError(kind) {
3601
- return kind === 'MISSING_PAYLOAD' || kind === 'PROTOCOL_ERROR';
2831
+ return kind === "MISSING_PAYLOAD" || kind === "PROTOCOL_ERROR";
3602
2832
  }
3603
- /**
3604
- * Parses payloads from a stream of FDv2 events by delegating to a protocol handler.
3605
- * Sends completed payloads to registered listeners.
3606
- * Invalid event sequences may be dropped silently, but the processor will continue to operate.
3607
- */
2833
+
3608
2834
  class PayloadProcessor {
3609
2835
  constructor(objProcessors, _errorHandler, _logger) {
3610
2836
  this._errorHandler = _errorHandler;
@@ -3622,47 +2848,35 @@ class PayloadProcessor {
3622
2848
  }
3623
2849
  }
3624
2850
  processEvents(events) {
3625
- events.forEach((event) => {
2851
+ events.forEach(event => {
3626
2852
  const action = this._handler.processEvent(event);
3627
2853
  switch (action.type) {
3628
- case 'payload':
3629
- this._listeners.forEach((it) => it(action.payload));
3630
- break;
3631
- case 'error':
3632
- if (isActionableError(action.kind)) {
3633
- this._errorHandler?.(DataSourceErrorKind.InvalidData, action.message);
3634
- }
3635
- else {
3636
- this._logger?.warn(action.message);
3637
- }
3638
- break;
2854
+ case "payload":
2855
+ this._listeners.forEach(it => it(action.payload));
2856
+ break;
2857
+
2858
+ case "error":
2859
+ if (isActionableError(action.kind)) {
2860
+ this._errorHandler?.(DataSourceErrorKind.InvalidData, action.message);
2861
+ } else {
2862
+ this._logger?.warn(action.message);
2863
+ }
2864
+ break;
3639
2865
  }
3640
2866
  });
3641
2867
  }
3642
2868
  }
3643
2869
 
3644
- /**
3645
- * A FDv2 PayloadStreamReader can be used to parse payloads from a stream of FDv2 events. See {@link PayloadProcessor}
3646
- * for more details.
3647
- */
3648
2870
  class PayloadStreamReader {
3649
- /**
3650
- * Creates a PayloadStreamReader
3651
- *
3652
- * @param eventStream event stream of FDv2 events
3653
- * @param _objProcessors defines object processors for each object kind.
3654
- * @param _errorHandler that will be called with parsing errors as they are encountered
3655
- * @param _logger for logging
3656
- */
3657
2871
  constructor(eventStream, _objProcessors, _errorHandler, _logger) {
3658
2872
  this._errorHandler = _errorHandler;
3659
2873
  this._logger = _logger;
3660
- this._attachHandler(eventStream, 'server-intent');
3661
- this._attachHandler(eventStream, 'put-object');
3662
- this._attachHandler(eventStream, 'delete-object');
3663
- this._attachHandler(eventStream, 'payload-transferred');
3664
- this._attachHandler(eventStream, 'goodbye');
3665
- this._attachHandler(eventStream, 'error');
2874
+ this._attachHandler(eventStream, "server-intent");
2875
+ this._attachHandler(eventStream, "put-object");
2876
+ this._attachHandler(eventStream, "delete-object");
2877
+ this._attachHandler(eventStream, "payload-transferred");
2878
+ this._attachHandler(eventStream, "goodbye");
2879
+ this._attachHandler(eventStream, "error");
3666
2880
  this._payloadProcessor = new PayloadProcessor(_objProcessors, _errorHandler, _logger);
3667
2881
  }
3668
2882
  addPayloadListener(listener) {
@@ -3672,72 +2886,45 @@ class PayloadStreamReader {
3672
2886
  this._payloadProcessor.removePayloadListener(listener);
3673
2887
  }
3674
2888
  _attachHandler(stream, eventName) {
3675
- stream.addEventListener(eventName, async (event) => {
2889
+ stream.addEventListener(eventName, async event => {
3676
2890
  if (event?.data) {
3677
2891
  this._logger?.debug(`Received ${eventName} event. Data is ${event.data}`);
3678
2892
  try {
3679
- this._payloadProcessor.processEvents([
3680
- { event: eventName, data: JSON.parse(event.data) },
3681
- ]);
3682
- }
3683
- catch {
2893
+ this._payloadProcessor.processEvents([ {
2894
+ event: eventName,
2895
+ data: JSON.parse(event.data)
2896
+ } ]);
2897
+ } catch {
3684
2898
  this._logger?.error(`Stream received data that was unable to be processed in "${eventName}" message`);
3685
2899
  this._logger?.debug(`Data follows: ${event.data}`);
3686
- this._errorHandler?.(DataSourceErrorKind.InvalidData, 'Malformed data in EventStream.');
2900
+ this._errorHandler?.(DataSourceErrorKind.InvalidData, "Malformed data in EventStream.");
3687
2901
  }
3688
- }
3689
- else if (eventName !== 'error') {
3690
- // Missing data is a protocol violation for every type except 'error': a connection
3691
- // failure also dispatches under 'error', without data, and the transport owner handles
3692
- // it. Only a server-sent error frame carries data.
3693
- this._errorHandler?.(DataSourceErrorKind.Unknown, 'Event from EventStream missing data.');
2902
+ } else if (eventName !== "error") {
2903
+ this._errorHandler?.(DataSourceErrorKind.Unknown, "Event from EventStream missing data.");
3694
2904
  }
3695
2905
  });
3696
2906
  }
3697
2907
  }
3698
2908
 
3699
- /**
3700
- * The most redirect hops one streaming request follows. When a chain exceeds the cap, the last
3701
- * redirect response goes to the caller as an ordinary non-200 response. The caller's error
3702
- * handling decides whether to retry.
3703
- */
3704
2909
  const MAX_STREAMING_REDIRECT_HOPS = 5;
3705
- /**
3706
- * Resolves the target of a redirect response. The target can be relative, and it resolves
3707
- * against the URL of the redirected request. Only an `http:` or `https:` target can carry
3708
- * the stream; any other scheme, a missing or empty `Location`, and an unparsable value all
3709
- * resolve to `undefined`, and the redirect response then goes to the caller unfollowed.
3710
- */
2910
+
3711
2911
  function redirectTarget(headers, baseUrl) {
3712
2912
  const raw = headers.location;
3713
2913
  const value = Array.isArray(raw) ? raw[0] : raw;
3714
- if (typeof value !== 'string' || value === '') {
2914
+ if (typeof value !== "string" || value === "") {
3715
2915
  return undefined;
3716
2916
  }
3717
2917
  try {
3718
2918
  const resolved = new URL(value, baseUrl);
3719
- if (resolved.protocol !== 'http:' && resolved.protocol !== 'https:') {
2919
+ if (resolved.protocol !== "http:" && resolved.protocol !== "https:") {
3720
2920
  return undefined;
3721
2921
  }
3722
2922
  return resolved.href;
3723
- }
3724
- catch {
2923
+ } catch {
3725
2924
  return undefined;
3726
2925
  }
3727
2926
  }
3728
- /**
3729
- * Issues a streaming request and follows up to {@link MAX_STREAMING_REDIRECT_HOPS} hops of
3730
- * `301` and `307` redirects. Each hop calls `doRequest` again with the target URL, so the
3731
- * request carries the same method, body, and headers to each target, the `Authorization`
3732
- * header included. A `302` and every other status return to the caller unfollowed.
3733
- *
3734
- * The loop holds no state across calls. A reconnect starts from the original URL again and
3735
- * re-follows the chain.
3736
- *
3737
- * @param url The URL of the initial request.
3738
- * @param doRequest Issues one request and resolves with its response. The caller builds the
3739
- * options inside it from the given URL, so each hop gets options for its own target.
3740
- */
2927
+
3741
2928
  async function followStreamingRedirects(url, doRequest) {
3742
2929
  let currentUrl = url;
3743
2930
  let res = await doRequest(currentUrl);
@@ -3748,176 +2935,123 @@ async function followStreamingRedirects(url, doRequest) {
3748
2935
  return res;
3749
2936
  }
3750
2937
  hops += 1;
3751
- // The destroy releases the skipped redirect response and its connection at once, so a
3752
- // redirect body that never ends cannot hold a socket for the life of the attempt.
3753
2938
  try {
3754
2939
  res.destroy?.();
3755
- }
3756
- catch {
3757
- // A throwing destroy has nothing left to release.
3758
- }
2940
+ } catch {}
3759
2941
  currentUrl = target;
3760
- // The hops are sequential. The next request cannot start until this response arrives.
3761
- // eslint-disable-next-line no-await-in-loop
3762
2942
  res = await doRequest(currentUrl);
3763
2943
  }
3764
2944
  return res;
3765
2945
  }
3766
2946
 
3767
- /**
3768
- * Wraps the raw headers in the fetch `Headers` shape. Lookups are case-insensitive.
3769
- * Multi-value headers are joined with ", ", names that differ only by case merge into one
3770
- * joined value, and names without a value are skipped.
3771
- */
3772
2947
  function wrapRawHeaders(headers) {
3773
- const normalized = new Map();
3774
- Object.keys(headers).forEach((key) => {
2948
+ const normalized = new Map;
2949
+ Object.keys(headers).forEach(key => {
3775
2950
  const val = headers[key];
3776
2951
  if (val !== undefined && val !== null) {
3777
2952
  const name = key.toLowerCase();
3778
- const joined = Array.isArray(val) ? val.join(', ') : val;
2953
+ const joined = Array.isArray(val) ? val.join(", ") : val;
3779
2954
  const existing = normalized.get(name);
3780
2955
  normalized.set(name, existing === undefined ? joined : `${existing}, ${joined}`);
3781
2956
  }
3782
2957
  });
3783
2958
  return {
3784
- get: (name) => normalized.get(name.toLowerCase()) ?? null,
2959
+ get: name => normalized.get(name.toLowerCase()) ?? null,
3785
2960
  keys: () => normalized.keys(),
3786
2961
  values: () => normalized.values(),
3787
2962
  entries: () => normalized.entries(),
3788
- forEach: (callback) => {
2963
+ forEach: callback => {
3789
2964
  normalized.forEach((value, key) => callback(value, key));
3790
2965
  },
3791
- has: (name) => normalized.has(name.toLowerCase()),
2966
+ has: name => normalized.has(name.toLowerCase())
3792
2967
  };
3793
2968
  }
3794
- /**
3795
- * Creates a response for a streaming request. The response does not buffer the body. Each
3796
- * read hands out the next chunk from the source iterator. The body does not enforce a
3797
- * consumer lock: every `getReader`, `text`, and `json` call reads from the same iterator,
3798
- * so the caller uses one consumer per response. The `cancel` methods on the body and the
3799
- * reader call every release function the source provides: they destroy the source when it
3800
- * has a `destroy` method, and they also call the iterator's `return` method when one
3801
- * exists. The body passes through as-is, so the caller decodes any content encoding first.
3802
- *
3803
- * @param source The raw platform response, for example a Node `IncomingMessage`. A missing
3804
- * status code maps to 0, and a missing status message maps to an empty string.
3805
- */
2969
+
3806
2970
  function createStreamingResponse(source) {
3807
- // A consumer compiled without `Symbol.asyncIterator` in its lib can pass a source that
3808
- // lacks the iterator without a compile error. The check turns that mistake into a named
3809
- // failure instead of a bare member-access TypeError.
3810
- if (typeof source[Symbol.asyncIterator] !== 'function') {
3811
- throw new TypeError('the streaming response source does not provide an async iterator');
2971
+ if (typeof source[Symbol.asyncIterator] !== "function") {
2972
+ throw new TypeError("the streaming response source does not provide an async iterator");
3812
2973
  }
3813
2974
  const iterator = source[Symbol.asyncIterator]();
3814
2975
  const cancel = async () => {
3815
- // Destroy the stream first. That rejects a pending read and unblocks a queued return
3816
- // call. A Node readable iterator queues the return call behind a pending read, and on
3817
- // a stream that was never read it completes without a destroy, so the return call
3818
- // alone cannot release the connection. Do not await it for the same reason. Each
3819
- // release call is guarded on its own, so a release function that throws, or a return
3820
- // that resolves synchronously, does not skip the other release path or reject cancel.
3821
2976
  try {
3822
2977
  source.destroy?.();
3823
- }
3824
- catch {
3825
- // A throwing destroy has nothing left to release.
3826
- }
2978
+ } catch {}
3827
2979
  try {
3828
- Promise.resolve(iterator.return?.()).catch(() => { });
3829
- }
3830
- catch {
3831
- // A throwing return has nothing left to release.
3832
- }
2980
+ Promise.resolve(iterator.return?.()).catch(() => {});
2981
+ } catch {}
3833
2982
  };
3834
2983
  async function text() {
3835
- const decoder = new TextDecoder();
3836
- let result = '';
2984
+ const decoder = new TextDecoder;
2985
+ let result = "";
3837
2986
  try {
3838
2987
  let next = await iterator.next();
3839
2988
  while (!next.done) {
3840
2989
  if (next.value !== undefined) {
3841
2990
  try {
3842
- result += decoder.decode(next.value, { stream: true });
3843
- }
3844
- catch {
3845
- // decode() rejects a chunk that is not a BufferSource. The fixed message keeps
3846
- // chunk contents out of error messages.
3847
- throw new TypeError('the source supplied a chunk that is not a BufferSource');
2991
+ result += decoder.decode(next.value, {
2992
+ stream: true
2993
+ });
2994
+ } catch {
2995
+ throw new TypeError("the source supplied a chunk that is not a BufferSource");
3848
2996
  }
3849
2997
  }
3850
- // The stream provides the chunks in sequence, so the reads cannot run in parallel.
3851
- // oxlint-disable-next-line no-await-in-loop
3852
2998
  next = await iterator.next();
3853
2999
  }
3854
- }
3855
- catch (err) {
3856
- // text() owns the body, so any failed read must release the source itself. This
3857
- // covers a rejecting next() as well as a bad chunk.
3000
+ } catch (err) {
3858
3001
  cancel();
3859
3002
  throw err;
3860
3003
  }
3861
- // The final decode flushes a trailing partial multi-byte sequence.
3862
3004
  return result + decoder.decode();
3863
3005
  }
3864
3006
  return {
3865
3007
  headers: wrapRawHeaders(source.headers),
3866
3008
  status: source.statusCode ?? 0,
3867
- statusText: source.statusMessage ?? '',
3009
+ statusText: source.statusMessage ?? "",
3868
3010
  body: {
3869
3011
  getReader: () => ({
3870
3012
  read: async () => {
3871
3013
  const next = await iterator.next();
3872
3014
  if (next.done) {
3873
- return { done: true };
3015
+ return {
3016
+ done: true
3017
+ };
3874
3018
  }
3875
- return { done: false, value: next.value };
3019
+ return {
3020
+ done: false,
3021
+ value: next.value
3022
+ };
3876
3023
  },
3877
- cancel,
3024
+ cancel: cancel
3878
3025
  }),
3879
- cancel,
3026
+ cancel: cancel
3880
3027
  },
3881
- text,
3882
- json: async () => JSON.parse(await text()),
3028
+ text: text,
3029
+ json: async () => JSON.parse(await text())
3883
3030
  };
3884
3031
  }
3885
3032
 
3886
- /**
3887
- * Converts the request options into the init shape a platform's native `fetch` accepts. A
3888
- * platform can declare its `AbortSignal` as a lexical class, which `AbortSignalLike`
3889
- * cannot resolve to, so the `signal` member widens here. The caller must pass a signal
3890
- * created by the running platform. The widening then only restores the type the runtime
3891
- * already has.
3892
- */
3893
3033
  function toRequestInit(options) {
3894
3034
  return options;
3895
3035
  }
3896
3036
 
3897
- /**
3898
- * Creates an InitMetadata object from initialization headers.
3899
- *
3900
- * @param initHeaders Initialization headers received when establishing
3901
- * a streaming or polling connection to LD.
3902
- * @returns InitMetadata object, or undefined if initHeaders is undefined
3903
- * or missing the required header values.
3904
- */
3905
3037
  function initMetadataFromHeaders(initHeaders) {
3906
3038
  if (initHeaders) {
3907
- const envIdKey = Object.keys(initHeaders).find((key) => key.toLowerCase() === 'x-ld-envid');
3039
+ const envIdKey = Object.keys(initHeaders).find(key => key.toLowerCase() === "x-ld-envid");
3908
3040
  if (envIdKey) {
3909
- return { environmentId: initHeaders[envIdKey] };
3041
+ return {
3042
+ environmentId: initHeaders[envIdKey]
3043
+ };
3910
3044
  }
3911
3045
  }
3912
3046
  return undefined;
3913
3047
  }
3914
3048
 
3915
- const UNKNOWN_PLUGIN_NAME = 'unknown plugin';
3049
+ const UNKNOWN_PLUGIN_NAME = "unknown plugin";
3050
+
3916
3051
  function safeGetName(logger, plugin) {
3917
3052
  try {
3918
3053
  return plugin.getMetadata().name || UNKNOWN_PLUGIN_NAME;
3919
- }
3920
- catch {
3054
+ } catch {
3921
3055
  logger.error(`Exception thrown getting metadata for plugin. Unable to get plugin name.`);
3922
3056
  return UNKNOWN_PLUGIN_NAME;
3923
3057
  }
@@ -3925,17 +3059,15 @@ function safeGetName(logger, plugin) {
3925
3059
 
3926
3060
  function safeGetHooks(logger, environmentMetadata, plugins) {
3927
3061
  const hooks = [];
3928
- plugins.forEach((plugin) => {
3062
+ plugins.forEach(plugin => {
3929
3063
  try {
3930
3064
  const pluginHooks = plugin.getHooks?.(environmentMetadata);
3931
3065
  if (pluginHooks === undefined) {
3932
3066
  logger.error(`Plugin ${safeGetName(logger, plugin)} returned undefined from getHooks.`);
3933
- }
3934
- else if (pluginHooks && pluginHooks.length > 0) {
3067
+ } else if (pluginHooks && pluginHooks.length > 0) {
3935
3068
  hooks.push(...pluginHooks);
3936
3069
  }
3937
- }
3938
- catch (error) {
3070
+ } catch (error) {
3939
3071
  logger.error(`Exception thrown getting hooks for plugin ${safeGetName(logger, plugin)}. Unable to get hooks.`);
3940
3072
  }
3941
3073
  });
@@ -3943,17 +3075,16 @@ function safeGetHooks(logger, environmentMetadata, plugins) {
3943
3075
  }
3944
3076
 
3945
3077
  function safeRegisterPlugins(logger, environmentMetadata, client, plugins) {
3946
- plugins.forEach((plugin) => {
3078
+ plugins.forEach(plugin => {
3947
3079
  try {
3948
3080
  plugin.register(client, environmentMetadata);
3949
- }
3950
- catch (error) {
3081
+ } catch (error) {
3951
3082
  logger.error(`Exception thrown registering plugin ${safeGetName(logger, plugin)}.`);
3952
3083
  }
3953
3084
  });
3954
3085
  }
3955
3086
 
3956
- var index = /*#__PURE__*/Object.freeze({
3087
+ var index = Object.freeze({
3957
3088
  __proto__: null,
3958
3089
  ClientMessages: ClientMessages,
3959
3090
  DiagnosticsManager: DiagnosticsManager,