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