featurehub-openfeature-common 0.0.0-stage → 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/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,18 @@
1
- # Temporary Holding Version
1
+ # FeatureHub OpenFeature — common
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
+ Shared implementation for the official FeatureHub OpenFeature providers:
4
+
5
+ - [`featurehub-openfeature-node-sdk`](../openfeature-node)
6
+ - [`featurehub-openfeature-web-sdk`](../openfeature-web)
7
+
8
+ This package is an **implementation detail**. It is published because the providers depend on it, but it is not intended to be used directly.
9
+
10
+ ## What lives here
11
+
12
+ - **Context mapping** — `mapEvaluationContext` and `toContextRecord`, following the FeatureHub SDK specification's evaluation context: `targetingKey` → `userkey`; the well-known keys (`device`, `country`, `platform`, `session`, `version`) case-insensitively; `fhubWhenActive` dropped; strings, numbers, booleans and dates, or lists of them; nested objects rejected. Plus `contextSignature` (change detection) and `isClientEvaluatedKey`.
13
+ - **Resolution semantics** — `captureFeature` (one `FeatureStateHolder.getValue()` call returning the value, the strategy id and whether it was a percentage rollout, plus the feature's properties) and `resolveFromEvaluation`, which follows the FeatureHub SDK specification's OpenFeature resolution: not found, type mismatch, value-less `DISABLED`, conversion of string values, `STATIC` / `SPLIT` / `TARGETING_MATCH` with the strategy id as `variant`, and flag metadata. Plus the standard error resolutions.
14
+ - **Provider lifecycle** — `FeatureHubProviderCore`, the base class both providers extend: config creation, event wiring with per-feature change detection, transport selection (`applyTransport`), readiness handling and teardown.
15
+
16
+ ## License
17
+
18
+ MIT
package/dist/index.cjs ADDED
@@ -0,0 +1,585 @@
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
+ ContextConflictError: () => ContextConflictError,
24
+ FeatureHubProviderCore: () => FeatureHubProviderCore,
25
+ InvalidContextError: () => InvalidContextError,
26
+ applyTransport: () => applyTransport,
27
+ buildFlagMetadata: () => buildFlagMetadata,
28
+ captureFeature: () => captureFeature,
29
+ contextSignature: () => contextSignature,
30
+ expectedFeatureType: () => expectedFeatureType,
31
+ flagNotFoundResolution: () => flagNotFoundResolution,
32
+ generalErrorResolution: () => generalErrorResolution,
33
+ invalidContextResolution: () => invalidContextResolution,
34
+ isClientEvaluatedKey: () => isClientEvaluatedKey,
35
+ mapEvaluationContext: () => mapEvaluationContext,
36
+ notReadyResolution: () => notReadyResolution,
37
+ resolveFromEvaluation: () => resolveFromEvaluation,
38
+ toContextRecord: () => toContextRecord
39
+ });
40
+ module.exports = __toCommonJS(index_exports);
41
+
42
+ // src/context-mapper.ts
43
+ var import_featurehub_javascript_core_sdk = require("featurehub-javascript-core-sdk");
44
+ var FHUB_WHEN_ACTIVE = import_featurehub_javascript_core_sdk.StrategyAttributeWellKnownNames.FhubWhenActive.toLowerCase();
45
+ var WELL_KNOWN_KEYS = new Set(
46
+ Object.values(import_featurehub_javascript_core_sdk.StrategyAttributeWellKnownNames).map((k) => k.toLowerCase()).filter((k) => k !== "userkey" && k !== FHUB_WHEN_ACTIVE)
47
+ );
48
+ var InvalidContextError = class extends Error {
49
+ key;
50
+ constructor(key) {
51
+ super(
52
+ `Context attribute '${key}' is an object or contains nested objects; FeatureHub attributes must be strings, numbers, booleans, date-times, or lists of those.`
53
+ );
54
+ this.name = "InvalidContextError";
55
+ this.key = key;
56
+ }
57
+ };
58
+ var ContextConflictError = class extends Error {
59
+ constructor() {
60
+ super(
61
+ "A server-evaluated API key holds one evaluation context for the whole process, and a resolution for a different context arrived while another context's was in progress. Use the same context everywhere, or a client-evaluated key (containing '*') to resolve many contexts at once."
62
+ );
63
+ this.name = "ContextConflictError";
64
+ }
65
+ };
66
+ function isClientEvaluatedKey(apiKey) {
67
+ return apiKey.includes("*");
68
+ }
69
+ function isValue(v) {
70
+ return typeof v === "string" || typeof v === "number" || typeof v === "boolean" || v instanceof Date;
71
+ }
72
+ function isAllowedList(v) {
73
+ return Array.isArray(v) && v.every(isValue);
74
+ }
75
+ function mapEvaluationContext(context) {
76
+ const attributes = {};
77
+ let userkey;
78
+ if (context) {
79
+ for (const [key, value] of Object.entries(context)) {
80
+ if (value === void 0 || value === null) {
81
+ continue;
82
+ }
83
+ const lower = key.toLowerCase();
84
+ if (lower === "targetingkey" || lower === "userkey") {
85
+ userkey = String(value);
86
+ } else if (lower === FHUB_WHEN_ACTIVE) {
87
+ continue;
88
+ } else if (isValue(value) || isAllowedList(value)) {
89
+ attributes[WELL_KNOWN_KEYS.has(lower) ? lower : key] = value;
90
+ } else {
91
+ throw new InvalidContextError(key);
92
+ }
93
+ }
94
+ }
95
+ return { userkey, attributes };
96
+ }
97
+ function toContextRecord(context) {
98
+ const { userkey, attributes } = mapEvaluationContext(context);
99
+ return userkey === void 0 ? { ...attributes } : { userkey, ...attributes };
100
+ }
101
+ function contextSignature(context) {
102
+ const { userkey, attributes } = mapEvaluationContext(context);
103
+ const json = (v) => v instanceof Date ? { date: v.toISOString() } : v;
104
+ const entries = Object.entries(attributes).map(([key, value]) => [
105
+ key,
106
+ Array.isArray(value) ? value.map(json) : json(value)
107
+ ]);
108
+ if (userkey !== void 0) {
109
+ entries.push(["userkey", userkey]);
110
+ }
111
+ return JSON.stringify(entries.sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
112
+ }
113
+
114
+ // src/lifecycle.ts
115
+ var import_core2 = require("@openfeature/core");
116
+ var import_featurehub_javascript_core_sdk2 = require("featurehub-javascript-core-sdk");
117
+
118
+ // src/resolution.ts
119
+ var import_core = require("@openfeature/core");
120
+ function captureFeature(holder) {
121
+ if (holder === void 0 || !holder.exists) {
122
+ return { exists: false };
123
+ }
124
+ const evaluated = holder.getValue();
125
+ return {
126
+ exists: true,
127
+ featureType: holder.getType()?.toString(),
128
+ version: holder.getVersion(),
129
+ value: evaluated?.value,
130
+ strategyId: evaluated?.strategyId,
131
+ split: evaluated?.split === true,
132
+ properties: holder.featureProperties
133
+ };
134
+ }
135
+ var FEATURE_TYPES = {
136
+ boolean: "BOOLEAN",
137
+ string: "STRING",
138
+ number: "NUMBER",
139
+ object: "JSON"
140
+ };
141
+ function expectedFeatureType(kind) {
142
+ return FEATURE_TYPES[kind];
143
+ }
144
+ function buildFlagMetadata(featureType, version, properties) {
145
+ const metadata = { ...properties ?? {} };
146
+ if (typeof version === "number" && version >= 0) {
147
+ metadata["featureVersion"] = version;
148
+ }
149
+ if (featureType) {
150
+ metadata["featureType"] = featureType;
151
+ }
152
+ return metadata;
153
+ }
154
+ function notReadyResolution(defaultValue) {
155
+ return {
156
+ value: defaultValue,
157
+ reason: import_core.StandardResolutionReasons.ERROR,
158
+ errorCode: import_core.ErrorCode.PROVIDER_NOT_READY,
159
+ errorMessage: "FeatureHub provider has not completed initialization."
160
+ };
161
+ }
162
+ function flagNotFoundResolution(flagKey, defaultValue) {
163
+ return {
164
+ value: defaultValue,
165
+ reason: import_core.StandardResolutionReasons.ERROR,
166
+ errorCode: import_core.ErrorCode.FLAG_NOT_FOUND,
167
+ errorMessage: `Flag '${flagKey}' was not found in this FeatureHub environment.`
168
+ };
169
+ }
170
+ function invalidContextResolution(defaultValue, error) {
171
+ return {
172
+ value: defaultValue,
173
+ reason: import_core.StandardResolutionReasons.ERROR,
174
+ errorCode: import_core.ErrorCode.INVALID_CONTEXT,
175
+ errorMessage: error instanceof Error ? error.message : String(error)
176
+ };
177
+ }
178
+ function generalErrorResolution(defaultValue, error) {
179
+ return {
180
+ value: defaultValue,
181
+ reason: import_core.StandardResolutionReasons.ERROR,
182
+ errorCode: import_core.ErrorCode.GENERAL,
183
+ errorMessage: error instanceof Error ? error.message : String(error)
184
+ };
185
+ }
186
+ var NUMERIC_STRING = /^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;
187
+ function convert(flagKey, kind, value) {
188
+ const mismatch = () => ({
189
+ errorCode: import_core.ErrorCode.TYPE_MISMATCH,
190
+ errorMessage: `Flag '${flagKey}' has a value that cannot be resolved as ${kind}.`
191
+ });
192
+ switch (kind) {
193
+ case "boolean":
194
+ if (typeof value === "boolean") return { value };
195
+ if (value === "true") return { value: true };
196
+ if (value === "false") return { value: false };
197
+ return mismatch();
198
+ case "string":
199
+ if (typeof value === "string") return { value };
200
+ if (typeof value === "number" || typeof value === "boolean") return { value: String(value) };
201
+ return mismatch();
202
+ case "number":
203
+ if (typeof value === "number") return Number.isFinite(value) ? { value } : mismatch();
204
+ if (typeof value === "string" && NUMERIC_STRING.test(value)) {
205
+ const n = Number(value);
206
+ return Number.isFinite(n) ? { value: n } : mismatch();
207
+ }
208
+ return mismatch();
209
+ case "object": {
210
+ let decoded = value;
211
+ if (typeof value === "string") {
212
+ try {
213
+ decoded = JSON.parse(value);
214
+ } catch {
215
+ return {
216
+ errorCode: import_core.ErrorCode.PARSE_ERROR,
217
+ errorMessage: `Flag '${flagKey}' contains invalid JSON.`
218
+ };
219
+ }
220
+ }
221
+ if (typeof decoded === "object" && decoded !== null && !Array.isArray(decoded)) {
222
+ return { value: decoded };
223
+ }
224
+ return mismatch();
225
+ }
226
+ }
227
+ }
228
+ function resolveFromEvaluation(flagKey, kind, defaultValue, evaluation) {
229
+ if (!evaluation.exists) {
230
+ return flagNotFoundResolution(flagKey, defaultValue);
231
+ }
232
+ const metadata = buildFlagMetadata(
233
+ evaluation.featureType,
234
+ evaluation.version,
235
+ evaluation.properties
236
+ );
237
+ if (evaluation.featureType && evaluation.featureType !== expectedFeatureType(kind)) {
238
+ return {
239
+ value: defaultValue,
240
+ reason: import_core.StandardResolutionReasons.ERROR,
241
+ errorCode: import_core.ErrorCode.TYPE_MISMATCH,
242
+ errorMessage: `Flag '${flagKey}' is of type ${evaluation.featureType} and cannot be resolved as ${kind}.`,
243
+ flagMetadata: metadata
244
+ };
245
+ }
246
+ if (evaluation.value === void 0 || evaluation.value === null) {
247
+ return {
248
+ value: defaultValue,
249
+ reason: import_core.StandardResolutionReasons.DISABLED,
250
+ variant: evaluation.strategyId,
251
+ flagMetadata: metadata
252
+ };
253
+ }
254
+ const converted = convert(flagKey, kind, evaluation.value);
255
+ if (!("value" in converted)) {
256
+ return {
257
+ value: defaultValue,
258
+ reason: import_core.StandardResolutionReasons.ERROR,
259
+ errorCode: converted.errorCode,
260
+ errorMessage: converted.errorMessage,
261
+ flagMetadata: metadata
262
+ };
263
+ }
264
+ return {
265
+ value: converted.value,
266
+ reason: !evaluation.strategyId ? import_core.StandardResolutionReasons.STATIC : evaluation.split ? import_core.StandardResolutionReasons.SPLIT : import_core.StandardResolutionReasons.TARGETING_MATCH,
267
+ variant: evaluation.strategyId,
268
+ flagMetadata: metadata
269
+ };
270
+ }
271
+
272
+ // src/lifecycle.ts
273
+ var noEdge = {
274
+ contextChange: () => Promise.resolve(),
275
+ clientEvaluated: () => true,
276
+ requiresReplacementOnHeaderChange: () => false,
277
+ close: () => {
278
+ },
279
+ poll: () => Promise.resolve()
280
+ };
281
+ var given = (value) => value !== void 0 && value.trim().length > 0 ? value.trim() : void 0;
282
+ var PROVIDER_READY = "PROVIDER_READY";
283
+ var PROVIDER_ERROR = "PROVIDER_ERROR";
284
+ var PROVIDER_CONFIGURATION_CHANGED = "PROVIDER_CONFIGURATION_CHANGED";
285
+ var PROVIDER_STALE = "PROVIDER_STALE";
286
+ function applyTransport(cfg, options, defaultTransport) {
287
+ if (options.cacheTimeToLiveMs !== void 0) {
288
+ cfg.restPassive(options.cacheTimeToLiveMs);
289
+ return;
290
+ }
291
+ if (options.pollIntervalMs !== void 0) {
292
+ cfg.restActive(options.pollIntervalMs);
293
+ return;
294
+ }
295
+ const transport = options.transport ?? defaultTransport;
296
+ if (transport === void 0) {
297
+ return;
298
+ }
299
+ switch (transport) {
300
+ case "passive":
301
+ cfg.restPassive();
302
+ break;
303
+ case "polling":
304
+ cfg.restActive();
305
+ break;
306
+ default:
307
+ cfg.streaming();
308
+ }
309
+ }
310
+ var FeatureHubProviderCore = class {
311
+ options;
312
+ /** Edge's URL and the API key, as given in code or found in the environment; neither for stores only */
313
+ host;
314
+ apiKey;
315
+ clientEval;
316
+ waitForReadyMs;
317
+ config;
318
+ /**
319
+ * Features are held and resolve: readiness is Ready, or Stale (a context change in progress, or a
320
+ * connection that stopped for good after delivering features; featurehub-protocol.yaml repository.readiness).
321
+ */
322
+ ready = false;
323
+ started = false;
324
+ /** the connection has stopped for good (connection failed, or environment stale) */
325
+ stopped = false;
326
+ staleEmitted = false;
327
+ lastReadiness = import_featurehub_javascript_core_sdk2.Readyness.NotReady;
328
+ /** key → last seen feature version, so polls that change nothing stay silent. */
329
+ featureVersions = /* @__PURE__ */ new Map();
330
+ seenPayload = false;
331
+ /**
332
+ * featurehub-protocol.yaml providers.source_selection and validation_errors: a connection needs both a host
333
+ * and an API key; with neither, a `configFactory` can supply a config whose features come from stores alone.
334
+ */
335
+ constructor(providerName, options, connection = options ?? {}) {
336
+ if (!options) {
337
+ throw new Error(`${providerName} requires its options.`);
338
+ }
339
+ const host = given(connection.host);
340
+ const apiKey = given(connection.apiKey);
341
+ if (host === void 0 && apiKey === void 0) {
342
+ if (!options.configFactory) {
343
+ throw new Error(
344
+ `${providerName} requires \`host\` and \`apiKey\`, or a \`configFactory\` whose config gets its features from stores.`
345
+ );
346
+ }
347
+ } else if (host === void 0 || apiKey === void 0) {
348
+ throw new Error(`${providerName} requires both \`host\` and \`apiKey\`: only one was given.`);
349
+ }
350
+ this.options = options;
351
+ this.host = host;
352
+ this.apiKey = apiKey;
353
+ this.clientEval = apiKey === void 0 || isClientEvaluatedKey(apiKey);
354
+ this.waitForReadyMs = options.waitForReadyMs ?? 1e4;
355
+ }
356
+ /** Creates the config, wires its listeners, applies the transport and calls `init()`. */
357
+ startConfig() {
358
+ const cfg = this.options.configFactory ? this.options.configFactory({ ...this.options, host: this.host, apiKey: this.apiKey }) : this.createConfig();
359
+ this.config = cfg;
360
+ if (this.apiKey === void 0) {
361
+ cfg.isClientEvaluated = true;
362
+ }
363
+ cfg.addReadinessListener((readiness) => this.onReadiness(readiness));
364
+ cfg.addConnectionEventListener?.(() => this.onConnectionStopped());
365
+ cfg.registerRawUpdateFeatureListener({
366
+ get connected() {
367
+ return cfg.initialized;
368
+ },
369
+ processUpdate: (feature) => this.emitChanged(this.noteVersions([feature], false)),
370
+ processUpdates: (features) => this.emitChanged(this.noteVersions(features, true)),
371
+ deleteFeature: (feature) => {
372
+ if (!feature?.key) {
373
+ return;
374
+ }
375
+ this.featureVersions.delete(feature.key);
376
+ this.emitChanged([feature.key]);
377
+ },
378
+ close: () => {
379
+ },
380
+ configChanged: () => {
381
+ }
382
+ });
383
+ applyTransport(cfg, this.options, this.defaultTransport);
384
+ cfg.init();
385
+ return cfg;
386
+ }
387
+ /**
388
+ * Waits for the repository to become ready, then allows lifecycle events through
389
+ * (featurehub-protocol.yaml providers.events):
390
+ * - Failed (the connection was rejected before any features): initialisation fails, PROVIDER_FATAL
391
+ * - Stale with features, because the connection stopped for good with the first response: initialisation
392
+ * succeeds and STALE follows READY
393
+ * - anything else not Ready in time: initialisation fails
394
+ */
395
+ async awaitReady(cfg, waitMs = this.waitForReadyMs) {
396
+ const readiness = await cfg.waitForReady(waitMs);
397
+ const stopped = this.stopped || cfg.connectionFailed === true || cfg.environmentStale === true;
398
+ if (readiness === import_featurehub_javascript_core_sdk2.Readyness.Failed) {
399
+ await this.onClose();
400
+ throw new import_core2.ProviderFatalError(
401
+ "FeatureHub rejected the connection before sending any features (readiness: Failed)."
402
+ );
403
+ }
404
+ if (readiness !== import_featurehub_javascript_core_sdk2.Readyness.Ready && !(readiness === import_featurehub_javascript_core_sdk2.Readyness.Stale && stopped)) {
405
+ this.started = true;
406
+ throw new Error(
407
+ `FeatureHub did not become ready within ${this.waitForReadyMs}ms (readiness: ${readiness}).`
408
+ );
409
+ }
410
+ this.ready = true;
411
+ this.started = true;
412
+ if (stopped) {
413
+ this.stopped = true;
414
+ setTimeout(() => this.emitStale(), 0);
415
+ }
416
+ }
417
+ /**
418
+ * OpenFeature tracking: records a FeatureHub named usage event (ClientContext.recordNamedUsage) with the
419
+ * evaluation context and the event's details, for the registered usage plugins (Segment, say). It needs a
420
+ * usage plugin to go anywhere, and never fails the caller: an unusable context records nothing.
421
+ */
422
+ track(trackingEventName, context, trackingEventDetails) {
423
+ const cfg = this.config;
424
+ if (!cfg) {
425
+ return;
426
+ }
427
+ try {
428
+ const repository = cfg.repository();
429
+ const ctx = new import_featurehub_javascript_core_sdk2.ClientEvalFeatureContext(repository, noEdge);
430
+ ctx.attributes = toContextRecord(context);
431
+ ctx.recordNamedUsage(
432
+ trackingEventName,
433
+ trackingEventDetails ? { ...trackingEventDetails } : void 0
434
+ );
435
+ } catch {
436
+ }
437
+ }
438
+ async onClose() {
439
+ this.ready = false;
440
+ this.started = false;
441
+ this.stopped = false;
442
+ this.staleEmitted = false;
443
+ this.lastReadiness = import_featurehub_javascript_core_sdk2.Readyness.NotReady;
444
+ this.featureVersions.clear();
445
+ this.seenPayload = false;
446
+ const cfg = this.config;
447
+ this.config = void 0;
448
+ try {
449
+ cfg?.forceClose();
450
+ } catch {
451
+ }
452
+ }
453
+ /** Synchronous resolution helper (web providers). */
454
+ resolveSync(flagKey, kind, defaultValue, logger, take) {
455
+ if (!this.ready || !this.config) {
456
+ return notReadyResolution(defaultValue);
457
+ }
458
+ try {
459
+ return resolveFromEvaluation(flagKey, kind, defaultValue, take());
460
+ } catch (err) {
461
+ return this.failedResolution(flagKey, defaultValue, err, logger);
462
+ }
463
+ }
464
+ /** Asynchronous resolution helper (node providers). */
465
+ async resolveAsync(flagKey, kind, defaultValue, logger, take) {
466
+ if (!this.ready || !this.config) {
467
+ return notReadyResolution(defaultValue);
468
+ }
469
+ try {
470
+ return resolveFromEvaluation(flagKey, kind, defaultValue, await take());
471
+ } catch (err) {
472
+ return this.failedResolution(flagKey, defaultValue, err, logger);
473
+ }
474
+ }
475
+ failedResolution(flagKey, defaultValue, err, logger) {
476
+ if (err instanceof InvalidContextError || err instanceof ContextConflictError) {
477
+ return invalidContextResolution(defaultValue, err);
478
+ }
479
+ logger?.error(`FeatureHub evaluation of '${flagKey}' failed`, err);
480
+ return generalErrorResolution(defaultValue, err);
481
+ }
482
+ onReadiness(readiness) {
483
+ if (readiness === this.lastReadiness) {
484
+ return;
485
+ }
486
+ const wasReady = this.ready;
487
+ this.lastReadiness = readiness;
488
+ switch (readiness) {
489
+ case import_featurehub_javascript_core_sdk2.Readyness.Ready:
490
+ this.ready = true;
491
+ if (this.started && !wasReady) {
492
+ this.eventSink.emit(PROVIDER_READY, { message: "FeatureHub repository is ready" });
493
+ }
494
+ break;
495
+ case import_featurehub_javascript_core_sdk2.Readyness.Stale:
496
+ this.ready = wasReady || this.started;
497
+ break;
498
+ case import_featurehub_javascript_core_sdk2.Readyness.Failed:
499
+ this.ready = false;
500
+ if (this.started) {
501
+ this.eventSink.emit(PROVIDER_ERROR, { message: "FeatureHub repository failed" });
502
+ }
503
+ break;
504
+ default:
505
+ this.ready = false;
506
+ }
507
+ }
508
+ onConnectionStopped() {
509
+ this.stopped = true;
510
+ if (this.started) {
511
+ this.emitStale();
512
+ }
513
+ }
514
+ /** STALE once, after READY, while features are held; resolutions continue from the last features. */
515
+ emitStale() {
516
+ if (this.staleEmitted || !this.ready || !this.config) {
517
+ return;
518
+ }
519
+ this.staleEmitted = true;
520
+ this.eventSink.emit(PROVIDER_STALE, {
521
+ message: "FeatureHub will send no more updates: resolving from the last features"
522
+ });
523
+ }
524
+ /**
525
+ * Records the versions carried by a payload and returns the keys that
526
+ * actually changed. The first payload after construction is a baseline: the
527
+ * repository replays the full feature set on every poll (and on every SSE
528
+ * reconnect), so without this comparison ConfigurationChanged would fire on
529
+ * every poll even when nothing changed. A full set also removes every feature
530
+ * it does not hold, which is a change too.
531
+ */
532
+ noteVersions(features, fullSet) {
533
+ const baseline = !this.seenPayload;
534
+ const changed = [];
535
+ if (fullSet) {
536
+ const delivered = new Set(features.map((f) => f?.key).filter((k) => !!k));
537
+ for (const key of [...this.featureVersions.keys()]) {
538
+ if (!delivered.has(key)) {
539
+ this.featureVersions.delete(key);
540
+ if (!baseline) {
541
+ changed.push(key);
542
+ }
543
+ }
544
+ }
545
+ }
546
+ for (const feature of features) {
547
+ const key = feature?.key;
548
+ if (!key) {
549
+ continue;
550
+ }
551
+ const had = this.featureVersions.has(key);
552
+ if (had ? this.featureVersions.get(key) !== feature.version : !baseline) {
553
+ changed.push(key);
554
+ }
555
+ this.featureVersions.set(key, feature.version);
556
+ }
557
+ this.seenPayload = true;
558
+ return changed;
559
+ }
560
+ emitChanged(keys) {
561
+ if (!this.started || keys.length === 0) {
562
+ return;
563
+ }
564
+ this.eventSink.emit(PROVIDER_CONFIGURATION_CHANGED, { flagsChanged: keys });
565
+ }
566
+ };
567
+ // Annotate the CommonJS export names for ESM import in node:
568
+ 0 && (module.exports = {
569
+ ContextConflictError,
570
+ FeatureHubProviderCore,
571
+ InvalidContextError,
572
+ applyTransport,
573
+ buildFlagMetadata,
574
+ captureFeature,
575
+ contextSignature,
576
+ expectedFeatureType,
577
+ flagNotFoundResolution,
578
+ generalErrorResolution,
579
+ invalidContextResolution,
580
+ isClientEvaluatedKey,
581
+ mapEvaluationContext,
582
+ notReadyResolution,
583
+ resolveFromEvaluation,
584
+ toContextRecord
585
+ });