@splitsoftware/openfeature-web-split-provider 1.0.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.
package/CHANGES.txt ADDED
@@ -0,0 +1,3 @@
1
+ 1.0.0 (October 1, 2025)
2
+ - First release.
3
+ - Up to date with @openfeature/web-sdk v1.6.1, and @splitsoftware/splitio-browserjs 1.4.0
@@ -0,0 +1,28 @@
1
+ # Contributing to the Split OpenFeature Provider
2
+
3
+ The Split Provider is an open source project and we welcome feedback and contribution. The information below describes how to build the project with your changes, run the tests, and send the Pull Request(PR).
4
+
5
+ ## Development
6
+
7
+ ### Development process
8
+
9
+ 1. Fork the repository and create a topic branch from `development` branch. Please use a descriptive name for your branch.
10
+ 2. While developing, use descriptive messages in your commits. Avoid short or meaningless sentences like "fix bug".
11
+ 3. Make sure to add tests for both positive and negative cases.
12
+ 4. Run the build script and make sure it runs with no errors.
13
+ 5. Run all tests and make sure there are no failures.
14
+ 6. `git push` your changes to GitHub within your topic branch.
15
+ 7. Open a Pull Request(PR) from your forked repo and into the `development` branch of the original repository.
16
+ 8. When creating your PR, please fill out all the fields of the PR template, as applicable, for the project.
17
+ 9. Check for conflicts once the pull request is created to make sure your PR can be merged cleanly into `development`.
18
+ 10. Keep an eye out for any feedback or comments from the Split team.
19
+
20
+ ### Building the Split Provider
21
+ - `npm run build`
22
+
23
+ ### Running tests
24
+ - `npm run test`
25
+
26
+ # Contact
27
+
28
+ If you have any other questions or need to contact us directly in a private manner send us a note at sdks@split.io
package/LICENSE ADDED
@@ -0,0 +1,13 @@
1
+ Copyright © 2022 Split Software, Inc.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,137 @@
1
+ # Split OpenFeature Provider for NodeJS
2
+ [![Twitter Follow](https://img.shields.io/twitter/follow/splitsoftware.svg?style=social&label=Follow&maxAge=1529000)](https://twitter.com/intent/follow?screen_name=splitsoftware)
3
+
4
+ ## Overview
5
+ This Provider is designed to allow the use of OpenFeature with Split, the platform for controlled rollouts, serving features to your users via the Split feature flag to manage your complete customer experience.
6
+
7
+ ## Getting started
8
+ Below is a simple example that describes the instantiation of the Split Provider. Please see the [OpenFeature Documentation](https://docs.openfeature.dev/docs/reference/concepts/evaluation-api) for details on how to use the OpenFeature SDK.
9
+
10
+ ### Add the Split provider
11
+
12
+ ```sh
13
+ npm install @splitsoftware/openfeature-web-split-provider
14
+ ```
15
+
16
+ ### Confirm peer dependencies are installed
17
+ ```sh
18
+ npm install @splitsoftware/splitio-browserjs
19
+ npm install @openfeature/web-sdk
20
+ ```
21
+
22
+ ### Register the Split provider with OpenFeature using splitFactory
23
+ ```js
24
+ import { OpenFeature } from '@openfeature/web-sdk';
25
+ import { SplitFactory } from '@splitsoftware/splitio-browserjs';
26
+ import { OpenFeatureSplitProvider } from '@splitsoftware/openfeature-web-split-provider';
27
+
28
+ const splitFactory = SplitFactory({
29
+ core: {
30
+ authorizationKey: 'your auth key'
31
+ }
32
+ });
33
+ const provider = new OpenFeatureSplitProvider(splitFactory);
34
+ OpenFeature.setProvider(provider);
35
+ ```
36
+
37
+ ## Use of OpenFeature with Split
38
+ After the initial setup you can use OpenFeature according to their [documentation](https://docs.openfeature.dev/docs/reference/concepts/evaluation-api/).
39
+
40
+ One important note is that the Split Provider **requires a targeting key** to be set. Often times this should be set when evaluating the value of a flag by [setting an EvaluationContext](https://docs.openfeature.dev/docs/reference/concepts/evaluation-context) which contains the targeting key. An example flag evaluation is
41
+ ```js
42
+ const context: EvaluationContext = {
43
+ targetingKey: 'TARGETING_KEY',
44
+ trafficType: 'account'
45
+ };
46
+ OpenFeature.setContext(context)
47
+ ```
48
+
49
+ ## Evaluate with details
50
+ Use the get*Details(...) APIs to get the value and rich context (variant, reason, error code, metadata). This provider includes the Split treatment config as a raw JSON string under flagMetadata["config"]
51
+
52
+ ```js
53
+ const booleanTreatment = client.getBooleanDetails('boolFlag', false);
54
+
55
+ const config = booleanTreatment.flagMetadata.config;
56
+ ```
57
+
58
+ ## Evaluate with attributes
59
+ Evaluation attributes must be set in context before evaluation
60
+
61
+ ```js
62
+ const context: EvaluationContext = {
63
+ targetingKey: 'TARGETING_KEY',
64
+ trafficType: 'account',
65
+ plan: 'premium',
66
+ couppon: 'WELCOME10'
67
+ };
68
+ OpenFeature.setContext(context);
69
+ const booleanTreatment = client.getBooleanDetails('boolFlag', false);
70
+ ```
71
+
72
+ ## Tracking
73
+
74
+ To use track(eventName, context, details) you must provide:
75
+
76
+ - A non-blank `eventName`.
77
+ - A context with:
78
+ - `targetingKey` (non-blank).
79
+ - `trafficType` (string, e.g. "user" or "account", "user" by default).
80
+
81
+ Optional:
82
+
83
+ - details with:
84
+ - `value`: numeric event value (defaults to 0).
85
+ - `properties`: map of attributes (prefer primitives: string/number/boolean/null).
86
+
87
+ Example:
88
+ ```js
89
+ const context = { targetingKey: 'user-123', trafficType: 'account' }
90
+ const details = { value: 19.99, properties: { plan: 'pro', coupon: 'WELCOME10' }}
91
+
92
+ client.setEvaluationContext(context)
93
+ client.track('checkout.completed', details)
94
+ ```
95
+ ## Submitting issues
96
+
97
+ The Split team monitors all issues submitted to this [issue tracker](https://github.com/splitio/split-openfeature-provider-web-js/issues). We encourage you to use this issue tracker to submit any bug reports, feedback, and feature enhancements. We'll do our best to respond in a timely manner.
98
+
99
+ ## Contributing
100
+ Please see [Contributors Guide](CONTRIBUTORS-GUIDE.md) to find all you need to submit a Pull Request (PR).
101
+
102
+ ## License
103
+ Licensed under the Apache License, Version 2.0. See: [Apache License](http://www.apache.org/licenses/).
104
+
105
+ ## About Split
106
+
107
+ Split is the leading Feature Delivery Platform for engineering teams that want to confidently deploy features as fast as they can develop them. Split’s fine-grained management, real-time monitoring, and data-driven experimentation ensure that new features will improve the customer experience without breaking or degrading performance. Companies like Twilio, Salesforce, GoDaddy and WePay trust Split to power their feature delivery.
108
+
109
+ To learn more about Split, contact hello@split.io, or get started with feature flags for free at https://www.split.io/signup.
110
+
111
+ Split has built and maintains SDKs for:
112
+
113
+ * .NET [Github](https://github.com/splitio/dotnet-client) [Docs](https://help.split.io/hc/en-us/articles/360020240172--NET-SDK)
114
+ * Android [Github](https://github.com/splitio/android-client) [Docs](https://help.split.io/hc/en-us/articles/360020343291-Android-SDK)
115
+ * Angular [Github](https://github.com/splitio/angular-sdk-plugin) [Docs](https://help.split.io/hc/en-us/articles/6495326064397-Angular-utilities)
116
+ * Elixir thin-client [Github](https://github.com/splitio/elixir-thin-client) [Docs](https://help.split.io/hc/en-us/articles/26988707417869-Elixir-Thin-Client-SDK)
117
+ * Flutter [Github](https://github.com/splitio/flutter-sdk-plugin) [Docs](https://help.split.io/hc/en-us/articles/8096158017165-Flutter-plugin)
118
+ * GO [Github](https://github.com/splitio/go-client) [Docs](https://help.split.io/hc/en-us/articles/360020093652-Go-SDK)
119
+ * iOS [Github](https://github.com/splitio/ios-client) [Docs](https://help.split.io/hc/en-us/articles/360020401491-iOS-SDK)
120
+ * Java [Github](https://github.com/splitio/java-client) [Docs](https://help.split.io/hc/en-us/articles/360020405151-Java-SDK)
121
+ * JavaScript [Github](https://github.com/splitio/javascript-client) [Docs](https://help.split.io/hc/en-us/articles/360020448791-JavaScript-SDK)
122
+ * JavaScript for Browser [Github](https://github.com/splitio/javascript-browser-client) [Docs](https://help.split.io/hc/en-us/articles/360058730852-Browser-SDK)
123
+ * Node.js [Github](https://github.com/splitio/javascript-client) [Docs](https://help.split.io/hc/en-us/articles/360020564931-Node-js-SDK)
124
+ * PHP [Github](https://github.com/splitio/php-client) [Docs](https://help.split.io/hc/en-us/articles/360020350372-PHP-SDK)
125
+ * PHP thin-client [Github](https://github.com/splitio/php-thin-client) [Docs](https://help.split.io/hc/en-us/articles/18305128673933-PHP-Thin-Client-SDK)
126
+ * Python [Github](https://github.com/splitio/python-client) [Docs](https://help.split.io/hc/en-us/articles/360020359652-Python-SDK)
127
+ * React [Github](https://github.com/splitio/react-client) [Docs](https://help.split.io/hc/en-us/articles/360038825091-React-SDK)
128
+ * React Native [Github](https://github.com/splitio/react-native-client) [Docs](https://help.split.io/hc/en-us/articles/4406066357901-React-Native-SDK)
129
+ * Redux [Github](https://github.com/splitio/redux-client) [Docs](https://help.split.io/hc/en-us/articles/360038851551-Redux-SDK)
130
+ * Ruby [Github](https://github.com/splitio/ruby-client) [Docs](https://help.split.io/hc/en-us/articles/360020673251-Ruby-SDK)
131
+
132
+ For a comprehensive list of open source projects visit our [Github page](https://github.com/splitio?utf8=%E2%9C%93&query=%20only%3Apublic%20).
133
+
134
+ **Learn more about Split:**
135
+
136
+ Visit [split.io/product](https://www.split.io/product) for an overview of Split, or visit our documentation at [help.split.io](http://help.split.io) for more detailed information.
137
+
package/es/index.js ADDED
@@ -0,0 +1 @@
1
+ export * from './lib/js-split-provider';
@@ -0,0 +1,197 @@
1
+ import { __assign, __awaiter, __generator, __rest } from "tslib";
2
+ /* eslint-disable @typescript-eslint/no-explicit-any */
3
+ /* eslint-disable @typescript-eslint/no-unused-vars */
4
+ import { ParseError, FlagNotFoundError, StandardResolutionReasons, ProviderEvents, OpenFeatureEventEmitter, } from "@openfeature/web-sdk";
5
+ var CONTROL_VALUE_ERROR_MESSAGE = "Received the 'control' value from Split.";
6
+ var CONTROL_TREATMENT = 'control';
7
+ var OpenFeatureSplitProvider = /** @class */ (function () {
8
+ function OpenFeatureSplitProvider(splitFactory) {
9
+ this.metadata = {
10
+ name: "split",
11
+ };
12
+ this.events = new OpenFeatureEventEmitter();
13
+ // Asume 'user' as default traffic type'
14
+ this.trafficType = 'user';
15
+ this.factory = splitFactory;
16
+ this.client = splitFactory.client();
17
+ }
18
+ OpenFeatureSplitProvider.prototype.onContextChange = function (oldContext, newContext) {
19
+ var _this = this;
20
+ var oldTargetingKey = oldContext.targetingKey;
21
+ var newTargetingKey = newContext.targetingKey, newTrafficType = newContext.trafficType;
22
+ this.trafficType = newTrafficType && newTrafficType !== this.trafficType ? newTrafficType : this.trafficType;
23
+ if (newTargetingKey && newTargetingKey !== oldTargetingKey) {
24
+ this.client = this.factory.client(newTargetingKey);
25
+ return new Promise(function (resolve, reject) {
26
+ var emitContextChange = function () {
27
+ _this.events.emit(ProviderEvents.ConfigurationChanged);
28
+ resolve();
29
+ };
30
+ _this.eventsHandler(emitContextChange, reject);
31
+ });
32
+ }
33
+ return Promise.resolve();
34
+ };
35
+ OpenFeatureSplitProvider.prototype.initialize = function () {
36
+ return __awaiter(this, void 0, void 0, function () {
37
+ var _this = this;
38
+ return __generator(this, function (_a) {
39
+ switch (_a.label) {
40
+ case 0: return [4 /*yield*/, new Promise(function (resolve, reject) {
41
+ try {
42
+ _this.eventsHandler(resolve, reject);
43
+ }
44
+ catch (_a) {
45
+ reject();
46
+ }
47
+ })];
48
+ case 1:
49
+ _a.sent();
50
+ return [2 /*return*/];
51
+ }
52
+ });
53
+ });
54
+ };
55
+ OpenFeatureSplitProvider.prototype.resolveBooleanEvaluation = function (flagKey, _, context, _logger) {
56
+ var details = this.evaluateTreatment(flagKey, this.transformContext(context));
57
+ var treatment = details.value.toLowerCase();
58
+ if (treatment === 'on' || treatment === 'true') {
59
+ return __assign(__assign({}, details), { value: true });
60
+ }
61
+ if (treatment === 'off' || treatment === 'false') {
62
+ return __assign(__assign({}, details), { value: false });
63
+ }
64
+ throw new ParseError("Invalid boolean value for ".concat(treatment));
65
+ };
66
+ OpenFeatureSplitProvider.prototype.resolveStringEvaluation = function (flagKey, _, context, _logger) {
67
+ var details = this.evaluateTreatment(flagKey, this.transformContext(context));
68
+ return details;
69
+ };
70
+ OpenFeatureSplitProvider.prototype.resolveNumberEvaluation = function (flagKey, _, context, _logger) {
71
+ var details = this.evaluateTreatment(flagKey, this.transformContext(context));
72
+ return __assign(__assign({}, details), { value: this.parseValidNumber(details.value) });
73
+ };
74
+ OpenFeatureSplitProvider.prototype.resolveObjectEvaluation = function (flagKey, _, context, _logger) {
75
+ var details = this.evaluateTreatment(flagKey, this.transformContext(context));
76
+ return __assign(__assign({}, details), { value: this.parseValidJsonObject(details.value) });
77
+ };
78
+ OpenFeatureSplitProvider.prototype.evaluateTreatment = function (flagKey, consumer) {
79
+ if (flagKey == null || flagKey === '') {
80
+ throw new FlagNotFoundError('flagKey must be a non-empty string');
81
+ }
82
+ var treatment = this.client.getTreatmentWithConfig(flagKey, consumer.attributes);
83
+ var value = treatment.treatment, config = treatment.config;
84
+ if (value === CONTROL_TREATMENT) {
85
+ throw new FlagNotFoundError(CONTROL_VALUE_ERROR_MESSAGE);
86
+ }
87
+ var flagMetadata = { config: config ? config : '' };
88
+ var details = {
89
+ value: value,
90
+ variant: value,
91
+ flagMetadata: flagMetadata,
92
+ reason: StandardResolutionReasons.TARGETING_MATCH,
93
+ };
94
+ return details;
95
+ };
96
+ OpenFeatureSplitProvider.prototype.track = function (trackingEventName, context, details) {
97
+ // eventName is always required
98
+ if (trackingEventName == null || trackingEventName === '')
99
+ throw new ParseError('Missing eventName, required to track');
100
+ var trafficType = this.transformContext(context).trafficType;
101
+ var value;
102
+ var properties = {};
103
+ if (details != null) {
104
+ if (details.value != null) {
105
+ value = details.value;
106
+ }
107
+ if (details.properties != null) {
108
+ properties = details.properties;
109
+ }
110
+ }
111
+ this.client.track(trafficType, trackingEventName, value, properties);
112
+ };
113
+ OpenFeatureSplitProvider.prototype.onClose = function () {
114
+ return __awaiter(this, void 0, void 0, function () {
115
+ return __generator(this, function (_a) {
116
+ return [2 /*return*/, this.factory.destroy()];
117
+ });
118
+ });
119
+ };
120
+ //Transform the context into an object useful for the Split API, an key string with arbitrary Split "Attributes".
121
+ OpenFeatureSplitProvider.prototype.transformContext = function (context) {
122
+ var targetingKey = context.targetingKey, ttVal = context.trafficType, attributes = __rest(context, ["targetingKey", "trafficType"]);
123
+ var trafficType = ttVal != null && typeof ttVal === 'string' && ttVal.trim() !== ''
124
+ ? ttVal
125
+ : this.trafficType;
126
+ return {
127
+ targetingKey: targetingKey,
128
+ trafficType: trafficType,
129
+ // Stringify context objects include date.
130
+ attributes: JSON.parse(JSON.stringify(attributes)),
131
+ };
132
+ };
133
+ OpenFeatureSplitProvider.prototype.parseValidNumber = function (stringValue) {
134
+ if (stringValue === undefined) {
135
+ throw new ParseError("Invalid 'undefined' value.");
136
+ }
137
+ var result = Number.parseFloat(stringValue);
138
+ if (Number.isNaN(result)) {
139
+ throw new ParseError("Invalid numeric value ".concat(stringValue));
140
+ }
141
+ return result;
142
+ };
143
+ OpenFeatureSplitProvider.prototype.parseValidJsonObject = function (stringValue) {
144
+ if (stringValue === undefined) {
145
+ throw new ParseError("Invalid 'undefined' JSON value.");
146
+ }
147
+ // we may want to allow the parsing to be customized.
148
+ try {
149
+ var value = JSON.parse(stringValue);
150
+ if (typeof value !== "object") {
151
+ throw new ParseError("Flag value ".concat(stringValue, " had unexpected type ").concat(typeof value, ", expected \"object\""));
152
+ }
153
+ return value;
154
+ }
155
+ catch (err) {
156
+ throw new ParseError("Error parsing ".concat(stringValue, " as JSON, ").concat(err));
157
+ }
158
+ };
159
+ OpenFeatureSplitProvider.prototype.eventsHandler = function (onSdkReady, onSdkTimedOut) {
160
+ return __awaiter(this, void 0, void 0, function () {
161
+ var onSdkReadyFromCache, clientStatus;
162
+ var _this = this;
163
+ return __generator(this, function (_a) {
164
+ onSdkReadyFromCache = function () {
165
+ _this.events.emit(ProviderEvents.Stale, {
166
+ message: "Split ready from cache",
167
+ });
168
+ };
169
+ clientStatus = this.client.__getStatus();
170
+ if (clientStatus.isReady) {
171
+ onSdkReady();
172
+ }
173
+ else {
174
+ if (clientStatus.isReadyFromCache) {
175
+ onSdkReadyFromCache();
176
+ }
177
+ else {
178
+ this.client.on(this.client.Event.SDK_READY_FROM_CACHE, onSdkReadyFromCache);
179
+ }
180
+ if (clientStatus.hasTimedout) {
181
+ onSdkTimedOut();
182
+ }
183
+ else {
184
+ this.client.on(this.client.Event.SDK_READY_TIMED_OUT, onSdkTimedOut);
185
+ }
186
+ this.client.on(this.client.Event.SDK_READY, onSdkReady);
187
+ }
188
+ this.client.on(this.client.Event.SDK_UPDATE, function () {
189
+ _this.events.emit(ProviderEvents.ConfigurationChanged);
190
+ });
191
+ return [2 /*return*/];
192
+ });
193
+ });
194
+ };
195
+ return OpenFeatureSplitProvider;
196
+ }());
197
+ export { OpenFeatureSplitProvider };
package/lib/index.js ADDED
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ var tslib_1 = require("tslib");
4
+ tslib_1.__exportStar(require("./lib/js-split-provider"), exports);
@@ -0,0 +1,200 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.OpenFeatureSplitProvider = void 0;
4
+ var tslib_1 = require("tslib");
5
+ /* eslint-disable @typescript-eslint/no-explicit-any */
6
+ /* eslint-disable @typescript-eslint/no-unused-vars */
7
+ var web_sdk_1 = require("@openfeature/web-sdk");
8
+ var CONTROL_VALUE_ERROR_MESSAGE = "Received the 'control' value from Split.";
9
+ var CONTROL_TREATMENT = 'control';
10
+ var OpenFeatureSplitProvider = /** @class */ (function () {
11
+ function OpenFeatureSplitProvider(splitFactory) {
12
+ this.metadata = {
13
+ name: "split",
14
+ };
15
+ this.events = new web_sdk_1.OpenFeatureEventEmitter();
16
+ // Asume 'user' as default traffic type'
17
+ this.trafficType = 'user';
18
+ this.factory = splitFactory;
19
+ this.client = splitFactory.client();
20
+ }
21
+ OpenFeatureSplitProvider.prototype.onContextChange = function (oldContext, newContext) {
22
+ var _this = this;
23
+ var oldTargetingKey = oldContext.targetingKey;
24
+ var newTargetingKey = newContext.targetingKey, newTrafficType = newContext.trafficType;
25
+ this.trafficType = newTrafficType && newTrafficType !== this.trafficType ? newTrafficType : this.trafficType;
26
+ if (newTargetingKey && newTargetingKey !== oldTargetingKey) {
27
+ this.client = this.factory.client(newTargetingKey);
28
+ return new Promise(function (resolve, reject) {
29
+ var emitContextChange = function () {
30
+ _this.events.emit(web_sdk_1.ProviderEvents.ConfigurationChanged);
31
+ resolve();
32
+ };
33
+ _this.eventsHandler(emitContextChange, reject);
34
+ });
35
+ }
36
+ return Promise.resolve();
37
+ };
38
+ OpenFeatureSplitProvider.prototype.initialize = function () {
39
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
40
+ var _this = this;
41
+ return tslib_1.__generator(this, function (_a) {
42
+ switch (_a.label) {
43
+ case 0: return [4 /*yield*/, new Promise(function (resolve, reject) {
44
+ try {
45
+ _this.eventsHandler(resolve, reject);
46
+ }
47
+ catch (_a) {
48
+ reject();
49
+ }
50
+ })];
51
+ case 1:
52
+ _a.sent();
53
+ return [2 /*return*/];
54
+ }
55
+ });
56
+ });
57
+ };
58
+ OpenFeatureSplitProvider.prototype.resolveBooleanEvaluation = function (flagKey, _, context, _logger) {
59
+ var details = this.evaluateTreatment(flagKey, this.transformContext(context));
60
+ var treatment = details.value.toLowerCase();
61
+ if (treatment === 'on' || treatment === 'true') {
62
+ return tslib_1.__assign(tslib_1.__assign({}, details), { value: true });
63
+ }
64
+ if (treatment === 'off' || treatment === 'false') {
65
+ return tslib_1.__assign(tslib_1.__assign({}, details), { value: false });
66
+ }
67
+ throw new web_sdk_1.ParseError("Invalid boolean value for ".concat(treatment));
68
+ };
69
+ OpenFeatureSplitProvider.prototype.resolveStringEvaluation = function (flagKey, _, context, _logger) {
70
+ var details = this.evaluateTreatment(flagKey, this.transformContext(context));
71
+ return details;
72
+ };
73
+ OpenFeatureSplitProvider.prototype.resolveNumberEvaluation = function (flagKey, _, context, _logger) {
74
+ var details = this.evaluateTreatment(flagKey, this.transformContext(context));
75
+ return tslib_1.__assign(tslib_1.__assign({}, details), { value: this.parseValidNumber(details.value) });
76
+ };
77
+ OpenFeatureSplitProvider.prototype.resolveObjectEvaluation = function (flagKey, _, context, _logger) {
78
+ var details = this.evaluateTreatment(flagKey, this.transformContext(context));
79
+ return tslib_1.__assign(tslib_1.__assign({}, details), { value: this.parseValidJsonObject(details.value) });
80
+ };
81
+ OpenFeatureSplitProvider.prototype.evaluateTreatment = function (flagKey, consumer) {
82
+ if (flagKey == null || flagKey === '') {
83
+ throw new web_sdk_1.FlagNotFoundError('flagKey must be a non-empty string');
84
+ }
85
+ var treatment = this.client.getTreatmentWithConfig(flagKey, consumer.attributes);
86
+ var value = treatment.treatment, config = treatment.config;
87
+ if (value === CONTROL_TREATMENT) {
88
+ throw new web_sdk_1.FlagNotFoundError(CONTROL_VALUE_ERROR_MESSAGE);
89
+ }
90
+ var flagMetadata = { config: config ? config : '' };
91
+ var details = {
92
+ value: value,
93
+ variant: value,
94
+ flagMetadata: flagMetadata,
95
+ reason: web_sdk_1.StandardResolutionReasons.TARGETING_MATCH,
96
+ };
97
+ return details;
98
+ };
99
+ OpenFeatureSplitProvider.prototype.track = function (trackingEventName, context, details) {
100
+ // eventName is always required
101
+ if (trackingEventName == null || trackingEventName === '')
102
+ throw new web_sdk_1.ParseError('Missing eventName, required to track');
103
+ var trafficType = this.transformContext(context).trafficType;
104
+ var value;
105
+ var properties = {};
106
+ if (details != null) {
107
+ if (details.value != null) {
108
+ value = details.value;
109
+ }
110
+ if (details.properties != null) {
111
+ properties = details.properties;
112
+ }
113
+ }
114
+ this.client.track(trafficType, trackingEventName, value, properties);
115
+ };
116
+ OpenFeatureSplitProvider.prototype.onClose = function () {
117
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
118
+ return tslib_1.__generator(this, function (_a) {
119
+ return [2 /*return*/, this.factory.destroy()];
120
+ });
121
+ });
122
+ };
123
+ //Transform the context into an object useful for the Split API, an key string with arbitrary Split "Attributes".
124
+ OpenFeatureSplitProvider.prototype.transformContext = function (context) {
125
+ var targetingKey = context.targetingKey, ttVal = context.trafficType, attributes = tslib_1.__rest(context, ["targetingKey", "trafficType"]);
126
+ var trafficType = ttVal != null && typeof ttVal === 'string' && ttVal.trim() !== ''
127
+ ? ttVal
128
+ : this.trafficType;
129
+ return {
130
+ targetingKey: targetingKey,
131
+ trafficType: trafficType,
132
+ // Stringify context objects include date.
133
+ attributes: JSON.parse(JSON.stringify(attributes)),
134
+ };
135
+ };
136
+ OpenFeatureSplitProvider.prototype.parseValidNumber = function (stringValue) {
137
+ if (stringValue === undefined) {
138
+ throw new web_sdk_1.ParseError("Invalid 'undefined' value.");
139
+ }
140
+ var result = Number.parseFloat(stringValue);
141
+ if (Number.isNaN(result)) {
142
+ throw new web_sdk_1.ParseError("Invalid numeric value ".concat(stringValue));
143
+ }
144
+ return result;
145
+ };
146
+ OpenFeatureSplitProvider.prototype.parseValidJsonObject = function (stringValue) {
147
+ if (stringValue === undefined) {
148
+ throw new web_sdk_1.ParseError("Invalid 'undefined' JSON value.");
149
+ }
150
+ // we may want to allow the parsing to be customized.
151
+ try {
152
+ var value = JSON.parse(stringValue);
153
+ if (typeof value !== "object") {
154
+ throw new web_sdk_1.ParseError("Flag value ".concat(stringValue, " had unexpected type ").concat(typeof value, ", expected \"object\""));
155
+ }
156
+ return value;
157
+ }
158
+ catch (err) {
159
+ throw new web_sdk_1.ParseError("Error parsing ".concat(stringValue, " as JSON, ").concat(err));
160
+ }
161
+ };
162
+ OpenFeatureSplitProvider.prototype.eventsHandler = function (onSdkReady, onSdkTimedOut) {
163
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
164
+ var onSdkReadyFromCache, clientStatus;
165
+ var _this = this;
166
+ return tslib_1.__generator(this, function (_a) {
167
+ onSdkReadyFromCache = function () {
168
+ _this.events.emit(web_sdk_1.ProviderEvents.Stale, {
169
+ message: "Split ready from cache",
170
+ });
171
+ };
172
+ clientStatus = this.client.__getStatus();
173
+ if (clientStatus.isReady) {
174
+ onSdkReady();
175
+ }
176
+ else {
177
+ if (clientStatus.isReadyFromCache) {
178
+ onSdkReadyFromCache();
179
+ }
180
+ else {
181
+ this.client.on(this.client.Event.SDK_READY_FROM_CACHE, onSdkReadyFromCache);
182
+ }
183
+ if (clientStatus.hasTimedout) {
184
+ onSdkTimedOut();
185
+ }
186
+ else {
187
+ this.client.on(this.client.Event.SDK_READY_TIMED_OUT, onSdkTimedOut);
188
+ }
189
+ this.client.on(this.client.Event.SDK_READY, onSdkReady);
190
+ }
191
+ this.client.on(this.client.Event.SDK_UPDATE, function () {
192
+ _this.events.emit(web_sdk_1.ProviderEvents.ConfigurationChanged);
193
+ });
194
+ return [2 /*return*/];
195
+ });
196
+ });
197
+ };
198
+ return OpenFeatureSplitProvider;
199
+ }());
200
+ exports.OpenFeatureSplitProvider = OpenFeatureSplitProvider;
package/package.json ADDED
@@ -0,0 +1,78 @@
1
+ {
2
+ "name": "@splitsoftware/openfeature-web-split-provider",
3
+ "version": "1.0.0",
4
+ "description": "Split OpenFeature Web Provider",
5
+ "files": [
6
+ "README.md",
7
+ "CONTRIBUTORS-GUIDE.md",
8
+ "LICENSE",
9
+ "CHANGES.txt",
10
+ "lib",
11
+ "types",
12
+ "es",
13
+ "src"
14
+ ],
15
+ "repository": "splitio/split-openfeature-provider-web-js",
16
+ "homepage": "https://github.com/splitio/split-openfeature-provider-web-js#readme",
17
+ "bugs": "https://github.com/splitio/split-openfeature-provider-web-js/issues",
18
+ "license": "Apache-2.0",
19
+ "author": "Josh Sirota <josh.sirota@split.io>",
20
+ "contributors": [
21
+ "Nicolas Zelaya <nicolas.zelaya@harness.io> (https://github.com/NicoZelaya)",
22
+ "Emiliano Sanchez <emiliano.sanchez@harness.io> (https://github.com/EmilianoSanchez)",
23
+ "Emmanuel Zamora <emmanuel.zamora@harness.io> (https://github.com/ZamoraEmmanuel)",
24
+ "SDK Team <sdks@harness.io>"
25
+ ],
26
+ "main": "lib/index.js",
27
+ "module": "es/index.js",
28
+ "browser": "lib/index.js",
29
+ "types": "types/index.d.ts",
30
+ "engines": {
31
+ "npm": ">=3"
32
+ },
33
+ "peerDependencies": {
34
+ "@openfeature/web-sdk": "^1.6.1",
35
+ "@splitsoftware/splitio-browserjs": "^1.4.0"
36
+ },
37
+ "devDependencies": {
38
+ "@eslint/js": "^9.35.0",
39
+ "@openfeature/web-sdk": "^1.6.1",
40
+ "@splitsoftware/splitio-browserjs": "^1.4.0",
41
+ "copyfiles": "^2.4.1",
42
+ "cross-env": "^7.0.3",
43
+ "eslint": "^9.35.0",
44
+ "eslint-plugin-jest": "^28.14.0",
45
+ "globals": "^16.4.0",
46
+ "jest": "^29.7.0",
47
+ "jest-environment-jsdom": "^29.7.0",
48
+ "jest-fetch-mock": "^3.0.3",
49
+ "jiti": "^2.5.1",
50
+ "replace": "^1.2.1",
51
+ "rimraf": "^3.0.2",
52
+ "ts-jest": "^29.4.1",
53
+ "typescript": "^4.9.5",
54
+ "typescript-eslint": "^8.43.0"
55
+ },
56
+ "scripts": {
57
+ "build-esm": "rimraf es && tsc -outDir es",
58
+ "postbuild-esm": "cross-env NODE_ENV=es node scripts/copy.packages.json.js && ./scripts/build_esm_replace_imports.sh",
59
+ "build-cjs": "rimraf lib && tsc -outDir lib -m CommonJS",
60
+ "postbuild-cjs": "cross-env NODE_ENV=cjs node scripts/copy.packages.json.js && ./scripts/build_cjs_replace_imports.sh",
61
+ "check": "npm run check:lint",
62
+ "check:lint": "eslint src",
63
+ "build": "rimraf lib es && npm run build-cjs && npm run build-esm",
64
+ "pretest-ts-decls": "npm run build-esm && npm run build-cjs && npm link",
65
+ "test-ts-decls": "./scripts/ts-tests.sh",
66
+ "posttest-ts-decls": "npm unlink && npm install",
67
+ "test": "jest --testPathIgnorePatterns=node_modules/ -c jest.config.js",
68
+ "publish:rc": "npm run check && npm run build && npm publish --tag canary",
69
+ "publish:stable": "npm run check && npm run build && npm publish"
70
+ },
71
+ "greenkeeper": {
72
+ "ignore": [
73
+ "karma",
74
+ "karma-tap",
75
+ "karma-webpack"
76
+ ]
77
+ }
78
+ }