@openfeature/ofrep-web-provider 0.1.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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,107 @@
1
+ # Client-Side OFREP Provider
2
+
3
+ This provider is designed to use the [OpenFeature Remote Evaluation Protocol (OFREP)](https://openfeature.dev/specification/appendix-c).
4
+
5
+ ## Installation
6
+
7
+ ### npm
8
+
9
+ ```sh
10
+ npm install @openfeature/ofrep-web
11
+ ```
12
+
13
+ ### yarn
14
+
15
+ ```sh
16
+ yarn add @openfeature/ofrep-web @openfeature/ofrep-core @openfeature/web-sdk
17
+ ```
18
+
19
+ > [!NOTE]
20
+ > yarn requires manual installation of peer dependencies
21
+
22
+ ## Configurations and Usage
23
+
24
+ The provider needs the base url of the OFREP server for instantiation.
25
+
26
+ ```ts
27
+ import { OFREPWebProvider } from '@openfeature/ofrep-web';
28
+
29
+ OpenFeature.setProvider(new OFREPWebProvider({ baseUrl: 'https://localhost:8080', pollingInterval: 60000 }));
30
+ ```
31
+
32
+ ### HTTP headers
33
+
34
+ The provider can use headers from either a static header map or a custom header factory.
35
+
36
+ #### Static Headers
37
+
38
+ Headers can be given as a list of tuples or as a map of headers.
39
+
40
+ ```ts
41
+ import { OFREPWebProvider } from '@openfeature/ofrep-web';
42
+
43
+ OpenFeature.setProvider(
44
+ new OFREPWebProvider({
45
+ baseUrl: 'https://localhost:8080',
46
+ headers: [
47
+ ['Authorization', `my-api-key`],
48
+ ['X-My-Header', `CustomHeaderValue`],
49
+ ],
50
+ }),
51
+ );
52
+ ```
53
+
54
+ ```ts
55
+ import { OFREPWebProvider } from '@openfeature/ofrep-web';
56
+
57
+ OpenFeature.setProvider(
58
+ new OFREPWebProvider({
59
+ baseUrl: 'https://localhost:8080',
60
+ headers: { Authorization: `my-api-key`, 'X-My-Header': `CustomHeaderValue` },
61
+ }),
62
+ );
63
+ ```
64
+
65
+ #### Header Factory
66
+
67
+ The header factory is evaluated before every flag evaluation which makes it possible to use dynamic values for the headers.
68
+
69
+ The following shows an example of loading a token and using it as bearer token.
70
+
71
+ ```ts
72
+ import { OFREPWebProvider } from '@openfeature/ofrep-web';
73
+
74
+ OpenFeature.setProvider(
75
+ new OFREPWebProvider({
76
+ baseUrl: 'https://localhost:8080',
77
+ headersFactory: () => {
78
+ const token: string = loadDynamicToken();
79
+ return [['Authorization', `Bearer ${token}`]];
80
+ },
81
+ }),
82
+ );
83
+ ```
84
+
85
+ ### Fetch implementation
86
+
87
+ If needed, a custom fetch implementation can be injected, if e.g. the platform does not have fetch built in.
88
+
89
+ ```ts
90
+ import { OFREPWebProvider } from '@openfeature/ofrep-web';
91
+ import { fetchPolyfill } from 'some-fetch-polyfill';
92
+
93
+ OpenFeature.setProvider(
94
+ new OFREPWebProvider({
95
+ baseUrl: 'https://localhost:8080',
96
+ fetchImplementation: fetchPolyfill
97
+ }),
98
+ );
99
+ ```
100
+
101
+ ## Building
102
+
103
+ Run `nx package providers-ofrep-web` to build the library.
104
+
105
+ ## Running unit tests
106
+
107
+ Run `nx test providers-ofrep-web` to execute the unit tests via [Jest](https://jestjs.io).
package/index.cjs.d.ts ADDED
@@ -0,0 +1 @@
1
+ export * from "./src/index";
@@ -0,0 +1 @@
1
+ exports._default = require('./index.cjs.js').default;
package/index.cjs.js ADDED
@@ -0,0 +1,281 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var tslib = require('tslib');
6
+ var webSdk = require('@openfeature/web-sdk');
7
+ var ofrepCore = require('@openfeature/ofrep-core');
8
+ var core = require('@openfeature/core');
9
+
10
+ function isResolutionError(response) {
11
+ if (!response || typeof response !== 'object') {
12
+ return false;
13
+ }
14
+ return 'reason' in response && 'errorCode' in response && !('value' in response);
15
+ }
16
+
17
+ var BulkEvaluationStatus;
18
+ (function (BulkEvaluationStatus) {
19
+ BulkEvaluationStatus["SUCCESS_NO_CHANGES"] = "SUCCESS_NO_CHANGES";
20
+ BulkEvaluationStatus["SUCCESS_WITH_CHANGES"] = "SUCCESS_WITH_CHANGES";
21
+ })(BulkEvaluationStatus || (BulkEvaluationStatus = {}));
22
+
23
+ class OFREPWebProvider {
24
+ constructor(options, logger) {
25
+ var _a;
26
+ this.DEFAULT_POLL_INTERVAL = 30000;
27
+ this.metadata = {
28
+ name: 'OpenFeature Remote Evaluation Protocol Web Provider',
29
+ };
30
+ this.runsOn = 'client';
31
+ this.events = new webSdk.OpenFeatureEventEmitter();
32
+ this._cache = {};
33
+ try {
34
+ // Cannot use URL.canParse as it is only available from Node 19.x
35
+ new URL(options.baseUrl);
36
+ }
37
+ catch (_b) {
38
+ throw new Error(`The given OFREP URL "${options.baseUrl}" is not a valid URL.`);
39
+ }
40
+ this._options = options;
41
+ this._logger = logger;
42
+ this._etag = null;
43
+ this._ofrepAPI = new ofrepCore.OFREPApi(this._options.baseUrl, this._options.fetchImplementation);
44
+ this._pollingInterval = (_a = this._options.pollInterval) !== null && _a !== void 0 ? _a : this.DEFAULT_POLL_INTERVAL;
45
+ }
46
+ /**
47
+ * Initialize the provider, it will evaluate the flags and start the polling if it is not disabled.
48
+ * @param context - the context to use for the evaluation
49
+ */
50
+ initialize(context) {
51
+ return tslib.__awaiter(this, void 0, void 0, function* () {
52
+ var _a;
53
+ try {
54
+ this._context = context;
55
+ yield this._evaluateFlags(context);
56
+ if (this._pollingInterval > 0) {
57
+ this.startPolling();
58
+ }
59
+ (_a = this._logger) === null || _a === void 0 ? void 0 : _a.debug(`${this.metadata.name} initialized successfully`);
60
+ }
61
+ catch (error) {
62
+ if (error instanceof ofrepCore.OFREPApiUnauthorizedError || error instanceof ofrepCore.OFREPForbiddenError) {
63
+ throw new webSdk.ProviderFatalError('Initialization failed', error);
64
+ }
65
+ throw error;
66
+ }
67
+ });
68
+ }
69
+ resolveBooleanEvaluation(flagKey) {
70
+ return this.evaluate(flagKey, 'boolean');
71
+ }
72
+ resolveStringEvaluation(flagKey) {
73
+ return this.evaluate(flagKey, 'string');
74
+ }
75
+ resolveNumberEvaluation(flagKey) {
76
+ return this.evaluate(flagKey, 'number');
77
+ }
78
+ resolveObjectEvaluation(flagKey) {
79
+ return this.evaluate(flagKey, 'object');
80
+ }
81
+ /**
82
+ * onContextChange is called when the context changes, it will re-evaluate the flags with the new context
83
+ * and update the cache.
84
+ * @param oldContext - the old evaluation context
85
+ * @param newContext - the new evaluation context
86
+ */
87
+ onContextChange(oldContext, newContext) {
88
+ return tslib.__awaiter(this, void 0, void 0, function* () {
89
+ var _a, _b, _c;
90
+ try {
91
+ this._context = newContext;
92
+ const now = new Date();
93
+ if (this._retryPollingAfter !== undefined && this._retryPollingAfter > now) {
94
+ // we do nothing because we should not call the endpoint
95
+ return;
96
+ }
97
+ yield this._evaluateFlags(newContext);
98
+ }
99
+ catch (error) {
100
+ if (error instanceof ofrepCore.OFREPApiTooManyRequestsError) {
101
+ (_a = this.events) === null || _a === void 0 ? void 0 : _a.emit(webSdk.ClientProviderEvents.Stale, { message: `${error.name}: ${error.message}` });
102
+ return;
103
+ }
104
+ if (error instanceof webSdk.OpenFeatureError ||
105
+ error instanceof ofrepCore.OFREPApiFetchError ||
106
+ error instanceof ofrepCore.OFREPApiUnauthorizedError ||
107
+ error instanceof ofrepCore.OFREPForbiddenError) {
108
+ (_b = this.events) === null || _b === void 0 ? void 0 : _b.emit(webSdk.ClientProviderEvents.Error, { message: `${error.name}: ${error.message}` });
109
+ return;
110
+ }
111
+ (_c = this.events) === null || _c === void 0 ? void 0 : _c.emit(webSdk.ClientProviderEvents.Error, { message: `Unknown error: ${error}` });
112
+ }
113
+ });
114
+ }
115
+ /**
116
+ * onClose is called when the provider is closed, it will stop the polling if it is enabled.
117
+ */
118
+ onClose() {
119
+ this.stopPolling();
120
+ return Promise.resolve();
121
+ }
122
+ /**
123
+ * _evaluateFlags is a function that will call the bulk evaluate flags endpoint to get the flags values.
124
+ * @param context - the context to use for the evaluation
125
+ * @private
126
+ * @returns EvaluationStatus if the evaluation the API returned a 304, 200.
127
+ * @throws TargetingKeyMissingError if the API returned a 400 with the error code TargetingKeyMissing
128
+ * @throws InvalidContextError if the API returned a 400 with the error code InvalidContext
129
+ * @throws ParseError if the API returned a 400 with the error code ParseError
130
+ * @throws GeneralError if the API returned a 400 with an unknown error code
131
+ */
132
+ _evaluateFlags(context) {
133
+ return tslib.__awaiter(this, void 0, void 0, function* () {
134
+ var _a, _b;
135
+ try {
136
+ const evalReq = {
137
+ context,
138
+ };
139
+ const options = Object.assign({ headers: new Headers({
140
+ 'Content-Type': 'application/json',
141
+ }) }, (this._etag !== null ? { headers: { 'If-None-Match': this._etag } } : {}));
142
+ const response = yield this._ofrepAPI.postBulkEvaluateFlags(evalReq, options);
143
+ if (response.httpStatus === 304) {
144
+ // nothing has changed since last time, we are doing nothing
145
+ return { status: BulkEvaluationStatus.SUCCESS_NO_CHANGES, flags: [] };
146
+ }
147
+ if (response.httpStatus !== 200) {
148
+ ofrepCore.handleEvaluationError(response);
149
+ }
150
+ const bulkSuccessResp = response.value;
151
+ const newCache = {};
152
+ (_a = bulkSuccessResp.flags) === null || _a === void 0 ? void 0 : _a.forEach((evalResp) => {
153
+ if (ofrepCore.isEvaluationFailureResponse(evalResp)) {
154
+ newCache[evalResp.key] = {
155
+ errorCode: evalResp.errorCode,
156
+ errorDetails: evalResp.errorDetails,
157
+ reason: core.StandardResolutionReasons.ERROR,
158
+ };
159
+ }
160
+ if (ofrepCore.isEvaluationSuccessResponse(evalResp) && evalResp.key) {
161
+ newCache[evalResp.key] = {
162
+ value: evalResp.value,
163
+ flagMetadata: evalResp.metadata,
164
+ reason: evalResp.reason,
165
+ variant: evalResp.variant,
166
+ };
167
+ }
168
+ });
169
+ const listUpdatedFlags = this._getListUpdatedFlags(this._cache, newCache);
170
+ this._cache = newCache;
171
+ this._etag = (_b = response.httpResponse) === null || _b === void 0 ? void 0 : _b.headers.get('etag');
172
+ return { status: BulkEvaluationStatus.SUCCESS_WITH_CHANGES, flags: listUpdatedFlags };
173
+ }
174
+ catch (error) {
175
+ if (error instanceof ofrepCore.OFREPApiTooManyRequestsError && error.retryAfterDate !== null) {
176
+ this._retryPollingAfter = error.retryAfterDate;
177
+ }
178
+ throw error;
179
+ }
180
+ });
181
+ }
182
+ /**
183
+ * _getListUpdatedFlags is a function that will compare the old cache with the new cache and
184
+ * return the list of flags that have been updated / deleted / created.
185
+ * @param oldCache
186
+ * @param newCache
187
+ * @private
188
+ */
189
+ _getListUpdatedFlags(oldCache, newCache) {
190
+ const changedKeys = [];
191
+ const oldKeys = Object.keys(oldCache);
192
+ const newKeys = Object.keys(newCache);
193
+ // Check for added or modified keys in newCache
194
+ for (const key in newCache) {
195
+ if (oldKeys.indexOf(key) === -1 || JSON.stringify(oldCache[key]) !== JSON.stringify(newCache[key])) {
196
+ changedKeys.push(key);
197
+ }
198
+ }
199
+ // Check for removed keys in oldCache
200
+ for (const key in oldCache) {
201
+ if (newKeys.indexOf(key) === -1) {
202
+ changedKeys.push(key);
203
+ }
204
+ }
205
+ return changedKeys;
206
+ }
207
+ /**
208
+ * Evaluate is a function retrieving the value from a flag in the cache.
209
+ * @param flagKey - name of the flag to retrieve
210
+ * @param type - type of the flag
211
+ * @private
212
+ */
213
+ evaluate(flagKey, type) {
214
+ const resolved = this._cache[flagKey];
215
+ if (!resolved) {
216
+ throw new webSdk.FlagNotFoundError(`flag key ${flagKey} not found in cache`);
217
+ }
218
+ if (isResolutionError(resolved)) {
219
+ switch (resolved.errorCode) {
220
+ case ofrepCore.EvaluationFailureErrorCode.FlagNotFound:
221
+ throw new webSdk.FlagNotFoundError(`flag key ${flagKey} not found: ${resolved.errorDetails}`);
222
+ case ofrepCore.EvaluationFailureErrorCode.TargetingKeyMissing:
223
+ throw new core.TargetingKeyMissingError(`targeting key missing for flag key ${flagKey}: ${resolved.errorDetails}`);
224
+ case ofrepCore.EvaluationFailureErrorCode.InvalidContext:
225
+ throw new core.InvalidContextError(`invalid context for flag key ${flagKey}: ${resolved.errorDetails}`);
226
+ case ofrepCore.EvaluationFailureErrorCode.ParseError:
227
+ throw new core.ParseError(`parse error for flag key ${flagKey}: ${resolved.errorDetails}`);
228
+ case ofrepCore.EvaluationFailureErrorCode.General:
229
+ default:
230
+ throw new webSdk.GeneralError(`general error during flag evaluation for flag key ${flagKey}: ${resolved.errorDetails}`);
231
+ }
232
+ }
233
+ if (typeof resolved.value !== type) {
234
+ throw new webSdk.TypeMismatchError(`flag key ${flagKey} is not of type ${type}`);
235
+ }
236
+ return {
237
+ variant: resolved.variant,
238
+ value: resolved.value,
239
+ flagMetadata: resolved.flagMetadata,
240
+ errorCode: resolved.errorCode,
241
+ errorMessage: resolved.errorMessage,
242
+ reason: resolved.reason,
243
+ };
244
+ }
245
+ /**
246
+ * Start polling for flag updates, it will call the bulk update function every pollInterval
247
+ * @private
248
+ */
249
+ startPolling() {
250
+ this._pollingIntervalId = setInterval(() => tslib.__awaiter(this, void 0, void 0, function* () {
251
+ var _a, _b;
252
+ try {
253
+ const now = new Date();
254
+ if (this._retryPollingAfter !== undefined && this._retryPollingAfter > now) {
255
+ return;
256
+ }
257
+ const res = yield this._evaluateFlags(this._context);
258
+ if (res.status === BulkEvaluationStatus.SUCCESS_WITH_CHANGES) {
259
+ (_a = this.events) === null || _a === void 0 ? void 0 : _a.emit(webSdk.ClientProviderEvents.ConfigurationChanged, {
260
+ message: 'Flags updated',
261
+ flagsChanged: res.flags,
262
+ });
263
+ }
264
+ }
265
+ catch (error) {
266
+ (_b = this.events) === null || _b === void 0 ? void 0 : _b.emit(webSdk.ClientProviderEvents.Stale, { message: `Error while polling: ${error}` });
267
+ }
268
+ }), this._pollingInterval);
269
+ }
270
+ /**
271
+ * Stop polling for flag updates
272
+ * @private
273
+ */
274
+ stopPolling() {
275
+ if (this._pollingIntervalId) {
276
+ clearInterval(this._pollingIntervalId);
277
+ }
278
+ }
279
+ }
280
+
281
+ exports.OFREPWebProvider = OFREPWebProvider;
package/index.cjs.mjs ADDED
@@ -0,0 +1,2 @@
1
+ export * from './index.cjs.js';
2
+ export { _default as default } from './index.cjs.default.js';
package/index.esm.js ADDED
@@ -0,0 +1,277 @@
1
+ import { __awaiter } from 'tslib';
2
+ import { OpenFeatureEventEmitter, ProviderFatalError, ClientProviderEvents, OpenFeatureError, FlagNotFoundError, GeneralError, TypeMismatchError } from '@openfeature/web-sdk';
3
+ import { OFREPApi, OFREPApiUnauthorizedError, OFREPForbiddenError, OFREPApiTooManyRequestsError, OFREPApiFetchError, handleEvaluationError, isEvaluationFailureResponse, isEvaluationSuccessResponse, EvaluationFailureErrorCode } from '@openfeature/ofrep-core';
4
+ import { StandardResolutionReasons, ParseError, InvalidContextError, TargetingKeyMissingError } from '@openfeature/core';
5
+
6
+ function isResolutionError(response) {
7
+ if (!response || typeof response !== 'object') {
8
+ return false;
9
+ }
10
+ return 'reason' in response && 'errorCode' in response && !('value' in response);
11
+ }
12
+
13
+ var BulkEvaluationStatus;
14
+ (function (BulkEvaluationStatus) {
15
+ BulkEvaluationStatus["SUCCESS_NO_CHANGES"] = "SUCCESS_NO_CHANGES";
16
+ BulkEvaluationStatus["SUCCESS_WITH_CHANGES"] = "SUCCESS_WITH_CHANGES";
17
+ })(BulkEvaluationStatus || (BulkEvaluationStatus = {}));
18
+
19
+ class OFREPWebProvider {
20
+ constructor(options, logger) {
21
+ var _a;
22
+ this.DEFAULT_POLL_INTERVAL = 30000;
23
+ this.metadata = {
24
+ name: 'OpenFeature Remote Evaluation Protocol Web Provider',
25
+ };
26
+ this.runsOn = 'client';
27
+ this.events = new OpenFeatureEventEmitter();
28
+ this._cache = {};
29
+ try {
30
+ // Cannot use URL.canParse as it is only available from Node 19.x
31
+ new URL(options.baseUrl);
32
+ }
33
+ catch (_b) {
34
+ throw new Error(`The given OFREP URL "${options.baseUrl}" is not a valid URL.`);
35
+ }
36
+ this._options = options;
37
+ this._logger = logger;
38
+ this._etag = null;
39
+ this._ofrepAPI = new OFREPApi(this._options.baseUrl, this._options.fetchImplementation);
40
+ this._pollingInterval = (_a = this._options.pollInterval) !== null && _a !== void 0 ? _a : this.DEFAULT_POLL_INTERVAL;
41
+ }
42
+ /**
43
+ * Initialize the provider, it will evaluate the flags and start the polling if it is not disabled.
44
+ * @param context - the context to use for the evaluation
45
+ */
46
+ initialize(context) {
47
+ return __awaiter(this, void 0, void 0, function* () {
48
+ var _a;
49
+ try {
50
+ this._context = context;
51
+ yield this._evaluateFlags(context);
52
+ if (this._pollingInterval > 0) {
53
+ this.startPolling();
54
+ }
55
+ (_a = this._logger) === null || _a === void 0 ? void 0 : _a.debug(`${this.metadata.name} initialized successfully`);
56
+ }
57
+ catch (error) {
58
+ if (error instanceof OFREPApiUnauthorizedError || error instanceof OFREPForbiddenError) {
59
+ throw new ProviderFatalError('Initialization failed', error);
60
+ }
61
+ throw error;
62
+ }
63
+ });
64
+ }
65
+ resolveBooleanEvaluation(flagKey) {
66
+ return this.evaluate(flagKey, 'boolean');
67
+ }
68
+ resolveStringEvaluation(flagKey) {
69
+ return this.evaluate(flagKey, 'string');
70
+ }
71
+ resolveNumberEvaluation(flagKey) {
72
+ return this.evaluate(flagKey, 'number');
73
+ }
74
+ resolveObjectEvaluation(flagKey) {
75
+ return this.evaluate(flagKey, 'object');
76
+ }
77
+ /**
78
+ * onContextChange is called when the context changes, it will re-evaluate the flags with the new context
79
+ * and update the cache.
80
+ * @param oldContext - the old evaluation context
81
+ * @param newContext - the new evaluation context
82
+ */
83
+ onContextChange(oldContext, newContext) {
84
+ return __awaiter(this, void 0, void 0, function* () {
85
+ var _a, _b, _c;
86
+ try {
87
+ this._context = newContext;
88
+ const now = new Date();
89
+ if (this._retryPollingAfter !== undefined && this._retryPollingAfter > now) {
90
+ // we do nothing because we should not call the endpoint
91
+ return;
92
+ }
93
+ yield this._evaluateFlags(newContext);
94
+ }
95
+ catch (error) {
96
+ if (error instanceof OFREPApiTooManyRequestsError) {
97
+ (_a = this.events) === null || _a === void 0 ? void 0 : _a.emit(ClientProviderEvents.Stale, { message: `${error.name}: ${error.message}` });
98
+ return;
99
+ }
100
+ if (error instanceof OpenFeatureError ||
101
+ error instanceof OFREPApiFetchError ||
102
+ error instanceof OFREPApiUnauthorizedError ||
103
+ error instanceof OFREPForbiddenError) {
104
+ (_b = this.events) === null || _b === void 0 ? void 0 : _b.emit(ClientProviderEvents.Error, { message: `${error.name}: ${error.message}` });
105
+ return;
106
+ }
107
+ (_c = this.events) === null || _c === void 0 ? void 0 : _c.emit(ClientProviderEvents.Error, { message: `Unknown error: ${error}` });
108
+ }
109
+ });
110
+ }
111
+ /**
112
+ * onClose is called when the provider is closed, it will stop the polling if it is enabled.
113
+ */
114
+ onClose() {
115
+ this.stopPolling();
116
+ return Promise.resolve();
117
+ }
118
+ /**
119
+ * _evaluateFlags is a function that will call the bulk evaluate flags endpoint to get the flags values.
120
+ * @param context - the context to use for the evaluation
121
+ * @private
122
+ * @returns EvaluationStatus if the evaluation the API returned a 304, 200.
123
+ * @throws TargetingKeyMissingError if the API returned a 400 with the error code TargetingKeyMissing
124
+ * @throws InvalidContextError if the API returned a 400 with the error code InvalidContext
125
+ * @throws ParseError if the API returned a 400 with the error code ParseError
126
+ * @throws GeneralError if the API returned a 400 with an unknown error code
127
+ */
128
+ _evaluateFlags(context) {
129
+ return __awaiter(this, void 0, void 0, function* () {
130
+ var _a, _b;
131
+ try {
132
+ const evalReq = {
133
+ context,
134
+ };
135
+ const options = Object.assign({ headers: new Headers({
136
+ 'Content-Type': 'application/json',
137
+ }) }, (this._etag !== null ? { headers: { 'If-None-Match': this._etag } } : {}));
138
+ const response = yield this._ofrepAPI.postBulkEvaluateFlags(evalReq, options);
139
+ if (response.httpStatus === 304) {
140
+ // nothing has changed since last time, we are doing nothing
141
+ return { status: BulkEvaluationStatus.SUCCESS_NO_CHANGES, flags: [] };
142
+ }
143
+ if (response.httpStatus !== 200) {
144
+ handleEvaluationError(response);
145
+ }
146
+ const bulkSuccessResp = response.value;
147
+ const newCache = {};
148
+ (_a = bulkSuccessResp.flags) === null || _a === void 0 ? void 0 : _a.forEach((evalResp) => {
149
+ if (isEvaluationFailureResponse(evalResp)) {
150
+ newCache[evalResp.key] = {
151
+ errorCode: evalResp.errorCode,
152
+ errorDetails: evalResp.errorDetails,
153
+ reason: StandardResolutionReasons.ERROR,
154
+ };
155
+ }
156
+ if (isEvaluationSuccessResponse(evalResp) && evalResp.key) {
157
+ newCache[evalResp.key] = {
158
+ value: evalResp.value,
159
+ flagMetadata: evalResp.metadata,
160
+ reason: evalResp.reason,
161
+ variant: evalResp.variant,
162
+ };
163
+ }
164
+ });
165
+ const listUpdatedFlags = this._getListUpdatedFlags(this._cache, newCache);
166
+ this._cache = newCache;
167
+ this._etag = (_b = response.httpResponse) === null || _b === void 0 ? void 0 : _b.headers.get('etag');
168
+ return { status: BulkEvaluationStatus.SUCCESS_WITH_CHANGES, flags: listUpdatedFlags };
169
+ }
170
+ catch (error) {
171
+ if (error instanceof OFREPApiTooManyRequestsError && error.retryAfterDate !== null) {
172
+ this._retryPollingAfter = error.retryAfterDate;
173
+ }
174
+ throw error;
175
+ }
176
+ });
177
+ }
178
+ /**
179
+ * _getListUpdatedFlags is a function that will compare the old cache with the new cache and
180
+ * return the list of flags that have been updated / deleted / created.
181
+ * @param oldCache
182
+ * @param newCache
183
+ * @private
184
+ */
185
+ _getListUpdatedFlags(oldCache, newCache) {
186
+ const changedKeys = [];
187
+ const oldKeys = Object.keys(oldCache);
188
+ const newKeys = Object.keys(newCache);
189
+ // Check for added or modified keys in newCache
190
+ for (const key in newCache) {
191
+ if (oldKeys.indexOf(key) === -1 || JSON.stringify(oldCache[key]) !== JSON.stringify(newCache[key])) {
192
+ changedKeys.push(key);
193
+ }
194
+ }
195
+ // Check for removed keys in oldCache
196
+ for (const key in oldCache) {
197
+ if (newKeys.indexOf(key) === -1) {
198
+ changedKeys.push(key);
199
+ }
200
+ }
201
+ return changedKeys;
202
+ }
203
+ /**
204
+ * Evaluate is a function retrieving the value from a flag in the cache.
205
+ * @param flagKey - name of the flag to retrieve
206
+ * @param type - type of the flag
207
+ * @private
208
+ */
209
+ evaluate(flagKey, type) {
210
+ const resolved = this._cache[flagKey];
211
+ if (!resolved) {
212
+ throw new FlagNotFoundError(`flag key ${flagKey} not found in cache`);
213
+ }
214
+ if (isResolutionError(resolved)) {
215
+ switch (resolved.errorCode) {
216
+ case EvaluationFailureErrorCode.FlagNotFound:
217
+ throw new FlagNotFoundError(`flag key ${flagKey} not found: ${resolved.errorDetails}`);
218
+ case EvaluationFailureErrorCode.TargetingKeyMissing:
219
+ throw new TargetingKeyMissingError(`targeting key missing for flag key ${flagKey}: ${resolved.errorDetails}`);
220
+ case EvaluationFailureErrorCode.InvalidContext:
221
+ throw new InvalidContextError(`invalid context for flag key ${flagKey}: ${resolved.errorDetails}`);
222
+ case EvaluationFailureErrorCode.ParseError:
223
+ throw new ParseError(`parse error for flag key ${flagKey}: ${resolved.errorDetails}`);
224
+ case EvaluationFailureErrorCode.General:
225
+ default:
226
+ throw new GeneralError(`general error during flag evaluation for flag key ${flagKey}: ${resolved.errorDetails}`);
227
+ }
228
+ }
229
+ if (typeof resolved.value !== type) {
230
+ throw new TypeMismatchError(`flag key ${flagKey} is not of type ${type}`);
231
+ }
232
+ return {
233
+ variant: resolved.variant,
234
+ value: resolved.value,
235
+ flagMetadata: resolved.flagMetadata,
236
+ errorCode: resolved.errorCode,
237
+ errorMessage: resolved.errorMessage,
238
+ reason: resolved.reason,
239
+ };
240
+ }
241
+ /**
242
+ * Start polling for flag updates, it will call the bulk update function every pollInterval
243
+ * @private
244
+ */
245
+ startPolling() {
246
+ this._pollingIntervalId = setInterval(() => __awaiter(this, void 0, void 0, function* () {
247
+ var _a, _b;
248
+ try {
249
+ const now = new Date();
250
+ if (this._retryPollingAfter !== undefined && this._retryPollingAfter > now) {
251
+ return;
252
+ }
253
+ const res = yield this._evaluateFlags(this._context);
254
+ if (res.status === BulkEvaluationStatus.SUCCESS_WITH_CHANGES) {
255
+ (_a = this.events) === null || _a === void 0 ? void 0 : _a.emit(ClientProviderEvents.ConfigurationChanged, {
256
+ message: 'Flags updated',
257
+ flagsChanged: res.flags,
258
+ });
259
+ }
260
+ }
261
+ catch (error) {
262
+ (_b = this.events) === null || _b === void 0 ? void 0 : _b.emit(ClientProviderEvents.Stale, { message: `Error while polling: ${error}` });
263
+ }
264
+ }), this._pollingInterval);
265
+ }
266
+ /**
267
+ * Stop polling for flag updates
268
+ * @private
269
+ */
270
+ stopPolling() {
271
+ if (this._pollingIntervalId) {
272
+ clearInterval(this._pollingIntervalId);
273
+ }
274
+ }
275
+ }
276
+
277
+ export { OFREPWebProvider };
package/package.json ADDED
@@ -0,0 +1,26 @@
1
+ {
2
+ "name": "@openfeature/ofrep-web-provider",
3
+ "version": "0.1.1",
4
+ "dependencies": {
5
+ "tslib": "^2.3.0"
6
+ },
7
+ "main": "./index.cjs.js",
8
+ "typings": "./src/index.d.ts",
9
+ "scripts": {
10
+ "publish-if-not-exists": "cp $NPM_CONFIG_USERCONFIG .npmrc && if [ \"$(npm show $npm_package_name@$npm_package_version version)\" = \"$(npm run current-version -s)\" ]; then echo 'already published, skipping'; else npm publish --access public; fi",
11
+ "current-version": "echo $npm_package_version"
12
+ },
13
+ "peerDependencies": {
14
+ "@openfeature/web-sdk": ">=0.4.0",
15
+ "@openfeature/ofrep-core": "^0.1.0"
16
+ },
17
+ "exports": {
18
+ "./package.json": "./package.json",
19
+ ".": {
20
+ "module": "./index.esm.js",
21
+ "import": "./index.cjs.mjs",
22
+ "default": "./index.cjs.js"
23
+ }
24
+ },
25
+ "module": "./index.esm.js"
26
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1 @@
1
+ export * from './lib/ofrep-web-provider';
@@ -0,0 +1,14 @@
1
+ export declare enum BulkEvaluationStatus {
2
+ SUCCESS_NO_CHANGES = "SUCCESS_NO_CHANGES",
3
+ SUCCESS_WITH_CHANGES = "SUCCESS_WITH_CHANGES"
4
+ }
5
+ export interface EvaluateFlagsResponse {
6
+ /**
7
+ * Status of the bulk evaluation.
8
+ */
9
+ status: BulkEvaluationStatus;
10
+ /**
11
+ * The List of flags changed when doing the bulk evaluation.
12
+ */
13
+ flags: string[];
14
+ }
@@ -0,0 +1,8 @@
1
+ import { FlagValue, ResolutionDetails } from '@openfeature/web-sdk';
2
+ import { ResolutionError } from './resolution-error';
3
+ /**
4
+ * inMemoryCache is a type representing the internal cache of the flags.
5
+ */
6
+ export type InMemoryCache = {
7
+ [key: string]: ResolutionDetails<FlagValue> | ResolutionError;
8
+ };
@@ -0,0 +1,11 @@
1
+ import { OFREPProviderBaseOptions } from '@openfeature/ofrep-core';
2
+ export type OFREPWebProviderOptions = OFREPProviderBaseOptions & {
3
+ /**
4
+ * pollInterval is the time in milliseconds to wait between we call the OFREP
5
+ * API to get the latest evaluation of your flags.
6
+ *
7
+ * If a negative number is provided, the provider will not poll the OFREP API.
8
+ * Default: 30000
9
+ */
10
+ pollInterval?: number;
11
+ };
@@ -0,0 +1,8 @@
1
+ import { ResolutionReason } from '@openfeature/web-sdk';
2
+ import { EvaluationFailureErrorCode } from '@openfeature/ofrep-core';
3
+ export type ResolutionError = {
4
+ reason: ResolutionReason;
5
+ errorCode: EvaluationFailureErrorCode;
6
+ errorDetails?: string;
7
+ };
8
+ export declare function isResolutionError(response: unknown): response is ResolutionError;
@@ -0,0 +1,77 @@
1
+ import { EvaluationContext, Hook, JsonValue, Logger, OpenFeatureEventEmitter, Provider, ResolutionDetails } from '@openfeature/web-sdk';
2
+ import { OFREPWebProviderOptions } from './model/ofrep-web-provider-options';
3
+ export declare class OFREPWebProvider implements Provider {
4
+ DEFAULT_POLL_INTERVAL: number;
5
+ readonly metadata: {
6
+ name: string;
7
+ };
8
+ readonly runsOn = "client";
9
+ events: OpenFeatureEventEmitter;
10
+ hooks?: Hook[] | undefined;
11
+ private _logger?;
12
+ private _options;
13
+ private _ofrepAPI;
14
+ private _etag;
15
+ private _pollingInterval;
16
+ private _retryPollingAfter;
17
+ private _cache;
18
+ private _context;
19
+ private _pollingIntervalId?;
20
+ constructor(options: OFREPWebProviderOptions, logger?: Logger);
21
+ /**
22
+ * Initialize the provider, it will evaluate the flags and start the polling if it is not disabled.
23
+ * @param context - the context to use for the evaluation
24
+ */
25
+ initialize?(context?: EvaluationContext | undefined): Promise<void>;
26
+ resolveBooleanEvaluation(flagKey: string): ResolutionDetails<boolean>;
27
+ resolveStringEvaluation(flagKey: string): ResolutionDetails<string>;
28
+ resolveNumberEvaluation(flagKey: string): ResolutionDetails<number>;
29
+ resolveObjectEvaluation<T extends JsonValue>(flagKey: string): ResolutionDetails<T>;
30
+ /**
31
+ * onContextChange is called when the context changes, it will re-evaluate the flags with the new context
32
+ * and update the cache.
33
+ * @param oldContext - the old evaluation context
34
+ * @param newContext - the new evaluation context
35
+ */
36
+ onContextChange(oldContext: EvaluationContext, newContext: EvaluationContext): Promise<void>;
37
+ /**
38
+ * onClose is called when the provider is closed, it will stop the polling if it is enabled.
39
+ */
40
+ onClose?(): Promise<void>;
41
+ /**
42
+ * _evaluateFlags is a function that will call the bulk evaluate flags endpoint to get the flags values.
43
+ * @param context - the context to use for the evaluation
44
+ * @private
45
+ * @returns EvaluationStatus if the evaluation the API returned a 304, 200.
46
+ * @throws TargetingKeyMissingError if the API returned a 400 with the error code TargetingKeyMissing
47
+ * @throws InvalidContextError if the API returned a 400 with the error code InvalidContext
48
+ * @throws ParseError if the API returned a 400 with the error code ParseError
49
+ * @throws GeneralError if the API returned a 400 with an unknown error code
50
+ */
51
+ private _evaluateFlags;
52
+ /**
53
+ * _getListUpdatedFlags is a function that will compare the old cache with the new cache and
54
+ * return the list of flags that have been updated / deleted / created.
55
+ * @param oldCache
56
+ * @param newCache
57
+ * @private
58
+ */
59
+ private _getListUpdatedFlags;
60
+ /**
61
+ * Evaluate is a function retrieving the value from a flag in the cache.
62
+ * @param flagKey - name of the flag to retrieve
63
+ * @param type - type of the flag
64
+ * @private
65
+ */
66
+ private evaluate;
67
+ /**
68
+ * Start polling for flag updates, it will call the bulk update function every pollInterval
69
+ * @private
70
+ */
71
+ private startPolling;
72
+ /**
73
+ * Stop polling for flag updates
74
+ * @private
75
+ */
76
+ private stopPolling;
77
+ }
@@ -0,0 +1,3 @@
1
+ {
2
+ "module": "commonjs"
3
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * TestLogger is a logger build for testing purposes.
3
+ * This is not ready to be production ready, so please avoid using it.
4
+ */
5
+ export default class TestLogger {
6
+ error(...args: unknown[]): void;
7
+ warn(...args: unknown[]): void;
8
+ info(...args: unknown[]): void;
9
+ debug(...args: unknown[]): void;
10
+ }