featurehub-openfeature-web-sdk 0.0.0-stage → 1.0.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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 FeatureHub
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,197 @@
1
- # Temporary Holding Version
1
+ # FeatureHub OpenFeature Provider — Web
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Official [OpenFeature](https://openfeature.dev) provider for [FeatureHub](https://featurehub.io), for browsers.
4
+
5
+ FeatureHub always evaluates features against a **local copy of the features**: the full feature bundle (including rollout strategies) is fetched from Edge and cached, and every OpenFeature resolution is evaluated in-memory. The browser never asks the server per evaluation — it only contacts Edge to fetch or refresh the bundle (on the update interval, or in passive mode when a resolution happens after the cached bundle has expired). There is no concept of a price per evaluation.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ npm install featurehub-openfeature-web-sdk @openfeature/web-sdk
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ Set the evaluation context before registering the provider, so the first evaluations already use it:
16
+
17
+ ```ts
18
+ import { OpenFeature } from "@openfeature/web-sdk";
19
+ import { FeatureHubWebProvider } from "featurehub-openfeature-web-sdk";
20
+
21
+ // 1. Create the provider
22
+ const provider = new FeatureHubWebProvider({
23
+ host: "https://edge.featurehub.io",
24
+ apiKey: "your-client-evaluated-key", // must contain `*`
25
+ });
26
+
27
+ // 2. Set the evaluation context (e.g. user targeting attributes)
28
+ await OpenFeature.setContext({
29
+ targetingKey: "user-123",
30
+ plan: "enterprise",
31
+ });
32
+
33
+ // 3. Register the provider and wait for it to initialize
34
+ await OpenFeature.setProviderAndWait(provider);
35
+
36
+ const client = OpenFeature.getClient();
37
+ const enabled = client.getBooleanValue("checkout-v2", false);
38
+ ```
39
+
40
+ Only **client-evaluated** keys (containing `*`) are accepted; the constructor throws for server-evaluated keys, because the OpenFeature web paradigm resolves synchronously.
41
+
42
+ ## Transport
43
+
44
+ The default transport is **REST passive**: Edge is only contacted when a resolution happens after the cached bundle has expired. That avoids a long-lived SSE connection (or constant polling) per browser tab. Opt in to the others with `transport: "streaming"` (SSE) or `pollIntervalMs`.
45
+
46
+ The provider keeps a single evaluation context: it is created in `initialize`, rebuilt on `onContextChange`, and reused across resolutions. As the key is client-evaluated, the bundle holds every strategy, so a context change is applied locally and fetches nothing.
47
+
48
+ ## Options
49
+
50
+ | Option | Description |
51
+ | --- | --- |
52
+ | `host` | FeatureHub Edge base URL. |
53
+ | `apiKey` | Client-evaluated FeatureHub SDK API key (must contain `*`). |
54
+ | `transport` | `"passive"` (default), `"streaming"` or `"polling"`. |
55
+ | `pollIntervalMs` | REST active polling interval; implies `transport: "polling"`. |
56
+ | `cacheTimeToLiveMs` | REST passive cache TTL; implies `transport: "passive"`. |
57
+ | `waitForReadyMs` | How long `initialize` waits for the first feature payload. Default 10s. |
58
+ | `configFactory` | Supply a pre-built config (used by tests). |
59
+
60
+ ## Resolution
61
+
62
+ Every resolution is evaluated locally against the current context. It reports `SPLIT` for a percentage rollout and `TARGETING_MATCH` for any other matched strategy, each with the strategy id as `variant`; `STATIC` when no strategy applies; and `DISABLED`, with the code default, for a feature that has no value. A value supplied as a string (by a value interceptor, say) is converted to the type asked for: `"true"` and `"false"` for a boolean, a numeric string for a number. Errors use the standard OpenFeature codes (`FLAG_NOT_FOUND`, `TYPE_MISMATCH`, `PARSE_ERROR`, `INVALID_CONTEXT`, `PROVIDER_NOT_READY`, `PROVIDER_FATAL`). Flag metadata holds the feature's properties, plus `featureVersion` and `featureType`.
63
+
64
+ ## Tracking
65
+
66
+ `client.track(name, details)` records a FeatureHub named usage event, with the current context's attributes and the details, for the usage plugins registered on the config (through `configFactory`). Without a usage plugin it goes nowhere.
67
+
68
+ ## Events
69
+
70
+ `PROVIDER_CONFIGURATION_CHANGED` is emitted with the keys of the features that changed: a new version, a feature added, or one deleted or no longer in a full set.
71
+
72
+ If the connection to FeatureHub stops for good once features have arrived (the API key is rejected, or FeatureHub says the environment is stale), the provider emits `PROVIDER_STALE`, once, and keeps resolving from the last features it received. This also happens if the connection stops with the very first response: initialisation succeeds, and `PROVIDER_STALE` follows `PROVIDER_READY`. If the connection is rejected before any features arrive, initialisation fails as `PROVIDER_FATAL`.
73
+
74
+ ## Migrating from the FeatureHub browser SDK
75
+
76
+ The provider is built on `featurehub-javascript-client-sdk`, so your features, API key and rollout strategies carry over unchanged: only the code that reads them changes, from the SDK's API to OpenFeature's. Each feature is evaluated locally, exactly as before.
77
+
78
+ It needs a **client-evaluated** key (containing `*`). If your app uses a server-evaluated key, keep using the SDK: OpenFeature's web paradigm resolves synchronously, which a key evaluated by FeatureHub cannot support.
79
+
80
+ ### Setting up
81
+
82
+ Before:
83
+
84
+ ```ts
85
+ import { EdgeFeatureHubConfig, FeatureHub } from "featurehub-javascript-client-sdk";
86
+
87
+ const fhConfig = new EdgeFeatureHubConfig("https://edge.example.com", "default/abc123/key*secret");
88
+ fhConfig.restActive(30000);
89
+ const context = await fhConfig.newContext().userKey("user-123").attributeValue("plan", "enterprise").build();
90
+ FeatureHub.set(fhConfig, context);
91
+ ```
92
+
93
+ After:
94
+
95
+ ```ts
96
+ import { OpenFeature } from "@openfeature/web-sdk";
97
+ import { FeatureHubWebProvider } from "featurehub-openfeature-web-sdk";
98
+
99
+ await OpenFeature.setContext({ targetingKey: "user-123", plan: "enterprise" });
100
+ await OpenFeature.setProviderAndWait(
101
+ new FeatureHubWebProvider({
102
+ host: "https://edge.example.com",
103
+ apiKey: "default/abc123/key*secret",
104
+ pollIntervalMs: 30000,
105
+ }),
106
+ );
107
+ const client = OpenFeature.getClient();
108
+ ```
109
+
110
+ | FeatureHub SDK | Provider |
111
+ | --- | --- |
112
+ | `new EdgeFeatureHubConfig(url, apiKey)` | `new FeatureHubWebProvider({ host, apiKey })` |
113
+ | `fhConfig.restActive(30000)` (the SDK's default mode) | `pollIntervalMs: 30000`. Note the provider's default is passive, not active polling |
114
+ | `fhConfig.restPassive(30000)` | `cacheTimeToLiveMs: 30000` (or `transport: "passive"`) |
115
+ | `fhConfig.streaming()` | `transport: "streaming"` |
116
+ | `await fhConfig.waitForReady()` | `await OpenFeature.setProviderAndWait(provider)`; `waitForReadyMs` sets how long it waits |
117
+ | `fhConfig.close()` | `await OpenFeature.close()` |
118
+
119
+ ### Contexts and reading features
120
+
121
+ The SDK reads features from a context you build. With OpenFeature the context is set for the whole app (`OpenFeature.setContext`), and each read is synchronous. Changing the context later (a user signing in, say) is another `setContext`; as the key is client-evaluated, it is applied locally and nothing is fetched. OpenFeature always returns the default you give when a feature is missing or has no value, where the SDK returns `undefined`.
122
+
123
+ Before:
124
+
125
+ ```ts
126
+ if (context.isEnabled("checkout-v2")) {
127
+ const banner = context.getString("banner-text") ?? "Welcome";
128
+ }
129
+ ```
130
+
131
+ After:
132
+
133
+ ```ts
134
+ if (client.getBooleanValue("checkout-v2", false)) {
135
+ const banner = client.getStringValue("banner-text", "Welcome");
136
+ }
137
+ ```
138
+
139
+ | FeatureHub SDK | OpenFeature |
140
+ | --- | --- |
141
+ | `.userKey("user-123")` | `targetingKey: "user-123"` |
142
+ | `.sessionKey(id)` | `session: id` |
143
+ | `.country(...)`, `.device(...)`, `.platform(...)`, `.version(...)` | `country`, `device`, `platform`, `version`, as the enum's string value (`StrategyAttributeDeviceName.Browser` is `"browser"`) |
144
+ | `.attributeValue("plan", "enterprise")` | `plan: "enterprise"`; a list of strings, numbers, booleans or dates is fine, a nested object is `INVALID_CONTEXT`. Keys other than the well-known ones keep their case, and `fhubWhenActive` is ignored, as only a strategy may set it |
145
+ | a `Date` attribute value | the same `Date` (or a list of them); it is evaluated, and sent to FeatureHub, as UTC to the second |
146
+ | `context.isEnabled(key)`, `getFlag(key)`, `getBoolean(key)` | `client.getBooleanValue(key, false)` |
147
+ | `context.getString(key)` | `client.getStringValue(key, default)` |
148
+ | `context.getNumber(key)` | `client.getNumberValue(key, default)` |
149
+ | `context.getJson(key)` | `client.getObjectValue(key, default)`; the value must be a JSON object |
150
+ | `context.getRawJson(key)` | no equivalent: OpenFeature only gives the parsed object |
151
+ | `context.recordNamedUsage(name, params)` | `client.track(name, params)` ([Tracking](#tracking)) |
152
+ | `context.isSet(key)` | `get...Details(...)`: `errorCode` is `FLAG_NOT_FOUND` if the feature does not exist; `reason` is `DISABLED` if it exists with no value |
153
+ | the strategy that matched (`feature(key).getValue().strategyId`) | `details.variant`, with `details.reason` (`SPLIT`, `TARGETING_MATCH` or `STATIC`) |
154
+ | `feature(key).featureProperties` | `details.flagMetadata`, which also holds `featureVersion` and `featureType` |
155
+ | `feature(key).locked` | no equivalent |
156
+
157
+ ### Listening for changes
158
+
159
+ | FeatureHub SDK | OpenFeature |
160
+ | --- | --- |
161
+ | `fhConfig.addReadinessListener(...)` | `client.addHandler(ProviderEvents.Ready, ...)`, and `client.providerStatus` |
162
+ | readiness `Failed` | `setProviderAndWait` rejects, and `providerStatus` is `FATAL` |
163
+ | `fhConfig.addConnectionEventListener(...)` | `client.addHandler(ProviderEvents.Stale, ...)` |
164
+ | `feature(key).addListener(...)` | `client.addHandler(ProviderEvents.ConfigurationChanged, (details) => ...)`; `details.flagsChanged` lists the keys, so read the ones you need again |
165
+
166
+ ### Interceptors, stores and usage plugins
167
+
168
+ Value interceptors (such as the browser's session overrides), feature stores and usage plugins are attached to the FeatureHub config, which the provider creates. Pass `configFactory` to create it yourself and attach them; the provider still applies its transport options to it and starts it, so do not call `init()`:
169
+
170
+ ```ts
171
+ import { EdgeFeatureHubConfig } from "featurehub-javascript-client-sdk";
172
+ import { LocalSessionStore } from "featurehub-store-localstorage";
173
+
174
+ const provider = new FeatureHubWebProvider({
175
+ host: "https://edge.example.com",
176
+ apiKey: "default/abc123/key*secret",
177
+ configFactory: ({ host, apiKey }) => {
178
+ const config = new EdgeFeatureHubConfig(host, apiKey);
179
+ new LocalSessionStore(config); // features from the last visit are available at once
180
+ return config;
181
+ },
182
+ });
183
+ ```
184
+
185
+ A value an interceptor supplies as a string is converted to the type you ask for.
186
+
187
+ ### React
188
+
189
+ OpenFeature's React SDK (`@openfeature/react-sdk`) works with this provider, in place of `featurehub-react-sdk`.
190
+
191
+ ### What stays with the SDK
192
+
193
+ Keep using the SDK directly for catch-and-release (holding feature updates back until the app chooses to show them), a server-evaluated key, the repository itself (raw feature updates, `simpleFeatures()`), a feature's lock, and raw JSON.
194
+
195
+ ## License
196
+
197
+ MIT
package/dist/index.cjs ADDED
@@ -0,0 +1,140 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ FeatureHubWebProvider: () => FeatureHubWebProvider,
24
+ InvalidContextError: () => import_featurehub_openfeature_common2.InvalidContextError,
25
+ mapEvaluationContext: () => import_featurehub_openfeature_common2.mapEvaluationContext,
26
+ toContextRecord: () => import_featurehub_openfeature_common2.toContextRecord
27
+ });
28
+ module.exports = __toCommonJS(index_exports);
29
+
30
+ // src/provider.ts
31
+ var import_web_sdk = require("@openfeature/web-sdk");
32
+ var import_featurehub_javascript_client_sdk = require("featurehub-javascript-client-sdk");
33
+ var import_featurehub_openfeature_common = require("featurehub-openfeature-common");
34
+ var FeatureHubWebProvider = class extends import_featurehub_openfeature_common.FeatureHubProviderCore {
35
+ metadata = { name: "featurehub" };
36
+ runsOn = "client";
37
+ events = new import_web_sdk.OpenFeatureEventEmitter();
38
+ /**
39
+ * The single FeatureHub context the web paradigm evaluates against; created
40
+ * in `initialize`, rebuilt on `onContextChange`, and reused across
41
+ * resolutions.
42
+ */
43
+ context;
44
+ currentSignature;
45
+ constructor(options) {
46
+ super("FeatureHubWebProvider", options);
47
+ if (!this.clientEval) {
48
+ throw new Error(
49
+ "FeatureHubWebProvider requires a client-evaluated API key (containing '*'). Server-evaluated keys cannot be resolved synchronously in a browser."
50
+ );
51
+ }
52
+ }
53
+ get eventSink() {
54
+ return this.events;
55
+ }
56
+ get defaultTransport() {
57
+ return "passive";
58
+ }
59
+ createConfig() {
60
+ return new import_featurehub_javascript_client_sdk.EdgeFeatureHubConfig(this.host, this.apiKey);
61
+ }
62
+ async initialize(context) {
63
+ (0, import_featurehub_openfeature_common.toContextRecord)(context);
64
+ const cfg = this.startConfig();
65
+ this.applyContext(context);
66
+ await this.awaitReady(cfg);
67
+ }
68
+ /** Keeps the single evaluation context in step with the OpenFeature client context. */
69
+ onContextChange(_oldContext, newContext) {
70
+ if (this.config) {
71
+ this.applyContext(newContext);
72
+ }
73
+ }
74
+ resolveBooleanEvaluation(flagKey, defaultValue, context, logger) {
75
+ return this.resolve(
76
+ flagKey,
77
+ context,
78
+ "boolean",
79
+ defaultValue,
80
+ logger
81
+ );
82
+ }
83
+ resolveStringEvaluation(flagKey, defaultValue, context, logger) {
84
+ return this.resolve(
85
+ flagKey,
86
+ context,
87
+ "string",
88
+ defaultValue,
89
+ logger
90
+ );
91
+ }
92
+ resolveNumberEvaluation(flagKey, defaultValue, context, logger) {
93
+ return this.resolve(
94
+ flagKey,
95
+ context,
96
+ "number",
97
+ defaultValue,
98
+ logger
99
+ );
100
+ }
101
+ resolveObjectEvaluation(flagKey, defaultValue, context, logger) {
102
+ return this.resolve(flagKey, context, "object", defaultValue, logger);
103
+ }
104
+ resolve(flagKey, context, kind, defaultValue, logger) {
105
+ return this.resolveSync(
106
+ flagKey,
107
+ kind,
108
+ defaultValue,
109
+ logger,
110
+ () => (0, import_featurehub_openfeature_common.captureFeature)(this.contextFor(context).feature(flagKey))
111
+ );
112
+ }
113
+ /**
114
+ * Returns the single stored context. It is rebuilt when the supplied context
115
+ * differs from the stored one — normally `onContextChange` has already done
116
+ * this, but a context set before the provider was registered still self-heals
117
+ * here without rebuilding on every resolution.
118
+ */
119
+ contextFor(context) {
120
+ const signature = (0, import_featurehub_openfeature_common.contextSignature)(context);
121
+ if (!this.context || signature !== this.currentSignature) {
122
+ this.applyContext(context);
123
+ }
124
+ return this.context;
125
+ }
126
+ applyContext(context) {
127
+ this.context = this.config.context((0, import_featurehub_openfeature_common.toContextRecord)(context));
128
+ this.currentSignature = (0, import_featurehub_openfeature_common.contextSignature)(context);
129
+ }
130
+ };
131
+
132
+ // src/index.ts
133
+ var import_featurehub_openfeature_common2 = require("featurehub-openfeature-common");
134
+ // Annotate the CommonJS export names for ESM import in node:
135
+ 0 && (module.exports = {
136
+ FeatureHubWebProvider,
137
+ InvalidContextError,
138
+ mapEvaluationContext,
139
+ toContextRecord
140
+ });
@@ -0,0 +1,73 @@
1
+ import { Provider, ProviderMetadata, OpenFeatureEventEmitter, EvaluationContext, Logger, ResolutionDetails, JsonValue } from '@openfeature/web-sdk';
2
+ import { FeatureHubConfig } from 'featurehub-javascript-client-sdk';
3
+ import { FeatureHubProviderCore, BaseProviderOptions, ProviderEventSink, Transport } from 'featurehub-openfeature-common';
4
+ export { ContextAttribute, InvalidContextError, MappedContext, mapEvaluationContext, toContextRecord } from 'featurehub-openfeature-common';
5
+
6
+ interface FeatureHubWebProviderOptions extends BaseProviderOptions<FeatureHubWebProviderOptions> {
7
+ /** Base URL of FeatureHub Edge, e.g. `https://edge.featurehub.io`. */
8
+ host?: string;
9
+ /**
10
+ * A **client-evaluated** FeatureHub API key (contains `*`): the full feature
11
+ * bundle — including rollout strategies — is delivered to the browser and
12
+ * every OpenFeature resolution is evaluated locally. Server-evaluated keys
13
+ * are not supported by this provider because the OpenFeature web paradigm
14
+ * resolves synchronously.
15
+ *
16
+ * With no host and no key, a `configFactory` can supply a config whose features come from stores.
17
+ */
18
+ apiKey?: string;
19
+ /** How long `initialize` waits for the first feature payload. Default 10s. */
20
+ waitForReadyMs?: number;
21
+ /**
22
+ * Build the FeatureHub config yourself, to attach value interceptors, feature stores and usage plugins.
23
+ */
24
+ configFactory?: (options: FeatureHubWebProviderOptions) => FeatureHubConfig;
25
+ }
26
+ /**
27
+ * Official OpenFeature provider for FeatureHub (Web/browser).
28
+ *
29
+ * The provider holds no evaluation logic of its own: it drives a
30
+ * [FeatureHubConfig]{@link FeatureHubConfig}, which keeps the entire feature
31
+ * bundle in a local repository, and every OpenFeature resolution is evaluated
32
+ * locally against the current context — never with a per-flag network call.
33
+ *
34
+ * Because this runs in a browser, the default transport is REST passive: Edge
35
+ * is only contacted when a resolution happens after the cached bundle has
36
+ * expired, which avoids a long-lived SSE connection (or constant polling) per
37
+ * tab. Set `transport: "streaming"` or `pollIntervalMs` to opt in to those.
38
+ */
39
+ declare class FeatureHubWebProvider extends FeatureHubProviderCore<FeatureHubWebProviderOptions> implements Provider {
40
+ readonly metadata: ProviderMetadata;
41
+ readonly runsOn: "client";
42
+ readonly events: OpenFeatureEventEmitter;
43
+ /**
44
+ * The single FeatureHub context the web paradigm evaluates against; created
45
+ * in `initialize`, rebuilt on `onContextChange`, and reused across
46
+ * resolutions.
47
+ */
48
+ private context?;
49
+ private currentSignature?;
50
+ constructor(options: FeatureHubWebProviderOptions);
51
+ protected get eventSink(): ProviderEventSink;
52
+ protected get defaultTransport(): Transport;
53
+ protected createConfig(): FeatureHubConfig;
54
+ initialize(context?: EvaluationContext): Promise<void>;
55
+ /** Keeps the single evaluation context in step with the OpenFeature client context. */
56
+ onContextChange(_oldContext: EvaluationContext, newContext: EvaluationContext): void;
57
+ resolveBooleanEvaluation(flagKey: string, defaultValue: boolean, context: EvaluationContext, logger: Logger): ResolutionDetails<boolean>;
58
+ resolveStringEvaluation(flagKey: string, defaultValue: string, context: EvaluationContext, logger: Logger): ResolutionDetails<string>;
59
+ resolveNumberEvaluation(flagKey: string, defaultValue: number, context: EvaluationContext, logger: Logger): ResolutionDetails<number>;
60
+ resolveObjectEvaluation<T extends JsonValue>(flagKey: string, defaultValue: T, context: EvaluationContext, logger: Logger): ResolutionDetails<T>;
61
+ private resolve;
62
+ /**
63
+ * Returns the single stored context. It is rebuilt when the supplied context
64
+ * differs from the stored one — normally `onContextChange` has already done
65
+ * this, but a context set before the provider was registered still self-heals
66
+ * here without rebuilding on every resolution.
67
+ */
68
+ private contextFor;
69
+ private applyContext;
70
+ }
71
+
72
+ export { FeatureHubWebProvider, type FeatureHubWebProviderOptions };
73
+ declare module 'featurehub-openfeature-web-sdk'
@@ -0,0 +1,73 @@
1
+ import { Provider, ProviderMetadata, OpenFeatureEventEmitter, EvaluationContext, Logger, ResolutionDetails, JsonValue } from '@openfeature/web-sdk';
2
+ import { FeatureHubConfig } from 'featurehub-javascript-client-sdk';
3
+ import { FeatureHubProviderCore, BaseProviderOptions, ProviderEventSink, Transport } from 'featurehub-openfeature-common';
4
+ export { ContextAttribute, InvalidContextError, MappedContext, mapEvaluationContext, toContextRecord } from 'featurehub-openfeature-common';
5
+
6
+ interface FeatureHubWebProviderOptions extends BaseProviderOptions<FeatureHubWebProviderOptions> {
7
+ /** Base URL of FeatureHub Edge, e.g. `https://edge.featurehub.io`. */
8
+ host?: string;
9
+ /**
10
+ * A **client-evaluated** FeatureHub API key (contains `*`): the full feature
11
+ * bundle — including rollout strategies — is delivered to the browser and
12
+ * every OpenFeature resolution is evaluated locally. Server-evaluated keys
13
+ * are not supported by this provider because the OpenFeature web paradigm
14
+ * resolves synchronously.
15
+ *
16
+ * With no host and no key, a `configFactory` can supply a config whose features come from stores.
17
+ */
18
+ apiKey?: string;
19
+ /** How long `initialize` waits for the first feature payload. Default 10s. */
20
+ waitForReadyMs?: number;
21
+ /**
22
+ * Build the FeatureHub config yourself, to attach value interceptors, feature stores and usage plugins.
23
+ */
24
+ configFactory?: (options: FeatureHubWebProviderOptions) => FeatureHubConfig;
25
+ }
26
+ /**
27
+ * Official OpenFeature provider for FeatureHub (Web/browser).
28
+ *
29
+ * The provider holds no evaluation logic of its own: it drives a
30
+ * [FeatureHubConfig]{@link FeatureHubConfig}, which keeps the entire feature
31
+ * bundle in a local repository, and every OpenFeature resolution is evaluated
32
+ * locally against the current context — never with a per-flag network call.
33
+ *
34
+ * Because this runs in a browser, the default transport is REST passive: Edge
35
+ * is only contacted when a resolution happens after the cached bundle has
36
+ * expired, which avoids a long-lived SSE connection (or constant polling) per
37
+ * tab. Set `transport: "streaming"` or `pollIntervalMs` to opt in to those.
38
+ */
39
+ declare class FeatureHubWebProvider extends FeatureHubProviderCore<FeatureHubWebProviderOptions> implements Provider {
40
+ readonly metadata: ProviderMetadata;
41
+ readonly runsOn: "client";
42
+ readonly events: OpenFeatureEventEmitter;
43
+ /**
44
+ * The single FeatureHub context the web paradigm evaluates against; created
45
+ * in `initialize`, rebuilt on `onContextChange`, and reused across
46
+ * resolutions.
47
+ */
48
+ private context?;
49
+ private currentSignature?;
50
+ constructor(options: FeatureHubWebProviderOptions);
51
+ protected get eventSink(): ProviderEventSink;
52
+ protected get defaultTransport(): Transport;
53
+ protected createConfig(): FeatureHubConfig;
54
+ initialize(context?: EvaluationContext): Promise<void>;
55
+ /** Keeps the single evaluation context in step with the OpenFeature client context. */
56
+ onContextChange(_oldContext: EvaluationContext, newContext: EvaluationContext): void;
57
+ resolveBooleanEvaluation(flagKey: string, defaultValue: boolean, context: EvaluationContext, logger: Logger): ResolutionDetails<boolean>;
58
+ resolveStringEvaluation(flagKey: string, defaultValue: string, context: EvaluationContext, logger: Logger): ResolutionDetails<string>;
59
+ resolveNumberEvaluation(flagKey: string, defaultValue: number, context: EvaluationContext, logger: Logger): ResolutionDetails<number>;
60
+ resolveObjectEvaluation<T extends JsonValue>(flagKey: string, defaultValue: T, context: EvaluationContext, logger: Logger): ResolutionDetails<T>;
61
+ private resolve;
62
+ /**
63
+ * Returns the single stored context. It is rebuilt when the supplied context
64
+ * differs from the stored one — normally `onContextChange` has already done
65
+ * this, but a context set before the provider was registered still self-heals
66
+ * here without rebuilding on every resolution.
67
+ */
68
+ private contextFor;
69
+ private applyContext;
70
+ }
71
+
72
+ export { FeatureHubWebProvider, type FeatureHubWebProviderOptions };
73
+ declare module 'featurehub-openfeature-web-sdk'
package/dist/index.js ADDED
@@ -0,0 +1,119 @@
1
+ // src/provider.ts
2
+ import { OpenFeatureEventEmitter } from "@openfeature/web-sdk";
3
+ import { EdgeFeatureHubConfig } from "featurehub-javascript-client-sdk";
4
+ import {
5
+ captureFeature,
6
+ contextSignature,
7
+ FeatureHubProviderCore,
8
+ toContextRecord
9
+ } from "featurehub-openfeature-common";
10
+ var FeatureHubWebProvider = class extends FeatureHubProviderCore {
11
+ metadata = { name: "featurehub" };
12
+ runsOn = "client";
13
+ events = new OpenFeatureEventEmitter();
14
+ /**
15
+ * The single FeatureHub context the web paradigm evaluates against; created
16
+ * in `initialize`, rebuilt on `onContextChange`, and reused across
17
+ * resolutions.
18
+ */
19
+ context;
20
+ currentSignature;
21
+ constructor(options) {
22
+ super("FeatureHubWebProvider", options);
23
+ if (!this.clientEval) {
24
+ throw new Error(
25
+ "FeatureHubWebProvider requires a client-evaluated API key (containing '*'). Server-evaluated keys cannot be resolved synchronously in a browser."
26
+ );
27
+ }
28
+ }
29
+ get eventSink() {
30
+ return this.events;
31
+ }
32
+ get defaultTransport() {
33
+ return "passive";
34
+ }
35
+ createConfig() {
36
+ return new EdgeFeatureHubConfig(this.host, this.apiKey);
37
+ }
38
+ async initialize(context) {
39
+ toContextRecord(context);
40
+ const cfg = this.startConfig();
41
+ this.applyContext(context);
42
+ await this.awaitReady(cfg);
43
+ }
44
+ /** Keeps the single evaluation context in step with the OpenFeature client context. */
45
+ onContextChange(_oldContext, newContext) {
46
+ if (this.config) {
47
+ this.applyContext(newContext);
48
+ }
49
+ }
50
+ resolveBooleanEvaluation(flagKey, defaultValue, context, logger) {
51
+ return this.resolve(
52
+ flagKey,
53
+ context,
54
+ "boolean",
55
+ defaultValue,
56
+ logger
57
+ );
58
+ }
59
+ resolveStringEvaluation(flagKey, defaultValue, context, logger) {
60
+ return this.resolve(
61
+ flagKey,
62
+ context,
63
+ "string",
64
+ defaultValue,
65
+ logger
66
+ );
67
+ }
68
+ resolveNumberEvaluation(flagKey, defaultValue, context, logger) {
69
+ return this.resolve(
70
+ flagKey,
71
+ context,
72
+ "number",
73
+ defaultValue,
74
+ logger
75
+ );
76
+ }
77
+ resolveObjectEvaluation(flagKey, defaultValue, context, logger) {
78
+ return this.resolve(flagKey, context, "object", defaultValue, logger);
79
+ }
80
+ resolve(flagKey, context, kind, defaultValue, logger) {
81
+ return this.resolveSync(
82
+ flagKey,
83
+ kind,
84
+ defaultValue,
85
+ logger,
86
+ () => captureFeature(this.contextFor(context).feature(flagKey))
87
+ );
88
+ }
89
+ /**
90
+ * Returns the single stored context. It is rebuilt when the supplied context
91
+ * differs from the stored one — normally `onContextChange` has already done
92
+ * this, but a context set before the provider was registered still self-heals
93
+ * here without rebuilding on every resolution.
94
+ */
95
+ contextFor(context) {
96
+ const signature = contextSignature(context);
97
+ if (!this.context || signature !== this.currentSignature) {
98
+ this.applyContext(context);
99
+ }
100
+ return this.context;
101
+ }
102
+ applyContext(context) {
103
+ this.context = this.config.context(toContextRecord(context));
104
+ this.currentSignature = contextSignature(context);
105
+ }
106
+ };
107
+
108
+ // src/index.ts
109
+ import {
110
+ InvalidContextError,
111
+ mapEvaluationContext,
112
+ toContextRecord as toContextRecord2
113
+ } from "featurehub-openfeature-common";
114
+ export {
115
+ FeatureHubWebProvider,
116
+ InvalidContextError,
117
+ mapEvaluationContext,
118
+ toContextRecord2 as toContextRecord
119
+ };
package/package.json CHANGED
@@ -1,6 +1,72 @@
1
1
  {
2
2
  "name": "featurehub-openfeature-web-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.0.1",
4
+ "description": "Official OpenFeature provider for FeatureHub (Web/browser). Streams the feature bundle and evaluates locally - no per-flag network calls.",
5
+ "author": "info@featurehub.io",
6
+ "type": "module",
7
+ "main": "dist/index.js",
8
+ "types": "dist/index.d.ts",
9
+ "module": "lib/index.js",
10
+ "homepage": "https://featurehub.io",
11
+ "repository": "github:featurehub-io/featurehub-javascript-sdk",
12
+ "license": "MIT",
13
+ "files": [
14
+ "dist"
15
+ ],
16
+ "keywords": [
17
+ "feature-flag-api",
18
+ "feature-flag-sdk",
19
+ "feature-experimentation",
20
+ "feature-flag",
21
+ "flag",
22
+ "toggle",
23
+ "feature-toggle-api",
24
+ "remote-configuration",
25
+ "ab-testing",
26
+ "openfeature",
27
+ "openfeature-provider",
28
+ "featurehub"
29
+ ],
30
+ "exports": {
31
+ ".": {
32
+ "types": "./dist/index.d.ts",
33
+ "import": "./dist/index.js",
34
+ "require": "./dist/index.cjs"
35
+ }
36
+ },
37
+ "publishConfig": {
38
+ "provenance": true,
39
+ "access": "public"
40
+ },
41
+ "peerDependencies": {
42
+ "@openfeature/web-sdk": ">=1.10.0 <2"
43
+ },
44
+ "dependencies": {
45
+ "featurehub-openfeature-common": "^1.0.1",
46
+ "featurehub-javascript-client-sdk": "^2.1.0"
47
+ },
48
+ "devDependencies": {
49
+ "@openfeature/web-sdk": "^1.10.0",
50
+ "jsdom": "^27.1.0",
51
+ "rimraf": "6.1.3",
52
+ "tsup": "8.5.0",
53
+ "typescript": "5.9.3",
54
+ "vite": "^7.3.8",
55
+ "vitest": "^3.2.7",
56
+ "featurehub-tsconfig": "0.0.0"
57
+ },
58
+ "engines": {
59
+ "node": ">=20.0.0"
60
+ },
61
+ "scripts": {
62
+ "build": "tsup",
63
+ "build:watch": "tsup --watch",
64
+ "clean": "rimraf node_modules dist",
65
+ "lint": "eslint .",
66
+ "lint:fix": "eslint --fix .",
67
+ "typecheck": "tsc --noEmit",
68
+ "test": "vitest run",
69
+ "test:watch": "vitest",
70
+ "test:coverage": "vitest run --coverage"
71
+ }
6
72
  }