Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/slim-bootstrap-snapshots.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@reflag/node-sdk": patch
"@reflag/browser-sdk": patch
"@reflag/react-sdk": patch
---

Return smaller, JSON-safe bootstrap snapshots. They retain flag values and the metadata needed for checks and refreshes, but omit unused evaluation details and properties with `undefined` values. Existing v2 clients can still read the snapshots at runtime. TypeScript apps passing Node bootstrap data directly to an older client SDK may need to update the client SDK to accept an omitted flag value.
39 changes: 35 additions & 4 deletions packages/browser-sdk/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,13 @@ import {
} from "./feedback/feedback";
import * as feedbackLib from "./feedback/ui";
import { isValidBootstrapSnapshot } from "./flag/bootstrap";
import { CheckEvent, FlagsClient, OptInFlag, RawFlags } from "./flag/flags";
import {
type BootstrappedFlags,
CheckEvent,
FlagsClient,
OptInFlag,
RawFlags,
} from "./flag/flags";
import { isValidFlagStateVersion } from "./flag/flagStateVersion";
import {
FlagDefaultValue,
Expand Down Expand Up @@ -226,7 +232,7 @@ export type FlagDefinitions = Readonly<Array<string>>;
export type BootstrappedState = {
protocolVersion: 2;
context: ReflagContext;
flags: RawFlags;
flags: BootstrappedFlags;
flagStateVersion?: number;
};

Expand Down Expand Up @@ -1150,11 +1156,36 @@ export class ReflagClient {
}

getFlagsForBootstrap(): BootstrappedState {
const flagStateVersion = this.flagsClient.getFlagStateVersion();
const flags = Object.fromEntries(
Object.entries(this.getFlagResults()).map(([key, flag]) => [
key,
{
resolved: flag.resolved,
...(flag.value === undefined ? {} : { value: flag.value }),
...(flag.variantKey === undefined ||
flag.sourceVersionId === undefined
? {}
: {
variantKey: flag.variantKey,
sourceVersionId: flag.sourceVersionId,
}),
ruleResults: flag.ruleResults.map(({ ruleId, matched }) => ({
ruleId,
matched,
})),
errors: flag.errors,
...(flag.optInEnabled === undefined
? {}
: { optInEnabled: flag.optInEnabled, optIn: flag.optIn }),
},
]),
);
return {
protocolVersion: 2,
context: this.getContext(),
flags: this.getFlagResults(),
flagStateVersion: this.flagsClient.getFlagStateVersion(),
flags,
...(flagStateVersion === undefined ? {} : { flagStateVersion }),
};
}

Expand Down
11 changes: 8 additions & 3 deletions packages/browser-sdk/src/flag/flags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,9 +179,14 @@ const REFRESH_LIMIT_WINDOW_MS = 60 * 1000;

export type FlagOverrides = Record<string, FlagValue | undefined>;

type BootstrappedFlag = Omit<RawFlag, "value"> & {
value?: RawFlag["value"];
};
export type BootstrappedFlags = Record<string, BootstrappedFlag>;

type BootstrappedState = {
protocolVersion: 2;
flags: RawFlags;
flags: BootstrappedFlags;
flagStateVersion?: number;
};

Expand Down Expand Up @@ -476,7 +481,7 @@ export class FlagsClient {
}

setFetchedFlags(
fetchedFlags: RawFlags,
fetchedFlags: BootstrappedFlags,
triggerEvent = true,
flagStateVersion?: number,
) {
Expand All @@ -495,7 +500,7 @@ export class FlagsClient {
// A newly accepted snapshot supersedes any metadata-only request in flight.
this.optInMetadataFetchVersion++;
this.setOptInMetadata(validated, flagStateVersion);
this.warnMissingFlagContextFields(fetchedFlags);
this.warnMissingFlagContextFields(validated);
this.updateFlags(triggerEvent);
}

Expand Down
53 changes: 53 additions & 0 deletions packages/browser-sdk/test/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,59 @@ describe("direct values and root checks", () => {
expect(checks()[0].evalErrors).toEqual([error]);
});

test("reserializes only bootstrap fields without losing check metadata", async () => {
const client = create({
bootstrappedState: {
protocolVersion: 2,
context: { user: { id: "alice" } },
flags: {
flagA: {
...selectedFlag(null, "none"),
matchedRuleId: "split",
allocationIndex: 0,
ruleResults: [
{ ruleId: "skipped", matched: false },
{
ruleId: "split",
matched: true,
allocationIndex: 0,
destination: { type: "variant", variantKey: "none" },
},
],
},
unresolved: { resolved: false, ruleResults: [], errors: [] },
},
},
});
expect(client.getFlagResults().flagA.allocationIndex).toBe(0);
const state = client.getFlagsForBootstrap();
expect(state).toStrictEqual(JSON.parse(JSON.stringify(state)));
expect(state).not.toHaveProperty("flagStateVersion");
expect(state.flags.flagA).toStrictEqual({
value: null,
resolved: true,
variantKey: "none",
sourceVersionId: "version-1",
ruleResults: [
{ ruleId: "skipped", matched: false },
{ ruleId: "split", matched: true },
],
errors: [],
});
expect(state.flags.unresolved).not.toHaveProperty("value");

const restored = create({ bootstrappedState: state });
expect(restored.getFlag("flagA", null)).toBeNull();
expect(restored.getFlag("unresolved", "fallback")).toBe("fallback");
await restored.stop();
expect(checks()[0]).toMatchObject({
key: "flagA",
evalResult: "none",
sourceVersionId: "version-1",
evalRuleResults: [false, true],
});
});

test("registers an ignored root read immediately, but diagnostics/bootstrap register none; delivery stays buffered", async () => {
const client = create();
const check = vi.fn();
Expand Down
6 changes: 4 additions & 2 deletions packages/node-sdk/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -422,8 +422,10 @@ console.log(bootstrappedState);
// "huddle-settings": {
// "value": { "maxParticipants": 50, "videoQuality": "hd" },
// "variantKey": "enhanced",
// "sourceVersionId": "example-version",
// "resolved": true,
// ...
// "ruleResults": [{ "ruleId": "example-rule", "matched": true }],
// "errors": []
// }
// },
// flagStateVersion: 42
Expand All @@ -447,7 +449,7 @@ const bootstrappedState = boundClient.getFlagsForBootstrap();

### Key differences from `getFlags()`

- **Raw data**: Returns the evaluated raw flags, including their values and evaluation details, as JSON serializable objects
- **Bootstrap data**: Returns JSON-safe flag values and the metadata needed to record checks in the client, without the full evaluation trace
- **Public flags only**: Leaves out flags that aren't marked `secret: false`
- **No checks**: Doesn't record `check` events
- **Context included**: Returns both the evaluated flags and the context used for evaluation
Expand Down
19 changes: 16 additions & 3 deletions packages/node-sdk/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -522,9 +522,22 @@ export class ReflagClient {
.map(([key, result]) => [
key,
{
...result,
// Match publishable-key HTTP evaluation: dependency origins can name
// private flags or segments, even when the requested root is public.
resolved: result.resolved,
...(result.value === undefined ? {} : { value: result.value }),
...(result.resolved &&
result.variantKey !== undefined &&
result.sourceVersionId !== undefined
? {
variantKey: result.variantKey,
sourceVersionId: result.sourceVersionId,
}
: {}),
// v2 readers require rule IDs, even though checks only send match booleans.
ruleResults: result.ruleResults.map(({ ruleId, matched }) => ({
ruleId,
matched,
})),
// Dependency origins can name private flags or segments.
errors: result.errors.map(({ source: _source, ...error }) => error),
},
]),
Expand Down
10 changes: 9 additions & 1 deletion packages/node-sdk/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,10 +102,18 @@ export type RawFlag = Omit<
resolved: boolean;
};
export type RawFlags = Record<string, RawFlag>;
type BootstrappedFlag = Pick<
RawFlag,
"resolved" | "variantKey" | "sourceVersionId"
> & {
value?: FlagValue;
ruleResults: Pick<RawFlag["ruleResults"][number], "ruleId" | "matched">[];
errors: (EvaluationError & { source?: never })[];
};
export type BootstrappedFlags = {
protocolVersion: 2;
context: Context;
flags: RawFlags;
flags: Record<string, BootstrappedFlag>;
flagStateVersion?: number;
};
export type EvaluatedFlagsAPIResponse = {
Expand Down
34 changes: 32 additions & 2 deletions packages/node-sdk/test/bootstrap-secrecy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,13 +117,13 @@ describe("bootstrap visibility boundary", () => {
resolved: true,
variantKey: "on",
sourceVersionId: "version:public",
matchedRuleId: "public-target",
ruleResults: [{ ruleId: "public-target", matched: true }],
errors: [{ code: "MISSING_CONTEXT_FIELD", field: "user.plan" }],
},
},
});
const serialized = JSON.stringify(bootstrap);
expect(bootstrap).toStrictEqual(JSON.parse(serialized));
for (const privateData of [
privatePayload,
"private-dependency",
Expand Down Expand Up @@ -154,6 +154,37 @@ describe("bootstrap visibility boundary", () => {
},
);

it("keeps only the fields needed to bootstrap a percentage rollout", async () => {
const flag = definition("rollout", null);
flag.rules.unshift({
id: "rollout-rule",
filter: { type: "constant", value: true },
result: {
type: "percentageDistribution",
key: "rollout",
attribute: "company.id",
allocations: [
{
percentage: 100,
destination: { type: "variant", variantKey: "default" },
},
],
},
});
const h = harness(snapshot([flag]));
await h.client.initialize();
expect(h.client.getFlagsForBootstrap(context).flags).toStrictEqual({
rollout: {
value: null,
resolved: true,
variantKey: "default",
sourceVersionId: "version:rollout",
ruleResults: [{ ruleId: "rollout-rule", matched: true }],
errors: [],
},
});
});

it.each([undefined, null, "false", 0, {}, true])(
"does not treat visibility %j as an explicit public declaration",
async (secret) => {
Expand Down Expand Up @@ -187,7 +218,6 @@ describe("bootstrap visibility boundary", () => {
const bootstrap = h.client.getFlagsForBootstrap(context);
expect(bootstrap.flags).toEqual({
public: {
flagKey: "public",
value: { nested: [false] },
resolved: false,
ruleResults: [],
Expand Down
4 changes: 1 addition & 3 deletions packages/react-sdk/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,7 @@ export type OptInFlag = Omit<BrowserOptInFlag, "key"> & {
*/
export type RawFlags = BrowserRawFlags;

export type BootstrappedFlags = BrowserBootstrappedState & {
flags: BrowserRawFlags;
};
export type BootstrappedFlags = BrowserBootstrappedState;

const SDK_VERSION = `react-sdk/${version}`;

Expand Down
Loading