@defra/lis-sdk-npm-api-feature-flags 0.1.0-lreg-359.alpha.1

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/README.md ADDED
@@ -0,0 +1,73 @@
1
+ # Defra Livestock API SDK (npm)
2
+
3
+ JavaScript/Node client for the feature flag REST API, retrieving feature flags for a given product and environment. This is the npm counterpart to the [NuGet Feature Flags SDK](../../nuget/api-feature-flags).
4
+
5
+ ## Installation & Usage
6
+
7
+ ```js
8
+ import { FeatureFlagClient } from '@defra/lis-sdk-npm-api-feature-flags'
9
+
10
+ const featureFlagClient = new FeatureFlagClient({
11
+ baseUrl: 'https://feature-flag-url.com',
12
+ apiKey: 'your-api-key',
13
+ productName: 'YourProductName',
14
+ environmentName: 'dev',
15
+ cacheTimeoutSeconds: 1800, // Optional: default is 1800, must be 30 or greater
16
+ correlationIdFactory: () => crypto.randomUUID() // Optional: called once per request. Defaults to a random UUID.
17
+ })
18
+
19
+ // Check a single feature flag
20
+ const flag = await featureFlagClient.getFeatureFlagStatus('MyGroup', 'MyFlag')
21
+
22
+ if (flag.flagEnabled) {
23
+ // Execute new feature logic
24
+ }
25
+
26
+ // Check a whole group of flags
27
+ const group = await featureFlagClient.getFeatureFlagGroupStatus('MyGroup')
28
+
29
+ if (group.groupEnabled) {
30
+ for (const feature of group.features) {
31
+ console.log(`Flag: ${feature.flagName}, Enabled: ${feature.flagEnabled}`)
32
+ }
33
+ }
34
+ ```
35
+
36
+ ### Constructor Options
37
+
38
+ | Property | Type | Description | Required |
39
+ | :--------------------- | :------------- | :---------------------------------------------------- | :------------------------ |
40
+ | `baseUrl` | `string` | The base URL of the Feature Flag API. | Yes |
41
+ | `apiKey` | `string` | The API key for authentication. | Yes |
42
+ | `productName` | `string` | The name of your product. | Yes |
43
+ | `environmentName` | `string` | The environment (e.g. dev, test, ext-test, prod). | Yes |
44
+ | `cacheTimeoutSeconds` | `number` | How long to cache flag values (min 30s). | No (default: 1800) |
45
+ | `correlationIdFactory` | `() => string` | Called once per request to generate a correlation id. | No (default: random UUID) |
46
+
47
+ ### Response Shapes
48
+
49
+ #### FeatureFlagStatus
50
+
51
+ Returned when querying an individual flag, or as an entry in a group's `features` list.
52
+
53
+ - `flagName` (string): The name of the flag.
54
+ - `flagEnabled` (boolean): Whether the flag is enabled.
55
+ - `success` (boolean): Whether the flag could be retrieved successfully.
56
+
57
+ #### FeatureFlagGroupStatus
58
+
59
+ Returned when querying a flag group.
60
+
61
+ - `groupName` (string): The name of the group.
62
+ - `groupEnabled` (boolean): Whether the group itself is enabled.
63
+ - `features` (FeatureFlagStatus[]): The individual feature flag statuses within the group.
64
+ - `success` (boolean): Whether the group could be retrieved successfully.
65
+
66
+ ### Error Handling
67
+
68
+ The SDK may throw the following errors, both exported from the package:
69
+
70
+ - `FeatureFlagParameterError`: Thrown when constructor options or method arguments are invalid, or if `correlationIdFactory` returns an empty value.
71
+ - `FeatureFlagQueryError`: Thrown when there is an error communicating with the Feature Flag API, or it returns a non-2xx response.
72
+
73
+ Consumers are expected to handle logging themselves should an error be thrown, in order to avoid double logging.
package/package.json ADDED
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "@defra/lis-sdk-npm-api-feature-flags",
3
+ "version": "0.1.0-lreg-359.alpha.1",
4
+ "description": "JavaScript/Node client SDK for the Livestock feature flag API.",
5
+ "main": "src/index.js",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/DEFRA/lis-sdk-npm-api-feature-flags.git"
9
+ },
10
+ "exports": {
11
+ ".": "./src/index.js"
12
+ },
13
+ "files": [
14
+ "src"
15
+ ],
16
+ "type": "module",
17
+ "engines": {
18
+ "node": ">=24"
19
+ },
20
+ "scripts": {
21
+ "format": "prettier --write \"src/**/*.js\" \"**/*.{js,cjs,md,json}\"",
22
+ "format:check": "prettier --check \"src/**/*.js\" \"**/*.{js,cjs,md,json}\"",
23
+ "lint": "eslint .",
24
+ "lint:fix": "eslint . --fix",
25
+ "test": "vitest run",
26
+ "test:coverage": "vitest run --coverage --coverage.provider=istanbul --coverage.reporter=text --coverage.reporter=lcov --coverage.include=\"src/**/*.js\"",
27
+ "prepare": "if [ \"$npm_command\" = \"install\" ] && [ -z \"$CI\" ] && command -v husky >/dev/null 2>&1; then husky; fi",
28
+ "security-audit": "audit-ci",
29
+ "git:pre-commit-hook": "npm run security-audit && npm run format:check && npm run lint"
30
+ },
31
+ "author": "Defra DDTS",
32
+ "license": "OGL-UK-3.0",
33
+ "dependencies": {
34
+ "@hapi/wreck": "18.1.2"
35
+ },
36
+ "devDependencies": {
37
+ "@defra/lis-infra-eslint-config": "^0.6.0",
38
+ "@types/node": "^26.2.0",
39
+ "@vitest/coverage-istanbul": "^4.1.10",
40
+ "audit-ci": "^7.1.0",
41
+ "eslint": "^9.0.0",
42
+ "husky": "^9.1.7",
43
+ "prettier": "^3.9.6",
44
+ "vitest": "^4.1.10"
45
+ },
46
+ "peerDependencies": {
47
+ "eslint": "^9.0.0"
48
+ }
49
+ }
package/src/errors.js ADDED
@@ -0,0 +1,17 @@
1
+ /** Thrown when arguments passed to the client (or its options) are invalid. */
2
+ export class FeatureFlagParameterError extends Error {
3
+ /** @param {string} message */
4
+ constructor(message) {
5
+ super(message)
6
+ this.name = 'FeatureFlagParameterError'
7
+ }
8
+ }
9
+
10
+ /** Thrown when the feature flag API request fails or returns an error response. */
11
+ export class FeatureFlagQueryError extends Error {
12
+ /** @param {string} message */
13
+ constructor(message) {
14
+ super(message)
15
+ this.name = 'FeatureFlagQueryError'
16
+ }
17
+ }
@@ -0,0 +1,178 @@
1
+ import { randomUUID } from 'node:crypto'
2
+
3
+ import Wreck from '@hapi/wreck'
4
+
5
+ import { FeatureFlagParameterError, FeatureFlagQueryError } from './errors.js'
6
+ import { addCaching } from './internal/add-caching.js'
7
+ import {
8
+ getValidatedApiKey,
9
+ getValidatedBaseUrl,
10
+ getValidatedCacheTimeoutSeconds,
11
+ getValidatedEnvironmentName,
12
+ getValidatedProductName
13
+ } from './internal/validate-options.js'
14
+ import {
15
+ getValidatedFlagName,
16
+ getValidatedGroupName
17
+ } from './internal/validate-parameters.js'
18
+ import {
19
+ mapFlagStatusResponse,
20
+ mapGroupStatusResponse
21
+ } from './internal/map-response.js'
22
+
23
+ /**
24
+ * @typedef {object} FeatureFlagStatus
25
+ * @property {string} flagName
26
+ * @property {boolean} flagEnabled
27
+ * @property {boolean} success
28
+ */
29
+
30
+ /**
31
+ * @typedef {object} FeatureFlagGroupStatus
32
+ * @property {string} groupName
33
+ * @property {boolean} groupEnabled
34
+ * @property {FeatureFlagStatus[]} features
35
+ * @property {boolean} success
36
+ */
37
+
38
+ const HTTP_STATUS_OK_MIN = 200
39
+ const HTTP_STATUS_OK_MAX = 299
40
+
41
+ export class FeatureFlagClient {
42
+ #apiKey
43
+ #baseUrl
44
+ #productName
45
+ #environmentName
46
+ #correlationIdFactory
47
+ #getGroupStatus
48
+ #getFlagStatus
49
+
50
+ /**
51
+ * @param {object} options
52
+ * @param {string} options.apiKey - API key for authentication.
53
+ * @param {string} options.baseUrl - Base URL of the feature flag API.
54
+ * @param {string} options.productName - Name of the consuming product.
55
+ * @param {string} options.environmentName - Environment (e.g. dev, test, prod).
56
+ * @param {number} [options.cacheTimeoutSeconds] - How long to cache flag values, minimum 30. Defaults to 1800.
57
+ * @param {() => string} [options.correlationIdFactory] - Generates a correlation id per request. Defaults to a random UUID.
58
+ */
59
+ constructor({
60
+ apiKey,
61
+ baseUrl,
62
+ productName,
63
+ environmentName,
64
+ cacheTimeoutSeconds,
65
+ correlationIdFactory = randomUUID
66
+ }) {
67
+ this.#apiKey = getValidatedApiKey(apiKey)
68
+ this.#baseUrl = getValidatedBaseUrl(baseUrl)
69
+ this.#productName = getValidatedProductName(productName)
70
+ this.#environmentName = getValidatedEnvironmentName(environmentName)
71
+ this.#correlationIdFactory = correlationIdFactory
72
+
73
+ const validCacheTimeoutSeconds =
74
+ getValidatedCacheTimeoutSeconds(cacheTimeoutSeconds)
75
+ this.#getGroupStatus = addCaching(
76
+ this.#fetchGroupStatus.bind(this),
77
+ validCacheTimeoutSeconds
78
+ )
79
+ this.#getFlagStatus = addCaching(
80
+ this.#fetchFlagStatus.bind(this),
81
+ validCacheTimeoutSeconds
82
+ )
83
+ }
84
+
85
+ /**
86
+ * Gets the status of all feature flags in a group.
87
+ *
88
+ * @param {string} groupName
89
+ * @returns {Promise<FeatureFlagGroupStatus>}
90
+ */
91
+ async getFeatureFlagGroupStatus(groupName) {
92
+ groupName = getValidatedGroupName(groupName)
93
+
94
+ return this.#getGroupStatus(groupName)
95
+ }
96
+
97
+ /**
98
+ * Gets the status of a specific feature flag.
99
+ *
100
+ * @param {string} groupName
101
+ * @param {string} flagName
102
+ * @returns {Promise<FeatureFlagStatus>}
103
+ */
104
+ async getFeatureFlagStatus(groupName, flagName) {
105
+ groupName = getValidatedGroupName(groupName)
106
+ flagName = getValidatedFlagName(flagName)
107
+
108
+ return this.#getFlagStatus(groupName, flagName)
109
+ }
110
+
111
+ #getHeaders() {
112
+ const correlationId = this.#correlationIdFactory()
113
+
114
+ if (!correlationId) {
115
+ throw new FeatureFlagParameterError(
116
+ 'FeatureFlag correlationId cannot be empty'
117
+ )
118
+ }
119
+
120
+ return {
121
+ 'x-api-key': this.#apiKey,
122
+ 'x-cdp-request-id': correlationId,
123
+ 'product-name': this.#productName,
124
+ 'environment-name': this.#environmentName
125
+ }
126
+ }
127
+
128
+ async #fetchGroupStatus(groupName) {
129
+ const result = await this.#get(
130
+ `evaluate/${encodeURIComponent(groupName)}`,
131
+ `Failed to get feature flag group status for group '${groupName}'`
132
+ )
133
+ return mapGroupStatusResponse(result)
134
+ }
135
+
136
+ async #fetchFlagStatus(groupName, flagName) {
137
+ const result = await this.#get(
138
+ `evaluate/${encodeURIComponent(groupName)}/${encodeURIComponent(flagName)}`,
139
+ `Failed to get feature flag status for flag '${flagName}' within group '${groupName}'`
140
+ )
141
+ return mapFlagStatusResponse(result)
142
+ }
143
+
144
+ async #get(relativeUrl, errorPrefix) {
145
+ let result
146
+
147
+ try {
148
+ result = await Wreck.get(relativeUrl, {
149
+ baseUrl: this.#baseUrl,
150
+ json: true,
151
+ headers: this.#getHeaders()
152
+ })
153
+ } catch (err) {
154
+ throw this.#wrapError(err, errorPrefix)
155
+ }
156
+
157
+ if (
158
+ result.res.statusCode < HTTP_STATUS_OK_MIN ||
159
+ result.res.statusCode > HTTP_STATUS_OK_MAX
160
+ ) {
161
+ throw new FeatureFlagQueryError(
162
+ `${errorPrefix}: 'Request failed with status ${result.res.statusCode}'`
163
+ )
164
+ }
165
+
166
+ return result.payload
167
+ }
168
+
169
+ #wrapError(err, errorPrefix) {
170
+ if (
171
+ err instanceof FeatureFlagParameterError ||
172
+ err instanceof FeatureFlagQueryError
173
+ ) {
174
+ return err
175
+ }
176
+ return new FeatureFlagQueryError(`${errorPrefix}: '${err.message}'`)
177
+ }
178
+ }
@@ -0,0 +1,228 @@
1
+ import { afterEach, describe, expect, test, vi } from 'vitest'
2
+
3
+ import Wreck from '@hapi/wreck'
4
+ import { FeatureFlagClient } from './feature-flag-client.js'
5
+ import { FeatureFlagParameterError, FeatureFlagQueryError } from './errors.js'
6
+
7
+ const mocks = {
8
+ get: vi.spyOn(Wreck, 'get')
9
+ }
10
+
11
+ function validOptions(overrides = {}) {
12
+ return {
13
+ apiKey: 'api-key',
14
+ baseUrl: 'https://feature-flags.example.com',
15
+ productName: 'my-product',
16
+ environmentName: 'dev',
17
+ ...overrides
18
+ }
19
+ }
20
+
21
+ describe('FeatureFlagClient', () => {
22
+ afterEach(() => {
23
+ vi.clearAllMocks()
24
+ })
25
+
26
+ test('constructor throws a FeatureFlagParameterError for invalid options', () => {
27
+ // Arrange
28
+ const options = validOptions({ apiKey: '' })
29
+
30
+ // Act
31
+ let error
32
+ try {
33
+ // eslint-disable-next-line no-new
34
+ new FeatureFlagClient(options)
35
+ } catch (e) {
36
+ error = e
37
+ }
38
+
39
+ // Assert
40
+ expect(error).toBeInstanceOf(FeatureFlagParameterError)
41
+ })
42
+
43
+ test('getFeatureFlagGroupStatus requests the group and forwards the required headers', async () => {
44
+ // Arrange
45
+ const correlationIdFactory = vi.fn().mockReturnValue('correlation-1')
46
+ const client = new FeatureFlagClient(validOptions({ correlationIdFactory }))
47
+ mocks.get.mockResolvedValueOnce({
48
+ res: { statusCode: 200 },
49
+ payload: {
50
+ group_name: 'my-group',
51
+ group_enabled: true,
52
+ success: true,
53
+ features: [{ flag_name: 'flag-a', flag_enabled: true }]
54
+ }
55
+ })
56
+
57
+ // Act
58
+ const result = await client.getFeatureFlagGroupStatus('my-group')
59
+
60
+ // Assert
61
+ expect(mocks.get).toHaveBeenCalledTimes(1)
62
+ const [path, options] = mocks.get.mock.calls[0]
63
+ expect(path).toBe('evaluate/my-group')
64
+ expect(options.baseUrl).toBe('https://feature-flags.example.com')
65
+ expect(options.headers).toEqual({
66
+ 'x-api-key': 'api-key',
67
+ 'x-cdp-request-id': 'correlation-1',
68
+ 'product-name': 'my-product',
69
+ 'environment-name': 'dev'
70
+ })
71
+ expect(result).toEqual({
72
+ groupName: 'my-group',
73
+ groupEnabled: true,
74
+ success: true,
75
+ features: [{ flagName: 'flag-a', flagEnabled: true, success: true }]
76
+ })
77
+ })
78
+
79
+ test('getFeatureFlagGroupStatus does not request again while the cached value is fresh', async () => {
80
+ // Arrange
81
+ const client = new FeatureFlagClient(validOptions())
82
+ mocks.get.mockResolvedValueOnce({
83
+ res: { statusCode: 200 },
84
+ payload: {
85
+ group_name: 'my-group',
86
+ group_enabled: true,
87
+ success: true,
88
+ features: []
89
+ }
90
+ })
91
+ await client.getFeatureFlagGroupStatus('my-group')
92
+
93
+ // Act
94
+ await client.getFeatureFlagGroupStatus('my-group')
95
+
96
+ // Assert
97
+ expect(mocks.get).toHaveBeenCalledTimes(1)
98
+ })
99
+
100
+ test('getFeatureFlagGroupStatus throws a FeatureFlagParameterError for an invalid group name', async () => {
101
+ // Arrange
102
+ const client = new FeatureFlagClient(validOptions())
103
+ let error
104
+
105
+ // Act
106
+ try {
107
+ await client.getFeatureFlagGroupStatus('')
108
+ } catch (e) {
109
+ error = e
110
+ }
111
+
112
+ // Assert
113
+ expect(error).toBeInstanceOf(FeatureFlagParameterError)
114
+ })
115
+
116
+ test('getFeatureFlagGroupStatus wraps a non-2xx response in a FeatureFlagQueryError', async () => {
117
+ // Arrange
118
+ const client = new FeatureFlagClient(validOptions())
119
+ mocks.get.mockResolvedValueOnce({
120
+ res: { statusCode: 500 },
121
+ payload: null
122
+ })
123
+ let error
124
+
125
+ // Act
126
+ try {
127
+ await client.getFeatureFlagGroupStatus('my-group')
128
+ } catch (e) {
129
+ error = e
130
+ }
131
+
132
+ // Assert
133
+ expect(error).toBeInstanceOf(FeatureFlagQueryError)
134
+ expect(error?.message).toContain(
135
+ "Failed to get feature flag group status for group 'my-group'"
136
+ )
137
+ })
138
+
139
+ test('getFeatureFlagGroupStatus wraps a Wreck failure in a FeatureFlagQueryError', async () => {
140
+ // Arrange
141
+ const client = new FeatureFlagClient(validOptions())
142
+ mocks.get.mockRejectedValueOnce(new Error('network down'))
143
+ let error
144
+
145
+ // Act
146
+ try {
147
+ await client.getFeatureFlagGroupStatus('my-group')
148
+ } catch (e) {
149
+ error = e
150
+ }
151
+
152
+ // Assert
153
+ expect(error).toBeInstanceOf(FeatureFlagQueryError)
154
+ expect(error?.message).toContain('network down')
155
+ })
156
+
157
+ test('getFeatureFlagGroupStatus throws a FeatureFlagParameterError when the correlation id is empty', async () => {
158
+ // Arrange
159
+ const client = new FeatureFlagClient(
160
+ validOptions({ correlationIdFactory: () => '' })
161
+ )
162
+ let error
163
+
164
+ // Act
165
+ try {
166
+ await client.getFeatureFlagGroupStatus('my-group')
167
+ } catch (e) {
168
+ error = e
169
+ }
170
+
171
+ // Assert
172
+ expect(error).toBeInstanceOf(FeatureFlagParameterError)
173
+ expect(mocks.get).not.toHaveBeenCalled()
174
+ })
175
+
176
+ test('getFeatureFlagStatus requests the flag and maps the response', async () => {
177
+ // Arrange
178
+ const client = new FeatureFlagClient(validOptions())
179
+ mocks.get.mockResolvedValueOnce({
180
+ res: { statusCode: 200 },
181
+ payload: { flag_name: 'my-flag', flag_enabled: true, success: true }
182
+ })
183
+
184
+ // Act
185
+ const result = await client.getFeatureFlagStatus('my-group', 'my-flag')
186
+
187
+ // Assert
188
+ const [path] = mocks.get.mock.calls[0]
189
+ expect(path).toBe('evaluate/my-group/my-flag')
190
+ expect(result).toEqual({
191
+ flagName: 'my-flag',
192
+ flagEnabled: true,
193
+ success: true
194
+ })
195
+ })
196
+
197
+ test('getFeatureFlagStatus throws a FeatureFlagParameterError for an invalid flag name', async () => {
198
+ // Arrange
199
+ const client = new FeatureFlagClient(validOptions())
200
+ let error
201
+
202
+ // Act
203
+ try {
204
+ await client.getFeatureFlagStatus('my-group', '')
205
+ } catch (e) {
206
+ error = e
207
+ }
208
+
209
+ // Assert
210
+ expect(error).toBeInstanceOf(FeatureFlagParameterError)
211
+ })
212
+
213
+ test('getFeatureFlagStatus caches per group/flag combination independently', async () => {
214
+ // Arrange
215
+ const client = new FeatureFlagClient(validOptions())
216
+ mocks.get.mockResolvedValue({
217
+ res: { statusCode: 200 },
218
+ payload: { flag_name: 'my-flag', flag_enabled: true, success: true }
219
+ })
220
+ await client.getFeatureFlagStatus('my-group', 'flag-a')
221
+
222
+ // Act
223
+ await client.getFeatureFlagStatus('my-group', 'flag-b')
224
+
225
+ // Assert
226
+ expect(mocks.get).toHaveBeenCalledTimes(2)
227
+ })
228
+ })
package/src/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { FeatureFlagClient } from './feature-flag-client.js'
2
+ export { FeatureFlagParameterError, FeatureFlagQueryError } from './errors.js'
@@ -0,0 +1,40 @@
1
+ const MS_PER_SECOND = 1000
2
+
3
+ /**
4
+ * Wraps `fn`, caching each call's result for `ttlSeconds` keyed on its
5
+ * arguments, so repeat calls with the same arguments within the ttl are
6
+ * served from cache instead of calling `fn` again. Nothing is cached if
7
+ * `fn` throws. The in-flight call is cached too (not just its resolved
8
+ * value), so concurrent calls with the same arguments share a single call
9
+ * to `fn` rather than each triggering one.
10
+ *
11
+ * @template {(...args: *[]) => Promise<*>} T
12
+ * @param {T} fn
13
+ * @param {number} ttlSeconds
14
+ * @returns {T}
15
+ */
16
+ export function addCaching(fn, ttlSeconds) {
17
+ const store = new Map()
18
+
19
+ return async (...args) => {
20
+ const key = JSON.stringify(args)
21
+ const cached = store.get(key)
22
+ const now = Date.now()
23
+
24
+ if (cached && cached.expiresAt > now) {
25
+ return cached.value
26
+ }
27
+
28
+ const entry = { expiresAt: now + ttlSeconds * MS_PER_SECOND }
29
+ entry.value = fn(...args).catch((err) => {
30
+ if (store.get(key) === entry) {
31
+ store.delete(key)
32
+ }
33
+ throw err
34
+ })
35
+
36
+ store.set(key, entry)
37
+
38
+ return entry.value
39
+ }
40
+ }
@@ -0,0 +1,111 @@
1
+ import { afterEach, describe, expect, test, vi } from 'vitest'
2
+
3
+ import { addCaching } from './add-caching.js'
4
+
5
+ describe('addCaching()', () => {
6
+ afterEach(() => {
7
+ vi.useRealTimers()
8
+ })
9
+
10
+ test('it calls the wrapped function and returns its result on a cache miss', async () => {
11
+ // Arrange
12
+ const fn = vi.fn().mockResolvedValue('value')
13
+ const cachedFn = addCaching(fn, 30)
14
+
15
+ // Act
16
+ const result = await cachedFn('a')
17
+
18
+ // Assert
19
+ expect(result).toBe('value')
20
+ expect(fn).toHaveBeenCalledTimes(1)
21
+ expect(fn).toHaveBeenCalledWith('a')
22
+ })
23
+
24
+ test('it returns the cached value without calling the function again for the same arguments', async () => {
25
+ // Arrange
26
+ const fn = vi.fn().mockResolvedValue('value')
27
+ const cachedFn = addCaching(fn, 30)
28
+ await cachedFn('a')
29
+
30
+ // Act
31
+ const result = await cachedFn('a')
32
+
33
+ // Assert
34
+ expect(result).toBe('value')
35
+ expect(fn).toHaveBeenCalledTimes(1)
36
+ })
37
+
38
+ test('it calls the function again once the ttl has expired', async () => {
39
+ // Arrange
40
+ vi.useFakeTimers()
41
+ const fn = vi.fn().mockResolvedValue('value')
42
+ const cachedFn = addCaching(fn, 30)
43
+ await cachedFn('a')
44
+
45
+ // Act
46
+ vi.advanceTimersByTime(30_001)
47
+ await cachedFn('a')
48
+
49
+ // Assert
50
+ expect(fn).toHaveBeenCalledTimes(2)
51
+ })
52
+
53
+ test('it does not cache when the function throws', async () => {
54
+ // Arrange
55
+ const failingFn = vi.fn().mockRejectedValue(new Error('boom'))
56
+ const cachedFn = addCaching(failingFn, 30)
57
+ let error
58
+
59
+ // Act
60
+ try {
61
+ await cachedFn('a')
62
+ } catch (e) {
63
+ error = e
64
+ }
65
+ failingFn.mockResolvedValue('value')
66
+ const result = await cachedFn('a')
67
+
68
+ // Assert
69
+ expect(error?.message).toBe('boom')
70
+ expect(result).toBe('value')
71
+ expect(failingFn).toHaveBeenCalledTimes(2)
72
+ })
73
+
74
+ test('it deduplicates concurrent calls for the same arguments, calling the function only once', async () => {
75
+ // Arrange
76
+ let resolveFn
77
+ const fn = vi.fn(
78
+ () =>
79
+ new Promise((resolve) => {
80
+ resolveFn = resolve
81
+ })
82
+ )
83
+ const cachedFn = addCaching(fn, 30)
84
+
85
+ // Act
86
+ const promiseA = cachedFn('a')
87
+ const promiseB = cachedFn('a')
88
+ resolveFn('value')
89
+ const [resultA, resultB] = await Promise.all([promiseA, promiseB])
90
+
91
+ // Assert
92
+ expect(resultA).toBe('value')
93
+ expect(resultB).toBe('value')
94
+ expect(fn).toHaveBeenCalledTimes(1)
95
+ })
96
+
97
+ test('it caches different arguments independently', async () => {
98
+ // Arrange
99
+ const fn = vi.fn((value) => Promise.resolve(value))
100
+ const cachedFn = addCaching(fn, 30)
101
+
102
+ // Act
103
+ const resultA = await cachedFn('a')
104
+ const resultB = await cachedFn('b')
105
+
106
+ // Assert
107
+ expect(resultA).toBe('a')
108
+ expect(resultB).toBe('b')
109
+ expect(fn).toHaveBeenCalledTimes(2)
110
+ })
111
+ })
@@ -0,0 +1,30 @@
1
+ /** @import { FeatureFlagGroupStatus, FeatureFlagStatus } from '../feature-flag-client.js' */
2
+
3
+ /**
4
+ * @param {{group_name: string, group_enabled: boolean, success: boolean, features?: {flag_name: string, flag_enabled: boolean}[]}} response
5
+ * @returns {FeatureFlagGroupStatus}
6
+ */
7
+ export function mapGroupStatusResponse(response) {
8
+ return {
9
+ groupName: response.group_name,
10
+ groupEnabled: response.group_enabled,
11
+ success: response.success,
12
+ features: (response.features ?? []).map((feature) => ({
13
+ flagName: feature.flag_name,
14
+ flagEnabled: feature.flag_enabled,
15
+ success: true
16
+ }))
17
+ }
18
+ }
19
+
20
+ /**
21
+ * @param {{flag_name: string, flag_enabled: boolean, success: boolean}} response
22
+ * @returns {FeatureFlagStatus}
23
+ */
24
+ export function mapFlagStatusResponse(response) {
25
+ return {
26
+ flagName: response.flag_name,
27
+ flagEnabled: response.flag_enabled,
28
+ success: response.success
29
+ }
30
+ }
@@ -0,0 +1,65 @@
1
+ import { describe, expect, test } from 'vitest'
2
+
3
+ import {
4
+ mapFlagStatusResponse,
5
+ mapGroupStatusResponse
6
+ } from './map-response.js'
7
+
8
+ describe('map-response', () => {
9
+ test('mapGroupStatusResponse maps snake_case fields and forces success on each feature', () => {
10
+ // Arrange
11
+ const response = {
12
+ group_name: 'my-group',
13
+ group_enabled: true,
14
+ success: true,
15
+ features: [
16
+ { flag_name: 'flag-a', flag_enabled: true },
17
+ { flag_name: 'flag-b', flag_enabled: false }
18
+ ]
19
+ }
20
+
21
+ // Act
22
+ const result = mapGroupStatusResponse(response)
23
+
24
+ // Assert
25
+ expect(result).toEqual({
26
+ groupName: 'my-group',
27
+ groupEnabled: true,
28
+ success: true,
29
+ features: [
30
+ { flagName: 'flag-a', flagEnabled: true, success: true },
31
+ { flagName: 'flag-b', flagEnabled: false, success: true }
32
+ ]
33
+ })
34
+ })
35
+
36
+ test('mapGroupStatusResponse defaults features to an empty array when absent', () => {
37
+ // Arrange
38
+ const response = {
39
+ group_name: 'my-group',
40
+ group_enabled: false,
41
+ success: true
42
+ }
43
+
44
+ // Act
45
+ const result = mapGroupStatusResponse(response)
46
+
47
+ // Assert
48
+ expect(result.features).toEqual([])
49
+ })
50
+
51
+ test('mapFlagStatusResponse maps snake_case fields', () => {
52
+ // Arrange
53
+ const response = { flag_name: 'my-flag', flag_enabled: true, success: true }
54
+
55
+ // Act
56
+ const result = mapFlagStatusResponse(response)
57
+
58
+ // Assert
59
+ expect(result).toEqual({
60
+ flagName: 'my-flag',
61
+ flagEnabled: true,
62
+ success: true
63
+ })
64
+ })
65
+ })
@@ -0,0 +1,121 @@
1
+ import { FeatureFlagParameterError } from '../errors.js'
2
+
3
+ const DEFAULT_CACHE_TIMEOUT_SECONDS = 1800
4
+ const MIN_CACHE_TIMEOUT_SECONDS = 30
5
+ const MAX_CACHE_TIMEOUT_SECONDS = 86400
6
+ const MAX_API_KEY_LENGTH = 100
7
+ const MAX_BASE_URL_LENGTH = 2000
8
+ const MAX_ENVIRONMENT_NAME_LENGTH = 10
9
+ const MAX_PRODUCT_NAME_LENGTH = 50
10
+
11
+ function isAbsoluteUrl(value) {
12
+ try {
13
+ // eslint-disable-next-line no-new
14
+ new URL(value)
15
+ return true
16
+ } catch {
17
+ return false
18
+ }
19
+ }
20
+
21
+ /**
22
+ * @param {string} apiKey
23
+ * @returns {string} apiKey, if valid.
24
+ */
25
+ export function getValidatedApiKey(apiKey) {
26
+ if (!apiKey?.trim()) {
27
+ throw new FeatureFlagParameterError('FeatureFlag apiKey is required')
28
+ }
29
+
30
+ if (apiKey.length > MAX_API_KEY_LENGTH) {
31
+ throw new FeatureFlagParameterError(
32
+ `FeatureFlag apiKey cannot exceed ${MAX_API_KEY_LENGTH} characters`
33
+ )
34
+ }
35
+
36
+ return apiKey
37
+ }
38
+
39
+ /**
40
+ * @param {string} baseUrl
41
+ * @returns {string} baseUrl, if valid.
42
+ */
43
+ export function getValidatedBaseUrl(baseUrl) {
44
+ if (!baseUrl?.trim()) {
45
+ throw new FeatureFlagParameterError('FeatureFlag baseUrl is required')
46
+ }
47
+
48
+ if (baseUrl.length > MAX_BASE_URL_LENGTH) {
49
+ throw new FeatureFlagParameterError(
50
+ `FeatureFlag baseUrl cannot exceed ${MAX_BASE_URL_LENGTH} characters`
51
+ )
52
+ }
53
+
54
+ if (!isAbsoluteUrl(baseUrl)) {
55
+ throw new FeatureFlagParameterError(
56
+ 'FeatureFlag baseUrl is not a valid URL'
57
+ )
58
+ }
59
+
60
+ return baseUrl
61
+ }
62
+
63
+ /**
64
+ * @param {string} environmentName
65
+ * @returns {string} environmentName, if valid.
66
+ */
67
+ export function getValidatedEnvironmentName(environmentName) {
68
+ if (!environmentName?.trim()) {
69
+ throw new FeatureFlagParameterError(
70
+ 'FeatureFlag environmentName is required'
71
+ )
72
+ }
73
+
74
+ if (environmentName.length > MAX_ENVIRONMENT_NAME_LENGTH) {
75
+ throw new FeatureFlagParameterError(
76
+ `FeatureFlag environmentName cannot exceed ${MAX_ENVIRONMENT_NAME_LENGTH} characters`
77
+ )
78
+ }
79
+
80
+ return environmentName
81
+ }
82
+
83
+ /**
84
+ * @param {string} productName
85
+ * @returns {string} productName, if valid.
86
+ */
87
+ export function getValidatedProductName(productName) {
88
+ if (!productName?.trim()) {
89
+ throw new FeatureFlagParameterError('FeatureFlag productName is required')
90
+ }
91
+
92
+ if (productName.length > MAX_PRODUCT_NAME_LENGTH) {
93
+ throw new FeatureFlagParameterError(
94
+ `FeatureFlag productName cannot exceed ${MAX_PRODUCT_NAME_LENGTH} characters`
95
+ )
96
+ }
97
+
98
+ return productName
99
+ }
100
+
101
+ /**
102
+ * @param {number} [cacheTimeoutSeconds] - Defaults to 1800.
103
+ * @returns {number} cacheTimeoutSeconds, if valid.
104
+ */
105
+ export function getValidatedCacheTimeoutSeconds(
106
+ cacheTimeoutSeconds = DEFAULT_CACHE_TIMEOUT_SECONDS
107
+ ) {
108
+ if (cacheTimeoutSeconds < MIN_CACHE_TIMEOUT_SECONDS) {
109
+ throw new FeatureFlagParameterError(
110
+ `FeatureFlag cacheTimeoutSeconds must be ${MIN_CACHE_TIMEOUT_SECONDS} or greater`
111
+ )
112
+ }
113
+
114
+ if (cacheTimeoutSeconds > MAX_CACHE_TIMEOUT_SECONDS) {
115
+ throw new FeatureFlagParameterError(
116
+ `FeatureFlag cacheTimeoutSeconds cannot exceed ${MAX_CACHE_TIMEOUT_SECONDS}`
117
+ )
118
+ }
119
+
120
+ return cacheTimeoutSeconds
121
+ }
@@ -0,0 +1,270 @@
1
+ import { describe, expect, test } from 'vitest'
2
+
3
+ import {
4
+ getValidatedApiKey,
5
+ getValidatedBaseUrl,
6
+ getValidatedCacheTimeoutSeconds,
7
+ getValidatedEnvironmentName,
8
+ getValidatedProductName
9
+ } from './validate-options.js'
10
+
11
+ describe('getValidatedApiKey()', () => {
12
+ test('it returns the apiKey when it is valid', () => {
13
+ // Arrange
14
+ const apiKey = 'api-key'
15
+
16
+ // Act
17
+ const result = getValidatedApiKey(apiKey)
18
+
19
+ // Assert
20
+ expect(result).toBe(apiKey)
21
+ })
22
+
23
+ test('it throws when apiKey is missing', () => {
24
+ // Arrange
25
+ const apiKey = ''
26
+
27
+ // Act
28
+ let error
29
+ try {
30
+ getValidatedApiKey(apiKey)
31
+ } catch (e) {
32
+ error = e
33
+ }
34
+
35
+ // Assert
36
+ expect(error?.message).toBe('FeatureFlag apiKey is required')
37
+ })
38
+
39
+ test('it throws when apiKey exceeds 100 characters', () => {
40
+ // Arrange
41
+ const apiKey = 'a'.repeat(101)
42
+
43
+ // Act
44
+ let error
45
+ try {
46
+ getValidatedApiKey(apiKey)
47
+ } catch (e) {
48
+ error = e
49
+ }
50
+
51
+ // Assert
52
+ expect(error?.message).toBe(
53
+ 'FeatureFlag apiKey cannot exceed 100 characters'
54
+ )
55
+ })
56
+ })
57
+
58
+ describe('getValidatedBaseUrl()', () => {
59
+ test('it returns the baseUrl when it is valid', () => {
60
+ // Arrange
61
+ const baseUrl = 'https://feature-flags.example.com'
62
+
63
+ // Act
64
+ const result = getValidatedBaseUrl(baseUrl)
65
+
66
+ // Assert
67
+ expect(result).toBe(baseUrl)
68
+ })
69
+
70
+ test('it throws when baseUrl is missing', () => {
71
+ // Arrange
72
+ const baseUrl = ''
73
+
74
+ // Act
75
+ let error
76
+ try {
77
+ getValidatedBaseUrl(baseUrl)
78
+ } catch (e) {
79
+ error = e
80
+ }
81
+
82
+ // Assert
83
+ expect(error?.message).toBe('FeatureFlag baseUrl is required')
84
+ })
85
+
86
+ test('it throws when baseUrl is not a valid absolute URL', () => {
87
+ // Arrange
88
+ const baseUrl = 'not-a-url'
89
+
90
+ // Act
91
+ let error
92
+ try {
93
+ getValidatedBaseUrl(baseUrl)
94
+ } catch (e) {
95
+ error = e
96
+ }
97
+
98
+ // Assert
99
+ expect(error?.message).toBe('FeatureFlag baseUrl is not a valid URL')
100
+ })
101
+
102
+ test('it throws when baseUrl exceeds 2000 characters', () => {
103
+ // Arrange
104
+ const baseUrl = `https://feature-flags.example.com/${'a'.repeat(2000)}`
105
+
106
+ // Act
107
+ let error
108
+ try {
109
+ getValidatedBaseUrl(baseUrl)
110
+ } catch (e) {
111
+ error = e
112
+ }
113
+
114
+ // Assert
115
+ expect(error?.message).toBe(
116
+ 'FeatureFlag baseUrl cannot exceed 2000 characters'
117
+ )
118
+ })
119
+ })
120
+
121
+ describe('getValidatedEnvironmentName()', () => {
122
+ test('it returns the environmentName when it is valid', () => {
123
+ // Arrange
124
+ const environmentName = 'dev'
125
+
126
+ // Act
127
+ const result = getValidatedEnvironmentName(environmentName)
128
+
129
+ // Assert
130
+ expect(result).toBe(environmentName)
131
+ })
132
+
133
+ test('it throws when environmentName is missing', () => {
134
+ // Arrange
135
+ const environmentName = ''
136
+
137
+ // Act
138
+ let error
139
+ try {
140
+ getValidatedEnvironmentName(environmentName)
141
+ } catch (e) {
142
+ error = e
143
+ }
144
+
145
+ // Assert
146
+ expect(error?.message).toBe('FeatureFlag environmentName is required')
147
+ })
148
+
149
+ test('it throws when environmentName exceeds 10 characters', () => {
150
+ // Arrange
151
+ const environmentName = 'a'.repeat(11)
152
+
153
+ // Act
154
+ let error
155
+ try {
156
+ getValidatedEnvironmentName(environmentName)
157
+ } catch (e) {
158
+ error = e
159
+ }
160
+
161
+ // Assert
162
+ expect(error?.message).toBe(
163
+ 'FeatureFlag environmentName cannot exceed 10 characters'
164
+ )
165
+ })
166
+ })
167
+
168
+ describe('getValidatedProductName()', () => {
169
+ test('it returns the productName when it is valid', () => {
170
+ // Arrange
171
+ const productName = 'my-product'
172
+
173
+ // Act
174
+ const result = getValidatedProductName(productName)
175
+
176
+ // Assert
177
+ expect(result).toBe(productName)
178
+ })
179
+
180
+ test('it throws when productName is missing', () => {
181
+ // Arrange
182
+ const productName = ''
183
+
184
+ // Act
185
+ let error
186
+ try {
187
+ getValidatedProductName(productName)
188
+ } catch (e) {
189
+ error = e
190
+ }
191
+
192
+ // Assert
193
+ expect(error?.message).toBe('FeatureFlag productName is required')
194
+ })
195
+
196
+ test('it throws when productName exceeds 50 characters', () => {
197
+ // Arrange
198
+ const productName = 'a'.repeat(51)
199
+
200
+ // Act
201
+ let error
202
+ try {
203
+ getValidatedProductName(productName)
204
+ } catch (e) {
205
+ error = e
206
+ }
207
+
208
+ // Assert
209
+ expect(error?.message).toBe(
210
+ 'FeatureFlag productName cannot exceed 50 characters'
211
+ )
212
+ })
213
+ })
214
+
215
+ describe('getValidatedCacheTimeoutSeconds()', () => {
216
+ test('it returns cacheTimeoutSeconds when it is valid', () => {
217
+ // Arrange
218
+ const cacheTimeoutSeconds = 3600
219
+
220
+ // Act
221
+ const result = getValidatedCacheTimeoutSeconds(cacheTimeoutSeconds)
222
+
223
+ // Assert
224
+ expect(result).toBe(cacheTimeoutSeconds)
225
+ })
226
+
227
+ test('it defaults to 1800 when not provided', () => {
228
+ // Act
229
+ const result = getValidatedCacheTimeoutSeconds(undefined)
230
+
231
+ // Assert
232
+ expect(result).toBe(1800)
233
+ })
234
+
235
+ test('it throws when cacheTimeoutSeconds is below 30', () => {
236
+ // Arrange
237
+ const cacheTimeoutSeconds = 29
238
+
239
+ // Act
240
+ let error
241
+ try {
242
+ getValidatedCacheTimeoutSeconds(cacheTimeoutSeconds)
243
+ } catch (e) {
244
+ error = e
245
+ }
246
+
247
+ // Assert
248
+ expect(error?.message).toBe(
249
+ 'FeatureFlag cacheTimeoutSeconds must be 30 or greater'
250
+ )
251
+ })
252
+
253
+ test('it throws when cacheTimeoutSeconds exceeds 86400', () => {
254
+ // Arrange
255
+ const cacheTimeoutSeconds = 86401
256
+
257
+ // Act
258
+ let error
259
+ try {
260
+ getValidatedCacheTimeoutSeconds(cacheTimeoutSeconds)
261
+ } catch (e) {
262
+ error = e
263
+ }
264
+
265
+ // Assert
266
+ expect(error?.message).toBe(
267
+ 'FeatureFlag cacheTimeoutSeconds cannot exceed 86400'
268
+ )
269
+ })
270
+ })
@@ -0,0 +1,33 @@
1
+ import { FeatureFlagParameterError } from '../errors.js'
2
+
3
+ const MAX_GROUP_NAME_LENGTH = 100
4
+
5
+ /**
6
+ * @param {string} groupName
7
+ * @returns {string} groupName, if valid.
8
+ */
9
+ export function getValidatedGroupName(groupName) {
10
+ if (!groupName?.trim()) {
11
+ throw new FeatureFlagParameterError('FeatureFlag groupName is required')
12
+ }
13
+
14
+ if (groupName.length > MAX_GROUP_NAME_LENGTH) {
15
+ throw new FeatureFlagParameterError(
16
+ `FeatureFlag groupName cannot exceed ${MAX_GROUP_NAME_LENGTH} characters`
17
+ )
18
+ }
19
+
20
+ return groupName
21
+ }
22
+
23
+ /**
24
+ * @param {string} flagName
25
+ * @returns {string} flagName, if valid.
26
+ */
27
+ export function getValidatedFlagName(flagName) {
28
+ if (!flagName?.trim()) {
29
+ throw new FeatureFlagParameterError('FeatureFlag flagName is required')
30
+ }
31
+
32
+ return flagName
33
+ }
@@ -0,0 +1,80 @@
1
+ import { describe, expect, test } from 'vitest'
2
+
3
+ import {
4
+ getValidatedFlagName,
5
+ getValidatedGroupName
6
+ } from './validate-parameters.js'
7
+
8
+ describe('validate-parameters', () => {
9
+ test('getValidatedGroupName returns the group name when it is valid', () => {
10
+ // Arrange
11
+ const groupName = 'my-group'
12
+
13
+ // Act
14
+ const result = getValidatedGroupName(groupName)
15
+
16
+ // Assert
17
+ expect(result).toBe(groupName)
18
+ })
19
+
20
+ test('getValidatedGroupName throws when the group name is blank', () => {
21
+ // Arrange
22
+ const groupName = ' '
23
+
24
+ // Act
25
+ let error
26
+ try {
27
+ getValidatedGroupName(groupName)
28
+ } catch (e) {
29
+ error = e
30
+ }
31
+
32
+ // Assert
33
+ expect(error?.message).toBe('FeatureFlag groupName is required')
34
+ })
35
+
36
+ test('getValidatedGroupName throws when the group name exceeds 100 characters', () => {
37
+ // Arrange
38
+ const groupName = 'a'.repeat(101)
39
+
40
+ // Act
41
+ let error
42
+ try {
43
+ getValidatedGroupName(groupName)
44
+ } catch (e) {
45
+ error = e
46
+ }
47
+
48
+ // Assert
49
+ expect(error?.message).toBe(
50
+ 'FeatureFlag groupName cannot exceed 100 characters'
51
+ )
52
+ })
53
+
54
+ test('getValidatedFlagName returns the flag name when it is valid', () => {
55
+ // Arrange
56
+ const flagName = 'my-flag'
57
+
58
+ // Act
59
+ const result = getValidatedFlagName(flagName)
60
+
61
+ // Assert
62
+ expect(result).toBe(flagName)
63
+ })
64
+
65
+ test('getValidatedFlagName throws when the flag name is blank', () => {
66
+ // Arrange
67
+ const flagName = ''
68
+
69
+ // Act
70
+ let error
71
+ try {
72
+ getValidatedFlagName(flagName)
73
+ } catch (e) {
74
+ error = e
75
+ }
76
+
77
+ // Assert
78
+ expect(error?.message).toBe('FeatureFlag flagName is required')
79
+ })
80
+ })