flags / vercel-flags-core
CLAUDE.md622 starsChanged 3 months agoMITView on GitHub
Core feature flag evaluation engine for Vercel. Handles flag evaluation, real-time updates via streaming, and usage tracking. Authentication (controller/auth.ts) is built from the value passed to createClient: Auth.sourceProjectId names another project to read with the same OIDC token: X-Vercel-Flags-Project-Id is added on datafile, stream, and ingest requests (authHeaders()), bundled definitions are looked up by that id, and events bypass the runtime ingest transport because it attributes to the calling project. Nothing sets it yet. The Controller's unauthorized flag gates usage…
In this repository4 other files it gives its agents.
- apps/docs/AGENTS.mdAGENTS.md
- apps/playground/AGENTS.mdAGENTS.md
- apps/playground/CLAUDE.mdCLAUDE.md
- flags-sdkSkill
The file
Show its rules and text
We split this CLAUDE.md into the rules it gives an agent
20 rules. About 0 are common, 6 are distinctive, and 14 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈6
Distinctive · estimate
This author's own choices. Worth a look.
14
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 89
Look up environment config
- Distinctive: line 90
Check targeting rules (shortcut for immediate match)
- Very specific: line 109
When metricEnvironment is provided, evaluation metrics sent to /v1/ingest include it as X-Vercel-Env.
- Very specific: line 118
Provided datafile: - Use options.datafile if provided
- Very specific: line 119
Bundled definitions: - Use @vercel/flags-definitions
- Distinctive: line 121
Throw: - If all above fail
- Very specific: line 134
When streaming or polling is enabled and data already exists (bundled or provided), initialize() still waits for fresh data (stream …
- Distinctive: line 137
If stream reconnects while polling → stop polling
- Distinctive: line 138
If stream disconnects → start polling (if enabled)
- Very specific: line 139
Use buildStep: true to force static-only mode (e.g., serverless cold starts)
- Very specific: line 140
Use buildStep: false to force runtime mode (e.g., custom build environments)
- Very specific: line 168
All commands must be run from the package directory (packages/vercel-flags-core):
- Very specific: line 195
No stderr leaks: every console.warn and console.error the implementation emits must be captured by a spy (vi.spyOn(console, …
- Very specific: line 206
With fake timers: call client.initialize() (or client.evaluate() which triggers lazy init), then await …
- Very specific: line 224
Only call initialize() explicitly when the test specifically needs to verify initialization behavior (e.g., deduplication, timing, init …
- Distinctive: line 235
When updating tests for new behavior, preserve the strength of existing assertions:
- Very specific: line 236
Keep exact call count checks (e.g., expect(streamCalls).toHaveLength(2)) rather than weakening to .toBeGreaterThanOrEqual(1)
- Very specific: line 237
Keep specific header assertions (e.g., X-Retry-Attempt values) rather than removing them
- Very specific: line 238
Keep errorSpy/warnSpy assertions rather than dropping them
- Very specific: line 259
Default intervalMs: 30000ms (30s)
≈ “Common” is an estimate: at least 1 in 5 of the 12,729 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
@vercel/flags-core
Core feature flag evaluation engine for Vercel. Handles flag evaluation, real-time updates via streaming, and usage tracking.
Package Structure
src/
├── index.default.ts # Default exports
├── index.next-js.ts # Next.js exports (with 'use cache')
├── index.common.ts # Shared exports
├── index.make.ts # Client factory
├── types.ts # Type definitions
├── errors.ts # Error classes
├── evaluate.ts # Core evaluation logic
├── controller-fns.ts # Controller function wrappers + instance map
├── create-raw-client.ts # Raw client factory (ID-based indirection for 'use cache')
├── controller/ # Controller (state machine) and I/O sources
│ ├── index.ts # Controller class
│ ├── stream-source.ts # StreamSource (wraps stream-connection)
│ ├── polling-source.ts # PollingSource (wraps fetch-datafile)
│ ├── bundled-source.ts # BundledSource (wraps read-bundled-definitions)
│ ├── stream-connection.ts # Low-level NDJSON stream connection
│ ├── fetch-datafile.ts # HTTP datafile fetch
│ ├── tagged-data.ts # Data origin tagging types/helpers
│ ├── normalized-options.ts # Option normalization
│ └── typed-emitter.ts # Lightweight typed event emitter
├── openfeature.*.ts # OpenFeature provider
├── test-utils.ts # Shared test helpers
├── utils/ # Utilities
│ ├── usage-tracker.ts
│ ├── sdk-keys.ts
│ ├── sleep.ts
│ └── read-bundled-definitions.ts
└── lib/
└── report-value.ts # Flag evaluation reporting to Vercel request contextArchitecture
Data flow
createClient(sdkKey, options)
→ Controller (state machine, owns all data tagging and source coordination)
→ StreamSource / PollingSource / BundledSource (emit raw DatafileInput)
→ create-raw-client (ID-based indirection for 'use cache' support)
→ controller-fns (lookup by ID, evaluate, report)
→ FlagsClient (public API)Authentication
Authentication (controller/auth.ts) is built from the value passed to createClient:
vf_server_*/vf_client_*orflags:…&sdkKey=vf_…→ SDK key mode. The key is the bearer token and the bundled-definitions lookup key (hashed).undefined→ OIDC mode for the deployment's own project. The bearer token comes from@vercel/oidc; bundled definitions are looked up by the token'sproject_id.
Auth.sourceProjectId names another project to read with the same OIDC token: X-Vercel-Flags-Project-Id is added on datafile, stream, and ingest requests (authHeaders()), bundled definitions are looked up by that id, and events bypass the runtime ingest transport because it attributes to the calling project. Nothing sets it yet.
The Controller's unauthorized flag gates usage tracking. It is set on a 401 from any source (stream init, poll, one-time fetch) and cleared when a source delivers data again, so a transient 401 does not silence tracking for the client's lifetime.
Design principles
- Sources emit raw data — StreamSource, PollingSource, and BundledSource return/emit raw
DatafileInput. The Controller is solely responsible for tagging data with its origin (tagData(data, 'stream')etc.). - BundledSource is a plain class — unlike StreamSource and PollingSource which extend TypedEmitter, BundledSource has no event listeners. The Controller calls its methods directly and uses return values.
- Tests are black-box — all behavioral tests go through the public API (
createClientfrom./index.default). MockreadBundledDefinitionsandinternalReportValueas observable I/O. UsefetchMockfor network assertions. - ID-based indirection —
controller-fns.tsholds acontrollerInstanceMap(Map<number, ControllerInstance>) so that'use cache'wrappers in Next.js can pass serializable IDs instead of function references.
Key Concepts
FlagsClient
Main interface for interacting with flags:
type FlagsClient = {
initialize(): Promise<void>;
shutdown(): Promise<void>;
getDatafile(): Promise<Datafile>;
getFallbackDatafile(): Promise<BundledDefinitions>;
evaluate<T, E>(flagKey, defaultValue?, entities?): Promise<EvaluationResult<T>>;
}Evaluation Flow
- Retrieve flag definition from datafile
- Look up environment config
- Check targeting rules (shortcut for immediate match)
- Evaluate segment-based rules against entity context
- Return fallthrough default if no match
Controller Options
type ControllerOptions = {
auth: Auth;
datafile?: Datafile; // Initial datafile for immediate reads
stream?: boolean | { initTimeoutMs: number }; // default: true (3000ms)
polling?: boolean | { intervalMs: number; initTimeoutMs: number }; // default: true (30s interval, 3s timeout)
buildStep?: boolean; // Override build step auto-detection
metricEnvironment?: string; // Environment attached to ingested evaluation metrics
waitUntil?: (promise: Promise<unknown>) => void; // default: @vercel/functions waitUntil
sources?: { stream?: StreamSource; polling?: PollingSource; bundled?: BundledSource }; // DI for testing
};When metricEnvironment is provided, evaluation metrics sent to /v1/ingest
include it as X-Vercel-Env. The option does not affect datafile, polling, or
stream requests, or the environment used for flag evaluation.
Data Source Priority (Fallback Chain)
Behavior differs based on environment:
Build step (CI=1, NEXT_PHASE=phase-production-build, or buildStep: true):
- Provided datafile - Use
options.datafileif provided - Bundled definitions - Use
@vercel/flags-definitions - One-time fetch - Fallback network request
- Throw - If all above fail
Build-step reads are deduplicated: data is loaded once via a shared promise (buildDataPromise) and all concurrent evaluate() calls share the result. The entire build counts as a single tracked read event (buildReadTracked flag in Controller).
Runtime (default, or buildStep: false):
- Stream - Real-time updates via NDJSON streaming, wait up to
initTimeoutMs - Polling - Interval-based HTTP requests, wait up to
initTimeoutMs - Provided datafile - Use
options.datafileif provided - Bundled definitions - Use
@vercel/flags-definitions - One-time fetch - Last resort (only when stream and polling are both disabled)
Key behaviors:
- Bundled definitions are loaded eagerly so their revision can be sent to the stream via
X-Revisionheader - When streaming or polling is enabled and data already exists (bundled or provided),
initialize()still waits for fresh data (stream confirmation or first poll) up toinitTimeoutMs, then falls back to existing data on timeout - For offline mode with existing data,
initialize()returns immediately - Never stream AND poll simultaneously
- If stream reconnects while polling → stop polling
- If stream disconnects → start polling (if enabled)
- Use
buildStep: trueto force static-only mode (e.g., serverless cold starts) - Use
buildStep: falseto force runtime mode (e.g., custom build environments)
Resolution Reasons
TARGET_MATCH- Matched targeting rulesRULE_MATCH- Matched conditional rulesFALLTHROUGH- No match, returned fallbackPAUSED- Flag is pausedERROR- Evaluation error
Packed Format
Internal compact format for flag definitions:
- Variants stored as indices
- Conditions use tuples:
[LHS, Comparator, RHS](e.g.,[['user', 'id'], Comparator.EQ, 'user-123']) - Targets shorthand:
{ user: { id: ['user-123'] } } - Entities accessed via path arrays (e.g.,
['user', 'id'])
Entry Points
The package has conditional exports based on environment:
- Default:
./dist/index.default.js- Standard usage - Next.js:
./dist/index.next-js.js- Wraps functions with'use cache' - OpenFeature:
./openfeature- OpenFeature server SDK provider
Commands
All commands must be run from the package directory (packages/vercel-flags-core):
# Build
pnpm build
# Run all tests
pnpm test
# Run a single test file
pnpm vitest --run src/black-box.test.ts
# Run a single test file in watch mode
pnpm vitest src/black-box.test.ts
# Type check
pnpm check
# Integration tests (requires INTEGRATION_TEST_CONNECTION_STRING)
pnpm test:integrationTest Guidelines (black-box.test.ts)
Critical rules
- All tests must use fake timers unless there is a specific reason to use
vi.useRealTimers(). ThebeforeEachsets up fake timers; only opt out when testing real async timing. - No stderr leaks: every
console.warnandconsole.errorthe implementation emits must be captured by a spy (vi.spyOn(console, 'warn').mockImplementation(() => {})) and asserted. A test that produces stderr output is broken. - Tests should complete in milliseconds, not seconds. If a test takes ~3s, it's hitting a real timeout instead of advancing fake timers.
initialize() blocks on stream/poll confirmation
initialize() waits for fresh data before resolving, even when bundled data or a provided datafile is available:
- Streaming: waits for a stream message (
primedordatafile) up toinitTimeoutMs - Polling: waits for the first poll response up to
initTimeoutMs
This means:
- With fake timers: call
client.initialize()(orclient.evaluate()which triggers lazy init), thenawait vi.advanceTimersByTimeAsync(initTimeoutMs)to trigger the timeout fallback. - With real timers (
vi.useRealTimers()): for streaming, you MUST push a stream message before awaitinginitialize(), otherwise it blocks for the real 3s timeout:
For polling,const initPromise = client.initialize(); await new Promise((r) => setTimeout(r, 0)); // let stream connect stream.push({ type: 'primed', revision: 42, projectId: 'prj_123', environment: 'production' }); await initPromise; // resolves immediatelyinitialize()will await the first poll (which resolves immediately iffetchMockresponds synchronously).
Prefer evaluate-driven tests over explicit initialize()
Many tests on the control branch test that evaluate() triggers lazy initialization. Prefer this pattern to test the full public API path:
const evalPromise = client.evaluate('flagA');
await vi.advanceTimersByTimeAsync(3_000);
const result = await evalPromise;Only call initialize() explicitly when the test specifically needs to verify initialization behavior (e.g., deduplication, timing, init promise resolution).
Assert console output from the implementation
The implementation logs warnings/errors for specific conditions. Tests must assert these:
- Stream timeout:
console.warn('@vercel/flags-core: Stream initialization timeout, falling back while continuing to connect in the background') - Stream error: retryable failures are silent; the error is only logged once retries are exhausted via
console.error('@vercel/flags-core: Max retry count exceeded', lastError) - 401 fast-fail:
console.errorwith auth error (no retry, no timeout wait)
Do not weaken assertions when adapting tests
When updating tests for new behavior, preserve the strength of existing assertions:
- Keep exact call count checks (e.g.,
expect(streamCalls).toHaveLength(2)) rather than weakening to.toBeGreaterThanOrEqual(1) - Keep specific header assertions (e.g.,
X-Retry-Attemptvalues) rather than removing them - Keep
errorSpy/warnSpyassertions rather than dropping them
Important Implementation Details
Stream Connection
- Uses fetch with streaming body (NDJSON format)
- Callbacks:
onDatafile(new data),onPrimed(server confirmed revision is current),onDisconnect - Sends
X-Revisionheader with the current revision number on every connection (including reconnects), allowing the server to respond with a lightweightprimedmessage instead of a full datafile when the revision is current - The
primedmessage confirms the client's data is up-to-date; it resolves the init promise (likedatafile) but does not update data — only transitions state tostreaming - Reconnects with exponential backoff (base: 1s, max: 60s, max retries: 15)
- Retries on transient errors both before and after initial data is received. Before initial data, retries continue until max retries are exhausted or the abort controller is aborted (e.g., by the Controller's init timeout). The init promise rejects when the loop exits without data.
- Default
initTimeoutMs: 3000ms - 401 errors abort immediately (invalid SDK key) and reject the init promise, so fallback kicks in without waiting for the stream timeout
- On disconnect: state transitions to
'degraded', falls back to polling if enabled - On reconnect: Controller listens for
'connected'event and transitions back to'streaming' - Background stream promises (from init timeout) are
.catch-ed by the Controller to prevent unhandled rejections when the stream is aborted before receiving data
Polling
- Interval-based HTTP requests to
/v1/datafile - Default
intervalMs: 30000ms (30s) - Default
initTimeoutMs: 3000ms (3s) - Datafile fetches use three total attempts with 100ms and 200ms backoff for network, token, body parsing, and transient HTTP failures (408, 429, and 5xx). Other HTTP errors fail immediately. After exhausted retries, polling emits an error event and waits for the next interval.
- Stops automatically when stream reconnects
PollingSourcepasses its abort signal tofetchDatafilefor both initialization and scheduled polls, so callingstop()cancels pending requests and backoff without emitting a shutdown error.fetchDatafileowns a ten-second deadline covering token resolution, all attempts and backoff, and body parsing. It settles on timeout or cancellation even when a transport ignores its signal, and preserves the external abort reason.- Retries are enabled by default for every
fetchDatafilecaller: polling, build loading, offline initialization/evaluation, and directgetDatafile()fallback. Internal callers can overridemaxAttempts; retry scheduling and deadline handling remain in the fetch helper, independently of source classes and cache policy.
Data Origin Tagging
The Controller tags all data with its origin using tagData(data, origin) from tagged-data.ts. Origins map to public metrics.source values:
'stream','poll','provided'→'in-memory''fetched'→'remote''bundled'→'embedded'
tagData mutates the input object in-place via Object.assign (callers always pass freshly-created data).
Usage Tracking
- Batches flag read/evaluation events; flushes on either a 5s idle window (reset on every event) or a 60s max window (starts with the batch, never reset) — flushing is purely time-based, and each flush is sent in sequential POSTs of at most 2000 events (see
MAX_EVENTS_PER_REQUESTiningest.ts) - The scheduled flush awaits the full ingest send (incl. retries) before its
waitUntilpromise resolves;shutdown()drains any in-flight batch instead of orphaning it - Sends to
flags.vercel.com/v1/ingest - At runtime: deduplicates by request context (per-instance WeakSet in UsageTracker)
- During builds: deduplicates all reads to a single event (buildReadTracked flag in Controller), since there is no request context available
- Uses a custom
waitUntil()passed tocreateClient, or defaults to@vercel/functions(wrapped in try/catch for resilience) - The Next.js conditional export defaults to
after()fromnext/server; an explicitwaitUntiloption always takes precedence - Exposure reporting does not block evaluation;
shutdown()drains pending exposure reports for graceful shutdown in long-lived processes - On flush failure, events are re-queued for retry with a max queue size of 500 events (oldest events are dropped when exceeded)
flush()directly flushes queued events even when no scheduled flush is pending, ensuring events are not lost duringshutdown()
Client Management
- Each client gets unique incrementing ID
- Stored in
controllerInstanceMapincontroller-fns.ts - Supports multiple simultaneous clients
- Necessary as we can't pass functions to
'use cache'wrappers
configUpdatedAt Guard
The Controller rejects incoming data (from stream or poll) if its configUpdatedAt is older than or equal to the current in-memory data. This prevents stale updates from overwriting newer data. Accepts the update if either side lacks a configUpdatedAt.
Evaluation Reporting
internalReportValue(defined inlib/report-value.ts, called fromcontroller-fns.ts) reports flag evaluations to the Vercel request context- Reports are sent for all evaluations where
datafile.projectIdexists, including error cases (e.g., FLAG_NOT_FOUND)
Evaluation Safety
- Regex comparators (
REGEX,NOT_REGEX) limit input string length to 10,000 characters to prevent ReDoS read()andgetDatafile()return new objects with spread (never mutatethis.data)
Debug Mode
Enable debug logging with DEBUG=@vercel/flags-core environment variable.
Dependencies
@vercel/functions- ForwaitUntil()jose- JWT handlingjs-xxhash- Hash function for consistent splits
Peer dependencies:
@openfeature/server-sdk(optional) - For OpenFeature providerflags(workspace) - Type definitions
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

