-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathtranslate-context.ts
155 lines (143 loc) · 5.8 KB
/
translate-context.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
/* eslint-disable @typescript-eslint/no-explicit-any */
//Copyright 2022 Catamorphic, Co.
//
// Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
//limitations under the License.
//Code taken from https://github.com/launchdarkly/openfeature-node-server/blob/main/src/translateContext.ts
import { EvaluationContext, EvaluationContextValue } from '@openfeature/web-sdk';
import { LDContext, LDContextCommon, LDLogger, LDSingleKindContext } from 'launchdarkly-js-client-sdk';
const LDContextBuiltIns = {
name: 'string',
anonymous: 'boolean',
};
/**
* Convert attributes, potentially recursively, into appropriate types.
* @param logger Logger to use if issues are encountered.
* @param key The key for the attribute.
* @param value The value of the attribute.
* @param object Object to place the value in.
* @param visited Carry visited keys of the object
*/
function convertAttributes(logger: LDLogger, key: string, value: any, object: any, visited: any[]): any {
if (visited.includes(value)) {
// Prevent cycles by not visiting the same object
// with in the same branch. Different branches
// may contain the same object.
logger.error(
'Detected a cycle within the evaluation context. The ' +
'affected part of the context will not be included in evaluation.',
);
return;
}
// This method is recursively populating objects, so we are intentionally
// re-assigning to a parameter to prevent generating many intermediate objects.
if (value instanceof Date) {
// eslint-disable-next-line no-param-reassign
object[key] = value.toISOString();
} else if (typeof value === 'object' && !Array.isArray(value)) {
// eslint-disable-next-line no-param-reassign
object[key] = {};
Object.entries(value).forEach(([objectKey, objectValue]) => {
convertAttributes(logger, objectKey, objectValue, object[key], [...visited, value]);
});
} else {
// eslint-disable-next-line no-param-reassign
object[key] = value;
}
}
/**
* Translate the common part of a context. This could either be the attributes
* of a single context, or it could be the attributes of a nested context
* in a multi-context.
* @param logger Logger to use if issues are encountered.
* @param inCommon The source context information. Could be an EvaluationContext, or a value
* within an Evaluation context.
* @param inTargetingKey The targetingKey, either it or the key may be used.
* @returns A populated common context.
*/
function translateContextCommon(
logger: LDLogger,
inCommon: Record<string, EvaluationContextValue>,
inTargetingKey: string | undefined,
): LDContextCommon {
const keyAttr = inCommon['key'] as string;
const finalKey = inTargetingKey ?? keyAttr;
if (keyAttr != null && inTargetingKey != null) {
logger.warn(
"The EvaluationContext contained both a 'targetingKey' and a 'key' attribute. The" +
" 'key' attribute will be discarded.",
);
}
if (finalKey == null) {
logger.error(
"The EvaluationContext must contain either a 'targetingKey' or a 'key' and the " + 'type must be a string.',
);
}
const convertedContext: LDContextCommon = { key: finalKey };
Object.entries(inCommon).forEach(([key, value]) => {
if (key === 'targetingKey' || key === 'key') {
return;
}
if (key === 'privateAttributes') {
// eslint-disable-next-line no-underscore-dangle
convertedContext._meta = {
privateAttributes: value as string[],
};
} else if (key in LDContextBuiltIns) {
const typedKey = key as 'name' | 'anonymous';
if (typeof value === LDContextBuiltIns[typedKey]) {
convertedContext[key] = value;
} else {
// If the type does not match, then discard.
logger.error(`The attribute '${key}' must be of type ${LDContextBuiltIns[typedKey]}`);
}
} else {
convertAttributes(logger, key, value, convertedContext, [inCommon]);
}
});
return convertedContext;
}
/**
* Convert an OpenFeature evaluation context into an LDContext.
* @param logger Logger.
* @param evalContext The OpenFeature evaluation context to translate.
* @returns An LDContext based on the evaluation context.
*
* @internal
*/
export default function translateContext(logger: LDLogger, evalContext: EvaluationContext): LDContext {
let finalKind = 'user';
// A multi-context.
if (evalContext['kind'] === 'multi') {
return Object.entries(evalContext).reduce((acc: any, [key, value]: [string, EvaluationContextValue]) => {
if (key === 'kind') {
acc.kind = value;
} else if (typeof value === 'object' && !Array.isArray(value)) {
const valueRecord = value as Record<string, EvaluationContextValue>;
acc[key] = translateContextCommon(logger, valueRecord, valueRecord['targetingKey'] as string);
} else {
logger.error('Top level attributes in a multi-kind context should be Structure types.');
}
return acc;
}, {});
}
if (evalContext['kind'] !== undefined && typeof evalContext['kind'] === 'string') {
// Single context with specified kind.
finalKind = evalContext['kind'];
} else if (evalContext['kind'] !== undefined && typeof evalContext['kind'] !== 'string') {
logger.warn("Specified 'kind' of context was not a string.");
}
return {
kind: finalKind,
...translateContextCommon(logger, evalContext, evalContext.targetingKey),
} as LDSingleKindContext;
}