@openfeature/react-sdk 0.1.0-experimental โ†’ 0.1.1-experimental

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/README.md CHANGED
@@ -15,26 +15,66 @@
15
15
  <a href="https://github.com/open-feature/spec/releases/tag/v0.7.0">
16
16
  <img alt="Specification" src="https://img.shields.io/static/v1?label=specification&message=v0.7.0&color=yellow&style=for-the-badge" />
17
17
  </a>
18
+ <!-- x-release-please-start-version -->
19
+ <a href="https://github.com/open-feature/js-sdk/releases/tag/react-sdk-v0.1.1-experimental">
20
+ <img alt="Release" src="https://img.shields.io/static/v1?label=release&message=v0.1.1-experimental&color=blue&style=for-the-badge" />
21
+ </a>
22
+ <!-- x-release-please-end -->
18
23
  <br/>
19
24
  <a href="https://codecov.io/gh/open-feature/js-sdk">
20
25
  <img alt="codecov" src="https://codecov.io/gh/open-feature/js-sdk/branch/main/graph/badge.svg?token=3DC5XOEHMY" />
21
26
  </a>
27
+ <a href="https://www.npmjs.com/package/@openfeature/react-sdk">
28
+ <img alt="NPM Download" src="https://img.shields.io/npm/dm/%40openfeature%2Freact-sdk" />
29
+ </a>
22
30
  </p>
23
31
  <!-- x-hide-in-docs-start -->
24
32
 
25
- [OpenFeature](https://openfeature.dev) is an open specification that provides a vendor-agnostic, community-driven API for feature flagging that works with your favorite feature flag management tool.
33
+ [OpenFeature](https://openfeature.dev) is an open specification that provides a vendor-agnostic, community-driven API for feature flagging that works with your favorite feature flag management tool or in-house solution.
34
+
35
+ <!-- x-hide-in-docs-end -->
26
36
 
27
37
  ๐Ÿงช This SDK is experimental.
28
38
 
29
- ## Basic Usage
39
+ ## Overview
40
+
41
+ The OpenFeature React SDK adds React-specific functionality to the [OpenFeature Web SDK](https://openfeature.dev/docs/reference/technologies/client/web).
42
+
43
+ In addition to the feature provided by the [web sdk](https://openfeature.dev/docs/reference/technologies/client/web), capabilities include:
44
+
45
+ - [Multiple Providers and Scoping](#multiple-providers-and-scoping)
46
+ - [Re-rendering with Context Changes](#re-rendering-with-context-changes)
47
+ - [Re-rendering with Flag Configuration Changes](#re-rendering-with-flag-configuration-changes)
48
+ - [Suspense Support](#suspense-support)
49
+
50
+ ## ๐Ÿš€ Quick start
51
+
52
+ ### Requirements
53
+
54
+ - ES2022-compatible web browser (Chrome, Edge, Firefox, etc)
55
+ - React version 16.8+
30
56
 
31
- Here's a basic example of how to use the current API with the in-memory provider:
57
+ ### Install
58
+
59
+ #### npm
60
+
61
+ ```sh
62
+ npm install --save @openfeature/react-sdk
63
+ ```
64
+
65
+ #### Required peer dependencies
66
+
67
+ The following list contains the peer dependencies of `@openfeature/react-sdk` with its expected and compatible versions:
68
+
69
+ * `@openfeature/web-sdk`: >=0.4.10
70
+ * `react`: >=16.8.0
71
+
72
+ ### Usage
73
+
74
+ The example below shows how to use the `OpenFeatureProvider` with OpenFeature's `InMemoryProvider`.
32
75
 
33
76
  ```tsx
34
- import logo from './logo.svg';
35
- import './App.css';
36
- import { EvaluationContext, OpenFeatureProvider, useBooleanFlagValue, useBooleanFlagDetails, OpenFeature } from '@openfeature/react-sdk';
37
- import { FlagdWebProvider } from '@openfeature/flagd-web-provider';
77
+ import { EvaluationContext, OpenFeatureProvider, useBooleanFlagValue, useBooleanFlagDetails, OpenFeature, InMemoryProvider } from '@openfeature/react-sdk';
38
78
 
39
79
  const flagConfig = {
40
80
  'new-message': {
@@ -68,7 +108,6 @@ function Page() {
68
108
  return (
69
109
  <div className="App">
70
110
  <header className="App-header">
71
- <img src={logo} className="App-logo" alt="logo" />
72
111
  {newMessage ? <p>Welcome to this OpenFeature-enabled React app!</p> : <p>Welcome to this React app.</p>}
73
112
  </header>
74
113
  </div>
@@ -81,14 +120,14 @@ export default App;
81
120
  You use the detailed flag evaluation hooks to evaluate the flag and get additional information about the flag and the evaluation.
82
121
 
83
122
  ```tsx
84
- import { useBooleanFlagDetails} from '@openfeature/react-sdk';
123
+ import { useBooleanFlagDetails } from '@openfeature/react-sdk';
85
124
 
86
125
  const {
87
- value,
88
- variant,
89
- reason,
90
- flagMetadata
91
- } = useBooleanFlagDetails('new-message', false);
126
+ value,
127
+ variant,
128
+ reason,
129
+ flagMetadata
130
+ } = useBooleanFlagDetails('new-message', false);
92
131
  ```
93
132
 
94
133
  ### Multiple Providers and Scoping
@@ -182,3 +221,7 @@ function Fallback() {
182
221
  return <p>Waiting for provider to be ready...</p>;
183
222
  }
184
223
  ```
224
+
225
+ ## Resources
226
+
227
+ - [Example repo](https://github.com/open-feature/react-test-app)
package/dist/cjs/index.js CHANGED
@@ -3,22 +3,8 @@ var __create = Object.create;
3
3
  var __defProp = Object.defineProperty;
4
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
7
6
  var __getProtoOf = Object.getPrototypeOf;
8
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
9
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
10
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
11
- var __spreadValues = (a, b) => {
12
- for (var prop in b || (b = {}))
13
- if (__hasOwnProp.call(b, prop))
14
- __defNormalProp(a, prop, b[prop]);
15
- if (__getOwnPropSymbols)
16
- for (var prop of __getOwnPropSymbols(b)) {
17
- if (__propIsEnum.call(b, prop))
18
- __defNormalProp(a, prop, b[prop]);
19
- }
20
- return a;
21
- };
22
8
  var __export = (target, all) => {
23
9
  for (var name in all)
24
10
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -121,7 +107,7 @@ function useObjectFlagDetails(flagKey, defaultValue, options) {
121
107
  }, options);
122
108
  }
123
109
  function attachHandlersAndResolve(flagKey, defaultValue, resolver, options) {
124
- const defaultedOptions = __spreadValues(__spreadValues({}, DEFAULT_OPTIONS), options);
110
+ const defaultedOptions = { ...DEFAULT_OPTIONS, ...options };
125
111
  const [, updateState] = (0, import_react.useState)();
126
112
  const forceUpdate = () => {
127
113
  updateState({});
@@ -2,6 +2,6 @@
2
2
  "version": 3,
3
3
  "sources": ["../../src/index.ts", "../../src/use-feature-flag.ts", "../../src/provider.tsx"],
4
4
  "sourcesContent": ["export * from './use-feature-flag';\nexport * from './provider';\n// re-export the web-sdk so consumers can access that API from the react-sdk\nexport * from '@openfeature/web-sdk';\n", "import { Client, EvaluationDetails, FlagEvaluationOptions, FlagValue, JsonValue, ProviderEvents, ProviderStatus } from '@openfeature/web-sdk';\nimport { Dispatch, SetStateAction, useEffect, useState } from 'react';\nimport { useOpenFeatureClient } from './provider';\n\ntype ReactFlagEvaluationOptions = {\n /**\n * Suspend flag evaluations while the provider is not ready.\n * Set to false if you don't want to use React Suspense API.\n * Defaults to true.\n */\n suspend?: boolean,\n /**\n * Update the component if the provider emits a ConfigurationChanged event.\n * Set to false to prevent components from re-rendering when flag value changes\n * are received by the associated provider.\n * Defaults to true.\n */\n updateOnConfigurationChanged?: boolean,\n /**\n * Update the component when the OpenFeature context changes.\n * Set to false to prevent components from re-rendering when attributes which \n * may be factors in flag evaluation change.\n * Defaults to true.\n */\n updateOnContextChanged?: boolean,\n} & FlagEvaluationOptions;\n\nconst DEFAULT_OPTIONS: ReactFlagEvaluationOptions = {\n updateOnContextChanged: true,\n updateOnConfigurationChanged: true,\n suspend: true,\n};\n\nenum SuspendState {\n Pending,\n Success,\n Error\n}\n\n/**\n * Evaluates a feature flag, returning a boolean.\n * By default, components will re-render when the flag value changes.\n * @param {string} flagKey the flag identifier\n * @param {boolean} defaultValue the default value\n * @param {ReactFlagEvaluationOptions} options options for this evaluation\n * @returns { boolean} a EvaluationDetails object for this evaluation\n */\nexport function useBooleanFlagValue(flagKey: string, defaultValue: boolean, options?: ReactFlagEvaluationOptions): boolean {\n return useBooleanFlagDetails(flagKey, defaultValue, options).value;\n}\n\n/**\n * Evaluates a feature flag, returning evaluation details.\n * By default, components will re-render when the flag value changes.\n * @param {string} flagKey the flag identifier\n * @param {boolean} defaultValue the default value\n * @param {ReactFlagEvaluationOptions} options options for this evaluation\n * @returns { EvaluationDetails<boolean>} a EvaluationDetails object for this evaluation\n */\nexport function useBooleanFlagDetails(flagKey: string, defaultValue: boolean, options?: ReactFlagEvaluationOptions): EvaluationDetails<boolean> {\n return attachHandlersAndResolve(flagKey, defaultValue, (client) => {\n return client.getBooleanDetails;\n }, options);\n}\n\n/**\n * Evaluates a feature flag, returning a string.\n * By default, components will re-render when the flag value changes.\n * @param {string} flagKey the flag identifier\n * @template {string} [T=string] A optional generic argument constraining the string\n * @param {T} defaultValue the default value\n * @param {ReactFlagEvaluationOptions} options options for this evaluation\n * @returns { boolean} a EvaluationDetails object for this evaluation\n */\nexport function useStringFlagValue<T extends string = string>(flagKey: string, defaultValue: T, options?: ReactFlagEvaluationOptions): T {\n return useStringFlagDetails(flagKey, defaultValue, options).value;\n}\n\n/**\n * Evaluates a feature flag, returning evaluation details.\n * By default, components will re-render when the flag value changes.\n * @param {string} flagKey the flag identifier\n * @template {string} [T=string] A optional generic argument constraining the string\n * @param {T} defaultValue the default value\n * @param {ReactFlagEvaluationOptions} options options for this evaluation\n * @returns { EvaluationDetails<string>} a EvaluationDetails object for this evaluation\n */\nexport function useStringFlagDetails<T extends string = string>(flagKey: string, defaultValue: T, options?: ReactFlagEvaluationOptions): EvaluationDetails<T> {\n return attachHandlersAndResolve(flagKey, defaultValue, (client) => {\n return client.getStringDetails<T>;\n }, options);\n}\n\n/**\n * Evaluates a feature flag, returning a number.\n * By default, components will re-render when the flag value changes.\n * @param {string} flagKey the flag identifier\n * @template {number} [T=number] A optional generic argument constraining the number\n * @param {T} defaultValue the default value\n * @param {ReactFlagEvaluationOptions} options options for this evaluation\n * @returns { boolean} a EvaluationDetails object for this evaluation\n */\nexport function useNumberFlagValue<T extends number = number>(flagKey: string, defaultValue: T, options?: ReactFlagEvaluationOptions): T {\n return useNumberFlagDetails(flagKey, defaultValue, options).value;\n}\n\n/**\n * Evaluates a feature flag, returning evaluation details.\n * By default, components will re-render when the flag value changes.\n * @param {string} flagKey the flag identifier\n * @template {number} [T=number] A optional generic argument constraining the number\n * @param {T} defaultValue the default value\n * @param {ReactFlagEvaluationOptions} options options for this evaluation\n * @returns { EvaluationDetails<number>} a EvaluationDetails object for this evaluation\n */\nexport function useNumberFlagDetails<T extends number = number>(flagKey: string, defaultValue: T, options?: ReactFlagEvaluationOptions): EvaluationDetails<T> {\n return attachHandlersAndResolve(flagKey, defaultValue, (client) => {\n return client.getNumberDetails<T>;\n }, options);\n}\n\n/**\n * Evaluates a feature flag, returning an object.\n * By default, components will re-render when the flag value changes.\n * @param {string} flagKey the flag identifier\n * @template {JsonValue} [T=JsonValue] A optional generic argument describing the structure\n * @param {T} defaultValue the default value\n * @param {ReactFlagEvaluationOptions} options options for this evaluation\n * @returns { boolean} a EvaluationDetails object for this evaluation\n */\nexport function useObjectFlagValue<T extends JsonValue = JsonValue>(flagKey: string, defaultValue: T, options?: ReactFlagEvaluationOptions): T {\n return useObjectFlagDetails<T>(flagKey, defaultValue, options).value;\n}\n\n/**\n * Evaluates a feature flag, returning evaluation details.\n * By default, components will re-render when the flag value changes.\n * @param {string} flagKey the flag identifier\n * @param {T} defaultValue the default value\n * @template {JsonValue} [T=JsonValue] A optional generic argument describing the structure\n * @param {ReactFlagEvaluationOptions} options options for this evaluation\n * @returns { EvaluationDetails<T>} a EvaluationDetails object for this evaluation\n */\nexport function useObjectFlagDetails<T extends JsonValue = JsonValue>(flagKey: string, defaultValue: T, options?: ReactFlagEvaluationOptions): EvaluationDetails<T> {\n return attachHandlersAndResolve(flagKey, defaultValue, (client) => {\n return client.getObjectDetails<T>;\n }, options);\n}\n\nfunction attachHandlersAndResolve<T extends FlagValue>(flagKey: string, defaultValue: T, resolver: (client: Client) => (flagKey: string, defaultValue: T) => EvaluationDetails<T>, options?: ReactFlagEvaluationOptions): EvaluationDetails<T> {\n const defaultedOptions = { ...DEFAULT_OPTIONS, ...options };\n const [, updateState] = useState<object | undefined>();\n const forceUpdate = () => {\n updateState({});\n };\n const client = useOpenFeatureClient();\n\n useEffect(() => {\n\n if (client.providerStatus !== ProviderStatus.READY) {\n // update when the provider is ready\n client.addHandler(ProviderEvents.Ready, forceUpdate);\n if (defaultedOptions.suspend) {\n suspend(client, updateState);\n }\n }\n\n if (defaultedOptions.updateOnContextChanged) {\n // update when the context changes\n client.addHandler(ProviderEvents.ContextChanged, forceUpdate);\n }\n\n if (defaultedOptions.updateOnConfigurationChanged) {\n // update when the provider configuration changes\n client.addHandler(ProviderEvents.ConfigurationChanged, forceUpdate);\n }\n return () => {\n // cleanup the handlers (we can do this unconditionally with no impact)\n client.removeHandler(ProviderEvents.Ready, forceUpdate);\n client.removeHandler(ProviderEvents.ContextChanged, forceUpdate);\n client.removeHandler(ProviderEvents.ConfigurationChanged, forceUpdate);\n };\n }, [client]);\n\n return resolver(client).call(client, flagKey, defaultValue);\n}\n\n/**\n * Suspend function. If this runs, components using the calling hook will be suspended.\n * @param {Client} client the OpenFeature client\n * @param {Function} updateState the state update function\n */\nfunction suspend(client: Client, updateState: Dispatch<SetStateAction<object | undefined>>) {\n let suspendResolver: () => void;\n let suspendRejecter: () => void;\n const suspendPromise = new Promise<void>((resolve) => {\n suspendResolver = () => {\n resolve();\n client.removeHandler(ProviderEvents.Ready, suspendResolver); // remove handler once it's run\n };\n suspendRejecter = () => {\n resolve(); // we still resolve here, since we don't want to throw errors\n client.removeHandler(ProviderEvents.Error, suspendRejecter); // remove handler once it's run\n };\n client.addHandler(ProviderEvents.Ready, suspendResolver);\n client.addHandler(ProviderEvents.Error, suspendRejecter);\n });\n updateState(suspenseWrapper(suspendPromise));\n}\n\n/**\n * Promise wrapper that throws unresolved promises to support React suspense.\n * @param {Promise<T>} promise to wrap\n * @template T flag type\n * @returns {Function} suspense-compliant lambda\n */\nfunction suspenseWrapper <T>(promise: Promise<T>) {\n let status: SuspendState = SuspendState.Pending;\n let result: T;\n\n const suspended = promise.then(\n (value) => {\n status = SuspendState.Success;\n result = value;\n },\n (error) => {\n status = SuspendState.Error;\n result = error;\n }\n );\n\n return () => {\n switch (status) {\n case SuspendState.Pending:\n throw suspended;\n case SuspendState.Success:\n return result;\n case SuspendState.Error:\n throw result;\n default:\n throw new Error('Suspending promise is in an unknown state.');\n }\n };\n};", "import * as React from 'react';\nimport { Client, OpenFeature } from '@openfeature/web-sdk';\n\ntype ClientOrClientName =\n | {\n /**\n * The name of the client.\n * @see OpenFeature.setProvider() and overloads.\n */\n clientName: string;\n /**\n * OpenFeature client to use.\n */\n client?: never;\n }\n | {\n /**\n * OpenFeature client to use.\n */\n client: Client;\n /**\n * The name of the client.\n * @see OpenFeature.setProvider() and overloads.\n */\n clientName?: never;\n };\n\ntype ProviderProps = {\n children?: React.ReactNode;\n} & ClientOrClientName;\n\nconst Context = React.createContext<Client | undefined>(undefined);\n\nexport const OpenFeatureProvider = ({ client, clientName, children }: ProviderProps) => {\n if (!client) {\n client = OpenFeature.getClient(clientName);\n }\n\n return <Context.Provider value={client}>{children}</Context.Provider>;\n};\n\nexport const useOpenFeatureClient = () => {\n const client = React.useContext(Context);\n\n if (!client) {\n throw new Error(\n 'No OpenFeature client available - components using OpenFeature must be wrapped with an <OpenFeatureProvider>'\n );\n }\n\n return client;\n};\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,kBAAuH;AACvH,mBAA8D;;;ACD9D,YAAuB;AACvB,qBAAoC;AA8BpC,IAAM,UAAgB,oBAAkC,MAAS;AAE1D,IAAM,sBAAsB,CAAC,EAAE,QAAQ,YAAY,SAAS,MAAqB;AACtF,MAAI,CAAC,QAAQ;AACX,aAAS,2BAAY,UAAU,UAAU;AAAA,EAC3C;AAEA,SAAO,oCAAC,QAAQ,UAAR,EAAiB,OAAO,U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,+BAAe,sBAAsB,WAAW;AAAA,IACpE;AACA,WAAO,MAAM;AAEX,aAAO,cAAc,+BAAe,OAAO,WAAW;AACtD,aAAO,cAAc,+BAAe,gBAAgB,WAAW;AAC/D,aAAO,cAAc,+BAAe,sBAAsB,WAAW;AAAA,IACvE;AAAA,EACF,GAAG,CAAC,MAAM,CAAC;AAEX,SAAO,SAAS,MAAM,EAAE,KAAK,QAAQ,SAAS,YAAY;AAC5D;AAOA,SAAS,QAAQ,QAAgB,aAA2D;AAC1F,MAAI;AACJ,MAAI;AACJ,QAAM,iBAAiB,IAAI,QAAc,CAAC,YAAY;AACpD,sBAAkB,MAAM;AACtB,cAAQ;AACR,aAAO,cAAc,+BAAe,OAAO,eAAe;AAAA,IAC5D;AACA,sBAAkB,MAAM;AACtB,cAAQ;AACR,aAAO,cAAc,+BAAe,OAAO,eAAe;AAAA,IAC5D;AACA,WAAO,WAAW,+BAAe,OAAO,eAAe;AACvD,WAAO,WAAW,+BAAe,OAAO,eAAe;AAAA,EACzD,CAAC;AACD,cAAY,gBAAgB,cAAc,CAAC;AAC7C;AAQA,SAAS,gBAAoB,SAAqB;AAChD,MAAI,SAAuB;AAC3B,MAAI;AAEJ,QAAM,YAAY,QAAQ;AAAA,IACxB,CAAC,UAAU;AACT,eAAS;AACT,eAAS;AAAA,IACX;AAAA,IACA,CAAC,UAAU;AACT,eAAS;AACT,eAAS;AAAA,IACX;AAAA,EACF;AAEA,SAAO,MAAM;AACX,YAAQ,QAAQ;AAAA,MACd,KAAK;AACH,cAAM;AAAA,MACR,KAAK;AACH,eAAO;AAAA,MACT,KAAK;AACH,cAAM;AAAA,MACR;AACE,cAAM,IAAI,MAAM,4CAA4C;AAAA,IAChE;AAAA,EACF;AACF;;;ADhPA,wBAAc,iCAHd;",
6
6
  "names": ["import_web_sdk"]
7
7
  }
package/dist/esm/index.js CHANGED
@@ -1,20 +1,3 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
3
- var __hasOwnProp = Object.prototype.hasOwnProperty;
4
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
5
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
- var __spreadValues = (a, b) => {
7
- for (var prop in b || (b = {}))
8
- if (__hasOwnProp.call(b, prop))
9
- __defNormalProp(a, prop, b[prop]);
10
- if (__getOwnPropSymbols)
11
- for (var prop of __getOwnPropSymbols(b)) {
12
- if (__propIsEnum.call(b, prop))
13
- __defNormalProp(a, prop, b[prop]);
14
- }
15
- return a;
16
- };
17
-
18
1
  // src/use-feature-flag.ts
19
2
  import { ProviderEvents, ProviderStatus } from "@openfeature/web-sdk";
20
3
  import { useEffect, useState } from "react";
@@ -78,7 +61,7 @@ function useObjectFlagDetails(flagKey, defaultValue, options) {
78
61
  }, options);
79
62
  }
80
63
  function attachHandlersAndResolve(flagKey, defaultValue, resolver, options) {
81
- const defaultedOptions = __spreadValues(__spreadValues({}, DEFAULT_OPTIONS), options);
64
+ const defaultedOptions = { ...DEFAULT_OPTIONS, ...options };
82
65
  const [, updateState] = useState();
83
66
  const forceUpdate = () => {
84
67
  updateState({});
@@ -2,6 +2,6 @@
2
2
  "version": 3,
3
3
  "sources": ["../../src/use-feature-flag.ts", "../../src/provider.tsx", "../../src/index.ts"],
4
4
  "sourcesContent": ["import { Client, EvaluationDetails, FlagEvaluationOptions, FlagValue, JsonValue, ProviderEvents, ProviderStatus } from '@openfeature/web-sdk';\nimport { Dispatch, SetStateAction, useEffect, useState } from 'react';\nimport { useOpenFeatureClient } from './provider';\n\ntype ReactFlagEvaluationOptions = {\n /**\n * Suspend flag evaluations while the provider is not ready.\n * Set to false if you don't want to use React Suspense API.\n * Defaults to true.\n */\n suspend?: boolean,\n /**\n * Update the component if the provider emits a ConfigurationChanged event.\n * Set to false to prevent components from re-rendering when flag value changes\n * are received by the associated provider.\n * Defaults to true.\n */\n updateOnConfigurationChanged?: boolean,\n /**\n * Update the component when the OpenFeature context changes.\n * Set to false to prevent components from re-rendering when attributes which \n * may be factors in flag evaluation change.\n * Defaults to true.\n */\n updateOnContextChanged?: boolean,\n} & FlagEvaluationOptions;\n\nconst DEFAULT_OPTIONS: ReactFlagEvaluationOptions = {\n updateOnContextChanged: true,\n updateOnConfigurationChanged: true,\n suspend: true,\n};\n\nenum SuspendState {\n Pending,\n Success,\n Error\n}\n\n/**\n * Evaluates a feature flag, returning a boolean.\n * By default, components will re-render when the flag value changes.\n * @param {string} flagKey the flag identifier\n * @param {boolean} defaultValue the default value\n * @param {ReactFlagEvaluationOptions} options options for this evaluation\n * @returns { boolean} a EvaluationDetails object for this evaluation\n */\nexport function useBooleanFlagValue(flagKey: string, defaultValue: boolean, options?: ReactFlagEvaluationOptions): boolean {\n return useBooleanFlagDetails(flagKey, defaultValue, options).value;\n}\n\n/**\n * Evaluates a feature flag, returning evaluation details.\n * By default, components will re-render when the flag value changes.\n * @param {string} flagKey the flag identifier\n * @param {boolean} defaultValue the default value\n * @param {ReactFlagEvaluationOptions} options options for this evaluation\n * @returns { EvaluationDetails<boolean>} a EvaluationDetails object for this evaluation\n */\nexport function useBooleanFlagDetails(flagKey: string, defaultValue: boolean, options?: ReactFlagEvaluationOptions): EvaluationDetails<boolean> {\n return attachHandlersAndResolve(flagKey, defaultValue, (client) => {\n return client.getBooleanDetails;\n }, options);\n}\n\n/**\n * Evaluates a feature flag, returning a string.\n * By default, components will re-render when the flag value changes.\n * @param {string} flagKey the flag identifier\n * @template {string} [T=string] A optional generic argument constraining the string\n * @param {T} defaultValue the default value\n * @param {ReactFlagEvaluationOptions} options options for this evaluation\n * @returns { boolean} a EvaluationDetails object for this evaluation\n */\nexport function useStringFlagValue<T extends string = string>(flagKey: string, defaultValue: T, options?: ReactFlagEvaluationOptions): T {\n return useStringFlagDetails(flagKey, defaultValue, options).value;\n}\n\n/**\n * Evaluates a feature flag, returning evaluation details.\n * By default, components will re-render when the flag value changes.\n * @param {string} flagKey the flag identifier\n * @template {string} [T=string] A optional generic argument constraining the string\n * @param {T} defaultValue the default value\n * @param {ReactFlagEvaluationOptions} options options for this evaluation\n * @returns { EvaluationDetails<string>} a EvaluationDetails object for this evaluation\n */\nexport function useStringFlagDetails<T extends string = string>(flagKey: string, defaultValue: T, options?: ReactFlagEvaluationOptions): EvaluationDetails<T> {\n return attachHandlersAndResolve(flagKey, defaultValue, (client) => {\n return client.getStringDetails<T>;\n }, options);\n}\n\n/**\n * Evaluates a feature flag, returning a number.\n * By default, components will re-render when the flag value changes.\n * @param {string} flagKey the flag identifier\n * @template {number} [T=number] A optional generic argument constraining the number\n * @param {T} defaultValue the default value\n * @param {ReactFlagEvaluationOptions} options options for this evaluation\n * @returns { boolean} a EvaluationDetails object for this evaluation\n */\nexport function useNumberFlagValue<T extends number = number>(flagKey: string, defaultValue: T, options?: ReactFlagEvaluationOptions): T {\n return useNumberFlagDetails(flagKey, defaultValue, options).value;\n}\n\n/**\n * Evaluates a feature flag, returning evaluation details.\n * By default, components will re-render when the flag value changes.\n * @param {string} flagKey the flag identifier\n * @template {number} [T=number] A optional generic argument constraining the number\n * @param {T} defaultValue the default value\n * @param {ReactFlagEvaluationOptions} options options for this evaluation\n * @returns { EvaluationDetails<number>} a EvaluationDetails object for this evaluation\n */\nexport function useNumberFlagDetails<T extends number = number>(flagKey: string, defaultValue: T, options?: ReactFlagEvaluationOptions): EvaluationDetails<T> {\n return attachHandlersAndResolve(flagKey, defaultValue, (client) => {\n return client.getNumberDetails<T>;\n }, options);\n}\n\n/**\n * Evaluates a feature flag, returning an object.\n * By default, components will re-render when the flag value changes.\n * @param {string} flagKey the flag identifier\n * @template {JsonValue} [T=JsonValue] A optional generic argument describing the structure\n * @param {T} defaultValue the default value\n * @param {ReactFlagEvaluationOptions} options options for this evaluation\n * @returns { boolean} a EvaluationDetails object for this evaluation\n */\nexport function useObjectFlagValue<T extends JsonValue = JsonValue>(flagKey: string, defaultValue: T, options?: ReactFlagEvaluationOptions): T {\n return useObjectFlagDetails<T>(flagKey, defaultValue, options).value;\n}\n\n/**\n * Evaluates a feature flag, returning evaluation details.\n * By default, components will re-render when the flag value changes.\n * @param {string} flagKey the flag identifier\n * @param {T} defaultValue the default value\n * @template {JsonValue} [T=JsonValue] A optional generic argument describing the structure\n * @param {ReactFlagEvaluationOptions} options options for this evaluation\n * @returns { EvaluationDetails<T>} a EvaluationDetails object for this evaluation\n */\nexport function useObjectFlagDetails<T extends JsonValue = JsonValue>(flagKey: string, defaultValue: T, options?: ReactFlagEvaluationOptions): EvaluationDetails<T> {\n return attachHandlersAndResolve(flagKey, defaultValue, (client) => {\n return client.getObjectDetails<T>;\n }, options);\n}\n\nfunction attachHandlersAndResolve<T extends FlagValue>(flagKey: string, defaultValue: T, resolver: (client: Client) => (flagKey: string, defaultValue: T) => EvaluationDetails<T>, options?: ReactFlagEvaluationOptions): EvaluationDetails<T> {\n const defaultedOptions = { ...DEFAULT_OPTIONS, ...options };\n const [, updateState] = useState<object | undefined>();\n const forceUpdate = () => {\n updateState({});\n };\n const client = useOpenFeatureClient();\n\n useEffect(() => {\n\n if (client.providerStatus !== ProviderStatus.READY) {\n // update when the provider is ready\n client.addHandler(ProviderEvents.Ready, forceUpdate);\n if (defaultedOptions.suspend) {\n suspend(client, updateState);\n }\n }\n\n if (defaultedOptions.updateOnContextChanged) {\n // update when the context changes\n client.addHandler(ProviderEvents.ContextChanged, forceUpdate);\n }\n\n if (defaultedOptions.updateOnConfigurationChanged) {\n // update when the provider configuration changes\n client.addHandler(ProviderEvents.ConfigurationChanged, forceUpdate);\n }\n return () => {\n // cleanup the handlers (we can do this unconditionally with no impact)\n client.removeHandler(ProviderEvents.Ready, forceUpdate);\n client.removeHandler(ProviderEvents.ContextChanged, forceUpdate);\n client.removeHandler(ProviderEvents.ConfigurationChanged, forceUpdate);\n };\n }, [client]);\n\n return resolver(client).call(client, flagKey, defaultValue);\n}\n\n/**\n * Suspend function. If this runs, components using the calling hook will be suspended.\n * @param {Client} client the OpenFeature client\n * @param {Function} updateState the state update function\n */\nfunction suspend(client: Client, updateState: Dispatch<SetStateAction<object | undefined>>) {\n let suspendResolver: () => void;\n let suspendRejecter: () => void;\n const suspendPromise = new Promise<void>((resolve) => {\n suspendResolver = () => {\n resolve();\n client.removeHandler(ProviderEvents.Ready, suspendResolver); // remove handler once it's run\n };\n suspendRejecter = () => {\n resolve(); // we still resolve here, since we don't want to throw errors\n client.removeHandler(ProviderEvents.Error, suspendRejecter); // remove handler once it's run\n };\n client.addHandler(ProviderEvents.Ready, suspendResolver);\n client.addHandler(ProviderEvents.Error, suspendRejecter);\n });\n updateState(suspenseWrapper(suspendPromise));\n}\n\n/**\n * Promise wrapper that throws unresolved promises to support React suspense.\n * @param {Promise<T>} promise to wrap\n * @template T flag type\n * @returns {Function} suspense-compliant lambda\n */\nfunction suspenseWrapper <T>(promise: Promise<T>) {\n let status: SuspendState = SuspendState.Pending;\n let result: T;\n\n const suspended = promise.then(\n (value) => {\n status = SuspendState.Success;\n result = value;\n },\n (error) => {\n status = SuspendState.Error;\n result = error;\n }\n );\n\n return () => {\n switch (status) {\n case SuspendState.Pending:\n throw suspended;\n case SuspendState.Success:\n return result;\n case SuspendState.Error:\n throw result;\n default:\n throw new Error('Suspending promise is in an unknown state.');\n }\n };\n};", "import * as React from 'react';\nimport { Client, OpenFeature } from '@openfeature/web-sdk';\n\ntype ClientOrClientName =\n | {\n /**\n * The name of the client.\n * @see OpenFeature.setProvider() and overloads.\n */\n clientName: string;\n /**\n * OpenFeature client to use.\n */\n client?: never;\n }\n | {\n /**\n * OpenFeature client to use.\n */\n client: Client;\n /**\n * The name of the client.\n * @see OpenFeature.setProvider() and overloads.\n */\n clientName?: never;\n };\n\ntype ProviderProps = {\n children?: React.ReactNode;\n} & ClientOrClientName;\n\nconst Context = React.createContext<Client | undefined>(undefined);\n\nexport const OpenFeatureProvider = ({ client, clientName, children }: ProviderProps) => {\n if (!client) {\n client = OpenFeature.getClient(clientName);\n }\n\n return <Context.Provider value={client}>{children}</Context.Provider>;\n};\n\nexport const useOpenFeatureClient = () => {\n const client = React.useContext(Context);\n\n if (!client) {\n throw new Error(\n 'No OpenFeature client available - components using OpenFeature must be wrapped with an <OpenFeatureProvider>'\n );\n }\n\n return client;\n};\n", "export * from './use-feature-flag';\nexport * from './provider';\n// re-export the web-sdk so consumers can access that API from the react-sdk\nexport * from '@openfeature/web-sdk';\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA,SAAiF,gBAAgB,sBAAsB;AACvH,SAAmC,WAAW,gBAAgB;;;ACD9D,YAAY,WAAW;AACvB,SAAiB,mBAAmB;AA8BpC,IAAM,UAAgB,oBAAkC,MAAS;AAE1D,IAAM,sBAAsB,CAAC,EAAE,QAAQ,YAAY,SAAS,MAAqB;AACtF,MAAI,CAAC,QAAQ;AACX,aAAS,YAAY,UAAU,UAAU;AAAA,EAC3C;AAEA,SAAO,oCAAC,QAAQ,UAAR,EAAiB,OAAO,UAAS,QAAS;AACpD;AAEO,IAAM,uBAAuB,MAAM;AACxC,QAAM,SAAe,iBAAW,OAAO;AAEvC,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;;;ADxBA,IAAM,kBAA8C;AAAA,EAClD,wBAAwB;AAAA,EACxB,8BAA8B;AAAA,EAC9B,SAAS;AACX;AAgBO,SAAS,oBAAoB,SAAiB,cAAuB,SAA+C;AACzH,SAAO,sBAAsB,SAAS,cAAc,OAAO,EAAE;AAC/D;AAUO,SAAS,sBAAsB,SAAiB,cAAuB,SAAkE;AAC9I,SAAO,yBAAyB,SAAS,cAAc,CAAC,WAAW;AACjE,WAAO,OAAO;AAAA,EAChB,GAAI,OAAO;AACb;AAWO,SAAS,mBAA8C,SAAiB,cAAiB,SAAyC;AACvI,SAAO,qBAAqB,SAAS,cAAc,OAAO,EAAE;AAC9D;AAWO,SAAS,qBAAgD,SAAiB,cAAiB,SAA4D;AAC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,QAAQ;AAAA,IACxB,CAAC,UAAU;AACT,eAAS;AACT,eAAS;AAAA,IACX;AAAA,IACA,CAAC,UAAU;AACT,eAAS;AACT,eAAS;AAAA,IACX;AAAA,EACF;AAEA,SAAO,MAAM;AACX,YAAQ,QAAQ;AAAA,MACd,KAAK;AACH,cAAM;AAAA,MACR,KAAK;AACH,eAAO;AAAA,MACT,KAAK;AACH,cAAM;AAAA,MACR;AACE,cAAM,IAAI,MAAM,4CAA4C;AAAA,IAChE;AAAA,EACF;AACF;;;AEhPA,cAAc;",
6
6
  "names": []
7
7
  }
package/dist/types.d.ts CHANGED
@@ -1,996 +1,6 @@
1
+ import { EvaluationDetails, JsonValue, FlagEvaluationOptions, Client } from '@openfeature/web-sdk';
2
+ export * from '@openfeature/web-sdk';
1
3
  import * as React from 'react';
2
- import EventEmitter from 'events';
3
-
4
- type FlagValueType = 'boolean' | 'string' | 'number' | 'object';
5
- type PrimitiveValue = null | boolean | string | number;
6
- type JsonObject = {
7
- [key: string]: JsonValue;
8
- };
9
- type JsonArray = JsonValue[];
10
- /**
11
- * Represents a JSON node value.
12
- */
13
- type JsonValue = PrimitiveValue | JsonObject | JsonArray;
14
- /**
15
- * Represents a JSON node value, or Date.
16
- */
17
- type FlagValue = boolean | string | number | JsonValue;
18
- type ResolutionReason = keyof typeof StandardResolutionReasons | (string & Record<never, never>);
19
- /**
20
- * A structure which supports definition of arbitrary properties, with keys of type string, and values of type boolean, string, or number.
21
- *
22
- * This structure is populated by a provider for use by an Application Author (via the Evaluation API) or an Application Integrator (via hooks).
23
- */
24
- type FlagMetadata = Record<string, string | number | boolean>;
25
- type ResolutionDetails<U> = {
26
- value: U;
27
- variant?: string;
28
- flagMetadata?: FlagMetadata;
29
- reason?: ResolutionReason;
30
- errorCode?: ErrorCode;
31
- errorMessage?: string;
32
- };
33
- type EvaluationDetails<T extends FlagValue> = {
34
- flagKey: string;
35
- flagMetadata: Readonly<FlagMetadata>;
36
- } & ResolutionDetails<T>;
37
- declare const StandardResolutionReasons: {
38
- /**
39
- * The resolved value was the result of a dynamic evaluation, such as a rule or specific user-targeting.
40
- */
41
- readonly TARGETING_MATCH: "TARGETING_MATCH";
42
- /**
43
- * The resolved value was the result of pseudorandom assignment.
44
- */
45
- readonly SPLIT: "SPLIT";
46
- /**
47
- * The resolved value was the result of the flag being disabled in the management system.
48
- */
49
- readonly DISABLED: "DISABLED";
50
- /**
51
- * The resolved value was configured statically, or otherwise fell back to a pre-configured value.
52
- */
53
- readonly DEFAULT: "DEFAULT";
54
- /**
55
- * The reason for the resolved value could not be determined.
56
- */
57
- readonly UNKNOWN: "UNKNOWN";
58
- /**
59
- * The resolved value is static (no dynamic evaluation).
60
- */
61
- readonly STATIC: "STATIC";
62
- /**
63
- * The resolved value was retrieved from cache.
64
- */
65
- readonly CACHED: "CACHED";
66
- /**
67
- * The resolved value was the result of an error.
68
- *
69
- * Note: The `errorCode` and `errorMessage` fields may contain additional details of this error.
70
- */
71
- readonly ERROR: "ERROR";
72
- };
73
- declare enum ErrorCode {
74
- /**
75
- * The value was resolved before the provider was ready.
76
- */
77
- PROVIDER_NOT_READY = "PROVIDER_NOT_READY",
78
- /**
79
- * The flag could not be found.
80
- */
81
- FLAG_NOT_FOUND = "FLAG_NOT_FOUND",
82
- /**
83
- * An error was encountered parsing data, such as a flag configuration.
84
- */
85
- PARSE_ERROR = "PARSE_ERROR",
86
- /**
87
- * The type of the flag value does not match the expected type.
88
- */
89
- TYPE_MISMATCH = "TYPE_MISMATCH",
90
- /**
91
- * The provider requires a targeting key and one was not provided in the evaluation context.
92
- */
93
- TARGETING_KEY_MISSING = "TARGETING_KEY_MISSING",
94
- /**
95
- * The evaluation context does not meet provider requirements.
96
- */
97
- INVALID_CONTEXT = "INVALID_CONTEXT",
98
- /**
99
- * An error with an unspecified code.
100
- */
101
- GENERAL = "GENERAL"
102
- }
103
-
104
- type EvaluationContextValue = PrimitiveValue | Date | {
105
- [key: string]: EvaluationContextValue;
106
- } | EvaluationContextValue[];
107
- /**
108
- * A container for arbitrary contextual data that can be used as a basis for dynamic evaluation
109
- */
110
- type EvaluationContext = {
111
- /**
112
- * A string uniquely identifying the subject (end-user, or client service) of a flag evaluation.
113
- * Providers may require this field for fractional flag evaluation, rules, or overrides targeting specific users.
114
- * Such providers may behave unpredictably if a targeting key is not specified at flag resolution.
115
- */
116
- targetingKey?: string;
117
- } & Record<string, EvaluationContextValue>;
118
- interface ManageContext<T> {
119
- /**
120
- * Access the evaluation context set on the receiver.
121
- * @returns {EvaluationContext} Evaluation context
122
- */
123
- getContext(): EvaluationContext;
124
- /**
125
- * Sets evaluation context that will be used during flag evaluations
126
- * on this receiver.
127
- * @template T The type of the receiver
128
- * @param {EvaluationContext} context Evaluation context
129
- * @returns {T} The receiver (this object)
130
- */
131
- setContext(context: EvaluationContext): T;
132
- }
133
-
134
- /**
135
- * An enumeration of possible events for server-sdk providers.
136
- */
137
- declare enum ServerProviderEvents {
138
- /**
139
- * The provider is ready to evaluate flags.
140
- */
141
- Ready = "PROVIDER_READY",
142
- /**
143
- * The provider is in an error state.
144
- */
145
- Error = "PROVIDER_ERROR",
146
- /**
147
- * The flag configuration in the source-of-truth has changed.
148
- */
149
- ConfigurationChanged = "PROVIDER_CONFIGURATION_CHANGED",
150
- /**
151
- * The provider's cached state is no longer valid and may not be up-to-date with the source of truth.
152
- */
153
- Stale = "PROVIDER_STALE"
154
- }
155
- /**
156
- * An enumeration of possible events for web-sdk providers.
157
- */
158
- declare enum ClientProviderEvents {
159
- /**
160
- * The provider is ready to evaluate flags.
161
- */
162
- Ready = "PROVIDER_READY",
163
- /**
164
- * The provider is in an error state.
165
- */
166
- Error = "PROVIDER_ERROR",
167
- /**
168
- * The flag configuration in the source-of-truth has changed.
169
- */
170
- ConfigurationChanged = "PROVIDER_CONFIGURATION_CHANGED",
171
- /**
172
- * The context associated with the provider has changed, and the provider has reconciled it's associated state.
173
- */
174
- ContextChanged = "PROVIDER_CONTEXT_CHANGED",
175
- /**
176
- * The provider's cached state is no longer valid and may not be up-to-date with the source of truth.
177
- */
178
- Stale = "PROVIDER_STALE"
179
- }
180
-
181
- /**
182
- * A type representing any possible ProviderEvent (server or client side).
183
- * If you are implementing a hook or provider, you probably want to import `ProviderEvents` from the respective SDK.
184
- */
185
- type AnyProviderEvent = ServerProviderEvents | ClientProviderEvents;
186
-
187
- /**
188
- * Returns true if the provider's status corresponds to the event.
189
- * If the provider's status is not defined, it matches READY.
190
- * @param {AnyProviderEvent} event event to match
191
- * @param {ProviderStatus} status status of provider
192
- * @returns {boolean} boolean indicating if the provider status corresponds to the event.
193
- */
194
- declare const statusMatchesEvent: <T extends AnyProviderEvent>(event: T, status?: ProviderStatus) => boolean;
195
-
196
- type EventMetadata = {
197
- [key: string]: string | boolean | number;
198
- };
199
- type CommonEventDetails = {
200
- providerName: string;
201
- clientName?: string;
202
- };
203
- type CommonEventProps = {
204
- message?: string;
205
- metadata?: EventMetadata;
206
- };
207
- type ReadyEvent = CommonEventProps;
208
- type ErrorEvent = CommonEventProps;
209
- type StaleEvent = CommonEventProps;
210
- type ConfigChangeEvent = CommonEventProps & {
211
- flagsChanged?: string[];
212
- };
213
- type EventMap = {
214
- [ClientProviderEvents.Ready]: ReadyEvent;
215
- [ClientProviderEvents.Error]: ErrorEvent;
216
- [ClientProviderEvents.Stale]: StaleEvent;
217
- [ClientProviderEvents.ContextChanged]: CommonEventProps;
218
- [ClientProviderEvents.ConfigurationChanged]: ConfigChangeEvent;
219
- };
220
- type EventContext<U extends Record<string, unknown> = Record<string, unknown>> = EventMap[ClientProviderEvents] & U;
221
- type EventDetails = EventContext & CommonEventDetails;
222
- type EventHandler = (eventDetails?: EventDetails) => Promise<unknown> | unknown;
223
- interface Eventing {
224
- /**
225
- * Adds a handler for the given provider event type.
226
- * The handlers are called in the order they have been added.
227
- * @param {AnyProviderEvent} eventType The provider event type to listen to
228
- * @param {EventHandler} handler The handler to run on occurrence of the event type
229
- */
230
- addHandler(eventType: AnyProviderEvent, handler: EventHandler): void;
231
- /**
232
- * Removes a handler for the given provider event type.
233
- * @param {AnyProviderEvent} eventType The provider event type to remove the listener for
234
- * @param {EventHandler} handler The handler to remove for the provider event type
235
- */
236
- removeHandler(eventType: AnyProviderEvent, handler: EventHandler): void;
237
- /**
238
- * Gets the current handlers for the given provider event type.
239
- * @param {AnyProviderEvent} eventType The provider event type to get the current handlers for
240
- * @returns {EventHandler[]} The handlers currently attached to the given provider event type
241
- */
242
- getHandlers(eventType: AnyProviderEvent): EventHandler[];
243
- }
244
-
245
- interface Logger {
246
- error(...args: unknown[]): void;
247
- warn(...args: unknown[]): void;
248
- info(...args: unknown[]): void;
249
- debug(...args: unknown[]): void;
250
- }
251
- interface ManageLogger<T> {
252
- /**
253
- * Sets a logger on this receiver. This logger supersedes to the global logger
254
- * and is passed to various components in the SDK.
255
- * The logger configured on the global API object will be used for all evaluations,
256
- * unless overridden in a particular client.
257
- * @template T The type of the receiver
258
- * @param {Logger} logger The logger to be used
259
- * @returns {T} The receiver (this object)
260
- */
261
- setLogger(logger: Logger): T;
262
- }
263
-
264
- declare class DefaultLogger implements Logger {
265
- error(...args: unknown[]): void;
266
- warn(...args: unknown[]): void;
267
- info(): void;
268
- debug(): void;
269
- }
270
-
271
- declare const LOG_LEVELS: Array<keyof Logger>;
272
- declare class SafeLogger implements Logger {
273
- private readonly logger;
274
- private readonly fallbackLogger;
275
- constructor(logger: Logger);
276
- error(...args: unknown[]): void;
277
- warn(...args: unknown[]): void;
278
- info(...args: unknown[]): void;
279
- debug(...args: unknown[]): void;
280
- private log;
281
- }
282
-
283
- /**
284
- * The GenericEventEmitter should only be used within the SDK. It supports additional properties that can be included
285
- * in the event details.
286
- */
287
- declare abstract class GenericEventEmitter<E extends AnyProviderEvent, AdditionalContext extends Record<string, unknown> = Record<string, unknown>> implements ManageLogger<GenericEventEmitter<E, AdditionalContext>> {
288
- private readonly globalLogger?;
289
- protected abstract readonly eventEmitter: PlatformEventEmitter;
290
- private readonly _handlers;
291
- private _eventLogger?;
292
- constructor(globalLogger?: (() => Logger) | undefined);
293
- emit(eventType: E, context?: EventContext): void;
294
- addHandler(eventType: AnyProviderEvent, handler: EventHandler): void;
295
- removeHandler(eventType: AnyProviderEvent, handler: EventHandler): void;
296
- removeAllHandlers(eventType?: AnyProviderEvent): void;
297
- getHandlers(eventType: AnyProviderEvent): EventHandler[];
298
- setLogger(logger: Logger): this;
299
- protected get _logger(): Logger | undefined;
300
- }
301
- /**
302
- * This is an un-exported type that corresponds to NodeJS.EventEmitter.
303
- * We can't use that type here, because this module is used in both the browser, and the server.
304
- * In the server, node (or whatever server runtime) provides an implementation for this.
305
- * In the browser, we bundle in the popular 'events' package, which is a polyfill of NodeJS.EventEmitter.
306
- */
307
- interface PlatformEventEmitter {
308
- addListener(eventName: string | symbol, listener: (...args: any[]) => void): this;
309
- on(eventName: string | symbol, listener: (...args: any[]) => void): this;
310
- once(eventName: string | symbol, listener: (...args: any[]) => void): this;
311
- removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this;
312
- off(eventName: string | symbol, listener: (...args: any[]) => void): this;
313
- removeAllListeners(event?: string | symbol): this;
314
- setMaxListeners(n: number): this;
315
- getMaxListeners(): number;
316
- listeners(eventName: string | symbol): Function[];
317
- rawListeners(eventName: string | symbol): Function[];
318
- emit(eventName: string | symbol, ...args: any[]): boolean;
319
- listenerCount(eventName: string | symbol, listener?: Function): number;
320
- prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this;
321
- prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this;
322
- eventNames(): Array<string | symbol>;
323
- }
324
-
325
- interface Metadata {
326
- }
327
-
328
- /**
329
- * Defines where the library is intended to be run.
330
- */
331
- type Paradigm = 'server' | 'client';
332
-
333
- /**
334
- * The state of the provider.
335
- */
336
- declare enum ProviderStatus {
337
- /**
338
- * The provider has not been initialized and cannot yet evaluate flags.
339
- */
340
- NOT_READY = "NOT_READY",
341
- /**
342
- * The provider is ready to resolve flags.
343
- */
344
- READY = "READY",
345
- /**
346
- * The provider is in an error state and unable to evaluate flags.
347
- */
348
- ERROR = "ERROR",
349
- /**
350
- * The provider's cached state is no longer valid and may not be up-to-date with the source of truth.
351
- */
352
- STALE = "STALE"
353
- }
354
- /**
355
- * Static data about the provider.
356
- */
357
- interface ProviderMetadata extends Metadata {
358
- readonly name: string;
359
- }
360
- interface CommonProvider {
361
- readonly metadata: ProviderMetadata;
362
- /**
363
- * Represents where the provider is intended to be run. If defined,
364
- * the SDK will enforce that the defined paradigm at runtime.
365
- */
366
- readonly runsOn?: Paradigm;
367
- /**
368
- * Returns a representation of the current readiness of the provider.
369
- * If the provider needs to be initialized, it should return {@link ProviderStatus.READY}.
370
- * If the provider is in an error state, it should return {@link ProviderStatus.ERROR}.
371
- * If the provider is functioning normally, it should return {@link ProviderStatus.NOT_READY}.
372
- *
373
- * _Providers which do not implement this method are assumed to be ready immediately._
374
- */
375
- readonly status?: ProviderStatus;
376
- /**
377
- * An event emitter for ProviderEvents.
378
- * @see ProviderEvents
379
- */
380
- events?: GenericEventEmitter<AnyProviderEvent>;
381
- /**
382
- * A function used to shut down the provider.
383
- * Called when this provider is replaced with a new one, or when the OpenFeature is shut down.
384
- */
385
- onClose?(): Promise<void>;
386
- /**
387
- * A function used to setup the provider.
388
- * Called by the SDK after the provider is set if the provider's status is {@link ProviderStatus.NOT_READY}.
389
- * When the returned promise resolves, the SDK fires the ProviderEvents.Ready event.
390
- * If the returned promise rejects, the SDK fires the ProviderEvents.Error event.
391
- * Use this function to perform any context-dependent setup within the provider.
392
- * @param context
393
- */
394
- initialize?(context?: EvaluationContext): Promise<void>;
395
- }
396
-
397
- interface ClientMetadata extends Metadata {
398
- readonly version?: string;
399
- readonly name?: string;
400
- readonly providerMetadata: ProviderMetadata;
401
- }
402
-
403
- type HookHints = Readonly<Record<string, unknown>>;
404
- interface HookContext<T extends FlagValue = FlagValue> {
405
- readonly flagKey: string;
406
- readonly defaultValue: T;
407
- readonly flagValueType: FlagValueType;
408
- readonly context: Readonly<EvaluationContext>;
409
- readonly clientMetadata: ClientMetadata;
410
- readonly providerMetadata: ProviderMetadata;
411
- readonly logger: Logger;
412
- }
413
- interface BeforeHookContext extends HookContext {
414
- context: EvaluationContext;
415
- }
416
-
417
- interface BaseHook<T extends FlagValue = FlagValue, BeforeHookReturn = unknown, HooksReturn = unknown> {
418
- /**
419
- * Runs before flag values are resolved from the provider.
420
- * If an EvaluationContext is returned, it will be merged with the pre-existing EvaluationContext.
421
- * @param hookContext
422
- * @param hookHints
423
- */
424
- before?(hookContext: BeforeHookContext, hookHints?: HookHints): BeforeHookReturn;
425
- /**
426
- * Runs after flag values are successfully resolved from the provider.
427
- * @param hookContext
428
- * @param evaluationDetails
429
- * @param hookHints
430
- */
431
- after?(hookContext: Readonly<HookContext<T>>, evaluationDetails: EvaluationDetails<T>, hookHints?: HookHints): HooksReturn;
432
- /**
433
- * Runs in the event of an unhandled error or promise rejection during flag resolution, or any attached hooks.
434
- * @param hookContext
435
- * @param error
436
- * @param hookHints
437
- */
438
- error?(hookContext: Readonly<HookContext<T>>, error: unknown, hookHints?: HookHints): HooksReturn;
439
- /**
440
- * Runs after all other hook stages, regardless of success or error.
441
- * Errors thrown here are unhandled by the client and will surface in application code.
442
- * @param hookContext
443
- * @param hookHints
444
- */
445
- finally?(hookContext: Readonly<HookContext<T>>, hookHints?: HookHints): HooksReturn;
446
- }
447
-
448
- interface EvaluationLifeCycle<T> {
449
- /**
450
- * Adds hooks that will run during flag evaluations on this receiver.
451
- * Hooks are executed in the order they were registered. Adding additional hooks
452
- * will not remove existing hooks.
453
- * Hooks registered on the global API object run with all evaluations.
454
- * Hooks registered on the client run with all evaluations on that client.
455
- * @template T The type of the receiver
456
- * @param {BaseHook[]} hooks A list of hooks that should always run
457
- * @returns {T} The receiver (this object)
458
- */
459
- addHooks(...hooks: BaseHook[]): T;
460
- /**
461
- * Access all the hooks that are registered on this receiver.
462
- * @returns {BaseHook<FlagValue>[]} A list of the client hooks
463
- */
464
- getHooks(): BaseHook[];
465
- /**
466
- * Clears all the hooks that are registered on this receiver.
467
- * @template T The type of the receiver
468
- * @returns {T} The receiver (this object)
469
- */
470
- clearHooks(): T;
471
- }
472
-
473
- declare abstract class OpenFeatureError extends Error {
474
- abstract code: ErrorCode;
475
- constructor(message?: string);
476
- }
477
-
478
- declare class GeneralError extends OpenFeatureError {
479
- code: ErrorCode;
480
- constructor(message?: string);
481
- }
482
-
483
- declare class FlagNotFoundError extends OpenFeatureError {
484
- code: ErrorCode;
485
- constructor(message?: string);
486
- }
487
-
488
- declare class ParseError extends OpenFeatureError {
489
- code: ErrorCode;
490
- constructor(message?: string);
491
- }
492
-
493
- declare class TypeMismatchError extends OpenFeatureError {
494
- code: ErrorCode;
495
- constructor(message?: string);
496
- }
497
-
498
- declare class TargetingKeyMissingError extends OpenFeatureError {
499
- code: ErrorCode;
500
- constructor(message?: string);
501
- }
502
-
503
- declare class InvalidContextError extends OpenFeatureError {
504
- code: ErrorCode;
505
- constructor(message?: string);
506
- }
507
-
508
- declare class ProviderNotReadyError extends OpenFeatureError {
509
- code: ErrorCode;
510
- constructor(message?: string);
511
- }
512
-
513
- /**
514
- * Checks whether the parameter is a string.
515
- * @param {unknown} value The value to check
516
- * @returns {value is string} True if the value is a string
517
- */
518
- declare function isString(value: unknown): value is string;
519
- /**
520
- * Returns the parameter if it is a string, otherwise returns undefined.
521
- * @param {unknown} value The value to check
522
- * @returns {string|undefined} The parameter if it is a string, otherwise undefined
523
- */
524
- declare function stringOrUndefined(value: unknown): string | undefined;
525
- /**
526
- * Checks whether the parameter is an object.
527
- * @param {unknown} value The value to check
528
- * @returns {value is string} True if the value is an object
529
- */
530
- declare function isObject<T extends object>(value: unknown): value is T;
531
- /**
532
- * Returns the parameter if it is an object, otherwise returns undefined.
533
- * @param {unknown} value The value to check
534
- * @returns {object|undefined} The parameter if it is an object, otherwise undefined
535
- */
536
- declare function objectOrUndefined<T extends object>(value: unknown): T | undefined;
537
-
538
- declare abstract class OpenFeatureCommonAPI<P extends CommonProvider = CommonProvider, H extends BaseHook = BaseHook> implements Eventing, EvaluationLifeCycle<OpenFeatureCommonAPI<P>>, ManageLogger<OpenFeatureCommonAPI<P>> {
539
- protected abstract _createEventEmitter(): GenericEventEmitter<AnyProviderEvent>;
540
- protected abstract _defaultProvider: P;
541
- protected abstract readonly _events: GenericEventEmitter<AnyProviderEvent>;
542
- protected _hooks: H[];
543
- protected _context: EvaluationContext;
544
- protected _logger: Logger;
545
- private readonly _clientEventHandlers;
546
- protected _clientProviders: Map<string, P>;
547
- protected _clientEvents: Map<string | undefined, GenericEventEmitter<AnyProviderEvent>>;
548
- protected _runsOn: Paradigm;
549
- constructor(category: Paradigm);
550
- addHooks(...hooks: H[]): this;
551
- getHooks(): H[];
552
- clearHooks(): this;
553
- setLogger(logger: Logger): this;
554
- /**
555
- * Get metadata about the default provider.
556
- * @returns {ProviderMetadata} Provider Metadata
557
- */
558
- get providerMetadata(): ProviderMetadata;
559
- /**
560
- * Get metadata about a registered provider using the client name.
561
- * An unbound or empty client name will return metadata from the default provider.
562
- * @param {string} [clientName] The name to identify the client
563
- * @returns {ProviderMetadata} Provider Metadata
564
- */
565
- getProviderMetadata(clientName?: string): ProviderMetadata;
566
- /**
567
- * Adds a handler for the given provider event type.
568
- * The handlers are called in the order they have been added.
569
- * API (global) events run for all providers.
570
- * @param {AnyProviderEvent} eventType The provider event type to listen to
571
- * @param {EventHandler} handler The handler to run on occurrence of the event type
572
- */
573
- addHandler<T extends AnyProviderEvent>(eventType: T, handler: EventHandler): void;
574
- /**
575
- * Removes a handler for the given provider event type.
576
- * @param {AnyProviderEvent} eventType The provider event type to remove the listener for
577
- * @param {EventHandler} handler The handler to remove for the provider event type
578
- */
579
- removeHandler<T extends AnyProviderEvent>(eventType: T, handler: EventHandler): void;
580
- /**
581
- * Removes all event handlers.
582
- */
583
- clearHandlers(): void;
584
- /**
585
- * Gets the current handlers for the given provider event type.
586
- * @param {AnyProviderEvent} eventType The provider event type to get the current handlers for
587
- * @returns {EventHandler[]} The handlers currently attached to the given provider event type
588
- */
589
- getHandlers<T extends AnyProviderEvent>(eventType: T): EventHandler[];
590
- /**
591
- * Sets the default provider for flag evaluations and returns a promise that resolves when the provider is ready.
592
- * This provider will be used by unnamed clients and named clients to which no provider is bound.
593
- * Setting a provider supersedes the current provider used in new and existing clients without a name.
594
- * @template P
595
- * @param {P} provider The provider responsible for flag evaluations.
596
- * @returns {Promise<void>}
597
- * @throws Uncaught exceptions thrown by the provider during initialization.
598
- */
599
- setProviderAndWait(provider: P): Promise<void>;
600
- /**
601
- * Sets the provider that OpenFeature will use for flag evaluations of providers with the given name.
602
- * A promise is returned that resolves when the provider is ready.
603
- * Setting a provider supersedes the current provider used in new and existing clients with that name.
604
- * @template P
605
- * @param {string} clientName The name to identify the client
606
- * @param {P} provider The provider responsible for flag evaluations.
607
- * @returns {Promise<void>}
608
- * @throws Uncaught exceptions thrown by the provider during initialization.
609
- */
610
- setProviderAndWait(clientName: string, provider: P): Promise<void>;
611
- /**
612
- * Sets the default provider for flag evaluations.
613
- * This provider will be used by unnamed clients and named clients to which no provider is bound.
614
- * Setting a provider supersedes the current provider used in new and existing clients without a name.
615
- * @template P
616
- * @param {P} provider The provider responsible for flag evaluations.
617
- * @returns {this} OpenFeature API
618
- */
619
- setProvider(provider: P): this;
620
- /**
621
- * Sets the provider that OpenFeature will use for flag evaluations of providers with the given name.
622
- * Setting a provider supersedes the current provider used in new and existing clients with that name.
623
- * @template P
624
- * @param {string} clientName The name to identify the client
625
- * @param {P} provider The provider responsible for flag evaluations.
626
- * @returns {this} OpenFeature API
627
- */
628
- setProvider(clientName: string, provider: P): this;
629
- private setAwaitableProvider;
630
- protected getProviderForClient(name?: string): P;
631
- protected buildAndCacheEventEmitterForClient(name?: string): GenericEventEmitter<AnyProviderEvent>;
632
- private getUnboundEmitters;
633
- protected getAssociatedEventEmitters(clientName: string | undefined): GenericEventEmitter<AnyProviderEvent, Record<string, unknown>>[];
634
- private transferListeners;
635
- close(): Promise<void>;
636
- protected clearProvidersAndSetDefault(defaultProvider: P): Promise<void>;
637
- private handleShutdownError;
638
- }
639
-
640
- interface FlagEvaluationOptions {
641
- hooks?: BaseHook[];
642
- hookHints?: HookHints;
643
- }
644
- interface Features {
645
- /**
646
- * Performs a flag evaluation that returns a boolean.
647
- * @param {string} flagKey The flag key uniquely identifies a particular flag
648
- * @param {boolean} defaultValue The value returned if an error occurs
649
- * @param {FlagEvaluationOptions} options Additional flag evaluation options
650
- * @returns {boolean} Flag evaluation response
651
- */
652
- getBooleanValue(flagKey: string, defaultValue: boolean, options?: FlagEvaluationOptions): boolean;
653
- /**
654
- * Performs a flag evaluation that a returns an evaluation details object.
655
- * @param {string} flagKey The flag key uniquely identifies a particular flag
656
- * @param {boolean} defaultValue The value returned if an error occurs
657
- * @param {FlagEvaluationOptions} options Additional flag evaluation options
658
- * @returns {EvaluationDetails<boolean>} Flag evaluation details response
659
- */
660
- getBooleanDetails(flagKey: string, defaultValue: boolean, options?: FlagEvaluationOptions): EvaluationDetails<boolean>;
661
- /**
662
- * Performs a flag evaluation that returns a string.
663
- * @param {string} flagKey The flag key uniquely identifies a particular flag
664
- * @template {string} T A optional generic argument constraining the string
665
- * @param {T} defaultValue The value returned if an error occurs
666
- * @param {FlagEvaluationOptions} options Additional flag evaluation options
667
- * @returns {T} Flag evaluation response
668
- */
669
- getStringValue(flagKey: string, defaultValue: string, options?: FlagEvaluationOptions): string;
670
- getStringValue<T extends string = string>(flagKey: string, defaultValue: T, options?: FlagEvaluationOptions): T;
671
- /**
672
- * Performs a flag evaluation that a returns an evaluation details object.
673
- * @param {string} flagKey The flag key uniquely identifies a particular flag
674
- * @template {string} T A optional generic argument constraining the string
675
- * @param {T} defaultValue The value returned if an error occurs
676
- * @param {FlagEvaluationOptions} options Additional flag evaluation options
677
- * @returns {EvaluationDetails<T>} Flag evaluation details response
678
- */
679
- getStringDetails(flagKey: string, defaultValue: string, options?: FlagEvaluationOptions): EvaluationDetails<string>;
680
- getStringDetails<T extends string = string>(flagKey: string, defaultValue: T, options?: FlagEvaluationOptions): EvaluationDetails<T>;
681
- /**
682
- * Performs a flag evaluation that returns a number.
683
- * @param {string} flagKey The flag key uniquely identifies a particular flag
684
- * @template {number} T A optional generic argument constraining the number
685
- * @param {T} defaultValue The value returned if an error occurs
686
- * @param {FlagEvaluationOptions} options Additional flag evaluation options
687
- * @returns {T} Flag evaluation response
688
- */
689
- getNumberValue(flagKey: string, defaultValue: number, options?: FlagEvaluationOptions): number;
690
- getNumberValue<T extends number = number>(flagKey: string, defaultValue: T, options?: FlagEvaluationOptions): T;
691
- /**
692
- * Performs a flag evaluation that a returns an evaluation details object.
693
- * @param {string} flagKey The flag key uniquely identifies a particular flag
694
- * @template {number} T A optional generic argument constraining the number
695
- * @param {T} defaultValue The value returned if an error occurs
696
- * @param {FlagEvaluationOptions} options Additional flag evaluation options
697
- * @returns {Promise<EvaluationDetails<T>>} Flag evaluation details response
698
- */
699
- getNumberDetails(flagKey: string, defaultValue: number, options?: FlagEvaluationOptions): EvaluationDetails<number>;
700
- getNumberDetails<T extends number = number>(flagKey: string, defaultValue: T, options?: FlagEvaluationOptions): EvaluationDetails<T>;
701
- /**
702
- * Performs a flag evaluation that returns an object.
703
- * @param {string} flagKey The flag key uniquely identifies a particular flag
704
- * @template {JsonValue} T A optional generic argument describing the structure
705
- * @param {T} defaultValue The value returned if an error occurs
706
- * @param {FlagEvaluationOptions} options Additional flag evaluation options
707
- * @returns {Promise<T>} Flag evaluation response
708
- */
709
- getObjectValue(flagKey: string, defaultValue: JsonValue, options?: FlagEvaluationOptions): JsonValue;
710
- getObjectValue<T extends JsonValue = JsonValue>(flagKey: string, defaultValue: T, options?: FlagEvaluationOptions): T;
711
- /**
712
- * Performs a flag evaluation that a returns an evaluation details object.
713
- * @param {string} flagKey The flag key uniquely identifies a particular flag
714
- * @template {JsonValue} T A optional generic argument describing the structure
715
- * @param {T} defaultValue The value returned if an error occurs
716
- * @param {FlagEvaluationOptions} options Additional flag evaluation options
717
- * @returns {Promise<EvaluationDetails<T>>} Flag evaluation details response
718
- */
719
- getObjectDetails(flagKey: string, defaultValue: JsonValue, options?: FlagEvaluationOptions): EvaluationDetails<JsonValue>;
720
- getObjectDetails<T extends JsonValue = JsonValue>(flagKey: string, defaultValue: T, options?: FlagEvaluationOptions): EvaluationDetails<T>;
721
- }
722
-
723
- interface Client extends EvaluationLifeCycle<Client>, Features, ManageLogger<Client>, Eventing {
724
- readonly metadata: ClientMetadata;
725
- /**
726
- * Returns the status of the associated provider.
727
- */
728
- readonly providerStatus: ProviderStatus;
729
- }
730
-
731
- /**
732
- * A subset of events that can be directly emitted by providers.
733
- */
734
- type ProviderEmittableEvents = Exclude<ClientProviderEvents, ClientProviderEvents.ContextChanged>;
735
-
736
- /**
737
- * The OpenFeatureEventEmitter can be used by provider developers to emit
738
- * events at various parts of the provider lifecycle.
739
- *
740
- * NOTE: Ready and error events are automatically emitted by the SDK based on
741
- * the result of the initialize method.
742
- */
743
- declare class OpenFeatureEventEmitter extends GenericEventEmitter<ProviderEmittableEvents> {
744
- protected readonly eventEmitter: EventEmitter;
745
- constructor();
746
- }
747
-
748
- /**
749
- * The InternalEventEmitter is not exported publicly and should only be used within the SDK. It extends the
750
- * OpenFeatureEventEmitter to include additional properties that can be included
751
- * in the event details.
752
- */
753
- declare abstract class InternalEventEmitter extends GenericEventEmitter<ClientProviderEvents, CommonEventDetails> {
754
- }
755
-
756
- type Hook = BaseHook<FlagValue, void, void>;
757
-
758
- /**
759
- * Interface that providers must implement to resolve flag values for their particular
760
- * backend or vendor.
761
- *
762
- * Implementation for resolving all the required flag types must be defined.
763
- */
764
- interface Provider extends CommonProvider {
765
- /**
766
- * A provider hook exposes a mechanism for provider authors to register hooks
767
- * to tap into various stages of the flag evaluation lifecycle. These hooks can
768
- * be used to perform side effects and mutate the context for purposes of the
769
- * provider. Provider hooks are not configured or controlled by the application author.
770
- */
771
- readonly hooks?: Hook[];
772
- /**
773
- * A handler function to reconcile changes when the static context.
774
- * Called by the SDK when the context is changed.
775
- * @param oldContext
776
- * @param newContext
777
- */
778
- onContextChange?(oldContext: EvaluationContext, newContext: EvaluationContext): Promise<void>;
779
- /**
780
- * Resolve a boolean flag and its evaluation details.
781
- */
782
- resolveBooleanEvaluation(flagKey: string, defaultValue: boolean, context: EvaluationContext, logger: Logger): ResolutionDetails<boolean>;
783
- /**
784
- * Resolve a string flag and its evaluation details.
785
- */
786
- resolveStringEvaluation(flagKey: string, defaultValue: string, context: EvaluationContext, logger: Logger): ResolutionDetails<string>;
787
- /**
788
- * Resolve a numeric flag and its evaluation details.
789
- */
790
- resolveNumberEvaluation(flagKey: string, defaultValue: number, context: EvaluationContext, logger: Logger): ResolutionDetails<number>;
791
- /**
792
- * Resolve and parse an object flag and its evaluation details.
793
- */
794
- resolveObjectEvaluation<T extends JsonValue>(flagKey: string, defaultValue: T, context: EvaluationContext, logger: Logger): ResolutionDetails<T>;
795
- }
796
-
797
- /**
798
- * The No-op provider is set by default, and simply always returns the default value.
799
- */
800
- declare class NoopFeatureProvider implements Provider {
801
- readonly metadata: {
802
- readonly name: "No-op Provider";
803
- };
804
- get status(): ProviderStatus;
805
- resolveBooleanEvaluation(_: string, defaultValue: boolean): ResolutionDetails<boolean>;
806
- resolveStringEvaluation(_: string, defaultValue: string): ResolutionDetails<string>;
807
- resolveNumberEvaluation(_: string, defaultValue: number): ResolutionDetails<number>;
808
- resolveObjectEvaluation<T extends JsonValue>(_: string, defaultValue: T): ResolutionDetails<T>;
809
- private noOp;
810
- }
811
- declare const NOOP_PROVIDER: NoopFeatureProvider;
812
-
813
- /**
814
- * Don't export types from this file publicly.
815
- * It might cause confusion since these types are not a part of the general API,
816
- * but just for the in-memory provider.
817
- */
818
-
819
- type Variants<T> = Record<string, T>;
820
- /**
821
- * A Feature Flag definition, containing it's specification
822
- */
823
- type Flag = {
824
- /**
825
- * An object containing all possible flags mappings (variant -> flag value)
826
- */
827
- variants: Variants<boolean> | Variants<string> | Variants<number> | Variants<JsonValue>;
828
- /**
829
- * The variant it will resolve to in STATIC evaluation
830
- */
831
- defaultVariant: string;
832
- /**
833
- * Determines if flag evaluation is enabled or not for this flag.
834
- * If false, falls back to the default value provided to the client
835
- */
836
- disabled: boolean;
837
- /**
838
- * Function used in order to evaluate a flag to a specific value given the provided context.
839
- * It should return a variant key.
840
- * If it does not return a valid variant it falls back to the default value provided to the client
841
- * @param EvaluationContext
842
- */
843
- contextEvaluator?: (ctx: EvaluationContext) => string;
844
- };
845
- type FlagConfiguration = Record<string, Flag>;
846
-
847
- /**
848
- * A simple OpenFeature provider intended for demos and as a test stub.
849
- */
850
- declare class InMemoryProvider implements Provider {
851
- readonly events: OpenFeatureEventEmitter;
852
- readonly runsOn = "client";
853
- status: ProviderStatus;
854
- readonly metadata: {
855
- readonly name: "in-memory";
856
- };
857
- private _flagConfiguration;
858
- private _context;
859
- constructor(flagConfiguration?: FlagConfiguration);
860
- initialize(context?: EvaluationContext | undefined): Promise<void>;
861
- /**
862
- * Overwrites the configured flags.
863
- * @param { FlagConfiguration } flagConfiguration new flag configuration
864
- */
865
- putConfiguration(flagConfiguration: FlagConfiguration): Promise<void>;
866
- resolveBooleanEvaluation(flagKey: string, defaultValue: boolean, context?: EvaluationContext, logger?: Logger): ResolutionDetails<boolean>;
867
- resolveNumberEvaluation(flagKey: string, defaultValue: number, context?: EvaluationContext, logger?: Logger): ResolutionDetails<number>;
868
- resolveStringEvaluation(flagKey: string, defaultValue: string, context?: EvaluationContext, logger?: Logger): ResolutionDetails<string>;
869
- resolveObjectEvaluation<T extends JsonValue>(flagKey: string, defaultValue: T, context?: EvaluationContext, logger?: Logger): ResolutionDetails<T>;
870
- private resolveAndCheckFlag;
871
- private resolveFlagWithReason;
872
- private lookupFlagValue;
873
- }
874
-
875
- type OpenFeatureClientOptions = {
876
- name?: string;
877
- version?: string;
878
- };
879
- declare class OpenFeatureClient implements Client {
880
- private readonly providerAccessor;
881
- private readonly emitterAccessor;
882
- private readonly globalLogger;
883
- private readonly options;
884
- private _hooks;
885
- private _clientLogger?;
886
- constructor(providerAccessor: () => Provider, emitterAccessor: () => InternalEventEmitter, globalLogger: () => Logger, options: OpenFeatureClientOptions);
887
- get metadata(): ClientMetadata;
888
- get providerStatus(): ProviderStatus;
889
- addHandler(eventType: ClientProviderEvents, handler: EventHandler): void;
890
- removeHandler(notificationType: ClientProviderEvents, handler: EventHandler): void;
891
- getHandlers(eventType: ClientProviderEvents): EventHandler[];
892
- setLogger(logger: Logger): this;
893
- addHooks(...hooks: Hook[]): this;
894
- getHooks(): Hook[];
895
- clearHooks(): this;
896
- getBooleanValue(flagKey: string, defaultValue: boolean, options?: FlagEvaluationOptions): boolean;
897
- getBooleanDetails(flagKey: string, defaultValue: boolean, options?: FlagEvaluationOptions): EvaluationDetails<boolean>;
898
- getStringValue<T extends string = string>(flagKey: string, defaultValue: T, options?: FlagEvaluationOptions): T;
899
- getStringDetails<T extends string = string>(flagKey: string, defaultValue: T, options?: FlagEvaluationOptions): EvaluationDetails<T>;
900
- getNumberValue<T extends number = number>(flagKey: string, defaultValue: T, options?: FlagEvaluationOptions): T;
901
- getNumberDetails<T extends number = number>(flagKey: string, defaultValue: T, options?: FlagEvaluationOptions): EvaluationDetails<T>;
902
- getObjectValue<T extends JsonValue = JsonValue>(flagKey: string, defaultValue: T, options?: FlagEvaluationOptions): T;
903
- getObjectDetails<T extends JsonValue = JsonValue>(flagKey: string, defaultValue: T, options?: FlagEvaluationOptions): EvaluationDetails<T>;
904
- private evaluate;
905
- private beforeHooks;
906
- private afterHooks;
907
- private errorHooks;
908
- private finallyHooks;
909
- private get _provider();
910
- private get _logger();
911
- }
912
-
913
- declare class OpenFeatureAPI extends OpenFeatureCommonAPI<Provider, Hook> implements ManageContext<Promise<void>> {
914
- protected _events: GenericEventEmitter<ClientProviderEvents>;
915
- protected _defaultProvider: Provider;
916
- protected _createEventEmitter: () => OpenFeatureEventEmitter;
917
- protected _namedProviderContext: Map<string, EvaluationContext>;
918
- private constructor();
919
- /**
920
- * Gets a singleton instance of the OpenFeature API.
921
- * @ignore
922
- * @returns {OpenFeatureAPI} OpenFeature API
923
- */
924
- static getInstance(): OpenFeatureAPI;
925
- /**
926
- * Sets the evaluation context globally.
927
- * This will be used by all providers that have not been overridden with a named client.
928
- * @param {EvaluationContext} context Evaluation context
929
- * @example
930
- * await OpenFeature.setContext({ region: "us" });
931
- */
932
- setContext(context: EvaluationContext): Promise<void>;
933
- /**
934
- * Sets the evaluation context for a specific provider.
935
- * This will only affect providers with a matching client name.
936
- * @param {string} clientName The name to identify the client
937
- * @param {EvaluationContext} context Evaluation context
938
- * @example
939
- * await OpenFeature.setContext("test", { scope: "provider" });
940
- * OpenFeature.setProvider(new MyProvider()) // Uses the default context
941
- * OpenFeature.setProvider("test", new MyProvider()) // Uses context: { scope: "provider" }
942
- */
943
- setContext(clientName: string, context: EvaluationContext): Promise<void>;
944
- /**
945
- * Access the global evaluation context.
946
- * @returns {EvaluationContext} Evaluation context
947
- */
948
- getContext(): EvaluationContext;
949
- /**
950
- * Access the evaluation context for a specific named client.
951
- * The global evaluation context is returned if a matching named client is not found.
952
- * @param {string} clientName The name to identify the client
953
- * @returns {EvaluationContext} Evaluation context
954
- */
955
- getContext(clientName?: string): EvaluationContext;
956
- /**
957
- * Resets the global evaluation context to an empty object.
958
- */
959
- clearContext(): Promise<void>;
960
- /**
961
- * Removes the evaluation context for a specific named client.
962
- * @param {string} clientName The name to identify the client
963
- */
964
- clearContext(clientName: string): Promise<void>;
965
- /**
966
- * Resets the global evaluation context and removes the evaluation context for
967
- * all named clients.
968
- */
969
- clearContexts(): Promise<void>;
970
- /**
971
- * A factory function for creating new named OpenFeature clients. Clients can contain
972
- * their own state (e.g. logger, hook, context). Multiple clients can be used
973
- * to segment feature flag configuration.
974
- *
975
- * If there is already a provider bound to this name via {@link this.setProvider setProvider}, this provider will be used.
976
- * Otherwise, the default provider is used until a provider is assigned to that name.
977
- * @param {string} name The name of the client
978
- * @param {string} version The version of the client (only used for metadata)
979
- * @returns {Client} OpenFeature Client
980
- */
981
- getClient(name?: string, version?: string): Client;
982
- /**
983
- * Clears all registered providers and resets the default provider.
984
- * @returns {Promise<void>}
985
- */
986
- clearProviders(): Promise<void>;
987
- private runProviderContextChangeHandler;
988
- }
989
- /**
990
- * A singleton instance of the OpenFeature API.
991
- * @returns {OpenFeatureAPI} OpenFeature API
992
- */
993
- declare const OpenFeature: OpenFeatureAPI;
994
4
 
995
5
  type ReactFlagEvaluationOptions = {
996
6
  /**
@@ -1120,4 +130,4 @@ type ProviderProps = {
1120
130
  declare const OpenFeatureProvider: ({ client, clientName, children }: ProviderProps) => React.JSX.Element;
1121
131
  declare const useOpenFeatureClient: () => Client;
1122
132
 
1123
- export { ClientProviderEvents as AllProviderEvents, AnyProviderEvent, BaseHook, BeforeHookContext, Client, ClientMetadata, ClientProviderEvents, CommonEventDetails, CommonProvider, ConfigChangeEvent, DefaultLogger, ErrorCode, ErrorEvent, EvaluationContext, EvaluationContextValue, EvaluationDetails, EvaluationLifeCycle, EventContext, EventDetails, EventHandler, EventMetadata, Eventing, Features, FlagEvaluationOptions, FlagMetadata, FlagNotFoundError, FlagValue, FlagValueType, GeneralError, GenericEventEmitter, Hook, HookContext, HookHints, InMemoryProvider, InvalidContextError, JsonArray, JsonObject, JsonValue, LOG_LEVELS, Logger, ManageContext, ManageLogger, Metadata, NOOP_PROVIDER, OpenFeature, OpenFeatureAPI, OpenFeatureClient, OpenFeatureCommonAPI, OpenFeatureError, OpenFeatureEventEmitter, OpenFeatureProvider, Paradigm, ParseError, PrimitiveValue, Provider, ProviderEmittableEvents, ClientProviderEvents as ProviderEvents, ProviderMetadata, ProviderNotReadyError, ProviderStatus, ReadyEvent, ResolutionDetails, ResolutionReason, SafeLogger, ServerProviderEvents, StaleEvent, StandardResolutionReasons, TargetingKeyMissingError, TypeMismatchError, isObject, isString, objectOrUndefined, statusMatchesEvent, stringOrUndefined, useBooleanFlagDetails, useBooleanFlagValue, useNumberFlagDetails, useNumberFlagValue, useObjectFlagDetails, useObjectFlagValue, useOpenFeatureClient, useStringFlagDetails, useStringFlagValue };
133
+ export { OpenFeatureProvider, useBooleanFlagDetails, useBooleanFlagValue, useNumberFlagDetails, useNumberFlagValue, useObjectFlagDetails, useObjectFlagValue, useOpenFeatureClient, useStringFlagDetails, useStringFlagValue };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openfeature/react-sdk",
3
- "version": "0.1.0-experimental",
3
+ "version": "0.1.1-experimental",
4
4
  "description": "OpenFeature React SDK",
5
5
  "main": "./dist/cjs/index.js",
6
6
  "files": [
@@ -17,8 +17,8 @@
17
17
  "test": "jest --verbose",
18
18
  "lint": "eslint ./",
19
19
  "clean": "shx rm -rf ./dist",
20
- "build:react-esm": "esbuild src/index.ts --bundle --external:react --external:@openfeature/web-sdk --sourcemap --target=es2016 --platform=browser --format=esm --outfile=./dist/esm/index.js --analyze",
21
- "build:react-cjs": "esbuild src/index.ts --bundle --external:react --external:@openfeature/web-sdk --sourcemap --target=es2016 --platform=browser --format=cjs --outfile=./dist/cjs/index.js --analyze",
20
+ "build:react-esm": "esbuild src/index.ts --bundle --external:react --external:@openfeature/web-sdk --sourcemap --target=es2022 --platform=browser --format=esm --outfile=./dist/esm/index.js --analyze",
21
+ "build:react-cjs": "esbuild src/index.ts --bundle --external:react --external:@openfeature/web-sdk --sourcemap --target=es2022 --platform=browser --format=cjs --outfile=./dist/cjs/index.js --analyze",
22
22
  "build:rollup-types": "rollup -c ../../rollup.config.mjs",
23
23
  "build": "npm run clean && npm run build:react-esm && npm run build:react-cjs && npm run build:rollup-types",
24
24
  "postbuild": "shx cp ./../../package.esm.json ./dist/esm/package.json",