@wellth-app/experiments 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +223 -2
  2. package/dist/cjs/index.js +10 -0
  3. package/dist/cjs/index.js.map +1 -0
  4. package/dist/cjs/react.js +317 -0
  5. package/dist/cjs/react.js.map +1 -0
  6. package/dist/cjs/registry-pg5aaOm-.js +537 -0
  7. package/dist/cjs/registry-pg5aaOm-.js.map +1 -0
  8. package/dist/cjs/web.js +87 -0
  9. package/dist/cjs/web.js.map +1 -0
  10. package/dist/esm/index.js +3 -0
  11. package/dist/esm/index.js.map +1 -0
  12. package/dist/esm/react.js +290 -0
  13. package/dist/esm/react.js.map +1 -0
  14. package/dist/esm/registry-B73fwn9J.js +534 -0
  15. package/dist/esm/registry-B73fwn9J.js.map +1 -0
  16. package/dist/esm/web.js +85 -0
  17. package/dist/esm/web.js.map +1 -0
  18. package/dist/events.d.ts +65 -0
  19. package/dist/events.d.ts.map +1 -0
  20. package/dist/index.d.ts +10 -0
  21. package/dist/index.d.ts.map +1 -0
  22. package/dist/react/context.d.ts +37 -0
  23. package/dist/react/context.d.ts.map +1 -0
  24. package/dist/react/guard.d.ts +11 -0
  25. package/dist/react/guard.d.ts.map +1 -0
  26. package/dist/react/index.d.ts +12 -0
  27. package/dist/react/index.d.ts.map +1 -0
  28. package/dist/react/provider.d.ts +38 -0
  29. package/dist/react/provider.d.ts.map +1 -0
  30. package/dist/react/use-analytics.d.ts +12 -0
  31. package/dist/react/use-analytics.d.ts.map +1 -0
  32. package/dist/react/use-experiment-qa.d.ts +14 -0
  33. package/dist/react/use-experiment-qa.d.ts.map +1 -0
  34. package/dist/react/use-experiment.d.ts +30 -0
  35. package/dist/react/use-experiment.d.ts.map +1 -0
  36. package/dist/react/use-feature-flag.d.ts +16 -0
  37. package/dist/react/use-feature-flag.d.ts.map +1 -0
  38. package/dist/react/use-feature-value.d.ts +16 -0
  39. package/dist/react/use-feature-value.d.ts.map +1 -0
  40. package/dist/registry.d.ts +143 -0
  41. package/dist/registry.d.ts.map +1 -0
  42. package/dist/types.d.ts +111 -0
  43. package/dist/types.d.ts.map +1 -0
  44. package/dist/uuid.d.ts +6 -0
  45. package/dist/uuid.d.ts.map +1 -0
  46. package/dist/web/batched-event-sender.d.ts +35 -0
  47. package/dist/web/batched-event-sender.d.ts.map +1 -0
  48. package/dist/web/index.d.ts +7 -0
  49. package/dist/web/index.d.ts.map +1 -0
  50. package/package.json +127 -4
  51. package/src/events.ts +90 -0
  52. package/src/index.ts +37 -0
  53. package/src/react/context.ts +62 -0
  54. package/src/react/guard.ts +25 -0
  55. package/src/react/index.ts +17 -0
  56. package/src/react/provider.tsx +109 -0
  57. package/src/react/use-analytics.ts +17 -0
  58. package/src/react/use-experiment-qa.ts +26 -0
  59. package/src/react/use-experiment.ts +72 -0
  60. package/src/react/use-feature-flag.ts +35 -0
  61. package/src/react/use-feature-value.ts +42 -0
  62. package/src/registry.ts +715 -0
  63. package/src/types.ts +120 -0
  64. package/src/uuid.ts +14 -0
  65. package/src/web/batched-event-sender.ts +111 -0
  66. package/src/web/index.ts +9 -0
@@ -0,0 +1,715 @@
1
+ import {
2
+ GrowthBookClient,
3
+ setPolyfills,
4
+ type FeatureApiResponse,
5
+ type FeatureDefinition,
6
+ type FeatureDefinitions,
7
+ type FeatureResultSource,
8
+ type FeatureRule,
9
+ } from "@growthbook/growthbook";
10
+ import {
11
+ buildExperimentExposure,
12
+ type EventStream,
13
+ type ExposureSurface,
14
+ type StreamEvent,
15
+ } from "./events";
16
+ import type {
17
+ ExperimentParams,
18
+ ExposureInput,
19
+ KeyValueStorage,
20
+ OverrideEntry,
21
+ Overrides,
22
+ QaPin,
23
+ ResolvedAssignment,
24
+ TargetingAttributes,
25
+ } from "./types";
26
+ import { newId } from "./uuid";
27
+
28
+ /**
29
+ * The features-endpoint payload the registry consumes. This is the wire format of
30
+ * `<sdk-host>/api/features/<clientKey>` — the config the evaluation engine
31
+ * downloads once and then evaluates entirely locally.
32
+ */
33
+ export type RegistryPayload = FeatureApiResponse;
34
+
35
+ export interface RegistryInitOptions {
36
+ /** The SDK key identifying the environment's config on the features endpoint. */
37
+ clientKey?: string;
38
+ /** The SDK host. When absent, the evaluation client's built-in default host applies. */
39
+ apiHost?: string;
40
+ }
41
+
42
+ export interface EvaluateExperimentInput {
43
+ experimentKey: string;
44
+ subjectId: string;
45
+ attributes?: TargetingAttributes;
46
+ }
47
+
48
+ export interface EvaluateFlagInput {
49
+ featureKey: string;
50
+ subjectId: string;
51
+ attributes?: TargetingAttributes;
52
+ }
53
+
54
+ /** An experiment's remote start/stop. Anything not running is stopped. */
55
+ export type ExperimentStatus = "running" | "stopped";
56
+
57
+ /**
58
+ * A config key's shape, for the hooks' misuse guard. "experiment" keys carry
59
+ * an experiment-shaped rule (live or not); "flag" keys carry flag-shaped
60
+ * rules. A bare-default key reports "unknown": a stopped experiment and a
61
+ * static default are indistinguishable, and both read fail-closed from either
62
+ * path, so no guard fires.
63
+ */
64
+ export type KeyKind = "experiment" | "flag" | "unknown";
65
+
66
+ /**
67
+ * How a flag resolved. The evaluation engine's source vocabulary, re-exported
68
+ * under our name: "force" (a targeting/rollout rule matched), "defaultValue"
69
+ * (no rule matched), "unknownFeature" (absent from the config), and the rarer
70
+ * engine outcomes.
71
+ */
72
+ export type FlagSource = FeatureResultSource;
73
+
74
+ /** A feature flag's resolution for one subject. Flags never log exposure. */
75
+ export interface FlagEvaluation {
76
+ /** The flag's resolved value — rule value, or the config's default. */
77
+ value: unknown;
78
+ /** Boolean convenience over the value. */
79
+ on: boolean;
80
+ off: boolean;
81
+ source: FlagSource;
82
+ }
83
+
84
+ interface ExperimentVariation {
85
+ key: string;
86
+ params: ExperimentParams;
87
+ }
88
+
89
+ interface FeatureEntry {
90
+ /** The feature key call sites pass — the experiment's key by platform convention. */
91
+ key: string;
92
+ /** The key written to exposure events (the config rule's tracking key when it differs). */
93
+ experimentKey: string;
94
+ status: ExperimentStatus;
95
+ /**
96
+ * True when the config carries ANY experiment-shaped rule (two or more arms)
97
+ * for this key — regardless of lifecycle status or hash-contract trust. The
98
+ * flag path keys on presence, not parse status: the engine would still
99
+ * evaluate a failed-closed rule, so an experiment-shaped key must never
100
+ * reach it.
101
+ */
102
+ hasExperimentRule: boolean;
103
+ /**
104
+ * True when the config carries any rule for this key that is NOT
105
+ * experiment-shaped (a targeting/rollout/force rule) — an actively
106
+ * configured flag. Drives the misuse guard's flag classification.
107
+ */
108
+ hasFlagRule: boolean;
109
+ controlKey: string;
110
+ variations: readonly ExperimentVariation[];
111
+ /** The config's default payload, shaped for the experiment path. */
112
+ defaultParams: ExperimentParams;
113
+ /** The config's default value, raw — the flag path's default read. */
114
+ defaultValue: unknown;
115
+ }
116
+
117
+ export interface FeatureRegistry {
118
+ /**
119
+ * Fetch the experiment config from the features endpoint and start keeping it
120
+ * fresh. The evaluation client caches locally and revalidates stale reads in
121
+ * the background; init resolves with the cached config when one exists. Without
122
+ * a client key the registry stays disabled: every experiment reads control,
123
+ * every flag reads its fallback, and nothing is fetched. A failed fetch leaves
124
+ * the registry serving defaults, never throwing into the app.
125
+ */
126
+ init: (options: RegistryInitOptions) => Promise<void>;
127
+ /** Seed the registry synchronously from an already-available payload (tests, SSR). */
128
+ initSync: (options: { payload: RegistryPayload }) => void;
129
+ /**
130
+ * Re-fetch the config now (e.g. on app foreground). No-op on a disabled or
131
+ * payload-seeded registry — a seeded registry is fresh by construction and
132
+ * has no endpoint to refresh from.
133
+ */
134
+ refresh: () => Promise<void>;
135
+ /**
136
+ * Resolve the assignment for one subject. The evaluation order: a stopped or
137
+ * unknown experiment reads control with no exposure (overrides never
138
+ * resurrect it); then, checked before delegating to the engine's local
139
+ * evaluation — QA pin, then registry overrides (migration / QA, unexpired
140
+ * only); then the engine (targeting conditions, then the deterministic hash
141
+ * bucket). Subject ids are normalized (trim + lowercase) inside the
142
+ * evaluator.
143
+ */
144
+ evaluateExperiment: (input: EvaluateExperimentInput) => ResolvedAssignment;
145
+ /**
146
+ * Resolve a feature flag for one subject: targeting conditions and percentage
147
+ * rollouts evaluate locally against the same deterministic hash. Flags never
148
+ * log exposure. An experiment-shaped key read here returns the config's
149
+ * default by design — experiments go through evaluateExperiment, which is the
150
+ * exposure-aware path.
151
+ */
152
+ evaluateFlag: (input: EvaluateFlagInput) => FlagEvaluation;
153
+ /**
154
+ * Record that an assignment became visible. Emits exactly one event per unique
155
+ * (experiment, subject, variant) assignment per session — repeat calls for the
156
+ * same assignment are deduplicated.
157
+ */
158
+ trackExposure: (input: ExposureInput) => void;
159
+ /** Send an event on the configured stream. No-op when no stream is configured. */
160
+ sendEvent: (event: StreamEvent) => void;
161
+ /** Force a variant for one subject on this session. Pins never emit exposure. */
162
+ pin: (pin: QaPin) => void;
163
+ unpin: (input: { experimentKey: string }) => void;
164
+ getPins: () => readonly QaPin[];
165
+ /**
166
+ * The key's config shape, for the hooks' misuse guard: "experiment" when it
167
+ * carries an experiment-shaped rule (live or not), "flag" when it carries
168
+ * flag-shaped rules only, "unknown" otherwise (no config, or a bare default
169
+ * — indistinguishable from a stopped experiment, so no guard fires).
170
+ */
171
+ getKeyKind: (key: string) => KeyKind;
172
+ /** React subscription: re-render when the config or pins change. */
173
+ subscribe: (listener: () => void) => () => void;
174
+ getVersion: () => number;
175
+ /** True once a config payload is loaded and evaluations reflect it. */
176
+ isReady: () => boolean;
177
+ /** True when the registry was given a client key (evaluations are live config). */
178
+ isEnabled: () => boolean;
179
+ /** The loaded config's version (the payload's dateUpdated), null when unknown. */
180
+ getConfigVersion: () => string | null;
181
+ destroy: () => void;
182
+ }
183
+
184
+ interface FeatureRegistryOptions {
185
+ /**
186
+ * The surface exposures are stamped with. Required — each app declares
187
+ * itself; there is no default.
188
+ */
189
+ surface: ExposureSurface;
190
+ events?: EventStream;
191
+ overrides?: Overrides;
192
+ /**
193
+ * Where the config cache persists (AsyncStorage on React Native). Unset, the
194
+ * engine uses the platform's localStorage when present and memory otherwise.
195
+ */
196
+ cacheStorage?: KeyValueStorage;
197
+ /**
198
+ * Where config-guard warnings go: an experiment rule that breaks the platform
199
+ * contract fails closed and names its feature key here. Default: console.warn.
200
+ */
201
+ warn?: (message: string) => void;
202
+ }
203
+
204
+ /** The arm key returned when the experiment config doesn't name one. */
205
+ const CONTROL_VARIANT_KEY = "control";
206
+
207
+ /**
208
+ * The default warning channel. Apps route config-guard warnings through the
209
+ * `warn` option (their own logger or telemetry); unset, they land here.
210
+ */
211
+ const defaultWarn: (message: string) => void = (message) => {
212
+ // eslint-disable-next-line no-console -- the one sanctioned console call
213
+ console.warn(message);
214
+ };
215
+
216
+ /**
217
+ * Ids normalize inside the evaluator — trim + lowercase — so casing/whitespace
218
+ * drift at a call site can never scramble a cohort. The warehouse applies the
219
+ * same normalization before hashing.
220
+ */
221
+ function normalizeSubject(subjectId: string): string {
222
+ return subjectId.trim().toLowerCase();
223
+ }
224
+
225
+ /** The plain string form is a migration entry; entries may carry expiry + kind. */
226
+ function toOverrideEntry(
227
+ value: string | OverrideEntry | undefined,
228
+ ): OverrideEntry | undefined {
229
+ if (value === undefined) return undefined;
230
+ return typeof value === "string" ? { variant: value } : value;
231
+ }
232
+
233
+ function isLive(entry: OverrideEntry): boolean {
234
+ return (
235
+ entry.expiresAt === undefined || Date.parse(entry.expiresAt) > Date.now()
236
+ );
237
+ }
238
+
239
+ export function createFeatureRegistry(
240
+ options: FeatureRegistryOptions,
241
+ ): FeatureRegistry {
242
+ const surface = options.surface;
243
+ const events = options.events;
244
+ // Override map keys are subject ids; normalize them once at construction so
245
+ // a cutover export's casing/whitespace can never miss the lookup (ids
246
+ // normalize inside the evaluator, never at call sites).
247
+ const overrides: Overrides = {};
248
+ for (const [experimentKey, bySubject] of Object.entries(
249
+ options.overrides ?? {},
250
+ )) {
251
+ const normalized: Overrides[string] = {};
252
+ for (const [subjectKey, value] of Object.entries(bySubject)) {
253
+ normalized[normalizeSubject(subjectKey)] = value;
254
+ }
255
+ overrides[experimentKey] = normalized;
256
+ }
257
+ const cacheStorage = options.cacheStorage;
258
+ const warn = options.warn ?? defaultWarn;
259
+
260
+ let client: GrowthBookClient | null = null;
261
+ let activeClientKey: string | undefined;
262
+ let configVersion: string | null = null;
263
+ let entries: ReadonlyMap<string, FeatureEntry> = new Map();
264
+ let version = 0;
265
+ let enabled = false;
266
+ const pins = new Map<string, QaPin>();
267
+ const exposed = new Set<string>();
268
+ const listeners = new Set<() => void>();
269
+
270
+ const bump = (): void => {
271
+ version += 1;
272
+ for (const listener of listeners) listener();
273
+ };
274
+
275
+ const rebuildEntries = (): void => {
276
+ entries = client ? parseEntries(client.getFeatures(), warn) : new Map();
277
+ };
278
+
279
+ const captureConfigVersion = (): void => {
280
+ configVersion = client?.getPayload().dateUpdated ?? null;
281
+ };
282
+
283
+ const makeClient = (clientOptions?: {
284
+ apiHost?: string;
285
+ clientKey?: string;
286
+ }): GrowthBookClient => {
287
+ // The cache's persistent tier sits behind the app's storage when given
288
+ // (AsyncStorage on RN) — cold starts then evaluate offline from the last fetch.
289
+ if (cacheStorage) {
290
+ setPolyfills({ localStorage: cacheStorage });
291
+ }
292
+ return new GrowthBookClient(clientOptions ?? {});
293
+ };
294
+
295
+ const evaluateExperiment = ({
296
+ experimentKey,
297
+ subjectId,
298
+ attributes,
299
+ }: EvaluateExperimentInput): ResolvedAssignment => {
300
+ const subject = normalizeSubject(subjectId);
301
+ const entry = entries.get(experimentKey);
302
+
303
+ // Unknown, disabled, or stopped: control with no exposure. A stopped
304
+ // experiment always lands here — overrides never resurrect it.
305
+ if (client === null || !entry || entry.status === "stopped") {
306
+ return {
307
+ variant: entry?.controlKey ?? CONTROL_VARIANT_KEY,
308
+ params: entry?.defaultParams ?? {},
309
+ exposure: null,
310
+ };
311
+ }
312
+
313
+ // QA pins force a variant for the pinned subject and are never exposure.
314
+ const pin = pins.get(experimentKey);
315
+ if (pin && pin.subjectId === subject) {
316
+ const variation = findVariation(entry, pin.variant);
317
+ if (variation) {
318
+ return {
319
+ variant: variation.key,
320
+ params: variation.params,
321
+ exposure: null,
322
+ };
323
+ }
324
+ }
325
+
326
+ // Registry overrides keep a member on the assigned arm. Migration entries
327
+ // are real assignments and log exposure normally; QA entries log flagged
328
+ // as overrides so analysis drops them. Expired entries fall through to
329
+ // the hash as if they never existed.
330
+ const overrideEntry = toOverrideEntry(overrides[experimentKey]?.[subject]);
331
+ if (overrideEntry && isLive(overrideEntry)) {
332
+ const variation = findVariation(entry, overrideEntry.variant);
333
+ if (variation) {
334
+ return {
335
+ variant: variation.key,
336
+ params: variation.params,
337
+ exposure: {
338
+ experimentKey: entry.experimentKey,
339
+ subjectId: subject,
340
+ variant: variation.key,
341
+ configVersion,
342
+ override: overrideEntry.kind === "qa" ? true : undefined,
343
+ },
344
+ };
345
+ }
346
+ }
347
+
348
+ // Delegate to the engine's local evaluation: targeting conditions gate
349
+ // eligibility (including date windows — the registry always supplies the
350
+ // current ISO date as `date`), then the deterministic hash buckets the
351
+ // subject id. `id` is always the subject — attributes never override it.
352
+ const result = client.evalFeature(experimentKey, {
353
+ attributes: {
354
+ date: new Date().toISOString(),
355
+ ...attributes,
356
+ id: subject,
357
+ },
358
+ });
359
+ const experimentResult = result.experimentResult;
360
+ if (
361
+ result.source === "experiment" &&
362
+ experimentResult?.inExperiment === true
363
+ ) {
364
+ return {
365
+ variant: experimentResult.key,
366
+ params: isParams(result.value) ? result.value : entry.defaultParams,
367
+ exposure: {
368
+ experimentKey: entry.experimentKey,
369
+ subjectId: subject,
370
+ variant: experimentResult.key,
371
+ configVersion,
372
+ },
373
+ };
374
+ }
375
+
376
+ // Ineligible (targeting failed, outside the window, or outside coverage):
377
+ // the default arm, no exposure.
378
+ return {
379
+ variant: entry.controlKey,
380
+ params: entry.defaultParams,
381
+ exposure: null,
382
+ };
383
+ };
384
+
385
+ const evaluateFlag = ({
386
+ featureKey,
387
+ subjectId,
388
+ attributes,
389
+ }: EvaluateFlagInput): FlagEvaluation => {
390
+ const entry = entries.get(featureKey);
391
+
392
+ // Disabled or unknown: the null read.
393
+ if (client === null || !entry) {
394
+ return { value: null, on: false, off: true, source: "unknownFeature" };
395
+ }
396
+
397
+ // An experiment-shaped key read through the flag path gets the config's
398
+ // default, never the assigned value — that read would render a variant
399
+ // without an exposure event and corrupt the experiment's counts. Keyed on
400
+ // rule PRESENCE, not parse status: the engine would still evaluate a rule
401
+ // the parse guards failed closed, so a guarded key must never reach it.
402
+ if (entry.hasExperimentRule) {
403
+ return {
404
+ value: entry.defaultValue,
405
+ on: Boolean(entry.defaultValue),
406
+ off: !entry.defaultValue,
407
+ source: "defaultValue",
408
+ };
409
+ }
410
+
411
+ // Delegate to the engine's local evaluation: targeting conditions and
412
+ // percentage rollouts included.
413
+ const result = client.evalFeature(featureKey, {
414
+ attributes: {
415
+ date: new Date().toISOString(),
416
+ ...attributes,
417
+ id: normalizeSubject(subjectId),
418
+ },
419
+ });
420
+ return {
421
+ value: result.value,
422
+ on: result.on,
423
+ off: result.off,
424
+ source: result.source,
425
+ };
426
+ };
427
+
428
+ return {
429
+ async init({ clientKey, apiHost }: RegistryInitOptions): Promise<void> {
430
+ if (clientKey === undefined) return;
431
+ enabled = true;
432
+ activeClientKey = clientKey;
433
+ client = makeClient({ apiHost, clientKey });
434
+ await client.init();
435
+ rebuildEntries();
436
+ captureConfigVersion();
437
+ bump();
438
+ },
439
+ initSync({ payload }: { payload: RegistryPayload }): void {
440
+ enabled = true;
441
+ client = makeClient({});
442
+ client.initSync({ payload });
443
+ rebuildEntries();
444
+ captureConfigVersion();
445
+ bump();
446
+ },
447
+ async refresh(): Promise<void> {
448
+ if (client === null || activeClientKey === undefined) return;
449
+ await client.refreshFeatures();
450
+ rebuildEntries();
451
+ captureConfigVersion();
452
+ bump();
453
+ },
454
+ evaluateExperiment,
455
+ evaluateFlag,
456
+ getKeyKind(key: string): KeyKind {
457
+ const entry = entries.get(key);
458
+ if (!entry) return "unknown";
459
+ if (entry.hasExperimentRule) return "experiment";
460
+ return entry.hasFlagRule ? "flag" : "unknown";
461
+ },
462
+ trackExposure({
463
+ experimentKey,
464
+ subjectId,
465
+ variant,
466
+ configVersion: evaluatedConfigVersion,
467
+ override,
468
+ }: ExposureInput): void {
469
+ const subject = normalizeSubject(subjectId);
470
+ const dedupeKey = JSON.stringify([experimentKey, subject, variant]);
471
+ if (exposed.has(dedupeKey)) return;
472
+ exposed.add(dedupeKey);
473
+ events?.send(
474
+ buildExperimentExposure({
475
+ experimentKey,
476
+ subjectId: subject,
477
+ variant,
478
+ surface,
479
+ timestamp: Date.now(),
480
+ // The evaluation-time version — a config refresh between compute and
481
+ // render must not re-stamp the event.
482
+ configVersion: evaluatedConfigVersion,
483
+ exposureId: newId(),
484
+ override,
485
+ }),
486
+ );
487
+ },
488
+ sendEvent(event: StreamEvent): void {
489
+ events?.send(event);
490
+ },
491
+ pin(pin: QaPin): void {
492
+ pins.set(pin.experimentKey, {
493
+ ...pin,
494
+ subjectId: normalizeSubject(pin.subjectId),
495
+ });
496
+ bump();
497
+ },
498
+ unpin({ experimentKey }: { experimentKey: string }): void {
499
+ if (pins.delete(experimentKey)) bump();
500
+ },
501
+ getPins(): readonly QaPin[] {
502
+ return [...pins.values()];
503
+ },
504
+ subscribe(listener: () => void): () => void {
505
+ listeners.add(listener);
506
+ return () => listeners.delete(listener);
507
+ },
508
+ getVersion(): number {
509
+ return version;
510
+ },
511
+ isReady(): boolean {
512
+ return client?.ready ?? false;
513
+ },
514
+ isEnabled(): boolean {
515
+ return enabled;
516
+ },
517
+ getConfigVersion(): string | null {
518
+ return configVersion;
519
+ },
520
+ destroy(): void {
521
+ client?.destroy();
522
+ client = null;
523
+ listeners.clear();
524
+ },
525
+ };
526
+ }
527
+
528
+ function findVariation(
529
+ entry: FeatureEntry,
530
+ variantKey: string,
531
+ ): ExperimentVariation | undefined {
532
+ return entry.variations.find((variation) => variation.key === variantKey);
533
+ }
534
+
535
+ /** Experiment arms carry object payloads; anything else in the config reads as no payload. */
536
+ function isParams(value: unknown): value is ExperimentParams {
537
+ return typeof value === "object" && value !== null && !Array.isArray(value);
538
+ }
539
+
540
+ function parseEntries(
541
+ features: FeatureDefinitions,
542
+ warn: (message: string) => void,
543
+ ): ReadonlyMap<string, FeatureEntry> {
544
+ const entries = new Map<string, FeatureEntry>();
545
+ for (const [featureKey, definition] of Object.entries(features)) {
546
+ entries.set(featureKey, parseEntry(featureKey, definition, warn));
547
+ }
548
+ return entries;
549
+ }
550
+
551
+ /** A rule carrying a runnable experiment: two or more arms to assign between. */
552
+ type ExperimentRule = FeatureRule & { variations: unknown[] };
553
+
554
+ /**
555
+ * The wire's rule lifecycle fields. The engine's published rule type omits
556
+ * them (`status` is deprecated upstream but still emitted), so they are read
557
+ * defensively here — a remotely stopped experiment's rule can still ride the
558
+ * payload.
559
+ */
560
+ type WireExperimentRule = FeatureRule & {
561
+ active?: boolean;
562
+ status?: string;
563
+ };
564
+
565
+ /**
566
+ * A rule is live only while the config says so: two-plus arms, not deactivated
567
+ * (`active: false`), and not carrying a terminal lifecycle status. A remotely
568
+ * stopped rule that still rides the payload parses as stopped here — the entry
569
+ * never reaches the engine, so no override can resurrect it.
570
+ */
571
+ function hasLiveExperiment(rule: WireExperimentRule): rule is ExperimentRule {
572
+ return (
573
+ Array.isArray(rule.variations) &&
574
+ rule.variations.length >= 2 &&
575
+ rule.active !== false &&
576
+ rule.status !== "draft" &&
577
+ rule.status !== "stopped"
578
+ );
579
+ }
580
+
581
+ /**
582
+ * The bucketing contract the warehouse reproduces: the hash input is the bare
583
+ * subject id, hashed with hashVersion 2, with no sticky-bucket fallback. A rule
584
+ * that breaks it would bucket on inputs the warehouse can't reproduce — so the
585
+ * entry fails closed instead of ever producing a wrong assignment. Returns why
586
+ * the rule violates the contract, or null when it conforms.
587
+ */
588
+ function hashContractViolation(rule: ExperimentRule): string | null {
589
+ if (rule.hashAttribute !== undefined && rule.hashAttribute !== "id") {
590
+ return `buckets on hashAttribute "${rule.hashAttribute}" — the hash input must be the bare subject id`;
591
+ }
592
+ if (rule.fallbackAttribute !== undefined) {
593
+ return `buckets with fallbackAttribute "${rule.fallbackAttribute}" — sticky bucketing is out of contract`;
594
+ }
595
+ if (rule.hashVersion !== 2) {
596
+ return rule.hashVersion === undefined
597
+ ? "omits hashVersion — the contract is the explicit hashVersion 2"
598
+ : `buckets with hashVersion ${rule.hashVersion} — the contract is hashVersion 2`;
599
+ }
600
+ return null;
601
+ }
602
+
603
+ /** The entry shape for anything not running: the control experience only. */
604
+ function stoppedEntry(
605
+ featureKey: string,
606
+ hasExperimentRule: boolean,
607
+ hasFlagRule: boolean,
608
+ defaultParams: ExperimentParams,
609
+ defaultValue: unknown,
610
+ ): FeatureEntry {
611
+ return {
612
+ key: featureKey,
613
+ experimentKey: featureKey,
614
+ status: "stopped",
615
+ hasExperimentRule,
616
+ hasFlagRule,
617
+ controlKey: CONTROL_VARIANT_KEY,
618
+ variations: [],
619
+ defaultParams,
620
+ defaultValue,
621
+ };
622
+ }
623
+
624
+ function parseEntry(
625
+ featureKey: string,
626
+ definition: FeatureDefinition,
627
+ warn: (message: string) => void,
628
+ ): FeatureEntry {
629
+ const defaultParams = isParams(definition.defaultValue)
630
+ ? definition.defaultValue
631
+ : {};
632
+ const defaultValue: unknown = definition.defaultValue ?? null;
633
+ const rules = definition.rules ?? [];
634
+ // Presence, not parse status: any experiment-shaped rule, live or not,
635
+ // trusted or not — the flag path keys on this so it never evaluates one.
636
+ const hasExperimentRule = rules.some(
637
+ (rule) => Array.isArray(rule.variations) && rule.variations.length >= 2,
638
+ );
639
+ const hasFlagRule = rules.some(
640
+ (rule) => !(Array.isArray(rule.variations) && rule.variations.length >= 2),
641
+ );
642
+
643
+ // A feature carries at most one experiment-shaped rule: the engine evaluates
644
+ // every rule in order, so a second one would bucket subjects on inputs the
645
+ // contract never validated (and a stopped rule riding alongside a live one
646
+ // would still assign through it). Fail closed on the shape.
647
+ if (
648
+ rules.filter(
649
+ (rule) => Array.isArray(rule.variations) && rule.variations.length >= 2,
650
+ ).length > 1
651
+ ) {
652
+ warn(
653
+ `[experiments] "${featureKey}" carries more than one experiment rule; the experiment reads as stopped (control, no exposure)`,
654
+ );
655
+ return stoppedEntry(
656
+ featureKey,
657
+ hasExperimentRule,
658
+ hasFlagRule,
659
+ defaultParams,
660
+ defaultValue,
661
+ );
662
+ }
663
+
664
+ const experimentRule = rules.find(hasLiveExperiment);
665
+
666
+ // The config marks an experiment stopped by no longer carrying a live
667
+ // experiment rule: the feature keeps only its default payload, which is the
668
+ // control experience a stopped experiment serves. The same shape is a plain
669
+ // feature flag.
670
+ if (!experimentRule) {
671
+ return stoppedEntry(
672
+ featureKey,
673
+ hasExperimentRule,
674
+ hasFlagRule,
675
+ defaultParams,
676
+ defaultValue,
677
+ );
678
+ }
679
+
680
+ // A live rule that breaks the bucketing contract can only assign wrong: fail
681
+ // closed, and name the key on the warning channel so the config gets fixed
682
+ // rather than silently serving control forever.
683
+ const violation = hashContractViolation(experimentRule);
684
+ if (violation !== null) {
685
+ warn(
686
+ `[experiments] "${featureKey}" ${violation}; the experiment reads as stopped (control, no exposure)`,
687
+ );
688
+ return stoppedEntry(
689
+ featureKey,
690
+ hasExperimentRule,
691
+ hasFlagRule,
692
+ defaultParams,
693
+ defaultValue,
694
+ );
695
+ }
696
+
697
+ const variations: ExperimentVariation[] = experimentRule.variations.map(
698
+ (value: unknown, index: number) => ({
699
+ key: experimentRule.meta?.[index]?.key ?? String(index),
700
+ params: isParams(value) ? value : {},
701
+ }),
702
+ );
703
+
704
+ return {
705
+ key: featureKey,
706
+ experimentKey: experimentRule.key ?? featureKey,
707
+ status: "running",
708
+ hasExperimentRule,
709
+ hasFlagRule,
710
+ controlKey: variations[0]?.key ?? CONTROL_VARIANT_KEY,
711
+ variations,
712
+ defaultParams,
713
+ defaultValue,
714
+ };
715
+ }