@datadog/mobile-react-native-openfeature 3.5.2 → 3.5.4

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.
Files changed (58) hide show
  1. package/README.md +77 -0
  2. package/lib/commonjs/coreProvider.js +79 -0
  3. package/lib/commonjs/coreProvider.js.map +1 -0
  4. package/lib/commonjs/index.js +14 -0
  5. package/lib/commonjs/index.js.map +1 -1
  6. package/lib/commonjs/mappers.js +50 -0
  7. package/lib/commonjs/mappers.js.map +1 -0
  8. package/lib/commonjs/offlineProvider.js +149 -0
  9. package/lib/commonjs/offlineProvider.js.map +1 -0
  10. package/lib/commonjs/provider.js +9 -73
  11. package/lib/commonjs/provider.js.map +1 -1
  12. package/lib/module/coreProvider.js +72 -0
  13. package/lib/module/coreProvider.js.map +1 -0
  14. package/lib/module/index.js +3 -1
  15. package/lib/module/index.js.map +1 -1
  16. package/lib/module/mappers.js +42 -0
  17. package/lib/module/mappers.js.map +1 -0
  18. package/lib/module/offlineProvider.js +143 -0
  19. package/lib/module/offlineProvider.js.map +1 -0
  20. package/lib/module/provider.js +7 -71
  21. package/lib/module/provider.js.map +1 -1
  22. package/lib/typescript/core/src/flags/FlagsClient.d.ts +96 -0
  23. package/lib/typescript/core/src/flags/FlagsClient.d.ts.map +1 -1
  24. package/lib/typescript/core/src/flags/configuration/context.d.ts +20 -0
  25. package/lib/typescript/core/src/flags/configuration/context.d.ts.map +1 -0
  26. package/lib/typescript/core/src/flags/configuration/index.d.ts +5 -0
  27. package/lib/typescript/core/src/flags/configuration/index.d.ts.map +1 -0
  28. package/lib/typescript/core/src/flags/configuration/precomputed.d.ts +25 -0
  29. package/lib/typescript/core/src/flags/configuration/precomputed.d.ts.map +1 -0
  30. package/lib/typescript/core/src/flags/configuration/types.d.ts +24 -0
  31. package/lib/typescript/core/src/flags/configuration/types.d.ts.map +1 -0
  32. package/lib/typescript/core/src/flags/configuration/wire.d.ts +2 -0
  33. package/lib/typescript/core/src/flags/configuration/wire.d.ts.map +1 -0
  34. package/lib/typescript/core/src/flags/internal.d.ts.map +1 -1
  35. package/lib/typescript/core/src/flags/types.d.ts +1 -1
  36. package/lib/typescript/core/src/flags/types.d.ts.map +1 -1
  37. package/lib/typescript/core/src/index.d.ts +4 -2
  38. package/lib/typescript/core/src/index.d.ts.map +1 -1
  39. package/lib/typescript/core/src/version.d.ts +1 -1
  40. package/lib/typescript/react-native-openfeature/src/coreProvider.d.ts +34 -0
  41. package/lib/typescript/react-native-openfeature/src/coreProvider.d.ts.map +1 -0
  42. package/lib/typescript/react-native-openfeature/src/index.d.ts +3 -1
  43. package/lib/typescript/react-native-openfeature/src/index.d.ts.map +1 -1
  44. package/lib/typescript/react-native-openfeature/src/mappers.d.ts +20 -0
  45. package/lib/typescript/react-native-openfeature/src/mappers.d.ts.map +1 -0
  46. package/lib/typescript/react-native-openfeature/src/offlineProvider.d.ts +59 -0
  47. package/lib/typescript/react-native-openfeature/src/offlineProvider.d.ts.map +1 -0
  48. package/lib/typescript/react-native-openfeature/src/provider.d.ts +8 -21
  49. package/lib/typescript/react-native-openfeature/src/provider.d.ts.map +1 -1
  50. package/package.json +5 -5
  51. package/src/__tests__/offlineProvider.integration.test.ts +271 -0
  52. package/src/__tests__/offlineProvider.test.ts +252 -0
  53. package/src/__tests__/provider.test.ts +74 -0
  54. package/src/coreProvider.ts +142 -0
  55. package/src/index.ts +8 -1
  56. package/src/mappers.ts +47 -0
  57. package/src/offlineProvider.ts +185 -0
  58. package/src/provider.ts +10 -139
@@ -0,0 +1,185 @@
1
+ /*
2
+ * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
3
+ * This product includes software developed at Datadog (https://www.datadoghq.com/).
4
+ * Copyright 2016-Present Datadog, Inc.
5
+ */
6
+
7
+ import type {
8
+ FlagsClient,
9
+ ParsedFlagsConfiguration
10
+ } from '@datadog/mobile-react-native';
11
+ import {
12
+ ErrorCode,
13
+ GeneralError,
14
+ InvalidContextError,
15
+ ProviderEvents,
16
+ ProviderNotReadyError
17
+ } from '@openfeature/web-sdk';
18
+ import type {
19
+ EvaluationContext as OFEvaluationContext,
20
+ OpenFeatureError,
21
+ ProviderMetadata
22
+ } from '@openfeature/web-sdk';
23
+
24
+ import { DatadogCoreOpenFeatureProvider } from './coreProvider';
25
+ import { isEmptyContext, toDdContext } from './mappers';
26
+
27
+ // The outcome of a `FlagsClient` reconcile. Derived from the client so the provider maps it to
28
+ // OpenFeature transitions; not part of the package's public API.
29
+ type ConfigurationResult = ReturnType<FlagsClient['setConfiguration']>;
30
+ type ConfigurationErrorCode = Extract<
31
+ ConfigurationResult,
32
+ { status: 'error' }
33
+ >['errorCode'];
34
+
35
+ // A `PROVIDER_ERROR` event payload carrying the spec's top-level error code (§5.1.5). The web-sdk
36
+ // `ErrorEvent` type omits `errorCode`, but the emitter accepts the extra field and
37
+ // `ProviderWrapper` reads it.
38
+ type ProviderErrorEvent = { message: string; errorCode: ErrorCode };
39
+
40
+ const OF_ERROR_CODE: Record<ConfigurationErrorCode, ErrorCode> = {
41
+ INVALID_CONTEXT: ErrorCode.INVALID_CONTEXT,
42
+ PROVIDER_NOT_READY: ErrorCode.PROVIDER_NOT_READY,
43
+ GENERAL: ErrorCode.GENERAL
44
+ };
45
+
46
+ /**
47
+ * An offline Datadog OpenFeature provider.
48
+ *
49
+ * It behaves like the online `DatadogOpenFeatureProvider` — same flag evaluation and
50
+ * exposure/RUM tracking — **except it never fetches configuration from the network**.
51
+ * Instead of fetching on `initialize`/`onContextChange`, it evaluates against a configuration
52
+ * supplied via {@link DatadogOfflineOpenFeatureProvider.setConfiguration}. A precomputed
53
+ * configuration carries the evaluation context it was computed for, so you should **not** call
54
+ * `OpenFeature.setContext` for the offline precomputed flow — see the class remarks.
55
+ *
56
+ * A runtime context that does not match the configuration's embedded context (compared after
57
+ * normalization) cannot be served (offline never fetches), so it puts the provider into the
58
+ * OpenFeature `ERROR` state and evaluations fall back to your coded defaults (`INVALID_CONTEXT`).
59
+ * An empty *effective* context re-adopts the embedded context and recovers — but note that
60
+ * `clearContext(domain)` falls back to the global context, which may itself be non-empty and
61
+ * mismatching (and would keep the provider in `ERROR`). Load the configuration before setting the
62
+ * provider so it is ready with real flag values from the start:
63
+ *
64
+ * @example
65
+ * ```ts
66
+ * import { OpenFeature } from '@openfeature/web-sdk';
67
+ * import {
68
+ * DatadogOfflineOpenFeatureProvider,
69
+ * configurationFromString
70
+ * } from '@datadog/mobile-react-native-openfeature';
71
+ *
72
+ * const provider = new DatadogOfflineOpenFeatureProvider();
73
+ * provider.setConfiguration(configurationFromString(wire)); // no network
74
+ * await OpenFeature.setProviderAndWait(provider);
75
+ *
76
+ * const client = OpenFeature.getClient();
77
+ * const enabled = client.getBooleanValue('new-feature', false);
78
+ * ```
79
+ */
80
+ export class DatadogOfflineOpenFeatureProvider extends DatadogCoreOpenFeatureProvider {
81
+ readonly metadata: ProviderMetadata = {
82
+ name: 'datadog-react-native-offline'
83
+ };
84
+
85
+ // Whether the provider is currently in an error state, so a successful `setConfiguration` must
86
+ // emit `PROVIDER_READY` to recover (a bare `CONFIGURATION_CHANGED` would not clear `ERROR`).
87
+ // It may be set before the provider is registered, so it does not necessarily mirror
88
+ // OpenFeature's status yet.
89
+ private configurationInError = false;
90
+
91
+ async initialize(context: OFEvaluationContext = {}): Promise<void> {
92
+ const result = this.applyContext(context);
93
+
94
+ // OpenFeature derives the initial status from whether `initialize` settles: resolve =>
95
+ // READY, reject => ERROR. Reject when the provider cannot serve — an absent, invalid, or
96
+ // context-mismatched configuration — so it does not start in a misleading READY that only
97
+ // returns default values. Loading a valid configuration later recovers it.
98
+ if (result.status === 'error') {
99
+ throw this.toError(result.errorCode);
100
+ }
101
+ }
102
+
103
+ onContextChange(
104
+ _oldContext: OFEvaluationContext,
105
+ newContext: OFEvaluationContext
106
+ ): void {
107
+ // Synchronous on purpose. Reconciliation is synchronous, and a synchronous throw makes the
108
+ // Web SDK transition straight to ERROR (skipping the transient RECONCILING state) with no
109
+ // async window in which an interleaved `setConfiguration` could clobber the final status.
110
+ // Returning normally lets the Web SDK set READY — the automatic recovery path.
111
+ const result = this.applyContext(newContext);
112
+
113
+ if (result.status === 'error') {
114
+ throw this.toError(result.errorCode);
115
+ }
116
+ }
117
+
118
+ /**
119
+ * Load a configuration into the provider for offline evaluation.
120
+ *
121
+ * @param configuration A configuration parsed from a `ConfigurationWire` string via
122
+ * `configurationFromString`.
123
+ */
124
+ setConfiguration(configuration: ParsedFlagsConfiguration): void {
125
+ const result = this.flagsClient.setConfiguration(configuration);
126
+
127
+ if (result.status === 'ready') {
128
+ if (this.configurationInError) {
129
+ // Recover from a prior error: PROVIDER_READY clears the ERROR status (a bare
130
+ // CONFIGURATION_CHANGED would not).
131
+ this.configurationInError = false;
132
+ this.events.emit(ProviderEvents.Ready);
133
+ }
134
+ // The (re)loaded configuration changed the served flags.
135
+ this.events.emit(ProviderEvents.ConfigurationChanged);
136
+ } else {
137
+ this.configurationInError = true;
138
+ const details: ProviderErrorEvent = {
139
+ message:
140
+ 'The Datadog offline provider cannot serve the loaded configuration for the current context.',
141
+ errorCode: OF_ERROR_CODE[result.errorCode]
142
+ };
143
+ this.events.emit(ProviderEvents.Error, details);
144
+ }
145
+ }
146
+
147
+ private applyContext(context: OFEvaluationContext): ConfigurationResult {
148
+ // An empty context means "no external override": clear it so a loaded precomputed
149
+ // configuration is served against its embedded context. Order-independent — the synthetic
150
+ // `initialize({})`, `setContext({})`, and `clearContext()` all re-adopt the embedded
151
+ // context rather than being treated as a mismatch.
152
+ const result = isEmptyContext(context)
153
+ ? this.flagsClient.resetEvaluationContextWithoutFetching()
154
+ : this.flagsClient.setEvaluationContextWithoutFetching(
155
+ toDdContext(context)
156
+ );
157
+
158
+ this.configurationInError = result.status === 'error';
159
+
160
+ return result;
161
+ }
162
+
163
+ /**
164
+ * Map a reconcile error code to the precise OpenFeature error type, so direct callers of
165
+ * `initialize`/`onContextChange` (and `setProviderAndWait`) receive the correct typed error.
166
+ * (Web SDK 1.8.0 drops the code from the lifecycle-generated error *event*, but the thrown
167
+ * error type is still accurate for callers.)
168
+ */
169
+ private toError(errorCode: ConfigurationErrorCode): OpenFeatureError {
170
+ switch (errorCode) {
171
+ case 'INVALID_CONTEXT':
172
+ return new InvalidContextError(
173
+ 'The evaluation context does not match the offline precomputed configuration. Serving default values.'
174
+ );
175
+ case 'PROVIDER_NOT_READY':
176
+ return new ProviderNotReadyError(
177
+ 'The Datadog offline provider has no configuration loaded. Provide one via setConfiguration.'
178
+ );
179
+ default:
180
+ return new GeneralError(
181
+ 'The Datadog offline provider cannot serve the loaded configuration.'
182
+ );
183
+ }
184
+ }
185
+ }
package/src/provider.ts CHANGED
@@ -4,59 +4,27 @@
4
4
  * Copyright 2016-Present Datadog, Inc.
5
5
  */
6
6
 
7
- import { DdFlags } from '@datadog/mobile-react-native';
8
- import type {
9
- FlagDetails,
10
- FlagsClient,
11
- EvaluationContext as DdEvaluationContext
12
- } from '@datadog/mobile-react-native';
13
- import { OpenFeatureEventEmitter, ErrorCode } from '@openfeature/web-sdk';
14
7
  import type {
15
8
  EvaluationContext as OFEvaluationContext,
16
- JsonValue,
17
- Logger,
18
- Paradigm,
19
- Provider,
20
- ProviderMetadata,
21
- ResolutionDetails,
22
- PrimitiveValue,
23
- ProviderEventEmitter,
24
- ProviderEvents
9
+ ProviderMetadata
25
10
  } from '@openfeature/web-sdk';
26
11
 
27
- export interface DatadogOpenFeatureProviderOptions {
28
- /**
29
- * The name of the Datadog Flags client to use.
30
- *
31
- * Provide this parameter in order to use different Datadog Flags clients for different OpenFeature domains.
32
- *
33
- * @default 'default'
34
- */
35
- clientName?: string;
36
- }
12
+ import { DatadogCoreOpenFeatureProvider } from './coreProvider';
13
+ import { toDdContext } from './mappers';
37
14
 
38
- export class DatadogOpenFeatureProvider implements Provider {
39
- readonly runsOn: Paradigm = 'client';
15
+ export type { DatadogOpenFeatureProviderOptions } from './coreProvider';
16
+
17
+ /**
18
+ * The online Datadog OpenFeature provider. Fetches precomputed flag assignments from Datadog
19
+ * whenever the evaluation context is set or changed.
20
+ */
21
+ export class DatadogOpenFeatureProvider extends DatadogCoreOpenFeatureProvider {
40
22
  readonly metadata: ProviderMetadata = {
41
23
  name: 'datadog-react-native'
42
24
  };
43
25
 
44
- private options: DatadogOpenFeatureProviderOptions;
45
- private flagsClient: FlagsClient;
46
-
47
- readonly events: ProviderEventEmitter<ProviderEvents> = new OpenFeatureEventEmitter();
48
26
  private contextChangePromise = Promise.resolve();
49
27
 
50
- constructor(options: DatadogOpenFeatureProviderOptions = {}) {
51
- if (!options.clientName) {
52
- options.clientName = 'default';
53
- }
54
-
55
- this.options = options;
56
-
57
- this.flagsClient = DdFlags.getClient(this.options.clientName);
58
- }
59
-
60
28
  async initialize(context: OFEvaluationContext = {}): Promise<void> {
61
29
  const ddContext = toDdContext(context);
62
30
  this.contextChangePromise = this.flagsClient.setEvaluationContext(
@@ -80,101 +48,4 @@ export class DatadogOpenFeatureProvider implements Provider {
80
48
  // Wait for the current context change to complete.
81
49
  await this.contextChangePromise;
82
50
  }
83
-
84
- resolveBooleanEvaluation(
85
- flagKey: string,
86
- defaultValue: boolean,
87
- _context: OFEvaluationContext,
88
- _logger: Logger
89
- ): ResolutionDetails<boolean> {
90
- const details = this.flagsClient.getBooleanDetails(
91
- flagKey,
92
- defaultValue
93
- );
94
- return toFlagResolution(details);
95
- }
96
-
97
- resolveStringEvaluation(
98
- flagKey: string,
99
- defaultValue: string,
100
- _context: OFEvaluationContext,
101
- _logger: Logger
102
- ): ResolutionDetails<string> {
103
- const details = this.flagsClient.getStringDetails(
104
- flagKey,
105
- defaultValue
106
- );
107
- return toFlagResolution(details);
108
- }
109
-
110
- resolveNumberEvaluation(
111
- flagKey: string,
112
- defaultValue: number,
113
- _context: OFEvaluationContext,
114
- _logger: Logger
115
- ): ResolutionDetails<number> {
116
- const details = this.flagsClient.getNumberDetails(
117
- flagKey,
118
- defaultValue
119
- );
120
- return toFlagResolution(details);
121
- }
122
-
123
- resolveObjectEvaluation<T extends JsonValue>(
124
- flagKey: string,
125
- defaultValue: T,
126
- _context: OFEvaluationContext,
127
- _logger: Logger
128
- ): ResolutionDetails<T> {
129
- // The OpenFeature spec states that the return value can be any valid JSON value.
130
- // However, the Datadog Flags feature only supports JSON objects for the JSON feature flag type.
131
- // Thus, the user should always expect the returned value to be an object instead of any arbitrary JSON value.
132
- // Also, the user is responsible for providing a proper `defaultValue` that's an object.
133
-
134
- const details = this.flagsClient.getObjectDetails<T>(
135
- flagKey,
136
- defaultValue
137
- );
138
- return toFlagResolution(details);
139
- }
140
51
  }
141
-
142
- const toDdContext = (context: OFEvaluationContext): DdEvaluationContext => {
143
- const { targetingKey, ...attributes } = context;
144
-
145
- // Important ⚠️
146
- // The Flags SDK doesn't support nested non-primitive values in the evaluation context as per OF.3 FFE SDK requirement.
147
- // However, we let the SDK handle this inside of FlagsClient since it does this processing anyways.
148
- const ddContextAttributes = attributes as Record<string, PrimitiveValue>;
149
-
150
- return {
151
- // Allow flag evaluations without a provided targeting key.
152
- targetingKey: targetingKey ?? '',
153
- attributes: ddContextAttributes
154
- };
155
- };
156
-
157
- const toFlagResolution = <T>(details: FlagDetails<T>): ResolutionDetails<T> => {
158
- const {
159
- value,
160
- reason,
161
- variant,
162
- allocationKey,
163
- errorCode,
164
- errorMessage
165
- } = details;
166
-
167
- const parsedErrorCode =
168
- errorCode && (ErrorCode[errorCode as ErrorCode] || ErrorCode.GENERAL);
169
-
170
- const result: ResolutionDetails<T> = {
171
- value,
172
- reason,
173
- variant,
174
- flagMetadata: allocationKey ? { allocationKey } : undefined,
175
- errorCode: parsedErrorCode,
176
- errorMessage
177
- };
178
-
179
- return result;
180
- };