@splitsoftware/openfeature-web-split-provider 1.0.0 → 1.2.0

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.
Files changed (37) hide show
  1. package/CHANGES.txt +13 -2
  2. package/README.md +190 -16
  3. package/es/lib/context.js +55 -0
  4. package/es/lib/evaluation.js +21 -0
  5. package/es/lib/events.js +69 -0
  6. package/es/lib/js-split-provider.js +80 -142
  7. package/es/lib/parsers.js +38 -0
  8. package/es/lib/types.js +2 -0
  9. package/lib/lib/context.js +61 -0
  10. package/lib/lib/evaluation.js +25 -0
  11. package/lib/lib/events.js +74 -0
  12. package/lib/lib/js-split-provider.js +78 -140
  13. package/lib/lib/parsers.js +44 -0
  14. package/lib/lib/types.js +5 -0
  15. package/package.json +2 -2
  16. package/src/__tests__/bucketingKey.spec.js +145 -0
  17. package/src/__tests__/context.spec.js +146 -0
  18. package/src/__tests__/evaluation.spec.js +76 -0
  19. package/src/__tests__/events.spec.js +182 -0
  20. package/src/__tests__/integration/bucketing-key.test.js +81 -0
  21. package/src/__tests__/integration/e2e-events.test.js +1 -8
  22. package/src/__tests__/integration/openfeature-evaluation.test.js +162 -0
  23. package/src/__tests__/parsers.spec.js +115 -0
  24. package/src/__tests__/provider.spec.js +59 -3
  25. package/src/__tests__/types.spec.js +15 -0
  26. package/src/lib/context.ts +62 -0
  27. package/src/lib/evaluation.ts +33 -0
  28. package/src/lib/events.ts +105 -0
  29. package/src/lib/js-split-provider.ts +103 -180
  30. package/src/lib/parsers.ts +43 -0
  31. package/src/lib/types.ts +12 -0
  32. package/types/lib/context.d.ts +15 -0
  33. package/types/lib/evaluation.d.ts +7 -0
  34. package/types/lib/events.d.ts +20 -0
  35. package/types/lib/js-split-provider.d.ts +11 -7
  36. package/types/lib/parsers.d.ts +8 -0
  37. package/types/lib/types.d.ts +10 -0
@@ -1,5 +1,6 @@
1
1
  /* eslint-disable jest/no-conditional-expect */
2
2
  /* eslint-disable @typescript-eslint/no-unused-vars */
3
+ import { ProviderEvents } from '@openfeature/web-sdk';
3
4
  import { OpenFeatureSplitProvider } from '../lib/js-split-provider';
4
5
 
5
6
  describe('OpenFeatureSplitProvider Unit Tests', () => {
@@ -21,8 +22,11 @@ describe('OpenFeatureSplitProvider Unit Tests', () => {
21
22
  }
22
23
  return { id: 'mock-listener' };
23
24
  }),
24
- // Define SDK_READY event constant
25
- Event: { SDK_READY: 'SDK_READY' },
25
+ // Define event constants used by provider
26
+ Event: {
27
+ SDK_READY: 'SDK_READY',
28
+ SDK_UPDATE: 'SDK_UPDATE',
29
+ },
26
30
 
27
31
  // Mock the treatments
28
32
  getTreatmentWithConfig: jest.fn((flagKey, _attributes) => {
@@ -159,5 +163,57 @@ describe('OpenFeatureSplitProvider Unit Tests', () => {
159
163
  expect(trackSpy).toHaveBeenCalledTimes(1);
160
164
  expect(trackSpy).toHaveBeenCalledWith('user', 'purchase', 9.99, { plan: 'pro', beta: true });
161
165
  });
162
-
166
+
167
+ describe('SDK_UPDATE / ConfigurationChanged', () => {
168
+ beforeEach(async () => {
169
+ await provider.initialize();
170
+ });
171
+
172
+ function getSdkUpdateCallback() {
173
+ const call = mockSplitClient.on.mock.calls.find((c) => c[0] === 'SDK_UPDATE');
174
+ return call ? call[1] : null;
175
+ }
176
+
177
+ test('emits ConfigurationChanged with only providerName when updateMetadata is undefined', () => {
178
+ const emitSpy = jest.spyOn(provider.events, 'emit');
179
+ const sdkUpdateCallback = getSdkUpdateCallback();
180
+ expect(sdkUpdateCallback).toBeDefined();
181
+
182
+ sdkUpdateCallback(undefined);
183
+
184
+ expect(emitSpy).toHaveBeenCalledWith(ProviderEvents.ConfigurationChanged, {
185
+ providerName: provider.metadata.name,
186
+ });
187
+ });
188
+
189
+ test('emits ConfigurationChanged with metadata when updateMetadata is provided', () => {
190
+ const emitSpy = jest.spyOn(provider.events, 'emit');
191
+ const sdkUpdateCallback = getSdkUpdateCallback();
192
+ const updateMetadata = { type: 'SPLIT_KILL', names: ['flag-a', 'flag-b'] };
193
+
194
+ sdkUpdateCallback(updateMetadata);
195
+
196
+ expect(emitSpy).toHaveBeenCalledWith(ProviderEvents.ConfigurationChanged, {
197
+ providerName: provider.metadata.name,
198
+ flagsChanged: updateMetadata.names,
199
+ metadata: { type: updateMetadata.type },
200
+ });
201
+ });
202
+
203
+ test('emits ConfigurationChanged with flagsChanged when updateMetadata.type is FLAGS_UPDATE', () => {
204
+ const emitSpy = jest.spyOn(provider.events, 'emit');
205
+ const sdkUpdateCallback = getSdkUpdateCallback();
206
+ const updateMetadata = { type: 'FLAGS_UPDATE', names: ['my-flag', 'other-flag'] };
207
+
208
+ sdkUpdateCallback(updateMetadata);
209
+
210
+ expect(emitSpy).toHaveBeenCalledWith(ProviderEvents.ConfigurationChanged, {
211
+ providerName: provider.metadata.name,
212
+ metadata: {
213
+ type: 'FLAGS_UPDATE',
214
+ },
215
+ flagsChanged: ['my-flag', 'other-flag'],
216
+ });
217
+ });
218
+ });
163
219
  });
@@ -0,0 +1,15 @@
1
+ import {
2
+ CONTROL_TREATMENT,
3
+ CONTROL_VALUE_ERROR_MESSAGE,
4
+ } from '../lib/types';
5
+
6
+ describe('types', () => {
7
+ test('CONTROL_TREATMENT is "control"', () => {
8
+ expect(CONTROL_TREATMENT).toBe('control');
9
+ });
10
+
11
+ test('CONTROL_VALUE_ERROR_MESSAGE mentions control', () => {
12
+ expect(CONTROL_VALUE_ERROR_MESSAGE).toContain('control');
13
+ expect(CONTROL_VALUE_ERROR_MESSAGE).toBe("Received the 'control' value from Split.");
14
+ });
15
+ });
@@ -0,0 +1,62 @@
1
+ import type { EvaluationContext } from "@openfeature/web-sdk";
2
+ import type SplitIO from "@splitsoftware/splitio-browserjs/types/splitio";
3
+ import type { Consumer } from "./types";
4
+
5
+ /** Split SDK limit for key values. */
6
+ const KEY_MAX_LENGTH = 250;
7
+
8
+ type BucketingKeyRead = { value?: string; reason?: string };
9
+
10
+ /** Trimmed bucketing key, or the reason it cannot be used. The reason never includes the value. */
11
+ function parseBucketingKey(value: unknown): BucketingKeyRead {
12
+ if (value === undefined || value === null) return {};
13
+ if (typeof value !== 'string') return { reason: 'it is not a string' };
14
+ const bucketingKey = value.trim();
15
+ if (!bucketingKey) return { reason: 'it is blank' };
16
+ if (bucketingKey.length > KEY_MAX_LENGTH) return { reason: `it is longer than ${KEY_MAX_LENGTH} characters` };
17
+ return { value: bucketingKey };
18
+ }
19
+
20
+ function readBucketingKey(value: unknown): string | undefined {
21
+ return parseBucketingKey(value).value;
22
+ }
23
+
24
+ /**
25
+ * Warning for a bucketingKey in the context that will not be used, or undefined when there is nothing to report.
26
+ * Names the reason only, never the value.
27
+ */
28
+ export function bucketingKeyWarning(context: EvaluationContext): string | undefined {
29
+ const { value, reason } = parseBucketingKey(context.bucketingKey);
30
+ if (reason) {
31
+ return `bucketingKey ignored because ${reason}${context.targetingKey ? '; using the targeting key only' : ''}.`;
32
+ }
33
+ if (value && !context.targetingKey) return 'bucketingKey ignored because the context has no targetingKey.';
34
+ return undefined;
35
+ }
36
+
37
+ /**
38
+ * Transform OpenFeature evaluation context into a consumer object for the Split API.
39
+ * `bucketingKey` is reserved: it is never forwarded as an attribute.
40
+ */
41
+ export function transformContext(
42
+ context: EvaluationContext,
43
+ defaultTrafficType: string
44
+ ): Consumer {
45
+ const { targetingKey, bucketingKey, trafficType: ttVal, ...attributes } = context;
46
+ const trafficType =
47
+ ttVal != null && typeof ttVal === 'string' && ttVal.trim() !== ''
48
+ ? ttVal
49
+ : defaultTrafficType;
50
+ return {
51
+ targetingKey,
52
+ bucketingKey: readBucketingKey(bucketingKey),
53
+ trafficType,
54
+ attributes: JSON.parse(JSON.stringify(attributes)),
55
+ };
56
+ }
57
+
58
+ /** Split key for a consumer: `{ matchingKey, bucketingKey }` or the targeting key alone. */
59
+ export function toSplitKey({ targetingKey, bucketingKey }: Consumer): SplitIO.SplitKey | undefined {
60
+ if (!targetingKey) return undefined;
61
+ return bucketingKey ? { matchingKey: targetingKey, bucketingKey } : targetingKey;
62
+ }
@@ -0,0 +1,33 @@
1
+ import type { ResolutionDetails } from "@openfeature/web-sdk";
2
+ import { FlagNotFoundError, StandardResolutionReasons } from "@openfeature/web-sdk";
3
+ import type SplitIO from "@splitsoftware/splitio-browserjs/types/splitio";
4
+ import { CONTROL_TREATMENT, CONTROL_VALUE_ERROR_MESSAGE } from "./types";
5
+ import type { Consumer } from "./types";
6
+
7
+ /**
8
+ * Evaluate a flag with the Split client and return string resolution details.
9
+ */
10
+ export function evaluateTreatment(
11
+ client: SplitIO.IBrowserClient,
12
+ flagKey: string,
13
+ consumer: Consumer
14
+ ): ResolutionDetails<string> {
15
+ if (flagKey == null || flagKey === '') {
16
+ throw new FlagNotFoundError('flagKey must be a non-empty string');
17
+ }
18
+ const treatment: SplitIO.TreatmentWithConfig = client.getTreatmentWithConfig(
19
+ flagKey,
20
+ consumer.attributes
21
+ );
22
+ const { treatment: value, config } = treatment;
23
+
24
+ if (value === CONTROL_TREATMENT) {
25
+ throw new FlagNotFoundError(CONTROL_VALUE_ERROR_MESSAGE);
26
+ }
27
+ return {
28
+ value,
29
+ variant: value,
30
+ flagMetadata: { config: config ? config : '' },
31
+ reason: StandardResolutionReasons.TARGETING_MATCH,
32
+ };
33
+ }
@@ -0,0 +1,105 @@
1
+ /* eslint-disable @typescript-eslint/no-explicit-any */
2
+ import { ProviderEvents } from "@openfeature/web-sdk";
3
+ import type { EventDetails, EventMetadata, OpenFeatureEventEmitter } from "@openfeature/web-sdk";
4
+ import type SplitIO from "@splitsoftware/splitio-browserjs/types/splitio";
5
+
6
+ /**
7
+ * Split SDK emits SDK_READY with SdkReadyMetadata:
8
+ * - initialCacheLoad: boolean — true when fresh install / no cache, false when ready from cache
9
+ * - lastUpdateTimestamp?: number — ms since epoch when cache was last updated (undefined if initialCacheLoad is true)
10
+ */
11
+
12
+ export type ReadyCallbacks = {
13
+ onSdkReady: () => void;
14
+ onSdkTimedOut: () => void;
15
+ };
16
+
17
+ /** Map Split SdkReadyMetadata to OpenFeature EventMetadata (string | boolean | number). */
18
+ function toReadyEventMetadata(sdkReadyMetadata: SplitIO.SdkReadyMetadata): EventMetadata {
19
+ const meta: EventMetadata = {
20
+ initialCacheLoad: sdkReadyMetadata.initialCacheLoad,
21
+ };
22
+ if (sdkReadyMetadata.lastUpdateTimestamp != null) {
23
+ meta.lastUpdateTimestamp = sdkReadyMetadata.lastUpdateTimestamp;
24
+ }
25
+ return meta;
26
+ }
27
+
28
+ /**
29
+ * Emit OpenFeature ProviderEvents.Ready with Split SDK ready metadata, then invoke the callback.
30
+ * When sdkReadyMetadata is provided (from SDK_READY event), use it; otherwise emit with empty metadata (e.g. when already ready).
31
+ */
32
+ function emitReadyWithSplitMetadata(
33
+ eventsEmitter: OpenFeatureEventEmitter,
34
+ providerName: string,
35
+ onSdkReady: () => void,
36
+ sdkReadyMetadata?: SplitIO.SdkReadyMetadata
37
+ ): void {
38
+ const readyDetails: EventDetails = {
39
+ providerName,
40
+ metadata: sdkReadyMetadata ? toReadyEventMetadata(sdkReadyMetadata) : {},
41
+ };
42
+ eventsEmitter.emit(ProviderEvents.Ready, readyDetails);
43
+ onSdkReady();
44
+ }
45
+
46
+ /**
47
+ * Attach Split SDK event listeners and resolve/reject the ready promise based on client status.
48
+ * When the Split SDK becomes ready, emits ProviderEvents.Ready with Split ready metadata before resolving.
49
+ */
50
+ export function attachSplitReadyHandlers(
51
+ client: SplitIO.IBrowserClient,
52
+ eventsEmitter: OpenFeatureEventEmitter,
53
+ callbacks: ReadyCallbacks,
54
+ providerName: string
55
+ ): void {
56
+ const { onSdkReady, onSdkTimedOut } = callbacks;
57
+
58
+ const onSdkReadyFromCache = () => {
59
+ eventsEmitter.emit(ProviderEvents.Stale, { message: 'Split ready from cache' });
60
+ };
61
+
62
+ const clientStatus = (client as any).__getStatus();
63
+ if (clientStatus.isReady) {
64
+ emitReadyWithSplitMetadata(eventsEmitter, providerName, onSdkReady);
65
+ return;
66
+ }
67
+
68
+ if (clientStatus.isReadyFromCache) {
69
+ onSdkReadyFromCache();
70
+ } else {
71
+ client.on(client.Event.SDK_READY_FROM_CACHE, onSdkReadyFromCache);
72
+ }
73
+
74
+ if (clientStatus.hasTimedout) {
75
+ onSdkTimedOut();
76
+ } else {
77
+ client.on(client.Event.SDK_READY_TIMED_OUT, onSdkTimedOut);
78
+ }
79
+ client.on(client.Event.SDK_READY, (sdkReadyMetadata?: SplitIO.SdkReadyMetadata) => {
80
+ emitReadyWithSplitMetadata(eventsEmitter, providerName, onSdkReady, sdkReadyMetadata);
81
+ });
82
+ }
83
+
84
+ /**
85
+ * Subscribe to Split SDK_UPDATE and emit OpenFeature ConfigurationChanged with details.
86
+ */
87
+ export function attachSplitUpdateHandler(
88
+ client: SplitIO.IBrowserClient,
89
+ eventsEmitter: OpenFeatureEventEmitter,
90
+ providerName: string
91
+ ): void {
92
+ client.on(client.Event.SDK_UPDATE, (updateMetadata: SplitIO.SdkUpdateMetadata) => {
93
+ let eventDetails: EventDetails = { providerName };
94
+ if (updateMetadata) {
95
+ eventDetails = {
96
+ ...eventDetails,
97
+ metadata: {
98
+ type: updateMetadata.type,
99
+ },
100
+ flagsChanged: updateMetadata.names || []
101
+ };
102
+ }
103
+ eventsEmitter.emit(ProviderEvents.ConfigurationChanged, eventDetails);
104
+ });
105
+ }
@@ -1,13 +1,10 @@
1
- /* eslint-disable @typescript-eslint/no-explicit-any */
2
1
  /* eslint-disable @typescript-eslint/no-unused-vars */
3
2
  import {
4
3
  EvaluationContext,
5
4
  Provider,
6
5
  ResolutionDetails,
7
6
  ParseError,
8
- FlagNotFoundError,
9
7
  JsonValue,
10
- StandardResolutionReasons,
11
8
  Logger,
12
9
  ProviderEvents,
13
10
  OpenFeatureEventEmitter,
@@ -15,60 +12,104 @@ import {
15
12
  } from "@openfeature/web-sdk";
16
13
  import type SplitIO from "@splitsoftware/splitio-browserjs/types/splitio";
17
14
 
18
- type Consumer = {
19
- targetingKey: string | undefined;
20
- trafficType: string;
21
- attributes: SplitIO.Attributes;
22
- };
23
-
24
- const CONTROL_VALUE_ERROR_MESSAGE = "Received the 'control' value from Split.";
25
- const CONTROL_TREATMENT = 'control';
15
+ import { bucketingKeyWarning, toSplitKey, transformContext } from "./context";
16
+ import { attachSplitReadyHandlers, attachSplitUpdateHandler } from "./events";
17
+ import { evaluateTreatment } from "./evaluation";
18
+ import { parseBooleanTreatment, parseValidJsonObject, parseValidNumber } from "./parsers";
26
19
 
27
20
  export class OpenFeatureSplitProvider implements Provider {
28
- metadata = {
29
- name: "split",
30
- };
21
+ metadata = { name: "split" };
22
+
31
23
  private client: SplitIO.IBrowserClient;
32
24
  private factory: SplitIO.IBrowserSDK;
33
25
  private trafficType: string;
26
+ /** Readiness of the bound client (rejects if it timed out). */
27
+ private ready: Promise<void> = Promise.resolve();
34
28
  public events = new OpenFeatureEventEmitter();
35
29
 
36
- onContextChange(oldContext: EvaluationContext, newContext: EvaluationContext): Promise<void> {
37
- const { targetingKey: oldTargetingKey } = oldContext;
38
- const { targetingKey: newTargetingKey, trafficType: newTrafficType } = newContext;
39
-
40
- this.trafficType = newTrafficType && newTrafficType !== this.trafficType ? newTrafficType as string : this.trafficType ;
41
- if (newTargetingKey && newTargetingKey !== oldTargetingKey) {
42
- this.client = this.factory.client(newTargetingKey);
43
-
44
- return new Promise((resolve, reject) => {
45
- const emitContextChange = () => {
46
- this.events.emit(ProviderEvents.ConfigurationChanged);
47
- resolve();
48
- };
49
-
50
- this.eventsHandler(emitContextChange, reject);
51
- });
52
- }
53
- return Promise.resolve();
54
- }
55
-
56
30
  constructor(splitFactory: SplitIO.IBrowserSDK) {
57
- // Asume 'user' as default traffic type'
58
31
  this.trafficType = 'user';
59
32
  this.factory = splitFactory;
60
33
  this.client = splitFactory.client();
61
34
  }
62
35
 
63
- async initialize(): Promise<void> {
64
-
65
- await new Promise ((resolve, reject) => {
36
+ /**
37
+ * Warn through the Split SDK logger, so it follows the SDK log settings (`debug`, `factory.Logger`).
38
+ * `settings.log` is internal: the public typings only expose `factory.Logger`, which has no `warn`.
39
+ */
40
+ private warn(message: string): void {
41
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
42
+ (this.factory as any).settings?.log?.warn?.(`[${this.metadata.name}-openfeature] ${message}`);
43
+ }
44
+
45
+ /** Warn once per context set; evaluations reuse the context and would repeat it. */
46
+ private warnIfBucketingKeyIgnored(context: EvaluationContext): void {
47
+ const warning = bucketingKeyWarning(context);
48
+ if (warning) this.warn(warning);
49
+ }
50
+
51
+ async initialize(context?: EvaluationContext): Promise<void> {
52
+ if (context) this.warnIfBucketingKeyIgnored(context);
53
+ // Apply the context set before the provider. The SDK returns the factory client for the factory key.
54
+ const key = context && toSplitKey(transformContext(context, this.trafficType));
55
+ if (key) this.client = this.factory.client(key);
56
+
57
+ this.ready = new Promise<void>((resolve, reject) => {
66
58
  try {
67
- this.eventsHandler(resolve, reject);
59
+ attachSplitReadyHandlers(
60
+ this.client,
61
+ this.events,
62
+ { onSdkReady: resolve as () => void, onSdkTimedOut: reject },
63
+ this.metadata.name
64
+ );
65
+ attachSplitUpdateHandler(this.client, this.events, this.metadata.name);
68
66
  } catch {
69
67
  reject();
70
68
  }
71
69
  });
70
+ await this.ready;
71
+ }
72
+
73
+ onContextChange(oldContext: EvaluationContext, newContext: EvaluationContext): Promise<void> {
74
+ this.warnIfBucketingKeyIgnored(newContext);
75
+ const { trafficType: newTrafficType } = newContext;
76
+
77
+ this.trafficType =
78
+ newTrafficType && newTrafficType !== this.trafficType
79
+ ? (newTrafficType as string)
80
+ : this.trafficType;
81
+
82
+ const oldConsumer = transformContext(oldContext, this.trafficType);
83
+ const newConsumer = transformContext(newContext, this.trafficType);
84
+ const newKey = toSplitKey(newConsumer);
85
+ const keyChanged =
86
+ newConsumer.targetingKey !== oldConsumer.targetingKey ||
87
+ newConsumer.bucketingKey !== oldConsumer.bucketingKey;
88
+
89
+ if (!newKey || !keyChanged) {
90
+ // Same client: OpenFeature marks the provider READY when this resolves, so wait if it is still loading
91
+ // (a timeout during that load must still surface as ERROR). If it already timed out, that was reported
92
+ // and this.ready stays rejected, so resolve instead of moving the provider to ERROR on a no-key change.
93
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
94
+ const { isReady, hasTimedout } = (this.client as any).__getStatus();
95
+ return isReady || hasTimedout ? Promise.resolve() : this.ready;
96
+ }
97
+
98
+ this.client = this.factory.client(newKey);
99
+ this.ready = new Promise((resolve, reject) => {
100
+ const emitContextChange = () => {
101
+ this.events.emit(ProviderEvents.ConfigurationChanged);
102
+ resolve();
103
+ };
104
+ attachSplitReadyHandlers(
105
+ this.client,
106
+ this.events,
107
+ { onSdkReady: emitContextChange, onSdkTimedOut: reject },
108
+ this.metadata.name
109
+ );
110
+ attachSplitUpdateHandler(this.client, this.events, this.metadata.name);
111
+ });
112
+ return this.ready;
72
113
  }
73
114
 
74
115
  resolveBooleanEvaluation(
@@ -77,22 +118,13 @@ export class OpenFeatureSplitProvider implements Provider {
77
118
  context: EvaluationContext,
78
119
  _logger: Logger
79
120
  ): ResolutionDetails<boolean> {
80
- const details = this.evaluateTreatment(
121
+ const details = evaluateTreatment(
122
+ this.client,
81
123
  flagKey,
82
- this.transformContext(context),
124
+ transformContext(context, this.trafficType)
83
125
  );
84
-
85
- const treatment = details.value.toLowerCase();
86
-
87
- if ( treatment === 'on' || treatment === 'true' ) {
88
- return { ...details, value: true };
89
- }
90
-
91
- if ( treatment === 'off' || treatment === 'false' ) {
92
- return { ...details, value: false };
93
- }
94
-
95
- throw new ParseError(`Invalid boolean value for ${treatment}`);
126
+ const value = parseBooleanTreatment(details.value);
127
+ return { ...details, value };
96
128
  }
97
129
 
98
130
  resolveStringEvaluation(
@@ -101,11 +133,11 @@ export class OpenFeatureSplitProvider implements Provider {
101
133
  context: EvaluationContext,
102
134
  _logger: Logger
103
135
  ): ResolutionDetails<string> {
104
- const details = this.evaluateTreatment(
136
+ return evaluateTreatment(
137
+ this.client,
105
138
  flagKey,
106
- this.transformContext(context),
139
+ transformContext(context, this.trafficType)
107
140
  );
108
- return details;
109
141
  }
110
142
 
111
143
  resolveNumberEvaluation(
@@ -114,11 +146,12 @@ export class OpenFeatureSplitProvider implements Provider {
114
146
  context: EvaluationContext,
115
147
  _logger: Logger
116
148
  ): ResolutionDetails<number> {
117
- const details = this.evaluateTreatment(
149
+ const details = evaluateTreatment(
150
+ this.client,
118
151
  flagKey,
119
- this.transformContext(context),
152
+ transformContext(context, this.trafficType)
120
153
  );
121
- return { ...details, value: this.parseValidNumber(details.value) };
154
+ return { ...details, value: parseValidNumber(details.value) };
122
155
  }
123
156
 
124
157
  resolveObjectEvaluation<U extends JsonValue>(
@@ -127,39 +160,12 @@ export class OpenFeatureSplitProvider implements Provider {
127
160
  context: EvaluationContext,
128
161
  _logger: Logger
129
162
  ): ResolutionDetails<U> {
130
- const details = this.evaluateTreatment(
163
+ const details = evaluateTreatment(
164
+ this.client,
131
165
  flagKey,
132
- this.transformContext(context)
166
+ transformContext(context, this.trafficType)
133
167
  );
134
- return { ...details, value: this.parseValidJsonObject(details.value) };
135
- }
136
-
137
- private evaluateTreatment(
138
- flagKey: string,
139
- consumer: Consumer
140
- ): ResolutionDetails<string> {
141
- if (flagKey == null || flagKey === '') {
142
- throw new FlagNotFoundError(
143
- 'flagKey must be a non-empty string'
144
- );
145
- }
146
- const treatment: SplitIO.TreatmentWithConfig = this.client.getTreatmentWithConfig(
147
- flagKey,
148
- consumer.attributes
149
- );
150
- const {treatment: value, config} = treatment;
151
-
152
- if (value === CONTROL_TREATMENT) {
153
- throw new FlagNotFoundError(CONTROL_VALUE_ERROR_MESSAGE);
154
- }
155
- const flagMetadata = { config: config ? config : '' };
156
- const details: ResolutionDetails<string> = {
157
- value: value,
158
- variant: value,
159
- flagMetadata: flagMetadata,
160
- reason: StandardResolutionReasons.TARGETING_MATCH,
161
- };
162
- return details;
168
+ return { ...details, value: parseValidJsonObject<U>(details.value) };
163
169
  }
164
170
 
165
171
  track(
@@ -167,105 +173,22 @@ export class OpenFeatureSplitProvider implements Provider {
167
173
  context: EvaluationContext,
168
174
  details: TrackingEventDetails
169
175
  ): void {
170
-
171
- // eventName is always required
172
- if (trackingEventName == null || trackingEventName === '')
176
+ if (trackingEventName == null || trackingEventName === '') {
173
177
  throw new ParseError('Missing eventName, required to track');
174
-
175
- const {trafficType} = this.transformContext(context);
176
- let value;
178
+ }
179
+ const { trafficType } = transformContext(context, this.trafficType);
180
+ let value: unknown;
177
181
  let properties: SplitIO.Properties = {};
178
182
  if (details != null) {
179
- if (details.value != null) {
180
- value = details.value;
181
- }
183
+ if (details.value != null) value = details.value;
182
184
  if (details.properties != null) {
183
185
  properties = details.properties as SplitIO.Properties;
184
186
  }
185
- }
186
-
187
- this.client.track(trafficType, trackingEventName, value, properties);
187
+ }
188
+ this.client.track(trafficType, trackingEventName, value as number | undefined, properties);
188
189
  }
189
190
 
190
191
  async onClose?(): Promise<void> {
191
192
  return this.factory.destroy();
192
193
  }
193
-
194
- //Transform the context into an object useful for the Split API, an key string with arbitrary Split "Attributes".
195
- private transformContext(context: EvaluationContext): Consumer {
196
- const { targetingKey, trafficType: ttVal, ...attributes } = context;
197
- const trafficType =
198
- ttVal != null && typeof ttVal === 'string' && ttVal.trim() !== ''
199
- ? ttVal
200
- : this.trafficType;
201
- return {
202
- targetingKey,
203
- trafficType,
204
- // Stringify context objects include date.
205
- attributes: JSON.parse(JSON.stringify(attributes)),
206
- };
207
- }
208
-
209
- private parseValidNumber(stringValue: string | undefined) {
210
- if (stringValue === undefined) {
211
- throw new ParseError(`Invalid 'undefined' value.`);
212
- }
213
- const result = Number.parseFloat(stringValue);
214
- if (Number.isNaN(result)) {
215
- throw new ParseError(`Invalid numeric value ${stringValue}`);
216
- }
217
- return result;
218
- }
219
-
220
- private parseValidJsonObject<T extends JsonValue>(
221
- stringValue: string | undefined
222
- ): T {
223
- if (stringValue === undefined) {
224
- throw new ParseError(`Invalid 'undefined' JSON value.`);
225
- }
226
- // we may want to allow the parsing to be customized.
227
- try {
228
- const value = JSON.parse(stringValue);
229
- if (typeof value !== "object") {
230
- throw new ParseError(
231
- `Flag value ${stringValue} had unexpected type ${typeof value}, expected "object"`
232
- );
233
- }
234
- return value;
235
- } catch (err) {
236
- throw new ParseError(`Error parsing ${stringValue} as JSON, ${err}`);
237
- }
238
- }
239
-
240
- private async eventsHandler(onSdkReady: (params?: any) => void, onSdkTimedOut: () => void): Promise <void> {
241
-
242
- const onSdkReadyFromCache = () => {
243
- this.events.emit(ProviderEvents.Stale, {
244
- message: `Split ready from cache`,
245
- });
246
- };
247
-
248
- const clientStatus = (this.client as any).__getStatus();
249
- if (clientStatus.isReady) {
250
- onSdkReady();
251
- } else {
252
-
253
- if (clientStatus.isReadyFromCache) {
254
- onSdkReadyFromCache();
255
- } else {
256
- this.client.on(this.client.Event.SDK_READY_FROM_CACHE, onSdkReadyFromCache);
257
- }
258
-
259
- if (clientStatus.hasTimedout) {
260
- onSdkTimedOut();
261
- } else {
262
- this.client.on(this.client.Event.SDK_READY_TIMED_OUT, onSdkTimedOut);
263
- }
264
- this.client.on(this.client.Event.SDK_READY, onSdkReady);
265
- }
266
-
267
- this.client.on(this.client.Event.SDK_UPDATE, () => {
268
- this.events.emit(ProviderEvents.ConfigurationChanged);
269
- });
270
- }
271
194
  }