@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,111 @@
1
+ /**
2
+ * The public contract of the experiment SDK. Call sites bind to these types
3
+ * only — never to the evaluation engine's own types.
4
+ */
5
+ /**
6
+ * The parameter payload configured on one experiment arm. Genuinely dynamic JSON
7
+ * owned by the experiment config, so the shape is open; call sites narrow what
8
+ * they read (e.g. `params["button_color"] === "blue"`).
9
+ */
10
+ export type ExperimentParams = Record<string, unknown>;
11
+ /**
12
+ * Targeting attributes an experiment's conditions evaluate against before
13
+ * bucketing (platform, program, appVersion, …). The attribute catalogue is owned
14
+ * by the experiment config, so the map is open. Never consulted for bucketing —
15
+ * the hash input is always the subject id alone. The registry always supplies a
16
+ * `date` attribute (the current ISO date) so configs can enforce time windows;
17
+ * callers may override it (tests).
18
+ */
19
+ export type TargetingAttributes = Record<string, unknown>;
20
+ /** Who the assignment is for, plus the attributes targeting gates on. */
21
+ export interface ExperimentContext {
22
+ /**
23
+ * The stable member id — the only input the bucketing hash ever sees.
24
+ * Normalized (trim + lowercase) inside the evaluator, so casing/whitespace
25
+ * drift at call sites never scrambles cohorts. Defaults to the session's.
26
+ */
27
+ subjectId?: string;
28
+ attributes?: TargetingAttributes;
29
+ /**
30
+ * "auto" (default): exposure fires when the assigned variant renders.
31
+ * "manual": the hook returns a `markExposed` trigger instead, for call sites
32
+ * that evaluate now but render the experience later.
33
+ */
34
+ exposure?: "auto" | "manual";
35
+ }
36
+ /** What `useExperiment` returns: the assigned arm's key and its configured payload. */
37
+ export interface ExperimentAssignment {
38
+ /** The assigned arm's key from the experiment config (e.g. "control" | "treatment"). */
39
+ variant: string;
40
+ /** The assigned arm's configured parameter payload. */
41
+ params: ExperimentParams;
42
+ /**
43
+ * Present when called with `exposure: "manual"`: records the exposure when the
44
+ * experience actually renders. No-ops for an assignment that isn't exposed
45
+ * (not enrolled, stopped, QA-pinned).
46
+ */
47
+ markExposed?: () => void;
48
+ }
49
+ /**
50
+ * A QA/debug pin forcing one variant for one subject on the current session.
51
+ * Pinned evaluations never emit exposure.
52
+ */
53
+ export interface QaPin {
54
+ experimentKey: string;
55
+ subjectId: string;
56
+ variant: string;
57
+ }
58
+ /**
59
+ * A cutover assignment map imported at migration time, so no member flips arms
60
+ * mid-experiment: per experiment, subject id to the variant key they were
61
+ * already on. The app bundles the map and hands it to the registry — it is
62
+ * config, not a service. A plain variant string is a migration entry; the full
63
+ * entry form adds an optional expiry and kind.
64
+ */
65
+ export type Overrides = Record<string, Record<string, string | OverrideEntry>>;
66
+ export interface OverrideEntry {
67
+ /** The forced variant key. */
68
+ variant: string;
69
+ /** ISO timestamp after which the override is ignored. Overrides always expire. */
70
+ expiresAt?: string;
71
+ /**
72
+ * "migration" (default): a real assignment — exposure logs normally and
73
+ * analysis keeps the member. "qa": a debug/support forcing — exposure logs
74
+ * with `override: true` so analysis drops it by default.
75
+ */
76
+ kind?: "migration" | "qa";
77
+ }
78
+ /** The registry's resolution, including whether the assignment may log exposure. */
79
+ export interface ResolvedAssignment extends ExperimentAssignment {
80
+ /**
81
+ * Present only when this assignment is a real in-experiment allocation that
82
+ * becomes an exposure once rendered. Null for defaults, stopped experiments,
83
+ * targeting failures, and QA pins.
84
+ */
85
+ exposure: ExposureInput | null;
86
+ }
87
+ /** An allocation that became visible — one exposure event when rendered. */
88
+ export interface ExposureInput {
89
+ experimentKey: string;
90
+ subjectId: string;
91
+ variant: string;
92
+ /**
93
+ * The config version the assignment was evaluated against — captured when the
94
+ * exposure is built, so a config refresh between compute and render can never
95
+ * re-stamp the event. Null when unknown.
96
+ */
97
+ configVersion: string | null;
98
+ /** True when a QA-kind override produced the assignment — flagged on the event. */
99
+ override?: boolean;
100
+ }
101
+ /**
102
+ * A minimal key/value store for persisting the config cache (AsyncStorage on
103
+ * React Native, a localStorage-compatible shim elsewhere). Both methods may be
104
+ * async. When provided, the evaluation client caches the config here, so cold
105
+ * starts evaluate offline from the last fetch.
106
+ */
107
+ export interface KeyValueStorage {
108
+ getItem(key: string): string | null | Promise<string | null>;
109
+ setItem(key: string, value: string): void | Promise<void>;
110
+ }
111
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH;;;;GAIG;AACH,MAAM,MAAM,gBAAgB,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAEvD;;;;;;;GAOG;AACH,MAAM,MAAM,mBAAmB,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAE1D,yEAAyE;AACzE,MAAM,WAAW,iBAAiB;IAChC;;;;OAIG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,UAAU,CAAC,EAAE,mBAAmB,CAAC;IACjC;;;;OAIG;IACH,QAAQ,CAAC,EAAE,MAAM,GAAG,QAAQ,CAAC;CAC9B;AAED,uFAAuF;AACvF,MAAM,WAAW,oBAAoB;IACnC,wFAAwF;IACxF,OAAO,EAAE,MAAM,CAAC;IAChB,uDAAuD;IACvD,MAAM,EAAE,gBAAgB,CAAC;IACzB;;;;OAIG;IACH,WAAW,CAAC,EAAE,MAAM,IAAI,CAAC;CAC1B;AAED;;;GAGG;AACH,MAAM,WAAW,KAAK;IACpB,aAAa,EAAE,MAAM,CAAC;IACtB,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC;CACjB;AAED;;;;;;GAMG;AACH,MAAM,MAAM,SAAS,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,aAAa,CAAC,CAAC,CAAC;AAE/E,MAAM,WAAW,aAAa;IAC5B,8BAA8B;IAC9B,OAAO,EAAE,MAAM,CAAC;IAChB,kFAAkF;IAClF,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;;OAIG;IACH,IAAI,CAAC,EAAE,WAAW,GAAG,IAAI,CAAC;CAC3B;AAED,oFAAoF;AACpF,MAAM,WAAW,kBAAmB,SAAQ,oBAAoB;IAC9D;;;;OAIG;IACH,QAAQ,EAAE,aAAa,GAAG,IAAI,CAAC;CAChC;AAED,4EAA4E;AAC5E,MAAM,WAAW,aAAa;IAC5B,aAAa,EAAE,MAAM,CAAC;IACtB,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC;IAChB;;;;OAIG;IACH,aAAa,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,mFAAmF;IACnF,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB;AAED;;;;;GAKG;AACH,MAAM,WAAW,eAAe;IAC9B,OAAO,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;IAC7D,OAAO,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAC3D"}
package/dist/uuid.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ /**
2
+ * A v4 UUID for idempotency keys — uniqueness, not security. Uses the platform
3
+ * crypto when it has one (web, modern Hermes), a Math.random fallback otherwise.
4
+ */
5
+ export declare function newId(): string;
6
+ //# sourceMappingURL=uuid.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"uuid.d.ts","sourceRoot":"","sources":["../src/uuid.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,wBAAgB,KAAK,IAAI,MAAM,CAS9B"}
@@ -0,0 +1,35 @@
1
+ import type { EventStream, StreamEvent } from "../events";
2
+ export interface BatchedEventSender extends EventStream {
3
+ /** Push every queued event now. Best-effort: a failed batch is dropped. */
4
+ flush(): Promise<void>;
5
+ /** Stop the flush timer and drop anything still queued. */
6
+ destroy(): void;
7
+ /** Events queued but not yet flushed. */
8
+ pendingCount(): number;
9
+ }
10
+ interface BatchedEventSenderOptions {
11
+ url: string;
12
+ authorization?: string;
13
+ /** Flush as soon as this many events are queued. Default 20. */
14
+ batchSize?: number;
15
+ /** Flush interval while the page is alive. Default 5000ms. */
16
+ flushIntervalMs?: number;
17
+ /**
18
+ * Where a serialized batch goes. Defaults to sendBeacon while the page is
19
+ * hidden (a mid-unload fetch can die) and a keepalive POST otherwise.
20
+ */
21
+ transport?: (batch: readonly StreamEvent[]) => Promise<void>;
22
+ }
23
+ /**
24
+ * An EventStream that buffers events and flushes them in batches — the same
25
+ * stream every product event uses. Batches are best-effort: analytics events
26
+ * ride the network's happy path and a failed batch is dropped, never retried
27
+ * into a duplicate.
28
+ *
29
+ * This transport is the web flavor (document visibility + sendBeacon). Other
30
+ * runtimes supply their own transport through the `transport` option or their
31
+ * own EventStream entirely.
32
+ */
33
+ export declare function createBatchedEventSender({ url, authorization, batchSize, flushIntervalMs, transport, }: BatchedEventSenderOptions): BatchedEventSender;
34
+ export {};
35
+ //# sourceMappingURL=batched-event-sender.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"batched-event-sender.d.ts","sourceRoot":"","sources":["../../src/web/batched-event-sender.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AAE1D,MAAM,WAAW,kBAAmB,SAAQ,WAAW;IACrD,2EAA2E;IAC3E,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACvB,2DAA2D;IAC3D,OAAO,IAAI,IAAI,CAAC;IAChB,yCAAyC;IACzC,YAAY,IAAI,MAAM,CAAC;CACxB;AAED,UAAU,yBAAyB;IACjC,GAAG,EAAE,MAAM,CAAC;IACZ,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,gEAAgE;IAChE,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,8DAA8D;IAC9D,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB;;;OAGG;IACH,SAAS,CAAC,EAAE,CAAC,KAAK,EAAE,SAAS,WAAW,EAAE,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CAC9D;AAED;;;;;;;;;GASG;AACH,wBAAgB,wBAAwB,CAAC,EACvC,GAAG,EACH,aAAa,EACb,SAAc,EACd,eAAsB,EACtB,SAAgD,GACjD,EAAE,yBAAyB,GAAG,kBAAkB,CA+ChD"}
@@ -0,0 +1,7 @@
1
+ /**
2
+ * `@wellth-app/experiments/web` — the web event transport: a batching sender over
3
+ * fetch/sendBeacon for browsers. React Native and other runtimes supply their
4
+ * own EventStream instead.
5
+ */
6
+ export { createBatchedEventSender, type BatchedEventSender, } from "./batched-event-sender";
7
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/web/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EACL,wBAAwB,EACxB,KAAK,kBAAkB,GACxB,MAAM,wBAAwB,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,129 @@
1
1
  {
2
2
  "name": "@wellth-app/experiments",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Wellth's thin experiment client: deterministic local assignment, overrides, and render-time exposure logging behind our own hook interface. Wraps @growthbook/growthbook; call sites never bind to it.",
5
+ "license": "MIT",
6
+ "publishConfig": {
7
+ "registry": "https://registry.npmjs.org",
8
+ "access": "public"
9
+ },
10
+ "main": "dist/cjs/index.js",
11
+ "module": "dist/esm/index.js",
12
+ "types": "dist/index.d.ts",
13
+ "typings": "dist/index.d.ts",
14
+ "exports": {
15
+ "./package.json": "./package.json",
16
+ ".": {
17
+ "import": {
18
+ "types": "./dist/index.d.ts",
19
+ "default": "./dist/esm/index.js"
20
+ },
21
+ "require": {
22
+ "types": "./dist/index.d.ts",
23
+ "default": "./dist/cjs/index.js"
24
+ }
25
+ },
26
+ "./core": {
27
+ "import": {
28
+ "types": "./dist/index.d.ts",
29
+ "default": "./dist/esm/index.js"
30
+ },
31
+ "require": {
32
+ "types": "./dist/index.d.ts",
33
+ "default": "./dist/cjs/index.js"
34
+ }
35
+ },
36
+ "./react": {
37
+ "import": {
38
+ "types": "./dist/react/index.d.ts",
39
+ "default": "./dist/esm/react.js"
40
+ },
41
+ "require": {
42
+ "types": "./dist/react/index.d.ts",
43
+ "default": "./dist/cjs/react.js"
44
+ }
45
+ },
46
+ "./web": {
47
+ "import": {
48
+ "types": "./dist/web/index.d.ts",
49
+ "default": "./dist/esm/web.js"
50
+ },
51
+ "require": {
52
+ "types": "./dist/web/index.d.ts",
53
+ "default": "./dist/cjs/web.js"
54
+ }
55
+ }
56
+ },
57
+ "files": [
58
+ "dist",
59
+ "src"
60
+ ],
61
+ "engines": {
62
+ "node": ">=10"
63
+ },
64
+ "sideEffects": false,
65
+ "repository": {
66
+ "type": "git",
67
+ "url": "https://github.com/wellth-app/experiments"
68
+ },
69
+ "scripts": {
70
+ "build:bundles": "rollup -c",
71
+ "build:clean": "rimraf -rf dist",
72
+ "build:types": "tsc --emitDeclarationOnly",
73
+ "build": "pnpm build:clean && npm-run-all --parallel build:types build:bundles",
74
+ "test": "jest",
75
+ "clean": "rimraf node_modules",
76
+ "type-check": "tsgo --pretty --noEmit",
77
+ "lint": "eslint --max-warnings 0 .",
78
+ "lint:fix": "eslint --fix --max-warnings 0 .",
79
+ "format": "prettier --write .",
80
+ "format:check": "prettier --check .",
81
+ "generate-vectors": "node scripts/generate-hash-vectors.mjs",
82
+ "example:dev": "pnpm --dir examples/demo-app dev",
83
+ "example:build": "pnpm --dir examples/demo-app build",
84
+ "example:test:e2e": "pnpm --dir examples/demo-app test:e2e"
85
+ },
86
+ "packageManager": "pnpm@10.33.4",
87
+ "peerDependencies": {
88
+ "react": "^16.8.0-0 || ^17.0.0-0 || ^18.0.0-0 || ^19.0.0-0"
89
+ },
90
+ "peerDependenciesMeta": {
91
+ "react": {
92
+ "optional": true
93
+ }
94
+ },
95
+ "dependencies": {
96
+ "@growthbook/growthbook": "^1.7.0"
97
+ },
98
+ "devDependencies": {
99
+ "@babel/cli": "^7.28.3",
100
+ "@babel/core": "^7.28.5",
101
+ "@babel/preset-react": "^7.28.5",
102
+ "@babel/preset-typescript": "^7.28.5",
103
+ "@eslint/js": "^10.0.1",
104
+ "@rollup/plugin-babel": "^6.1.0",
105
+ "@rollup/plugin-commonjs": "^26.0.1",
106
+ "@rollup/plugin-node-resolve": "^16.0.3",
107
+ "@rollup/plugin-replace": "^6.0.3",
108
+ "@testing-library/react": "^16.3.0",
109
+ "@types/jest": "^29.5.14",
110
+ "@types/node": "^22.8.6",
111
+ "@types/react": "^18.0.15",
112
+ "@types/react-dom": "^18.0.6",
113
+ "@typescript/native-preview": "7.0.0-dev.20260309.1",
114
+ "eslint": "^10.4.0",
115
+ "eslint-config-prettier": "^10.1.8",
116
+ "globals": "^17.12.0",
117
+ "jest": "^29.7.0",
118
+ "jest-environment-jsdom": "^29.7.0",
119
+ "npm-run-all": "^4.1.5",
120
+ "prettier": "^3.6.2",
121
+ "react": "^18.2.0",
122
+ "react-dom": "^18.2.0",
123
+ "rimraf": "^3.0.2",
124
+ "rollup": "^4.52.5",
125
+ "ts-jest": "^29.4.11",
126
+ "typescript": "5.7.3",
127
+ "typescript-eslint": "^8.60.0"
128
+ }
129
+ }
package/src/events.ts ADDED
@@ -0,0 +1,90 @@
1
+ /**
2
+ * The analytics stream the SDK emits into. One stream carries every product
3
+ * event; `experiment_exposed` is one event type on it. The stream is the seam
4
+ * where the platform's analytics pipeline plugs in.
5
+ */
6
+
7
+ /**
8
+ * The warehouse contract for an experiment exposure. Field names are contractual —
9
+ * the warehouse recomputes assignment from `experiment_id` + `subject` and joins
10
+ * exposures on them. Exactly one emission per render-visible assignment.
11
+ *
12
+ * `config_version` + `subject` let the warehouse recompute the cohort *as
13
+ * configured at exposure time*; `exposure_id` is the idempotency key the
14
+ * ingestion and warehouse dedupe layers key on; `override` marks QA-forced
15
+ * assignments that analysis drops by default.
16
+ */
17
+ /**
18
+ * The surfaces that emit exposure. Each app declares itself at registry
19
+ * construction — the app is "app", Atlas is "web", notifications dispatch is
20
+ * "notifications". Extend as new surfaces ship.
21
+ */
22
+ export type ExposureSurface = "app" | "web" | "notifications";
23
+
24
+ export interface ExperimentExposureEvent {
25
+ event: "experiment_exposed";
26
+ /** The experiment's key. */
27
+ experiment_id: string;
28
+ /** The assigned arm's key. */
29
+ variation_id: string;
30
+ /** The member id the assignment hashed on (normalized: trimmed, lowercased). */
31
+ subject: string;
32
+ /** The emitting surface, declared by the app. */
33
+ surface: ExposureSurface;
34
+ /** Epoch milliseconds, at render time. */
35
+ timestamp: number;
36
+ /**
37
+ * The registry config version the assignment was evaluated against — captured
38
+ * at evaluation time and carried on the exposure, never re-read at send time.
39
+ * Null when unknown.
40
+ */
41
+ config_version: string | null;
42
+ /** Idempotency key: one per unique assignment per session. */
43
+ exposure_id: string;
44
+ /** Present and true only when a QA-kind override produced the assignment. */
45
+ override?: true;
46
+ }
47
+
48
+ /** Any event on the product-analytics stream. ExperimentExposureEvent is one of these. */
49
+ export interface StreamEvent {
50
+ event: string;
51
+ /** Epoch milliseconds. */
52
+ timestamp: number;
53
+ }
54
+
55
+ /** Where events go. Batching and transport live behind this seam. */
56
+ export interface EventStream {
57
+ send: (event: StreamEvent) => void;
58
+ }
59
+
60
+ export function buildExperimentExposure({
61
+ experimentKey,
62
+ subjectId,
63
+ variant,
64
+ surface,
65
+ timestamp,
66
+ configVersion,
67
+ exposureId,
68
+ override,
69
+ }: {
70
+ experimentKey: string;
71
+ subjectId: string;
72
+ variant: string;
73
+ surface: ExposureSurface;
74
+ timestamp: number;
75
+ configVersion: string | null;
76
+ exposureId: string;
77
+ override?: boolean;
78
+ }): ExperimentExposureEvent {
79
+ return {
80
+ event: "experiment_exposed",
81
+ experiment_id: experimentKey,
82
+ variation_id: variant,
83
+ subject: subjectId,
84
+ surface,
85
+ timestamp,
86
+ config_version: configVersion,
87
+ exposure_id: exposureId,
88
+ ...(override === true ? { override: true } : {}),
89
+ };
90
+ }
package/src/index.ts ADDED
@@ -0,0 +1,37 @@
1
+ /**
2
+ * @wellth-app/experiments — the core entry: deterministic local assignment,
3
+ * overrides, and the exposure contract. No React, no DOM. React apps also want
4
+ * `@wellth-app/experiments/react`; web apps batching to an HTTP intake also want
5
+ * `@wellth-app/experiments/web`.
6
+ */
7
+ export {
8
+ buildExperimentExposure,
9
+ type EventStream,
10
+ type ExperimentExposureEvent,
11
+ type ExposureSurface,
12
+ type StreamEvent,
13
+ } from "./events";
14
+ export {
15
+ createFeatureRegistry,
16
+ type EvaluateExperimentInput,
17
+ type EvaluateFlagInput,
18
+ type FlagEvaluation,
19
+ type FlagSource,
20
+ type FeatureRegistry,
21
+ type KeyKind,
22
+ type ExperimentStatus,
23
+ type RegistryInitOptions,
24
+ type RegistryPayload,
25
+ } from "./registry";
26
+ export type {
27
+ ExperimentAssignment,
28
+ ExperimentContext,
29
+ ExperimentParams,
30
+ ExposureInput,
31
+ KeyValueStorage,
32
+ OverrideEntry,
33
+ Overrides,
34
+ QaPin,
35
+ ResolvedAssignment,
36
+ TargetingAttributes,
37
+ } from "./types";
@@ -0,0 +1,62 @@
1
+ import { createContext, useContext } from "react";
2
+ import type { FeatureRegistry } from "../registry";
3
+ import type { TargetingAttributes } from "../types";
4
+
5
+ /** A product event handed to the stream. The context stamps subject and timestamp. */
6
+ export interface ProductEventInput {
7
+ event: string;
8
+ [property: string]: unknown;
9
+ }
10
+
11
+ /**
12
+ * The registry as components see it: the full read/QA surface minus
13
+ * trackExposure. Exposure emission stays inside the package's hooks, so no
14
+ * component can hand-craft an event around the never-log guards.
15
+ */
16
+ export type ComponentRegistry = Omit<FeatureRegistry, "trackExposure">;
17
+
18
+ export interface ExperimentsContextValue {
19
+ registry: ComponentRegistry;
20
+ /** The session's subject — the member id assignments hash on. */
21
+ subjectId: string;
22
+ /** The session's targeting attributes; a call-site's context overrides these. */
23
+ attributes?: TargetingAttributes;
24
+ /** Send a product event on the same stream exposures ride. */
25
+ trackEvent: (input: ProductEventInput) => void;
26
+ }
27
+
28
+ export const ExperimentsContext = createContext<ExperimentsContextValue | null>(
29
+ null,
30
+ );
31
+
32
+ /**
33
+ * The real registry, trackExposure included — the internal channel the
34
+ * package's own hooks use. Deliberately not re-exported from the React entry,
35
+ * so the surface has no typed path to exposure emission.
36
+ */
37
+ export const InternalRegistryContext = createContext<FeatureRegistry | null>(
38
+ null,
39
+ );
40
+
41
+ /** The mounted experiments context. Throws when no ExperimentProvider is mounted. */
42
+ export function useExperiments(): ExperimentsContextValue {
43
+ const value = useContext(ExperimentsContext);
44
+ if (value === null) {
45
+ throw new Error("useExperiments must be used within <ExperimentProvider>");
46
+ }
47
+ return value;
48
+ }
49
+
50
+ /**
51
+ * The real registry for the package's own hooks (useExperiment's exposure
52
+ * emission). Throws when no ExperimentProvider is mounted.
53
+ */
54
+ export function useInternalRegistry(): FeatureRegistry {
55
+ const registry = useContext(InternalRegistryContext);
56
+ if (registry === null) {
57
+ throw new Error(
58
+ "useInternalRegistry must be used within <ExperimentProvider>",
59
+ );
60
+ }
61
+ return registry;
62
+ }
@@ -0,0 +1,25 @@
1
+ import type { FeatureRegistry, KeyKind } from "../registry";
2
+
3
+ /**
4
+ * The misuse guard — dev-only. Experiments go through useExperiment, flags
5
+ * through the flag hooks; crossing them either renders a variant with no
6
+ * exposure (corrupting the experiment's counts) or reads an experiment as a
7
+ * flag. In development a crossed read throws a clear error at the call site.
8
+ * Production builds strip the check (the bundle pins NODE_ENV to
9
+ * "production") and keep the registry's documented fail-closed behavior.
10
+ */
11
+ export function assertHookKeyKind(
12
+ registry: Pick<FeatureRegistry, "getKeyKind">,
13
+ key: string,
14
+ expected: KeyKind,
15
+ hook: string,
16
+ ): void {
17
+ if (process.env.NODE_ENV === "production") return;
18
+ const kind = registry.getKeyKind(key);
19
+ if (kind === "unknown" || kind === expected) return;
20
+ throw new Error(
21
+ expected === "experiment"
22
+ ? `[experiments] ${hook}("${key}") was called on a feature flag. Flags go through useFeatureFlag/useFeatureValue; ${hook} is for experiment keys.`
23
+ : `[experiments] ${hook}("${key}") was called on an experiment. Experiments go through useExperiment — a flag hook on an experiment key reads the config's default and never records exposure.`,
24
+ );
25
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * `@wellth-app/experiments/react` — the React surface: the provider and the
3
+ * hooks call sites use. Works anywhere React runs (web, React Native).
4
+ */
5
+ export {
6
+ ExperimentsContext,
7
+ useExperiments,
8
+ type ComponentRegistry,
9
+ type ExperimentsContextValue,
10
+ type ProductEventInput,
11
+ } from "./context";
12
+ export { ExperimentProvider, type ExperimentProviderProps } from "./provider";
13
+ export { useAnalytics } from "./use-analytics";
14
+ export { useExperiment } from "./use-experiment";
15
+ export { useExperimentQa } from "./use-experiment-qa";
16
+ export { useFeatureFlag } from "./use-feature-flag";
17
+ export { useFeatureValue } from "./use-feature-value";
@@ -0,0 +1,109 @@
1
+ import * as React from "react";
2
+ import { useEffect, useMemo, useState, type ReactNode } from "react";
3
+ import type { EventStream, ExposureSurface } from "../events";
4
+ import { createFeatureRegistry, type RegistryPayload } from "../registry";
5
+ import type { KeyValueStorage, Overrides, TargetingAttributes } from "../types";
6
+ import {
7
+ ExperimentsContext,
8
+ InternalRegistryContext,
9
+ type ExperimentsContextValue,
10
+ type ProductEventInput,
11
+ } from "./context";
12
+
13
+ export interface ExperimentProviderProps {
14
+ /** The session's subject — the member id assignments hash on. */
15
+ subjectId: string;
16
+ /**
17
+ * The surface exposures are stamped with ("app" | "web" | "notifications").
18
+ * Required — each app declares itself.
19
+ */
20
+ surface: ExposureSurface;
21
+ /** Session targeting attributes (platform, program, appVersion, …). */
22
+ attributes?: TargetingAttributes;
23
+ /** The analytics pipeline exposures batch through. Unset = computed but not sent. */
24
+ events?: EventStream;
25
+ /** The assignment override map, bundled by the app. Default: no overrides. */
26
+ overrides?: Overrides;
27
+ /** Where the config cache persists (AsyncStorage on React Native). Default: platform localStorage or memory. */
28
+ cacheStorage?: KeyValueStorage;
29
+ /** Config endpoint credentials. Unset = disabled: control reads, no fetch. */
30
+ clientKey?: string;
31
+ apiHost?: string;
32
+ /** An already-available config payload to seed synchronously instead of fetching. */
33
+ payload?: RegistryPayload;
34
+ children: ReactNode;
35
+ }
36
+
37
+ /**
38
+ * Mounts the session's experiment registry once, after auth. A `payload` seeds
39
+ * the registry synchronously at construction, so the first paint already reads
40
+ * the real assignment; the fetch path initializes async and children render
41
+ * immediately against a still-initializing registry, which returns control
42
+ * defaults, so a variant never flashes ahead of the assignment. Without a
43
+ * client key nothing is fetched — the control experience.
44
+ */
45
+ export function ExperimentProvider({
46
+ subjectId,
47
+ surface,
48
+ attributes,
49
+ events,
50
+ overrides,
51
+ cacheStorage,
52
+ clientKey,
53
+ apiHost,
54
+ payload,
55
+ children,
56
+ }: ExperimentProviderProps) {
57
+ const [registry] = useState(() => {
58
+ const created = createFeatureRegistry({
59
+ surface,
60
+ events,
61
+ overrides,
62
+ cacheStorage,
63
+ });
64
+ // Seed synchronously when the payload is already available: the first
65
+ // commit reads the real assignment instead of flashing control for a
66
+ // frame. The effect below re-seeds on payload change and on remount
67
+ // (StrictMode's simulated unmount destroys the client).
68
+ if (payload !== undefined) created.initSync({ payload });
69
+ return created;
70
+ });
71
+
72
+ useEffect(() => {
73
+ if (payload !== undefined) {
74
+ registry.initSync({ payload });
75
+ } else {
76
+ void registry.init({ clientKey, apiHost });
77
+ }
78
+ return () => {
79
+ registry.destroy();
80
+ };
81
+ }, [registry, clientKey, apiHost, payload]);
82
+
83
+ const value = useMemo<ExperimentsContextValue>(
84
+ () => ({
85
+ registry,
86
+ subjectId,
87
+ attributes,
88
+ trackEvent(input: ProductEventInput): void {
89
+ const event = {
90
+ ...input,
91
+ subject: input["subject"] ?? subjectId,
92
+ timestamp: Date.now(),
93
+ };
94
+ registry.sendEvent(event);
95
+ },
96
+ }),
97
+ [registry, subjectId, attributes],
98
+ );
99
+
100
+ return (
101
+ // The internal channel carries the real registry (trackExposure included)
102
+ // to the package's own hooks; the public context carries the facade.
103
+ <InternalRegistryContext.Provider value={registry}>
104
+ <ExperimentsContext.Provider value={value}>
105
+ {children}
106
+ </ExperimentsContext.Provider>
107
+ </InternalRegistryContext.Provider>
108
+ );
109
+ }
@@ -0,0 +1,17 @@
1
+ import { useSyncExternalStore } from "react";
2
+ import { useExperiments, type ProductEventInput } from "./context";
3
+
4
+ /**
5
+ * The session's product-analytics stream — the same stream experiment exposures
6
+ * ride. `track` stamps the subject and timestamp. `ready` is false until the
7
+ * experiment config finishes initializing, so callers can skip events that have
8
+ * no meaningful assignment context yet.
9
+ */
10
+ export function useAnalytics(): {
11
+ ready: boolean;
12
+ track: (input: ProductEventInput) => void;
13
+ } {
14
+ const { registry, trackEvent } = useExperiments();
15
+ useSyncExternalStore(registry.subscribe, registry.getVersion);
16
+ return { ready: registry.isReady(), track: trackEvent };
17
+ }