diff --git a/.changeset/node-sdk-collection-values.md b/.changeset/node-sdk-collection-values.md new file mode 100644 index 000000000..43948018d --- /dev/null +++ b/.changeset/node-sdk-collection-values.md @@ -0,0 +1,19 @@ +--- +"@reflag/node-sdk": major +"@reflag/openfeature-node-provider": patch +--- + +Adopt protocol-v2, adding support for multivariate and JSON flags. + +- `getFlag(context, key)` and bound `getFlag(key)` return direct values instead of flag wrappers. Reads without a default return Booleans, using `false` when unavailable. Replace `.isEnabled` and `.config` access with direct values. +- Pass a positional default to read strings, numbers, arrays, or objects. TypeScript infers the return type from the default without generated declarations. Missing values or values of a different top-level type use the default. Pass `null` to accept any JSON value, including null. Nested payload schemas are not validated at runtime. +- With optional `Flags` registration, TypeScript checks non-null defaults against each flag's value type for local, remote, and bound reads. Named-interface and readonly defaults are supported. +- Flag reads automatically record checks. Replace flag-level `.track()` calls with the client's separate `track()` API. +- `getFlags()` and `getFlagsRemote()` return records of direct values; unavailable flags may be `undefined`. +- `getFlagRemote(key, defaultValue, userId?, companyId?, context?)` now takes the default second, shifting existing user/company arguments one position to the right. Pass `undefined` for a Boolean read with explicit IDs. Bound clients use `getFlagRemote(key, defaultValue?)`. +- `getFlagDefinitions()` returns `{ flags, segments }` instead of an array. +- Saved fallback snapshots use a new format; v1 snapshots are not migrated automatically. Regenerate saved snapshots when upgrading. Built-in storage keeps v1 and v2 snapshots separate. +- `getFlagsForBootstrap()` produces protocol-v2 state. Upgrade Browser/framework consumers to compatible v2 SDKs before using this state; v1 bootstrap consumers are incompatible. +- Existing synchronization modes, bound contexts, and local overrides remain supported. Overrides and static fallbacks accept direct JSON values. + +The OpenFeature Node provider continues to use Node SDK v1. Legacy remote configuration is not automatically converted into multivariate flag values. diff --git a/docs.sh b/docs.sh index 70f103048..f47584095 100755 --- a/docs.sh +++ b/docs.sh @@ -24,7 +24,7 @@ do echo "Processing $file..." # Fix anchor links in globals.md files - if [[ "$file" == *"globals.md" ]]; then + if [ "${file##*/}" = "globals.md" ]; then sed -r "$SEDCOMMAND" "$file" > "$file.fixed" rm "$file" mv "$file.fixed" "$file" diff --git a/packages/flag-evaluation/README.md b/packages/flag-evaluation/README.md index 01f55645a..e435f7152 100644 --- a/packages/flag-evaluation/README.md +++ b/packages/flag-evaluation/README.md @@ -97,8 +97,10 @@ V2 exports `newEvaluator(collection)`, `flattenContext`, and `hashInt`, plus the public types. `newEvaluator` accepts a complete compiled collection, not value rules or a single flag. It returns an object with `evaluateAll(context)` and `evaluateFlag(context, flagKey)` methods, rather than a callable evaluator. -Publishers and consumers must adopt the collection/reference protocol together; -the unchanged Node SDK remains on the published v1 evaluator. +Publishers and consumers must adopt the collection/reference protocol together. +Node SDK v2 uses the collection evaluator. The OpenFeature Node provider and the +v1 React bootstrap demo remain pinned to published Node SDK 1.8.3 and its v1 +evaluator. V1's `evaluateFlagRules`, scalar `evaluate`, `flattenJSON`, `unflattenJSON`, and value-rule types are removed. There is no v2 one-shot evaluation wrapper. diff --git a/packages/flag-evaluation/test/release.test.ts b/packages/flag-evaluation/test/release.test.ts index f0e44924a..18993976a 100644 --- a/packages/flag-evaluation/test/release.test.ts +++ b/packages/flag-evaluation/test/release.test.ts @@ -5,6 +5,7 @@ import { describe, expect, it } from "vitest"; import * as legacy from "@reflag/flag-evaluation-v1"; import nodeSdk from "../../node-sdk/package.json"; +import openfeature from "../../openfeature-node-provider/package.json"; describe("v1/v2 release isolation", () => { it("resolves the legacy alias to the published package, not this workspace", () => { @@ -15,10 +16,22 @@ describe("v1/v2 release isolation", () => { expect(typeof legacy.evaluateFlagRules).toBe("function"); }); - it("keeps the unchanged Node SDK off the v2 workspace dependency", () => { - expect(nodeSdk.dependencies).not.toHaveProperty("@reflag/flag-evaluation"); - expect(nodeSdk.dependencies["@reflag/flag-evaluation-v1"]).toBe( - "npm:@reflag/flag-evaluation@1.1.2", + it("moves the v2 Node SDK onto the collection evaluator", () => { + expect(nodeSdk.dependencies["@reflag/flag-evaluation"]).toBe("workspace:*"); + expect(nodeSdk.dependencies).not.toHaveProperty( + "@reflag/flag-evaluation-v1", ); }); + + it("keeps the unchanged OpenFeature provider on published Node SDK v1", () => { + // Matching the v2 workspace's version would silently link this alias locally. + expect(require.resolve("@reflag/node-sdk-v1/package.json")).not.toBe( + resolve(__dirname, "../../node-sdk/package.json"), + ); + expect(require("@reflag/node-sdk-v1/package.json").version).toBe("1.8.3"); + expect(openfeature.dependencies["@reflag/node-sdk-v1"]).toBe( + "npm:@reflag/node-sdk@1.8.3", + ); + expect(openfeature.dependencies).not.toHaveProperty("@reflag/node-sdk"); + }); }); diff --git a/packages/node-sdk/README.md b/packages/node-sdk/README.md index 67924ed3c..6d3cde0a1 100644 --- a/packages/node-sdk/README.md +++ b/packages/node-sdk/README.md @@ -1,1127 +1,227 @@ # Reflag Node.js SDK -Node.js, JavaScript/TypeScript client for [Reflag.com](https://reflag.com). +Server-side Boolean and multivariate flag values for [Reflag](https://reflag.com). -Reflag supports flag toggling, tracking flag usage, collecting feedback on features, and [remotely configuring flags](#remote-config). +> This branch implements the breaking v2 API. It requires the collection-capable evaluator, the v2 `/flags` endpoint, and compatible variant-key check ingestion. It has not been published or deployed. -## Installation - -Install using your favorite package manager: - -{% tabs %} -{% tab title="npm" %} - -```sh -npm i @reflag/node-sdk -``` - -{% endtab %} - -{% tab title="yarn" %} +## Installation and initialization ```sh yarn add @reflag/node-sdk ``` -{% endtab %} - -{% tab title="bun" %} - -```sh -bun add @reflag/node-sdk -``` - -{% endtab %} - -{% tab title="pnpm" %} - -```sh -pnpm add @reflag/node-sdk -``` - -{% endtab %} - -{% tab title="deno" %} - -```sh -deno add npm:@reflag/node-sdk -``` +Create one client per process and initialize it before reading flags. Obtain your environment's secret key from Reflag's environment settings; complete flag definitions must remain server-side. -{% endtab %} -{% endtabs %} - -Other supported languages/frameworks are in the [Supported languages](https://docs.reflag.com/quickstart/supported-languages) documentation pages. - -You can also [use the HTTP API directly](https://docs.reflag.com/api/http-api) - -## Basic usage - -To get started you need to obtain your secret key from the [environment settings](https://app.reflag.com/env-current/settings/app-environments) -in Reflag. - -Reflag will load settings through the various environment variables automatically (see [Configuring](#configuring) below). - -1. Find the Reflag secret key for your development environment under [environment settings](https://app.reflag.com/env-current/settings/app-environments) in Reflag. -2. Set `REFLAG_SECRET_KEY` in your `.env` file -3. Create a `reflag.ts` file containing the following: - -```typescript +```ts import { ReflagClient } from "@reflag/node-sdk"; -// Create a new instance of the client with the secret key. Additional options -// are available, such as supplying a logger and other custom properties. -// -// We recommend that only one global instance of `client` should be created -// to avoid multiple round-trips to our servers. -export const reflagClient = new ReflagClient(); - -// Initialize the client and begin fetching flag targeting definitions. -// You must call this method prior to any calls to `getFlags()`, -// otherwise an empty object will be returned. -reflagClient.initialize().then(() => { - console.log("Reflag initialized!"); -}); -``` - -Once the client is initialized, you can obtain flags along with the `isEnabled` -status to indicate whether the flag is targeted for this user/company: - -> [!IMPORTANT] -> If `user.id` is not given, the whole `user` object is ignore. Similarly, without `company.id` the `company` object is ignored. - -```typescript -// configure the client -const boundClient = reflagClient.bindClient({ - user: { - id: "john_doe", - name: "John Doe", - email: "john@acme.com", - avatar: "https://example.com/users/jdoe", - }, - company: { - id: "acme_inc", - name: "Acme, Inc.", - avatar: "https://example.com/companies/acme", - }, +export const reflag = new ReflagClient({ + secretKey: process.env.REFLAG_SECRET_KEY, }); - -// get the huddle flag using company, user and custom context to -// evaluate the targeting. -const { isEnabled, track, config } = boundClient.getFlag("huddle"); - -if (isEnabled) { - // this is your flag gated code ... - // send an event when the flag is used: - track(); - - if (config?.key === "zoom") { - // this code will run if a given remote configuration - // is set up. - } - - // CAUTION: if you plan to use the event for automated feedback surveys - // call `flush` immediately after `track`. It can optionally be awaited - // to guarantee the sent happened. - boundClient.flush(); -} +await reflag.initialize(); ``` -You can also use the `getFlags()` method which returns a map of all flags: +## Direct values, immediate checks -```typescript -// get the current flags (uses company, user and custom context to -// evaluate the flags). -const flags = boundClient.getFlags(); -const bothEnabled = flags.huddle?.isEnabled && flags.voiceHuddle?.isEnabled; -``` - -## High performance flag targeting - -The SDK contacts the Reflag servers when you call `initialize()` -and downloads the flags with their targeting rules. -These rules are then matched against the user/company information you provide -to `getFlags()` (or through `bindClient(..).getFlags()`). That means the -`getFlags()` call does not need to contact the Reflag servers once -`initialize()` has completed. By default, `ReflagClient` uses -`flagsSyncMode: "push"`, which keeps targeting rules up to date via live SSE -updates. You can switch `flagsSyncMode` to `polling` for periodic background -refreshes or `in-request` for request-driven refreshes instead. - -### Batch Operations - -The SDK automatically batches operations like user/company updates and flag tracking events to minimize API calls. -The batch buffer is configurable through the client options: - -```typescript -const client = new ReflagClient({ - batchOptions: { - maxSize: 100, // Maximum number of events to batch - intervalMs: 10000, // Flush interval in milliseconds (default: 10000) - }, -}); -``` - -You can manually flush the batch buffer at any time: +```ts +const context = { + user: { id: "user-1" }, + company: { id: "acme", plan: "enterprise" }, +}; -```typescript -await client.flush(); +const enabled = reflag.getFlag(context, "new-editor"); // boolean; implicit false +const model = reflag.getFlag(context, "model", "quick"); // string +const limits = reflag.getFlag(context, "limits", { maxItems: 10 }); // { maxItems: number } ``` -> [!TIP] -> It's recommended to call `flush()` before your application shuts down to ensure all events are sent. - -### Rate Limiting - -The SDK includes automatic rate limiting for flag events to prevent overwhelming the API. -Rate limiting is applied per unique combination of flag key and evaluation context. -This behavior is built in and does not currently require configuration. - -### Flag definitions - -Flag definitions include the rules needed to determine which flags should be enabled and which config values should be applied to any given user/company. -Flag definitions are automatically fetched when calling `initialize()`. -They are then cached and refreshed in the background. Ordinary refreshes use -ETags to avoid downloading unchanged definitions. A `304 Not Modified` response -keeps the cached definitions and resets their freshness without recompiling -rules or writing a new fallback snapshot. Initial fetches and refreshes with a -`waitForVersion` target remain unconditional. When a fallback provider is -configured, the SDK retains the ETag only after the snapshot is saved -successfully. A failed or pending save keeps ordinary refreshes unconditional -so persistence can recover, without delaying flag availability. +**`getFlag()` returns the value itself**, not a flag object. There is no `.value`, `.isEnabled`, `.config`, or flag `.track()` wrapper. Without a default it is a Boolean read: unavailable or non-Boolean values return `false`, never a truthy object. With a positional default, missing values use that default. Valid `false`, `0`, empty strings, arrays, and objects are preserved rather than replaced by truthiness checks. -Custom HTTP clients can enable this optimization by returning the exact ETag -value in `HttpClientResponse.etag` and returning 304 responses with -`body: undefined`. Clients that omit the ETag continue using full fetches. +Non-null defaults specify the expected JSON category: Boolean, number, string, array, or object. A category mismatch logs a warning without the payload and returns the default. This is not nested payload validation: object properties and array elements must still match your authored schema. Use an explicit `null` default for arbitrary JSON or nullable/off selections, and narrow the result before accessing object fields: -It's also possible to get the currently in use flag definitions: - -```typescript -import fs from "fs"; - -const client = new ReflagClient(); - -const flagDefs = await client.getFlagDefinitions(); -// [{ -// key: "huddle", -// description: "Live voice conversations with colleagues." -// flag: { ... } -// config: { ... } -// }] +```ts +const payload = reflag.getFlag(context, "nullable-settings", null); // FlagValue +// Authored null is preserved, as are any other valid JSON values. Missing uses null. ``` -### Fallback provider - -`flagsFallbackProvider` is a reliability feature that lets the SDK persist the latest successfully fetched raw flag definitions to fallback storage such as a local file, Redis, S3, GCS, or a custom backend. +Defaults infer useful types without generated declarations, including widening primitive literals. Readonly defaults are accepted; results and defaults are returned as independent copies. Defaults are ordinary JSON payloads, with no reserved property names. -> [!NOTE] -> -> `fallbackFlags` is deprecated. Prefer `flagsFallbackProvider` for startup fallback and outage recovery. -> `flagsFallbackProvider` is not used in offline mode. - -#### How it works - -Reflag servers remain the primary source of truth. On `initialize()`, the SDK always tries to fetch a live copy of the flag definitions first, and it continues refreshing those definitions from the Reflag servers over time. - -If that initial live fetch fails, the SDK can call `flagsFallbackProvider.load()` and start with the last saved snapshot instead. This is mainly useful for cold starts in the exceedingly rare case that Reflag has an outage. - -If Reflag becomes unavailable after the SDK has already initialized successfully, the SDK keeps using the last successfully fetched definitions it already has in memory. In other words, the fallback provider is mainly what helps future processes start, not what keeps an already running process alive. - -After successfully fetching updated flag definitions, the SDK calls `flagsFallbackProvider.save()` to keep the stored snapshot up to date. - -Typical reliability flow: - -1. The SDK starts and tries to fetch live flag definitions from Reflag. -2. If that succeeds, those definitions are used immediately and the SDK continues operating normally. -3. After successfully fetching updated flag definitions, the SDK saves the latest snapshot through the fallback provider so a recent copy is available if needed later. -4. If a future process starts while Reflag is unavailable, it can load the last saved snapshot from the fallback provider and still initialize. -5. Once Reflag becomes available again, the SDK resumes using live data and refreshes the fallback snapshot. - -Most deployments run multiple SDK processes, so more than one process may save identical flag definitions to the fallback storage at roughly the same time. This is expected and generally harmless for backends like a local file, Redis, S3, or GCS because the operation is cheap. In practice, this only becomes worth thinking about once you have many thousands of SDK processes writing to the same fallback storage. - -> [!TIP] -> If you are building a web or client-side application and want the most resilient setup, combine `flagsFallbackProvider` on the server with bootstrapped flags on the client. -> -> `flagsFallbackProvider` helps new server processes start if they cannot reach Reflag during initialization. Bootstrapping helps clients render from server-provided flags instead of depending on an initial client-side fetch from the Reflag servers. -> -> This applies to React (`getFlagsForBootstrap()` + `ReflagBootstrappedProvider`), React Native, the Browser SDK (`bootstrappedState`), and the Vue SDK (bootstrapped flags via the provider). - -#### Built-in providers - -You can access the built-in providers through the `fallbackProviders` namespace: - -- `fallbackProviders.static(...)` -- `fallbackProviders.file(...)` -- `fallbackProviders.redis(...)` -- `fallbackProviders.s3(...)` -- `fallbackProviders.gcs(...)` - -##### Static provider - -If you just want a fixed fallback copy of simple enabled/disabled flags, you can provide a static map: - -```typescript -import { ReflagClient, fallbackProviders } from "@reflag/node-sdk"; - -const client = new ReflagClient({ - secretKey: process.env.REFLAG_SECRET_KEY, - flagsFallbackProvider: fallbackProviders.static({ - flags: { - huddle: true, - "smart-summaries": false, - }, - }), -}); +Each call immediately registers a check for the requested root, including when you do not subsequently use its return value. Dependencies traversed internally do not register extra checks. Delivery is buffered and rate-limited. A check records the selected **variant key**, never the JSON payload: -await client.initialize(); +```ts +{ + type: "feature-flag-event", + action: "check", + key: "model", + evalResult: "quality", + sourceVersionId: "version-id", + flagStateVersion: 42, + evalContext: { company: { id: "acme", plan: "enterprise" } }, +} ``` -##### File provider - -```typescript -import { ReflagClient, fallbackProviders } from "@reflag/node-sdk"; +Boolean selections send `"true"` / `"false"` while returning Boolean values. Caller defaults, including category-mismatch defaults, do not claim an authored selection: their checks omit `evalResult` and `sourceVersionId`. Check deduplication includes normalized context, selection identity, root version, and snapshot version. Equal-valued variants are not interchangeable selections. Batch `getFlags()` remains a raw value record, without per-root caller defaults; unavailable batch values may be `undefined`. -const client = new ReflagClient({ - secretKey: process.env.REFLAG_SECRET_KEY, - flagsFallbackProvider: fallbackProviders.file({ - directory: ".reflag", - }), -}); +```ts +const values = reflag.getFlags(context); // value record; checks each returned root +const bound = reflag.bindClient(context); +const value = bound.getFlag("model", "quick"); +const allValues = bound.getFlags(); -await client.initialize(); +// Ordinary usage tracking is separate from flag checks. +await bound.track("Document created", { attributes: { source: "editor" } }); +await reflag.flush(); ``` -The file provider stores one snapshot file per environment in the configured -`directory`, using the filename -`flags-fallback-.json`. - -##### Redis provider - -The built-in Redis provider creates a Redis client automatically when omitted and uses `REDIS_URL` from the environment. It stores snapshots under the configured `keyPrefix` and appends the first 16 characters of the secret key hash to that prefix. - -Without a `keyPrefix` set, it will default to the key `reflag:flags-fallback:`. When you provide a custom `keyPrefix`, any trailing `:` is trimmed before the hash suffix is appended. - -```typescript -import { ReflagClient, fallbackProviders } from "@reflag/node-sdk"; +Binding queues user/company attributes and their association even if the client is subsequently used only for tracking or remote reads. Synchronization is asynchronous and respects offline/tracking guards; failures are logged. -const client = new ReflagClient({ - secretKey: process.env.REFLAG_SECRET_KEY, - flagsFallbackProvider: fallbackProviders.redis(), -}); +Local reads made before initialization include a `CLIENT_NOT_INITIALIZED` diagnostic in their check's optional `evalErrors`. Targeting diagnostics retain their code, field/operator when applicable, message, and dependency origin. Remote evaluation does not require the local definition cache to be initialized, and bootstrap/diagnostic access does not itself register checks. -await client.initialize(); -``` +`enableTracking: false` disables checks, context synchronization, and bound-client usage tracking. Explicit calls to the root client's `track()`, `updateUser()`, and `updateCompany()` remain separate operations. -##### S3 provider +## Evaluation and synchronization -The built-in S3 provider works out of the box using the AWS SDK's default credential chain and region resolution. It stores the snapshot object under the configured `keyPrefix` and uses the filename `flags-fallback-.json`. +The SDK fetches a complete `{ flags, segments }` graph from secret-key-only `GET /flags`. Definitions are validated and prepared before the flags, segments, and snapshot version replace the current cache together. Malformed graphs and stale responses cannot replace last-known-good state. -Without a `keyPrefix` set, it will default to the object key `reflag/flags-fallback/flags-fallback-.json`. When you provide a custom `keyPrefix`, any trailing `/` is trimmed before the filename is appended. +`getFlag()` evaluates only its root and dependencies. `getFlags()` evaluates the collection. References are reevaluated on every traversal: there is **no context/dependency-result caching**. Only immutable definition preparation is retained. Returned objects are independent copies, so changing a value cannot mutate the saved definitions. -```typescript -import { ReflagClient, fallbackProviders } from "@reflag/node-sdk"; +Synchronization modes: -const client = new ReflagClient({ - secretKey: process.env.REFLAG_SECRET_KEY, - flagsFallbackProvider: fallbackProviders.s3({ - bucket: "reflag-fallback-bucket", - }), -}); +- `push` (default): authenticated SSE updates with reconnect handling. +- `polling`: periodic background refreshes. +- `in-request`: request-driven refreshes, suitable for constrained runtimes. -await client.initialize(); +```ts +await reflag.refreshFlags(); +await reflag.refreshFlags(42); // request at least this snapshot version +const definitions = reflag.getFlagDefinitions(); // { flags, segments }, not an array ``` -##### GCS provider +Refreshes are throttled. In-request mode can queue a refresh during the throttle window until a later access; a refresh call is not an unconditional synchronization barrier. -The built-in GCS provider works out of the box using Google Cloud's default application credentials. It stores the snapshot object under the configured `keyPrefix` and uses the filename `flags-fallback-.json`. +Ordinary warm `/flags` refreshes send `If-None-Match` when the accepted snapshot has an ETag. A bodyless `304` retains the complete prepared graph and version while resetting freshness, without recompiling or saving it again. Cold/fallback initialization and version-targeted requests remain unconditional. Custom HTTP clients can return the exact optional `HttpClientResponse.etag` to enable this behavior; clients without one continue to use full GETs. Validators are enabled only after the snapshot's fallback save succeeds. Failed or pending saves leave refreshes unconditional, and rejected snapshots cannot replace a validator or overwrite fallback storage. -Without a `keyPrefix` set, it will default to the object key `reflag/flags-fallback/flags-fallback-.json`. When you provide a custom `keyPrefix`, any trailing `/` is trimmed before the filename is appended. +## Fallback providers -```typescript +```ts import { ReflagClient, fallbackProviders } from "@reflag/node-sdk"; const client = new ReflagClient({ secretKey: process.env.REFLAG_SECRET_KEY, - flagsFallbackProvider: fallbackProviders.gcs({ - bucket: "reflag-fallback-bucket", - }), + flagsFallbackProvider: fallbackProviders.file({ directory: ".reflag" }), }); - -await client.initialize(); -``` - -#### Testing fallback startup locally - -To test fallback startup in your own app, first run it once with a working Reflag connection so a snapshot is saved. Then restart it with the same secret key and fallback provider configuration, but set `apiBaseUrl` (or set the `REFLAG_API_BASE_URL` environment variable) to `http://127.0.0.1:65535`. That forces the live fetch to fail and lets you verify that the SDK initializes from the saved snapshot instead. - -#### Writing a custom provider - -If you just store definitions in your database or similar, a custom provider can be very small: - -```typescript -import type { - FlagsFallbackProvider, - FlagsFallbackSnapshot, -} from "@reflag/node-sdk"; - -export const customFallbackProvider: FlagsFallbackProvider = { - async load(context) { - // load snapshot from database - // optionally, look up the snapshot using the context.secretKeyHash as a key - return snapshot; - }, - - async save(context, snapshot) { - const serialized = JSON.stringify(snapshot); - // write serialized snapshot to database, optionally using context.secretKeyHash as a key - }, -}; -``` - -## Bootstrapping client-side applications - -The `getFlagsForBootstrap()` method is useful whenever you need to pass flag data to another runtime or serialize it without wrapper functions. Server-side rendering (SSR) is a common example, but it is also useful for other bootstrapping and hydration flows. - -```typescript -const client = new ReflagClient(); await client.initialize(); - -// Get bootstrapped state with full context -const bootstrappedState = client.getFlagsForBootstrap({ - user: { - id: "user123", - name: "John Doe", - email: "john@acme.com", - }, - company: { - id: "company456", - name: "Acme Inc", - plan: "enterprise", - }, - other: { - source: "web", - platform: "desktop", - }, -}); - -// Pass this data to your client-side application -console.log(bootstrappedState); -// { -// context: { ... }, -// flags: { -// "huddle": { -// "key": "huddle", -// "isEnabled": true, -// "config": { -// "key": "enhanced", -// "payload": { "maxParticipants": 50, "videoQuality": "hd" }, -// } -// } -// }, -// flagStateVersion: 42 -// } -``` - -You can also use a bound client for simpler API: - -```typescript -const boundClient = client.bindClient({ - user: { id: "user123", name: "John Doe", email: "john@acme.com" }, - company: { id: "company456", name: "Acme Inc", plan: "enterprise" }, -}); - -const bootstrappedState = boundClient.getFlagsForBootstrap(); -``` - -### Key differences from `getFlags()` - -- **Raw data**: Returns plain objects without `track()` functions, making them JSON serializable -- **Context included**: Returns both the evaluated flags and the context used for evaluation -- **Version included**: Returns `flagStateVersion` when known so bootstrapped clients can avoid redundant live-update refreshes -- **Bootstrapping focus**: Designed specifically for passing data to client-side applications - -## Edge-runtimes like Cloudflare Workers - -To use the Reflag NodeSDK with Cloudflare workers, set the `node_compat` flag [in your wrangler file](https://developers.cloudflare.com/workers/runtime-apis/nodejs/#get-started). - -Instead of using `ReflagClient`, use `EdgeClient` and make sure you call `ctx.waitUntil(reflag.flush());` before returning from your worker function. - -```typescript -import { EdgeClient } from "@reflag/node-sdk"; - -// set the REFLAG_SECRET_KEY environment variable or pass the secret key in the constructor -const reflag = new EdgeClient(); - -export default { - async fetch(request, _env, ctx): Promise { - // initialize the client and wait for it to complete - // if the client was initialized on a previous invocation, this is a no-op. - await reflag.initialize(); - const flags = reflag.getFlags({ - user: { id: "userId" }, - company: { id: "companyId" }, - }); - - // ensure all events are flushed and any requests to refresh the flag cache - // have completed after the response is sent - ctx.waitUntil(reflag.flush()); - - return new Response( - `Flags for user ${userId} and company ${companyId}: ${JSON.stringify(flags, null, 2)}`, - ); - }, -}; ``` -See [examples/cloudflare-worker](https://github.com/reflagcom/javascript/tree/main/packages/node-sdk/examples/cloudflare-worker/src/index.ts) for a deployable example. - -Reflag maintains a cached set of flag definitions in the memory of your worker which it uses to decide which flags to turn on for which users/companies. - -The SDK caches flag definitions in memory for fast performance. The first request to a new worker instance fetches definitions from Reflag's servers, while subsequent requests use the cache. When the cache expires, it's updated in the background. `ctx.waitUntil(reflag.flush())` ensures completion of the background work, so response times are not affected. This background work may increase wall-clock time for your worker, but it will not measurably increase billable CPU time on platforms like Cloudflare. - -`EdgeClient` uses `flagsSyncMode: "in-request"`. Refresh fetch starts are throttled to at most once per second, and Cloudflare Workers cannot rely on delayed timer callbacks to run follow-up refreshes later. That means `refreshFlags()` calls made during the throttle window only mark a refresh as pending, so the call itself may resolve before the fetch runs. The queued refresh runs on the next request/access or `refreshFlags()` call after the throttle window expires. - -## Error Handling - -The SDK is designed to fail gracefully and never throw exceptions to the caller. Instead, it logs errors and provides -fallback behavior: - -1. **Flag Evaluation Failures**: - - ```typescript - const { isEnabled } = client.getFlag("my-flag"); - // If flag evaluation fails, isEnabled will be false - ``` +Live state is primary. When the initial live fetch fails, the SDK can load a saved complete collection. Later outages retain the in-memory graph rather than reloading older fallback state. Accepted live snapshots are saved in order; `flush()` also waits for pending saves. -2. **Network Errors**: - - ```typescript - // Network errors during tracking are logged but don't affect your application - const { isEnabled, track } = client.getFlag("my-flag"); - if (isEnabled) { - // network errors are caught internally and logged and never bubbled up to your application - // no need to try/catch around "track" or "getFlag" - await track(); - } - ``` - -3. **Missing Context**: - - ```typescript - // The SDK tracks missing context fields but continues operation - const flags = client.getFlags({ - user: { id: "user123" }, - // Missing company context will be logged but won't cause errors - }); - ``` - -4. **Offline Mode**: - - ```typescript - // In offline mode, the SDK uses explicit local configuration only. - // It does not fetch from Reflag or use flagsFallbackProvider. - const client = new ReflagClient({ - offline: true, - flagOverrides: () => ({ - "my-flag": true, - }), - }); - ``` - -The SDK logs all errors with appropriate severity levels. You can customize logging by providing your own logger: - -```typescript -const client = new ReflagClient({ - logger: { - debug: (msg) => console.debug(msg), - info: (msg) => console.info(msg), - warn: (msg) => console.warn(msg), - error: (msg, error) => { - console.error(msg, error); - // Send to your error tracking service - errorTracker.capture(error); - }, - }, -}); -``` - -## Remote config - -Remote config is a dynamic and flexible approach to configuring flag behavior outside of your app – without needing to re-deploy it. - -Similar to `isEnabled`, each flag has a `config` property. This configuration is managed from within Reflag. -It is managed similar to the way access to flags is managed, but instead of the binary `isEnabled` you can have -multiple configuration values which are given to different user/companies. +Available providers: `static`, `file`, `redis`, `s3`, and `gcs`, plus custom `FlagsFallbackProvider` implementations. A v2 snapshot contains: ```ts -const flags = reflagClient.getFlags(); -// { -// huddle: { -// isEnabled: true, -// targetingVersion: 42, -// config: { -// key: "gpt-3.5", -// payload: { maxTokens: 10000, model: "gpt-3.5-beta1" } -// } -// } -// } -``` - -`key` is mandatory for a config, but if a flag has no config or no config value was matched against the context, the `key` will be `undefined`. Make sure to check against this case when trying to use the configuration in your application. `payload` is an optional JSON value for arbitrary configuration needs. - -Just as `isEnabled`, accessing `config` on the object returned by `getFlags` does not automatically -generate a `check` event, contrary to the `config` property on the object returned by `getFlag`. - -## Configuring - -The Reflag `Node.js` SDK can be configured through environment variables, -a configuration file on disk or by passing options to the `ReflagClient` -constructor. By default, the SDK searches for `reflag.config.json` in the -current working directory. - -| Option | Type | Description | Env Var | -| ----------------------- | ------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------- | -| `secretKey` | string | The secret key used for authentication with Reflag's servers. | REFLAG_SECRET_KEY | -| `logLevel` | string | The log level for the SDK (e.g., `"DEBUG"`, `"INFO"`, `"WARN"`, `"ERROR"`). Default: `INFO` | REFLAG_LOG_LEVEL | -| `offline` | boolean | Operate in offline mode. Default: `false`, except in tests it will default to `true` based off of the `TEST` env. var. In offline mode the SDK does not fetch from Reflag and does not use `flagsFallbackProvider`. | REFLAG_OFFLINE | -| `apiBaseUrl` | string | The base API URL for the Reflag servers. | REFLAG_API_BASE_URL | -| `flagOverrides` | Record | An object specifying flag overrides for testing or local development. See [examples/express/app.test.ts](https://github.com/reflagcom/javascript/tree/main/packages/node-sdk/examples/express/app.test.ts) for how to use `flagOverrides` in tests. | REFLAG_FLAGS_ENABLED, REFLAG_FLAGS_DISABLED | -| `flagsFallbackProvider` | `FlagsFallbackProvider` | Optional provider used to load and save raw flag definitions for fallback startup when the initial live fetch fails. Available only through the constructor. Ignored in offline mode. | - | -| `flagsSyncMode` | `"polling" \| "in-request" \| "push"` | Flag-definition sync mode. `push` subscribes to live updates, `polling` uses periodic background refresh, and `in-request` refreshes stale flags during request handling. Default: `"push"`. | - | -| `flagsPushUrl` | string | Push endpoint used when `flagsSyncMode: "push"`. The SDK opens it as an authenticated streaming GET. Default: `https://front.reflag.com/sse/server`. | - | -| `configFile` | string | Load this config file from disk. Default: `reflag.config.json` | REFLAG_CONFIG_FILE | - -> [!NOTE] -> -> `REFLAG_FLAGS_ENABLED` and `REFLAG_FLAGS_DISABLED` are comma separated lists of flags which will be enabled or disabled respectively. - -`reflag.config.json` example: - -```json { - "secretKey": "...", - "logLevel": "warn", - "offline": true, - "apiBaseUrl": "https://proxy.slick-demo.com", - "flagOverrides": { - "huddles": true, - "voiceChat": { "isEnabled": false }, - "aiAssist": { - "isEnabled": true, - "config": { - "key": "gpt-4.0", - "payload": { - "maxTokens": 50000 - } - } - } - } + version: 2, + savedAt: "2026-01-01T00:00:00.000Z", + flagStateVersion: 42, + flags: [/* compiled flags */], + segments: [/* compiled segment predicates */], } ``` -When using a `reflag.config.json` for local development, make sure you add it to your -`.gitignore` file. You can also set these options directly in the `ReflagClient` -constructor. The precedence for configuration options is as follows, listed in the -order of importance: - -1. Options passed along to the constructor directly, -2. Environment variable, -3. The config file. - -## Type safe flags - -To get type checked flags, install the Reflag CLI: - -```sh -npm i --save-dev @reflag/cli -``` - -then generate the types: - -```sh -npx reflag flags types -``` - -This will generate a `reflag.d.ts` containing all your flags. -Any flag look ups will now be checked against the flags that exist in Reflag. - -Here's an example of a failed type check: - -```typescript -import { ReflagClient } from "@reflag/node-sdk"; - -export const reflagClient = new ReflagClient(); - -reflagClient.initialize().then(() => { - console.log("Reflag initialized!"); - - // TypeScript will catch this error: "invalid-flag" doesn't exist - reflagClient.getFlag("invalid-flag"); - - const { - isEnabled, - config: { payload }, - } = reflagClient.getFlag("create-todos"); -}); -``` - -![Type check failed](docs/type-check-failed.png "Type check failed") - -This is an example of a failed config payload check: - -```typescript -reflagClient.initialize().then(() => { - // TypeScript will catch this error as well: "minLength" is not part of the payload. - if (isEnabled && todo.length > config.payload.minLength) { - // ... - } -}); -``` - -![Config type check failed](docs/type-check-payload-failed.png "Remote config type check failed") +V1 flag-only snapshots are incompatible and are not automatically expanded or converted. Built-in files/S3/GCS objects use `flags-fallback-v2-.json`; Redis uses `:v2:`. This keeps v1 and v2 processes from overwriting each other's fallback state. -## Testing with flag overrides +A static fallback can contain any JSON values: -When writing tests that cover code with flags, you can toggle flags on/off programmatically to test different behavior. For tests, you will often want to run the client in offline mode: - -`reflag.ts`: - -```typescript -import { ReflagClient } from "@reflag/node-sdk"; - -export const reflag = new ReflagClient({ - offline: true, +```ts +fallbackProviders.static({ + flags: { "new-editor": false, model: "quick", limits: null }, }); ``` -There are a few ways to programmatically manipulate the overrides which are appropriate when testing: - -### Base overrides +Static values, `fallbackFlags`, and overrides do not identify authored variants. Their checks omit `evalResult` and `sourceVersionId`; they must not claim exposure to an authored selection. Restored real collection snapshots retain their real selection/version metadata. Providers are not loaded in offline mode. -You can set base overrides for a test run by passing `flagOverrides` in the constructor, replacing them later with `setFlagOverrides()` and clearing them with `clearFlagOverrides()`: +## Overrides and tests -```typescript -// pass directly in the constructor +```ts const client = new ReflagClient({ offline: true, - flagOverrides: { myFlag: true }, -}); - -// or replace the base overrides at a later time -client.setFlagOverrides({ myFlag: false }); - -// clear only the base overrides -client.clearFlagOverrides(); -``` - -`app.test.ts`: - -```typescript -import { reflag } from "./reflag.ts"; - -beforeAll(async () => await reflag.initialize()); -afterEach(() => { - reflag.clearFlagOverrides(); -}); - -describe("API Tests", () => { - it("should return 200 for the root endpoint", async () => { - reflag.setFlagOverrides({ - "show-todo": true, - }); - - const response = await request(app).get("/"); - expect(response.status).toBe(200); - expect(response.body).toEqual({ message: "Ready to manage some TODOs!" }); - }); + flagOverrides: { "new-editor": true, limits: { maxItems: 5 } }, }); -``` - -### Layering overrides - -`pushFlagOverrides()` serves a different purpose: it adds a temporary layer on top of the base overrides and returns a remove function that removes only that layer. This is useful for nested tests: - -```typescript -export const flag = function (name: string, enabled: boolean): void { - let remove: (() => void) | undefined; - - beforeEach(function () { - remove = reflagClient.pushFlagOverrides({ [name]: enabled }); - }); - - afterEach(function () { - remove?.(); - remove = undefined; - }); -}; - -describe("foo", () => { - describe("with new search ranking enabled", () => { - flag("search-ranking-v2", true); - - describe("with summaries enabled", () => { - flag("smart-summaries", true); - - // ... - }); - }); -}); -``` - -The precedence is: - -1. Base overrides from the constructor or `setFlagOverrides()` -2. Temporary layers added by `pushFlagOverrides()` - -If the same flag is set in both places, the pushed override wins until its remove function is called. - -### Context dependent overrides - -`setFlagOverrides()` and `pushFlagOverrides()` also accept a function if the override depends on the evaluation context: - -```typescript +await client.initialize(); +client.setFlagOverrides({ model: "quick" }); const remove = client.pushFlagOverrides((context) => ({ - "smart-summaries": context.user?.id === "qa-user", + model: context.company?.id === "qa" ? "quality" : "quick", })); - -// ... - remove(); +client.clearFlagOverrides(); ``` -### Additional ways to provide flag overrides - -You also have these additional ways to provide overrides, which can be helpful when testing out locally: - -1. Through environment variables: - -```bash -REFLAG_FLAGS_ENABLED=flag1,flag2 -REFLAG_FLAGS_DISABLED=flag3,flag4 -``` - -1. Through `reflag.config.json`: - -```json -{ - "flagOverrides": { - "delete-todos": { - "isEnabled": true, - "config": { - "key": "dev-config", - "payload": { - "requireConfirmation": true, - "maxDeletionsPerDay": 5 - } - } - } - } -} -``` - -## Remote Flag Evaluation - -In addition to local flag evaluation, Reflag supports remote evaluation using stored context. This is useful when you want to evaluate flags using user/company attributes that were previously sent to Reflag: - -```typescript -// First, update user and company attributes -await client.updateUser("user123", { - attributes: { - role: "admin", - subscription: "premium", - }, -}); - -await client.updateCompany("company456", { - attributes: { - tier: "enterprise", - employees: 1000, - }, -}); - -// Later, evaluate flags remotely using stored context. -// Note: the argument order is (userId, companyId, additionalContext?) -const userId = "user123"; -const companyId = "company456"; - -const flags = await client.getFlagsRemote(userId, companyId); -// Or evaluate a single flag -const flag = await client.getFlagRemote("create-todos", userId, companyId); - -// You can also provide additional context -const flagsWithContext = await client.getFlagsRemote(userId, companyId, { - other: { - location: "US", - platform: "mobile", - }, -}); -``` - -Remote evaluation is particularly useful when: - -- You want to use the most up-to-date user/company attributes stored in Reflag -- You don't want to pass all context attributes with every evaluation -- You need to ensure consistent flag evaluation across different services - -## Using with Express - -A popular way to integrate the Reflag Node.js SDK is through an express middleware. - -```typescript -import reflag from "./reflag"; -import express from "express"; -import { BoundReflagClient } from "@reflag/node-sdk"; - -// Augment the Express types to include a `boundReflagClient` property on the -// `res.locals` object. -// This will allow us to access the ReflagClient instance in our route handlers -// without having to pass it around manually -declare global { - namespace Express { - interface Locals { - boundReflagClient: BoundReflagClient; - } - } -} - -// Add express middleware -app.use((req, res, next) => { - // Extract the user and company IDs from the request - // You'll want to use a proper authentication and identification - // mechanism in a real-world application - const user = { - id: req.user?.id, - name: req.user?.name, - email: req.user?.email - } - - const company = { - id: req.user?.companyId, - name: req.user?.companyName - } +Overrides are direct JSON values. Pushed layers win over base overrides and can be removed independently. They apply **after evaluation**, so overriding a dependency's returned value does not rewrite dependent flag evaluations. Offline mode does not fetch, load a provider, or send tracking events. - // Create a new BoundReflagClient instance by calling the `bindClient` - // method on a `ReflagClient` instance - // This will create a new instance that is bound to the user/company given. - const boundReflagClient = reflag.bindClient({ user, company }); - - // Store the BoundReflagClient instance in the `res.locals` object so we - // can access it in our route handlers - res.locals.boundReflagClient = boundReflagClient; - next(); -}); +## Typed flags -// Now use res.locals.boundReflagClient in your handlers -app.get("/todos", async (_req, res) => { - const { track, isEnabled } = res.locals.boundReflagClient.getFlag("show-todos"); +Generated declarations are optional. Singular reads infer their return type from the default, or return Boolean when no default is supplied. Optionally augment `Flags` to constrain keys, check non-null defaults against each key's value schema, and type batch records: - if (!isEnabled) { - res.status(403).send({"error": "flag inaccessible"}) - return +```ts +declare module "@reflag/node-sdk" { + interface Flags { + "new-editor": boolean; + model: "quick" | "quality"; + limits: { maxItems: number } | null; } - - ... -} -``` - -See [examples/express/app.ts](https://github.com/reflagcom/javascript/tree/main/packages/node-sdk/example/express/app.ts) for a full example. - -## Remote flag evaluation with stored context - -If you don't want to provide context each time when evaluating flags but -rather you would like to utilize the attributes you sent to Reflag previously -(by calling `updateCompany` and `updateUser`) you can do so by calling `getFlagsRemote` -(or `getFlagRemote` for a specific flag) with just `userId` and `companyId` -in that order. -These methods will call Reflag's servers and flags will be evaluated remotely -using the stored attributes. - -```typescript -// Update user and company attributes -client.updateUser("john_doe", { - attributes: { - name: "John O.", - role: "admin", - }, -}); - -client.updateCompany("acme_inc", { - attributes: { - name: "Acme, Inc", - tier: "premium" - }, -}); -... - -// This will evaluate flags using the stored attributes for the user/company pair -const flags = await client.getFlagsRemote("john_doe", "acme_inc"); -``` - -> [!IMPORTANT] -> User and company attribute updates are processed asynchronously, so there might -> be a small delay between when attributes are updated and when they are available -> for evaluation. - -## Opting out of tracking - -There are use cases in which you not want to be sending `user`, `company` and -`track` events to [Reflag.com](https://reflag.com). These are usually cases where you could be impersonating -another user in the system and do not want to interfere with the data being -collected by Reflag. - -To disable tracking, bind the client using `bindClient()` as follows: - -```typescript -// binds the client to a given user and company and set `enableTracking` to `false`. -const boundClient = client.bindClient({ user, company, enableTracking: false }); - -boundClient.track("some event"); // this will not actually send the event to Reflag. - -// the following code will not update the `user` nor `company` in Reflag and will -// not send `track` events either. -const { isEnabled, track } = boundClient.getFlag("user-menu"); -if (isEnabled) { - track(); } -``` - -Another way way to disable tracking without employing a bound client is to call `getFlag()` -or `getFlags()` by supplying `enableTracking: false` in the arguments passed to -these functions. - -> [!IMPORTANT] -> Note, however, that calling `track()`, `updateCompany()` or `updateUser()` in the `ReflagClient` -> will still send tracking data. As such, it is always recommended to use `bindClient()` -> when using this SDK. - -## Flushing - -ReflagClient employs a batching technique to minimize the number of calls that are sent to -Reflag's servers. - -By default, the SDK attempts to flush pending events when the Node.js event loop empties -(the `beforeExit` event). This behavior is controlled by the `flushOnExit` option in the client configuration: - -```typescript -const client = new ReflagClient({ - batchOptions: { - flushOnExit: false, // disable automatic flushing on exit - }, -}); -``` - -Node.js does not emit `beforeExit` for unhandled termination signals (such as `SIGTERM` or -`SIGINT`) or explicit `process.exit()` calls. For these shutdown paths, **await `client.flush()` -in your application's existing graceful shutdown hook**, after stopping incoming work and -waiting for in-flight requests or jobs to finish, and before exiting. This ensures events -produced during shutdown are included. Automatic flushing is best-effort and does not replace -an application-managed shutdown hook. - -## Tracking custom events and setting custom attributes - -Tracking allows events and updating user/company attributes in Reflag. -For example, if a customer changes their plan, you'll want Reflag to know about it, -in order to continue to provide up-do-date targeting information in the Reflag interface. -The following example shows how to register a new user, associate it with a company -and finally update the plan they are on. - -```typescript -// registers the user with Reflag using the provided unique ID, and -// providing a set of custom attributes (can be anything) -client.updateUser("user_id", { - attributes: { longTimeUser: true, payingCustomer: false }, -}); -client.updateCompany("company_id", { userId: "user_id" }); - -// the user started a voice huddle -client.track("user_id", "huddle", { attributes: { voice: true } }); +const model = reflag.getFlag(context, "model", "quick"); // string +const models = reflag.getFlags(context); // models.model: "quick" | "quality" | undefined ``` -It's also possible to achieve the same through a bound client in the following manner: +Augmentation rejects defaults with the wrong category, missing required properties, or incompatible nested types. Named-interface and readonly defaults are supported. Explicit `null` remains an arbitrary-JSON request, and bare/`undefined` reads still return Boolean. Return types continue to be inferred and widened from the default; generated types do not add nested runtime validation. The v2 CLI generates direct-value schemas from current production-environment variants. Regenerate old CLI wrapper declarations when migrating. Both destructuring `.isEnabled` and accessing it through an assigned singular value fail type checking, including without generated declarations. See the Express example for a typed direct-value integration. -```typescript -const boundClient = client.bindClient({ - user: { id: "user_id", longTimeUser: true, payingCustomer: false }, - company: { id: "company_id" }, -}); +## Bootstrap state -boundClient.track("huddle", { attributes: { voice: true } }); +```ts +const bootstrap = reflag.getFlagsForBootstrap(context); +// { protocolVersion: 2, context, flags: { model: { resolved, value, +// variantKey, sourceVersionId, matchedRuleId, ruleResults, errors, ... } }, +// flagStateVersion } ``` -Some attributes are used by Reflag to improve the UI, and are recommended -to provide for easier navigation: +Bootstrap uses batch evaluation and preserves selection metadata and raw context. It does **not** register browser checks. Local overrides/value-only fallbacks carry their values without fabricated authored-selection metadata. -- `name` -- display name for `user`/`company`, -- `email` -- the email of the user, -- `avatar` -- the URL for `user`/`company` avatar image. +**This is a v2 bootstrap contract, not the existing v1 Browser/React/Vue bootstrap shape.** Those consumers require a coordinated migration before accepting this state. Likewise, the current OpenFeature provider deliberately remains on published Node SDK v1 until its separate migration. -Attributes cannot be nested (multiple levels) and must be either strings, -integers or booleans. +## Remote evaluation -## Managing `Last seen` - -By default `updateUser`/`updateCompany` calls automatically update the given -user/company `Last seen` property on Reflag servers. - -You can control if `Last seen` should be updated when the events are sent by setting -`meta.active = false`. This is often useful if you -have a background job that goes through a set of companies just to update their -attributes but not their activity. - -Example: - -```typescript -client.updateUser("john_doe", { - attributes: { name: "John O." }, - meta: { active: true }, -}); - -client.updateCompany("acme_inc", { - attributes: { name: "Acme, Inc" }, - meta: { active: false }, +```ts +const enabled = await reflag.getFlagRemote( + "new-editor", + undefined, + "user-1", + "acme", +); +const model = await reflag.getFlagRemote("model", "quick", "user-1", "acme"); +const boundModel = await reflag + .bindClient(context) + .getFlagRemote("model", "quick"); +const values = await reflag.getFlagsRemote("user-1", "acme", { + other: { region: "eu" }, }); ``` -`bindClient()` updates attributes on the Reflag servers but does not automatically -update `Last seen`. - -## Zero PII +These methods use `/flags/evaluated` and return direct values. Singular remote reads use the same defaults, category checks, and JSON validation as local reads. The root `getFlagRemote(key, defaultValue, userId?, companyId?, context?)` places the default second; use `undefined` for an implicit Boolean read when passing explicit IDs. This moves the old positional IDs one place to the right. `getFlagsRemote()` keeps its existing argument order and returns a raw value record. -The Reflag SDK doesn't collect any metadata and HTTP IP addresses are _not_ being -stored. For tracking individual users, we recommend using something like database -ID as userId, as it's unique and doesn't include any PII (personal identifiable -information). If, however, you're using e.g. email address as userId, but prefer -not to send any PII to Reflag, you can hash the sensitive data before sending -it to Reflag: +Each requested singular root registers a check, including a default after a failed/missing remote evaluation, unless tracking is disabled. Only accepted authored selections retain the server's selection/version metadata. Explicit IDs, including numeric zero, take precedence over IDs in additional context. Stored attribute updates are asynchronous; remote evaluation need not immediately observe a just-sent update. -```typescript -import { sha256 } from 'crypto-hash'; - -client.updateUser({ userId: await sha256("john_doe"), ... }); -``` +## Edge runtimes -## Migrating from Bucket SDK +Use `EdgeClient` with Node compatibility enabled. It selects in-request synchronization. Call `ctx.waitUntil(client.flush())` before returning from a Worker so queued events and refresh work can complete. -If you have been using the Bucket SDKs previously, the following list will help you migrate to Reflag SDK: +## Configuration -- `Bucket*` classes, and types have been renamed to `Reflag*` (e.g. `BucketClient` is now `ReflagClient`) -- `Feature*` classes, and types have been renamed to `Flag*` (e.g. `Feature` is now `Flag`, `RawFeatures` is now `RawFlags`) -- When using strongly-typed flags, the new `Flags` interface replaced `Features` interface -- All methods that contained `feature` in the name have been renamed to use the `flag` terminology (e.g. `getFeature` is `getFlag`) -- All environment variables that were prefixed with `BUCKET_` are now prefixed with `REFLAG_` -- The `BUCKET_HOST` environment variable and `host` option have been removed from `ReflagClient` constructor, use `REFLAG_API_BASE_URL` instead -- The `BUCKET_FEATURES_ENABLED` and `BUCKET_FEATURES_DISABLED` have been renamed to `REFLAG_FLAGS_ENABLED` and `REFLAG_FLAGS_DISABLED` -- The default configuration file has been renamed from `bucketConfig.json` to `reflag.config.json` -- The `fallbackFeatures` property in client constructor and configuration files has been renamed to `fallbackFlags` -- `featureKey` has been renamed to `flagKey` in all methods that accepts that argument -- The SDKs will not emit `evaluate` and `evaluate-config` events anymore +Configuration precedence is constructor options, environment variables, then `reflag.config.json`. Supported environment variables include `REFLAG_SECRET_KEY`, `REFLAG_API_BASE_URL`, `REFLAG_LOG_LEVEL`, `REFLAG_OFFLINE`, `REFLAG_CONFIG_FILE`, and Boolean override lists `REFLAG_FLAGS_ENABLED` / `REFLAG_FLAGS_DISABLED`. -## Typescript +Constructor options also include a custom `logger` / `httpClient`, `flagsSyncMode`, `flagsPushUrl`, `fetchTimeoutMs`, `flagsFetchRetries`, `flagsFallbackProvider`, direct-value `flagOverrides`, and `batchOptions` (`maxSize`, `intervalMs`, `flushOnExit`). `emitEvaluationEvents` is deprecated and has no effect. -Types are bundled together with the library and exposed automatically when importing -through a package manager. +Invalid options/context or non-JSON defaults can throw. Network or definition-refresh failures are logged and retain usable state. Singular reads use their caller default (implicit `false`) without fabricating an authored false selection; batch reads retain raw values/`undefined`. Call `await client.flush()` before shutting down, then `client.destroy()` to stop background work. `batchOptions.flushOnExit` only flushes on natural Node process exit (`beforeExit`); it does not install signal handlers or force application shutdown. For signal-driven shutdown or an explicit `process.exit()`, await `flush()` in the application's own shutdown hook before exiting. ## License -> MIT License -> Copyright (c) 2025 Bucket ApS +MIT License. Copyright (c) 2025 Bucket ApS. diff --git a/packages/node-sdk/examples/cloudflare-worker/src/index.test.ts b/packages/node-sdk/examples/cloudflare-worker/src/index.test.ts index 515e3710d..c6af34d10 100644 --- a/packages/node-sdk/examples/cloudflare-worker/src/index.test.ts +++ b/packages/node-sdk/examples/cloudflare-worker/src/index.test.ts @@ -8,7 +8,7 @@ import worker from "./index"; const sdk = vi.hoisted(() => ({ initialize: vi.fn().mockResolvedValue(undefined), - getFlags: vi.fn().mockReturnValue({ "example-flag": { isEnabled: true } }), + getFlags: vi.fn().mockReturnValue({ "example-flag": true }), flush: vi.fn().mockResolvedValue(undefined), })); @@ -33,7 +33,7 @@ it("evaluates flags for the requested context and flushes background work", asyn await waitOnExecutionContext(ctx); expect(response.status).toBe(200); - expect(await response.text()).toContain('"example-flag"'); + expect(await response.text()).toContain('"example-flag": true'); expect(sdk.initialize).toHaveBeenCalledOnce(); expect(sdk.getFlags).toHaveBeenCalledWith({ user: { id: "user42" }, diff --git a/packages/node-sdk/examples/express/app.test.ts b/packages/node-sdk/examples/express/app.test.ts index 5471c90d2..83cf1b1e6 100644 --- a/packages/node-sdk/examples/express/app.test.ts +++ b/packages/node-sdk/examples/express/app.test.ts @@ -42,9 +42,9 @@ describe("API Tests", () => { expect(response.body).toEqual({ todos }); }); - it("denies todo creation when the enabled flag has no config payload", async () => { + it("denies todo creation when settings are unavailable", async () => { const remove = reflag.pushFlagOverrides({ - "create-todos": { isEnabled: true }, + "create-todos": null, }); try { const response = await request(app) diff --git a/packages/node-sdk/examples/express/app.ts b/packages/node-sdk/examples/express/app.ts index 4b251dce1..c938e644b 100644 --- a/packages/node-sdk/examples/express/app.ts +++ b/packages/node-sdk/examples/express/app.ts @@ -45,11 +45,9 @@ app.get("/todos", async (_req, res) => { // We use the `getFlag` method to check if the user has the "show-todos" feature enabled. // Note that "show-todos" is a feature that we defined in the `Flags` interface in the `reflag.ts` file. // and that the indexing for feature name below is type-checked at compile time. - const { isEnabled, track } = res.locals.reflagUser.getFlag("show-todos"); - - if (isEnabled) { - track(); + const showTodos = res.locals.reflagUser.getFlag("show-todos"); + if (showTodos) { // You can instead also send any custom event if you prefer, including attributes. // res.locals.reflagUser.track("Todo's viewed", { attributes: { access: "api" } }); @@ -67,20 +65,24 @@ app.post("/todos", (req, res) => { return res.status(400).json({ error: "Invalid todo" }); } - const { track, isEnabled, config } = - res.locals.reflagUser.getFlag("create-todos"); + const settings = res.locals.reflagUser.getFlag("create-todos", null); - // Check if the user has the "create-todos" feature enabled - if (isEnabled && config.payload) { + // Null/missing settings disable creation. Validate the arbitrary JSON payload. + if ( + settings !== null && + typeof settings === "object" && + !Array.isArray(settings) && + typeof settings.minimumLength === "number" + ) { // Check if the todo is at least N characters long - if (todo.length < config.payload.minimumLength) { + if (todo.length < settings.minimumLength) { return res .status(400) .json({ error: "Todo must be at least 5 characters long" }); } - // Track the feature usage - track(); + // Ordinary usage events are separate from the automatically registered check. + void res.locals.reflagUser.track("Todo created"); todos.push(todo); return res.status(201).json({ todo }); @@ -98,13 +100,12 @@ app.delete("/todos/:idx", (req, res) => { return res.status(400).json({ error: "Invalid index" }); } - const { track, isEnabled } = res.locals.reflagUser.getFlag("delete-todos"); + const canDelete = res.locals.reflagUser.getFlag("delete-todos"); - if (isEnabled) { + if (canDelete) { todos.splice(idx, 1); - - track(); - res.json({}); + void res.locals.reflagUser.track("Todo deleted"); + return res.json({}); } res diff --git a/packages/node-sdk/examples/express/reflag.ts b/packages/node-sdk/examples/express/reflag.ts index f754bbe96..4043cf6de 100644 --- a/packages/node-sdk/examples/express/reflag.ts +++ b/packages/node-sdk/examples/express/reflag.ts @@ -8,11 +8,7 @@ type CreateConfigPayload = { declare module "@reflag/node-sdk" { interface Flags { "show-todos": boolean; - "create-todos": { - config: { - payload: CreateConfigPayload; - }; - }; + "create-todos": CreateConfigPayload | null; "delete-todos": boolean; "some-else": {}; } @@ -20,15 +16,7 @@ declare module "@reflag/node-sdk" { const flagOverrides = (_: Context): FlagOverrides => { return { - "create-todos": { - isEnabled: true, - config: { - key: "short", - payload: { - minimumLength: 10, - }, - }, - }, + "create-todos": { minimumLength: 10 }, }; // feature keys checked at compile time }; diff --git a/packages/node-sdk/package.json b/packages/node-sdk/package.json index cddb0a328..770c8a20f 100644 --- a/packages/node-sdk/package.json +++ b/packages/node-sdk/package.json @@ -1,6 +1,6 @@ { "name": "@reflag/node-sdk", - "version": "1.8.3", + "version": "2.0.0-next.0", "license": "MIT", "repository": { "type": "git", @@ -18,7 +18,8 @@ "dev": "vite", "start": "vite", "build": "tsc --project tsconfig.build.json", - "test": "vitest run", + "test": "yarn test:types && vitest run", + "test:types": "tsc --project tsconfig.type-tests.json && tsc --project tsconfig.type-tests-augmented.json", "test:watch": "vitest", "test:ci": "yarn test --reporter=default --reporter=junit --outputFile=junit.xml", "coverage": "yarn test --coverage", @@ -34,7 +35,7 @@ "@aws-sdk/client-s3": "^3.888.0", "@googleapis/storage": "21.2.0", "@redis/client": "^5.11.0", - "@reflag/flag-evaluation-v1": "npm:@reflag/flag-evaluation@1.1.2" + "@reflag/flag-evaluation": "workspace:*" }, "devDependencies": { "@babel/core": "~7.29.6", diff --git a/packages/node-sdk/src/client.ts b/packages/node-sdk/src/client.ts index 1f10be5c0..52062c097 100644 --- a/packages/node-sdk/src/client.ts +++ b/packages/node-sdk/src/client.ts @@ -1,11 +1,6 @@ import fs from "fs"; -import { - EvaluationError, - EvaluationResult, - flattenJSON, - newEvaluator, -} from "@reflag/flag-evaluation-v1"; +import { flattenContext } from "@reflag/flag-evaluation"; import BatchBuffer from "./batch-buffer"; import { @@ -20,47 +15,50 @@ import { SDK_VERSION_HEADER_NAME, } from "./config"; import fetchClient, { withRetry } from "./fetch-http-client"; -import { FlagsCache, type FlagsCacheSnapshot } from "./flags-cache"; +import { + applyFlagDefault, + checkFlagDefault, + flagValueType, +} from "./flag-defaults"; +import { isFlagValue, prepareFlagCollection } from "./flag-definitions"; +import { FlagsCache } from "./flags-cache"; import { createFlagsSyncController, - FlagsSyncController, + type FlagsSyncController, } from "./flags-refresher"; import { isFlagsFallbackSnapshot } from "./flagsFallbackProvider"; import { subscribe as triggerOnExit } from "./flusher"; import { newRateLimiter } from "./rate-limiter"; import type { BootstrappedFlags, - CachedFlagDefinition, - EvaluatedFlagsAPIResponse, - FlagAPIResponse, - FlagDefinition, - FlagOverrides, - FlagOverridesFn, - FlagsFallbackProvider, - FlagsFallbackProviderContext, - FlagsFallbackSnapshot, - FlagsSyncMode, - IdType, - RawFlag, - RawFlags, - TypedFlagKey, -} from "./types"; -import { - Attributes, ClientOptions, Context, ContextWithTracking, + EvaluatedFlagsAPIResponse, + FlagCollection, + FlagDefaultFor, + FlagDefaultValue, + Flags, FlagEvent, + FlagOverrides, + FlagOverridesFn, FlagsAPIResponse, + FlagsFallbackSnapshot, + FlagValue, + FlagValueFromDefault, HttpClient, + IdType, Logger, - TrackingMeta, + RawFlag, + RawFlags, TrackOptions, + TypedFlagKey, TypedFlags, } from "./types"; import { applyLogLevel, canonicalContextJSONStringify, + canonicalJSONStringify, decorateLogger, hashObject, hashString, @@ -71,573 +69,302 @@ import { once, } from "./utils"; -const reflagConfigDefaultFile = "reflag.config.json"; - -function evaluationErrorsRateLimitKey(errors: EvaluationError[]): string { - return errors - .map((error) => - JSON.stringify([ - error.code, - error.field, - "operator" in error ? error.operator : "", - ]), - ) - .sort() - .join("\n"); -} - -const CLIENT_NOT_INITIALIZED_EVALUATION_ERROR = { - code: "CLIENT_NOT_INITIALIZED", - field: "", - message: - "ReflagClient was not initialized before this flag was evaluated. Call initialize() before evaluating flags.", -} as const; - -function withClientInitializationDiagnostic( - errors: FlagEvent["evalErrors"], - evaluatedBeforeInitialization: boolean, -): FlagEvent["evalErrors"] { - return evaluatedBeforeInitialization - ? [...(errors ?? []), CLIENT_NOT_INITIALIZED_EVALUATION_ERROR] - : errors; -} - -type PartialBy = Omit & Partial>; -type FlagOverrideLayer = { - id: number; - overrides: FlagOverridesFn; -}; - -function scheduleTrailingRefreshWithTimeout( - delayMs: number, - callback: () => void, -) { - const timer = setTimeout(callback, delayMs); - timer.unref?.(); - return () => { - clearTimeout(timer); - }; -} - -function normalizeFlagOverrides( - overrides: FlagOverridesFn | FlagOverrides | undefined, -): FlagOverridesFn { - if (typeof overrides === "function") { - return overrides; - } - - return () => overrides ?? {}; -} - -function composeFlagOverrides( - baseOverrides: FlagOverridesFn, - layers: FlagOverrideLayer[], -): FlagOverridesFn { - if (layers.length === 0) { - return baseOverrides; - } - - return (context) => - layers.reduce( - (acc, layer) => ({ - ...acc, - ...layer.overrides(context), - }), - baseOverrides(context), - ); -} - type BulkEvent = + | ({ type: "feature-flag-event" } & FlagEvent) | { type: "company"; companyId: IdType; userId?: IdType; - attributes?: Attributes; - context?: TrackingMeta; + attributes?: TrackOptions["attributes"]; + context?: TrackOptions["meta"]; } | { type: "user"; userId: IdType; - attributes?: Attributes; - context?: TrackingMeta; + attributes?: TrackOptions["attributes"]; + context?: TrackOptions["meta"]; } - | ({ type: "feature-flag-event" } & FlagEvent) | { type: "event"; event: string; - companyId?: IdType; userId: IdType; - attributes?: Attributes; - context?: TrackingMeta; + companyId?: IdType; + attributes?: TrackOptions["attributes"]; + context?: TrackOptions["meta"]; }; -function compileFlagDefinitions( - flags: FlagAPIResponse[], -): CachedFlagDefinition[] { - return flags.map((flagDef) => { - return { - ...flagDef, - enabledEvaluator: newEvaluator( - flagDef.targeting.rules.map((rule) => ({ - filter: rule.filter, - value: true, - })), - ), - configEvaluator: flagDef.config - ? newEvaluator( - flagDef.config.variants.map((variant) => ({ - filter: variant.filter, - value: { - key: variant.key, - payload: variant.payload, - }, - })), - ) - : undefined, - } satisfies CachedFlagDefinition; - }); +function normalizeOverrides( + overrides?: FlagOverrides | FlagOverridesFn, +): FlagOverridesFn { + if (typeof overrides === "function") { + return (context) => { + const result = overrides(context); + ok( + isObject(result) && isFlagValue(result), + "flagOverrides must return a JSON value map", + ); + return result; + }; + } + ok( + overrides === undefined || (isObject(overrides) && isFlagValue(overrides)), + "flagOverrides must be a JSON value map or function", + ); + return () => overrides ?? {}; } - -function createFlagsFallbackSnapshot( - flags: FlagAPIResponse[], -): FlagsFallbackSnapshot { - return { - version: 1, - savedAt: new Date().toISOString(), - flags, - }; +function scheduleRefresh(delayMs: number, callback: () => void) { + const timer = setTimeout(callback, delayMs); + timer.unref?.(); + return () => clearTimeout(timer); } - -function formatFlagsFallbackAge(savedAt: string): string | undefined { - const savedAtMs = Date.parse(savedAt); - if (!Number.isFinite(savedAtMs)) { - return undefined; - } - - const ageMs = Math.max(0, Date.now() - savedAtMs); - const minuteMs = 60_000; - const hourMs = 60 * minuteMs; - const dayMs = 24 * hourMs; - - if (ageMs < minuteMs) { - return "<1m"; - } - - if (ageMs < hourMs) { - return `${Math.floor(ageMs / minuteMs)}m`; - } - - if (ageMs < dayMs) { - return `${Math.floor(ageMs / hourMs)}h`; - } - - return `${Math.floor(ageMs / dayMs)}d`; +function copyValue(value: RawFlag["value"]): RawFlag["value"] { + return value === undefined ? undefined : structuredClone(value); } - -function createErrorWithCause(message: string, cause: unknown): Error { - const error = new Error(message) as Error & { cause?: unknown }; - error.cause = cause; - return error; +function localResult(key: string, value: RawFlag["value"]): RawFlag { + return { flagKey: key, resolved: false, value, ruleResults: [], errors: [] }; +} +function contextOnly({ + enableTracking: _, + meta: __, + ...context +}: ContextWithTracking): Context { + return context; } -/** - * The SDK client. - * - * @remarks - * This is the main class for interacting with Reflag. - * It is used to evaluate flags, update user and company contexts, and track events. - * - * @example - * ```ts - * // set the REFLAG_SECRET_KEY environment variable or pass the secret key to the constructor - * const client = new ReflagClient(); - * - * // evaluate a flag - * const isFlagEnabled = client.getFlag("flag-key", { - * user: { id: "user-id" }, - * company: { id: "company-id" }, - * }); - * ``` - **/ +/** V2 client: flag reads return values and immediately register checks. */ export class ReflagClient { - private _config: { - apiBaseUrl: string; - refetchInterval: number; - headers: Record; - fallbackFlags?: RawFlags; - flagsFallbackProvider?: FlagsFallbackProvider; - flagsFallbackProviderContext: FlagsFallbackProviderContext; - flagOverrides: FlagOverridesFn; - offline: boolean; - configFile?: string; - flagsFetchRetries: number; - fetchTimeoutMs: number; - flagsSyncMode: FlagsSyncMode; - flagsPushUrl: string; - }; - httpClient: HttpClient; - - private flagsCache: FlagsCache; - private batchBuffer: BatchBuffer; - private rateLimiter: ReturnType; - private baseFlagOverrides: FlagOverridesFn = () => ({}); - private flagOverrideLayers: FlagOverrideLayer[] = []; - private nextFlagOverrideLayerId = 0; - - /** - * Gets the logger associated with the client. - */ public readonly logger: Logger; - - private flagsSyncController: FlagsSyncController; - private initializationFinished = false; - private canLoadFlagsFallbackProvider = true; - private flagsFallbackSavePromise = Promise.resolve(); - private _initialize = once(async () => { - const start = Date.now(); - if (!this._config.offline) { + public readonly httpClient: HttpClient; + private readonly config; + private readonly flagsCache: FlagsCache; + private readonly flagsSyncController: FlagsSyncController; + private readonly batchBuffer: BatchBuffer; + private readonly rateLimiter = newRateLimiter( + FLAG_EVENT_RATE_LIMITER_WINDOW_SIZE_MS, + ); + private baseOverrides: FlagOverridesFn; + private overrideLayers: { overrides: FlagOverridesFn }[] = []; + private initialized = false; + private canLoadFallback = true; + private fallbackSave = Promise.resolve(); + private readonly initializeOnce = once(async () => { + if (!this.config.offline) { await this.flagsSyncController.start(); await this.flagsCache.refresh(); } + this.initialized = true; this.logger.info( - "Reflag initialized in " + - Math.round(Date.now() - start) + - "ms" + - (this._config.offline ? " (offline mode)" : ""), + `Reflag initialized${this.config.offline ? " (offline mode)" : ""}`, ); - this.initializationFinished = true; }); - /** - * Creates a new SDK client. - * See README for configuration options. - * - * @param options - The options for the client or an existing client to clone. - * @param options.secretKey - The secret key to use for the client. - * @param options.apiBaseUrl - The base URL to send requests to (optional). - * @param options.logger - The logger to use for logging (optional). - * @param options.httpClient - The HTTP client to use for sending requests (optional). - * @param options.logLevel - The log level to use for logging (optional). - * @param options.offline - Whether to run in offline mode (optional). - * @param options.fallbackFlags - The fallback flags to use if the flag is not found (optional). - * @param options.batchOptions - The options for the batch buffer (optional). - * @param options.flagOverrides - The flag overrides to use for the client (optional). - * @param options.configFile - The path to the config file (optional). - * @param options.flagsFetchRetries - Number of retries for fetching flags (optional, defaults to 3). - * @param options.fetchTimeoutMs - Timeout for fetching flags (optional, defaults to 10000ms). - * @param options.flagsSyncMode - How flag definitions are synchronized (optional, defaults to "push"). - * - * @throws An error if the options are invalid. - **/ constructor(options: ClientOptions = {}) { ok(isObject(options), "options must be an object"); - - ok( - options.host === undefined || - (typeof options.host === "string" && options.host.length > 0), - "host must be a string", - ); - ok( - options.apiBaseUrl === undefined || - (typeof options.apiBaseUrl === "string" && - options.apiBaseUrl.length > 0), - "apiBaseUrl must be a string", - ); + for (const key of [ + "host", + "apiBaseUrl", + "flagsPushUrl", + "secretKey", + ] as const) { + ok( + options[key] === undefined || + (typeof options[key] === "string" && options[key].length > 0), + `${key} must be a non-empty string`, + ); + } + for (const key of ["logger", "httpClient", "batchOptions"] as const) + ok( + options[key] === undefined || isObject(options[key]), + `${key} must be an object`, + ); + for (const key of ["flagsFetchRetries", "fetchTimeoutMs"] as const) + ok( + options[key] === undefined || + (Number.isInteger(options[key]) && options[key] >= 0), + `${key} must be a non-negative integer`, + ); ok( - options.logger === undefined || isObject(options.logger), - "logger must be an object", + options.offline === undefined || typeof options.offline === "boolean", + "offline must be a boolean", ); ok( - options.httpClient === undefined || isObject(options.httpClient), - "httpClient must be an object", + options.configFile === undefined || + typeof options.configFile === "string", + "configFile must be a string", ); ok( options.flagsFallbackProvider === undefined || (isObject(options.flagsFallbackProvider) && typeof options.flagsFallbackProvider.load === "function" && typeof options.flagsFallbackProvider.save === "function"), - "flagsFallbackProvider must be an object with load/save functions", - ); - ok( - options.fallbackFlags === undefined || - Array.isArray(options.fallbackFlags) || - isObject(options.fallbackFlags), - "fallbackFlags must be an array or object", - ); - ok( - options.batchOptions === undefined || isObject(options.batchOptions), - "batchOptions must be an object", - ); - ok( - options.configFile === undefined || - typeof options.configFile === "string", - "configFile must be a string", - ); - - ok( - options.flagsFetchRetries === undefined || - (Number.isInteger(options.flagsFetchRetries) && - options.flagsFetchRetries >= 0), - "flagsFetchRetries must be a non-negative integer", - ); - - ok( - options.fetchTimeoutMs === undefined || - (Number.isInteger(options.fetchTimeoutMs) && - options.fetchTimeoutMs >= 0), - "fetchTimeoutMs must be a non-negative integer", - ); - - ok( - options.flagsSyncMode === undefined || - options.flagsSyncMode === "polling" || - options.flagsSyncMode === "in-request" || - options.flagsSyncMode === "push", - 'flagsSyncMode must be one of "polling", "in-request", or "push"', + "flagsFallbackProvider must have load/save functions", ); - + const configFile = + options.configFile ?? + process.env.REFLAG_CONFIG_FILE ?? + (fs.existsSync("reflag.config.json") ? "reflag.config.json" : undefined); + const config = mergeSkipUndefined(loadConfig(configFile), options); + const offline = config.offline ?? process.env.NODE_ENV === "test"; ok( - options.flagsPushUrl === undefined || - (typeof options.flagsPushUrl === "string" && - options.flagsPushUrl.length > 0), - "flagsPushUrl must be a non-empty string", + offline || + (typeof config.secretKey === "string" && config.secretKey.length > 22), + "a valid secretKey is required unless offline=true", ); - - const envConfigFile = - typeof process.env.REFLAG_CONFIG_FILE === "string" && - process.env.REFLAG_CONFIG_FILE.length > 0 - ? process.env.REFLAG_CONFIG_FILE - : undefined; - - if (!options.configFile) { - options.configFile = - envConfigFile ?? - (fs.existsSync(reflagConfigDefaultFile) - ? reflagConfigDefaultFile - : undefined); - } - - const externalConfig = loadConfig(options.configFile); - const config = mergeSkipUndefined(externalConfig, options); - - const offline = config.offline ?? process.env.NODE_ENV === "test"; - if (!offline) { - ok( - typeof config.secretKey === "string", - "secretKey must be a string, or set offline=true", + this.logger = + options.logger ?? + applyLogLevel( + decorateLogger(REFLAG_LOG_PREFIX, console), + config.logLevel ?? "INFO", ); - ok(config.secretKey.length > 22, "invalid secretKey specified"); - } - - // use the supplied logger or apply the log level to the console logger - const logLevel = options.logLevel ?? config?.logLevel ?? "INFO"; - - this.logger = options.logger - ? options.logger - : applyLogLevel(decorateLogger(REFLAG_LOG_PREFIX, console), logLevel); - - const baseFlagOverrides = normalizeFlagOverrides( - typeof config.flagOverrides === "function" || - isObject(config.flagOverrides) - ? config.flagOverrides - : {}, - ); - + this.httpClient = options.httpClient ?? fetchClient; + this.baseOverrides = normalizeOverrides(config.flagOverrides); const fallbackFlags = Array.isArray(options.fallbackFlags) - ? options.fallbackFlags.reduce((acc, key) => { - acc[key as TypedFlagKey] = { - isEnabled: true, - key, - }; - return acc; - }, {} as RawFlags) - : isObject(options.fallbackFlags) - ? Object.entries(options.fallbackFlags).reduce( - (acc, [key, fallback]) => { - acc[key as TypedFlagKey] = { - isEnabled: - typeof fallback === "object" - ? fallback.isEnabled - : !!fallback, - key, - config: - typeof fallback === "object" && fallback.config - ? { - key: fallback.config.key, - payload: fallback.config.payload, - } - : undefined, - }; - return acc; - }, - {} as RawFlags, - ) - : undefined; - - this.rateLimiter = newRateLimiter(FLAG_EVENT_RATE_LIMITER_WINDOW_SIZE_MS); - this.httpClient = options.httpClient || fetchClient; - this.batchBuffer = new BatchBuffer({ - ...options?.batchOptions, - flushHandler: (items) => this.sendBulkEvents(items), - logger: this.logger, - }); - - const flagsSyncMode: FlagsSyncMode = + ? Object.fromEntries(options.fallbackFlags.map((key) => [key, true])) + : (options.fallbackFlags ?? {}); + ok( + isObject(fallbackFlags) && isFlagValue(fallbackFlags), + "fallbackFlags must contain JSON values", + ); + const flagsSyncMode = options.flagsSyncMode ?? (options.cacheStrategy === "in-request" ? "in-request" : options.cacheStrategy === "periodically-update" ? "polling" : "push"); - - const secretKeyHash = config.secretKey ? hashString(config.secretKey) : ""; - ok( - offline || flagsSyncMode !== "push" || secretKeyHash.length > 0, - 'flagsSyncMode="push" requires a valid secretKey', + ["polling", "push", "in-request"].includes(flagsSyncMode), + "invalid flagsSyncMode", ); - const pushUrl = new URL(options.flagsPushUrl ?? PUBSUB_SSE_URL); pushUrl.searchParams.delete("channels"); - - this._config = { + this.config = { offline, - apiBaseUrl: (config.apiBaseUrl ?? config.host) || API_BASE_URL, + fallbackFlags, + flagsFallbackProvider: options.flagsFallbackProvider, + fallbackContext: { + secretKeyHash: config.secretKey ? hashString(config.secretKey) : "", + }, + apiBaseUrl: (config.apiBaseUrl ?? config.host ?? API_BASE_URL).replace( + /\/?$/, + "/", + ), + fetchTimeoutMs: options.fetchTimeoutMs ?? API_TIMEOUT_MS, + flagsFetchRetries: options.flagsFetchRetries ?? 3, headers: { "Content-Type": "application/json", [SDK_VERSION_HEADER_NAME]: SDK_VERSION, - ["Authorization"]: `Bearer ${config.secretKey}`, + Authorization: `Bearer ${config.secretKey}`, }, - refetchInterval: FLAGS_REFETCH_MS, - fallbackFlags: fallbackFlags, - flagsFallbackProvider: options.flagsFallbackProvider, - flagsFallbackProviderContext: { - secretKeyHash, - }, - flagOverrides: baseFlagOverrides, - flagsFetchRetries: options.flagsFetchRetries ?? 3, - fetchTimeoutMs: options.fetchTimeoutMs ?? API_TIMEOUT_MS, - flagsSyncMode, - flagsPushUrl: pushUrl.toString(), }; - this.baseFlagOverrides = baseFlagOverrides; - - if ((config.batchOptions?.flushOnExit ?? true) && !this._config.offline) { + this.batchBuffer = new BatchBuffer({ + ...config.batchOptions, + logger: this.logger, + flushHandler: (events) => this.post("bulk", events), + }); + if (!offline && (config.batchOptions?.flushOnExit ?? true)) triggerOnExit(() => this.flush()); - } - - if (!new URL(this._config.apiBaseUrl).pathname.endsWith("/")) { - this._config.apiBaseUrl += "/"; - } - this.flagsCache = new FlagsCache( - async (waitForVersion?: number) => { - const path = - waitForVersion === undefined - ? "features" - : `features?waitForVersion=${encodeURIComponent(String(waitForVersion))}`; - - // A 304 cannot prove that a newer requested version was reached. - // Keep version-targeted fetches unconditional. + async (waitForVersion) => { + // A 304 cannot establish that a requested newer version was reached. const etag = waitForVersion === undefined ? this.flagsCache.getETag() : undefined; const response = await this.getResponse( - path, - this._config.flagsFetchRetries, + `flags${waitForVersion === undefined ? "" : `?waitForVersion=${encodeURIComponent(waitForVersion)}`}`, { etag }, ); - if (response?.status === 304) { - return { notModified: true }; - } - - const res = response?.body; - const flagStateVersion = res?.flagStateVersion; - if ( - !isObject(res) || - !Array.isArray(res?.features) || - typeof flagStateVersion !== "number" || - !Number.isInteger(flagStateVersion) || - flagStateVersion < 0 - ) { - const fallbackDefinitions = await this.loadFlagsFallbackDefinitions(); - return fallbackDefinitions - ? { definitions: fallbackDefinitions } - : undefined; - } - - if (flagStateVersion < (this.flagsCache.getFlagStateVersion() ?? -1)) { - return undefined; + if (response?.status === 304) return { notModified: true }; + const body = response?.body; + try { + if ( + !body || + body.protocolVersion !== 2 || + !Number.isSafeInteger(body.flagStateVersion) || + body.flagStateVersion < 0 + ) + throw new Error("invalid v2 flag response"); + return { + definitions: prepareFlagCollection(body), + flagStateVersion: body.flagStateVersion, + etag: response?.etag, + }; + } catch (error) { + this.logger.debug("flag collection unavailable or invalid", error); + return this.loadFallback(); } - - const snapshot: FlagsCacheSnapshot = { - definitions: compileFlagDefinitions(res.features), - flagStateVersion, - }; - this.saveFlagsFallbackDefinitions( - res.features, - snapshot, - response?.etag, - ); - this.canLoadFlagsFallbackProvider = false; - return snapshot; }, { logger: this.logger, - // Edge runtimes use `in-request` mode and cannot rely on delayed timer - // callbacks to perform trailing refresh work after the current request. scheduleTrailingRefresh: - flagsSyncMode === "in-request" - ? undefined - : scheduleTrailingRefreshWithTimeout, + flagsSyncMode === "in-request" ? undefined : scheduleRefresh, + onApply: (accepted) => { + const { definitions, flagStateVersion, fallback, etag } = accepted; + // Publish this snapshot's validator only after persistence succeeds. + // A late save must never change a replacement or destroyed cache. + accepted.etag = undefined; + if (fallback) return; + this.canLoadFallback = false; + if (!this.config.flagsFallbackProvider) { + accepted.etag = etag; + return; + } + // Persist only accepted snapshots, and serialize saves to prevent an old + // slow write from overwriting a newer collection in external storage. + const snapshot: FlagsFallbackSnapshot = structuredClone({ + version: 2, + savedAt: new Date().toISOString(), + flagStateVersion, + flags: definitions.flags, + segments: definitions.segments, + }); + this.fallbackSave = this.fallbackSave.then(async () => { + try { + await this.config.flagsFallbackProvider?.save( + this.config.fallbackContext, + snapshot, + ); + accepted.etag = etag; + } catch (error) { + this.logger.error( + "flagsFallbackProvider: failed to save flag definitions", + error, + ); + } + }); + }, }, ); - this.flagsSyncController = createFlagsSyncController({ - mode: this._config.flagsSyncMode, + mode: flagsSyncMode, cache: this.flagsCache, - intervalMs: this._config.refetchInterval, - pushUrl: this._config.flagsPushUrl, - headers: this._config.headers, + intervalMs: FLAGS_REFETCH_MS, + pushUrl: pushUrl.toString(), + headers: this.config.headers, logger: this.logger, }); } - private async loadFlagsFallbackDefinitions() { - if (!this.canLoadFlagsFallbackProvider) { - return undefined; - } - - this.canLoadFlagsFallbackProvider = false; - const provider = this._config.flagsFallbackProvider; - if (!provider) { - return undefined; - } - + private async loadFallback() { + if (!this.canLoadFallback) return undefined; + this.canLoadFallback = false; try { - const snapshot = await provider.load( - this._config.flagsFallbackProviderContext, + const snapshot = await this.config.flagsFallbackProvider?.load( + this.config.fallbackContext, + ); + if (!snapshot) return undefined; + ok(isFlagsFallbackSnapshot(snapshot), "invalid fallback snapshot"); + const definitions = prepareFlagCollection( + snapshot, + snapshot.source !== "static", ); - - if (!snapshot) { - this.logger.warn( - "remote flags unavailable, no fallback flags found in flagsFallbackProvider", - ); - return undefined; - } - - if (!isFlagsFallbackSnapshot(snapshot)) { - this.logger.warn("flagsFallbackProvider: invalid snapshot returned"); - return undefined; - } - - const fallbackAge = formatFlagsFallbackAge(snapshot.savedAt); this.logger.warn( - fallbackAge - ? `remote flags unavailable, using fallback flags fetched ${fallbackAge} ago (${snapshot.savedAt})` - : `remote flags unavailable, using fallback flags (${snapshot.savedAt})`, + `remote flags unavailable, using fallback flags (${snapshot.savedAt})`, ); - - return compileFlagDefinitions(snapshot.flags); + return { + definitions, + flagStateVersion: snapshot.flagStateVersion, + fallback: true, + }; } catch (error) { this.logger.error( "flagsFallbackProvider: failed to load flag definitions", @@ -647,619 +374,534 @@ export class ReflagClient { } } - private saveFlagsFallbackDefinitions( - flags: FlagAPIResponse[], - snapshot: FlagsCacheSnapshot, - etag?: string, - ) { - // Serialize background writes so an older save cannot overwrite a newer one. - this.flagsFallbackSavePromise = this.flagsFallbackSavePromise.then( - async () => { - try { - const provider = this._config.flagsFallbackProvider; - if (provider) { - await provider.save( - this._config.flagsFallbackProviderContext, - createFlagsFallbackSnapshot(flags), - ); - } - // Enable revalidation only after saving. A late save updates only its - // own snapshot, never a replacement or destroyed cache. - snapshot.etag = etag; - } catch (error) { - this.logger.error( - "flagsFallbackProvider: failed to save flag definitions", - error, - ); - } - }, + public async initialize() { + await this.initializeOnce(); + } + public async flush() { + if (this.config.offline) return; + await this.batchBuffer.flush(); + await this.flagsCache.waitRefresh(); + await this.fallbackSave; + } + public async refreshFlags(waitForVersion?: number) { + ok( + waitForVersion === undefined || + (Number.isSafeInteger(waitForVersion) && waitForVersion >= 0), + "waitForVersion must be a non-negative safe integer", ); + if (!this.config.offline) await this.flagsCache.refresh(waitForVersion); } - - /** - * Replaces the base flag overrides used by the client. - * - * @param overrides - The flag overrides. - * - * @remarks - * Base overrides are always applied before any temporary layers added through - * `pushFlagOverrides()`. - * - * @example - * ```ts - * client.setFlagOverrides({ - * "flag-1": true, - * "flag-2": false, - * }); - * ``` - **/ - setFlagOverrides(overrides: FlagOverridesFn | FlagOverrides) { - this.baseFlagOverrides = normalizeFlagOverrides(overrides); - this.syncFlagOverrides(); + public destroy() { + this.flagsSyncController.destroy(); + this.flagsCache.destroy(); + this.batchBuffer.destroy(); } - - /** - * @deprecated - * Use `setFlagOverrides()` for replacing the base override set. - **/ - set flagOverrides(overrides: FlagOverridesFn | FlagOverrides) { + public setFlagOverrides(overrides: FlagOverrides | FlagOverridesFn) { + this.baseOverrides = normalizeOverrides(overrides); + } + /** @deprecated Use setFlagOverrides. */ + public set flagOverrides(overrides: FlagOverrides | FlagOverridesFn) { this.setFlagOverrides(overrides); } - - /** - * Temporarily layers flag overrides on top of the current overrides. - * - * @param overrides - The flag overrides to apply for the scoped period. - * - * @returns A remove function that removes only this override layer. - * - * @remarks - * This is intended for tests or other short-lived local overrides. The remove - * function is idempotent and can safely be called multiple times. - * - * @example - * ```ts - * let remove: (() => void) | undefined; - * - * beforeEach(() => { - * remove = client.pushFlagOverrides({ "flag-1": true }); - * }); - * - * afterEach(() => { - * remove?.(); - * remove = undefined; - * }); - * ``` - **/ - pushFlagOverrides(overrides: FlagOverridesFn | FlagOverrides): () => void { - const layer: FlagOverrideLayer = { - id: this.nextFlagOverrideLayerId++, - overrides: normalizeFlagOverrides(overrides), - }; - - this.flagOverrideLayers.push(layer); - this.syncFlagOverrides(); - - let restored = false; - + public clearFlagOverrides() { + this.baseOverrides = () => ({}); + } + public pushFlagOverrides(overrides: FlagOverrides | FlagOverridesFn) { + const layer = { overrides: normalizeOverrides(overrides) }; + this.overrideLayers.push(layer); return () => { - if (restored) { - return; - } - restored = true; - - const layerIndex = this.flagOverrideLayers.findIndex( - ({ id }) => id === layer.id, + this.overrideLayers = this.overrideLayers.filter( + (candidate) => candidate !== layer, ); - if (layerIndex === -1) { - return; - } - - this.flagOverrideLayers.splice(layerIndex, 1); - this.syncFlagOverrides(); }; } - - /** - * Clears the base flag overrides. - * - * @remarks - * This does not affect temporary layers added with `pushFlagOverrides()`. - * - * @example - * ```ts - * client.clearFlagOverrides(); - * ``` - **/ - clearFlagOverrides() { - this.baseFlagOverrides = () => ({}); - this.syncFlagOverrides(); - } - - private syncFlagOverrides() { - this._config.flagOverrides = composeFlagOverrides( - this.baseFlagOverrides, - this.flagOverrideLayers, + public bindClient(options: ContextWithTracking) { + const bound = new BoundReflagClient(this, options); + void this.syncContext(options).catch((error) => + this.logger.error("failed to synchronize context", error), ); + return bound; } - /** - * Returns a new BoundReflagClient with the user/company/otherContext - * set to be used in subsequent calls. - * For example, for evaluating flag targeting or tracking events. - * - * @param context - The context to bind the client to. - * @param context.enableTracking - Whether to enable tracking for the context. - * @param context.user - The user context. - * @param context.company - The company context. - * @param context.other - The other context. - * - * @returns A new client bound with the arguments given. - * - * @throws An error if the user/company is given but their ID is not a string. - * - * @remarks - * The `updateUser` / `updateCompany` methods will automatically be called when - * the user/company is set respectively. - **/ - public bindClient({ - enableTracking = true, - ...context - }: ContextWithTracking) { - return new BoundReflagClient(this, { enableTracking, ...context }); + /** Complete definitions, including segments needed for offline evaluation. */ + public getFlagDefinitions(): FlagCollection { + this.onAccess(); + const collection = this.flagsCache.get(); + return JSON.parse( + JSON.stringify({ + flags: collection?.flags ?? [], + segments: collection?.segments ?? [], + }), + ) as FlagCollection; } - - /** - * Updates the associated user in Reflag. - * - * @param userId - The userId of the user to update. - * @param options - The options for the user. - * @param options.attributes - The additional attributes of the user (optional). - * @param options.meta - The meta context associated with tracking (optional). - * - * @throws An error if the company is not set or the options are invalid. - * @remarks - * The company must be set using `withCompany` before calling this method. - * If the user is set, the company will be associated with the user. - **/ - public async updateUser(userId: IdType, options?: TrackOptions) { - idOk(userId, "userId"); - ok(options === undefined || isObject(options), "options must be an object"); - ok( - options?.attributes === undefined || isObject(options.attributes), - "attributes must be an object", + /** Read a Boolean with an implicit false default, or supply an explicit value default. */ + public getFlag( + options: ContextWithTracking, + key: Key, + defaultValue?: undefined, + ): boolean; + public getFlag< + Key extends TypedFlagKey, + Default extends FlagDefaultFor, + >( + options: ContextWithTracking, + key: Key, + defaultValue: Default, + ): FlagValueFromDefault; + public getFlag( + options: ContextWithTracking, + key: TypedFlagKey, + defaultValue: FlagDefaultValue = false, + ): FlagValue { + checkFlagDefault(defaultValue); + return this.readFlagValue( + key, + defaultValue, + { ...this.evaluate(options, key, false), context: contextOnly(options) }, + options.enableTracking !== false, ); - checkMeta(options?.meta); - - if (this._config.offline) { - return; - } + } - if (this.rateLimiter.isAllowed(hashObject({ ...options, userId }))) { - await this.batchBuffer.add({ - type: "user", - userId, - attributes: options?.attributes, - context: options?.meta, - }); + private readFlagValue( + key: string, + defaultValue: FlagValue, + evaluation: { + flags: RawFlags; + context: Context; + flagStateVersion?: number; + evaluatedBeforeInitialization?: boolean; + }, + enableTracking: boolean, + ): FlagValue { + const result = evaluation.flags[key] ?? localResult(key, undefined); + const selected = applyFlagDefault(result.value, defaultValue); + if (selected.typeMismatch) + this.logger.warn( + `flag "${key}" returned ${flagValueType(result.value!)}; expected ${flagValueType(defaultValue)}. Using the default value.`, + ); + if (enableTracking) { + const checkResult = selected.usedDefault + ? { + ...localResult(key, defaultValue), + ruleResults: result.ruleResults, + errors: result.errors, + } + : result; + this.registerCheck( + key, + checkResult, + evaluation.context, + evaluation.flagStateVersion, + evaluation.evaluatedBeforeInitialization, + ); } + return structuredClone(selected.value); } - - /** - * Updates the associated company in Reflag. - * - * @param companyId - The companyId of the company to update. - * @param options - The options for the company. - * @param options.attributes - The additional attributes of the company (optional). - * @param options.meta - The meta context associated with tracking (optional). - * @param options.userId - The userId of the user to associate with the company (optional). - * - * @throws An error if the company is not set or the options are invalid. - * @remarks - * The company must be set using `withCompany` before calling this method. - * If the user is set, the company will be associated with the user. - **/ - public async updateCompany( - companyId: IdType, - options?: TrackOptions & { userId?: IdType }, - ) { - idOk(companyId, "companyId"); - ok(options === undefined || isObject(options), "options must be an object"); - ok( - options?.attributes === undefined || isObject(options.attributes), - "attributes must be an object", - ); - checkMeta(options?.meta); - - if (typeof options?.userId !== "undefined") { - idOk(options?.userId, "userId"); - } - - if (this._config.offline) { - return; - } - - if (this.rateLimiter.isAllowed(hashObject({ ...options, companyId }))) { - await this.batchBuffer.add({ - type: "company", - companyId, - userId: options?.userId, - attributes: options?.attributes, - context: options?.meta, - }); - } - } - - /** - * Tracks an event in Reflag. - - * @param options.companyId - Optional company ID for the event (optional). - * - * @throws An error if the user is not set or the event is invalid or the options are invalid. - * @remarks - * If the company is set, the event will be associated with the company. - **/ - public async track( - userId: IdType, - event: string, - options?: TrackOptions & { companyId?: IdType }, - ) { - idOk(userId, "userId"); - ok(typeof event === "string" && event.length > 0, "event must be a string"); - ok(options === undefined || isObject(options), "options must be an object"); - ok( - options?.attributes === undefined || isObject(options.attributes), - "attributes must be an object", - ); - ok( - options?.meta === undefined || isObject(options.meta), - "meta must be an object", - ); - if (options?.companyId !== undefined) { - idOk(options?.companyId, "companyId"); - } - - if (this._config.offline) { - return; - } - - await this.batchBuffer.add({ - type: "event", - event, - companyId: options?.companyId, - userId, - attributes: options?.attributes, - context: options?.meta, - }); - } - - /** - * Initializes the client by caching the flags definitions. - * - * @remarks - * Call this method before calling `getFlags` to ensure the flag definitions are cached. - * The client will ignore subsequent calls to this method. - **/ - public async initialize() { - await this._initialize(); - return; - } - - /** - * Flushes and completes any in-flight fetches in the flag cache. - * - * @remarks - * It is recommended to call this method when the application is shutting down to ensure all events are sent - * before the process exits. - * - * This method is automatically called on natural process exit (`beforeExit`) if - * `batchOptions.flushOnExit` is `true` in the options (default). For signal-driven - * shutdown or an explicit `process.exit()`, await this method in your application's - * shutdown hook before exiting. The SDK does not install signal handlers. - */ - public async flush() { - if (this._config.offline) { - return; - } - - await this.batchBuffer.flush(); - await this.flagsCache.waitRefresh(); - } - - /** - * Refreshes the flag definitions from the server. - * - * @remarks - * This triggers an on-demand refresh of the cached flag definitions. - * Useful when you know flags have changed and don't want to wait for the next automatic refresh cycle. - * - * Note: updated flag rules take a few seconds to propagate to all servers. - * - * Fetch starts are throttled to at most once per second. - * Outside `in-request` mode, throttling only delays when the next fetch - * begins: `refreshFlags(99)` still waits until the cache has applied flag - * definitions from version `99` or newer before the promise resolves. - * Concurrent callers are deduplicated and may share the same in-flight or - * scheduled follow-up refresh. - * - * In `in-request` mode, delayed follow-up refreshes are not scheduled. On edge - * runtimes like Cloudflare Workers, a call during the throttle window only - * records pending refresh work, and the promise may resolve before that fetch - * runs. The pending refresh is executed on the next request/access or - * `refreshFlags()` call after the throttle window expires. - * - * @param waitForVersion - Optional flag state version to wait for before returning updated definitions. - */ - public async refreshFlags(waitForVersion?: number) { - if (this._config.offline) { - return; - } - - await this.flagsCache.refresh(waitForVersion); - } - - /** - * Destroys the client and cleans up all resources including timers and background processes. - * - * @remarks - * After calling this method, the client should not be used anymore. - * This is particularly useful in development environments with hot reloading to prevent - * multiple background processes from running simultaneously. - */ - public destroy() { - this.flagsSyncController.destroy(); - this.flagsCache.destroy(); - this.batchBuffer.destroy(); - } - - /** - * Gets the flag definitions, including all config values. - * To evaluate which flags are enabled for a given user/company, use `getFlags`. - * - * @returns The flags definitions. - */ - public getFlagDefinitions(): FlagDefinition[] { - if (!this._config.offline) { - this.flagsSyncController.onAccess?.(); - } - const flags = this.flagsCache.get() || []; - return flags.map((f) => ({ - key: f.key, - description: f.description, - flag: f.targeting, - config: f.config, - })); - } - - /** - * Gets the evaluated flags for the current context which includes the user, company, and custom context. - * - * @param options - The options for the context. - * @param options.enableTracking - Whether to enable tracking for the context. - * @param options.meta - The meta context associated with the context. - * @param options.user - The user context. - * @param options.company - The company context. - * @param options.other - The other context. - * - * @returns The evaluated flags. - * - * @remarks - * Call `initialize` before calling this method to ensure the flag definitions are cached, no flags will be returned otherwise. - **/ - public getFlags({ - enableTracking = true, - ...context - }: ContextWithTracking): TypedFlags { - const contextWithTracking = { enableTracking, ...context }; - const rawFlags = this._getFlags(contextWithTracking); + /** Return all values and immediately register checks for the returned roots. */ + public getFlags(options: ContextWithTracking): TypedFlags { + const { flags } = this.evaluate(options, undefined, true); return Object.fromEntries( - Object.entries(rawFlags).map(([key, rawFlag]) => [ + Object.entries(flags).map(([key, result]) => [ key, - this._wrapRawFlag(contextWithTracking, rawFlag), + copyValue(result.value), ]), - ); + ) as TypedFlags; } - - /** - * Gets the evaluated flag for the current context which includes the user, company, and custom context. - * Using the `isEnabled` property sends a `check` event to Reflag. - * - * @param key - The key of the flag to get. - * @returns The evaluated flag. - * - * @remarks - * Call `initialize` before calling this method to ensure the flag definitions are cached, no flags will be returned otherwise. - **/ - public getFlag( - { enableTracking = true, ...context }: ContextWithTracking, - key: TKey, - ): TypedFlags[TKey] { - const contextWithTracking = { enableTracking, ...context }; - const rawFlag = this._getFlags(contextWithTracking, key); - return this._wrapRawFlag( - { enableChecks: true, ...contextWithTracking }, - rawFlag ?? { key }, + /** Serialization is not a read by the browser; it must not emit check events. */ + public getFlagsForBootstrap(options: ContextWithTracking): BootstrappedFlags { + const { flags, flagStateVersion } = this.evaluate( + options, + undefined, + false, ); + return { + protocolVersion: 2, + context: JSON.parse( + canonicalJSONStringify(contextOnly(options)), + ) as Context, + flags: structuredClone(flags), + ...(flagStateVersion === undefined ? {} : { flagStateVersion }), + }; } - /** - * Gets the evaluated flags for the current context without wrapping them in getters. - * This method returns raw flag data suitable for bootstrapping client-side applications. - * - * @param options - The options for the context. - * @param options.enableTracking - Whether to enable tracking for the context. - * @param options.meta - The meta context associated with the context. - * @param options.user - The user context. - * @param options.company - The company context. - * @param options.other - The other context. - * - * @returns The evaluated raw flags and the context. - * - * @remarks - * Call `initialize` before calling this method to ensure the flag definitions are cached, no flags will be returned otherwise. - * This method returns RawFlag objects without wrapping them in getters, making them suitable for serialization. - **/ - public getFlagsForBootstrap({ - enableTracking = true, - ...context - }: ContextWithTracking): BootstrappedFlags { - const contextWithTracking = { enableTracking, ...context }; + private onAccess() { + if (!this.config.offline) this.flagsSyncController.onAccess?.(); + } + private evaluate( + options: ContextWithTracking, + key: string | undefined, + checks: boolean, + ) { + checkContext(options); + const { enableTracking = true } = options; + const context = contextOnly(options); + if (!this.initialized) + this.logger.error("getFlag(s): ReflagClient is not initialized yet."); + void this.syncContext({ ...options, enableTracking }).catch((error) => + this.logger.error("failed to synchronize context", error), + ); + this.onAccess(); + const collection = this.flagsCache.get(); const flagStateVersion = this.flagsCache.getFlagStateVersion(); - + const flags: RawFlags = Object.create(null); + if (collection) { + if (key === undefined) + Object.assign(flags, collection.evaluator.evaluateAll(context).flags); + else if (collection.flags.some((flag) => flag.key === key)) + flags[key] = collection.evaluator.evaluateFlag(context, key); + if (!collection.trackSelections) + for (const [flagKey, result] of Object.entries(flags)) + flags[flagKey] = localResult(flagKey, result.value); + } else { + for (const [flagKey, value] of Object.entries(this.config.fallbackFlags)) + if (key === undefined || key === flagKey) + flags[flagKey] = localResult(flagKey, value); + } + const overrides = this.overrideLayers.reduce( + (current, layer) => ({ ...current, ...layer.overrides(context) }), + this.baseOverrides(context), + ); + for (const [flagKey, value] of Object.entries(overrides)) { + if (key !== undefined && key !== flagKey) continue; + ok(isFlagValue(value), "flag overrides must contain JSON values"); + flags[flagKey] = localResult(flagKey, value); + } + if (key !== undefined && !Object.prototype.hasOwnProperty.call(flags, key)) + flags[key] = localResult(key, undefined); + if (checks && enableTracking) + for (const [flagKey, result] of Object.entries(flags)) + this.registerCheck( + flagKey, + result, + context, + flagStateVersion, + !this.initialized, + ); return { - context: contextWithTracking, - flags: this._getFlags(contextWithTracking), - ...(flagStateVersion !== undefined ? { flagStateVersion } : {}), + flags, + flagStateVersion, + evaluatedBeforeInitialization: !this.initialized, + }; + } + + private registerCheck( + key: string, + result: RawFlag, + context: Context, + flagStateVersion?: number, + evaluatedBeforeInitialization = false, + ) { + if (this.config.offline) return; + const evalErrors: NonNullable = [...result.errors]; + if (evaluatedBeforeInitialization) + evalErrors.push({ + code: "CLIENT_NOT_INITIALIZED", + field: "", + message: + "ReflagClient was not initialized before this flag was evaluated. Call initialize() before evaluating flags.", + }); + const event: FlagEvent = { + action: "check", + key, + ...(result.resolved + ? { + evalResult: result.variantKey, + sourceVersionId: result.sourceVersionId, + } + : {}), + flagStateVersion, + evalContext: JSON.parse(canonicalJSONStringify(context)) as Record< + string, + unknown + >, + evalRuleResults: result.ruleResults.map((rule) => rule.matched), + ...(evalErrors.length ? { evalErrors } : {}), + }; + // Include selection/version identity: equal JSON payloads are not the same variant. + const identity = { + ...event, + evalContext: flattenContext(event.evalContext ?? {}), }; + if ( + !this.rateLimiter.isAllowed(hashString(canonicalJSONStringify(identity))) + ) + return; + if (result.errors.length) + this.logger.warn("flag targeting rules could not be fully evaluated.", { + [key]: result.errors, + }); + void this.batchBuffer + .add({ type: "feature-flag-event", ...event }) + .catch((error) => + this.logger.error(`failed to send check event for "${key}"`, error), + ); } - /** - * Gets evaluated flags with the usage of remote context. - * This method triggers a network request every time it's called. - * - * @param userId - The userId of the user to get the flags for. - * @param companyId - The companyId of the company to get the flags for. - * @param additionalContext - The additional context to get the flags for. - * - * @returns evaluated flags - */ public async getFlagsRemote( userId?: IdType, companyId?: IdType, - additionalContext?: Context, + context?: ContextWithTracking, ): Promise { - return this._getFlagsRemote( + const evaluation = await this.getRemote( undefined, userId, companyId, - additionalContext, + context, ); + if (context?.enableTracking !== false) + for (const [key, result] of Object.entries(evaluation.flags)) + this.registerCheck( + key, + result, + evaluation.context, + evaluation.flagStateVersion, + ); + return Object.fromEntries( + Object.entries(evaluation.flags).map(([key, result]) => [ + key, + copyValue(result.value), + ]), + ) as TypedFlags; } - - /** - * Gets evaluated flag with the usage of remote context. - * This method triggers a network request every time it's called. - * - * @param key - The key of the flag to get. - * @param userId - The userId of the user to get the flag for. - * @param companyId - The companyId of the company to get the flag for. - * @param additionalContext - The additional context to get the flag for. - * - * @returns evaluated flag - */ - public async getFlagRemote( - key: TKey, + public getFlagRemote( + key: Key, + defaultValue?: undefined, + userId?: IdType, + companyId?: IdType, + context?: ContextWithTracking, + ): Promise; + public getFlagRemote< + Key extends TypedFlagKey, + Default extends FlagDefaultFor, + >( + key: Key, + defaultValue: Default, userId?: IdType, companyId?: IdType, - additionalContext?: Context, - ): Promise { - return this._getFlagsRemote(key, userId, companyId, additionalContext); + context?: ContextWithTracking, + ): Promise>; + public async getFlagRemote( + key: TypedFlagKey, + defaultValue: FlagDefaultValue = false, + userId?: IdType, + companyId?: IdType, + context?: ContextWithTracking, + ): Promise { + checkFlagDefault(defaultValue); + const evaluation = await this.getRemote(key, userId, companyId, context); + return this.readFlagValue( + key, + defaultValue, + evaluation, + context?.enableTracking !== false, + ); } - - private buildUrl(path: string) { - if (path.startsWith("/")) { - path = path.slice(1); + private async getRemote( + key: string | undefined, + userId?: IdType, + companyId?: IdType, + additionalContext: ContextWithTracking = {}, + ): Promise<{ flags: RawFlags; context: Context; flagStateVersion?: number }> { + const context = { + ...contextOnly(additionalContext), + ...(userId === undefined + ? {} + : { user: { ...additionalContext.user, id: userId } }), + ...(companyId === undefined + ? {} + : { company: { ...additionalContext.company, id: companyId } }), + }; + checkContext(additionalContext); + checkContext(context); + if (this.config.offline) + return { + ...this.evaluate({ ...context, enableTracking: false }, key, false), + context, + }; + const query = new URLSearchParams({ + contextJson: canonicalContextJSONStringify(context) ?? "{}", + }); + if (key !== undefined) query.set("key", key); + const response = ( + await this.getResponse( + `flags/evaluated?${query}`, + ) + )?.body; + const flags: RawFlags = Object.create(null); + if ( + !response || + response.protocolVersion !== 2 || + !Number.isSafeInteger(response.flagStateVersion) || + response.flagStateVersion < 0 || + !isObject(response.flags) + ) + return { flags, context }; + for (const [flagKey, result] of Object.entries(response.flags)) { + if (key !== undefined && key !== flagKey) continue; + // The endpoint returns only successful selections, with the same metadata as local evaluation. + if ( + !isObject(result) || + !isFlagValue(result.value) || + typeof result.variantKey !== "string" || + !result.variantKey || + typeof result.sourceVersionId !== "string" || + !result.sourceVersionId || + typeof result.matchedRuleId !== "string" || + !Array.isArray(result.ruleResults) || + !result.ruleResults.every( + (rule) => + isObject(rule) && + typeof rule.ruleId === "string" && + typeof rule.matched === "boolean", + ) || + !Array.isArray(result.errors) || + !result.errors.every( + (error: unknown) => + isObject(error) && + typeof error.code === "string" && + typeof error.message === "string" && + (error.field === undefined || typeof error.field === "string") && + (error.operator === undefined || + typeof error.operator === "string") && + (error.source === undefined || + (isObject(error.source) && + ["flag", "segment"].includes(error.source.type) && + typeof error.source.key === "string")), + ) + ) + continue; + flags[flagKey] = { ...result, flagKey, resolved: true }; } - - const url = new URL(path, this._config.apiBaseUrl); - return url.toString(); + return { flags, context, flagStateVersion: response.flagStateVersion }; } - /** - * Sends a POST request to the specified path. - * - * @param path - The path to send the request to. - * @param body - The body of the request. - * - * @throws An error if the path or body is invalid. - **/ - private async post(path: string, body: TBody) { - ok(typeof path === "string" && path.length > 0, "path must be a string"); - ok(typeof body === "object", "body must be an object"); - - const url = this.buildUrl(path); - try { - const response = await this.httpClient.post( - url, - this._config.headers, - body, - ); - - this.logger.debug(`post request to "${url}"`, response); - - if (!response.ok || !isObject(response.body) || !response.body.success) { - throw createErrorWithCause( - `invalid response received from server for "${url}"`, - JSON.stringify(response), - ); - } - } catch (error) { - throw createErrorWithCause( - `post request to "${url}" failed with error`, - error, + public async updateUser(userId: IdType, options?: TrackOptions) { + idOk(userId, "userId"); + checkTrackOptions(options); + if ( + this.config.offline || + !this.rateLimiter.isAllowed(hashObject({ userId, ...options })) + ) + return; + await this.batchBuffer.add({ + type: "user", + userId, + attributes: options?.attributes, + context: options?.meta, + }); + } + public async updateCompany( + companyId: IdType, + options?: TrackOptions & { userId?: IdType }, + ) { + idOk(companyId, "companyId"); + checkTrackOptions(options); + if (options?.userId !== undefined) idOk(options.userId, "userId"); + if ( + this.config.offline || + !this.rateLimiter.isAllowed(hashObject({ companyId, ...options })) + ) + return; + await this.batchBuffer.add({ + type: "company", + companyId, + userId: options?.userId, + attributes: options?.attributes, + context: options?.meta, + }); + } + public async track( + userId: IdType, + event: string, + options?: TrackOptions & { companyId?: IdType }, + ) { + idOk(userId, "userId"); + ok( + typeof event === "string" && event.length > 0, + "event must be a non-empty string", + ); + checkTrackOptions(options); + if (options?.companyId !== undefined) idOk(options.companyId, "companyId"); + if (!this.config.offline) + await this.batchBuffer.add({ + type: "event", + userId, + event, + companyId: options?.companyId, + attributes: options?.attributes, + context: options?.meta, + }); + } + private async syncContext({ + enableTracking = true, + user, + company, + meta, + }: ContextWithTracking) { + if (!enableTracking || this.config.offline) return; + const pending: Promise[] = []; + if (user?.id !== undefined) { + const { id, ...attributes } = user; + pending.push(this.updateUser(id, { attributes, meta })); + } + if (company?.id !== undefined) { + const { id, ...attributes } = company; + pending.push( + this.updateCompany(id, { userId: user?.id, attributes, meta }), ); } + await Promise.all(pending); } - - /** - * Sends a GET request to the specified path. - * - * @param path - The path to send the request to. - * @param retries - Optional number of retries for the request. - * - * @returns The response from the server. - * @throws An error if the path is invalid. - **/ - private async getResponse( + private async post(path: string, body: BulkEvent[]) { + const response = await this.httpClient.post< + BulkEvent[], + { success: boolean } + >( + new URL(path, this.config.apiBaseUrl).toString(), + this.config.headers, + body, + ); + if (!response.ok || !response.body?.success) + throw new Error("invalid response sending bulk events"); + } + private async getResponse( path: string, - retries: number = 3, revalidation?: { etag?: string }, ) { - ok(typeof path === "string" && path.length > 0, "path must be a string"); - + const retries = this.config.flagsFetchRetries; + const url = new URL(path, this.config.apiBaseUrl).toString(); + const etag = revalidation?.etag; + const headers = etag + ? { ...this.config.headers, "If-None-Match": etag } + : this.config.headers; + let recoveryAvailable = Boolean(revalidation && !etag); + const request = (requestHeaders: Record) => + this.httpClient.get( + url, + requestHeaders, + this.config.fetchTimeoutMs, + ); try { - const url = this.buildUrl(path); - const etag = revalidation?.etag; - const headers = etag - ? { ...this._config.headers, "If-None-Match": etag } - : this._config.headers; - let recoveryAvailable = Boolean(revalidation && !etag); - const request = async (requestHeaders: Record) => { - const response = await this.httpClient.get< - TResponse & { success: boolean } - >(url, requestHeaders, this._config.fetchTimeoutMs); - this.logger.debug(`get request to "${url}"`, response); - return response; - }; - return await withRetry( async () => { let response = await request(headers); - if (response.status === 304 && etag) { - return response; - } - - // An unconditional definition request should not receive a 304. - // Recover once before falling back to normal error handling. + if (response.status === 304 && etag) return response; + // Recover once from an unexpected unconditional 304 across retries. if (response.status === 304 && recoveryAvailable) { recoveryAvailable = false; - response = await request(this._config.headers); + response = await request(this.config.headers); } - if ( !response.ok || !isObject(response.body) || - !response.body.success - ) { + response.body.success !== true + ) throw new Error( - `invalid response received from server for "${url}": ${JSON.stringify(response.body)}`, + `invalid response received from server for "${url}"`, ); - } return response; }, - (error) => { - this.logger.warn("failed to fetch flags, will retry", error); - }, + (error) => this.logger.warn("failed to fetch flags, will retry", error), retries, 1000, 10000, @@ -1272,782 +914,146 @@ export class ReflagClient { return undefined; } } - - /** - * Sends a batch of events to the Reflag API. - * - * @param events - The events to send. - * - * @throws An error if the send fails. - **/ - private async sendBulkEvents(events: BulkEvent[]) { - ok( - Array.isArray(events) && events.length > 0, - "events must be a non-empty array", - ); - - try { - await this.post("bulk", events); - } catch (error) { - throw createErrorWithCause("failed to send bulk events", error); - } - } - - /** - * Sends a flag event to the Reflag API. - * - * Flag events are used to track the evaluation of flag targeting rules. - * "check" events are sent when a flag's `isEnabled` property is checked. - * "evaluate" events are sent when a flag's targeting rules are matched against - * the current context. - * - * @param event - The event to send. - * @param event.action - The action to send. - * @param event.key - The key of the flag to send. - * @param event.targetingVersion - The targeting version of the flag to send. - * @param event.evalResult - The evaluation result of the flag to send. - * @param event.evalContext - The evaluation context of the flag to send. - * @param event.evalRuleResults - The evaluation rule results of the flag to send. - * @param event.evalMissingFields - The evaluation missing fields of the flag to send. - * @param event.evalErrors - The non-fatal evaluation diagnostics of the flag to send. - * - * @throws An error if the event is invalid. - * - * @remarks - * This method is rate-limited to prevent too many events from being sent. - **/ - private async sendFlagEvent(event: FlagEvent) { - ok(typeof event === "object", "event must be an object"); - ok( - typeof event.action === "string" && - (event.action === "check" || event.action === "check-config"), - "event must have an action", - ); - ok( - typeof event.key === "string" && event.key.length > 0, - "event must have a flag key", - ); - ok( - typeof event.targetingVersion === "number" || - event.targetingVersion === undefined, - "event must have a targeting version", - ); - ok( - typeof event.evalResult === "boolean" || isObject(event.evalResult), - "event must have an evaluation result", - ); - ok( - event.evalContext === undefined || typeof event.evalContext === "object", - "event context must be an object", - ); - ok( - event.evalRuleResults === undefined || - Array.isArray(event.evalRuleResults), - "event rule results must be an array", - ); - ok( - event.evalMissingFields === undefined || - Array.isArray(event.evalMissingFields), - "event missing fields must be an array", - ); - ok( - event.evalErrors === undefined || Array.isArray(event.evalErrors), - "event evaluation errors must be an array", - ); - - const contextKey = new URLSearchParams( - flattenJSON(event.evalContext || {}), - ).toString(); - - if (this._config.offline) { - return; - } - - if ( - !this.rateLimiter.isAllowed( - hashObject({ - action: event.action, - key: event.key, - targetingVersion: event.targetingVersion, - evalResult: event.evalResult, - contextKey, - }), - ) - ) { - return; - } - - await this.batchBuffer.add({ - type: "feature-flag-event", - ...event, - }); - } - - /** - * Updates the context in Reflag (if needed). - * This method should be used before requesting flags or binding a client. - * - * @param options - The options for the context. - * @param options.enableTracking - Whether to enable tracking for the context. - * @param options.meta - The meta context associated with the context. - * @param options.user - The user context. - * @param options.company - The company context. - * @param options.other - The other context. - */ - private async syncContext(options: ContextWithTracking) { - if (!options.enableTracking) { - this.logger.debug("tracking disabled, not updating user/company"); - - return; - } - - const promises: Promise[] = []; - if (typeof options.company?.id !== "undefined") { - const { id: _, ...attributes } = options.company; - promises.push( - this.updateCompany(options.company.id, { - userId: options.user?.id, - attributes, - meta: options.meta, - }), - ); - } - - if (typeof options.user?.id !== "undefined") { - const { id: _, ...attributes } = options.user; - promises.push( - this.updateUser(options.user.id, { - attributes, - meta: options.meta, - }), - ); - } - - if (promises.length > 0) { - await Promise.all(promises); - } - } - - /** - * Warns if a flag or config evaluation produced diagnostics. - * - * @param flag - The flag to check. - */ - private _warnFlagEvaluationDiagnostics(flag: { - key: string; - missingContextFields?: string[]; - evaluationErrors?: EvaluationError[]; - config?: { - key: string; - missingContextFields?: string[]; - evaluationErrors?: EvaluationError[]; - }; - }) { - const missingFieldsReport: Record = {}; - const errorReport: Record = {}; - const { config, ...flagData } = flag; - const evaluations = [ - { - reportKey: flagData.key, - rateLimitKey: { flagKey: flagData.key }, - missingContextFields: flagData.missingContextFields, - errors: flagData.evaluationErrors, - }, - ...(config - ? [ - { - reportKey: `${flagData.key}.config`, - rateLimitKey: { flagKey: flagData.key, configKey: config.key }, - missingContextFields: config.missingContextFields, - errors: config.evaluationErrors, - }, - ] - : []), - ]; - - for (const evaluation of evaluations) { - if ( - evaluation.missingContextFields?.length && - !evaluation.errors?.some( - ({ code }) => code === "MISSING_CONTEXT_FIELD", - ) && - this.rateLimiter.isAllowed( - hashObject({ - ...evaluation.rateLimitKey, - missingContextFields: JSON.stringify( - [...evaluation.missingContextFields].sort(), - ), - }), - ) - ) { - missingFieldsReport[evaluation.reportKey] = - evaluation.missingContextFields; - } - } - - if (Object.keys(missingFieldsReport).length > 0) { - this.logger.warn( - `flag targeting rules might not be correctly evaluated due to missing context fields.`, - missingFieldsReport, - ); - } - - for (const evaluation of evaluations) { - if ( - evaluation.errors?.length && - this.rateLimiter.isAllowed( - hashObject({ - ...evaluation.rateLimitKey, - evaluationErrors: evaluationErrorsRateLimitKey(evaluation.errors), - }), - ) - ) { - errorReport[evaluation.reportKey] = evaluation.errors; - } - } - - if (Object.keys(errorReport).length > 0) { - this.logger.warn( - "flag targeting rules could not be fully evaluated.", - errorReport, - ); - } - } - - private _getFlags(options: ContextWithTracking): RawFlags; - private _getFlags( - options: ContextWithTracking, - key: TKey, - ): RawFlag | undefined; - private _getFlags( - options: ContextWithTracking, - key?: TKey, - ): RawFlags | RawFlag | undefined { - checkContextWithTracking(options); - - if (!this.initializationFinished && !this._config.offline) { - this.logger.error("getFlag(s): ReflagClient is not initialized yet."); - } - - void this.syncContext(options); - let flagDefinitions: CachedFlagDefinition[] = []; - - if (!this._config.offline) { - this.flagsSyncController.onAccess?.(); - const flagDefs = this.flagsCache.get(); - if (!flagDefs) { - this.logger.warn( - "no flag definitions available, using fallback flags.", - ); - const fallbackFlags = this._config.fallbackFlags || {}; - if (key) { - return fallbackFlags[key]; - } - return fallbackFlags; - } - flagDefinitions = flagDefs; - } - - const { enableTracking: _, meta: __, ...context } = options; - - const evaluated = flagDefinitions - .filter(({ key: flagKey }) => (key ? key === flagKey : true)) - .map((flag) => ({ - flagKey: flag.key, - targetingVersion: flag.targeting.version, - configVersion: flag.config?.version, - enabledResult: flag.enabledEvaluator(context, flag.key), - configResult: - flag.configEvaluator?.(context, flag.key) ?? - ({ - flagKey: flag.key, - context, - value: undefined, - ruleEvaluationResults: [], - missingContextFields: [], - errors: undefined, - } satisfies EvaluationResult), - })); - - let evaluatedFlags = evaluated.reduce((acc, res) => { - acc[res.flagKey as TypedFlagKey] = { - key: res.flagKey, - isEnabled: res.enabledResult.value ?? false, - ruleEvaluationResults: res.enabledResult.ruleEvaluationResults, - missingContextFields: res.enabledResult.missingContextFields, - ...(res.enabledResult.errors?.length - ? { evaluationErrors: res.enabledResult.errors } - : {}), - targetingVersion: res.targetingVersion, - config: { - key: res.configResult?.value?.key, - payload: res.configResult?.value?.payload, - targetingVersion: res.configVersion, - ruleEvaluationResults: res.configResult?.ruleEvaluationResults, - missingContextFields: res.configResult?.missingContextFields, - ...(res.configResult?.errors?.length - ? { evaluationErrors: res.configResult.errors } - : {}), - }, - }; - return acc; - }, {} as RawFlags); - - const overrides = Object.entries(this._config.flagOverrides(context)) - .filter(([flagKey]) => (key ? key === flagKey : true)) - .map(([flagKey, override]) => [ - flagKey, - isObject(override) - ? { - key: flagKey, - isEnabled: override.isEnabled, - config: override.config, - } - : { - key: flagKey, - isEnabled: !!override, - config: undefined, - }, - ]); - - if (overrides.length > 0) { - // merge overrides into evaluated flags - evaluatedFlags = { - ...evaluatedFlags, - ...Object.fromEntries(overrides), - }; - } - - if (key) { - return evaluatedFlags[key]; - } - - return evaluatedFlags; - } - - private _wrapRawFlag( - { - enableTracking, - enableChecks = false, - ...context - }: { enableTracking: boolean; enableChecks?: boolean } & Context, - { config, ...flag }: PartialBy, - ): TypedFlags[TKey] { - // eslint-disable-next-line @typescript-eslint/no-this-alias - const client = this; - - const simplifiedConfig = config - ? { key: config.key, payload: config.payload } - : { key: undefined, payload: undefined }; - const evaluatedBeforeInitialization = - !this.initializationFinished && !this._config.offline; - const flagEvaluationErrors = withClientInitializationDiagnostic( - flag.evaluationErrors, - evaluatedBeforeInitialization, - ); - const configEvaluationErrors = withClientInitializationDiagnostic( - config?.evaluationErrors, - evaluatedBeforeInitialization, - ); - - return { - get isEnabled() { - if (enableTracking && enableChecks) { - client._warnFlagEvaluationDiagnostics(flag); - - void client - .sendFlagEvent({ - action: "check", - key: flag.key, - targetingVersion: flag.targetingVersion, - evalResult: flag.isEnabled ?? false, - evalContext: context, - evalRuleResults: flag.ruleEvaluationResults, - evalMissingFields: flag.missingContextFields, - evalErrors: flagEvaluationErrors, - }) - .catch((err) => { - client.logger?.error( - `failed to send check event for "${flag.key}": ${err}`, - err, - ); - }); - } - return flag.isEnabled ?? false; - }, - get config() { - if (enableTracking && enableChecks) { - client._warnFlagEvaluationDiagnostics({ ...flag, config }); - - void client - .sendFlagEvent({ - action: "check-config", - key: flag.key, - targetingVersion: config?.targetingVersion, - evalResult: simplifiedConfig, - evalContext: context, - evalRuleResults: config?.ruleEvaluationResults, - evalMissingFields: config?.missingContextFields, - evalErrors: configEvaluationErrors, - }) - .catch((err) => { - client.logger?.error( - `failed to send check event for "${flag.key}": ${err}`, - err, - ); - }); - } - return simplifiedConfig as TypedFlags[TKey]["config"]; - }, - key: flag.key, - track: async () => { - if (typeof context.user?.id === "undefined") { - this.logger.warn("no user set, cannot track event"); - return; - } - - if (enableTracking) { - await this.track(context.user.id, flag.key, { - companyId: context.company?.id, - }); - } else { - this.logger.debug("tracking disabled, not tracking event"); - } - }, - }; - } - - private async _getFlagsRemote( - key: undefined, - userId?: IdType, - companyId?: IdType, - additionalContext?: Context, - ): Promise; - private async _getFlagsRemote( - key: TKey, - userId?: IdType, - companyId?: IdType, - additionalContext?: Context, - ): Promise; - private async _getFlagsRemote( - key?: string, - userId?: IdType, - companyId?: IdType, - additionalContext?: Context, - ): Promise { - const context = additionalContext || {}; - if (userId) { - context.user = { id: userId }; - } - if (companyId) { - context.company = { id: companyId }; - } - - const contextWithTracking = { - ...context, - enableTracking: true, - }; - - checkContextWithTracking(contextWithTracking); - - const params = new URLSearchParams(); - const contextJson = canonicalContextJSONStringify(context); - if (contextJson) { - params.set("contextJson", contextJson); - } - - if (key) { - params.append("key", key); - } - - const query = params.toString(); - const response = await this.getResponse( - `features/evaluated${query ? `?${query}` : ""}`, - ); - const res = response?.body; - - if (key) { - const flag = res?.features[key]; - if (!flag) { - this.logger.error(`flag ${key} not found`); - } - return this._wrapRawFlag(contextWithTracking, { key, ...flag }); - } else { - return res?.features - ? Object.fromEntries( - Object.entries(res?.features).map(([flagKey, flag]) => [ - flagKey, - this._wrapRawFlag(contextWithTracking, flag), - ]), - ) - : {}; - } - } } -/** - * A client bound with a specific user, company, and other context. - */ +/** Context-bound reads have the same direct-value and immediate-check semantics. */ export class BoundReflagClient { - private readonly _client: ReflagClient; - private readonly _options: ContextWithTracking; - - /** - * (Internal) Creates a new BoundReflagClient. Use `bindClient` to create a new client bound with a specific context. - * - * @param client - The `ReflagClient` to use. - * @param options - The options for the client. - * @param options.enableTracking - Whether to enable tracking for the client. - * - * @internal - */ constructor( - client: ReflagClient, - { enableTracking = true, ...context }: ContextWithTracking, + private readonly client: ReflagClient, + private readonly options: ContextWithTracking, ) { - this._client = client; - - this._options = { enableTracking, ...context }; - - checkContextWithTracking(this._options); - void this._client["syncContext"](this._options); + checkContext(options); } - - /** - * Gets the "other" context associated with the client. - * - * @returns The "other" context or `undefined` if it is not set. - **/ - public get otherContext() { - return this._options.other; - } - - /** - * Gets the user associated with the client. - * - * @returns The user or `undefined` if it is not set. - **/ public get user() { - return this._options.user; + return this.options.user; } - - /** - * Gets the company associated with the client. - * - * @returns The company or `undefined` if it is not set. - **/ public get company() { - return this._options.company; + return this.options.company; + } + public get otherContext() { + return this.options.other; + } + public getFlag( + key: Key, + defaultValue?: undefined, + ): boolean; + public getFlag< + Key extends TypedFlagKey, + Default extends FlagDefaultFor, + >(key: Key, defaultValue: Default): FlagValueFromDefault; + public getFlag( + key: TypedFlagKey, + defaultValue: FlagDefaultValue = false, + ): FlagValue { + // The public overload already checked the key/default relationship. + return this.client.getFlag( + this.options, + key, + defaultValue as FlagDefaultFor, + ) as FlagValue; } - - /** - * Get flags for the user/company/other context bound to this client. - * Meant for use in serialization of flags for transferring to the client-side/browser. - * - * @returns Flags for the given user/company and whether each one is enabled or not - */ public getFlags(): TypedFlags { - return this._client.getFlags(this._options); + return this.client.getFlags(this.options); } - - /** - * Get raw flags for the user/company/other context bound to this client without wrapping them in getters. - * This method returns raw flag data suitable for bootstrapping client-side applications. - * - * @returns Raw flags for the given user/company and whether each one is enabled or not - */ - public getFlagsForBootstrap(): BootstrappedFlags { - return this._client.getFlagsForBootstrap({ ...this._options }); + public getFlagsForBootstrap() { + return this.client.getFlagsForBootstrap(this.options); } - - /** - * Get a specific flag for the user/company/other context bound to this client. - * Using the `isEnabled` property sends a `check` event to Reflag. - * - * @param key - The key of the flag to get. - * - * @returns Flags for the given user/company and whether each one is enabled or not - */ - public getFlag(key: TKey): TypedFlags[TKey] { - return this._client.getFlag(this._options, key); + public async getFlagsRemote(): Promise { + return this.client.getFlagsRemote(undefined, undefined, this.options); } - - /** - * Get remotely evaluated flag for the user/company/other context bound to this client. - * - * @returns Flags for the given user/company and whether each one is enabled or not - */ - public async getFlagsRemote() { - const { enableTracking: _, meta: __, ...context } = this._options; - return await this._client.getFlagsRemote(undefined, undefined, context); + public getFlagRemote( + key: Key, + defaultValue?: undefined, + ): Promise; + public getFlagRemote< + Key extends TypedFlagKey, + Default extends FlagDefaultFor, + >(key: Key, defaultValue: Default): Promise>; + public getFlagRemote( + key: TypedFlagKey, + defaultValue: FlagDefaultValue = false, + ): Promise { + // Preserve the relationship checked by the bound public overload. + return this.client.getFlagRemote( + key, + defaultValue as FlagDefaultFor, + undefined, + undefined, + this.options, + ) as Promise; } - - /** - * Get remotely evaluated flag for the user/company/other context bound to this client. - * - * @param key - The key of the flag to get. - * - * @returns Flag for the given user/company and key and whether it's enabled or not - */ - public async getFlagRemote(key: string) { - const { enableTracking: _, meta: __, ...context } = this._options; - return await this._client.getFlagRemote(key, undefined, undefined, context); + public bindClient(next: ContextWithTracking) { + return this.client.bindClient({ + ...this.options, + ...next, + enableTracking: next.enableTracking ?? this.options.enableTracking, + meta: next.meta ?? this.options.meta, + user: + next.user === undefined ? this.user : { ...this.user, ...next.user }, + company: + next.company === undefined + ? this.company + : { ...this.company, ...next.company }, + other: + next.other === undefined + ? this.otherContext + : { ...this.otherContext, ...next.other }, + }); } - - /** - * Track an event in Reflag. - * - * @param event - The event to track. - * @param options - The options for the event. - * @param options.attributes - The attributes of the event (optional). - * @param options.meta - The meta context associated with tracking (optional). - * @param options.companyId - Optional company ID for the event (optional). - * - * @throws An error if the event is invalid or the options are invalid. - */ public async track( event: string, - options?: TrackOptions & { companyId?: string }, + options?: TrackOptions & { companyId?: IdType }, ) { - ok(options === undefined || isObject(options), "options must be an object"); - checkMeta(options?.meta); - - const userId = this._options.user?.id; - - if (!userId) { - this._client.logger?.warn("no user set, cannot track event"); + if (this.user?.id === undefined) { + this.client.logger.warn("no user set, cannot track event"); return; } - - if (!this._options.enableTracking) { - this._client.logger?.debug( - "tracking disabled for this bound client, not tracking event", - ); - return; - } - - await this._client.track( - userId, - event, - options?.companyId - ? options - : { ...options, companyId: this._options.company?.id }, - ); - } - - /** - * Create a new client bound with the additional context. - * Note: This performs a shallow merge for user/company/other individually. - * - * @param context - The context to bind the client to. - * @param context.user - The user to bind the client to. - * @param context.company - The company to bind the client to. - * @param context.other - The other context to bind the client to. - * @param context.enableTracking - Whether to enable tracking for the client. - * @param context.meta - The meta context to bind the client to. - * - * @returns new client bound with the additional context - */ - public bindClient({ - user, - company, - other, - enableTracking, - meta, - }: ContextWithTracking) { - // merge new context into existing - const boundConfig = { - ...this._options, - user: - user === undefined - ? this._options.user - : { ...this._options.user, ...user }, - company: - company === undefined - ? this._options.company - : { ...this._options.company, ...company }, - other: - other === undefined - ? this._options.other - : { ...this._options.other, ...other }, - enableTracking: enableTracking ?? this._options.enableTracking, - meta: meta ?? this._options.meta, - }; - - return new BoundReflagClient(this._client, boundConfig); + if (this.options.enableTracking === false) return; + await this.client.track(this.user.id, event, { + ...options, + companyId: options?.companyId ?? this.company?.id, + }); } - - /** - * Flushes the batch buffer. - */ public async flush() { - await this._client.flush(); + await this.client.flush(); } - - /** - * Refreshes the flag definitions from the server. - * - * Fetch starts are throttled to at most once per second. Outside - * `in-request` mode, a call to `refreshFlags(waitForVersion)` still waits - * until the cache has applied that version or newer. - * - * In `in-request` mode, a throttled call only records pending refresh work. - * The fetch then runs on the next request/access or `refreshFlags()` call - * after the throttle window expires. - * - * @param waitForVersion - Optional flag state version to wait for before returning updated definitions. - */ public async refreshFlags(waitForVersion?: number) { - await this._client.refreshFlags(waitForVersion); + await this.client.refreshFlags(waitForVersion); } } - -function checkMeta( - meta?: TrackingMeta, -): asserts meta is TrackingMeta | undefined { - ok( - typeof meta === "undefined" || isObject(meta), - "meta must be an object if given", - ); +function checkTrackOptions(options?: TrackOptions) { + ok(options === undefined || isObject(options), "options must be an object"); ok( - meta?.active === undefined || typeof meta?.active === "boolean", - "meta.active must be a boolean if given", + options?.attributes === undefined || isObject(options.attributes), + "attributes must be an object", ); -} - -function checkContext(context: Context): asserts context is Context { - ok(isObject(context), "context must be an object"); ok( - typeof context.user === "undefined" || isObject(context.user), - "user must be an object if given", + options?.meta === undefined || isObject(options.meta), + "meta must be an object", ); - if (typeof context.user?.id !== "undefined") { - idOk(context.user.id, "user.id"); - } - ok( - typeof context.company === "undefined" || isObject(context.company), - "company must be an object if given", + options?.meta?.active === undefined || + typeof options.meta.active === "boolean", + "meta.active must be a boolean", ); - if (typeof context.company?.id !== "undefined") { - idOk(context.company.id, "company.id"); +} +function checkContext(context: ContextWithTracking) { + ok(isObject(context), "context must be an object"); + for (const name of ["user", "company"] as const) { + ok( + context[name] === undefined || isObject(context[name]), + `${name} must be an object`, + ); + if (context[name]?.id !== undefined) idOk(context[name].id, `${name}.id`); } - ok( context.other === undefined || isObject(context.other), - "other must be an object if given", + "other must be an object", ); -} - -function checkContextWithTracking( - context: ContextWithTracking, -): asserts context is ContextWithTracking & { enableTracking: boolean } { - checkContext(context); - ok( - typeof context.enableTracking === "boolean", + context.enableTracking === undefined || + typeof context.enableTracking === "boolean", "enableTracking must be a boolean", ); - - checkMeta(context.meta); + checkTrackOptions({ meta: context.meta }); } diff --git a/packages/node-sdk/src/config.ts b/packages/node-sdk/src/config.ts index e549274c1..b0ab3ccf2 100644 --- a/packages/node-sdk/src/config.ts +++ b/packages/node-sdk/src/config.ts @@ -1,6 +1,7 @@ import { readFileSync } from "fs"; import { version } from "../package.json"; +import { isFlagValue } from "./flag-definitions"; import { LOG_LEVELS } from "./types"; import { isObject, ok } from "./utils"; @@ -24,26 +25,7 @@ function parseOverrides(config: object | undefined) { if (!config) return {}; if ("flagOverrides" in config && isObject(config.flagOverrides)) { Object.entries(config.flagOverrides).forEach(([key, value]) => { - ok( - typeof value === "boolean" || isObject(value), - `invalid type "${typeof value}" for key ${key}, expected boolean or object`, - ); - if (isObject(value)) { - ok( - "isEnabled" in value && typeof value.isEnabled === "boolean", - `invalid type "${typeof value.isEnabled}" for key ${key}.isEnabled, expected boolean`, - ); - ok( - value.config === undefined || isObject(value.config), - `invalid type "${typeof value.config}" for key ${key}.config, expected object or undefined`, - ); - if (isObject(value.config)) { - ok( - "key" in value.config && typeof value.config.key === "string", - `invalid type "${typeof value.config.key}" for key ${key}.config.key, expected string`, - ); - } - } + ok(isFlagValue(value), `invalid JSON flag override for ${key}`); }); return config.flagOverrides; diff --git a/packages/node-sdk/src/flag-defaults.ts b/packages/node-sdk/src/flag-defaults.ts new file mode 100644 index 000000000..9669111e8 --- /dev/null +++ b/packages/node-sdk/src/flag-defaults.ts @@ -0,0 +1,32 @@ +import { isFlagValue } from "./flag-definitions"; +import type { FlagValue } from "./types"; +import { ok } from "./utils"; + +export function checkFlagDefault(value: unknown): asserts value is FlagValue { + ok(isFlagValue(value), "defaultValue must be a JSON value"); +} + +export function flagValueType(value: FlagValue): string { + return value === null + ? "null" + : Array.isArray(value) + ? "array" + : typeof value; +} + +/** Null is an explicit arbitrary-JSON read; other defaults require the same category. */ +export function applyFlagDefault( + value: FlagValue | undefined, + defaultValue: FlagValue, +) { + const typeMismatch = + value !== undefined && + defaultValue !== null && + flagValueType(value) !== flagValueType(defaultValue); + const usedDefault = value === undefined || typeMismatch; + return { + value: usedDefault ? defaultValue : value, + usedDefault, + typeMismatch, + }; +} diff --git a/packages/node-sdk/src/flag-definitions.ts b/packages/node-sdk/src/flag-definitions.ts new file mode 100644 index 000000000..8989b51ce --- /dev/null +++ b/packages/node-sdk/src/flag-definitions.ts @@ -0,0 +1,211 @@ +import { + newEvaluator, + type RuleFilter, + type RuleResult, +} from "@reflag/flag-evaluation"; + +import type { CachedFlagCollection, FlagCollection, FlagValue } from "./types"; +import { isObject, ok } from "./utils"; + +export function isFlagValue( + value: unknown, + ancestors = new Set(), +): value is FlagValue { + if (value === null || typeof value === "string" || typeof value === "boolean") + return true; + if (typeof value === "number") return Number.isFinite(value); + if (typeof value !== "object" || ancestors.has(value)) return false; + if ( + !Array.isArray(value) && + Object.getPrototypeOf(value) !== Object.prototype && + Object.getPrototypeOf(value) !== null + ) + return false; + ancestors.add(value); + const valid = Object.values(value).every((entry) => + isFlagValue(entry, ancestors), + ); + ancestors.delete(value); + return valid; +} + +const operators = new Set([ + "IS", + "IS_NOT", + "ANY_OF", + "NOT_ANY_OF", + "CONTAINS", + "NOT_CONTAINS", + "GT", + "LT", + "AFTER", + "BEFORE", + "DATE_AFTER", + "DATE_BEFORE", + "SET", + "NOT_SET", + "IS_TRUE", + "IS_FALSE", +]); +function isFilter(value: unknown): value is RuleFilter { + if (!isObject(value)) return false; + switch (value.type) { + case "constant": + return typeof value.value === "boolean"; + case "context": + return ( + typeof value.field === "string" && + operators.has(value.operator) && + (value.values === undefined || + (Array.isArray(value.values) && + value.values.every((v: unknown) => typeof v === "string"))) + ); + case "rolloutPercentage": + return ( + typeof value.key === "string" && + typeof value.partialRolloutAttribute === "string" && + Number.isInteger(value.partialRolloutThreshold) && + value.partialRolloutThreshold >= 0 && + value.partialRolloutThreshold <= 100000 + ); + case "flag": + return ( + typeof value.key === "string" && typeof value.variantKey === "string" + ); + case "segment": + return typeof value.key === "string"; + case "negation": + return isFilter(value.filter); + case "group": + return ( + (value.operator === "and" || value.operator === "or") && + Array.isArray(value.filters) && + value.filters.every(isFilter) + ); + default: + return false; + } +} +function isResult( + value: unknown, + variants: Record, +): value is RuleResult { + if (!isObject(value)) return false; + if (value.type === "variant") + return ( + typeof value.variantKey === "string" && + Object.prototype.hasOwnProperty.call(variants, value.variantKey) + ); + if ( + value.type !== "percentageDistribution" || + typeof value.key !== "string" || + !value.key || + typeof value.attribute !== "string" || + !value.attribute || + !Array.isArray(value.allocations) || + !value.allocations.length + ) + return false; + return ( + value.allocations.every( + (a: unknown) => + isObject(a) && + Number.isFinite(a.percentage) && + a.percentage >= 0 && + a.percentage <= 100 && + Math.abs(a.percentage * 1000 - Math.round(a.percentage * 1000)) <= + 1e-8 && + isObject(a.destination) && + (a.destination.type === "nextRule" || + (a.destination.type === "variant" && + isResult(a.destination, variants))), + ) && + value.allocations.reduce( + (sum: number, a: { percentage: number }) => + sum + Math.round(a.percentage * 1000), + 0, + ) === 100000 + ); +} + +/** Validate and prepare the entire graph before replacing any cached snapshot. */ +export function prepareFlagCollection( + value: unknown, + trackSelections = true, +): CachedFlagCollection { + ok( + isObject(value) && + Array.isArray(value.flags) && + Array.isArray(value.segments), + "expected a complete flags/segments collection", + ); + for (const flag of value.flags) { + ok( + isObject(flag) && + typeof flag.key === "string" && + flag.key.length > 0 && + typeof flag.sourceVersionId === "string" && + flag.sourceVersionId.length > 0 && + isObject(flag.variants) && + isFlagValue(flag.variants) && + Object.keys(flag.variants).length > 0 && + Object.keys(flag.variants).every((key) => key.length > 0) && + Array.isArray(flag.rules) && + flag.rules.length > 0, + "invalid compiled flag", + ); + const ids = new Set(); + for (const rule of flag.rules) { + ok( + isObject(rule) && + typeof rule.id === "string" && + rule.id.length > 0 && + !ids.has(rule.id) && + isFilter(rule.filter) && + isResult(rule.result, flag.variants as Record), + "invalid compiled rule", + ); + ids.add(rule.id); + } + const last = flag.rules[flag.rules.length - 1]; + ok( + last.filter.type === "constant" && + last.filter.value === true && + last.result.type === "variant", + "compiled flag requires a fixed catch-all", + ); + } + for (const segment of value.segments) + ok( + isObject(segment) && + typeof segment.key === "string" && + isFilter(segment.filter), + "invalid compiled segment", + ); + const collection = structuredClone({ + flags: value.flags.map( + ({ + key, + sourceVersionId, + variants, + rules, + }: FlagCollection["flags"][number]) => ({ + key, + sourceVersionId, + variants, + rules, + }), + ), + segments: value.segments.map( + ({ key, filter }: FlagCollection["segments"][number]) => ({ + key, + filter, + }), + ), + }) as FlagCollection; + return { + ...collection, + evaluator: newEvaluator(collection), + trackSelections, + }; +} diff --git a/packages/node-sdk/src/flags-cache.ts b/packages/node-sdk/src/flags-cache.ts index 21713f918..a2e0e4b9c 100644 --- a/packages/node-sdk/src/flags-cache.ts +++ b/packages/node-sdk/src/flags-cache.ts @@ -1,11 +1,12 @@ -import type { CachedFlagDefinition, Logger } from "./types"; +import type { CachedFlagCollection, Logger } from "./types"; const DEFAULT_MIN_REFRESH_INTERVAL_MS = 1000; /** ETags belong to their snapshot, even when persistence publishes them later. */ export type FlagsCacheSnapshot = { - readonly definitions: CachedFlagDefinition[]; + readonly definitions: CachedFlagCollection; readonly flagStateVersion?: number; + fallback?: boolean; etag?: string; }; @@ -21,6 +22,7 @@ type ScheduledRefresh = { type FlagsCacheOptions = { logger?: Logger; + onApply?: (snapshot: FlagsCacheSnapshot) => void; minRefreshIntervalMs?: number; scheduleTrailingRefresh?: ( delayMs: number, @@ -57,7 +59,7 @@ export class FlagsCache { private readonly fetchFlags: ( waitForVersion?: number, ) => Promise, - options: FlagsCacheOptions = {}, + private readonly options: FlagsCacheOptions = {}, ) { this.logger = options.logger; this.minRefreshIntervalMs = @@ -258,6 +260,7 @@ export class FlagsCache { this.snapshot = result; this.lastRefreshAt = Date.now(); + this.options.onApply?.(result); this.logger?.info("refreshed flag definitions"); } diff --git a/packages/node-sdk/src/flagsFallbackProvider.ts b/packages/node-sdk/src/flagsFallbackProvider.ts index 5caeb900a..8ad3d55dd 100644 --- a/packages/node-sdk/src/flagsFallbackProvider.ts +++ b/packages/node-sdk/src/flagsFallbackProvider.ts @@ -2,7 +2,8 @@ import { promises as fs } from "fs"; import path from "path"; import type { - FlagAPIResponse, + FlagDefinition, + FlagValue, FlagsFallbackProvider, FlagsFallbackProviderContext, FlagsFallbackSnapshot, @@ -133,11 +134,11 @@ export type StaticFallbackProviderOptions = { /** * Static fallback flags keyed by flag key. */ - flags: Record; + flags: Record; }; function defaultSnapshotName(secretKeyHash: string) { - return `flags-fallback-${secretKeyHash.slice(0, 16)}.json`; + return `flags-fallback-v2-${secretKeyHash.slice(0, 16)}.json`; } function snapshotFilePath( @@ -166,7 +167,7 @@ function snapshotRedisKey( context: FlagsFallbackProviderContext, keyPrefix = "reflag:flags-fallback", ) { - return `${trimTrailingCharacter(keyPrefix, ":")}:${context.secretKeyHash.slice(0, 16)}`; + return `${trimTrailingCharacter(keyPrefix, ":")}:v2:${context.secretKeyHash.slice(0, 16)}`; } export function isFlagsFallbackSnapshot( @@ -174,25 +175,15 @@ export function isFlagsFallbackSnapshot( ): value is FlagsFallbackSnapshot { return ( isObject(value) && - value.version === 1 && + value.version === 2 && typeof value.savedAt === "string" && + Number.isFinite(Date.parse(value.savedAt)) && + (value.source === undefined || value.source === "static") && + (value.flagStateVersion === undefined || + (Number.isSafeInteger(value.flagStateVersion) && + value.flagStateVersion >= 0)) && Array.isArray(value.flags) && - value.flags.every(isFlagApiResponse) - ); -} - -function isFlagApiResponse(value: unknown): value is FlagAPIResponse { - return ( - isObject(value) && - typeof value.key === "string" && - typeof value.description !== "undefined" && - isObject(value.targeting) && - typeof value.targeting.version === "number" && - Array.isArray(value.targeting.rules) && - (value.config === undefined || - (isObject(value.config) && - typeof value.config.version === "number" && - Array.isArray(value.config.variants))) + Array.isArray(value.segments) ); } @@ -230,24 +221,18 @@ function isNotFoundError(error: any) { ); } -function staticFlagApiResponse( - key: string, - isEnabled: boolean, -): FlagAPIResponse { +function staticFlagDefinition(key: string, value: FlagValue): FlagDefinition { return { key, - description: null, - targeting: { - version: 1, - rules: [ - { - filter: { - type: "constant", - value: isEnabled, - }, - }, - ], - }, + sourceVersionId: `static:${key}`, + variants: { default: value }, + rules: [ + { + id: "default", + filter: { type: "constant", value: true }, + result: { type: "variant", variantKey: "default" }, + }, + ], }; } @@ -371,11 +356,13 @@ export function createStaticFallbackProvider({ return { async load() { return { - version: 1, + version: 2, + source: "static", savedAt: new Date().toISOString(), - flags: Object.entries(flags).map(([key, isEnabled]) => - staticFlagApiResponse(key, isEnabled), + flags: Object.entries(flags).map(([key, value]) => + staticFlagDefinition(key, value), ), + segments: [], }; }, diff --git a/packages/node-sdk/src/index.ts b/packages/node-sdk/src/index.ts index e6bcd752c..d5f67a5d8 100644 --- a/packages/node-sdk/src/index.ts +++ b/packages/node-sdk/src/index.ts @@ -7,7 +7,7 @@ import { } from "./flagsFallbackProvider"; export { BoundReflagClient, ReflagClient } from "./client"; -export { EdgeClient, EdgeClientOptions } from "./edgeClient"; +export { EdgeClient, type EdgeClientOptions } from "./edgeClient"; export type { FileFallbackProviderOptions, GCSFallbackProviderClient, @@ -18,7 +18,6 @@ export type { S3FallbackProviderOptions, StaticFallbackProviderOptions, } from "./flagsFallbackProvider"; - export const fallbackProviders = { static: createStaticFallbackProvider, file: createFileFallbackProvider, @@ -34,30 +33,27 @@ export type { ClientOptions, Context, ContextWithTracking, - EmptyFlagRemoteConfig, - Flag, - FlagAPIResponse, - FlagConfigVariant, + FlagCollection, FlagDefinition, - FlagOverride, + FlagDefaultFor, + FlagDefaultValue, + FlagEvent, FlagOverrides, FlagOverridesFn, - FlagRemoteConfig, Flags, FlagsAPIResponse, FlagsFallbackProvider, FlagsFallbackProviderContext, FlagsFallbackSnapshot, FlagsSyncMode, - FlagType, + FlagValue, + FlagValueFromDefault, HttpClient, HttpClientResponse, IdType, - LOG_LEVELS, Logger, LogLevel, RawFlag, - RawFlagRemoteConfig, RawFlags, TrackingMeta, TrackOptions, diff --git a/packages/node-sdk/src/types.ts b/packages/node-sdk/src/types.ts index 3757f504e..1c79e7e0b 100644 --- a/packages/node-sdk/src/types.ts +++ b/packages/node-sdk/src/types.ts @@ -1,871 +1,240 @@ -/* eslint-disable @typescript-eslint/no-empty-object-type */ - -import { +import type { + CompiledCollection, + CompiledFlag, EvaluationError, - newEvaluator, - RuleFilter, -} from "@reflag/flag-evaluation-v1"; + Evaluator, + FlagEvaluationResult, +} from "@reflag/flag-evaluation"; + +export type FlagValue = + | null + | boolean + | number + | string + | FlagValue[] + | { [key: string]: FlagValue }; +/** JSON defaults may be readonly; returned values are independent mutable copies. */ +export type FlagDefaultValue = + | null + | boolean + | number + | string + | readonly FlagDefaultValue[] + | { readonly [key: string]: FlagDefaultValue }; + +// Keep arbitrary JSON opaque instead of recursively expanding its index signature. +type ReadonlyFlagValue = FlagValue extends T + ? FlagDefaultValue | object + : T extends object + ? { readonly [Key in keyof T]: ReadonlyFlagValue } + : T; + +/** Registered defaults match the value schema; null explicitly requests arbitrary JSON. */ +export type FlagDefaultFor< + Registry, + Key extends PropertyKey, +> = keyof Registry extends never + ? FlagDefaultValue | object + : Key extends keyof Registry + ? ReadonlyFlagValue | null + : never; + +/** Infer values from defaults, widening literals. Null explicitly requests arbitrary JSON. */ +export type FlagValueFromDefault = T extends null + ? FlagValue + : T extends boolean + ? boolean + : T extends number + ? number + : T extends string + ? string + : T extends readonly (infer Element)[] + ? [Element] extends [never] + ? FlagValue[] + : FlagValueFromDefault[] + : T extends object + ? { -readonly [Key in keyof T]: FlagValueFromDefault } + : never; -/** - * Describes the meta context associated with tracking. - **/ -export type TrackingMeta = { - /** - * Whether the user or company is active. - **/ - active?: boolean; -}; - -/** - * Describes the attributes of a user, company or event. - **/ export type Attributes = Record; +export type TrackingMeta = { active?: boolean }; +export type IdType = string | number; -/** - * Describes a flag event. Can be "check" or "check-config event". - **/ -export type FlagEvent = { - /** - * The action that was performed. - **/ - action: "check" | "check-config"; - - /** - * The flag key. - **/ - key: string; - - /** - * The feature targeting version (optional). - **/ - targetingVersion: number | undefined; - - /** - * The result of targeting evaluation. - **/ - evalResult: - | boolean - | { key: string; payload: any } - | { key: undefined; payload: undefined }; - - /** - * The context that was used for evaluation. - **/ - evalContext?: Record; - - /** - * The result of evaluation of each rule (optional). - **/ - evalRuleResults?: boolean[]; - - /** - * The missing fields in the evaluation context (optional). - * @deprecated Use `evalErrors` and check for `MISSING_CONTEXT_FIELD`. - **/ - evalMissingFields?: string[]; +/** Augment this interface with flag keys and their returned value types. */ +// eslint-disable-next-line @typescript-eslint/no-empty-object-type +export interface Flags {} +export type TypedFlagKey = keyof Flags extends never + ? string + : Extract; +export type TypedFlags = keyof Flags extends never + ? Record + : { [Key in keyof Flags]: Flags[Key] | undefined }; +export type FlagOverrides = Partial< + keyof Flags extends never + ? Record + : { [Key in keyof Flags]: Flags[Key] } +>; +export type FlagOverridesFn = (context: Context) => FlagOverrides; - /** - * Non-fatal diagnostics produced while evaluating the flag (optional). - **/ - evalErrors?: Array<{ - code: string; - field: string; - operator?: string; - message: string; - }>; +export type FlagDefinition = CompiledFlag; +export type FlagCollection = CompiledCollection & { + segments: NonNullable; }; - -/** - * A remotely managed configuration value for a feature. - */ -export type RawFlagRemoteConfig = { - /** - * The key of the matched configuration value. - */ - key: string; - - /** - * The version of the targeting rules used to select the config value. - */ - targetingVersion?: number; - - /** - * The optional user-supplied payload data. - */ - payload: any; - - /** - * The rule results of the evaluation (optional). - */ - ruleEvaluationResults?: boolean[]; - - /** - * The missing fields in the evaluation context (optional). - * @deprecated Use `evaluationErrors` and check for `MISSING_CONTEXT_FIELD`. - */ - missingContextFields?: string[]; - - /** - * Non-fatal diagnostics produced while evaluating targeting rules. - */ - evaluationErrors?: EvaluationError[]; +export type FlagsAPIResponse = FlagCollection & { + protocolVersion: 2; + flagStateVersion: number; }; - -/** - * Describes a feature. - */ -export interface RawFlag { - /** - * The key of the feature. - */ - key: string; - - /** - * If the feature is enabled. - */ - isEnabled: boolean; - - /** - * The version of the targeting used to evaluate if the feature is enabled (optional). - */ - targetingVersion?: number; - - /** - * The remote configuration value for the feature. - */ - config?: RawFlagRemoteConfig; - - /** - * The rule results of the evaluation (optional). - */ - ruleEvaluationResults?: boolean[]; - - /** - * The missing fields in the evaluation context (optional). - * @deprecated Use `evaluationErrors` and check for `MISSING_CONTEXT_FIELD`. - */ - missingContextFields?: string[]; - - /** - * Non-fatal diagnostics produced while evaluating targeting rules. - */ - evaluationErrors?: EvaluationError[]; -} - -/** - * Describes a collection of evaluated raw flags. - */ -export type RawFlags = Record; - -/** - * Describes a collection of evaluated raw flags and the context for bootstrapping. - */ +export type CachedFlagCollection = FlagCollection & { + evaluator: Evaluator; + /** Static SDK values do not identify authored variants. */ + trackSelections: boolean; +}; +export type RawFlag = Omit< + FlagEvaluationResult, + "sourceVersionId" | "value" | "resolved" +> & { + sourceVersionId?: string; + value: FlagValue | undefined; + resolved: boolean; +}; +export type RawFlags = Record; export type BootstrappedFlags = { + protocolVersion: 2; context: Context; flags: RawFlags; flagStateVersion?: number; }; - -export type EmptyFlagRemoteConfig = { key: undefined; payload: undefined }; - -/** - * A remotely managed configuration value for a feature. - */ -export type FlagRemoteConfig = - | { - /** - * The key of the matched configuration value. - */ - key: string; - - /** - * The optional user-supplied payload data. - */ - payload: any; - } - | EmptyFlagRemoteConfig; - -/** - * Describes a feature - */ -export interface Flag< - TConfig extends FlagType["config"] = EmptyFlagRemoteConfig, -> { - /** - * The key of the feature. - */ - key: string; - - /** - * If the feature is enabled. - */ - isEnabled: boolean; - - /* - * Optional user-defined configuration. - */ - config: - | ({ - key: string; - } & TConfig) - | EmptyFlagRemoteConfig; - - /** - * Track feature usage in Reflag. - */ - track(): Promise; -} - -export type FlagType = { - config?: { - payload: any; - }; -}; - -export type FlagOverride = - | (FlagType & { - isEnabled: boolean; - config?: { - key: string; - }; - }) - | boolean; - -/** - * Describes a feature definition. - */ -export type FlagDefinition = { - /** - * The key of the feature. - */ - key: string; - - /** - * Description of the feature. - */ - description: string | null; - - /** - * The targeting rules for the feature. - */ - flag: { - /** - * The version of the targeting rules. - */ - version: number; - - /** - * The targeting rules. - */ - rules: { - /** - * The filter for the rule. - */ - filter: RuleFilter; - }[]; - }; - - /** - * The remote configuration for the feature. - */ - config?: { - /** - * The version of the remote configuration. - */ - version: number; - - /** - * The variants of the remote configuration. - */ - variants: FlagConfigVariant[]; - }; -}; - -/** - * Describes a collection of evaluated features. - * - * @remarks - * You should extend the Flags interface to define the available features. - */ -export interface Flags {} - -/** - * Describes a collection of evaluated feature. - * - * @remarks - * This types falls back to a generic Record if the Flags interface - * has not been extended. - * - */ -export type TypedFlags = keyof Flags extends never - ? Record - : { - [FlagKey in keyof Flags]: Flags[FlagKey] extends FlagType - ? Flag - : Flag; - }; - -export type TypedFlagKey = keyof TypedFlags; - -/** - * Describes the feature overrides. - */ -export type FlagOverrides = Partial< - keyof Flags extends never - ? Record - : { - [FlagKey in keyof Flags]: Flags[FlagKey] extends FlagOverride - ? Flags[FlagKey] - : Exclude; - } ->; - -export type FlagOverridesFn = (context: Context) => FlagOverrides; - -/** - * Describes a remote feature config variant. - */ -export type FlagConfigVariant = { - /** - * The filter for the variant. - */ - filter: RuleFilter; - - /** - * The optional user-supplied payload data. - */ - payload: any; - - /** - * The key of the variant. - */ - key: string; +export type EvaluatedFlagsAPIResponse = { + protocolVersion: 2; + flagStateVersion: number; + remoteContextUsed: boolean; + flags: Record< + string, + Omit< + Extract, { resolved: true }>, + "flagKey" | "resolved" + > + >; }; -/** - * (Internal) Describes a specific feature in the API response. - * - * @internal - */ -export type FlagAPIResponse = { - /** - * The key of the feature. - */ +/** A check records the selected variant key, never its JSON payload. */ +export type FlagEvent = { + action: "check"; key: string; - - /** - * Description of the feature. - */ - description: string | null; - - /** - * The targeting rules for the feature. - */ - targeting: { - /** - * The version of the targeting rules. - */ - version: number; - - /** - * The targeting rules. - */ - rules: { - /** - * The filter for the rule. - */ - filter: RuleFilter; - }[]; - }; - - /** - * The remote configuration for the feature. - */ - config?: { - /** - * The version of the remote configuration. - */ - version: number; - - /** - * The variants of the remote configuration. - */ - variants: FlagConfigVariant[]; - }; -}; - -/** - * (Internal) Describes the response of the features endpoint. - * - * @internal - */ -export type FlagsAPIResponse = { - /** - * Optional for backward compatibility; when absent, the snapshot version - * should be treated as unknown by consumers. - */ + evalResult?: string; + sourceVersionId?: string; flagStateVersion?: number; - - /** - * The feature definitions. - */ - features: FlagAPIResponse[]; + evalContext?: Record; + evalRuleResults?: boolean[]; + /** @deprecated Use evalErrors and check for MISSING_CONTEXT_FIELD. */ + evalMissingFields?: string[]; + evalErrors?: Array< + | EvaluationError + | { code: "CLIENT_NOT_INITIALIZED"; field: string; message: string } + >; }; -/** - * Snapshot of flag definitions used for fallback initialization. - */ -export type FlagsFallbackSnapshot = { - /** - * Snapshot schema version. - */ - version: number; - - /** - * ISO timestamp indicating when the snapshot was saved. - */ +/** V1 snapshots cannot be evaluated by the collection evaluator. */ +export type FlagsFallbackSnapshot = FlagCollection & { + version: 2; savedAt: string; - - /** - * Raw flag definitions as returned by the API. - */ - flags: FlagAPIResponse[]; -}; - -/** - * Non-secret context passed to fallback providers so they can derive - * storage keys without access to the raw secret key. - */ -export type FlagsFallbackProviderContext = { - /** - * Deterministic hash of the configured secret key. - */ - secretKeyHash: string; + flagStateVersion?: number; + source?: "static"; }; - -/** - * Provider used to load and save raw flag definition snapshots. - */ +export type FlagsFallbackProviderContext = { secretKeyHash: string }; export interface FlagsFallbackProvider { - /** - * Load a previously saved snapshot. - */ load( context: FlagsFallbackProviderContext, ): Promise; - - /** - * Persist a snapshot after a successful live fetch. - */ save( context: FlagsFallbackProviderContext, snapshot: FlagsFallbackSnapshot, ): Promise; } -/** - * (Internal) Flag definitions with the addition of a pre-prepared - * evaluators functions for the rules. - * - * @internal - */ -export type CachedFlagDefinition = FlagAPIResponse & { - enabledEvaluator: ReturnType>; - configEvaluator: ReturnType> | undefined; -}; - -/** - * (Internal) Describes the response of the evaluated features endpoint. - * - * @internal - */ -export type EvaluatedFlagsAPIResponse = { - /** - * True if request successful. - */ - success: true; - - /** - * True if additional context for user or company was found and used for evaluation on the remote server. - */ - remoteContextUsed: boolean; - - /** - * The feature definitions. - */ - features: RawFlags; -}; - -/** - * Describes the response of a HTTP client. - * - * @typeParam TResponse - The type of the response body. - */ -export type HttpClientResponse = { - /** - * The status code of the response. - **/ +export type HttpClientResponse = { status: number; - - /** - * Indicates that the request succeeded. - **/ ok: boolean; - - /** - * The body of the response if available. - **/ - body: TResponse | undefined; - - /** - * The response's ETag, if available. Return its exact value to enable - * conditional flag-definition refreshes with a custom HTTP client. - **/ + body: Response | undefined; + /** Exact response ETag for conditional definition refreshes, when available. */ etag?: string; }; - -/** - * Defines the interface for an HTTP client. - * - * @remarks - * This interface is used to abstract the HTTP client implementation from the SDK. - * Define your own implementation of this interface to use a different HTTP client. - **/ export interface HttpClient { - /** - * Sends a POST request to the specified URL. - * - * @param url - The URL to send the request to. - * @param headers - The headers to include in the request. - * @param body - The body of the request. - * @returns The response from the server. - **/ - post( + post( url: string, headers: Record, - body: TBody, - ): Promise>; - - /** - * Sends a GET request to the specified URL. - * - * @param url - The URL to send the request to. - * @param headers - The headers to include in the request. - * @returns The response from the server. - **/ - get( + body: Body, + ): Promise>; + get( url: string, headers: Record, timeoutMs: number, - ): Promise>; + ): Promise>; } - -/** - * Logger interface for logging messages - */ export interface Logger { - /** - * Log a debug messages - * - * @param message - The message to log - * @param data - Optional data to log - */ - debug: (message: string, data?: any) => void; - - /** - * Log an info messages - * - * @param message - The message to log - * @param data - Optional data to log - */ - info: (message: string, data?: any) => void; - - /** - * Log a warning messages - * - * @param message - The message to log - * @param data - Optional data to log - */ - warn: (message: string, data?: any) => void; - - /** - * Log an error messages - * - * @param message - The message to log - * @param data - Optional data to log - */ - error: (message: string, data?: any) => void; + debug(message: string, data?: any): void; + info(message: string, data?: any): void; + warn(message: string, data?: any): void; + error(message: string, data?: any): void; } - -/** - * Options for configuring the BatchBuffer. - * - * @template T - The type of items in the buffer. - */ export type BatchBufferOptions = { - /** - * A function that handles flushing the items in the buffer. - **/ flushHandler: (items: T[]) => Promise; - - /** - * The logger to use for logging (optional). - **/ logger?: Logger; - - /** - * The maximum size of the buffer before it is flushed. - * - * @defaultValue `100` - **/ maxSize?: number; - - /** - * The interval in milliseconds at which the buffer is flushed. - * @remarks - * If `0`, the buffer is flushed only when `maxSize` is reached. - * @defaultValue `10000` - **/ intervalMs?: number; - /** - * Whether to flush the buffer on natural process exit (`beforeExit`). - * This does not install signal handlers. For signal-driven shutdown or an - * explicit `process.exit()`, await `client.flush()` in your application's - * shutdown hook before exiting. - * - * @defaultValue `true` + * Flush on natural process exit (beforeExit), without installing signal handlers. + * For signals or process.exit(), await client.flush() in the application hook. */ flushOnExit?: boolean; }; - export type CacheStrategy = "periodically-update" | "in-request"; - export type FlagsSyncMode = "polling" | "in-request" | "push"; - -/** - * Defines the options for the SDK client. - * - **/ export type ClientOptions = { - /** - * The secret key used to authenticate with the Reflag API. - **/ secretKey?: string; - - /** - * @deprecated - * Use `apiBaseUrl` instead. - **/ + /** @deprecated Use apiBaseUrl. */ host?: string; - - /** - * The host to send requests to (optional). - **/ apiBaseUrl?: string; - - /** - * The logger to use for logging (optional). Default is info level logging to console. - **/ logger?: Logger; - - /** - * Use the console logger, but set a log level. Ineffective if a custom logger is provided. - **/ logLevel?: LogLevel; - - /** - * The features to "enable" as fallbacks when the API is unavailable (optional). - * Can be an array of feature keys, or a record of feature keys and boolean or object values. - * - * If a record is supplied instead of array, the values of each key are either the - * configuration values or the boolean value `true`. - * - * @deprecated Use `flagsFallbackProvider` instead. - **/ - fallbackFlags?: - | TypedFlagKey[] - | Record>; - - /** - * Optional provider used to load and save raw flag definitions for fallback startup. - * Ignored in offline mode. - */ + /** Value-only startup fallbacks. Prefer a complete saved collection. */ + fallbackFlags?: TypedFlagKey[] | FlagOverrides; flagsFallbackProvider?: FlagsFallbackProvider; - - /** - * The HTTP client to use for sending requests (optional). Default is the built-in fetch client. - **/ httpClient?: HttpClient; - - /** - * The timeout in milliseconds for fetching feature targeting data (optional). - * Default is 10000 ms. - **/ fetchTimeoutMs?: number; - - /** - * Number of times to retry fetching feature definitions (optional). - * Default is 3 times. - **/ flagsFetchRetries?: number; - - /** - * The options for the batch buffer (optional). - * If not provided, the default options are used. - **/ batchOptions?: Omit, "flushHandler" | "logger">; - - /** - * Local flag overrides for testing or development. - * - * If a function is specified, the function will be called with the context - * and should return a record of flag keys and boolean or object values. - **/ - flagOverrides?: FlagOverrides | ((context: Context) => FlagOverrides); - - /** - * In offline mode, no data is sent or fetched from the the Reflag API, - * and `flagsFallbackProvider` is not used. - * This is useful for testing or development. - */ + /** Applied after evaluation; overrides do not change dependency results. */ + flagOverrides?: FlagOverrides | FlagOverridesFn; offline?: boolean; - - /** - * Deprecated: evaluation events are no longer emitted. - * - * @deprecated This option has no effect and will be removed in the next major version. - */ + /** @deprecated Evaluation events are not emitted. */ emitEvaluationEvents?: boolean; - - /** - * The path to the config file. If supplied, the config file will be loaded. - * Defaults to `reflag.config.json` when NODE_ENV is not production. Can also be - * set through the environment variable REFLAG_CONFIG_FILE. - */ configFile?: string; - - /** - * How flag definitions are synchronized. - * - * - `push` (default): live updates over SSE keep flag definitions up to date. - * - `polling`: periodic background refresh. - * - `in-request`: stale refresh is triggered during request handling. - */ flagsSyncMode?: FlagsSyncMode; - - /** - * Push endpoint used when `flagsSyncMode` is `"push"`. - * - * @defaultValue `"https://front.reflag.com/sse/server"` - */ flagsPushUrl?: string; - - /** - * @deprecated Use `flagsSyncMode`. - **/ + /** @deprecated Use flagsSyncMode. */ cacheStrategy?: CacheStrategy; }; - -/** - * Defines the options for tracking of entities. - * - **/ -export type TrackOptions = { - /** - * The attributes associated with the event. - **/ - attributes?: Attributes; - - /** - * The meta context associated with the event. - **/ - meta?: TrackingMeta; -}; - -/** - * Describes the current user context, company context, and other context. - * This is used to determine if feature targeting matches and to track events. - **/ +export type TrackOptions = { attributes?: Attributes; meta?: TrackingMeta }; export type Context = { - /** - * The user context. If no `id` key is set, the whole object is ignored. - */ user?: { - /** - * The identifier of the user. - */ - id: string | number | undefined; - - /** - * The name of the user. - */ - name?: string | undefined; - - /** - * The email of the user. - */ - email?: string | undefined; - - /** - * The avatar URL of the user. - */ - avatar?: string | undefined; - - /** - * Custom attributes of the user. - */ - [k: string]: any; + id: IdType | undefined; + name?: string; + email?: string; + avatar?: string; + [key: string]: any; }; - /** - * The company context. If no `id` key is set, the whole object is ignored. - */ company?: { - /** - * The identifier of the company. - */ - id: string | number | undefined; - - /** - * The name of the company. - */ - name?: string | undefined; - - /** - * The avatar URL of the company. - */ - avatar?: string | undefined; - - /** - * Custom attributes of the company. - */ - [k: string]: any; + id: IdType | undefined; + name?: string; + avatar?: string; + [key: string]: any; }; - - /** - * The other context. This is used for any additional context that is not related to user or company. - */ other?: Record; }; - -/** - * A context with tracking option. - **/ export interface ContextWithTracking extends Context { - /** - * Enable tracking for the context. - * If set to `false`, tracking will be disabled for the context. Default is `true`. - */ enableTracking?: boolean; - - /** - * The meta context used to update the user or company when syncing is required during - * feature retrieval. - */ meta?: TrackingMeta; } - export const LOG_LEVELS = ["DEBUG", "INFO", "WARN", "ERROR"] as const; export type LogLevel = (typeof LOG_LEVELS)[number]; - -export type IdType = string | number; diff --git a/packages/node-sdk/test/client-sync.test.ts b/packages/node-sdk/test/client-sync.test.ts new file mode 100644 index 000000000..58a45ec8d --- /dev/null +++ b/packages/node-sdk/test/client-sync.test.ts @@ -0,0 +1,153 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { ReflagClient, type ClientOptions, type HttpClient } from "../src"; +import { FLAGS_REFETCH_MS } from "../src/config"; +import { graph } from "./fixtures"; + +const sse = vi.hoisted(() => ({ open: vi.fn(), close: vi.fn() })); +vi.mock("../src/flag-updates-sse", () => ({ openFlagUpdatesSSE: sse.open })); +vi.mock("../src/flusher", () => ({ subscribe: vi.fn() })); +const clients: ReflagClient[] = []; +function harness(options: ClientOptions = {}) { + const state = { response: graph() }; + const get = vi.fn( + async ( + _url: string, + _headers: Record, + _timeout: number, + ) => ({ + ok: true, + status: 200, + body: { success: true, ...state.response }, + }), + ); + const logger = { + debug: vi.fn(), + info: vi.fn(), + warn: vi.fn(), + error: vi.fn(), + }; + const client = new ReflagClient({ + offline: false, + secretKey: "validSecretKeyWithMoreThan22Chars", + flagsFetchRetries: 0, + flagsPushUrl: "https://sse.example.com/server?channels=not-authoritative", + apiBaseUrl: "https://api.example.com/", + httpClient: { get, post: vi.fn() } as unknown as HttpClient, + logger, + batchOptions: { intervalMs: 1e9, flushOnExit: false }, + ...options, + }); + clients.push(client); + return { client, state, get }; +} +beforeEach(() => { + vi.useFakeTimers(); + sse.open.mockReset(); + sse.close.mockReset(); + sse.open.mockImplementation(() => ({ + ready: Promise.resolve(), + close: sse.close, + })); +}); +afterEach(() => { + clients.splice(0).forEach((client) => client.destroy()); + vi.useRealTimers(); +}); + +describe("collection sync wiring", () => { + it("uses authenticated push by default and refreshes the complete graph for a notified version", async () => { + const h = harness(); + await h.client.initialize(); + expect(sse.open).toHaveBeenCalledWith( + expect.objectContaining({ + url: "https://sse.example.com/server", + headers: expect.objectContaining({ + Authorization: "Bearer validSecretKeyWithMoreThan22Chars", + }), + }), + ); + h.state.response.flagStateVersion = 2; + h.state.response.segments[0].filter = { type: "constant", value: false }; + await vi.advanceTimersByTimeAsync(1001); + sse.open.mock.calls[0][0].onFlagStateVersion(2); + await h.client.flush(); + expect(h.get).toHaveBeenLastCalledWith( + "https://api.example.com/flags?waitForVersion=2", + expect.anything(), + expect.any(Number), + ); + expect( + h.client.getFlags({ + company: { id: "acme", plan: "enterprise" }, + enableTracking: false, + }), + ).toEqual({ model: "quick", dependent: false }); + h.client.destroy(); + expect(sse.close).toHaveBeenCalledOnce(); + }); + it("polls complete snapshots without opening SSE", async () => { + const h = harness({ flagsSyncMode: "polling" }); + await h.client.initialize(); + h.state.response = { + ...graph(), + flags: [], + segments: [], + flagStateVersion: 2, + }; + await vi.advanceTimersByTimeAsync(FLAGS_REFETCH_MS); + await h.client.flush(); + expect(h.get).toHaveBeenCalledTimes(2); + expect(sse.open).not.toHaveBeenCalled(); + expect(h.client.getFlagDefinitions()).toEqual({ flags: [], segments: [] }); + }); + it("refreshes stale state on access in request-driven mode", async () => { + const h = harness({ flagsSyncMode: "in-request" }); + await h.client.initialize(); + h.state.response = { + ...graph(), + flags: [], + segments: [], + flagStateVersion: 2, + }; + await vi.advanceTimersByTimeAsync(FLAGS_REFETCH_MS + 1); + h.client.getFlags({ enableTracking: false }); + await h.client.flush(); + expect(h.get).toHaveBeenCalledTimes(2); + expect(sse.open).not.toHaveBeenCalled(); + expect(h.client.getFlags({ enableTracking: false })).toEqual({}); + }); + it.each(["periodically-update", "in-request"] as const)( + "preserves deprecated cache strategy %s", + async (cacheStrategy) => { + const h = harness({ cacheStrategy }); + await h.client.initialize(); + expect(sse.open).not.toHaveBeenCalled(); + }, + ); +}); + +describe("v2 option validation", () => { + it.each([ + { flagsFetchRetries: -1 }, + { fetchTimeoutMs: 1.5 }, + { flagsSyncMode: "invalid" }, + { flagsPushUrl: "" }, + { flagsPushUrl: "not a URL" }, + { secretKey: 123 }, + { flagOverrides: { flag: undefined } }, + { flagOverrides: null }, + { fallbackFlags: { flag: NaN } }, + { flagsFallbackProvider: { load: () => undefined } }, + { logger: "not a logger" }, + { httpClient: false }, + ])("rejects invalid options %#", (options) => { + expect( + () => + new ReflagClient({ + offline: true, + ...options, + } as unknown as ClientOptions), + ).toThrow(); + }); +}); diff --git a/packages/node-sdk/test/client.test.ts b/packages/node-sdk/test/client.test.ts index 02b0fe490..025a5c2e2 100644 --- a/packages/node-sdk/test/client.test.ts +++ b/packages/node-sdk/test/client.test.ts @@ -1,3776 +1,1071 @@ -import { mkdtempSync, rmSync, writeFileSync } from "fs"; -import os from "os"; -import path from "path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import flushPromises from "flush-promises"; import { - afterEach, - beforeAll, - beforeEach, - describe, - expect, - it, - test, - vi, -} from "vitest"; - -import { BoundReflagClient, fallbackProviders, ReflagClient } from "../src"; -import { - API_BASE_URL, - API_TIMEOUT_MS, - BATCH_INTERVAL_MS, - BATCH_MAX_SIZE, - FLAG_EVENT_RATE_LIMITER_WINDOW_SIZE_MS, - FLAGS_REFETCH_MS, - SDK_VERSION, - SDK_VERSION_HEADER_NAME, -} from "../src/config"; -import fetchClient from "../src/fetch-http-client"; -import { subscribe as triggerOnExit } from "../src/flusher"; -import { newRateLimiter } from "../src/rate-limiter"; -import { - ClientOptions, - Context, - FlagsAPIResponse, - FlagsFallbackProvider, -} from "../src/types"; - -const BULK_ENDPOINT = "https://api.example.com/bulk"; - -const missingContextFieldError = (field: string) => ({ - code: "MISSING_CONTEXT_FIELD", - field, - message: `Context field "${field}" is required to evaluate targeting rules.`, -}); - -const clientNotInitializedError = { - code: "CLIENT_NOT_INITIALIZED", - field: "", - message: - "ReflagClient was not initialized before this flag was evaluated. Call initialize() before evaluating flags.", -}; - -vi.mock("../src/rate-limiter", async (importOriginal) => { - const original = (await importOriginal()) as any; - - return { - ...original, - newRateLimiter: vi.fn(original.newRateLimiter), - }; -}); - -vi.mock("../src/flusher", () => ({ - subscribe: vi.fn(), -})); - -// Mock NextJS headers module for dynamic import -vi.mock("next/headers", () => ({ - cookies: vi.fn(), -})); - -const user = { - id: "user123", - age: 1, - name: "John", -}; - -const company = { - id: "company123", - employees: 100, - name: "Acme Inc.", -}; - -const event = { - event: "flag-event", - attrs: { key: "value" }, -}; - -const otherContext = { custom: "context", key: "value" }; -const logger = { - debug: vi.fn(), - info: vi.fn(), - warn: vi.fn(), - error: vi.fn(), -}; -const httpClient = { post: vi.fn(), get: vi.fn() }; - -const fallbackFlags = ["key"]; - -const validOptions: ClientOptions = { - secretKey: "validSecretKeyWithMoreThan22Chars", - apiBaseUrl: "https://api.example.com/", - logger, - httpClient, - fallbackFlags, - flagsFetchRetries: 2, - batchOptions: { - maxSize: 99, - intervalMs: 10001, - flushOnExit: false, - }, - flagsSyncMode: "polling", - offline: false, -}; - -const expectedHeaders = { - [SDK_VERSION_HEADER_NAME]: SDK_VERSION, - "Content-Type": "application/json", - Authorization: `Bearer ${validOptions.secretKey}`, -}; - -function createSSEMessageStream(data: object) { - const encoder = new TextEncoder(); - return new ReadableStream({ - start(controller) { - controller.enqueue( - encoder.encode(`event: message\ndata: ${JSON.stringify(data)}\n\n`), - ); - }, - }); -} - -function createFailingSSEStream(error = new Error("stream failed")) { - return new ReadableStream({ - start(controller) { - controller.error(error); - }, - }); -} - -function createIdleSSEStream() { - return new ReadableStream({ - start() { - // keep the stream open without sending messages - }, - }); -} - -const flagDefinitions: FlagsAPIResponse = { - flagStateVersion: 1, - features: [ - { - key: "flag1", - description: "Flag 1", - targeting: { - version: 1, - rules: [ - { - filter: { - type: "context" as const, - field: "company.id", - operator: "IS", - values: ["company123"], - }, - }, - ], - }, - config: { - version: 1, - variants: [ - { - filter: { - type: "context", - field: "company.id", - operator: "IS", - values: ["company123"], - }, - key: "config-1", - payload: { something: "else" }, - }, - ], - }, - }, - { - key: "flag2", - description: "Flag 2", - targeting: { - version: 2, - rules: [ - { - filter: { - type: "group" as const, - operator: "and", - filters: [ - { - type: "context" as const, - field: "company.id", - operator: "IS", - values: ["company123"], - }, - { - partialRolloutThreshold: 0.5, - partialRolloutAttribute: "attributeKey", - type: "rolloutPercentage" as const, - key: "flag2", - }, - ], - }, - }, - ], - }, - }, - ], -}; - -describe("ReflagClient", () => { - afterEach(() => { - vi.clearAllMocks(); - }); - - describe("constructor", () => { - it("should initialize with no options", async () => { - const secretKeyEnv = process.env.REFLAG_SECRET_KEY; - process.env.REFLAG_SECRET_KEY = "validSecretKeyWithMoreThan22Chars"; - try { - const reflagInstance = new ReflagClient(); - expect(reflagInstance).toBeInstanceOf(ReflagClient); - } finally { - process.env.REFLAG_SECRET_KEY = secretKeyEnv; - } - }); - - it("should accept fallback flags as an array", async () => { - const reflagInstance = new ReflagClient({ - secretKey: "validSecretKeyWithMoreThan22Chars", - fallbackFlags: ["flag1", "flag2"], - }); - - expect(reflagInstance["_config"].fallbackFlags).toEqual({ - flag1: { - isEnabled: true, - key: "flag1", - }, - flag2: { - isEnabled: true, - key: "flag2", - }, - }); - }); - - it("should accept fallback flags as an object", async () => { - const reflagInstance = new ReflagClient({ - secretKey: "validSecretKeyWithMoreThan22Chars", - fallbackFlags: { - flag1: true, - flag2: { - isEnabled: true, - config: { - key: "config1", - payload: { value: true }, - }, - }, - }, - }); - - expect(reflagInstance["_config"].fallbackFlags).toStrictEqual({ - flag1: { - key: "flag1", - config: undefined, - isEnabled: true, - }, - flag2: { - key: "flag2", - isEnabled: true, - config: { - key: "config1", - payload: { value: true }, - }, - }, - }); - }); - - it("should use the REFLAG_CONFIG_FILE path when set", () => { - const tempDir = mkdtempSync(path.join(os.tmpdir(), "reflag-node-sdk-")); - const originalConfigFile = process.env.REFLAG_CONFIG_FILE; - const customConfigFile = path.join(tempDir, "custom.reflag.config.json"); - - writeFileSync( - customConfigFile, - JSON.stringify({ apiBaseUrl: "https://custom-config.example/" }), - ); - - process.env.REFLAG_CONFIG_FILE = customConfigFile; - - try { - const client = new ReflagClient({ - offline: true, - }); - - expect(client["_config"].apiBaseUrl).toBe( - "https://custom-config.example/", - ); - } finally { - if (originalConfigFile === undefined) { - delete process.env.REFLAG_CONFIG_FILE; - } else { - process.env.REFLAG_CONFIG_FILE = originalConfigFile; - } - rmSync(tempDir, { recursive: true, force: true }); - } - }); - - it("should create a client instance with valid options", () => { - const client = new ReflagClient(validOptions); - - expect(client).toBeInstanceOf(ReflagClient); - expect(client["_config"].apiBaseUrl).toBe("https://api.example.com/"); - expect(client["_config"].refetchInterval).toBe(FLAGS_REFETCH_MS); - expect(client.logger).toBeDefined(); - expect(client.httpClient).toBe(validOptions.httpClient); - expect(client["_config"].headers).toEqual(expectedHeaders); - expect(client["batchBuffer"]).toMatchObject({ - maxSize: 99, - intervalMs: 10001, - }); - - expect(client["_config"].fallbackFlags).toEqual({ - key: { - key: "key", - isEnabled: true, - }, - }); - expect(client["_config"].flagsFetchRetries).toBe(2); - }); - - it("should route messages to the supplied logger", () => { - const client = new ReflagClient(validOptions); - - const actualLogger = client.logger!; - actualLogger.debug("debug message"); - actualLogger.info("info message"); - actualLogger.warn("warn message"); - actualLogger.error("error message"); - - expect(logger.debug).toHaveBeenCalledWith( - expect.stringMatching("debug message"), - ); - expect(logger.info).toHaveBeenCalledWith( - expect.stringMatching("info message"), - ); - expect(logger.warn).toHaveBeenCalledWith( - expect.stringMatching("warn message"), - ); - expect(logger.error).toHaveBeenCalledWith( - expect.stringMatching("error message"), - ); - }); - - it("should create a client instance with default values for optional fields", () => { - const client = new ReflagClient({ - secretKey: "validSecretKeyWithMoreThan22Chars", - }); - - expect(client["_config"].apiBaseUrl).toBe(API_BASE_URL); - expect(client["_config"].refetchInterval).toBe(FLAGS_REFETCH_MS); - expect(client["_config"].flagsSyncMode).toBe("push"); - expect(client["_config"].flagsPushUrl).toBe( - "https://front.reflag.com/sse/server", - ); - expect(client.httpClient).toBe(fetchClient); - expect(client["_config"].headers).toEqual(expectedHeaders); - expect(client["_config"].fallbackFlags).toBeUndefined(); - expect(client["batchBuffer"]).toMatchObject({ - maxSize: BATCH_MAX_SIZE, - intervalMs: BATCH_INTERVAL_MS, - }); - }); - - it("should strip legacy channels from custom push URLs", () => { - const client = new ReflagClient({ - secretKey: "validSecretKeyWithMoreThan22Chars", - flagsPushUrl: "https://example.com/sse?channels=legacy&foo=bar", - }); - - expect(client["_config"].flagsPushUrl).toBe( - "https://example.com/sse?foo=bar", - ); - }); - - it("should map deprecated cacheStrategy values to sync modes", () => { - const inRequestClient = new ReflagClient({ - secretKey: "validSecretKeyWithMoreThan22Chars", - cacheStrategy: "in-request", - }); - const pollingClient = new ReflagClient({ - secretKey: "validSecretKeyWithMoreThan22Chars", - cacheStrategy: "periodically-update", - }); - - expect(inRequestClient["_config"].flagsSyncMode).toBe("in-request"); - expect(pollingClient["_config"].flagsSyncMode).toBe("polling"); - }); - - it("should throw an error if options are invalid", () => { - let invalidOptions: any = null; - expect(() => new ReflagClient(invalidOptions)).toThrow( - "options must be an object", - ); - - invalidOptions = { ...validOptions, secretKey: "shortKey" }; - expect(() => new ReflagClient(invalidOptions)).toThrow( - "invalid secretKey specified", - ); - - invalidOptions = { ...validOptions, host: 123 }; - expect(() => new ReflagClient(invalidOptions)).toThrow( - "host must be a string", - ); - - invalidOptions = { - ...validOptions, - logger: "invalidLogger" as any, - }; - expect(() => new ReflagClient(invalidOptions)).toThrow( - "logger must be an object", - ); - - invalidOptions = { - ...validOptions, - httpClient: "invalidHttpClient" as any, - }; - expect(() => new ReflagClient(invalidOptions)).toThrow( - "httpClient must be an object", - ); - - invalidOptions = { - ...validOptions, - batchOptions: "invalid" as any, - }; - expect(() => new ReflagClient(invalidOptions)).toThrow( - "batchOptions must be an object", - ); - - invalidOptions = { - ...validOptions, - fallbackFlags: "invalid" as any, - }; - expect(() => new ReflagClient(invalidOptions)).toThrow( - "fallbackFlags must be an array or object", - ); - - invalidOptions = { - ...validOptions, - flagsFallbackProvider: {} as any, - }; - expect(() => new ReflagClient(invalidOptions)).toThrow( - "flagsFallbackProvider must be an object with load/save functions", - ); - }); - - it("should create a new flag events rate-limiter", () => { - const client = new ReflagClient(validOptions); - - expect(client["rateLimiter"]).toBeDefined(); - expect(newRateLimiter).toHaveBeenCalledWith( - FLAG_EVENT_RATE_LIMITER_WINDOW_SIZE_MS, - ); - }); - - it("should not register an exit flush handler if `batchOptions.flushOnExit` is false", () => { - new ReflagClient({ - ...validOptions, - batchOptions: { ...validOptions.batchOptions, flushOnExit: false }, - }); - - expect(triggerOnExit).not.toHaveBeenCalled(); - }); - - it("should not register an exit flush handler if `offline` is true", () => { - new ReflagClient({ - ...validOptions, - offline: true, - }); - - expect(triggerOnExit).not.toHaveBeenCalled(); - }); - - it.each([undefined, true])( - "should register an exit flush handler if `batchOptions.flushOnExit` is `%s`", - (flushOnExit) => { - new ReflagClient({ - ...validOptions, - batchOptions: { ...validOptions.batchOptions, flushOnExit }, - }); - - expect(triggerOnExit).toHaveBeenCalledWith(expect.any(Function)); - }, - ); - - it.each([ - ["https://api.example.com", "https://api.example.com/bulk"], - ["https://api.example.com/", "https://api.example.com/bulk"], - ["https://api.example.com/path", "https://api.example.com/path/bulk"], - ["https://api.example.com/path/", "https://api.example.com/path/bulk"], - ])( - "should build the URLs correctly %s -> %s", - async (apiBaseUrl, expectedUrl) => { - const client = new ReflagClient({ - ...validOptions, - apiBaseUrl, - }); - - await client.updateUser("user_id"); - await client.flush(); - - expect(httpClient.post).toHaveBeenCalledWith( - expectedUrl, - expect.any(Object), - expect.any(Object), - ); - }, - ); - }); - - describe("bindClient", () => { - const client = new ReflagClient(validOptions); - const context = { - user, - company, - other: otherContext, - }; - - beforeEach(() => { - vi.mocked(httpClient.post).mockResolvedValue({ body: { success: true } }); - client["rateLimiter"].clearStale(true); - }); - - it("should return a new client instance with the `user`, `company` and `other` set", async () => { - const newClient = client.bindClient(context); - await client.flush(); - - expect(newClient.user).toEqual(user); - expect(newClient.company).toEqual(company); - expect(newClient.otherContext).toEqual(otherContext); - - expect(newClient).toBeInstanceOf(BoundReflagClient); - expect(newClient).not.toBe(client); // Ensure a new instance is returned - expect(newClient["_options"]).toEqual({ - enableTracking: true, - ...context, - }); - }); - - it("should update user in Reflag when called", async () => { - client.bindClient({ user: context.user }); - await client.flush(); - - const { id: _, ...attributes } = context.user; - - expect(httpClient.post).toHaveBeenCalledWith( - BULK_ENDPOINT, - expectedHeaders, - [ - { - type: "user", - userId: user.id, - attributes: attributes, - context: undefined, - }, - ], - ); - - expect(httpClient.post).toHaveBeenCalledOnce(); - }); - - it("should update company in Reflag when called", async () => { - client.bindClient({ company: context.company, meta: { active: true } }); - await client.flush(); - - const { id: _, ...attributes } = context.company; - - expect(httpClient.post).toHaveBeenCalledWith( - BULK_ENDPOINT, - expectedHeaders, - [ - { - type: "company", - companyId: company.id, - attributes: attributes, - context: { - active: true, - }, - }, - ], - ); - - expect(httpClient.post).toHaveBeenCalledOnce(); - }); - - it("should not update `company` or `user` in Reflag when `enableTracking` is `false`", async () => { - client.bindClient({ - user: context.user, - company: context.company, - enableTracking: false, - }); - - await client.flush(); - - expect(httpClient.post).not.toHaveBeenCalled(); - }); - - it("should throw an error if `user` is invalid", () => { - expect(() => - client.bindClient({ user: "bad_attributes" as any }), - ).toThrow("validation failed: user must be an object if given"); - expect(() => client.bindClient({ user: { id: {} as any } })).toThrow( - "validation failed: user.id must be a string or number if given", - ); - }); - - it("should throw an error if `company` is invalid", () => { - expect(() => - client.bindClient({ company: "bad_attributes" as any }), - ).toThrow("validation failed: company must be an object if given"); - expect(() => client.bindClient({ company: { id: {} as any } })).toThrow( - "validation failed: company.id must be a string or number if given", - ); - }); - - it("should throw an error if `other` is invalid", () => { - expect(() => - client.bindClient({ other: "bad_attributes" as any }), - ).toThrow("validation failed: other must be an object"); - }); - - it("should throw an error if `enableTracking` is invalid", () => { - expect(() => - client.bindClient({ enableTracking: "bad_attributes" as any }), - ).toThrow("validation failed: enableTracking must be a boolean"); - }); - - it("should allow context without id", () => { - const c = client.bindClient({ - user: { id: undefined, name: "userName" }, - company: { id: undefined, name: "companyName" }, - }); - expect(c.user?.id).toBeUndefined(); - expect(c.company?.id).toBeUndefined(); - }); - }); - - describe("updateUser", () => { - const client = new ReflagClient(validOptions); - - beforeEach(() => { - client["rateLimiter"].clearStale(true); - }); - - // try with both string and number IDs - test.each([ - { id: "user123", age: 1, name: "John" }, - { id: 42, age: 1, name: "John" }, - ])("should successfully update the user", async (testUser) => { - const response = { status: 200, body: { success: true } }; - httpClient.post.mockResolvedValue(response); - - await client.updateUser(testUser.id, { - attributes: { age: 2, brave: false }, - meta: { - active: true, - }, - }); - - await client.flush(); - - expect(httpClient.post).toHaveBeenCalledWith( - BULK_ENDPOINT, - expectedHeaders, - [ - { - type: "user", - userId: testUser.id, - attributes: { age: 2, brave: false }, - context: { active: true }, - }, - ], - ); - - expect(logger.debug).toHaveBeenCalledWith( - expect.stringMatching("post request to "), - response, - ); - }); - - it("should log an error if the post request throws", async () => { - const error = new Error("Network error"); - httpClient.post.mockRejectedValue(error); - - await client.updateUser(user.id); - await client.flush(); - - expect(logger.warn).toHaveBeenCalledWith( - "flush of buffered items failed; discarding items", - expect.objectContaining({ - count: 1, - error: expect.objectContaining({ - message: "failed to send bulk events", - }), - }), - ); - }); - - it("should log if API call returns false", async () => { - const response = { status: 200, body: { success: false } }; - - httpClient.post.mockResolvedValue(response); - - await client.updateUser(user.id); - await client.flush(); - - expect(logger.warn).toHaveBeenCalledWith( - "flush of buffered items failed; discarding items", - expect.objectContaining({ - count: 1, - error: expect.objectContaining({ - message: "failed to send bulk events", - }), - }), - ); - expect(logger.error).not.toHaveBeenCalled(); - }); - - it("should throw an error if opts are not valid or the user is not set", async () => { - await expect( - client.updateUser(user.id, "bad_opts" as any), - ).rejects.toThrow("validation failed: options must be an object"); - - await expect( - client.updateUser(user.id, { attributes: "bad_attributes" as any }), - ).rejects.toThrow("attributes must be an object"); - - await expect( - client.updateUser(user.id, { meta: "bad_meta" as any }), - ).rejects.toThrow("meta must be an object"); - }); - }); - - describe("updateCompany", () => { - const client = new ReflagClient(validOptions); - - beforeEach(() => { - client["rateLimiter"].clearStale(true); - }); - - test.each([ - { - id: "company123", - employees: 100, - name: "Acme Inc.", - userId: "user123", - }, - { id: 42, employees: 100, name: "Acme Inc.", userId: 42 }, - ])(`should successfully update the company`, async (testCompany) => { - const response = { status: 200, body: { success: true } }; - httpClient.post.mockResolvedValue(response); - - await client.updateCompany(testCompany.id, { - attributes: { employees: 200, bankrupt: false }, - meta: { active: true }, - userId: testCompany.userId, - }); - - await client.flush(); - - expect(httpClient.post).toHaveBeenCalledWith( - BULK_ENDPOINT, - expectedHeaders, - [ - { - type: "company", - companyId: testCompany.id, - attributes: { employees: 200, bankrupt: false }, - context: { active: true }, - userId: testCompany.userId, - }, - ], - ); - - expect(logger.debug).toHaveBeenCalledWith( - expect.stringMatching("post request to .*"), - response, - ); - }); - - it("should log an error if the post request throws", async () => { - const error = new Error("Network error"); - httpClient.post.mockRejectedValue(error); - - await client.updateCompany(company.id, {}); - await client.flush(); - - expect(logger.warn).toHaveBeenCalledWith( - "flush of buffered items failed; discarding items", - expect.objectContaining({ - count: 1, - error: expect.objectContaining({ - message: "failed to send bulk events", - }), - }), - ); - }); - - it("should log an error if API responds with success: false", async () => { - const response = { - status: 200, - body: { success: false }, - }; - - httpClient.post.mockResolvedValue(response); - - await client.updateCompany(company.id, {}); - await client.flush(); - - expect(logger.warn).toHaveBeenCalledWith( - "flush of buffered items failed; discarding items", - expect.objectContaining({ - count: 1, - error: expect.objectContaining({ - message: "failed to send bulk events", - }), - }), - ); - expect(logger.error).not.toHaveBeenCalled(); - }); - - it("should throw an error if company is not valid", async () => { - await expect( - client.updateCompany(company.id, "bad_opts" as any), - ).rejects.toThrow("validation failed: options must be an object"); - - await expect( - client.updateCompany(company.id, { - attributes: "bad_attributes" as any, - }), - ).rejects.toThrow("attributes must be an object"); - - await expect( - client.updateCompany(company.id, { meta: "bad_meta" as any }), - ).rejects.toThrow("meta must be an object"); - }); - }); - - describe("track", () => { - const client = new ReflagClient(validOptions); - - beforeEach(() => { - client["rateLimiter"].clearStale(true); - }); - - test.each([ - { id: "user123", age: 1, name: "John" }, - { id: 42, age: 1, name: "John" }, - ])("should successfully track the flag usage", async (testUser) => { - const response = { - status: 200, - body: { success: true }, - }; - httpClient.post.mockResolvedValue(response); - - await client.bindClient({ user: testUser, company }).track(event.event, { - attributes: event.attrs, - meta: { active: true }, - }); - - await client.flush(); - expect(httpClient.post).toHaveBeenCalledWith( - BULK_ENDPOINT, - expectedHeaders, - [ - expect.objectContaining({ - type: "company", - }), - expect.objectContaining({ - type: "user", - }), - { - attributes: { - key: "value", - }, - context: { - active: true, - }, - event: "flag-event", - type: "event", - userId: testUser.id, - companyId: company.id, - }, - ], - ); - - expect(logger.debug).toHaveBeenCalledWith( - expect.stringMatching("post request to"), - response, - ); - }); - - it("should successfully track the flag usage including user and company", async () => { - httpClient.post.mockResolvedValue({ - status: 200, - body: { success: true }, - }); - - await client.bindClient({ user }).track(event.event, { - companyId: "otherCompanyId", - attributes: event.attrs, - meta: { active: true }, - }); - - await client.flush(); - expect(httpClient.post).toHaveBeenCalledWith( - BULK_ENDPOINT, - expectedHeaders, - [ - expect.objectContaining({ - type: "user", - }), - { - attributes: { - key: "value", - }, - context: { - active: true, - }, - event: "flag-event", - companyId: "otherCompanyId", - type: "event", - userId: "user123", - }, - ], - ); - }); - - it("should log an error if the post request fails", async () => { - const error = new Error("Network error"); - httpClient.post.mockRejectedValue(error); - - await client.bindClient({ user }).track(event.event); - await client.flush(); - - expect(logger.warn).toHaveBeenCalledWith( - "flush of buffered items failed; discarding items", - expect.objectContaining({ - count: 2, - error: expect.objectContaining({ - message: "failed to send bulk events", - }), - }), - ); - }); - - it("should log if the API call returns false", async () => { - const response = { - status: 200, - body: { success: false }, - }; - - httpClient.post.mockResolvedValue(response); - - await client.bindClient({ user }).track(event.event); - await client.flush(); - - expect(logger.warn).toHaveBeenCalledWith( - "flush of buffered items failed; discarding items", - expect.objectContaining({ - count: 2, - error: expect.objectContaining({ - message: "failed to send bulk events", - }), - }), - ); - expect(logger.error).not.toHaveBeenCalled(); - }); - - it("should log if user is not set", async () => { - const boundClient = client.bindClient({ company }); - - await boundClient.track("hello"); - - expect(httpClient.post).not.toHaveBeenCalled(); - expect(logger.warn).toHaveBeenCalledWith( - expect.stringMatching("no user set, cannot track event"), - ); - }); - - it("should throw an error if event is invalid", async () => { - const boundClient = client.bindClient({ company, user }); - - await expect(boundClient.track(undefined as any)).rejects.toThrow( - "event must be a string", - ); - await expect(boundClient.track(1 as any)).rejects.toThrow( - "event must be a string", - ); - - await expect( - boundClient.track(event.event, "bad_opts" as any), - ).rejects.toThrow("validation failed: options must be an object"); - - await expect( - boundClient.track(event.event, { - attributes: "bad_attributes" as any, - }), - ).rejects.toThrow("attributes must be an object"); - - await expect( - boundClient.track(event.event, { meta: "bad_meta" as any }), - ).rejects.toThrow("meta must be an object"); - }); - }); - - describe("user", () => { - it("should return the undefined if user was not set", () => { - const client = new ReflagClient(validOptions).bindClient({ company }); - expect(client.user).toBeUndefined(); - }); - - it("should return the user if user was associated", () => { - const client = new ReflagClient(validOptions).bindClient({ user }); - - expect(client.user).toEqual(user); - }); - }); - - describe("company", () => { - it("should return the undefined if company was not set", () => { - const client = new ReflagClient(validOptions).bindClient({ user }); - expect(client.company).toBeUndefined(); - }); - - it("should return the user if company was associated", () => { - const client = new ReflagClient(validOptions).bindClient({ company }); - - expect(client.company).toEqual(company); - }); - }); - - describe("otherContext", () => { - it("should return the undefined if custom context was not set", () => { - const client = new ReflagClient(validOptions).bindClient({ company }); - expect(client.otherContext).toBeUndefined(); - }); - - it("should return the user if custom context was associated", () => { - const client = new ReflagClient(validOptions).bindClient({ - other: otherContext, - }); - - expect(client.otherContext).toEqual(otherContext); - }); - }); - - describe("initialize", () => { - it("should initialize the client", async () => { - const client = new ReflagClient(validOptions); - - const get = vi - .spyOn(client["flagsCache"], "get") - .mockReturnValue(undefined); - const refresh = vi - .spyOn(client["flagsCache"], "refresh") - .mockResolvedValue(undefined); - - await client.initialize(); - await client.initialize(); - await client.initialize(); - - expect(refresh).toHaveBeenCalledTimes(1); - expect(get).not.toHaveBeenCalled(); - }); - - it("should call the backend to obtain flags", async () => { - const client = new ReflagClient(validOptions); - - httpClient.get.mockResolvedValue({ - ok: true, - status: 200, - }); - - await client.initialize(); - - expect(httpClient.get).toHaveBeenCalledWith( - `https://api.example.com/features`, - expectedHeaders, - API_TIMEOUT_MS, - ); - }); - - it("should refresh features with waitForVersion when receiving push updates", async () => { - const fetchMock = vi.spyOn(global, "fetch").mockResolvedValue( - new Response( - createSSEMessageStream({ - id: "flags-state:test:0", - timestamp: 1774605839478, - name: "flags-updated", - clientId: "reflag-backend", - channel: "flags-state:test", - action: 0, - encoding: "json", - data: JSON.stringify({ - envId: "endbMeqfmcgLyZ", - flagStateVersion: 22, - }), - }), - { - status: 200, - headers: { - "Content-Type": "text/event-stream", - }, - }, - ), - ); - - try { - httpClient.get.mockResolvedValue({ - ok: true, - status: 200, - body: { - success: true, - ...flagDefinitions, - }, - }); - - const client = new ReflagClient({ - ...validOptions, - flagsSyncMode: "push", - }); - - await client.initialize(); - - await vi.waitFor(() => { - expect(httpClient.get).toHaveBeenCalledWith( - "https://api.example.com/features?waitForVersion=22", - expectedHeaders, - API_TIMEOUT_MS, - ); - }); - - const [calledUrl, calledInit] = fetchMock.mock.calls[0] ?? []; - const url = new URL(String(calledUrl)); - expect(url.origin).toBe("https://front.reflag.com"); - expect(url.pathname).toBe("/sse/server"); - expect(url.searchParams.has("channels")).toBe(false); - expect(calledInit).toMatchObject({ - method: "GET", - headers: { - ...expectedHeaders, - Accept: "text/event-stream", - "Cache-Control": "no-cache", - }, - }); - expect(calledInit?.body).toBeUndefined(); - expect(calledInit?.signal).toBeDefined(); - - client.destroy(); - } finally { - fetchMock.mockRestore(); - } - }); - - it("should refresh features after push reconnects", async () => { - const fetchMock = vi - .spyOn(global, "fetch") - .mockResolvedValueOnce( - new Response(createFailingSSEStream(), { - status: 200, - headers: { - "Content-Type": "text/event-stream", - }, - }), - ) - .mockResolvedValueOnce( - new Response(createIdleSSEStream(), { - status: 200, - headers: { - "Content-Type": "text/event-stream", - }, - }), - ); - - vi.useFakeTimers(); - try { - httpClient.get - .mockResolvedValueOnce({ - ok: true, - status: 200, - body: { - success: true, - ...flagDefinitions, - }, - etag: 'W/"flags-v1"', - }) - .mockResolvedValue({ ok: false, status: 304, body: undefined }); - - const client = new ReflagClient({ - ...validOptions, - flagsSyncMode: "push", - }); - - await client.initialize(); - await vi.runOnlyPendingTimersAsync(); - - await vi.waitFor(() => { - expect(httpClient.get).toHaveBeenCalledTimes(2); - }); - - expect(httpClient.get).toHaveBeenNthCalledWith( - 2, - "https://api.example.com/features", - { ...expectedHeaders, "If-None-Match": 'W/"flags-v1"' }, - API_TIMEOUT_MS, - ); - - client.destroy(); - } finally { - vi.useRealTimers(); - fetchMock.mockRestore(); - } - }); - - it("should load flag definitions from flagsFallbackProvider when live fetch fails", async () => { - const savedAt = "2026-03-09T00:00:00.000Z"; - const flagsFallbackProvider: FlagsFallbackProvider = { - load: vi.fn().mockResolvedValue({ - version: 1, - savedAt, - flags: flagDefinitions.features, - }), - save: vi.fn(), - }; - - httpClient.get.mockResolvedValue({ success: false }); - - const client = new ReflagClient({ - ...validOptions, - flagsFallbackProvider, - flagsFetchRetries: 0, - }); - - vi.useFakeTimers(); - vi.setSystemTime(new Date("2026-03-09T00:20:00.000Z")); - try { - await client.initialize(); - - expect(flagsFallbackProvider.load).toHaveBeenCalledWith( - expect.objectContaining({ - secretKeyHash: expect.any(String), - }), - ); - expect(logger.warn).toHaveBeenCalledTimes(1); - expect(logger.warn).toHaveBeenCalledWith( - `remote flags unavailable, using fallback flags fetched 20m ago (${savedAt})`, - ); - - expect( - client.getFlag({ company, user, other: otherContext }, "flag1"), - ).toStrictEqual({ - key: "flag1", - isEnabled: true, - config: { - key: "config-1", - payload: { something: "else" }, - }, - track: expect.any(Function), - }); - } finally { - vi.useRealTimers(); - } - }); - - it("should load static fallback flag definitions when live fetch fails", async () => { - httpClient.get.mockResolvedValue({ success: false }); - - const client = new ReflagClient({ - ...validOptions, - flagsFallbackProvider: fallbackProviders.static({ - flags: { - huddle: true, - "smart-summaries": false, - }, - }), - flagsFetchRetries: 0, - }); - - await client.initialize(); - - expect(client.getFlag({}, "huddle")).toStrictEqual({ - key: "huddle", - isEnabled: true, - config: { - key: undefined, - payload: undefined, - }, - track: expect.any(Function), - }); - expect(client.getFlag({}, "smart-summaries")).toStrictEqual({ - key: "smart-summaries", - isEnabled: false, - config: { - key: undefined, - payload: undefined, - }, - track: expect.any(Function), - }); - }); - - it("should log remote flag fetch failures at debug level when using fallback definitions", async () => { - const error = new Error("fetch failed"); - const savedAt = "2026-03-09T00:00:00.000Z"; - const flagsFallbackProvider: FlagsFallbackProvider = { - load: vi.fn().mockResolvedValue({ - version: 1, - savedAt, - flags: flagDefinitions.features, - }), - save: vi.fn(), - }; - - httpClient.get.mockRejectedValue(error); - - const client = new ReflagClient({ - ...validOptions, - flagsFallbackProvider, - flagsFetchRetries: 0, - }); - - vi.useFakeTimers(); - vi.setSystemTime(new Date("2026-03-09T00:20:00.000Z")); - try { - await client.initialize(); - - expect(logger.debug).toHaveBeenCalledWith( - 'get request to "features" failed with error after 0 retries', - error, - ); - expect(logger.warn).toHaveBeenCalledWith( - `remote flags unavailable, using fallback flags fetched 20m ago (${savedAt})`, - ); - expect(logger.error).not.toHaveBeenCalled(); - } finally { - vi.useRealTimers(); - } - }); - - it("should include the cause when warning that flag fetch will retry", async () => { - const error = new Error("fetch failed"); - httpClient.get.mockRejectedValue(error); - - const client = new ReflagClient({ - ...validOptions, - flagsSyncMode: "in-request", - flagsFetchRetries: 1, - }); - - vi.useFakeTimers(); - try { - const initializePromise = client.initialize(); - await vi.runAllTimersAsync(); - await initializePromise; - - expect(logger.warn).toHaveBeenCalledWith( - "failed to fetch flags, will retry", - error, - ); - } finally { - vi.useRealTimers(); - } - }); - - it("should warn when live fetch fails and flagsFallbackProvider has no saved snapshot", async () => { - const flagsFallbackProvider: FlagsFallbackProvider = { - load: vi.fn().mockResolvedValue(undefined), - save: vi.fn(), - }; - - httpClient.get.mockResolvedValue({ success: false }); - - const client = new ReflagClient({ - ...validOptions, - flagsFallbackProvider, - flagsFetchRetries: 0, - }); - - await client.initialize(); - - expect(flagsFallbackProvider.load).toHaveBeenCalledWith( - expect.objectContaining({ - secretKeyHash: expect.any(String), - }), - ); - expect(logger.warn).toHaveBeenCalledWith( - "remote flags unavailable, no fallback flags found in flagsFallbackProvider", - ); - }); - - it("should save fetched flag definitions to flagsFallbackProvider", async () => { - const flagsFallbackProvider: FlagsFallbackProvider = { - load: vi.fn(), - save: vi.fn().mockResolvedValue(undefined), - }; - - httpClient.get.mockResolvedValue({ - ok: true, - status: 200, - body: { - success: true, - ...flagDefinitions, - }, - }); - - const client = new ReflagClient({ - ...validOptions, - flagsFallbackProvider, - }); - - await client.initialize(); - await flushPromises(); - - expect(flagsFallbackProvider.save).toHaveBeenCalledWith( - expect.objectContaining({ - secretKeyHash: expect.any(String), - }), - expect.objectContaining({ - version: 1, - flags: flagDefinitions.features, - savedAt: expect.any(String), - }), - ); - }); - - it("should not fail initialize when flagsFallbackProvider.save fails", async () => { - const error = new Error("save failed"); - const flagsFallbackProvider: FlagsFallbackProvider = { - load: vi.fn(), - save: vi.fn().mockRejectedValue(error), - }; - - httpClient.get.mockResolvedValue({ - ok: true, - status: 200, - body: { - success: true, - ...flagDefinitions, - }, - }); - - const client = new ReflagClient({ - ...validOptions, - flagsFallbackProvider, - }); - - await client.initialize(); - await flushPromises(); - - expect(logger.error).toHaveBeenCalledWith( - "flagsFallbackProvider: failed to save flag definitions", - error, - ); - }); - }); - - describe("flush", () => { - it("should flush all bulk data", async () => { - const client = new ReflagClient(validOptions); - - await client.updateUser(user.id, { attributes: { age: 2 } }); - await client.updateUser(user.id, { attributes: { age: 3 } }); - await client.updateUser(user.id, { attributes: { name: "Jane" } }); - - await client.flush(); - - expect(httpClient.post).toHaveBeenCalledWith( - BULK_ENDPOINT, - expectedHeaders, - [ - { - type: "user", - userId: user.id, - attributes: { age: 2 }, - }, - { - type: "user", - userId: user.id, - attributes: { age: 3 }, - }, - { - type: "user", - userId: user.id, - attributes: { name: "Jane" }, - }, - ], - ); - }); - - it("should not flush all bulk data if `offline` is true", async () => { - const client = new ReflagClient({ - ...validOptions, - offline: true, - }); - - await client.updateUser(user.id, { attributes: { age: 2 } }); - await client.flush(); - - expect(httpClient.post).not.toHaveBeenCalled(); - }); - }); - - describe("refreshFlags", () => { - it("should call flagsCache.refresh()", async () => { - const client = new ReflagClient(validOptions); - - const refresh = vi - .spyOn(client["flagsCache"], "refresh") - .mockResolvedValue(undefined); - - await client.refreshFlags(); - - expect(refresh).toHaveBeenCalledTimes(1); - }); - - it("should call flagsCache.refresh() on each invocation", async () => { - const client = new ReflagClient(validOptions); - - const refresh = vi - .spyOn(client["flagsCache"], "refresh") - .mockResolvedValue(undefined); - - await client.refreshFlags(); - await client.refreshFlags(); - await client.refreshFlags(); - - expect(refresh).toHaveBeenCalledTimes(3); - }); - }); - - describe("getFlag", () => { - let client: ReflagClient; - - beforeEach(async () => { - httpClient.get.mockResolvedValue({ - ok: true, - status: 200, - body: { - success: true, - ...flagDefinitions, - }, - }); - - client = new ReflagClient(validOptions); - - httpClient.post.mockResolvedValue({ - status: 200, - body: { success: true }, - }); - }); - - it("returns a flag", async () => { - await client.initialize(); - const flag = client.getFlag( - { - company, - user, - other: otherContext, - }, - "flag1", - ); - - expect(flag).toStrictEqual({ - key: "flag1", - isEnabled: true, - config: { - key: "config-1", - payload: { something: "else" }, - }, - track: expect.any(Function), - }); - }); - - it("sends diagnostics when flags are evaluated before initialization", async () => { - const context = { - company, - user, - other: otherContext, - }; - - const flag = client.getFlag(context, "key"); - expect(flag.isEnabled).toBe(true); - expect(flag.config).toEqual({ key: undefined, payload: undefined }); - await client.flush(); - - const checkEvents = httpClient.post.mock.calls - .flatMap((call) => call[2]) - .filter((item) => item.type === "feature-flag-event"); - - expect(checkEvents).toEqual([ - expect.objectContaining({ - action: "check", - evalErrors: [clientNotInitializedError], - }), - expect.objectContaining({ - action: "check-config", - evalErrors: [clientNotInitializedError], - }), - ]); - }); - - it("does not add initialization diagnostics when offline", () => { - const offlineClient = new ReflagClient({ - ...validOptions, - offline: true, - }); - const sendFlagEvent = vi.spyOn(offlineClient as any, "sendFlagEvent"); - - expect(offlineClient.getFlag({}, "flag").isEnabled).toBe(false); - - expect(sendFlagEvent).toHaveBeenCalledWith( - expect.objectContaining({ evalErrors: undefined }), - ); - expect(logger.error).not.toHaveBeenCalled(); - }); - - it("evaluates percentage rollouts using user.id", async () => { - const userRolloutDefinitions: FlagsAPIResponse = { - flagStateVersion: 2, - features: [ - { - key: "test-flag", - description: "User rollout", - targeting: { - version: 1, - rules: [ - { - filter: { - type: "rolloutPercentage", - key: "test-flag", - partialRolloutAttribute: "user.id", - partialRolloutThreshold: 50000, - }, - }, - ], - }, - }, - ], - }; - httpClient.get.mockResolvedValue({ - ok: true, - status: 200, - body: { success: true, ...userRolloutDefinitions }, - }); - - await client.initialize(); - - expect( - client.getFlag( - { - user: { id: "user-1" }, - company, - enableTracking: false, - }, - "test-flag", - ).isEnabled, - ).toBe(true); - expect( - client.getFlag( - { - user: { id: "user-2" }, - company, - enableTracking: false, - }, - "test-flag", - ).isEnabled, - ).toBe(false); - }); - - it("`track` sends all expected events when `enableTracking` is `true`", async () => { - const context = { - company, - user, - other: otherContext, - }; - - // test that the flag is returned - await client.initialize(); - const flag = client.getFlag( - { - ...context, - meta: { - active: true, - }, - enableTracking: true, - }, - "flag1", - ); - - await flag.track(); - await client.flush(); - - expect(httpClient.post).toHaveBeenCalledWith( - BULK_ENDPOINT, - expectedHeaders, - [ - { - attributes: { - employees: 100, - name: "Acme Inc.", - }, - companyId: "company123", - context: { - active: true, - }, - type: "company", - userId: user.id, - }, - { - attributes: { - age: 1, - name: "John", - }, - context: { - active: true, - }, - type: "user", - userId: "user123", - }, - { - type: "event", - event: "flag1", - userId: user.id, - companyId: company.id, - }, - ], - ); - }); - - it("`isEnabled` sends `check` event", async () => { - const context = { - company, - user, - other: otherContext, - }; - - // test that the flag is returned - await client.initialize(); - const flag = client.getFlag(context, "flag1"); - - // trigger `check` event - expect(flag.isEnabled).toBe(true); - - await client.flush(); - const checkEvents = httpClient.post.mock.calls - .flatMap((call) => call[2]) - .filter((e) => e.action === "check"); - - expect(checkEvents).toStrictEqual([ - { - type: "feature-flag-event", - action: "check", - key: "flag1", - targetingVersion: 1, - evalResult: true, - evalContext: context, - evalRuleResults: [true], - evalMissingFields: [], - evalErrors: undefined, - }, - ]); - }); - - it("`isEnabled` sends evaluation errors", async () => { - const context = { - company, - user, - other: otherContext, - }; - - await client.initialize(); - expect(client.getFlag(context, "flag2").isEnabled).toBe(false); - await client.flush(); - - const checkEvents = httpClient.post.mock.calls - .flatMap((call) => call[2]) - .filter((item) => item.action === "check"); - - expect(checkEvents).toEqual([ - expect.objectContaining({ - key: "flag2", - evalErrors: [missingContextFieldError("attributeKey")], - }), - ]); - }); - - it("`isEnabled` warns about missing context fields", async () => { - const context = { - company, - user, - other: otherContext, - }; - - // test that the flag is returned - await client.initialize(); - const flag = client.getFlag(context, "flag2"); - - // trigger the warning - expect(flag.isEnabled).toBe(false); - - expect(logger.warn).toHaveBeenCalledWith( - "flag targeting rules could not be fully evaluated.", - { - flag2: [ - { - code: "MISSING_CONTEXT_FIELD", - field: "attributeKey", - message: - 'Context field "attributeKey" is required to evaluate targeting rules.', - }, - ], - }, - ); - - const sameErrorForAnotherUser = client.getFlag( - { ...context, user: { ...context.user, id: "another-user" } }, - "flag2", - ); - expect(sameErrorForAnotherUser.isEnabled).toBe(false); - expect(logger.warn).toHaveBeenCalledTimes(1); - }); - - it.each(["CONTAINS", "NOT_CONTAINS", "IS", "IS_NOT"] as const)( - "evaluates array %s for targeting and config without warnings", - async (operator) => { - const filter = { - type: "context" as const, - field: "user.roles", - operator, - values: ["admin"], - }; - const definitions: FlagsAPIResponse = { - flagStateVersion: 2, - features: [ - { - key: "array-membership", - description: "Array membership", - targeting: { version: 1, rules: [{ filter }] }, - config: { - version: 1, - variants: [ - { key: "matched", payload: { access: true }, filter }, - ], - }, - }, - ], - }; - httpClient.get.mockResolvedValue({ - ok: true, - status: 200, - body: { success: true, ...definitions }, - }); - await client.initialize(); - - for (const [roles, contains, equals] of [ - [["admin"], true, true], - [["admin", "editor"], true, false], - [["admin", "admin"], true, false], - [["superadmin"], false, false], - [["Admin"], false, false], - [[], false, false], - // Scalars retain substring matching and exact equality respectively. - ["SUPERADMIN", true, false], - ["admin", true, true], - ] as const) { - const flag = client.getFlag( - { user: { id: "user123", roles } }, - "array-membership", - ); - const positiveMatch = - operator === "IS" || operator === "IS_NOT" ? equals : contains; - const expected = - operator === "CONTAINS" || operator === "IS" - ? positiveMatch - : !positiveMatch; - expect(flag.isEnabled).toBe(expected); - expect(flag.config).toEqual( - expected - ? { key: "matched", payload: { access: true } } - : { key: undefined, payload: undefined }, - ); - } - expect(logger.warn).not.toHaveBeenCalled(); - }, - ); - - it("`isEnabled` warns about unsupported array operators", async () => { - const arrayDefinitions: FlagsAPIResponse = { - flagStateVersion: 2, - features: [ - { - key: "array-flag", - description: "Array flag", - targeting: { - version: 1, - rules: [ - { - filter: { - type: "context", - field: "user.roles", - operator: "GT", - values: ["admin"], - }, - }, - ], - }, - }, - ], - }; - httpClient.get.mockResolvedValue({ - ok: true, - status: 200, - body: { success: true, ...arrayDefinitions }, - }); - - await client.initialize(); - const flag = client.getFlag( - { user: { id: "user123", roles: ["admin"] } }, - "array-flag", - ); - - expect(flag.isEnabled).toBe(false); - expect(logger.warn).toHaveBeenCalledWith( - "flag targeting rules could not be fully evaluated.", - { - "array-flag": [ - { - code: "UNSUPPORTED_ARRAY_OPERATOR", - field: "user.roles", - operator: "GT", - message: - 'Operator GT does not support array-valued context field "user.roles".', - }, - ], - }, - ); - - const sameErrorForAnotherUser = client.getFlag( - { user: { id: "another-user", roles: ["admin"] } }, - "array-flag", - ); - expect(sameErrorForAnotherUser.isEnabled).toBe(false); - expect(logger.warn).toHaveBeenCalledTimes(1); - }); - - it("`config` warns about unsupported array operators", async () => { - const arrayConfigDefinitions: FlagsAPIResponse = { - flagStateVersion: 2, - features: [ - { - key: "array-config", - description: "Array config", - targeting: { - version: 1, - rules: [{ filter: { type: "constant", value: true } }], - }, - config: { - version: 1, - variants: [ - { - key: "admin", - payload: { access: true }, - filter: { - type: "context", - field: "user.roles", - operator: "GT", - values: ["admin"], - }, - }, - ], - }, - }, - ], - }; - httpClient.get.mockResolvedValue({ - ok: true, - status: 200, - body: { success: true, ...arrayConfigDefinitions }, - }); - - await client.initialize(); - const flag = client.getFlag( - { user: { id: "user123", roles: ["admin"] } }, - "array-config", - ); - - expect(flag.config).toEqual({ key: undefined, payload: undefined }); - expect(logger.warn).toHaveBeenCalledWith( - "flag targeting rules could not be fully evaluated.", - { - "array-config.config": [ - { - code: "UNSUPPORTED_ARRAY_OPERATOR", - field: "user.roles", - operator: "GT", - message: - 'Operator GT does not support array-valued context field "user.roles".', - }, - ], - }, - ); - }); - - it("`isEnabled` should not warn about missing context fields if not needed", async () => { - const context = { - company, - user, - other: otherContext, - }; - - // test that the flag is returned - await client.initialize(); - const flag = client.getFlag(context, "flag1"); - - // should not trigger the warning - expect(flag.isEnabled).toBe(true); - - expect(logger.warn).not.toHaveBeenCalled(); - }); - - it("`config` sends `check` event", async () => { - const context = { - company, - user, - other: otherContext, - }; - - // test that the flag is returned - await client.initialize(); - const flag = client.getFlag(context, "flag1"); - - // trigger `check` event - expect(flag.config).toBeDefined(); - - await client.flush(); - - const checkEvents = httpClient.post.mock.calls - .flatMap((call) => call[2]) - .filter((e) => e.action === "check-config"); - - expect(checkEvents).toStrictEqual([ - { - type: "feature-flag-event", - action: "check-config", - key: "flag1", - evalResult: { - key: "config-1", - payload: { - something: "else", - }, - }, - targetingVersion: 1, - evalContext: context, - evalRuleResults: [true], - evalMissingFields: [], - evalErrors: undefined, - }, - ]); - }); - - it("sends events for unknown flags", async () => { - const context: Context = { - company, - user, - other: otherContext, - }; - - // test that the flag is returned - await client.initialize(); - const flag = client.getFlag(context, "unknown-flag"); - - // trigger `check` event - expect(flag.isEnabled).toBe(false); - await flag.track(); - await client.flush(); - - const checkEvents = httpClient.post.mock.calls - .flatMap((call) => call[2]) - .filter((e) => e.type === "feature-flag-event"); - - expect(checkEvents).toStrictEqual([ - { - type: "feature-flag-event", - action: "check", - key: "unknown-flag", - targetingVersion: undefined, - evalContext: context, - evalResult: false, - evalRuleResults: undefined, - evalMissingFields: undefined, - evalErrors: undefined, - }, - ]); - }); - - it("sends company/user and track events", async () => { - const context: Context = { - company, - user, - other: otherContext, - }; - - // test that the flag is returned - await client.initialize(); - const flag = client.getFlag(context, "flag1"); - - // trigger `check` event - await flag.track(); - await client.flush(); - - const checkEvents = httpClient.post.mock.calls - .flatMap((call) => call[2]) - .filter( - (e) => - e.type === "company" || e.type === "user" || e.type === "event", - ); - - expect(checkEvents).toStrictEqual([ - { - type: "company", - companyId: "company123", - attributes: { - employees: 100, - name: "Acme Inc.", - }, - userId: user.id, - context: undefined, - }, - { - type: "user", - userId: "user123", - attributes: { - age: 1, - name: "John", - }, - context: undefined, - }, - { - type: "event", - event: "flag1", - userId: user.id, - companyId: company.id, - context: undefined, - attributes: undefined, - }, - ]); - }); - }); - - describe("getFlags", () => { - let client: ReflagClient; - - beforeEach(async () => { - httpClient.get.mockResolvedValue({ - ok: true, - status: 200, - body: { - success: true, - ...flagDefinitions, - }, - }); - - client = new ReflagClient(validOptions); - - client["rateLimiter"].clearStale(true); - - httpClient.post.mockResolvedValue({ - ok: true, - status: 200, - body: { success: true }, - }); - }); - - it("should return evaluated flags", async () => { - httpClient.post.mockClear(); // not interested in updates - - await client.initialize(); - const result = client.getFlags({ - company, - user, - other: otherContext, - }); - - expect(result).toStrictEqual({ - flag1: { - key: "flag1", - isEnabled: true, - config: { - key: "config-1", - payload: { - something: "else", - }, - }, - track: expect.any(Function), - }, - flag2: { - key: "flag2", - isEnabled: false, - config: { key: undefined, payload: undefined }, - track: expect.any(Function), - }, - }); - - await client.flush(); - - expect(httpClient.post).toHaveBeenCalledTimes(1); - }); - - it("should properly define the rate limiter key", async () => { - const isAllowedSpy = vi.spyOn(client["rateLimiter"], "isAllowed"); - - await client.initialize(); - client.getFlags({ user, company, other: otherContext }); - - expect(isAllowedSpy).toHaveBeenNthCalledWith( - 1, - "5Zt35h50IPRNU8yXAj/YbPME/qE=", - ); - expect(isAllowedSpy).toHaveBeenNthCalledWith( - 2, - "J3G4oF56f2t+T6xYzES6inc78+c=", - ); - }); - - it("should return evaluated flags when only user is defined", async () => { - httpClient.post.mockClear(); // not interested in updates - - await client.initialize(); - const flags = client.getFlags({ user }); - - expect(flags).toStrictEqual({ - flag1: { - isEnabled: false, - key: "flag1", - config: { - key: undefined, - payload: undefined, - }, - track: expect.any(Function), - }, - flag2: { - key: "flag2", - isEnabled: false, - config: { key: undefined, payload: undefined }, - track: expect.any(Function), - }, - }); - - await client.flush(); - - expect(httpClient.post).toHaveBeenCalledTimes(1); - }); - - it("should return evaluated flags when only company is defined", async () => { - await client.initialize(); - const flags = client.getFlags({ company }); - - // expect will trigger the `isEnabled` getter and send a `check` event - expect(flags).toStrictEqual({ - flag1: { - isEnabled: true, - key: "flag1", - config: { - key: "config-1", - payload: { - something: "else", - }, - }, - track: expect.any(Function), - }, - flag2: { - key: "flag2", - isEnabled: false, - config: { key: undefined, payload: undefined }, - track: expect.any(Function), - }, - }); - - await client.flush(); - - expect(httpClient.post).toHaveBeenCalledTimes(1); - }); - - it("should not send flag events when `enableTracking` is `false`", async () => { - await client.initialize(); - const flags = client.getFlags({ company, enableTracking: false }); - - // expect will trigger the `isEnabled` getter and send a `check` event - expect(flags).toStrictEqual({ - flag1: { - isEnabled: true, - key: "flag1", - config: { - key: "config-1", - payload: { - something: "else", - }, - }, - track: expect.any(Function), - }, - flag2: { - key: "flag2", - isEnabled: false, - config: { key: undefined, payload: undefined }, - track: expect.any(Function), - }, - }); - - await client.flush(); - - expect(httpClient.post).not.toHaveBeenCalled(); - }); - - it("should return evaluated flags when only other context is defined", async () => { - await client.initialize(); - const flags = client.getFlags({ other: otherContext }); - - expect(flags).toStrictEqual({ - flag1: { - isEnabled: false, - key: "flag1", - config: { - key: undefined, - payload: undefined, - }, - track: expect.any(Function), - }, - flag2: { - key: "flag2", - isEnabled: false, - config: { key: undefined, payload: undefined }, - track: expect.any(Function), - }, - }); - - await client.flush(); - }); - - it("should send `track` with user and company if provided", async () => { - await client.initialize(); - const flags = client.getFlags({ company, user }); - await client.flush(); - - await flags.flag1.track(); - await client.flush(); - - expect(httpClient.post).toHaveBeenCalledTimes(2); - // second call includes the track event - const events = httpClient.post.mock.calls[1][2].filter( - (e: any) => e.type === "event", - ); - - expect(events).toStrictEqual([ - { - event: "flag1", - type: "event", - userId: "user123", - companyId: "company123", - attributes: undefined, - context: undefined, - }, - ]); - }); - - it("should send `track` with user if provided", async () => { - await client.initialize(); - const flags = client.getFlags({ user }); - - await client.flush(); - await flags.flag1.track(); - await client.flush(); - - expect(httpClient.post).toHaveBeenCalledTimes(2); - - const emptyEvents = httpClient.post.mock.calls[0][2].filter( - (e: any) => e.type === "event", - ); - - expect(emptyEvents).toStrictEqual([]); - - // second call includes the track event - const events = httpClient.post.mock.calls[1][2].filter( - (e: any) => e.type === "event", - ); - - expect(events).toStrictEqual([ - { - event: "flag1", - type: "event", - userId: "user123", - companyId: undefined, - attributes: undefined, - context: undefined, - }, - ]); - }); - - it("should not send `track` with only company if no user is provided", async () => { - // we do not accept track events without a userId - await client.initialize(); - const flag = client.getFlags({ company }); - - await flag.flag1.track(); - await client.flush(); - - expect(httpClient.post).toHaveBeenCalledTimes(1); - const events = httpClient.post.mock.calls[0][2].filter( - (e: any) => e.type === "event", - ); - - expect(events).toStrictEqual([]); - }); - - it("`isEnabled` does not send `check` event", async () => { - const context = { - company, - user, - other: otherContext, - }; - - // test that the flag is returned - await client.initialize(); - const flag = client.getFlags(context); - - // trigger `check` event - expect(flag.flag1.isEnabled).toBe(true); - - await client.flush(); - const checkEvents = httpClient.post.mock.calls - .flatMap((call) => call[2]) - .filter((e) => e.action === "check"); - - expect(checkEvents).toStrictEqual([]); - }); - - it("`config` does not send `check` event", async () => { - const context = { - company, - user, - other: otherContext, - }; - - // test that the flag is returned - await client.initialize(); - const flag = client.getFlags(context); - - // attempt to trigger `check` event - expect(flag.flag1.config).toBeDefined(); - - await client.flush(); - - const checkEvents = httpClient.post.mock.calls - .flatMap((call) => call[2]) - .filter((e) => e.action === "check-config"); - - expect(checkEvents).toStrictEqual([]); - }); - - it("sends company/user events", async () => { - const context: Context = { - company, - user, - other: otherContext, - }; - - // test that the flag is returned - await client.initialize(); - client.getFlags(context); - - // trigger `check` event - await client.flush(); - - const checkEvents = httpClient.post.mock.calls - .flatMap((call) => call[2]) - .filter( - (e) => - e.type === "company" || e.type === "user" || e.type === "event", - ); - - expect(checkEvents).toStrictEqual([ - { - type: "company", - companyId: "company123", - attributes: { - employees: 100, - name: "Acme Inc.", - }, - userId: user.id, - context: undefined, - }, - { - type: "user", - userId: "user123", - attributes: { - age: 1, - name: "John", - }, - context: undefined, - }, - ]); - }); - - it("should use fallback flags when `getFlagDefinitions` returns `undefined`", async () => { - httpClient.get.mockResolvedValue({ - success: false, - }); - - await client.initialize(); - const result = client.getFlag( - { user: { id: "user123" }, enableTracking: true }, - "key", - ); - - expect(result).toStrictEqual({ - key: "key", - isEnabled: true, - config: { key: undefined, payload: undefined }, - track: expect.any(Function), - }); - - expect(logger.warn).toHaveBeenCalledWith( - expect.stringMatching( - "no flag definitions available, using fallback flags", - ), - ); - - await client.flush(); - - expect(httpClient.post).toHaveBeenCalledTimes(1); - expect(httpClient.post).toHaveBeenCalledWith( - BULK_ENDPOINT, - expectedHeaders, - [ - expect.objectContaining({ type: "user" }), - expect.objectContaining({ - type: "feature-flag-event", - action: "check-config", - key: "key", - }), - expect.objectContaining({ - type: "feature-flag-event", - action: "check", - key: "key", - evalResult: true, - }), - ], - ); - }); - - it("should not fail if sendFlagEvent fails to send check event", async () => { - httpClient.post.mockResolvedValue({ - status: 200, - body: { success: true }, - }); - - await client.initialize(); - httpClient.post.mockRejectedValue(new Error("Network error")); - const context = { user, company, other: otherContext }; - - const result = client.getFlags(context); - - // Trigger a flag check - expect(result.flag1).toStrictEqual({ - key: "flag1", - isEnabled: true, - track: expect.any(Function), - config: { - key: "config-1", - payload: { - something: "else", - }, - }, - }); - - await client.flush(); - - expect(logger.warn).toHaveBeenCalledWith( - "flush of buffered items failed; discarding items", - expect.objectContaining({ - count: 2, - error: expect.objectContaining({ - message: "failed to send bulk events", - }), - }), - ); - }); - - it("should use base flag overrides", async () => { - await client.initialize(); - const context = { user, company, other: otherContext }; - - const pristineResults = client.getFlags(context); - expect(pristineResults).toStrictEqual({ - flag1: { - key: "flag1", - isEnabled: true, - config: { - key: "config-1", - payload: { - something: "else", - }, - }, - track: expect.any(Function), - }, - flag2: { - key: "flag2", - isEnabled: false, - config: { key: undefined, payload: undefined }, - track: expect.any(Function), - }, - }); - - client.setFlagOverrides({ - flag1: false, - }); - const flags = client.getFlags(context); - - expect(flags).toStrictEqual({ - flag1: { - key: "flag1", - isEnabled: false, - config: { key: undefined, payload: undefined }, - track: expect.any(Function), - }, - flag2: { - key: "flag2", - isEnabled: false, - config: { key: undefined, payload: undefined }, - track: expect.any(Function), - }, - }); - - client.clearFlagOverrides(); - const flags2 = client.getFlags(context); - - expect(flags2).toStrictEqual({ - ...pristineResults, - flag1: { - ...pristineResults.flag1, - track: expect.any(Function), - }, - flag2: { - ...pristineResults.flag2, - track: expect.any(Function), - }, - }); - }); - - it("should use base flag overrides from function", async () => { - await client.initialize(); - const context = { user, company, other: otherContext }; - - const pristineResults = client.getFlags(context); - expect(pristineResults).toStrictEqual({ - flag1: { - key: "flag1", - isEnabled: true, - config: { - key: "config-1", - payload: { - something: "else", - }, - }, - track: expect.any(Function), - }, - flag2: { - key: "flag2", - isEnabled: false, - config: { key: undefined, payload: undefined }, - track: expect.any(Function), - }, - }); - - client.setFlagOverrides((_context: Context) => { - expect(context).toStrictEqual(context); - return { - flag1: { isEnabled: false }, - flag2: true, - flag3: { - isEnabled: true, - config: { - key: "config-1", - payload: { something: "else" }, - }, - }, - }; - }); - const flags = client.getFlags(context); - - expect(flags).toStrictEqual({ - flag1: { - key: "flag1", - isEnabled: false, - config: { key: undefined, payload: undefined }, - track: expect.any(Function), - }, - flag2: { - key: "flag2", - isEnabled: true, - config: { key: undefined, payload: undefined }, - track: expect.any(Function), - }, - flag3: { - key: "flag3", - isEnabled: true, - config: { - key: "config-1", - payload: { something: "else" }, - }, - track: expect.any(Function), - }, - }); - }); - - it("should push and restore layered flag overrides", async () => { - await client.initialize(); - const context = { user, company, other: otherContext }; - - expect(client.getFlag(context, "flag1").isEnabled).toBe(true); - expect(client.getFlag(context, "flag2").isEnabled).toBe(false); - - const removeFlag1 = client.pushFlagOverrides({ - flag1: false, - }); - - expect(client.getFlag(context, "flag1").isEnabled).toBe(false); - expect(client.getFlag(context, "flag2").isEnabled).toBe(false); - - const removeFlag2 = client.pushFlagOverrides({ - flag2: true, - }); - - expect(client.getFlag(context, "flag1").isEnabled).toBe(false); - expect(client.getFlag(context, "flag2").isEnabled).toBe(true); - - removeFlag2(); - - expect(client.getFlag(context, "flag1").isEnabled).toBe(false); - expect(client.getFlag(context, "flag2").isEnabled).toBe(false); - - removeFlag1(); - - expect(client.getFlag(context, "flag1").isEnabled).toBe(true); - expect(client.getFlag(context, "flag2").isEnabled).toBe(false); - }); - - it("should compose pushed flag overrides with existing override functions", async () => { - await client.initialize(); - const context = { user, company, other: otherContext }; - - client.setFlagOverrides(() => ({ - flag1: false, - })); - - const remove = client.pushFlagOverrides((overrideContext: Context) => { - expect(overrideContext).toStrictEqual({ - user, - company, - other: otherContext, - }); - - return { - flag2: true, - }; - }); - - expect(client.getFlag(context, "flag1").isEnabled).toBe(false); - expect(client.getFlag(context, "flag2").isEnabled).toBe(true); - - remove(); - remove(); - - expect(client.getFlag(context, "flag1").isEnabled).toBe(false); - expect(client.getFlag(context, "flag2").isEnabled).toBe(false); - }); - - it("should keep pushed overrides layered on top when replacing base overrides", async () => { - await client.initialize(); - const context = { user, company, other: otherContext }; - - client.setFlagOverrides({ - flag1: false, - }); - - const remove = client.pushFlagOverrides({ - flag1: true, - }); - - expect(client.getFlag(context, "flag1").isEnabled).toBe(true); - - client.setFlagOverrides({ - flag1: false, - flag2: true, - }); - - expect(client.getFlag(context, "flag1").isEnabled).toBe(true); - expect(client.getFlag(context, "flag2").isEnabled).toBe(true); - - remove(); - - expect(client.getFlag(context, "flag1").isEnabled).toBe(false); - expect(client.getFlag(context, "flag2").isEnabled).toBe(true); - }); - - it("should only clear the base overrides", async () => { - await client.initialize(); - const context = { user, company, other: otherContext }; - - client.setFlagOverrides({ - flag1: false, - }); - - const remove = client.pushFlagOverrides({ - flag2: true, - }); - - client.clearFlagOverrides(); - - expect(client.getFlag(context, "flag1").isEnabled).toBe(true); - expect(client.getFlag(context, "flag2").isEnabled).toBe(true); - - remove(); - - expect(client.getFlag(context, "flag1").isEnabled).toBe(true); - expect(client.getFlag(context, "flag2").isEnabled).toBe(false); - }); - }); - - describe("getFlagsForBootstrap", () => { - let client: ReflagClient; - - beforeEach(async () => { - httpClient.get.mockResolvedValue({ - ok: true, - status: 200, - body: { - success: true, - ...flagDefinitions, - }, - }); - - client = new ReflagClient(validOptions); - - client["rateLimiter"].clearStale(true); - - httpClient.post.mockResolvedValue({ - ok: true, - status: 200, - body: { success: true }, - }); - }); - - it("should return raw flags without wrapper functions", async () => { - httpClient.post.mockClear(); // not interested in updates - - await client.initialize(); - const result = client.getFlagsForBootstrap({ - company, - user, - other: otherContext, - enableTracking: true, - }); - - expect(result).toStrictEqual({ - context: { - company, - user, - other: otherContext, - enableTracking: true, - }, - flags: { - flag1: { - key: "flag1", - isEnabled: true, - targetingVersion: 1, - config: { - key: "config-1", - payload: { - something: "else", - }, - targetingVersion: 1, - missingContextFields: [], - ruleEvaluationResults: [true], - }, - ruleEvaluationResults: [true], - missingContextFields: [], - }, - flag2: { - key: "flag2", - isEnabled: false, - targetingVersion: 2, - config: { - key: undefined, - payload: undefined, - targetingVersion: undefined, - missingContextFields: [], - ruleEvaluationResults: [], - }, - ruleEvaluationResults: [false], - missingContextFields: ["attributeKey"], - evaluationErrors: [missingContextFieldError("attributeKey")], - }, - }, - flagStateVersion: 1, - }); - - // Should not have track function like regular getFlags - expect(result.flags.flag1).not.toHaveProperty("track"); - expect(result.flags.flag2).not.toHaveProperty("track"); - - await client.flush(); - - expect(httpClient.post).toHaveBeenCalledTimes(1); - }); - - it("should return raw flags when only user is defined", async () => { - httpClient.post.mockClear(); // not interested in updates - - await client.initialize(); - const flags = client.getFlagsForBootstrap({ user }); - - expect(flags).toStrictEqual({ - context: { - user, - enableTracking: true, - }, - flags: { - flag1: { - key: "flag1", - isEnabled: false, - targetingVersion: 1, - config: { - key: undefined, - payload: undefined, - targetingVersion: 1, - missingContextFields: ["company.id"], - evaluationErrors: [missingContextFieldError("company.id")], - ruleEvaluationResults: [false], - }, - ruleEvaluationResults: [false], - missingContextFields: ["company.id"], - evaluationErrors: [missingContextFieldError("company.id")], - }, - flag2: { - key: "flag2", - isEnabled: false, - targetingVersion: 2, - config: { - key: undefined, - payload: undefined, - targetingVersion: undefined, - missingContextFields: [], - ruleEvaluationResults: [], - }, - ruleEvaluationResults: [false], - missingContextFields: ["company.id"], - evaluationErrors: [missingContextFieldError("company.id")], - }, - }, - flagStateVersion: 1, - }); - - // Should not have track function - expect(flags.flags.flag1).not.toHaveProperty("track"); - expect(flags.flags.flag2).not.toHaveProperty("track"); - - await client.flush(); - - expect(httpClient.post).toHaveBeenCalledTimes(1); - }); - - it("should return raw flags when only company is defined", async () => { - await client.initialize(); - const flags = client.getFlagsForBootstrap({ company }); - - expect(flags).toStrictEqual({ - context: { - company, - enableTracking: true, - }, - flags: { - flag1: { - key: "flag1", - isEnabled: true, - targetingVersion: 1, - config: { - key: "config-1", - payload: { - something: "else", - }, - targetingVersion: 1, - missingContextFields: [], - ruleEvaluationResults: [true], - }, - ruleEvaluationResults: [true], - missingContextFields: [], - }, - flag2: { - key: "flag2", - isEnabled: false, - targetingVersion: 2, - config: { - key: undefined, - payload: undefined, - targetingVersion: undefined, - missingContextFields: [], - ruleEvaluationResults: [], - }, - ruleEvaluationResults: [false], - missingContextFields: ["attributeKey"], - evaluationErrors: [missingContextFieldError("attributeKey")], - }, - }, - flagStateVersion: 1, - }); - - // Should not have track function - expect(flags.flags.flag1).not.toHaveProperty("track"); - expect(flags.flags.flag2).not.toHaveProperty("track"); - }); - - it("should return raw flags when only other context is defined", async () => { - await client.initialize(); - const flags = client.getFlagsForBootstrap({ other: otherContext }); - - expect(flags).toStrictEqual({ - context: { - other: otherContext, - enableTracking: true, - }, - flags: { - flag1: { - key: "flag1", - isEnabled: false, - targetingVersion: 1, - config: { - key: undefined, - payload: undefined, - targetingVersion: 1, - missingContextFields: ["company.id"], - evaluationErrors: [missingContextFieldError("company.id")], - ruleEvaluationResults: [false], - }, - ruleEvaluationResults: [false], - missingContextFields: ["company.id"], - evaluationErrors: [missingContextFieldError("company.id")], - }, - flag2: { - key: "flag2", - isEnabled: false, - targetingVersion: 2, - config: { - key: undefined, - payload: undefined, - targetingVersion: undefined, - missingContextFields: [], - ruleEvaluationResults: [], - }, - ruleEvaluationResults: [false], - missingContextFields: ["company.id"], - evaluationErrors: [missingContextFieldError("company.id")], - }, - }, - flagStateVersion: 1, - }); - - // Should not have track function - expect(flags.flags.flag1).not.toHaveProperty("track"); - expect(flags.flags.flag2).not.toHaveProperty("track"); - }); - - it("should return fallback flags when client is not initialized", async () => { - const flags = client.getFlagsForBootstrap({ - company, - user, - other: otherContext, - enableTracking: true, - }); - - // Should return the fallback flags defined in validOptions - expect(flags).toStrictEqual({ - context: { - company, - user, - other: otherContext, - enableTracking: true, - }, - flags: { - key: { - isEnabled: true, - key: "key", - }, - }, - }); - }); - - it("should return fallback flags when flag definitions are not available", async () => { - httpClient.get.mockResolvedValueOnce({ - ok: true, - status: 200, - body: { - success: true, - flagStateVersion: 1, - features: [], // No flag definitions - }, - }); - - await client.initialize(); - const flags = client.getFlagsForBootstrap({ - company, - user, - other: otherContext, - }); - - expect(flags).toStrictEqual({ - context: { - company, - user, - other: otherContext, - enableTracking: true, - }, - flags: {}, - flagStateVersion: 1, - }); - }); - - it("should handle enableTracking parameter", async () => { - await client.initialize(); - - // Test with enableTracking: true (default) - const flagsWithTracking = client.getFlagsForBootstrap({ - company, - user, - other: otherContext, - enableTracking: true, - }); - - // Test with enableTracking: false - const flagsWithoutTracking = client.getFlagsForBootstrap({ - company, - user, - other: otherContext, - enableTracking: true, - }); - - // Both should return the same raw flag structure - expect(flagsWithTracking).toStrictEqual(flagsWithoutTracking); - - // Neither should have track functions - expect(flagsWithTracking.flags.flag1).not.toHaveProperty("track"); - expect(flagsWithoutTracking.flags.flag1).not.toHaveProperty("track"); - }); - - it("should properly define the rate limiter key", async () => { - const isAllowedSpy = vi.spyOn(client["rateLimiter"], "isAllowed"); - - await client.initialize(); - client.getFlagsForBootstrap({ user, company, other: otherContext }); - - expect(isAllowedSpy).toHaveBeenNthCalledWith( - 1, - "5Zt35h50IPRNU8yXAj/YbPME/qE=", - ); - expect(isAllowedSpy).toHaveBeenNthCalledWith( - 2, - "J3G4oF56f2t+T6xYzES6inc78+c=", - ); - }); - - it("should work in offline mode", async () => { - const offlineClient = new ReflagClient({ - ...validOptions, - offline: true, - }); - - const flags = offlineClient.getFlagsForBootstrap({ - company, - user, - other: otherContext, - enableTracking: true, - }); - - expect(flags).toStrictEqual({ - context: { - company, - user, - other: otherContext, - enableTracking: true, - }, - flags: {}, - }); - }); - - it("should use fallback flags when provided and no definitions available", async () => { - const fallbackTestFlags = { - fallbackFlag: { - key: "fallbackFlag", - isEnabled: true, - config: { key: "fallback-config", payload: { test: "data" } }, - }, - }; - - const clientWithFallback = new ReflagClient({ - ...validOptions, - fallbackFlags: fallbackTestFlags, - }); - - // Don't initialize to simulate no flag definitions - const flags = clientWithFallback.getFlagsForBootstrap({ - company, - user, - other: otherContext, - enableTracking: true, - }); - - expect(flags).toStrictEqual({ - context: { - company, - user, - other: otherContext, - enableTracking: true, - }, - flags: fallbackTestFlags, - }); - }); + fallbackProviders, + ReflagClient, + type ClientOptions, + type FlagsFallbackSnapshot, + type HttpClient, +} from "../src"; +import { + FLAG_EVENT_RATE_LIMITER_WINDOW_SIZE_MS, + SDK_VERSION, + SDK_VERSION_HEADER_NAME, +} from "../src/config"; +import { definition, graph, snapshot } from "./fixtures"; + +vi.mock("../src/flusher", () => ({ subscribe: vi.fn() })); +const clients: ReflagClient[] = []; +const company = { id: "acme", plan: "enterprise" }; +function harness(response: unknown = graph(), options: ClientOptions = {}) { + const state = { response }; + const logger = { + debug: vi.fn(), + info: vi.fn(), + warn: vi.fn(), + error: vi.fn(), + }; + const httpClient = { + get: vi.fn( + async ( + _url: string, + _headers: Record, + _timeoutMs: number, + ) => ({ + status: 200, + ok: true, + body: { success: true, ...(state.response as object) }, + }), + ), + post: vi.fn( + async ( + _url: string, + _headers: Record, + _body: { type: string; [key: string]: unknown }[], + ) => ({ status: 200, ok: true, body: { success: true } }), + ), + }; + const client = new ReflagClient({ + secretKey: "validSecretKeyWithMoreThan22Chars", + apiBaseUrl: "https://api.example.com/", + offline: false, + flagsFetchRetries: 0, + flagsSyncMode: "in-request", + logger, + httpClient: httpClient as unknown as HttpClient, + batchOptions: { intervalMs: 1e9, flushOnExit: false }, + ...options, }); + clients.push(client); + const events = () => httpClient.post.mock.calls.flatMap(([, , body]) => body); + return { + client, + state, + logger, + httpClient, + events, + checks: () => + events().filter((event) => event.type === "feature-flag-event"), + }; +} +async function nextRefresh(client: ReflagClient, version?: number) { + await vi.advanceTimersByTimeAsync(1001); + await client.refreshFlags(version); +} +beforeEach(() => { + vi.useFakeTimers(); +}); +afterEach(() => { + for (const client of clients.splice(0)) client.destroy(); + vi.useRealTimers(); + vi.restoreAllMocks(); }); -describe("getFlagsRemote", () => { - let client: ReflagClient; - - beforeEach(async () => { - httpClient.get.mockResolvedValue({ - ok: true, - status: 200, - body: { - success: true, - remoteContextUsed: true, - features: { - flag1: { - key: "flag1", - targetingVersion: 1, - isEnabled: true, - config: { - key: "config-1", - version: 3, - default: true, - payload: { something: "else" }, - missingContextFields: ["funny"], - }, - missingContextFields: ["something", "funny"], - }, - flag2: { - key: "flag2", - targetingVersion: 2, - isEnabled: false, - missingContextFields: ["another"], - }, - flag3: { - key: "flag3", - targetingVersion: 5, - isEnabled: true, - }, - }, - }, - }); - - client = new ReflagClient(validOptions); +describe("direct flag values", () => { + it.each([ + false, + true, + null, + 0, + 42, + "", + "quality", + [false, "a"], + { nested: { enabled: false } }, + ])("returns %j itself, without a wrapper", async (value) => { + const h = harness(snapshot([definition("flag", value)])); + await h.client.initialize(); + expect(h.client.getFlag({ company }, "flag", null)).toEqual(value); + await h.client.flush(); + expect(h.checks()).toEqual([ + expect.objectContaining({ + action: "check", + key: "flag", + evalResult: "default", + sourceVersionId: "version:flag", + flagStateVersion: 1, + evalContext: { company }, + }), + ]); + expect(h.checks()[0]).not.toHaveProperty("value"); }); - - afterEach(() => { - httpClient.get.mockClear(); + it("fetches one complete /flags collection with SDK authentication", async () => { + const h = harness(); + await h.client.initialize(); + await h.client.initialize(); + expect(h.httpClient.get).toHaveBeenCalledTimes(1); + expect(h.httpClient.get).toHaveBeenCalledWith( + "https://api.example.com/flags", + expect.objectContaining({ + Authorization: "Bearer validSecretKeyWithMoreThan22Chars", + [SDK_VERSION_HEADER_NAME]: SDK_VERSION, + }), + expect.any(Number), + ); }); - - it("should return evaluated flags", async () => { - const result = await client.getFlagsRemote("c1", "u1", { - other: otherContext, - }); - - expect(result).toStrictEqual({ - flag1: { - key: "flag1", - isEnabled: true, - config: { - key: "config-1", - payload: { something: "else" }, - }, - track: expect.any(Function), - }, - flag2: { - key: "flag2", - isEnabled: false, - config: { key: undefined, payload: undefined }, - track: expect.any(Function), - }, - flag3: { - key: "flag3", - isEnabled: true, - config: { key: undefined, payload: undefined }, - track: expect.any(Function), + it("checks only the requested root, even when the caller ignores its value", async () => { + const h = harness(); + await h.client.initialize(); + h.client.getFlag({ company }, "dependent"); + await h.client.flush(); + expect(h.checks()).toEqual([ + expect.objectContaining({ key: "dependent", evalResult: "true" }), + ]); + }); + it("batch-evaluates roots and returns a value record", async () => { + const h = harness(); + await h.client.initialize(); + expect(h.client.getFlags({ company })).toEqual({ + model: "quality", + dependent: true, + }); + await h.client.flush(); + expect(h.checks().map((event) => event.evalResult)).toEqual([ + "quality", + "true", + ]); + }); + it("keeps successive evaluations scoped to their contexts", async () => { + const h = harness(); + await h.client.initialize(); + expect(h.client.getFlag({ company }, "dependent")).toBe(true); + expect( + h.client.getFlag({ company: { id: "small", plan: "free" } }, "dependent"), + ).toBe(false); + expect(h.client.getFlag({ company }, "dependent")).toBe(true); + }); + it("single evaluation does not diagnose unrelated roots", async () => { + const collection = graph(); + const unrelated = definition("unrelated", false); + unrelated.rules.unshift({ + id: "requires-context", + filter: { + type: "context", + field: "other.missing", + operator: "IS", + values: ["yes"], }, + result: { type: "variant", variantKey: "default" }, + }); + collection.flags.push(unrelated); + const h = harness(collection); + await h.client.initialize(); + h.client.getFlag({ company }, "dependent"); + await h.client.flush(); + expect(h.checks()).toHaveLength(1); + expect(h.logger.warn).not.toHaveBeenCalled(); + }); + it("preserves diagnostic provenance with a successful fallback selection", async () => { + const h = harness(); + await h.client.initialize(); + expect(h.client.getFlag({}, "dependent")).toBe(false); + await h.client.flush(); + expect(h.checks()[0]).toMatchObject({ + evalResult: "false", + evalErrors: [ + expect.objectContaining({ + code: "MISSING_CONTEXT_FIELD", + field: "company.plan", + source: { type: "segment", key: "enterprise" }, + }), + ], }); - - expect(httpClient.get).toHaveBeenCalledTimes(1); - - expect(httpClient.get).toHaveBeenCalledWith( - `https://api.example.com/features/evaluated?${new URLSearchParams({ - contextJson: - '{"company":{"id":"u1"},"other":{"custom":"context","key":"value"},"user":{"id":"c1"}}', - })}`, - expectedHeaders, - API_TIMEOUT_MS, + }); + it("does not let callers mutate cached variant payloads", async () => { + const h = harness(snapshot([definition("flag", { enabled: false })])); + await h.client.initialize(); + const value = h.client.getFlag({}, "flag", { enabled: false }); + value.enabled = true; + expect(h.client.getFlag({}, "flag", { enabled: true })).toEqual({ + enabled: false, + }); + const batch = h.client.getFlags({ enableTracking: false }); + (batch.flag as { enabled: boolean }).enabled = true; + expect(h.client.getFlag({}, "flag", { enabled: true })).toEqual({ + enabled: false, + }); + }); + it("captures check context before the caller mutates it", async () => { + const h = harness(); + await h.client.initialize(); + const mutable = { id: "acme", plan: "enterprise" }; + h.client.getFlag({ company: mutable }, "dependent"); + mutable.plan = "free"; + h.client.getFlag({ company: mutable }, "dependent"); + await h.client.flush(); + expect(h.checks()).toEqual([ + expect.objectContaining({ + evalResult: "true", + evalContext: { company: { id: "acme", plan: "enterprise" } }, + }), + expect.objectContaining({ + evalResult: "false", + evalContext: { company: { id: "acme", plan: "free" } }, + }), + ]); + }); + it("supports prototype-like keys without polluting records", async () => { + const h = harness( + snapshot([definition("__proto__", 3), definition("constructor", null)]), + ); + await h.client.initialize(); + expect(h.client.getFlag({}, "__proto__", 0)).toBe(3); + expect(h.client.getFlags({ enableTracking: false })).toEqual( + JSON.parse('{"__proto__":3,"constructor":null}'), ); }); +}); - it("sends array context as canonical JSON", async () => { - await client.getFlagsRemote(undefined, undefined, { - other: { - z: { second: 2, first: 1 }, - roles: ["admin", "editor"], - a: true, - }, - }); +describe("default-value reads", () => { + it("distinguishes authored Boolean false from an identical implicit default", async () => { + const h = harness(snapshot([definition("release", false, "false")])); + await h.client.initialize(); + expect(h.client.getFlag({}, "release")).toBe(false); + expect(h.client.getFlag({}, "missing")).toBe(false); + await h.client.flush(); + expect(h.checks()).toEqual([ + expect.objectContaining({ + key: "release", + evalResult: "false", + sourceVersionId: "version:release", + }), + expect.objectContaining({ key: "missing", action: "check" }), + ]); + expect(h.checks()[1]).not.toHaveProperty("evalResult"); + expect(h.checks()[1]).not.toHaveProperty("sourceVersionId"); + }); - const requestUrl = new URL(httpClient.get.mock.calls[0][0]); - expect(requestUrl.searchParams.get("contextJson")).toBe( - '{"other":{"a":true,"roles":["admin","editor"],"z":{"first":1,"second":2}}}', - ); - expect(requestUrl.searchParams.has("context.other.roles.0")).toBe(false); + it("uses an explicit default for a missing bound read without authored provenance", async () => { + const h = harness(snapshot()); + await h.client.initialize(); + expect( + h.client.bindClient({}).getFlag("settings", { model: "Swift" }), + ).toEqual({ model: "Swift" }); + await h.client.flush(); + expect(h.checks()).toEqual([expect.objectContaining({ key: "settings" })]); + expect(h.checks()[0]).not.toHaveProperty("evalResult"); + expect(h.checks()[0]).not.toHaveProperty("sourceVersionId"); }); it.each([ - ["absent", undefined], - ["effectively empty", { other: { nested: { value: undefined } } }], - ])("does not append %s context", async (_case, additionalContext) => { - await client.getFlagsRemote(undefined, undefined, additionalContext); + [false, true], + [0, 42], + ["", "fallback"], + [[], [1]], + [{}, { model: "Swift" }], + ])( + "preserves a selected falsy/empty value %j rather than the default", + async (value, defaultValue) => { + const h = harness(snapshot([definition("flag", value)])); + await h.client.initialize(); + expect(h.client.getFlag({}, "flag", defaultValue)).toEqual(value); + await h.client.flush(); + expect(h.checks()[0]).toMatchObject({ + evalResult: "default", + sourceVersionId: "version:flag", + }); + }, + ); - expect(httpClient.get).toHaveBeenCalledTimes(1); + it.each([ + [null, { model: "Swift" }], + [[1], { model: "Swift" }], + ])( + "uses the default for a category mismatch without claiming a selected variant %#", + async (value, defaultValue) => { + const h = harness(snapshot([definition("flag", value)])); + await h.client.initialize(); + expect(h.client.getFlag({}, "flag", defaultValue)).toEqual(defaultValue); + await h.client.flush(); + expect(h.checks()).toEqual([expect.objectContaining({ key: "flag" })]); + expect(h.checks()[0]).not.toHaveProperty("evalResult"); + expect(h.checks()[0]).not.toHaveProperty("sourceVersionId"); + }, + ); + + it("keeps null as an explicit arbitrary-JSON read, including authored null", async () => { + const h = harness(snapshot([definition("flag", null)])); + await h.client.initialize(); + expect(h.client.getFlag({}, "flag", null)).toBeNull(); + expect(h.client.getFlag({}, "missing", null)).toBeNull(); + await h.client.flush(); + expect(h.checks()[0]).toMatchObject({ evalResult: "default" }); + expect(h.checks()[1]).not.toHaveProperty("evalResult"); + }); - expect(httpClient.get).toHaveBeenCalledWith( - "https://api.example.com/features/evaluated", - expectedHeaders, - API_TIMEOUT_MS, + it("keeps Boolean defaults separate from authored payloads and dependent selections", async () => { + const collection = graph(); + collection.flags[0].variants.quality = { secret: "do-not-log-payload" }; + const h = harness(collection); + await h.client.initialize(); + expect(h.client.getFlag({ company }, "model")).toBe(false); + expect(h.client.getFlag({ company }, "dependent")).toBe(true); + await h.client.flush(); + expect(h.checks()[0]).not.toHaveProperty("evalResult"); + expect(h.checks()[0]).not.toHaveProperty("sourceVersionId"); + expect(h.checks()[1]).toMatchObject({ + key: "dependent", + evalResult: "true", + }); + expect(h.logger.warn).toHaveBeenCalledWith( + expect.stringContaining("Using the default value"), + ); + expect(JSON.stringify(h.logger.warn.mock.calls)).not.toContain( + "do-not-log-payload", ); }); -}); - -describe("getFlagRemote", () => { - let client: ReflagClient; - beforeEach(async () => { - httpClient.get.mockResolvedValue({ - ok: true, - status: 200, - body: { - success: true, - remoteContextUsed: true, - features: { - flag1: { - key: "flag1", - targetingVersion: 1, - isEnabled: true, - config: { - key: "config-1", - version: 3, - default: true, - payload: { something: "else" }, - missingContextFields: ["two"], - }, - missingContextFields: ["one", "two"], - }, - }, - }, + it("returns independent mutable copies of caller defaults", async () => { + const h = harness(snapshot()); + await h.client.initialize(); + const fallback = { nested: { model: "Swift" }, items: [1] }; + const value = h.client.getFlag({}, "missing", fallback); + value.nested.model = "changed"; + value.items.push(2); + expect(fallback).toEqual({ nested: { model: "Swift" }, items: [1] }); + const frozen = Object.freeze({ model: "Swift", items: Object.freeze([1]) }); + expect(h.client.getFlag({}, "missing", frozen)).toEqual({ + model: "Swift", + items: [1], }); - - client = new ReflagClient(validOptions); }); - afterEach(() => { - httpClient.get.mockClear(); + it("validates local and remote defaults before evaluation or HTTP", async () => { + const h = harness(); + const defaultValue = { nested: undefined }; + expect(() => + Reflect.apply(h.client.getFlag, h.client, [{}, "flag", defaultValue]), + ).toThrow("JSON value"); + await expect( + Reflect.apply(h.client.getFlagRemote, h.client, ["flag", defaultValue]), + ).rejects.toThrow("JSON value"); + expect(h.httpClient.get).not.toHaveBeenCalled(); + await h.client.flush(); + expect(h.checks()).toEqual([]); }); - it("should return evaluated flag", async () => { - const result = await client.getFlagRemote("flag1", "c1", "u1", { - other: otherContext, - }); - - expect(result).toStrictEqual({ - key: "flag1", - isEnabled: true, - track: expect.any(Function), - config: { - key: "config-1", - payload: { something: "else" }, + it("applies remote defaults without authenticating a fabricated selection", async () => { + const h = harness({ + protocolVersion: 2, + flagStateVersion: 7, + flags: { + model: { + value: { model: "Reasoner" }, + variantKey: "quality", + sourceVersionId: "remote-version", + matchedRuleId: "r", + ruleResults: [], + errors: [], + }, }, }); - - expect(httpClient.get).toHaveBeenCalledTimes(1); - - expect(httpClient.get).toHaveBeenCalledWith( - `https://api.example.com/features/evaluated?${new URLSearchParams({ - contextJson: - '{"company":{"id":"u1"},"other":{"custom":"context","key":"value"},"user":{"id":"c1"}}', - key: "flag1", - })}`, - expectedHeaders, - API_TIMEOUT_MS, + expect(await h.client.getFlagRemote("model")).toBe(false); + expect( + await h.client.bindClient({}).getFlagRemote("model", { model: "Swift" }), + ).toEqual({ model: "Reasoner" }); + expect(await h.client.getFlagRemote("missing", { model: "Swift" })).toEqual( + { model: "Swift" }, ); + await h.client.flush(); + expect(h.checks()).toHaveLength(3); + expect(h.checks()[0]).not.toHaveProperty("evalResult"); + expect(h.checks()[1]).toMatchObject({ + evalResult: "quality", + sourceVersionId: "remote-version", + flagStateVersion: 7, + }); + expect(h.checks()[2]).not.toHaveProperty("sourceVersionId"); }); - it("should not try to append the context if it's empty", async () => { - await client.getFlagRemote("flag1"); - - expect(httpClient.get).toHaveBeenCalledWith( - "https://api.example.com/features/evaluated?key=flag1", - expectedHeaders, - API_TIMEOUT_MS, - ); + it("uses local defaults and overrides for offline remote reads without tracking", async () => { + const h = harness(graph(), { + offline: true, + flagOverrides: { model: { model: "Swift" } }, + }); + await h.client.initialize(); + expect( + await h.client.getFlagRemote("model", { model: "Reasoner" }), + ).toEqual({ model: "Swift" }); + expect(await h.client.bindClient({}).getFlagRemote("missing")).toBe(false); + expect(h.httpClient.get).not.toHaveBeenCalled(); + expect(h.checks()).toEqual([]); }); }); -describe("offline mode", () => { - let client: ReflagClient; - - beforeEach(async () => { - client = new ReflagClient({ - ...validOptions, - offline: true, +describe("check identity and context", () => { + it.each(["singular", "batch"])( + "records pre-initialization diagnostics at the time of a local %s read", + async (read) => { + const h = harness(graph(), { fallbackFlags: { flag: true } }); + if (read === "singular") h.client.getFlag({}, "flag"); + else h.client.getFlags({}); + await h.client.initialize(); + await h.client.flush(); + expect(h.checks()).toEqual([ + expect.objectContaining({ + key: "flag", + evalErrors: [ + expect.objectContaining({ + code: "CLIENT_NOT_INITIALIZED", + field: "", + }), + ], + }), + ]); + expect(h.checks()[0]).not.toHaveProperty("evalResult"); + expect(h.checks()[0]).not.toHaveProperty("sourceVersionId"); + }, + ); + it("does not diagnose a remote read as an uninitialized local evaluation", async () => { + const h = harness({ + protocolVersion: 2, + flagStateVersion: 1, + remoteContextUsed: true, + flags: {}, }); - await client.initialize(); + expect(await h.client.getFlagRemote("flag")).toBe(false); + await h.client.flush(); + expect(h.checks()).toHaveLength(1); + expect(h.checks()[0]).not.toHaveProperty("evalErrors"); }); - - it("should send not send or fetch anything", async () => { - client.getFlags({}); - - expect(httpClient.get).toHaveBeenCalledTimes(0); - expect(httpClient.post).toHaveBeenCalledTimes(0); + it("deduplicates equivalent normalized contexts within the check window", async () => { + const h = harness(); + await h.client.initialize(); + h.client.getFlag({ company, other: { n: 1 } }, "model", "quick"); + h.client.getFlag( + { other: { n: "1" }, company: { plan: "enterprise", id: "acme" } }, + "model", + "quick", + ); + await h.client.flush(); + expect(h.checks()).toHaveLength(1); + await vi.advanceTimersByTimeAsync( + FLAG_EVENT_RATE_LIMITER_WINDOW_SIZE_MS + 1, + ); + h.client.getFlag({ company, other: { n: 1 } }, "model", "quick"); + await h.client.flush(); + expect(h.checks()).toHaveLength(2); }); -}); - -describe("BoundReflagClient", () => { - beforeAll(() => { - const response = { - status: 200, - body: { success: true }, + it("distinguishes equal-valued variants for the same normalized context", async () => { + const flag = definition("flag", null, "first"); + flag.variants.second = null; + const response = snapshot([flag]); + const h = harness(response); + await h.client.initialize(); + h.client.getFlag({}, "flag", null); + // Simulate a new immutable accepted definition with an unchanged snapshot number. + const changed = structuredClone(response); + changed.flags[0].rules[0].result = { + type: "variant", + variantKey: "second", }; - - httpClient.post.mockResolvedValue(response); - - httpClient.get.mockResolvedValue({ - ok: true, - status: 200, - body: { - success: true, - ...flagDefinitions, - }, - }); + h.state.response = changed; + await nextRefresh(h.client); + h.client.getFlag({}, "flag", null); + await h.client.flush(); + expect(h.checks().map((event) => event.evalResult)).toEqual([ + "first", + "second", + ]); }); - const client = new ReflagClient(validOptions); - - beforeEach(async () => { - await flushPromises(); - await client.flush(); - - vi.mocked(httpClient.post).mockClear(); - client["rateLimiter"].clearStale(true); + it("includes the snapshot version when only a dependency changes", async () => { + const h = harness(); + await h.client.initialize(); + expect(h.client.getFlag({ company }, "dependent")).toBe(true); + const changed = graph(); + changed.flagStateVersion = 2; + changed.segments[0].filter = { type: "constant", value: false }; + h.state.response = changed; + await nextRefresh(h.client, 2); + expect(h.client.getFlag({ company }, "dependent")).toBe(false); + await h.client.flush(); + expect(h.checks()).toEqual([ + expect.objectContaining({ + sourceVersionId: "version:dependent", + flagStateVersion: 1, + evalResult: "true", + }), + expect.objectContaining({ + sourceVersionId: "version:dependent", + flagStateVersion: 2, + evalResult: "false", + }), + ]); }); - - it("should create a client instance", () => { - expect(client).toBeInstanceOf(ReflagClient); + it("registers a new check when only the definition version changes", async () => { + const h = harness(); + await h.client.initialize(); + h.client.getFlag({ company }, "model", "quick"); + const changed = graph(); + changed.flags[0].sourceVersionId = "updated"; + h.state.response = changed; + await nextRefresh(h.client); + h.client.getFlag({ company }, "model", "quick"); + await h.client.flush(); + expect(h.checks().map((event) => event.sourceVersionId)).toEqual([ + "version:model", + "updated", + ]); }); + it("disables both context synchronization and checks when requested", async () => { + const h = harness(); + await h.client.initialize(); + h.client.getFlag( + { company, user: { id: "u" }, enableTracking: false }, + "model", + "quick", + ); + h.client.getFlags({ company, enableTracking: false }); + await h.client.flush(); + expect(h.events()).toEqual([]); + }); + it("preserves numeric zero IDs for ordinary tracking", async () => { + const h = harness(); + await h.client.initialize(); + h.client.getFlag( + { + company: { id: 0, plan: "free" }, + user: { id: 0 }, + meta: { active: false }, + }, + "model", + "quick", + ); + await h.client.track(0, "clicked", { companyId: 0 }); + await h.client.flush(); + expect(h.events()).toContainEqual( + expect.objectContaining({ + type: "company", + companyId: 0, + userId: 0, + context: { active: false }, + }), + ); + expect(h.events()).toContainEqual( + expect.objectContaining({ type: "event", userId: 0, companyId: 0 }), + ); + }); +}); - it("should return a new client instance with merged attributes", () => { - const userOverride = { sex: "male", age: 30 }; - const companyOverride = { employees: 200, bankrupt: false }; - const otherOverride = { key: "new-value" }; - const other = { key: "value" }; - - const newClient = client - .bindClient({ - user, - company, - other, - }) - .bindClient({ - user: { id: user.id, ...userOverride }, - company: { id: company.id, ...companyOverride }, - other: otherOverride, +describe("bootstrap, bound clients, and overrides", () => { + it.each(["track", "remote"])( + "synchronizes bound attributes and association for %s-only clients", + async (operation) => { + const h = harness({ + protocolVersion: 2, + flagStateVersion: 1, + remoteContextUsed: true, + flags: {}, }); - - expect(newClient["_options"]).toEqual({ - user: { ...user, ...userOverride }, - company: { ...company, ...companyOverride }, - other: { ...other, ...otherOverride }, + const bound = h.client.bindClient({ + user: { id: 0, name: "User" }, + company: { id: "acme", plan: "enterprise" }, + meta: { active: false }, + }); + if (operation === "track") await bound.track("clicked"); + else await bound.getFlagsRemote(); + await bound.flush(); + expect(h.events()).toContainEqual({ + type: "user", + userId: 0, + attributes: { name: "User" }, + context: { active: false }, + }); + expect(h.events()).toContainEqual({ + type: "company", + companyId: "acme", + userId: 0, + attributes: { plan: "enterprise" }, + context: { active: false }, + }); + expect(h.checks()).toEqual([]); + expect(h.httpClient.get).toHaveBeenCalledTimes( + operation === "remote" ? 1 : 0, + ); + }, + ); + it("synchronizes newly merged bindings without a local flag read", async () => { + const h = harness(); + h.client.bindClient({ enableTracking: false }).bindClient({ + user: { id: "u", name: "User" }, + company, enableTracking: true, }); + await h.client.flush(); + expect(h.events()).toContainEqual( + expect.objectContaining({ + type: "company", + companyId: "acme", + userId: "u", + }), + ); + expect(h.checks()).toEqual([]); + }); + it.each(["offline", "tracking-disabled"])( + "does not synchronize a binding when %s", + async (guard) => { + const h = harness(graph(), { offline: guard === "offline" }); + h.client.bindClient({ + user: { id: "u" }, + company, + enableTracking: guard !== "tracking-disabled", + }); + await h.client.flush(); + expect(h.events()).toEqual([]); + expect(h.httpClient.get).not.toHaveBeenCalled(); + }, + ); + it("logs asynchronous bound context synchronization failures", async () => { + const h = harness(); + const error = new Error("user update failed"); + vi.spyOn(h.client, "updateUser").mockRejectedValue(error); + expect(() => h.client.bindClient({ user: { id: "u" } })).not.toThrow(); + await vi.advanceTimersByTimeAsync(0); + expect(h.logger.error).toHaveBeenCalledWith( + "failed to synchronize context", + error, + ); + }); + it.each([ + [undefined, "acme"], + [0, 0], + ["override", "override"], + ] as const)( + "resolves optional bound tracking company %j to %j", + async (companyId, expected) => { + const h = harness(); + const bound = h.client.bindClient({ user: { id: 0 }, company }); + await bound.track("clicked", { companyId }); + await bound.flush(); + expect(h.events().filter((event) => event.type === "event")).toEqual([ + expect.objectContaining({ + userId: 0, + companyId: expected, + event: "clicked", + }), + ]); + }, + ); + it("bootstraps selections and version without registering checks", async () => { + const h = harness(); + await h.client.initialize(); + const bootstrap = h.client.getFlagsForBootstrap({ + company, + other: { raw: 42 }, + }); + expect(bootstrap).toMatchObject({ + protocolVersion: 2, + flagStateVersion: 1, + context: { company, other: { raw: 42 } }, + flags: { + model: { resolved: true, value: "quality", variantKey: "quality" }, + }, + }); + await h.client.flush(); + expect(h.checks()).toEqual([]); }); - - it("should preserve existing user and company when omitted on rebind", () => { - const reboundClient = client - .bindClient({ user, company }) - .bindClient({ other: otherContext }); - - expect(reboundClient["_options"]).toEqual({ - user, + it("binds and merges context while preserving direct values and ordinary track", async () => { + const h = harness(); + await h.client.initialize(); + const bound = h.client + .bindClient({ company: { id: "acme", plan: "free" }, user: { id: 0 } }) + .bindClient({ company }); + expect(bound.getFlag("model", "quick")).toBe("quality"); + expect(bound.getFlags()).toEqual({ model: "quality", dependent: true }); + expect(bound.getFlagsForBootstrap().context).toMatchObject({ + user: { id: 0 }, company, - other: otherContext, - enableTracking: true, }); + await bound.track("selected"); + await bound.flush(); + expect(h.events()).toContainEqual( + expect.objectContaining({ + type: "event", + userId: 0, + companyId: "acme", + event: "selected", + }), + ); }); - - it("should preserve existing other context when omitted on rebind", () => { - const reboundClient = client - .bindClient({ other: otherContext }) - .bindClient({ user }); - - expect(reboundClient["_options"]).toEqual({ - user, - other: otherContext, - enableTracking: true, + it.each([false, null, { payload: 1 }, [1, 2], "override"])( + "returns a direct override %j without claiming an authored selection", + async (value) => { + const h = harness(graph(), { flagOverrides: { model: value } }); + await h.client.initialize(); + expect(h.client.getFlag({ company }, "model", null)).toEqual(value); + // Overrides remain post-evaluation; they do not rewrite dependency results. + expect(h.client.getFlag({ company }, "dependent")).toBe(true); + await h.client.flush(); + expect(h.checks()[0]).not.toHaveProperty("evalResult"); + expect(h.checks()[0]).not.toHaveProperty("sourceVersionId"); + }, + ); + it("retains explicit tracking disablement when merged options are undefined", async () => { + const h = harness(); + await h.client.initialize(); + const bound = h.client + .bindClient({ company, enableTracking: false }) + .bindClient({ enableTracking: undefined, other: { n: 1 } }); + expect(bound.getFlag("model", "quick")).toBe("quality"); + await bound.flush(); + expect(h.events()).toEqual([]); + }); + it("supports context functions and disposable override layers", async () => { + const h = harness(graph(), { + flagOverrides: (context) => ({ + model: context.company?.id === "acme" ? 1 : 0, + }), + }); + await h.client.initialize(); + const pop = h.client.pushFlagOverrides({ model: null, extra: false }); + expect(h.client.getFlags({ company, enableTracking: false })).toMatchObject( + { model: null, extra: false }, + ); + pop(); + pop(); + expect(h.client.getFlag({ company }, "model", 0)).toBe(1); + h.client.setFlagOverrides({ model: "base" }); + expect(h.client.getFlag({ company }, "model", "quick")).toBe("base"); + h.client.clearFlagOverrides(); + expect(h.client.getFlag({ company }, "model", "quick")).toBe("quality"); + }); + it("keeps prototype-like override keys", async () => { + const h = harness(snapshot(), { + flagOverrides: JSON.parse('{"__proto__":false}'), }); + await h.client.initialize(); + expect(h.client.getFlag({}, "__proto__")).toBe(false); }); + it("works offline without fetching, checks, or ordinary tracking", async () => { + const h = harness(graph(), { + offline: true, + flagOverrides: { model: null }, + }); + await h.client.initialize(); + expect(h.client.getFlag({ company }, "model", null)).toBeNull(); + await h.client.track(0, "event"); + await h.client.flush(); + expect(h.httpClient.get).not.toHaveBeenCalled(); + expect(h.events()).toEqual([]); + }); +}); - it("should allow using expected methods when bound to user", async () => { - const boundClient = client.bindClient({ user }); - expect(boundClient.user).toEqual(user); - - expect( - boundClient.bindClient({ other: otherContext }).otherContext, - ).toEqual(otherContext); - - boundClient.getFlags(); - - await boundClient.track("flag"); - await client.flush(); +describe("configured flag-fetch retries", () => { + it.each(["collection", "remote"] as const)( + "uses the configured retry count for %s requests", + async (endpoint) => { + const h = harness(graph(), { flagsFetchRetries: 2 }); + const error = new Error("network failure"); + h.httpClient.get.mockRejectedValue(error); + const pending = + endpoint === "collection" + ? h.client.initialize() + : h.client.getFlagRemote("missing"); + await vi.advanceTimersByTimeAsync(10000); + await pending; + + expect(h.httpClient.get).toHaveBeenCalledTimes(3); + expect(h.logger.warn).toHaveBeenCalledTimes(2); + expect(h.logger.debug).toHaveBeenCalledWith( + expect.stringContaining("failed with error after 2 retries"), + error, + ); + }, + ); +}); - expect(httpClient.post).toHaveBeenCalledWith( - BULK_ENDPOINT, - expectedHeaders, - [ - expect.objectContaining({ type: "user" }), - { - event: "flag", - type: "event", - userId: "user123", - }, - ], +describe("atomic refresh and complete fallback snapshots", () => { + it("replaces flags, segments, and version together", async () => { + const h = harness(); + await h.client.initialize(); + const changed = graph(); + changed.flagStateVersion = 2; + changed.segments[0].filter = { type: "constant", value: false }; + changed.flags[0].variants.quick = "new"; + h.state.response = changed; + await nextRefresh(h.client, 2); + expect(h.client.getFlags({ company, enableTracking: false })).toEqual({ + model: "new", + dependent: false, + }); + expect(h.client.getFlagsForBootstrap({ company }).flagStateVersion).toBe(2); + expect(h.httpClient.get).toHaveBeenLastCalledWith( + "https://api.example.com/flags?waitForVersion=2", + expect.anything(), + expect.any(Number), ); }); - - it("should add company ID from the context if not explicitly supplied", async () => { - const boundClient = client.bindClient({ user, company }); - - boundClient.getFlags(); - await boundClient.track("flag"); - - await client.flush(); - - expect(httpClient.post).toHaveBeenCalledWith( - BULK_ENDPOINT, - expectedHeaders, - [ - expect.objectContaining({ type: "company" }), - expect.objectContaining({ type: "user" }), + it("rejects stale responses before saving them to a fallback provider", async () => { + const save = vi.fn(); + const h = harness(snapshot([], [], 5), { + flagsFallbackProvider: { load: vi.fn(), save }, + }); + await h.client.initialize(); + h.state.response = graph(); + await nextRefresh(h.client); + await h.client.flush(); + expect(h.client.getFlagDefinitions()).toEqual({ flags: [], segments: [] }); + expect(h.client.getFlagsForBootstrap({}).flagStateVersion).toBe(5); + expect(save).toHaveBeenCalledTimes(1); + }); + it.each([ + { protocolVersion: 2, flagStateVersion: 2, flags: [] }, + { ...snapshot(), flagStateVersion: -1 }, + { ...snapshot(), protocolVersion: 1 }, + snapshot( + [definition("bad", 1)], + [{ key: "segment", filter: { type: "segment", key: "missing" } }], + 2, + ), + ])( + "retains a last-known-good graph after invalid refresh %#", + async (invalid) => { + const h = harness(); + await h.client.initialize(); + h.state.response = invalid; + await nextRefresh(h.client); + expect( + h.client.getFlag({ company, enableTracking: false }, "dependent"), + ).toBe(true); + expect(h.client.getFlagsForBootstrap({ company }).flagStateVersion).toBe( + 1, + ); + }, + ); + it("does not expose mutable definitions or its prepared evaluator", async () => { + const h = harness(); + await h.client.initialize(); + const definitions = h.client.getFlagDefinitions(); + definitions.segments.length = 0; + expect( + h.client.getFlag({ company, enableTracking: false }, "dependent"), + ).toBe(true); + expect(definitions).not.toHaveProperty("evaluator"); + }); + it("persists and restores the full graph and snapshot version", async () => { + let saved: FlagsFallbackSnapshot | undefined; + const provider = { + load: vi.fn(async () => saved), + save: vi.fn(async (_context: unknown, next: FlagsFallbackSnapshot) => { + saved = next; + }), + }; + const live = harness(graph(), { flagsFallbackProvider: provider }); + await live.client.initialize(); + await live.client.flush(); + expect(saved).toMatchObject({ + version: 2, + flagStateVersion: 1, + flags: graph().flags, + segments: graph().segments, + }); + const fallback = harness(undefined, { flagsFallbackProvider: provider }); + fallback.state.response = undefined; + await fallback.client.initialize(); + expect(fallback.client.getFlag({ company }, "dependent")).toBe(true); + await fallback.client.flush(); + expect(fallback.checks()[0]).toMatchObject({ + evalResult: "true", + sourceVersionId: "version:dependent", + flagStateVersion: 1, + }); + expect(provider.save).toHaveBeenCalledTimes(1); + }); + it.each([1, 2])( + "rejects incomplete or legacy fallback snapshots (version %i)", + async (version) => { + const h = harness( + {}, { - companyId: "company123", - event: "flag", - type: "event", - userId: "user123", + flagsFallbackProvider: { + load: vi.fn( + async () => + ({ + version, + savedAt: new Date().toISOString(), + flags: graph().flags, + }) as FlagsFallbackSnapshot, + ), + save: vi.fn(), + }, }, - ], + ); + await h.client.initialize(); + expect(h.client.getFlagDefinitions()).toEqual({ + flags: [], + segments: [], + }); + }, + ); + it("does not reload stale fallback state after a successful live refresh", async () => { + const load = vi.fn(); + const h = harness(graph(), { + flagsFallbackProvider: { load, save: vi.fn() }, + }); + await h.client.initialize(); + h.state.response = {}; + await nextRefresh(h.client); + expect(load).not.toHaveBeenCalled(); + }); + it("uses static JSON fallback values without an authored variant claim", async () => { + const h = harness( + {}, + { + flagsFallbackProvider: fallbackProviders.static({ + flags: { model: null, bool: false }, + }), + }, ); + await h.client.initialize(); + expect(h.client.getFlag({ company }, "model", null)).toBeNull(); + expect(h.client.getFlag({}, "bool")).toBe(false); + await h.client.flush(); + for (const event of h.checks()) { + expect(event).not.toHaveProperty("evalResult"); + expect(event).not.toHaveProperty("sourceVersionId"); + } }); - - it("should disable tracking within the client if `enableTracking` is `false`", async () => { - const boundClient = client.bindClient({ - user, - company, - enableTracking: false, - }); - - const { track } = boundClient.getFlag("flag2"); - await track(); - await boundClient.track("flag1"); - - await client.flush(); - - expect(httpClient.post).not.toHaveBeenCalled(); + it("uses value-only configured fallbacks without an authored variant claim", async () => { + const h = harness({}, { fallbackFlags: { flag: false } }); + await h.client.initialize(); + expect(h.client.getFlag({}, "flag")).toBe(false); + await h.client.flush(); + expect(h.checks()[0]).not.toHaveProperty("evalResult"); }); - - it("should allow using expected methods", async () => { - const boundClient = client.bindClient({ other: { key: "value" } }); - expect(boundClient.otherContext).toEqual({ - key: "value", + it("serializes fallback saves", async () => { + let finish!: () => void; + const pending = new Promise((resolve) => { + finish = resolve; + }); + const save = vi + .fn() + .mockImplementationOnce(() => pending) + .mockResolvedValue(undefined); + const h = harness(graph(), { + flagsFallbackProvider: { load: vi.fn(), save }, + }); + await h.client.initialize(); + h.state.response = snapshot([], [], 2); + await nextRefresh(h.client, 2); + expect(save).toHaveBeenCalledTimes(1); + finish(); + await h.client.flush(); + expect(save).toHaveBeenCalledTimes(2); + expect(save.mock.calls[1][1]).toMatchObject({ + flagStateVersion: 2, + flags: [], + segments: [], }); - - await client.initialize(); - - boundClient.getFlags(); - boundClient.getFlag("flag1"); - - await boundClient.flush(); }); +}); - it("should return raw flags for bootstrap from bound client", async () => { - // Ensure client is properly initialized - await client.initialize(); - const boundClient = client.bindClient({ - user, - company, - other: otherContext, - enableTracking: true, +describe("remote values", () => { + it("returns direct values, preserves explicit zero IDs, and registers selected keys", async () => { + const result = { + value: null, + variantKey: "quality", + sourceVersionId: "remote-version", + matchedRuleId: "r", + ruleResults: [], + errors: [], + }; + const h = harness({ + protocolVersion: 2, + flagStateVersion: 9, + flags: { model: result }, + remoteContextUsed: false, + }); + expect(await h.client.getFlagRemote("model", null, 0, 0)).toBeNull(); + await h.client.flush(); + expect(h.checks()[0]).toMatchObject({ + evalResult: "quality", + sourceVersionId: "remote-version", + flagStateVersion: 9, + evalContext: { user: { id: 0 }, company: { id: 0 } }, + }); + const url = new URL(h.httpClient.get.mock.calls[0][0]); + expect(url.pathname).toBe("/flags/evaluated"); + expect(JSON.parse(url.searchParams.get("contextJson")!)).toEqual({ + user: { id: 0 }, + company: { id: 0 }, }); - - const result = boundClient.getFlagsForBootstrap(); - - expect(result).toStrictEqual({ - context: { - user, - company, - other: otherContext, - enableTracking: true, - }, + }); + it("honors bound enableTracking=false for remote calls", async () => { + const h = harness({ + protocolVersion: 2, + flagStateVersion: 1, flags: { - flag1: { - key: "flag1", - isEnabled: true, - targetingVersion: 1, - config: { - key: "config-1", - payload: { - something: "else", - }, - targetingVersion: 1, - missingContextFields: [], - ruleEvaluationResults: [true], - }, - ruleEvaluationResults: [true], - missingContextFields: [], - }, - flag2: { - key: "flag2", - isEnabled: false, - targetingVersion: 2, - config: { - key: undefined, - payload: undefined, - targetingVersion: undefined, - missingContextFields: [], - ruleEvaluationResults: [], - }, - ruleEvaluationResults: [false], - missingContextFields: ["attributeKey"], - evaluationErrors: [missingContextFieldError("attributeKey")], + model: { + value: false, + variantKey: "false", + sourceVersionId: "v", + matchedRuleId: "r", + ruleResults: [], + errors: [], }, }, - flagStateVersion: 1, }); - - // Should not have track function like regular getFlags - expect(result.flags.flag1).not.toHaveProperty("track"); - expect(result.flags.flag2).not.toHaveProperty("track"); + expect( + await h.client + .bindClient({ company, enableTracking: false }) + .getFlagRemote("model"), + ).toBe(false); + await h.client.flush(); + expect(h.checks()).toEqual([]); }); - - describe("getFlagRemote/getFlagsRemote", () => { - beforeEach(async () => { - httpClient.get.mockClear(); - httpClient.get.mockResolvedValue({ - ok: true, - status: 200, - body: { - success: true, - remoteContextUsed: true, - features: { - flag1: { - key: "flag1", - targetingVersion: 1, - isEnabled: true, - config: { - key: "config-1", - version: 3, - default: true, - payload: { something: "else" }, - missingContextFields: ["else"], - }, - }, - flag2: { - key: "flag2", - targetingVersion: 2, - isEnabled: false, - missingContextFields: ["something"], - }, - }, - }, - }); - }); - - it("should return evaluated flags", async () => { - const boundClient = client.bindClient({ - user, - company, - other: otherContext, - }); - - const result = await boundClient.getFlagsRemote(); - - expect(result).toStrictEqual({ - flag1: { - key: "flag1", - isEnabled: true, - config: { key: "config-1", payload: { something: "else" } }, - track: expect.any(Function), - }, - flag2: { - key: "flag2", - isEnabled: false, - config: { key: undefined, payload: undefined }, - track: expect.any(Function), + it.each([ + { ruleResults: [null] }, + { errors: [null] }, + { sourceVersionId: "" }, + { variantKey: "" }, + ])("rejects malformed remote selection metadata %#", async (invalid) => { + const h = harness({ + protocolVersion: 2, + flagStateVersion: 1, + flags: { + model: { + value: false, + variantKey: "false", + sourceVersionId: "v", + matchedRuleId: "r", + ruleResults: [], + errors: [], + ...invalid, }, - }); - - expect(httpClient.get).toHaveBeenCalledTimes(1); - - expect(httpClient.get).toHaveBeenCalledWith( - `https://api.example.com/features/evaluated?${new URLSearchParams({ - contextJson: - '{"company":{"employees":100,"id":"company123","name":"Acme Inc."},"other":{"custom":"context","key":"value"},"user":{"age":1,"id":"user123","name":"John"}}', - })}`, - expectedHeaders, - API_TIMEOUT_MS, - ); - }); - - it("should return evaluated flag", async () => { - const boundClient = client.bindClient({ - user, - company, - other: otherContext, - }); - - const result = await boundClient.getFlagRemote("flag1"); - - expect(result).toStrictEqual({ - key: "flag1", - isEnabled: true, - config: { key: "config-1", payload: { something: "else" } }, - track: expect.any(Function), - }); - - expect(httpClient.get).toHaveBeenCalledTimes(1); - - expect(httpClient.get).toHaveBeenCalledWith( - `https://api.example.com/features/evaluated?${new URLSearchParams({ - contextJson: - '{"company":{"employees":100,"id":"company123","name":"Acme Inc."},"other":{"custom":"context","key":"value"},"user":{"age":1,"id":"user123","name":"John"}}', - key: "flag1", - })}`, - expectedHeaders, - API_TIMEOUT_MS, - ); + }, }); + expect(await h.client.getFlagRemote("model")).toBe(false); + await h.client.flush(); + expect(h.checks()).toEqual([expect.objectContaining({ key: "model" })]); + expect(h.checks()[0]).not.toHaveProperty("evalResult"); + expect(h.checks()[0]).not.toHaveProperty("sourceVersionId"); + }); + it("returns false without fabricating a remote selection after failure", async () => { + const h = harness({}); + expect(await h.client.getFlagRemote("missing")).toBe(false); + await h.client.flush(); + expect(h.checks()).toEqual([expect.objectContaining({ key: "missing" })]); + expect(h.checks()[0]).not.toHaveProperty("evalResult"); + expect(h.checks()[0]).not.toHaveProperty("sourceVersionId"); }); }); diff --git a/packages/node-sdk/test/fixtures.ts b/packages/node-sdk/test/fixtures.ts new file mode 100644 index 000000000..c290aaf07 --- /dev/null +++ b/packages/node-sdk/test/fixtures.ts @@ -0,0 +1,62 @@ +import type { + FlagCollection, + FlagDefinition, + FlagValue, + FlagsAPIResponse, +} from "../src"; + +export function definition( + key: string, + value: FlagValue, + variantKey = "default", +): FlagDefinition { + return { + key, + sourceVersionId: `version:${key}`, + variants: { [variantKey]: value }, + rules: [ + { + id: `default:${key}`, + filter: { type: "constant", value: true }, + result: { type: "variant", variantKey }, + }, + ], + }; +} +export function snapshot( + flags: FlagDefinition[] = [], + segments: FlagCollection["segments"] = [], + flagStateVersion = 1, +): FlagsAPIResponse { + return { protocolVersion: 2, flagStateVersion, flags, segments }; +} +export function graph(): FlagsAPIResponse { + const model = definition("model", "quick", "quick"); + model.variants.quality = "quality"; + model.rules.unshift({ + id: "enterprise", + filter: { type: "segment", key: "enterprise" }, + result: { type: "variant", variantKey: "quality" }, + }); + const dependent = definition("dependent", false, "false"); + dependent.variants.true = true; + dependent.rules.unshift({ + id: "quality-model", + filter: { type: "flag", key: "model", variantKey: "quality" }, + result: { type: "variant", variantKey: "true" }, + }); + return snapshot( + [model, dependent], + [ + { + key: "enterprise", + filter: { + type: "context", + field: "company.plan", + operator: "IS", + values: ["enterprise"], + }, + }, + ], + ); +} diff --git a/packages/node-sdk/test/flag-definitions.test.ts b/packages/node-sdk/test/flag-definitions.test.ts new file mode 100644 index 000000000..7a66156fc --- /dev/null +++ b/packages/node-sdk/test/flag-definitions.test.ts @@ -0,0 +1,170 @@ +import { describe, expect, it } from "vitest"; + +import { isFlagValue, prepareFlagCollection } from "../src/flag-definitions"; +import { definition, graph, snapshot } from "./fixtures"; + +describe("collection preparation", () => { + it("owns complete reference definitions before preparing evaluation", () => { + const original = graph(); + const collection = prepareFlagCollection(original); + expect(collection.flags).toEqual(original.flags); + expect(collection.segments).toEqual(original.segments); + original.segments[0].filter = { type: "constant", value: false }; + expect( + collection.evaluator.evaluateFlag( + { company: { plan: "enterprise" } }, + "dependent", + ).value, + ).toBe(true); + }); + it.each([ + undefined, + null, + {}, + { flags: [] }, + { flags: {}, segments: [] }, + { flags: [], segments: {} }, + { flags: [{ key: "invalid" }], segments: [] }, + snapshot([definition("duplicate", true), definition("duplicate", false)]), + snapshot([], [{ key: "cycle", filter: { type: "segment", key: "cycle" } }]), + snapshot( + [], + [ + { + key: "missing", + filter: { type: "flag", key: "absent", variantKey: "true" }, + }, + ], + ), + ])("rejects malformed/incomplete graphs %# before caching them", (value) => + expect(() => prepareFlagCollection(value)).toThrow(), + ); + it.each([ + { type: "group", operator: "xor", filters: [] }, + { type: "context", field: "x", operator: "IS", values: [1] }, + { type: "context", field: "x", operator: "UNKNOWN" }, + { + type: "rolloutPercentage", + key: "x", + partialRolloutAttribute: "id", + partialRolloutThreshold: NaN, + }, + { type: "segment", key: "absent" }, + { type: "flag", key: "dependent", variantKey: "absent" }, + ])("rejects invalid filter %#", (filter) => { + const value = graph(); + value.flags[0].rules[0].filter = filter as never; + expect(() => prepareFlagCollection(value)).toThrow(); + }); + it.each([ + { type: "variant", variantKey: "absent" }, + { + type: "percentageDistribution", + key: "d", + attribute: "id", + allocations: [ + { + percentage: 99, + destination: { type: "variant", variantKey: "default" }, + }, + ], + }, + { + type: "percentageDistribution", + key: "d", + attribute: "id", + allocations: [ + { + percentage: -1, + destination: { type: "variant", variantKey: "default" }, + }, + { percentage: 101, destination: { type: "nextRule" } }, + ], + }, + ])("rejects invalid rule results %#", (result) => { + const value = snapshot([definition("a", true)]); + value.flags[0].rules.unshift({ + ...value.flags[0].rules[0], + id: "invalid", + result: result as never, + }); + expect(() => prepareFlagCollection(value)).toThrow(); + }); + it.each([ + [33.333, 33.333, 33.334], + [12.345, 87.655], + [0, 0.001, 99.999], + [0.29, 99.71], + ])("accepts thousandth-percent allocations %j", (...percentages) => { + const value = snapshot([ + definition("a", true), + definition("unrelated", false), + ]); + value.flags[0].rules.unshift({ + id: "split", + filter: { type: "constant", value: true }, + result: { + type: "percentageDistribution", + key: "split", + attribute: "company.id", + allocations: percentages.map((percentage) => ({ + percentage, + destination: { type: "variant", variantKey: "default" }, + })), + }, + }); + const prepared = prepareFlagCollection(value); + const result = prepared.evaluator.evaluateAll({ company: { id: "acme" } }); + expect(result.flags.a).toMatchObject({ + resolved: true, + value: true, + errors: [], + }); + expect(result.flags.unrelated).toMatchObject({ + resolved: true, + value: false, + }); + }); + it.each([ + [33.3333, 33.3333, 33.3334], + [50.0001, 49.9999], + [33.333, 33.333, 33.333], + [NaN, 100], + [Infinity, 0], + ])("rejects invalid fractional allocations %j", (...percentages) => { + const value = snapshot([definition("a", true)]); + value.flags[0].rules.unshift({ + id: "split", + filter: { type: "constant", value: true }, + result: { + type: "percentageDistribution", + key: "split", + attribute: "company.id", + allocations: percentages.map((percentage) => ({ + percentage, + destination: { type: "variant", variantKey: "default" }, + })), + }, + }); + expect(() => prepareFlagCollection(value)).toThrow("invalid compiled rule"); + }); + it("requires a fixed catch-all and unique rule identities", () => { + const value = graph(); + value.flags[0].rules.pop(); + expect(() => prepareFlagCollection(value)).toThrow(); + const duplicate = graph(); + duplicate.flags[0].rules[0].id = duplicate.flags[0].rules[1].id; + expect(() => prepareFlagCollection(duplicate)).toThrow(); + }); + it.each([undefined, NaN, Infinity, 1n, () => true, new Date(), new Map()])( + "rejects non-JSON values %#", + (value) => expect(isFlagValue(value)).toBe(false), + ); + it("rejects cycles but accepts shared JSON subobjects", () => { + const cyclic: Record = {}; + cyclic.self = cyclic; + expect(isFlagValue(cyclic)).toBe(false); + const shared = { enabled: false }; + expect(isFlagValue({ a: shared, b: shared })).toBe(true); + }); +}); diff --git a/packages/node-sdk/test/flags-revalidation.test.ts b/packages/node-sdk/test/flags-revalidation.test.ts index 7483d79f4..10d37cd40 100644 --- a/packages/node-sdk/test/flags-revalidation.test.ts +++ b/packages/node-sdk/test/flags-revalidation.test.ts @@ -7,22 +7,11 @@ import type { FlagsAPIResponse, FlagsFallbackSnapshot, } from "../src/types"; +import { definition, snapshot as collection } from "./fixtures"; const etag = 'W/"flags-v1"'; const notModified = { ok: false, status: 304, body: undefined }; -const definitions: FlagsAPIResponse = { - flagStateVersion: 1, - features: [ - { - key: "flag", - description: null, - targeting: { - version: 1, - rules: [{ filter: { type: "constant", value: true } }], - }, - }, - ], -}; +const definitions: FlagsAPIResponse = collection([definition("flag", true)]); function modified(version = 1, responseETag: string | undefined = etag) { return { @@ -96,16 +85,7 @@ describe("flag-definition revalidation", () => { ...modified(2, '"flags-v2"'), body: { success: true, - flagStateVersion: 2, - features: [ - { - ...definitions.features[0], - targeting: { - version: 2, - rules: [{ filter: { type: "constant", value: false } }], - }, - }, - ], + ...collection([definition("flag", false)], [], 2), }, }); const client = createClient({ flagsFallbackProvider: provider }); @@ -132,13 +112,13 @@ describe("flag-definition revalidation", () => { "If-None-Match": etag, }); expect(requestHeaders(3)).toEqual(requestHeaders(2)); - expect(client["_config"].headers).not.toHaveProperty("If-None-Match"); + expect(client["config"].headers).not.toHaveProperty("If-None-Match"); await refresh(client); expect(cache.get()).not.toBe(initialDefinitions); expect(cache.getFlagStateVersion()).toBe(2); expect(cache.getETag()).toBe('"flags-v2"'); - expect(client.getFlag({}, "flag").isEnabled).toBe(false); + expect(client.getFlag({}, "flag")).toBe(false); expect(provider.save).toHaveBeenCalledTimes(2); }); @@ -154,7 +134,7 @@ describe("flag-definition revalidation", () => { const client = createClient({ flagsFallbackProvider: provider }); await client.initialize(); - expect(client.getFlag({}, "flag").isEnabled).toBe(true); + expect(client.getFlag({}, "flag")).toBe(true); expect(client["flagsCache"].getETag()).toBeUndefined(); expect(provider.save).toHaveBeenCalledTimes(1); expect(logger.error).toHaveBeenCalledWith( @@ -182,7 +162,7 @@ describe("flag-definition revalidation", () => { const client = createClient({ flagsFallbackProvider: provider }); await client.initialize(); - expect(client.getFlag({}, "flag").isEnabled).toBe(true); + expect(client.getFlag({}, "flag")).toBe(true); expect(client["flagsCache"].getETag()).toBeUndefined(); completeSave(); await vi.advanceTimersByTimeAsync(0); @@ -214,14 +194,14 @@ describe("flag-definition revalidation", () => { .mockResolvedValueOnce(modified()) .mockResolvedValueOnce({ ...modified(2, '"v2"'), - body: { success: true, flagStateVersion: 2, features: [] }, + body: { success: true, ...collection([], [], 2) }, }) .mockResolvedValue(notModified); const client = createClient({ flagsFallbackProvider: provider }); await client.initialize(); await refresh(client); - expect(client["flagsCache"].get()).toEqual([]); + expect(client["flagsCache"].get()?.flags).toEqual([]); expect(client["flagsCache"].getFlagStateVersion()).toBe(2); expect(client["flagsCache"].getETag()).toBeUndefined(); expect(provider.save).toHaveBeenCalledTimes(1); @@ -285,7 +265,7 @@ describe("flag-definition revalidation", () => { httpClient.get .mockResolvedValueOnce({ ...modified(), - body: { success: true, flagStateVersion: 1, features: [] }, + body: { success: true, ...collection() }, }) .mockResolvedValueOnce(notModified); const client = createClient(); @@ -293,7 +273,7 @@ describe("flag-definition revalidation", () => { const snapshot = client["flagsCache"].get(); await refresh(client); - expect(snapshot).toEqual([]); + expect(snapshot?.flags).toEqual([]); expect(client["flagsCache"].get()).toBe(snapshot); expect(requestHeaders(2)["If-None-Match"]).toBe(etag); }); @@ -322,10 +302,10 @@ describe("flag-definition revalidation", () => { expect(client["flagsCache"].get()).toBe(snapshot); expect(fetch).toHaveBeenNthCalledWith( 2, - "https://api.example.com/features", + "https://api.example.com/flags", expect.objectContaining({ cache: "no-cache", - headers: { ...client["_config"].headers, "If-None-Match": etag }, + headers: { ...client["config"].headers, "If-None-Match": etag }, }), ); await refresh(client); @@ -338,7 +318,13 @@ describe("flag-definition revalidation", () => { httpClient.get.mockResolvedValueOnce(modified()).mockResolvedValueOnce({ ok: true, status: 200, - body: { success: true, features: {}, remoteContextUsed: false }, + body: { + success: true, + protocolVersion: 2, + flagStateVersion: 1, + flags: {}, + remoteContextUsed: false, + }, }); const client = createClient(); await client.initialize(); @@ -346,7 +332,7 @@ describe("flag-definition revalidation", () => { expect(httpClient.get).toHaveBeenNthCalledWith( 2, - "https://api.example.com/features/evaluated", + "https://api.example.com/flags/evaluated?contextJson=%7B%7D", requestHeaders(1), API_TIMEOUT_MS, ); @@ -365,7 +351,7 @@ describe("flag-definition revalidation", () => { expect(httpClient.get).toHaveBeenCalledTimes(2); expect(requestHeaders(2)).not.toHaveProperty("If-None-Match"); - expect(client.getFlag({}, "flag").isEnabled).toBe(true); + expect(client.getFlag({}, "flag")).toBe(true); }); it("clears the old ETag when an accepted replacement omits it", async () => { @@ -393,7 +379,7 @@ describe("flag-definition revalidation", () => { .mockResolvedValueOnce(current) .mockResolvedValueOnce({ ...modified(1, '"v1"'), - body: { success: true, flagStateVersion: 1, features: [] }, + body: { success: true, ...collection() }, }) .mockResolvedValueOnce(notModified); const client = createClient({ flagsFallbackProvider: provider }); @@ -407,9 +393,7 @@ describe("flag-definition revalidation", () => { expect(client["flagsCache"].getETag()).toBe('"v2"'); expect(requestHeaders(3)["If-None-Match"]).toBe('"v2"'); expect(provider.save).toHaveBeenCalledTimes(1); - expect(provider.save.mock.calls[0]?.[1].flags).toEqual( - current.body.features, - ); + expect(provider.save.mock.calls[0]?.[1].flags).toEqual(current.body.flags); }); it.each([ @@ -418,7 +402,7 @@ describe("flag-definition revalidation", () => { "malformed definitions", { ...modified(2, '"invalid"'), - body: { success: true, flagStateVersion: 2, features: null }, + body: { success: true, ...collection([], [], 2), flags: null }, }, ], ["an older version", modified(0, '"older"')], @@ -456,7 +440,7 @@ describe("flag-definition revalidation", () => { await refresh(client); expect(requestHeaders(3)["If-None-Match"]).toBe(etag); - expect(client.getFlag({}, "flag").isEnabled).toBe(true); + expect(client.getFlag({}, "flag")).toBe(true); }); it("isolates validators between clients with different credentials", async () => { @@ -493,7 +477,7 @@ describe("flag-definition revalidation", () => { expect(httpClient.get).toHaveBeenCalledTimes(2); expect(requestHeaders(1)).not.toHaveProperty("If-None-Match"); expect(requestHeaders(2)).not.toHaveProperty("If-None-Match"); - expect(client.getFlag({}, "flag").isEnabled).toBe(true); + expect(client.getFlag({}, "flag")).toBe(true); expect(logger.warn).not.toHaveBeenCalled(); }); @@ -525,9 +509,11 @@ describe("flag-definition revalidation", () => { it("fetches unconditionally after loading fallback definitions", async () => { const provider = { load: vi.fn().mockResolvedValue({ - version: 1, + version: 2, savedAt: "2025-12-31T00:00:00Z", - flags: definitions.features, + flags: definitions.flags, + segments: definitions.segments, + flagStateVersion: 1, }), save: vi.fn().mockResolvedValue(undefined), }; @@ -564,7 +550,7 @@ describe("flag-definition revalidation", () => { expect(httpClient.get).toHaveBeenNthCalledWith( 2, - "https://api.example.com/features?waitForVersion=2", + "https://api.example.com/flags?waitForVersion=2", requestHeaders(1), API_TIMEOUT_MS, ); diff --git a/packages/node-sdk/test/flagsFallbackProvider.test.ts b/packages/node-sdk/test/flagsFallbackProvider.test.ts index c3d4382f7..05af5a613 100644 --- a/packages/node-sdk/test/flagsFallbackProvider.test.ts +++ b/packages/node-sdk/test/flagsFallbackProvider.test.ts @@ -4,420 +4,219 @@ import path from "path"; import { afterEach, describe, expect, it, vi } from "vitest"; -import type { FlagsFallbackProviderContext } from "../src"; -import { fallbackProviders } from "../src"; +import { fallbackProviders, type FlagsFallbackSnapshot } from "../src"; +import { graph } from "./fixtures"; -const context: FlagsFallbackProviderContext = { - secretKeyHash: "abc123def456ghi789", -}; - -const snapshot = { - version: 1 as const, +const context = { secretKeyHash: "abc123def456ghi789" }; +const snapshot: FlagsFallbackSnapshot = { + version: 2, savedAt: "2026-03-09T00:00:00.000Z", - flags: [ - { - key: "flag-1", - description: "Flag 1", - targeting: { - version: 1, - rules: [], - }, - }, - ], + flagStateVersion: 1, + flags: graph().flags, + segments: graph().segments, }; +const filename = `flags-fallback-v2-${context.secretKeyHash.slice(0, 16)}.json`; +const objectKey = `reflag/flags-fallback/${filename}`; describe("flagsFallbackProvider", () => { let tempDir: string | undefined; - afterEach(async () => { vi.restoreAllMocks(); - if (tempDir) { - await rm(tempDir, { recursive: true, force: true }); - tempDir = undefined; - } + if (tempDir) await rm(tempDir, { recursive: true, force: true }); + tempDir = undefined; }); - it("loads static snapshots from a flag map", async () => { + it("creates complete static snapshots with explicitly local selection provenance", async () => { const provider = fallbackProviders.static({ - flags: { - "flag-1": true, - "flag-2": false, - }, + flags: { a: true, b: false, json: null }, }); - - await expect(provider.load(context)).resolves.toEqual({ - version: 1, + const result = await provider.load(context); + expect(result).toMatchObject({ + version: 2, + source: "static", savedAt: expect.any(String), - flags: [ - { - key: "flag-1", - description: null, - targeting: { - version: 1, - rules: [ - { - filter: { - type: "constant", - value: true, - }, - }, - ], - }, - }, - { - key: "flag-2", - description: null, - targeting: { - version: 1, - rules: [ - { - filter: { - type: "constant", - value: false, - }, - }, - ], - }, - }, - ], + segments: [], }); + expect(result?.flags.map((flag) => flag.variants.default)).toEqual([ + true, + false, + null, + ]); }); - - it("loads undefined when a file snapshot does not exist", async () => { + it("returns undefined for missing files", async () => { tempDir = await mkdtemp(path.join(os.tmpdir(), "reflag-node-sdk-")); - const provider = fallbackProviders.file({ directory: tempDir }); - - await expect(provider.load(context)).resolves.toBeUndefined(); + await expect( + fallbackProviders.file({ directory: tempDir }).load(context), + ).resolves.toBeUndefined(); }); - - it("saves and loads file snapshots", async () => { + it("round-trips full file snapshots in a versioned namespace", async () => { tempDir = await mkdtemp(path.join(os.tmpdir(), "reflag-node-sdk-")); const provider = fallbackProviders.file({ directory: tempDir }); - await provider.save(context, snapshot); - - const files = await readFile( - path.join( - tempDir, - `flags-fallback-${context.secretKeyHash.slice(0, 16)}.json`, - ), - "utf-8", - ); - expect(JSON.parse(files)).toEqual(snapshot); - + expect( + JSON.parse(await readFile(path.join(tempDir, filename), "utf8")), + ).toEqual(snapshot); await expect(provider.load(context)).resolves.toEqual(snapshot); }); - - it("loads S3 snapshots", async () => { - const send = vi.fn().mockResolvedValue({ - Body: { - transformToString: vi.fn().mockResolvedValue(JSON.stringify(snapshot)), - }, - }); - - const provider = fallbackProviders.s3({ - bucket: "bucket-name", - client: { send }, + it.each([ + { ...snapshot, version: 1 }, + { ...snapshot, segments: undefined }, + { ...snapshot, flagStateVersion: -1 }, + { ...snapshot, savedAt: "invalid" }, + ])("rejects incompatible fallback envelopes %#", async (value) => { + const provider = fallbackProviders.redis({ + client: { get: vi.fn(async () => JSON.stringify(value)), set: vi.fn() }, }); - - await expect(provider.load(context)).resolves.toEqual(snapshot); - expect(send).toHaveBeenCalledWith( - expect.objectContaining({ - input: expect.objectContaining({ - Bucket: "bucket-name", - Key: expect.stringMatching(/^reflag\/flags-fallback\//), - }), - }), - ); + await expect(provider.load(context)).resolves.toBeUndefined(); }); - - it("trims trailing slashes from generated S3 keys without regex backtracking", async () => { - const send = vi.fn().mockResolvedValue({}); - const provider = fallbackProviders.s3({ - bucket: "bucket-name", - client: { send }, - keyPrefix: "reflag/flags-fallback///", - }); - - await provider.save(context, snapshot); - + it("loads S3 snapshots", async () => { + const send = vi.fn(async () => ({ + Body: { transformToString: async () => JSON.stringify(snapshot) }, + })); + await expect( + fallbackProviders + .s3({ bucket: "bucket", client: { send } }) + .load(context), + ).resolves.toEqual(snapshot); expect(send).toHaveBeenCalledWith( - expect.objectContaining({ - input: expect.objectContaining({ - Bucket: "bucket-name", - Key: `reflag/flags-fallback/flags-fallback-${context.secretKeyHash.slice(0, 16)}.json`, - }), - }), + expect.objectContaining({ input: { Bucket: "bucket", Key: objectKey } }), ); }); - - it("returns undefined for missing S3 snapshots", async () => { - const send = vi.fn().mockRejectedValue({ name: "NoSuchKey" }); - const provider = fallbackProviders.s3({ - bucket: "bucket-name", - client: { send }, - }); - - await expect(provider.load(context)).resolves.toBeUndefined(); - }); - - it("saves S3 snapshots", async () => { - const send = vi.fn().mockResolvedValue({}); - const provider = fallbackProviders.s3({ - bucket: "bucket-name", - client: { send }, - }); - - await provider.save(context, snapshot); - + it("trims S3 key-prefix slashes and saves versioned objects", async () => { + const send = vi.fn(); + await fallbackProviders + .s3({ + bucket: "bucket", + client: { send }, + keyPrefix: "reflag/flags-fallback///", + }) + .save(context, snapshot); expect(send).toHaveBeenCalledWith( expect.objectContaining({ - input: expect.objectContaining({ - Bucket: "bucket-name", - Key: expect.stringMatching(/^reflag\/flags-fallback\//), - Body: JSON.stringify(snapshot), + input: { + Bucket: "bucket", + Key: objectKey, ContentType: "application/json", - }), + Body: JSON.stringify(snapshot), + }, }), ); }); - - it("loads GCS snapshots", async () => { - const exists = vi.fn().mockResolvedValue([true]); - const download = vi - .fn() - .mockResolvedValue([Buffer.from(JSON.stringify(snapshot), "utf-8")]); - const save = vi.fn(); - const file = vi.fn().mockReturnValue({ exists, download, save }); - const bucket = vi.fn().mockReturnValue({ file }); - - const provider = fallbackProviders.gcs({ - bucket: "bucket-name", - client: { bucket }, - }); - - await expect(provider.load(context)).resolves.toEqual(snapshot); - expect(bucket).toHaveBeenCalledWith("bucket-name"); - expect(file).toHaveBeenCalledWith( - expect.stringMatching(/^reflag\/flags-fallback\//), + it("loads and saves legacy GCS injected clients", async () => { + const download = vi.fn( + async () => [Buffer.from(JSON.stringify(snapshot))] as [Buffer], ); - }); - - it("returns undefined for missing GCS snapshots", async () => { - const exists = vi.fn().mockResolvedValue([false]); - const download = vi.fn(); const save = vi.fn(); - const file = vi.fn().mockReturnValue({ exists, download, save }); - const bucket = vi.fn().mockReturnValue({ file }); - - const provider = fallbackProviders.gcs({ - bucket: "bucket-name", - client: { bucket }, - }); - - await expect(provider.load(context)).resolves.toBeUndefined(); - expect(download).not.toHaveBeenCalled(); - }); - - it("saves GCS snapshots", async () => { - const exists = vi.fn(); - const download = vi.fn(); - const save = vi.fn().mockResolvedValue(undefined); - const file = vi.fn().mockReturnValue({ exists, download, save }); - const bucket = vi.fn().mockReturnValue({ file }); - + const file = vi.fn(() => ({ + exists: async () => [true] as [boolean], + download, + save, + })); const provider = fallbackProviders.gcs({ - bucket: "bucket-name", - client: { bucket }, - keyPrefix: "reflag/flags-fallback///", + bucket: "bucket", + client: { bucket: () => ({ file }) }, }); - + await expect(provider.load(context)).resolves.toEqual(snapshot); await provider.save(context, snapshot); - - expect(file).toHaveBeenCalledWith( - `reflag/flags-fallback/flags-fallback-${context.secretKeyHash.slice(0, 16)}.json`, - ); + expect(file).toHaveBeenCalledWith(objectKey); expect(save).toHaveBeenCalledWith(JSON.stringify(snapshot), { contentType: "application/json", }); }); - - it("accepts a provided @googleapis/storage client", async () => { + it("loads and saves Google APIs GCS clients", async () => { const get = vi .fn() .mockResolvedValueOnce({ data: { kind: "storage#object" } }) - .mockResolvedValueOnce({ - data: Buffer.from(JSON.stringify(snapshot), "utf-8"), - }); - const insert = vi.fn().mockResolvedValue({}); - + .mockResolvedValueOnce({ data: Buffer.from(JSON.stringify(snapshot)) }); + const insert = vi.fn(); const provider = fallbackProviders.gcs({ - bucket: "bucket-name", - client: { - objects: { - get, - insert, - }, - }, + bucket: "bucket", keyPrefix: "reflag/flags-fallback///", + client: { objects: { get, insert } }, }); - await expect(provider.load(context)).resolves.toEqual(snapshot); await provider.save(context, snapshot); - expect(get).toHaveBeenNthCalledWith(1, { - bucket: "bucket-name", - object: `reflag/flags-fallback/flags-fallback-${context.secretKeyHash.slice(0, 16)}.json`, + bucket: "bucket", + object: objectKey, }); expect(get).toHaveBeenNthCalledWith( 2, - { - bucket: "bucket-name", - object: `reflag/flags-fallback/flags-fallback-${context.secretKeyHash.slice(0, 16)}.json`, - alt: "media", - }, - { - responseType: "arraybuffer", - }, + { bucket: "bucket", object: objectKey, alt: "media" }, + { responseType: "arraybuffer" }, ); expect(insert).toHaveBeenCalledWith({ - bucket: "bucket-name", - name: `reflag/flags-fallback/flags-fallback-${context.secretKeyHash.slice(0, 16)}.json`, + bucket: "bucket", + name: objectKey, uploadType: "media", - media: { - mimeType: "application/json", - body: JSON.stringify(snapshot), - }, + media: { mimeType: "application/json", body: JSON.stringify(snapshot) }, }); }); - it("creates the default GCS client from @googleapis/storage", async () => { vi.resetModules(); - const get = vi .fn() .mockResolvedValueOnce({ data: { kind: "storage#object" } }) - .mockResolvedValueOnce({ - data: Buffer.from(JSON.stringify(snapshot), "utf-8"), - }); - const insert = vi.fn().mockResolvedValue({}); - const storage = vi.fn().mockReturnValue({ - objects: { - get, - insert, - }, - }); + .mockResolvedValueOnce({ data: Buffer.from(JSON.stringify(snapshot)) }); + const insert = vi.fn(); + const storage = vi.fn(() => ({ objects: { get, insert } })); const GoogleAuth = vi.fn(); - - vi.doMock("@googleapis/storage", () => ({ - auth: { GoogleAuth }, - storage, - })); - + vi.doMock("@googleapis/storage", () => ({ auth: { GoogleAuth }, storage })); try { const { createGCSFallbackProvider } = await import("../src/flagsFallbackProvider"); - const provider = createGCSFallbackProvider({ - bucket: "bucket-name", - keyPrefix: "reflag/flags-fallback///", - }); - + const provider = createGCSFallbackProvider({ bucket: "bucket" }); await expect(provider.load(context)).resolves.toEqual(snapshot); await provider.save(context, snapshot); - expect(GoogleAuth).toHaveBeenCalledWith({ scopes: ["https://www.googleapis.com/auth/devstorage.read_write"], }); expect(storage).toHaveBeenCalledWith( - expect.objectContaining({ - version: "v1", - }), - ); - expect(get).toHaveBeenNthCalledWith(1, { - bucket: "bucket-name", - object: `reflag/flags-fallback/flags-fallback-${context.secretKeyHash.slice(0, 16)}.json`, - }); - expect(get).toHaveBeenNthCalledWith( - 2, - { - bucket: "bucket-name", - object: `reflag/flags-fallback/flags-fallback-${context.secretKeyHash.slice(0, 16)}.json`, - alt: "media", - }, - { - responseType: "arraybuffer", - }, + expect.objectContaining({ version: "v1" }), ); - expect(insert).toHaveBeenCalledWith({ - bucket: "bucket-name", - name: `reflag/flags-fallback/flags-fallback-${context.secretKeyHash.slice(0, 16)}.json`, - uploadType: "media", - media: { - mimeType: "application/json", - body: JSON.stringify(snapshot), - }, - }); } finally { vi.doUnmock("@googleapis/storage"); vi.resetModules(); } }); - - it("loads Redis snapshots", async () => { - const get = vi.fn().mockResolvedValue(JSON.stringify(snapshot)); - const set = vi.fn(); - const provider = fallbackProviders.redis({ - client: { get, set }, - }); - + it("loads Redis snapshots in a versioned namespace", async () => { + const get = vi.fn(async () => JSON.stringify(snapshot)); + const provider = fallbackProviders.redis({ client: { get, set: vi.fn() } }); await expect(provider.load(context)).resolves.toEqual(snapshot); expect(get).toHaveBeenCalledWith( - `reflag:flags-fallback:${context.secretKeyHash.slice(0, 16)}`, + `reflag:flags-fallback:v2:${context.secretKeyHash.slice(0, 16)}`, ); }); - it("returns undefined for missing Redis snapshots", async () => { - const get = vi.fn().mockResolvedValue(null); - const set = vi.fn(); - const provider = fallbackProviders.redis({ - client: { get, set }, - }); - - await expect(provider.load(context)).resolves.toBeUndefined(); + await expect( + fallbackProviders + .redis({ client: { get: vi.fn(async () => null), set: vi.fn() } }) + .load(context), + ).resolves.toBeUndefined(); }); - - it("saves Redis snapshots", async () => { - const get = vi.fn(); - const set = vi.fn().mockResolvedValue("OK"); - const provider = fallbackProviders.redis({ - client: { get, set }, - keyPrefix: "reflag:flags-fallback:::", - }); - - await provider.save(context, snapshot); - + it("trims Redis prefixes and saves versioned keys", async () => { + const set = vi.fn(); + await fallbackProviders + .redis({ + client: { get: vi.fn(), set }, + keyPrefix: "reflag:flags-fallback:::", + }) + .save(context, snapshot); expect(set).toHaveBeenCalledWith( - `reflag:flags-fallback:${context.secretKeyHash.slice(0, 16)}`, + `reflag:flags-fallback:v2:${context.secretKeyHash.slice(0, 16)}`, JSON.stringify(snapshot), ); }); - it("requires REDIS_URL when no Redis client is provided", async () => { - const previousRedisUrl = process.env.REDIS_URL; + const previous = process.env.REDIS_URL; delete process.env.REDIS_URL; - try { - const provider = fallbackProviders.redis(); - - await expect(provider.load(context)).rejects.toThrow( - "fallbackProviders.redis() requires REDIS_URL to be set when no client is provided", + await expect(fallbackProviders.redis().load(context)).rejects.toThrow( + "requires REDIS_URL", ); } finally { - if (previousRedisUrl === undefined) { - delete process.env.REDIS_URL; - } else { - process.env.REDIS_URL = previousRedisUrl; - } + if (previous === undefined) delete process.env.REDIS_URL; + else process.env.REDIS_URL = previous; } }); }); diff --git a/packages/node-sdk/tsconfig.test.json b/packages/node-sdk/tsconfig.test.json new file mode 100644 index 000000000..c45161cdb --- /dev/null +++ b/packages/node-sdk/tsconfig.test.json @@ -0,0 +1,20 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": true, + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "bundler", + "skipLibCheck": true, + "noUncheckedIndexedAccess": false + }, + "include": [ + "src", + "test/client.test.ts", + "test/fixtures.ts", + "test/flag-definitions.test.ts", + "test/flagsFallbackProvider.test.ts", + "test/flags-cache.test.ts", + "test/client-sync.test.ts" + ] +} diff --git a/packages/node-sdk/tsconfig.type-tests-augmented.json b/packages/node-sdk/tsconfig.type-tests-augmented.json new file mode 100644 index 000000000..ef4fcc1ef --- /dev/null +++ b/packages/node-sdk/tsconfig.type-tests-augmented.json @@ -0,0 +1,4 @@ +{ + "extends": "./tsconfig.type-tests.json", + "include": ["src", "type-tests/augmented-defaults.ts"] +} diff --git a/packages/node-sdk/tsconfig.type-tests.json b/packages/node-sdk/tsconfig.type-tests.json new file mode 100644 index 000000000..e8c16772b --- /dev/null +++ b/packages/node-sdk/tsconfig.type-tests.json @@ -0,0 +1,8 @@ +{ + "extends": "./tsconfig.test.json", + "compilerOptions": { + "noUnusedLocals": false, + "noUnusedParameters": false + }, + "include": ["src", "type-tests/defaults.ts"] +} diff --git a/packages/node-sdk/type-tests/augmented-defaults.ts b/packages/node-sdk/type-tests/augmented-defaults.ts new file mode 100644 index 000000000..694dc6386 --- /dev/null +++ b/packages/node-sdk/type-tests/augmented-defaults.ts @@ -0,0 +1,107 @@ +import { expectTypeOf } from "vitest"; + +import { ReflagClient, type FlagValue } from "../src"; + +interface Prompt { + tone: string; +} +interface Settings { + model: string; + prompt: Prompt; + methods: string[]; +} + +declare module "../src" { + interface Flags { + release: boolean; + settings: { model: string } | null; + "assistant-settings": Settings; + days: number; + arbitrary: FlagValue; + unknownArray: FlagValue[]; + methods: string[]; + model: "Swift" | "Reasoner"; + legacy: { isEnabled: boolean; config: { payload: string } }; + } +} + +declare const client: ReflagClient; +const bound = client.bindClient({}); + +expectTypeOf(client.getFlag({}, "legacy")).toEqualTypeOf(); +expectTypeOf(bound.getFlag("settings", { model: "Swift" })).toEqualTypeOf<{ + model: string; +}>(); +expectTypeOf(bound.getFlag("settings")).toEqualTypeOf(); +expectTypeOf(client.getFlagRemote("settings")).toEqualTypeOf< + Promise +>(); +expectTypeOf(client.getFlags({}).settings).toEqualTypeOf< + { model: string } | null | undefined +>(); +expectTypeOf(bound.getFlag("days", null)).toEqualTypeOf(); +expectTypeOf(bound.getFlag("model", "Swift")).toEqualTypeOf(); +expectTypeOf(bound.getFlag("methods", ["standard"] as const)).toEqualTypeOf< + string[] +>(); + +const fallback: Settings = { + model: "Swift", + prompt: { tone: "concise" }, + methods: ["standard"], +}; +expectTypeOf( + client.getFlag({}, "assistant-settings", fallback), +).toEqualTypeOf(); +expectTypeOf( + bound.getFlag("assistant-settings", fallback), +).toEqualTypeOf(); +expectTypeOf(bound.getFlag("arbitrary", fallback)).toEqualTypeOf(); +expectTypeOf(bound.getFlag("unknownArray", [fallback])).toEqualTypeOf< + Settings[] +>(); +expectTypeOf( + client.getFlagRemote("assistant-settings", fallback), +).toEqualTypeOf>(); +expectTypeOf(bound.getFlagRemote("assistant-settings", fallback)).toEqualTypeOf< + Promise +>(); +const frozen = { + model: "Swift", + prompt: { tone: "concise" }, + methods: ["standard"], +} as const; +const mutable = bound.getFlag("assistant-settings", frozen); +mutable.model = "Reasoner"; +mutable.prompt.tone = "detailed"; +mutable.methods.push("express"); + +// @ts-expect-error Unknown keys are rejected. +client.getFlag({}, "unknown"); +// @ts-expect-error Registered keys also apply to explicit defaults. +bound.getFlag("unknown", { model: "Swift" }); +// @ts-expect-error Defaults must match this key, not another registered key's number type. +client.getFlag({}, "settings", 123); +// @ts-expect-error Bound getters check the registered value shape. +bound.getFlag("assistant-settings", { model: "Swift" }); +// @ts-expect-error Nested properties are checked against the registered schema. +bound.getFlag("assistant-settings", { + model: "Swift", + prompt: { tone: 3 }, + methods: [], +}); +// @ts-expect-error Array elements are checked. +bound.getFlag("methods", [123]); +// @ts-expect-error Literal unions constrain defaults even though results widen. +bound.getFlag("model", "Unknown"); +// @ts-expect-error Boolean defaults cannot request an object-valued registered flag. +bound.getFlag("settings", false); +// @ts-expect-error Remote root getters also check the registered schema. +client.getFlagRemote("settings", 123); +// @ts-expect-error Bound remote getters also check the registered schema. +bound.getFlagRemote("days", "three"); +// @ts-expect-error Old generated wrapper types cannot restore the singular wrapper API. +const { isEnabled: _legacyAlias } = bound.getFlag("legacy"); +const legacy = client.getFlag({}, "legacy"); +// @ts-expect-error Nor can accessing an assigned singular result. +const _legacyProperty = legacy.isEnabled; diff --git a/packages/node-sdk/type-tests/defaults.ts b/packages/node-sdk/type-tests/defaults.ts new file mode 100644 index 000000000..edbba7ed7 --- /dev/null +++ b/packages/node-sdk/type-tests/defaults.ts @@ -0,0 +1,80 @@ +import { expectTypeOf } from "vitest"; + +import { ReflagClient, type FlagDefaultValue, type FlagValue } from "../src"; + +// Deliberately no Flags augmentation or generated declarations. +declare const client: ReflagClient; +const bound = client.bindClient({}); + +expectTypeOf(client.getFlag({}, "release")).toEqualTypeOf(); +expectTypeOf(client.getFlag({}, "release", false)).toEqualTypeOf(); +expectTypeOf(bound.getFlag("release")).toEqualTypeOf(); +expectTypeOf(client.getFlag({}, "number", 0)).toEqualTypeOf(); +expectTypeOf(bound.getFlag("string", "Swift")).toEqualTypeOf(); +expectTypeOf(client.getFlag({}, "json", null)).toEqualTypeOf(); +expectTypeOf(bound.getFlag("array", [])).toEqualTypeOf(); +expectTypeOf(bound.getFlag("array", [false])).toEqualTypeOf(); +const settings = client.getFlag({}, "settings", { + model: "Swift", + temperature: 0.7, +}); +expectTypeOf(settings).toEqualTypeOf<{ model: string; temperature: number }>(); +const { model } = bound.getFlag("settings", { model: "Swift" }); +expectTypeOf(model).toEqualTypeOf(); +const frozen = { + model: "Swift", + nested: { enabled: false }, + items: [1], +} as const; +expectTypeOf(bound.getFlag("settings", frozen)).toEqualTypeOf<{ + model: string; + nested: { enabled: boolean }; + items: number[]; +}>(); + +expectTypeOf(client.getFlagRemote("release", undefined, 0, 0)).toEqualTypeOf< + Promise +>(); +expectTypeOf(client.getFlagRemote("string", "Swift", 0, 0)).toEqualTypeOf< + Promise +>(); +expectTypeOf(bound.getFlagRemote("release")).toEqualTypeOf>(); +expectTypeOf(bound.getFlagRemote("settings", { model: "Swift" })).toEqualTypeOf< + Promise<{ model: string }> +>(); + +function forwardDefault(value: Default) { + return bound.getFlag("settings", value); +} +expectTypeOf(forwardDefault({ model: "Swift" })).toEqualTypeOf<{ + model: string; +}>(); + +// @ts-expect-error Boolean reads do not return the legacy wrapper, even with aliases. +const { isEnabled: _legacyAlias } = client.getFlag({}, "release"); +const legacyValue = client.getFlag({}, "release"); +// @ts-expect-error Assignment does not restore the wrapper type. +const _legacyProperty = legacyValue.isEnabled; + +const dictionaryDefault: Record = { model: "Swift" }; +expectTypeOf(bound.getFlag("settings", dictionaryDefault)).toEqualTypeOf< + Record +>(); + +interface Prompt { + tone: string; +} +interface Settings { + model: string; + prompt: Prompt; +} +const interfaceDefault: Settings = { + model: "Swift", + prompt: { tone: "concise" }, +}; +expectTypeOf( + bound.getFlag("settings", interfaceDefault), +).toEqualTypeOf(); +expectTypeOf(client.getFlagRemote("settings", interfaceDefault)).toEqualTypeOf< + Promise +>(); diff --git a/packages/node-sdk/typedoc.json b/packages/node-sdk/typedoc.json index 3ab82e82b..5981c7607 100644 --- a/packages/node-sdk/typedoc.json +++ b/packages/node-sdk/typedoc.json @@ -1,3 +1,4 @@ { - "tsconfig": "tsconfig.build.json" + "tsconfig": "tsconfig.build.json", + "intentionallyNotExported": ["ReadonlyFlagValue", "LOG_LEVELS"] } diff --git a/packages/openfeature-node-provider/package.json b/packages/openfeature-node-provider/package.json index f0bc8c93c..ff4809552 100644 --- a/packages/openfeature-node-provider/package.json +++ b/packages/openfeature-node-provider/package.json @@ -36,7 +36,7 @@ "fmt:fix": "oxfmt --write ." }, "dependencies": { - "@reflag/node-sdk": "1.8.3" + "@reflag/node-sdk-v1": "npm:@reflag/node-sdk@1.8.3" }, "devDependencies": { "@babel/core": "~7.29.6", diff --git a/packages/openfeature-node-provider/src/index.test.ts b/packages/openfeature-node-provider/src/index.test.ts index c57db5843..8d2607976 100644 --- a/packages/openfeature-node-provider/src/index.test.ts +++ b/packages/openfeature-node-provider/src/index.test.ts @@ -1,12 +1,12 @@ import { ProviderStatus } from "@openfeature/server-sdk"; import { beforeEach, describe, expect, it, Mock, vi } from "vitest"; -import { ReflagClient } from "@reflag/node-sdk"; +import { ReflagClient } from "@reflag/node-sdk-v1"; import { defaultContextTranslator, ReflagNodeProvider } from "./index"; -vi.mock("@reflag/node-sdk", () => { - const actualModule = vi.importActual("@reflag/node-sdk"); +vi.mock("@reflag/node-sdk-v1", () => { + const actualModule = vi.importActual("@reflag/node-sdk-v1"); return { __esModule: true, diff --git a/packages/openfeature-node-provider/src/index.ts b/packages/openfeature-node-provider/src/index.ts index b24e8f617..a677b8ab6 100644 --- a/packages/openfeature-node-provider/src/index.ts +++ b/packages/openfeature-node-provider/src/index.ts @@ -15,7 +15,7 @@ import { ClientOptions, Context as ReflagContext, ReflagClient, -} from "@reflag/node-sdk"; +} from "@reflag/node-sdk-v1"; type ProviderOptions = ClientOptions & { contextTranslator?: (context: EvaluationContext) => ReflagContext; diff --git a/packages/react-sdk/dev/nextjs-bootstrap-demo/app/client.ts b/packages/react-sdk/dev/nextjs-bootstrap-demo/app/client.ts index d7223c7e6..508f4dc20 100644 --- a/packages/react-sdk/dev/nextjs-bootstrap-demo/app/client.ts +++ b/packages/react-sdk/dev/nextjs-bootstrap-demo/app/client.ts @@ -1,4 +1,4 @@ -import { ReflagClient as ReflagNodeClient } from "@reflag/node-sdk"; +import { ReflagClient as ReflagNodeClient } from "@reflag/node-sdk-v1"; const secretKey = process.env.REFLAG_SECRET_KEY; export const publishableKey = process.env.REFLAG_PUBLISHABLE_KEY || ""; diff --git a/packages/react-sdk/dev/nextjs-bootstrap-demo/package.json b/packages/react-sdk/dev/nextjs-bootstrap-demo/package.json index fa90ae08e..f525f8673 100644 --- a/packages/react-sdk/dev/nextjs-bootstrap-demo/package.json +++ b/packages/react-sdk/dev/nextjs-bootstrap-demo/package.json @@ -14,7 +14,7 @@ "format": "yarn fmt:fix && yarn lint:fix" }, "dependencies": { - "@reflag/node-sdk": "workspace:^", + "@reflag/node-sdk-v1": "npm:@reflag/node-sdk@1.8.3", "@reflag/react-sdk": "workspace:^", "next": "16.4.5", "react": "^18", diff --git a/yarn.lock b/yarn.lock index ae9636c4b..72bddd535 100644 --- a/yarn.lock +++ b/yarn.lock @@ -6098,7 +6098,7 @@ __metadata: languageName: node linkType: hard -"@reflag/flag-evaluation@workspace:packages/flag-evaluation": +"@reflag/flag-evaluation@workspace:*, @reflag/flag-evaluation@workspace:packages/flag-evaluation": version: 0.0.0-use.local resolution: "@reflag/flag-evaluation@workspace:packages/flag-evaluation" dependencies: @@ -6141,7 +6141,19 @@ __metadata: languageName: unknown linkType: soft -"@reflag/node-sdk@npm:1.8.3, @reflag/node-sdk@workspace:*, @reflag/node-sdk@workspace:^, @reflag/node-sdk@workspace:packages/node-sdk": +"@reflag/node-sdk-v1@npm:@reflag/node-sdk@1.8.3": + version: 1.8.3 + resolution: "@reflag/node-sdk@npm:1.8.3" + dependencies: + "@aws-sdk/client-s3": "npm:^3.888.0" + "@googleapis/storage": "npm:21.2.0" + "@redis/client": "npm:^5.11.0" + "@reflag/flag-evaluation-v1": "npm:@reflag/flag-evaluation@1.1.2" + checksum: 10c0/9bf81b4186de1a4bfbcbc0123873bb6aef02dcf1b996e905ab92905168cfdc5e85e89033dcd5f4ab87358ef131956775359e01bf3e535328c8706e63cf948f4b + languageName: node + linkType: hard + +"@reflag/node-sdk@workspace:*, @reflag/node-sdk@workspace:packages/node-sdk": version: 0.0.0-use.local resolution: "@reflag/node-sdk@workspace:packages/node-sdk" dependencies: @@ -6149,7 +6161,7 @@ __metadata: "@babel/core": "npm:~7.29.6" "@googleapis/storage": "npm:21.2.0" "@redis/client": "npm:^5.11.0" - "@reflag/flag-evaluation-v1": "npm:@reflag/flag-evaluation@1.1.2" + "@reflag/flag-evaluation": "workspace:*" "@reflag/tsconfig": "npm:~0.0.2" "@types/node": "npm:^22.12.0" "@vitest/coverage-v8": "npm:4.1.12" @@ -6189,7 +6201,7 @@ __metadata: "@babel/core": "npm:~7.29.6" "@openfeature/core": "npm:^1.5.0" "@openfeature/server-sdk": "npm:>=1.16.1" - "@reflag/node-sdk": "npm:1.8.3" + "@reflag/node-sdk-v1": "npm:@reflag/node-sdk@1.8.3" "@reflag/tsconfig": "npm:~0.0.2" "@types/node": "npm:^22.12.0" flush-promises: "npm:~1.0.2" @@ -15128,7 +15140,7 @@ __metadata: version: 0.0.0-use.local resolution: "nextjs-bootstrap-demo@workspace:packages/react-sdk/dev/nextjs-bootstrap-demo" dependencies: - "@reflag/node-sdk": "workspace:^" + "@reflag/node-sdk-v1": "npm:@reflag/node-sdk@1.8.3" "@reflag/react-sdk": "workspace:^" "@types/node": "npm:^22.12.0" "@types/react": "npm:^18"