@splitsoftware/openfeature-js-split-provider 1.2.0 → 1.4.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 (38) hide show
  1. package/CHANGES.txt +14 -0
  2. package/README.md +37 -3
  3. package/es/lib/client-resolver.js +17 -0
  4. package/es/lib/context.js +28 -0
  5. package/es/lib/js-split-provider.js +66 -103
  6. package/es/lib/parsers.js +26 -0
  7. package/es/lib/readiness.js +64 -0
  8. package/es/lib/types.js +4 -0
  9. package/es/package.json +1 -0
  10. package/lib/index.js +1 -1
  11. package/lib/lib/client-resolver.js +21 -0
  12. package/lib/lib/context.js +32 -0
  13. package/lib/lib/js-split-provider.js +68 -105
  14. package/lib/lib/parsers.js +31 -0
  15. package/lib/lib/readiness.js +70 -0
  16. package/lib/lib/types.js +7 -0
  17. package/package.json +12 -7
  18. package/src/__tests__/nodeSuites/client.spec.js +17 -2
  19. package/src/__tests__/nodeSuites/client_redis.spec.js +9 -10
  20. package/src/__tests__/nodeSuites/provider.spec.js +191 -0
  21. package/src/index.ts +1 -1
  22. package/src/lib/__tests__/client-resolver.spec.ts +64 -0
  23. package/src/lib/__tests__/context.spec.ts +114 -0
  24. package/src/lib/__tests__/parsers.spec.ts +63 -0
  25. package/src/lib/__tests__/readiness.spec.ts +159 -0
  26. package/src/lib/client-resolver.ts +22 -0
  27. package/src/lib/context.ts +35 -0
  28. package/src/lib/js-split-provider.ts +120 -144
  29. package/src/lib/parsers.ts +32 -0
  30. package/src/lib/readiness.ts +103 -0
  31. package/src/lib/types.ts +41 -0
  32. package/types/index.d.ts +1 -1
  33. package/types/lib/client-resolver.d.ts +7 -0
  34. package/types/lib/context.d.ts +8 -0
  35. package/types/lib/js-split-provider.d.ts +16 -18
  36. package/types/lib/parsers.d.ts +3 -0
  37. package/types/lib/readiness.d.ts +16 -0
  38. package/types/lib/types.d.ts +32 -0
@@ -0,0 +1,64 @@
1
+ import type SplitIO from '@splitsoftware/splitio/types/splitio';
2
+ import { getSplitClient } from '../client-resolver';
3
+ import { SplitProviderOptions } from '../types';
4
+
5
+ function createMockSplitClient(): SplitIO.IClient {
6
+ return {
7
+ getTreatmentWithConfig: jest.fn(),
8
+ getStatus: jest.fn(),
9
+ on: jest.fn(),
10
+ track: jest.fn(),
11
+ destroy: jest.fn(),
12
+ Event: {
13
+ SDK_READY: 'init::ready',
14
+ SDK_READY_FROM_CACHE: 'init::cache-ready',
15
+ SDK_READY_TIMED_OUT: 'init::timeout',
16
+ SDK_UPDATE: 'state::update',
17
+ },
18
+ } as unknown as SplitIO.IClient;
19
+ }
20
+
21
+ describe('client-resolver', () => {
22
+ describe('getSplitClient', () => {
23
+ it('returns splitClient when options is SplitProviderOptions with splitClient', () => {
24
+ const mockClient = createMockSplitClient();
25
+ const options = { splitClient: mockClient };
26
+ const client = getSplitClient(options);
27
+ expect(client).toBe(mockClient);
28
+ });
29
+
30
+ it('returns client from factory when options has client() method', () => {
31
+ const mockClient = createMockSplitClient();
32
+ const mockFactory = {
33
+ client: jest.fn().mockReturnValue(mockClient),
34
+ };
35
+ const client = getSplitClient(mockFactory as unknown as SplitIO.ISDK);
36
+ expect(mockFactory.client).toHaveBeenCalled();
37
+ expect(client).toBe(mockClient);
38
+ });
39
+
40
+ it('falls back to splitClient when options.client() throws', () => {
41
+ const mockClient = createMockSplitClient();
42
+ const mockFactory = {
43
+ client: jest.fn().mockImplementation(() => {
44
+ throw new Error('not a real SDK');
45
+ }),
46
+ };
47
+ const options = { splitClient: mockClient, ...mockFactory };
48
+ const client = getSplitClient(options as SplitProviderOptions);
49
+ expect(client).toBe(mockClient);
50
+ });
51
+
52
+ it('creates client from API key when options is string', () => {
53
+ const client = getSplitClient('localhost');
54
+ expect(client).toBeDefined();
55
+ expect(typeof client.getTreatmentWithConfig).toBe('function');
56
+ expect(typeof client.getStatus).toBe('function');
57
+ expect(client.Event).toBeDefined();
58
+ expect(client.Event.SDK_READY).toBeDefined();
59
+ if (typeof client.destroy === 'function') {
60
+ client.destroy();
61
+ }
62
+ });
63
+ });
64
+ });
@@ -0,0 +1,114 @@
1
+ import { transformContext } from '../context';
2
+ import { DEFAULT_TRAFFIC_TYPE } from '../types';
3
+
4
+ describe('context', () => {
5
+ describe('transformContext', () => {
6
+ it('extracts targetingKey and uses default traffic type when missing', () => {
7
+ const context = { targetingKey: 'user-123' };
8
+ const result = transformContext(context);
9
+ expect(result.targetingKey).toBe('user-123');
10
+ expect(result.trafficType).toBe(DEFAULT_TRAFFIC_TYPE);
11
+ expect(result.attributes).toEqual({});
12
+ });
13
+
14
+ it('uses provided traffic type when present and non-empty', () => {
15
+ const context = {
16
+ targetingKey: 'user-1',
17
+ trafficType: 'account',
18
+ };
19
+ const result = transformContext(context);
20
+ expect(result.trafficType).toBe('account');
21
+ expect(result.targetingKey).toBe('user-1');
22
+ expect(result.attributes).toEqual({});
23
+ });
24
+
25
+ it('uses default traffic type when trafficType is empty string', () => {
26
+ const context = {
27
+ targetingKey: 'user-1',
28
+ trafficType: '',
29
+ };
30
+ const result = transformContext(context);
31
+ expect(result.trafficType).toBe(DEFAULT_TRAFFIC_TYPE);
32
+ });
33
+
34
+ it('uses default traffic type when trafficType is whitespace', () => {
35
+ const context = {
36
+ targetingKey: 'user-1',
37
+ trafficType: ' ',
38
+ };
39
+ const result = transformContext(context);
40
+ expect(result.trafficType).toBe(DEFAULT_TRAFFIC_TYPE);
41
+ });
42
+
43
+ it('passes remaining context as attributes', () => {
44
+ const context = {
45
+ targetingKey: 'user-1',
46
+ trafficType: 'user',
47
+ plan: 'premium',
48
+ region: 'us-east',
49
+ };
50
+ const result = transformContext(context);
51
+ expect(result.attributes).toEqual({ plan: 'premium', region: 'us-east' });
52
+ });
53
+
54
+ it('uses custom defaultTrafficType when provided', () => {
55
+ const context = { targetingKey: 'key' };
56
+ const result = transformContext(context, 'custom');
57
+ expect(result.trafficType).toBe('custom');
58
+ });
59
+
60
+ it('handles context with only targetingKey and extra attributes', () => {
61
+ const context = {
62
+ targetingKey: 'anon',
63
+ customAttr: 'value',
64
+ count: 42,
65
+ };
66
+ const result = transformContext(context);
67
+ expect(result.targetingKey).toBe('anon');
68
+ expect(result.trafficType).toBe(DEFAULT_TRAFFIC_TYPE);
69
+ expect(result.attributes).toEqual({ customAttr: 'value', count: 42 });
70
+ });
71
+ });
72
+ });
73
+
74
+ describe('transformContext bucketingKey', () => {
75
+ it('reads a valid bucketingKey and does not forward it as an attribute', () => {
76
+ const result = transformContext({ targetingKey: 'u1', bucketingKey: 'b1', plan: 'pro' });
77
+ expect(result.bucketingKey).toBe('b1');
78
+ expect(result.bucketingKeyIssue).toBeUndefined();
79
+ expect(result.attributes).toEqual({ plan: 'pro' });
80
+ });
81
+
82
+ it('trims surrounding whitespace', () => {
83
+ const result = transformContext({ targetingKey: 'u1', bucketingKey: ' b1 ' });
84
+ expect(result.bucketingKey).toBe('b1');
85
+ expect(result.bucketingKeyIssue).toBeUndefined();
86
+ });
87
+
88
+ it.each([undefined, null])('treats %p as absent, with no issue', (value) => {
89
+ const result = transformContext({ targetingKey: 'u1', bucketingKey: value } as never);
90
+ expect(result).not.toHaveProperty('bucketingKey');
91
+ expect(result.bucketingKeyIssue).toBeUndefined();
92
+ expect(result.attributes).toEqual({});
93
+ });
94
+
95
+ it.each([
96
+ ['', 'blank'],
97
+ [' ', 'blank'],
98
+ [1, 'not a string'],
99
+ [true, 'not a string'],
100
+ [{ x: 1 }, 'not a string'],
101
+ ])('ignores %p with issue %p and strips it from attributes', (value, issue) => {
102
+ const result = transformContext({ targetingKey: 'u1', bucketingKey: value } as never);
103
+ expect(result.bucketingKey).toBeUndefined();
104
+ expect(result.bucketingKeyIssue).toBe(issue);
105
+ expect(result.attributes).toEqual({});
106
+ });
107
+
108
+ it('keeps BucketingKey and bucketing_key as plain attributes', () => {
109
+ const result = transformContext({ targetingKey: 'u1', BucketingKey: 'x', bucketing_key: 'y' });
110
+ expect(result.bucketingKey).toBeUndefined();
111
+ expect(result.bucketingKeyIssue).toBeUndefined();
112
+ expect(result.attributes).toEqual({ BucketingKey: 'x', bucketing_key: 'y' });
113
+ });
114
+ });
@@ -0,0 +1,63 @@
1
+ import { ParseError } from '@openfeature/server-sdk';
2
+ import { parseValidNumber, parseValidJsonObject } from '../parsers';
3
+
4
+ describe('parsers', () => {
5
+ describe('parseValidNumber', () => {
6
+ it('returns parsed number for valid string', () => {
7
+ expect(parseValidNumber('0')).toBe(0);
8
+ expect(parseValidNumber('42')).toBe(42);
9
+ expect(parseValidNumber('-1')).toBe(-1);
10
+ expect(parseValidNumber('3.14')).toBe(3.14);
11
+ expect(parseValidNumber('1e2')).toBe(100);
12
+ });
13
+
14
+ it('throws ParseError for undefined', () => {
15
+ expect(() => parseValidNumber(undefined)).toThrow(ParseError);
16
+ expect(() => parseValidNumber(undefined)).toThrow("Invalid 'undefined' value.");
17
+ });
18
+
19
+ it('throws ParseError for non-numeric string', () => {
20
+ expect(() => parseValidNumber('')).toThrow(ParseError);
21
+ expect(() => parseValidNumber('abc')).toThrow(ParseError);
22
+ expect(() => parseValidNumber('NaN')).toThrow(ParseError);
23
+ });
24
+
25
+ it('throws with message containing the invalid value', () => {
26
+ expect(() => parseValidNumber('foo')).toThrow('Invalid numeric value foo');
27
+ });
28
+ });
29
+
30
+ describe('parseValidJsonObject', () => {
31
+ it('returns parsed object for valid JSON object string', () => {
32
+ expect(parseValidJsonObject('{}')).toEqual({});
33
+ expect(parseValidJsonObject('{"a":1}')).toEqual({ a: 1 });
34
+ expect(parseValidJsonObject('{"nested":{"b":2}}')).toEqual({
35
+ nested: { b: 2 },
36
+ });
37
+ expect(parseValidJsonObject('[]')).toEqual([]);
38
+ });
39
+
40
+ it('throws ParseError for undefined', () => {
41
+ expect(() => parseValidJsonObject(undefined)).toThrow(ParseError);
42
+ expect(() => parseValidJsonObject(undefined)).toThrow(
43
+ "Invalid 'undefined' JSON value."
44
+ );
45
+ });
46
+
47
+ it('throws ParseError for non-object JSON (string, number, boolean)', () => {
48
+ expect(() => parseValidJsonObject('"hello"')).toThrow(ParseError);
49
+ expect(() => parseValidJsonObject('42')).toThrow(ParseError);
50
+ expect(() => parseValidJsonObject('true')).toThrow(ParseError);
51
+ });
52
+
53
+ it('throws with message indicating expected object type', () => {
54
+ expect(() => parseValidJsonObject('"x"')).toThrow('expected "object"');
55
+ });
56
+
57
+ it('throws ParseError for invalid JSON', () => {
58
+ expect(() => parseValidJsonObject('{')).toThrow(ParseError);
59
+ expect(() => parseValidJsonObject('not json')).toThrow(ParseError);
60
+ expect(() => parseValidJsonObject('{"unclosed":')).toThrow(ParseError);
61
+ });
62
+ });
63
+ });
@@ -0,0 +1,159 @@
1
+ import { OpenFeatureEventEmitter, ProviderEvents } from '@openfeature/server-sdk';
2
+ import type SplitIO from '@splitsoftware/splitio/types/splitio';
3
+ import { attachReadyEventHandlers, waitUntilReady } from '../readiness';
4
+ import { PROVIDER_NAME } from '../types';
5
+
6
+ interface MockSplitClient {
7
+ Event: { SDK_READY: string; SDK_READY_FROM_CACHE: string; SDK_READY_TIMED_OUT: string };
8
+ getStatus: jest.Mock;
9
+ on: jest.Mock;
10
+ _emit: (event: string, metadata?: unknown) => void;
11
+ }
12
+
13
+ function createMockClient(overrides: Partial<{
14
+ isReady: boolean;
15
+ hasTimedout: boolean;
16
+ readyMetadata: { initialCacheLoad?: boolean; lastUpdateTimestamp?: number };
17
+ }> = {}): MockSplitClient {
18
+ const { isReady = false, hasTimedout = false } = overrides;
19
+ const listeners: Record<string, ((...args: unknown[]) => void)[]> = {
20
+ 'init::ready': [],
21
+ 'init::cache-ready': [],
22
+ 'init::timeout': [],
23
+ };
24
+ const mock: MockSplitClient = {
25
+ Event: {
26
+ SDK_READY: 'init::ready',
27
+ SDK_READY_FROM_CACHE: 'init::cache-ready',
28
+ SDK_READY_TIMED_OUT: 'init::timeout',
29
+ },
30
+ getStatus: jest.fn().mockReturnValue({ isReady, hasTimedout }),
31
+ on: jest.fn((event: string, cb: (...args: unknown[]) => void) => {
32
+ if (!listeners[event]) listeners[event] = [];
33
+ listeners[event].push(cb);
34
+ return mock;
35
+ }),
36
+ _emit(event: string, metadata?: unknown) {
37
+ (listeners[event] || []).forEach((cb) => cb(metadata));
38
+ },
39
+ };
40
+ return mock;
41
+ }
42
+
43
+ describe('readiness', () => {
44
+ describe('attachReadyEventHandlers', () => {
45
+ it('emits ProviderEvents.Ready with readyFromCache true when SDK_READY_FROM_CACHE fires', () => {
46
+ const client = createMockClient();
47
+ const events = new OpenFeatureEventEmitter();
48
+ const handler = jest.fn();
49
+ events.addHandler(ProviderEvents.Ready, handler);
50
+
51
+ attachReadyEventHandlers(client as unknown as SplitIO.IClient, events, 'split');
52
+ expect(client.on).toHaveBeenCalledWith('init::cache-ready', expect.any(Function));
53
+ expect(client.on).toHaveBeenCalledWith('init::ready', expect.any(Function));
54
+
55
+ client._emit('init::cache-ready', {
56
+ initialCacheLoad: true,
57
+ lastUpdateTimestamp: 12345,
58
+ });
59
+
60
+ expect(handler).toHaveBeenCalledTimes(1);
61
+ expect(handler.mock.calls[0][0]).toMatchObject({
62
+ providerName: 'split',
63
+ metadata: {
64
+ readyFromCache: true,
65
+ initialCacheLoad: true,
66
+ lastUpdateTimestamp: 12345,
67
+ },
68
+ });
69
+ });
70
+
71
+ it('emits ProviderEvents.Ready with readyFromCache false when SDK_READY fires', () => {
72
+ const client = createMockClient();
73
+ const events = new OpenFeatureEventEmitter();
74
+ const handler = jest.fn();
75
+ events.addHandler(ProviderEvents.Ready, handler);
76
+
77
+ attachReadyEventHandlers(client as unknown as SplitIO.IClient, events);
78
+ client._emit('init::ready', {
79
+ initialCacheLoad: false,
80
+ lastUpdateTimestamp: 99999,
81
+ });
82
+
83
+ expect(handler).toHaveBeenCalledWith(
84
+ expect.objectContaining({
85
+ providerName: PROVIDER_NAME,
86
+ metadata: expect.objectContaining({
87
+ readyFromCache: false,
88
+ initialCacheLoad: false,
89
+ lastUpdateTimestamp: 99999,
90
+ }),
91
+ })
92
+ );
93
+ });
94
+
95
+ it('handles undefined metadata (e.g. consumer/Redis mode)', () => {
96
+ const client = createMockClient();
97
+ const events = new OpenFeatureEventEmitter();
98
+ const handler = jest.fn();
99
+ events.addHandler(ProviderEvents.Ready, handler);
100
+
101
+ attachReadyEventHandlers(client as unknown as SplitIO.IClient, events);
102
+ client._emit('init::ready', undefined);
103
+
104
+ expect(handler).toHaveBeenCalledWith(
105
+ expect.objectContaining({
106
+ providerName: PROVIDER_NAME,
107
+ metadata: expect.objectContaining({
108
+ readyFromCache: false,
109
+ initialCacheLoad: false,
110
+ }),
111
+ })
112
+ );
113
+ });
114
+
115
+ it('emits Ready immediately when client is already ready (e.g. localhost or reused client)', () => {
116
+ const client = createMockClient({ isReady: true });
117
+ const events = new OpenFeatureEventEmitter();
118
+ const handler = jest.fn();
119
+ events.addHandler(ProviderEvents.Ready, handler);
120
+
121
+ attachReadyEventHandlers(client as unknown as SplitIO.IClient, events);
122
+
123
+ expect(handler).toHaveBeenCalledTimes(1);
124
+ expect(handler.mock.calls[0][0]).toMatchObject({
125
+ providerName: PROVIDER_NAME,
126
+ metadata: {
127
+ readyFromCache: false,
128
+ initialCacheLoad: false,
129
+ },
130
+ });
131
+ });
132
+ });
133
+
134
+ describe('waitUntilReady', () => {
135
+ it('resolves immediately when client is already ready', async () => {
136
+ const client = createMockClient({ isReady: true });
137
+ await expect(waitUntilReady(client as unknown as SplitIO.IClient, new OpenFeatureEventEmitter(), PROVIDER_NAME)).resolves.toBeUndefined();
138
+ });
139
+
140
+ it('rejects when client has timed out', async () => {
141
+ const client = createMockClient({ hasTimedout: true });
142
+ await expect(waitUntilReady(client as unknown as SplitIO.IClient, new OpenFeatureEventEmitter(), PROVIDER_NAME)).rejects.toBeUndefined();
143
+ });
144
+
145
+ it('resolves when SDK_READY fires', async () => {
146
+ const client = createMockClient({ isReady: false, hasTimedout: false });
147
+ const promise = waitUntilReady(client as unknown as SplitIO.IClient, new OpenFeatureEventEmitter(), PROVIDER_NAME);
148
+ client._emit('init::ready');
149
+ await expect(promise).resolves.toBeUndefined();
150
+ });
151
+
152
+ it('rejects when SDK_READY_TIMED_OUT fires', async () => {
153
+ const client = createMockClient({ isReady: false, hasTimedout: false });
154
+ const promise = waitUntilReady(client as unknown as SplitIO.IClient, new OpenFeatureEventEmitter(), PROVIDER_NAME);
155
+ client._emit('init::timeout');
156
+ await expect(promise).rejects.toBeUndefined();
157
+ });
158
+ });
159
+ });
@@ -0,0 +1,22 @@
1
+ import { SplitFactory } from '@splitsoftware/splitio';
2
+ import type SplitIO from '@splitsoftware/splitio/types/splitio';
3
+ import type { SplitProviderConstructorOptions, SplitProviderOptions } from './types.js';
4
+
5
+ /**
6
+ * Resolves the Split client from the various supported constructor option shapes.
7
+ * Supports: API key (string), Split SDK/AsyncSDK (factory), or pre-built splitClient.
8
+ */
9
+ export function getSplitClient(
10
+ options: SplitProviderConstructorOptions
11
+ ): SplitIO.IClient | SplitIO.IAsyncClient {
12
+ if (typeof options === 'string') {
13
+ const splitFactory = SplitFactory({ core: { authorizationKey: options } });
14
+ return splitFactory.client();
15
+ }
16
+
17
+ try {
18
+ return (options as SplitIO.ISDK | SplitIO.IAsyncSDK).client();
19
+ } catch {
20
+ return (options as SplitProviderOptions).splitClient;
21
+ }
22
+ }
@@ -0,0 +1,35 @@
1
+ import type { EvaluationContext } from '@openfeature/server-sdk';
2
+ import type { BucketingKeyIssue, Consumer } from './types.js';
3
+ import { DEFAULT_TRAFFIC_TYPE } from './types.js';
4
+
5
+ function readBucketingKey(
6
+ value: unknown
7
+ ): { bucketingKey?: string; bucketingKeyIssue?: BucketingKeyIssue } {
8
+ if (value == null) return {};
9
+ if (typeof value !== 'string') return { bucketingKeyIssue: 'not a string' };
10
+ const bucketingKey = value.trim();
11
+ if (bucketingKey === '') return { bucketingKeyIssue: 'blank' };
12
+ return { bucketingKey };
13
+ }
14
+
15
+ /**
16
+ * Transforms OpenFeature evaluation context into the consumer shape used by the Split API:
17
+ * targeting key, bucketing key (validated, trimmed), traffic type (with default),
18
+ * and remaining attributes. `bucketingKey` is never forwarded as an attribute.
19
+ */
20
+ export function transformContext(
21
+ context: EvaluationContext,
22
+ defaultTrafficType: string = DEFAULT_TRAFFIC_TYPE
23
+ ): Consumer {
24
+ const { targetingKey, bucketingKey, trafficType: ttVal, ...attributes } = context;
25
+ const trafficType =
26
+ ttVal != null && typeof ttVal === 'string' && ttVal.trim() !== ''
27
+ ? ttVal
28
+ : defaultTrafficType;
29
+ return {
30
+ targetingKey,
31
+ ...readBucketingKey(bucketingKey),
32
+ trafficType,
33
+ attributes: JSON.parse(JSON.stringify(attributes)),
34
+ };
35
+ }