diff --git a/.changeset/slim-bootstrap-snapshots.md b/.changeset/slim-bootstrap-snapshots.md new file mode 100644 index 000000000..60c7eea70 --- /dev/null +++ b/.changeset/slim-bootstrap-snapshots.md @@ -0,0 +1,7 @@ +--- +"@reflag/node-sdk": patch +"@reflag/browser-sdk": patch +"@reflag/react-sdk": patch +--- + +Return smaller, JSON-safe bootstrap snapshots that remain compatible with existing v2 clients. Updated clients also accept bootstrap snapshots without `ruleResults`; flag values and exposure tracking are unchanged. diff --git a/packages/browser-sdk/src/client.ts b/packages/browser-sdk/src/client.ts index cc5eb707b..4c7233568 100644 --- a/packages/browser-sdk/src/client.ts +++ b/packages/browser-sdk/src/client.ts @@ -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 BootstrappedState, + CheckEvent, + FlagsClient, + OptInFlag, + RawFlags, +} from "./flag/flags"; import { isValidFlagStateVersion } from "./flag/flagStateVersion"; import { FlagDefaultValue, @@ -220,15 +226,7 @@ export type ToolbarOptions = */ export type FlagDefinitions = Readonly>; -/** - * Pre-fetched evaluated state used to bootstrap the client. - */ -export type BootstrappedState = { - protocolVersion: 2; - context: ReflagContext; - flags: RawFlags; - flagStateVersion?: number; -}; +export type { BootstrappedState } from "./flag/flags"; /** * ReflagClient initialization options. @@ -1150,11 +1148,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 }), }; } diff --git a/packages/browser-sdk/src/flag/flagCache.ts b/packages/browser-sdk/src/flag/flagCache.ts index 2002d49e6..e81ca9b85 100644 --- a/packages/browser-sdk/src/flag/flagCache.ts +++ b/packages/browser-sdk/src/flag/flagCache.ts @@ -65,8 +65,9 @@ export function parseAPIFlagsResponse( isFlagValue(flag.value) || (bootstrap && flag.resolved === false && flag.value === undefined) ) || - !Array.isArray(flag.ruleResults) || - !flag.ruleResults.every(isRuleEvaluationResult) || + (!(bootstrap && flag.ruleResults === undefined) && + (!Array.isArray(flag.ruleResults) || + !flag.ruleResults.every(isRuleEvaluationResult))) || !Array.isArray(flag.errors) || !flag.errors.every(isEvaluationError) || (flag.matchedRuleId !== undefined && @@ -111,7 +112,7 @@ export function parseAPIFlagsResponse( sourceVersionId: flag.sourceVersionId, matchedRuleId: flag.matchedRuleId, allocationIndex: flag.allocationIndex, - ruleResults: flag.ruleResults, + ruleResults: flag.ruleResults ?? [], errors: flag.errors, ...(flag.optInEnabled === undefined ? {} diff --git a/packages/browser-sdk/src/flag/flags.ts b/packages/browser-sdk/src/flag/flags.ts index fdca62959..a46abfb4a 100644 --- a/packages/browser-sdk/src/flag/flags.ts +++ b/packages/browser-sdk/src/flag/flags.ts @@ -179,14 +179,20 @@ const REFRESH_LIMIT_WINDOW_MS = 60 * 1000; export type FlagOverrides = Record; -type BootstrappedState = { +/** Pre-fetched evaluated state used to bootstrap the client. */ +export type BootstrappedState = { protocolVersion: 2; - flags: RawFlags; + context: ReflagContext; + flags: Record< + string, + Omit & + Partial> + >; flagStateVersion?: number; }; type FlagsClientOptions = Partial & { - bootstrappedState?: BootstrappedState; + bootstrappedState?: Omit; cache?: FlagCache; rateLimiter?: RateLimiter; storage?: StorageAdapter; @@ -476,7 +482,7 @@ export class FlagsClient { } setFetchedFlags( - fetchedFlags: RawFlags, + fetchedFlags: BootstrappedState["flags"], triggerEvent = true, flagStateVersion?: number, ) { @@ -495,7 +501,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); } diff --git a/packages/browser-sdk/test/client.test.ts b/packages/browser-sdk/test/client.test.ts index 7cabaed00..f2fa6a6fc 100644 --- a/packages/browser-sdk/test/client.test.ts +++ b/packages/browser-sdk/test/client.test.ts @@ -3,7 +3,6 @@ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; import type { BulkEvent } from "../src/bulkQueue"; import { BootstrappedState, ReflagClient } from "../src/client"; -import { RawFlags } from "../src/flag/flags"; import { flagResponse, selectedFlag } from "./mocks/handlers"; import { server } from "./mocks/server"; import { testLogger } from "./testLogger"; @@ -40,7 +39,10 @@ function create( clients.push(client); return client; } -function bootstrap(flags: RawFlags, flagStateVersion = 1): BootstrappedState { +function bootstrap( + flags: BootstrappedState["flags"], + flagStateVersion = 1, +): BootstrappedState { return { protocolVersion: 2, context: { user: { id: "alice" }, company: { id: "acme" } }, @@ -95,6 +97,29 @@ describe("direct values and root checks", () => { }, ); + test("bootstraps and records the selected variant without rule results", async () => { + const client = create({ + bootstrappedState: bootstrap({ + flagA: { + value: "enhanced", + resolved: true, + variantKey: "enhanced", + sourceVersionId: "bootstrap-version", + errors: [], + }, + }), + }); + expect(client.getFlagResults().flagA.ruleResults).toEqual([]); + expect(client.getFlag("flagA", "default")).toBe("enhanced"); + await client.stop(); + expect(checks()[0]).toMatchObject({ + key: "flagA", + evalResult: "enhanced", + sourceVersionId: "bootstrap-version", + evalRuleResults: [], + }); + }); + test("forwards v2 diagnostics without adding initialization errors to bootstrap reads", async () => { const error = { code: "MISSING_CONTEXT_FIELD", @@ -112,6 +137,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(); diff --git a/packages/browser-sdk/test/flagCache.test.ts b/packages/browser-sdk/test/flagCache.test.ts index 801592f9a..5db0b9795 100644 --- a/packages/browser-sdk/test/flagCache.test.ts +++ b/packages/browser-sdk/test/flagCache.test.ts @@ -53,10 +53,22 @@ describe("v2 evaluated cache", () => { expect(parseAPIFlagsResponse(flags)).toEqual(flags); }); + test("accepts omitted rule results only in bootstrap snapshots", () => { + const { ruleResults: _ruleResults, ...flagA } = selectedFlag(true); + expect(parseAPIFlagsResponse({ flagA }, true)).toEqual({ + flagA: { ...flagA, ruleResults: [] }, + }); + expect(parseAPIFlagsResponse({ flagA })).toBeUndefined(); + expect( + parseAPIFlagsResponse({ flagA: { ...flagA, ruleResults: null } }, true), + ).toBeUndefined(); + }); + test.each([ null, true, {}, + { ...rule, ruleId: null }, { ...rule, ruleId: 1 }, { ...rule, matched: undefined }, { ...rule, matched: 1 }, @@ -72,12 +84,12 @@ describe("v2 evaluated cache", () => { { type: "variant", variantKey: 1 }, ].map((destination) => ({ ...rule, destination })), ])("rejects malformed rule diagnostics atomically: %j", (invalidRule) => { - expect( - parseAPIFlagsResponse({ - good: selectedFlag(true), - bad: { ...selectedFlag(true), ruleResults: [invalidRule] }, - }), - ).toBeUndefined(); + const flags = { + good: selectedFlag(true), + bad: { ...selectedFlag(true), ruleResults: [invalidRule] }, + }; + expect(parseAPIFlagsResponse(flags)).toBeUndefined(); + expect(parseAPIFlagsResponse(flags, true)).toBeUndefined(); }); test.each([ diff --git a/packages/node-sdk/README.md b/packages/node-sdk/README.md index d0d07a465..3536cc03c 100644 --- a/packages/node-sdk/README.md +++ b/packages/node-sdk/README.md @@ -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 @@ -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 diff --git a/packages/node-sdk/src/client.ts b/packages/node-sdk/src/client.ts index a7e8b438a..a8ae5eb32 100644 --- a/packages/node-sdk/src/client.ts +++ b/packages/node-sdk/src/client.ts @@ -516,19 +516,31 @@ export class ReflagClient { .filter((flag) => flag.secret === false) .map((flag) => flag.key), ); - const publicFlags = Object.fromEntries( - Object.entries(flags) - .filter(([key]) => publicKeys.has(key)) - .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. - errors: result.errors.map(({ source: _source, ...error }) => error), - }, - ]), - ); + const publicFlags: BootstrappedFlags["flags"] = Object.create(null); + for (const [key, result] of Object.entries(flags)) { + // Omit entries without a value. Reads still use their fallback, and v2 + // client types expect each entry to have a value property. + if (!publicKeys.has(key) || result.value === undefined) continue; + publicFlags[key] = { + resolved: result.resolved, + value: result.value, + ...(result.resolved && + result.variantKey !== undefined && + result.sourceVersionId !== undefined + ? { + variantKey: result.variantKey, + sourceVersionId: result.sourceVersionId, + } + : {}), + // Released v2 readers require the array and its rule IDs. + ruleResults: result.ruleResults.map(({ ruleId, matched }) => ({ + ruleId, + matched, + })), + // Dependency origins can name private flags or segments. + errors: result.errors.map(({ source: _source, ...error }) => error), + }; + } return { protocolVersion: 2, context: JSON.parse( diff --git a/packages/node-sdk/src/types.ts b/packages/node-sdk/src/types.ts index 917105166..2bdc6c19c 100644 --- a/packages/node-sdk/src/types.ts +++ b/packages/node-sdk/src/types.ts @@ -105,7 +105,14 @@ export type RawFlags = Record; export type BootstrappedFlags = { protocolVersion: 2; context: Context; - flags: RawFlags; + flags: Record< + string, + Pick & { + value: FlagValue; + ruleResults: Pick[]; + errors: (EvaluationError & { source?: never })[]; + } + >; flagStateVersion?: number; }; export type EvaluatedFlagsAPIResponse = { diff --git a/packages/node-sdk/test/bootstrap-secrecy.test.ts b/packages/node-sdk/test/bootstrap-secrecy.test.ts index 1bfd74aad..9c279f74c 100644 --- a/packages/node-sdk/test/bootstrap-secrecy.test.ts +++ b/packages/node-sdk/test/bootstrap-secrecy.test.ts @@ -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", @@ -154,6 +154,69 @@ 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("leaves flags without an evaluated value out of the snapshot", async () => { + const flag = definition("unresolved", false); + flag.rules.unshift({ + id: "unresolved-rollout", + filter: { type: "constant", value: true }, + result: Object.assign( + { + type: "percentageDistribution" as const, + key: "unresolved-rollout", + attribute: "company.id", + allocations: [ + { + percentage: 100, + destination: { type: "variant" as const, variantKey: "default" }, + }, + ], + }, + // Force evaluation to return no value despite the required catch-all. + { error: "Unusable rollout" }, + ), + }); + const h = harness(snapshot([flag, definition("available", null)])); + await h.client.initialize(); + expect(h.client.getFlags(context)).toStrictEqual({ + unresolved: undefined, + available: null, + }); + expect(h.client.getFlagsForBootstrap(context).flags).toStrictEqual({ + available: expect.objectContaining({ value: null }), + }); + }); + it.each([undefined, null, "false", 0, {}, true])( "does not treat visibility %j as an explicit public declaration", async (secret) => { @@ -187,7 +250,6 @@ describe("bootstrap visibility boundary", () => { const bootstrap = h.client.getFlagsForBootstrap(context); expect(bootstrap.flags).toEqual({ public: { - flagKey: "public", value: { nested: [false] }, resolved: false, ruleResults: [], diff --git a/packages/node-sdk/type-tests/defaults.ts b/packages/node-sdk/type-tests/defaults.ts index edbba7ed7..5d3d29518 100644 --- a/packages/node-sdk/type-tests/defaults.ts +++ b/packages/node-sdk/type-tests/defaults.ts @@ -9,6 +9,7 @@ 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(); @@ -78,3 +79,14 @@ expectTypeOf( expectTypeOf(client.getFlagRemote("settings", interfaceDefault)).toEqualTypeOf< Promise >(); + +// Node bootstrap must be assignable to the original v2 browser flag shape. +expectTypeOf(client.getFlagsForBootstrap({}).flags).toExtend< + Record< + string, + { + value: FlagValue | undefined; + ruleResults: { ruleId: string; matched: boolean }[]; + } + > +>(); diff --git a/packages/react-sdk/src/index.tsx b/packages/react-sdk/src/index.tsx index abd073cf1..256713f52 100644 --- a/packages/react-sdk/src/index.tsx +++ b/packages/react-sdk/src/index.tsx @@ -78,9 +78,7 @@ export type OptInFlag = Omit & { */ export type RawFlags = BrowserRawFlags; -export type BootstrappedFlags = BrowserBootstrappedState & { - flags: BrowserRawFlags; -}; +export type BootstrappedFlags = BrowserBootstrappedState; const SDK_VERSION = `react-sdk/${version}`;