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