Skip to content

Commit db4af1e

Browse files
committed
feat(sdk): publish initial bootstrapped flag events
1 parent 0414f80 commit db4af1e

8 files changed

Lines changed: 255 additions & 58 deletions

File tree

‎.changeset/quiet-flag-value-updates.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,6 @@
33
"@reflag/react-sdk": minor
44
---
55

6-
Add a per-flag `flagUpdated` event that fires only when the effective enabled/config value or flag presence changes. Include local overrides and config key/payload changes; ignore targeting/config versions, diagnostics, and opt-in metadata. The payload is `{ key, flag }`, with `flag` undefined on removal. Keep `flagsUpdated` unchanged for raw-data subscribers.
6+
Add a per-flag `flagUpdated` event that publishes each initial flag value during initialization, including bootstrapped flags after applying cached overrides. Subsequent events fire only when the effective enabled/config value or flag presence changes. Include local overrides and config key/payload changes; ignore targeting/config versions, diagnostics, and opt-in metadata. The payload is `{ key, flag }`, with `flag` undefined on removal. Keep `flagsUpdated` unchanged for raw-data subscribers.
77

88
Subscribe React `useFlag()` to updates for its own key so unrelated flag updates and metadata-only changes do not trigger rerenders. Continue reporting the latest evaluation metadata when consumers read enabled/config values.

‎packages/browser-sdk/README.md‎

Lines changed: 33 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -518,44 +518,54 @@ reflagClient.track("huddle", { voiceHuddle: true });
518518

519519
## Event listeners
520520

521-
Event listeners allow for capturing various events occurring in the `ReflagClient`. This is useful to build integrations with other system or for various debugging purposes. The available events are:
522-
523-
- `check`: Your code used `isEnabled` or `config` for a flag
524-
- `flagsUpdated`: Raw flag data changed, including targeting/config versions, evaluation diagnostics, and opt-in metadata
525-
- `flagUpdated`: An individual flag's effective `isEnabled` (including local overrides) or config key/payload changed, or that flag was added/removed. Metadata-only changes do not emit this event. The payload is `{ key, flag }`, with `flag` undefined on removal
526-
- `optInFlagsLoadingUpdated`: The opt-in flag loading state changed
527-
- `user`: User information updated (similar to the `identify` call used in tracking terminology)
528-
- `company`: Company information updated (sometimes to the `group` call used in tracking terminology)
529-
- `track`: Track event occurred.
530-
531-
Use the `on()` method to add an event listener to respond to certain events. See the API reference for details on each hook.
521+
For most integrations, subscribe to `flagUpdated` to receive initial flag values and react to subsequent value changes. Use `on()` to register a listener:
532522

533523
```ts
534-
import { ReflagClient, CheckEvent, RawFlags } from "@reflag/browser-sdk";
524+
import { ReflagClient } from "@reflag/browser-sdk";
535525

536526
const client = new ReflagClient({
537-
// options
527+
publishableKey: "publishableKey",
528+
});
529+
530+
const unsub = client.on("flagUpdated", ({ key, flag }) => {
531+
console.log(key, flag);
538532
});
539533

540-
// or add the hooks after construction:
541-
const unsub = client.on("check", (check: CheckEvent) =>
542-
console.log(`Check event ${check}`),
543-
);
544-
// use the returned function to unsubscribe, or call `off()` with the same arguments again
534+
// Register before initializing to receive initial values, including bootstrapped flags.
535+
await client.initialize();
536+
537+
// When disposing the integration, unsubscribe using the returned function,
538+
// or call `off()` with the same event and handler.
545539
unsub();
546540
```
547541

548-
For integrations that only need value changes, subscribe to `flagUpdated` instead of `flagsUpdated`:
542+
`flagUpdated` publishes an initial value for each flag during initialization. After that, it fires only when a flag's effective enabled value (including local overrides), config key/payload, or presence changes. Targeting/config versions, evaluation diagnostics, and opt-in metadata alone do not trigger subsequent events. The payload is `{ key, flag }`, with `flag` undefined on removal.
543+
544+
The `flag` field has the same raw shape as `getFlags()`; when present, its effective enabled value is `flag.isEnabledOverride ?? flag.isEnabled`. Accessing the event payload does not generate check telemetry.
545+
546+
Subscribe before calling `initialize()` to receive one initial event per flag, including disabled flags and bootstrapped flags. Bootstrapped flags are available immediately through `getFlags()`; their initial events are published during initialization after applying cached overrides, without fetching. Subscribers registered after initialization do not receive a replay.
547+
548+
Explicit silent updates (`updateFlags(flags, false)`) update the baseline without emitting events. Handle the `user` and `company` events separately if your integration needs to resynchronize traits when identity changes but flag values stay the same.
549+
550+
### Observing refreshed raw flag data
551+
552+
Use `flagsUpdated` when you need to observe raw flag updates, including refreshes where enabled/config values stay the same. It delivers the full flag map and also fires for targeting/config version, evaluation diagnostic, or opt-in metadata changes:
549553

550554
```ts
551-
client.on("flagUpdated", ({ key, flag }) => {
552-
console.log(key, flag);
555+
client.on("flagsUpdated", (flags) => {
556+
console.log(flags);
553557
});
554558
```
555559

556-
There is one event per changed flag, not a notification for all flags. The `flag` field has the same raw shape as `getFlags()`; its effective enabled value is `flag.isEnabledOverride ?? flag.isEnabled`. Accessing the event payload does not generate check telemetry.
560+
A refresh returning identical raw flag data does not emit this event.
557561

558-
Initially fetched flags emit an event for each added flag. Bootstrapped flags are available immediately through `getFlags()` and do not replay events to new subscribers. Explicit silent updates (`updateFlags(flags, false)`) update the baseline without emitting events. Handle the `user` and `company` events separately if your integration needs to resynchronize traits when identity changes but flag values stay the same.
562+
### Other events
563+
564+
- `check`: Your code used `isEnabled` or `config` for a flag
565+
- `optInFlagsLoadingUpdated`: The opt-in flag loading state changed
566+
- `user`: User information updated (similar to the `identify` call used in tracking terminology)
567+
- `company`: Company information updated (sometimes to the `group` call used in tracking terminology)
568+
- `track`: Track event occurred.
559569

560570
## Zero PII
561571

‎packages/browser-sdk/src/flag/flags.ts‎

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,8 @@ export type RawFlag = {
152152
export type RawFlags = Record<string, RawFlag>;
153153

154154
/**
155-
* An effective enabled/config value changed, or a flag was added or removed.
155+
* An initial flag value is published, its effective enabled/config value
156+
* changed, or the flag was added or removed.
156157
*/
157158
export type FlagUpdatedEvent = {
158159
key: string;
@@ -405,8 +406,17 @@ export class FlagsClient {
405406
);
406407
}
407408

408-
// Apply overrides and trigger update if flags have changed
409-
this.updateFlags();
409+
// Apply overrides before publishing initial bootstrapped values. Suppress
410+
// change events here so overridden flags are not published twice.
411+
const previousFlags = this.flags;
412+
this.updateFlags(!this.bootstrapped);
413+
const flagsChanged = previousFlags !== this.flags;
414+
if (this.bootstrapped) {
415+
for (const [key, flag] of Object.entries(this.flags)) {
416+
this.triggerFlagUpdated({ key, flag });
417+
}
418+
if (flagsChanged) this.triggerFlagsUpdated();
419+
}
410420
initializationSucceeded = true;
411421
} finally {
412422
this.initializationComplete = true;
@@ -666,9 +676,7 @@ export class FlagsClient {
666676
this.flags = updatedFlags;
667677
if (triggerEvent) {
668678
// Raw-data subscribers may synchronously change overrides again.
669-
for (const update of updates) {
670-
for (const callback of this.flagUpdatedListeners) callback(update);
671-
}
679+
for (const update of updates) this.triggerFlagUpdated(update);
672680
this.triggerFlagsUpdated();
673681
}
674682
}
@@ -707,8 +715,9 @@ export class FlagsClient {
707715
}
708716

709717
/**
710-
* Register a callback for individual effective enabled/config value changes,
711-
* including flags being added or removed. Metadata-only changes are ignored.
718+
* Register a callback for initial flag values and individual effective
719+
* enabled/config value changes, including additions/removals.
720+
* Metadata-only changes are ignored.
712721
*/
713722
onFlagUpdated(callback: (event: FlagUpdatedEvent) => void) {
714723
if (!this.abortController.signal.aborted) {
@@ -1046,6 +1055,10 @@ export class FlagsClient {
10461055
return mergedFlags;
10471056
}
10481057

1058+
private triggerFlagUpdated(event: FlagUpdatedEvent) {
1059+
for (const callback of this.flagUpdatedListeners) callback(event);
1060+
}
1061+
10491062
private triggerFlagsUpdated() {
10501063
this.eventTarget.dispatchEvent({ type: "flagsUpdated" });
10511064
}

‎packages/browser-sdk/src/hooksManager.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,8 @@ export interface HookArgs {
1111
check: CheckEvent;
1212
flagsUpdated: RawFlags;
1313
/**
14-
* Effective enabled/config values changed, or a flag was added or removed.
14+
* Initial values are published during initialization, including bootstrapped flags.
15+
* Subsequent events mean an effective enabled/config value or flag presence changed.
1516
* Targeting versions, diagnostics and opt-in metadata do not trigger this event.
1617
*/
1718
flagUpdated: FlagUpdatedEvent;

‎packages/browser-sdk/test/flagUpdated.test.ts‎

Lines changed: 111 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
22

3-
import { ReflagClient } from "../src/client";
3+
import { InitOptions, ReflagClient } from "../src/client";
44
import { FlagsClient, RawFlags } from "../src/flag/flags";
55
import { flagValueChanged } from "../src/flag/flagValueChanged";
66
import { testLogger } from "./testLogger";
@@ -23,7 +23,7 @@ function initialFlags(): RawFlags {
2323

2424
const clients: ReflagClient[] = [];
2525

26-
function newClient(flags?: RawFlags) {
26+
function newClient(flags?: RawFlags, options: Partial<InitOptions> = {}) {
2727
const client = new ReflagClient({
2828
publishableKey: "test-key-flag-updated",
2929
user: { id: "user1" },
@@ -34,6 +34,7 @@ function newClient(flags?: RawFlags) {
3434
toolbar: false,
3535
feedback: { enableAutoFeedback: false },
3636
logger: testLogger,
37+
...options,
3738
});
3839
clients.push(client);
3940
return client;
@@ -101,6 +102,113 @@ describe("flagUpdated", () => {
101102
expect(sendCheck).not.toHaveBeenCalled();
102103
});
103104

105+
test.each(["bootstrappedFlags", "bootstrappedState"] as const)(
106+
"publishes each initial %s flag once without fetching or emitting checks",
107+
async (source) => {
108+
const flags = initialFlags();
109+
const client = newClient(flags, {
110+
offline: false,
111+
...(source === "bootstrappedState"
112+
? {
113+
bootstrappedFlags: undefined,
114+
bootstrappedState: {
115+
flags,
116+
context: { user: { id: "user1" } },
117+
flagStateVersion: 1,
118+
},
119+
}
120+
: {}),
121+
});
122+
const listener = vi.fn();
123+
const flagsUpdated = vi.fn();
124+
const fetchFlags = vi.spyOn(FlagsClient.prototype, "fetchFlags");
125+
const sendCheck = vi.spyOn(FlagsClient.prototype, "sendCheckEvent");
126+
client.on("flagUpdated", listener);
127+
client.on("flagsUpdated", flagsUpdated);
128+
129+
expect(Object.keys(client.getFlags())).toEqual(["flagA", "flagB"]);
130+
expect(listener).not.toHaveBeenCalled();
131+
await client.initialize();
132+
133+
expect(listener).toHaveBeenCalledTimes(2);
134+
for (const [key, flag] of Object.entries(client.getFlags())) {
135+
expect(listener).toHaveBeenCalledWith({ key, flag });
136+
}
137+
expect(flagsUpdated).not.toHaveBeenCalled();
138+
expect(fetchFlags).not.toHaveBeenCalled();
139+
expect(sendCheck).not.toHaveBeenCalled();
140+
141+
await client.initialize();
142+
client.updateFlags(flags);
143+
client.updateFlags({
144+
...flags,
145+
flagA: { ...flags.flagA, targetingVersion: 2 },
146+
});
147+
expect(listener).toHaveBeenCalledTimes(2);
148+
expect(flagsUpdated).toHaveBeenCalledOnce();
149+
},
150+
);
151+
152+
test("publishes cached overrides in initial bootstrap events without duplicates", async () => {
153+
localStorage.setItem(
154+
"__reflag_overrides",
155+
JSON.stringify({ flagA: false, flagB: true }),
156+
);
157+
const client = newClient(initialFlags());
158+
const listener = vi.fn();
159+
const flagsUpdated = vi.fn();
160+
client.on("flagUpdated", listener);
161+
client.on("flagsUpdated", flagsUpdated);
162+
163+
await client.initialize();
164+
165+
expect(listener).toHaveBeenCalledTimes(2);
166+
expect(listener.mock.calls.map(([event]) => event.key)).toEqual([
167+
"flagA",
168+
"flagB",
169+
]);
170+
expect(
171+
listener.mock.calls.map(
172+
([{ flag }]) => flag.isEnabledOverride ?? flag.isEnabled,
173+
),
174+
).toEqual([false, true]);
175+
expect(flagsUpdated).toHaveBeenCalledOnce();
176+
expect(flagsUpdated).toHaveBeenCalledWith(client.getFlags());
177+
});
178+
179+
test("does not replay bootstrapped flags to listeners registered after initialization", async () => {
180+
const client = newClient(initialFlags());
181+
await client.initialize();
182+
const listener = vi.fn();
183+
client.on("flagUpdated", listener);
184+
185+
await client.initialize();
186+
expect(listener).not.toHaveBeenCalled();
187+
188+
const flags = initialFlags();
189+
client.updateFlags({
190+
...flags,
191+
flagA: { ...flags.flagA, isEnabled: false },
192+
});
193+
expect(listener).toHaveBeenCalledOnce();
194+
expect(listener).toHaveBeenCalledWith({
195+
key: "flagA",
196+
flag: client.getFlags().flagA,
197+
});
198+
});
199+
200+
test("initializing an empty bootstrapped snapshot does not publish flags", async () => {
201+
const client = newClient({});
202+
const listener = vi.fn();
203+
client.on("flagUpdated", listener);
204+
205+
await client.initialize();
206+
207+
expect(listener).not.toHaveBeenCalled();
208+
expect(client.getFlags()).toEqual({});
209+
expect(client.getState()).toBe("initialized");
210+
});
211+
104212
test("ignores metadata while preserving flagsUpdated and the deprecated alias", () => {
105213
const flags = initialFlags();
106214
const client = newClient(flags);
@@ -280,7 +388,7 @@ describe("flagUpdated", () => {
280388
});
281389
});
282390

283-
test("silent and bootstrapped updates establish a baseline without notifying", () => {
391+
test("silent updates establish a baseline without notifying", () => {
284392
const client = newClient(initialFlags());
285393
const listener = vi.fn();
286394
const flagsUpdated = vi.fn();

‎packages/react-sdk/README.md‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -914,9 +914,7 @@ function LoadingWrapper({ children }: { children: ReactNode }) {
914914
915915
### `useOnEvent()`
916916
917-
Attach a callback handler to client events to act on changes. It automatically disposes itself on unmount.
918-
919-
Use `flagUpdated` for individual flag value changes, including effective local overrides. Targeting/config versions, evaluation diagnostics, and opt-in metadata alone do not trigger it. Use `flagsUpdated` if you need raw flag data and metadata changes.
917+
For most integrations, subscribe to `flagUpdated` to receive initial flag values and react to subsequent value changes. `useOnEvent()` attaches the handler and automatically disposes it on unmount.
920918
921919
```tsx
922920
import { useOnEvent } from "@reflag/react-sdk";
@@ -930,7 +928,11 @@ function LoggingWrapper({ children }: { children: ReactNode }) {
930928
}
931929
```
932930
933-
The event fires once per changed flag with `{ key, flag }`. `flag` contains raw flag data and is undefined when removed. It does not replay existing bootstrapped values; use `useClient().getFlags()` to read current raw flags without fetching or generating checks. Handle identity changes separately if your integration needs to resynchronize traits even when flag values are unchanged.
931+
`flagUpdated` publishes one initial value per flag during client initialization, including bootstrapped and disabled flags. Bootstrapped values are published after cached overrides are applied, without fetching. Mount the subscription before initialization to receive these events; subscriptions added afterward do not receive a replay. `useClient().getFlags()` also lets you read current raw flags without fetching or generating checks.
932+
933+
After initialization, the event fires only when a flag's effective enabled value (including local overrides), config key/payload, or presence changes. Targeting/config versions, evaluation diagnostics, and opt-in metadata alone do not trigger subsequent events. The payload is `{ key, flag }`; `flag` contains raw flag data and is undefined when removed. Handle identity changes separately if your integration needs to resynchronize traits even when flag values are unchanged.
934+
935+
Use `flagsUpdated` if you need to observe refreshed raw flag data, even when enabled/config values stay the same. It delivers the full flag map and also fires for metadata-only updates. A refresh returning identical raw flag data does not emit this event. See the [Browser SDK event listeners](../browser-sdk/README.md#event-listeners) for the full event list.
934936
935937
## Migrating from Bucket SDK
936938

0 commit comments

Comments
 (0)