@vllnt/convex-flags 0.1.0-canary.bf53746 → 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 (56) hide show
  1. package/README.md +84 -25
  2. package/dist/client/index.d.ts +62 -16
  3. package/dist/client/index.d.ts.map +1 -1
  4. package/dist/client/index.js +54 -15
  5. package/dist/client/index.js.map +1 -1
  6. package/dist/client/types.d.ts +30 -4
  7. package/dist/client/types.d.ts.map +1 -1
  8. package/dist/component/_generated/api.d.ts +19 -1
  9. package/dist/component/_generated/api.d.ts.map +1 -1
  10. package/dist/component/_generated/api.js +16 -0
  11. package/dist/component/_generated/api.js.map +1 -1
  12. package/dist/component/_generated/component.d.ts +174 -24
  13. package/dist/component/_generated/component.d.ts.map +1 -1
  14. package/dist/component/_generated/server.d.ts +12 -0
  15. package/dist/component/_generated/server.d.ts.map +1 -1
  16. package/dist/component/_generated/server.js +2 -0
  17. package/dist/component/_generated/server.js.map +1 -1
  18. package/dist/component/convex.config.d.ts.map +1 -1
  19. package/dist/component/mutations.d.ts +90 -5
  20. package/dist/component/mutations.d.ts.map +1 -1
  21. package/dist/component/mutations.js +144 -10
  22. package/dist/component/mutations.js.map +1 -1
  23. package/dist/component/queries.d.ts +90 -13
  24. package/dist/component/queries.d.ts.map +1 -1
  25. package/dist/component/queries.js +58 -12
  26. package/dist/component/queries.js.map +1 -1
  27. package/dist/component/schema.d.ts +138 -4
  28. package/dist/component/schema.d.ts.map +1 -1
  29. package/dist/component/schema.js +7 -1
  30. package/dist/component/schema.js.map +1 -1
  31. package/dist/component/validators.d.ts +354 -14
  32. package/dist/component/validators.d.ts.map +1 -1
  33. package/dist/component/validators.js +57 -6
  34. package/dist/component/validators.js.map +1 -1
  35. package/dist/react/index.d.ts +29 -0
  36. package/dist/react/index.d.ts.map +1 -0
  37. package/dist/react/index.js +35 -0
  38. package/dist/react/index.js.map +1 -0
  39. package/dist/shared.d.ts +102 -4
  40. package/dist/shared.d.ts.map +1 -1
  41. package/dist/shared.js +126 -3
  42. package/dist/shared.js.map +1 -1
  43. package/package.json +36 -18
  44. package/src/client/index.ts +145 -20
  45. package/src/client/types.ts +48 -4
  46. package/src/component/_generated/api.ts +19 -1
  47. package/src/component/_generated/component.ts +259 -23
  48. package/src/component/_generated/server.ts +13 -0
  49. package/src/component/mutations.ts +160 -19
  50. package/src/component/queries.ts +74 -12
  51. package/src/component/schema.ts +7 -1
  52. package/src/component/validators.ts +87 -6
  53. package/src/react/index.test.ts +52 -0
  54. package/src/react/index.ts +69 -0
  55. package/src/shared.ts +235 -4
  56. package/src/status-backward-compat.test.ts +51 -0
package/dist/shared.d.ts CHANGED
@@ -1,19 +1,117 @@
1
- /** Shared constants + types used by both `client/` and `component/`. */
1
+ /**
2
+ * Shared constants, types, and the pure evaluation engine used by both
3
+ * `client/` and `component/`.
4
+ *
5
+ * The engine is intentionally pure — no `ctx`, no database — so it can be
6
+ * reused by the component queries and exercised exhaustively end-to-end. Per-
7
+ * subject overrides and unknown-key handling live in the query layer (they need
8
+ * a database read); everything from a flag document downward lives here.
9
+ */
2
10
  /**
3
11
  * Why an evaluation returned the value it did. Stable string codes so hosts can
4
12
  * branch on the reason without parsing prose.
5
13
  */
6
14
  export declare const EVAL_REASON: {
7
- /** A defined flag served its current value. */
15
+ /** Served the flag's fallthrough value — no rule or rollout matched. */
8
16
  readonly flag: "flag";
9
- /** No flag exists for the key; the safe default (`false`) was served. */
17
+ /** A targeting rule matched and served a fixed value. */
18
+ readonly rule: "rule";
19
+ /** A percentage rollout deterministically assigned the value. */
20
+ readonly rollout: "rollout";
21
+ /** A per-subject override forced the value. */
22
+ readonly override: "override";
23
+ /** The flag is archived; targeting was skipped and its base value served. */
24
+ readonly disabled: "disabled";
25
+ /** Unknown key; the caller-supplied default was served. */
26
+ readonly default: "default";
27
+ /** Unknown key and no caller default; the safe default (`false`) was served. */
10
28
  readonly unknown: "unknown";
11
29
  };
12
30
  /** The set of evaluation reason codes. */
13
31
  export type EvalReason = (typeof EVAL_REASON)[keyof typeof EVAL_REASON];
32
+ /**
33
+ * A flag/variant value. Typed primitives only — never `v.any()`. JSON-object
34
+ * variants are a documented future last resort (tracked in the roadmap).
35
+ */
36
+ export type VariantValue = boolean | string | number;
37
+ /** An attribute value usable in a targeting comparison. */
38
+ export type AttributeValue = boolean | string | number;
39
+ /**
40
+ * Host-supplied, per-evaluation context. Opaque to the component: the host owns
41
+ * what `subjectRef` and the attribute names/values mean.
42
+ */
43
+ export interface EvalContext {
44
+ /** Stable identifier used for rollout bucketing (e.g. a user or session ref). */
45
+ subjectRef?: string;
46
+ /** Targeting attributes, keyed by host-chosen names. */
47
+ attributes?: Record<string, AttributeValue>;
48
+ }
14
49
  /** Result of evaluating a single flag. */
15
50
  export interface FlagEvaluation {
16
- value: boolean;
51
+ value: VariantValue;
17
52
  reason: EvalReason;
18
53
  }
54
+ /** Comparison operators available to a targeting condition. */
55
+ export type ConditionOp = "eq" | "neq" | "in" | "nin" | "contains" | "gt" | "gte" | "lt" | "lte";
56
+ /** One targeting condition: `<attribute> <op> <values>`. */
57
+ export interface Condition {
58
+ attribute: string;
59
+ op: ConditionOp;
60
+ values: AttributeValue[];
61
+ }
62
+ /** One weighted entry in a rollout's distribution. */
63
+ export interface Split {
64
+ value: VariantValue;
65
+ /** Relative weight; normalized across the rollout's splits. */
66
+ weight: number;
67
+ }
68
+ /** A deterministic weighted distribution across variant values. */
69
+ export interface Rollout {
70
+ splits: Split[];
71
+ /** Context attribute to bucket by; defaults to `subjectRef` when omitted. */
72
+ by?: string;
73
+ }
74
+ /** A declared variant (metadata for tooling / labels). */
75
+ export interface Variant {
76
+ value: VariantValue;
77
+ label?: string;
78
+ }
79
+ /**
80
+ * A targeting rule. All `conditions` must match (AND); rules are evaluated in
81
+ * order and the first match wins. The outcome is a fixed `value` or a `rollout`.
82
+ */
83
+ export interface Rule {
84
+ conditions: Condition[];
85
+ value?: VariantValue;
86
+ rollout?: Rollout;
87
+ }
88
+ /** The evaluatable shape of a stored flag (the engine's input). */
89
+ export interface EvaluableFlag {
90
+ value: VariantValue;
91
+ status?: "active" | "archived";
92
+ rules?: Rule[];
93
+ rollout?: Rollout;
94
+ }
95
+ /** Deterministic 32-bit FNV-1a hash of a string → uint32. */
96
+ export declare function hashString(input: string): number;
97
+ /**
98
+ * Deterministically pick a split's value by hashing `flagKey:subject` across the
99
+ * cumulative weights. Returns `null` when no split has positive weight.
100
+ */
101
+ export declare function pickSplit(flagKey: string, subject: string, splits: Split[]): VariantValue | null;
102
+ /**
103
+ * Evaluate a flag against context. Pure — given the same flag document and
104
+ * context it always returns the same result.
105
+ */
106
+ export declare function evaluateFlag(flagKey: string, flag: EvaluableFlag, context: EvalContext): FlagEvaluation;
107
+ /**
108
+ * Materialize a flag's lifecycle status for return to callers: a legacy row
109
+ * written before `status` existed has none and reads as `"active"`. Keeps the
110
+ * stored column optional (deploy-safe) while the public shape stays concrete.
111
+ */
112
+ export declare function withStatus<T extends {
113
+ status?: "active" | "archived";
114
+ }>(flag: T): T & {
115
+ status: "active" | "archived";
116
+ };
19
117
  //# sourceMappingURL=shared.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"shared.d.ts","sourceRoot":"","sources":["../src/shared.ts"],"names":[],"mappings":"AAAA,wEAAwE;AAExE;;;GAGG;AACH,eAAO,MAAM,WAAW;IACtB,+CAA+C;;IAE/C,yEAAyE;;CAEjE,CAAC;AAEX,0CAA0C;AAC1C,MAAM,MAAM,UAAU,GAAG,CAAC,OAAO,WAAW,CAAC,CAAC,MAAM,OAAO,WAAW,CAAC,CAAC;AAExE,0CAA0C;AAC1C,MAAM,WAAW,cAAc;IAC7B,KAAK,EAAE,OAAO,CAAC;IACf,MAAM,EAAE,UAAU,CAAC;CACpB"}
1
+ {"version":3,"file":"shared.d.ts","sourceRoot":"","sources":["../src/shared.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH;;;GAGG;AACH,eAAO,MAAM,WAAW;IACtB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 /**
2
+ * Shared constants, types, and the pure evaluation engine used by both
3
+ * `client/` and `component/`.
4
+ *
5
+ * The engine is intentionally pure — no `ctx`, no database — so it can be
6
+ * reused by the component queries and exercised exhaustively end-to-end. Per-
7
+ * subject overrides and unknown-key handling live in the query layer (they need
8
+ * a database read); everything from a flag document downward lives here.
9
+ */
2
10
  /**
3
11
  * Why an evaluation returned the value it did. Stable string codes so hosts can
4
12
  * branch on the reason without parsing prose.
5
13
  */
6
14
  export const EVAL_REASON = {
7
- /** A defined flag served its current value. */
15
+ /** Served the flag's fallthrough value — no rule or rollout matched. */
8
16
  flag: "flag",
9
- /** No flag exists for the key; the safe default (`false`) was served. */
17
+ /** A targeting rule matched and served a fixed value. */
18
+ rule: "rule",
19
+ /** A percentage rollout deterministically assigned the value. */
20
+ rollout: "rollout",
21
+ /** A per-subject override forced the value. */
22
+ override: "override",
23
+ /** The flag is archived; targeting was skipped and its base value served. */
24
+ disabled: "disabled",
25
+ /** Unknown key; the caller-supplied default was served. */
26
+ default: "default",
27
+ /** Unknown key and no caller default; the safe default (`false`) was served. */
10
28
  unknown: "unknown",
11
29
  };
30
+ /** Operator implementations. A table (not a switch) so there is no unreachable
31
+ * default branch — every operator resolves to one of these. */
32
+ const OPERATORS = {
33
+ eq: (actual, values) => actual === values[0],
34
+ neq: (actual, values) => actual !== values[0],
35
+ in: (actual, values) => values.includes(actual),
36
+ nin: (actual, values) => !values.includes(actual),
37
+ contains: (actual, values) => typeof actual === "string" &&
38
+ typeof values[0] === "string" &&
39
+ actual.includes(values[0]),
40
+ gt: (actual, values) => typeof actual === "number" && typeof values[0] === "number" && actual > values[0],
41
+ gte: (actual, values) => typeof actual === "number" && typeof values[0] === "number" && actual >= values[0],
42
+ lt: (actual, values) => typeof actual === "number" && typeof values[0] === "number" && actual < values[0],
43
+ lte: (actual, values) => typeof actual === "number" && typeof values[0] === "number" && actual <= values[0],
44
+ };
45
+ /** Does a single condition hold for the given context? A missing attribute never
46
+ * matches (mirrors how mainstream flag SDKs treat absent targeting data). */
47
+ function matchesCondition(condition, context) {
48
+ const actual = context.attributes?.[condition.attribute];
49
+ if (actual === undefined) {
50
+ return false;
51
+ }
52
+ return OPERATORS[condition.op](actual, condition.values);
53
+ }
54
+ /** Do all of a rule's conditions hold? An empty condition list always matches
55
+ * (a catch-all rule). */
56
+ function matchesRule(rule, context) {
57
+ return rule.conditions.every((condition) => matchesCondition(condition, context));
58
+ }
59
+ /** Deterministic 32-bit FNV-1a hash of a string → uint32. */
60
+ export function hashString(input) {
61
+ let hash = 0x811c9dc5;
62
+ for (let i = 0; i < input.length; i++) {
63
+ hash ^= input.charCodeAt(i);
64
+ hash = Math.imul(hash, 0x01000193);
65
+ }
66
+ return hash >>> 0;
67
+ }
68
+ /**
69
+ * Deterministically pick a split's value by hashing `flagKey:subject` across the
70
+ * cumulative weights. Returns `null` when no split has positive weight.
71
+ */
72
+ export function pickSplit(flagKey, subject, splits) {
73
+ const positive = splits.filter((split) => split.weight > 0);
74
+ const total = positive.reduce((sum, split) => sum + split.weight, 0);
75
+ if (total === 0) {
76
+ return null;
77
+ }
78
+ const point = hashString(`${flagKey}:${subject}`) % total;
79
+ let cumulative = 0;
80
+ let chosen = null;
81
+ for (const split of positive) {
82
+ cumulative += split.weight;
83
+ if (chosen === null && point < cumulative) {
84
+ chosen = split.value;
85
+ }
86
+ }
87
+ return chosen;
88
+ }
89
+ /** Resolve a rollout to a value, or `null` if it cannot bucket (no rollout, no
90
+ * bucketing subject, or no positive-weight split). */
91
+ function resolveRollout(flagKey, rollout, context) {
92
+ if (rollout === undefined) {
93
+ return null;
94
+ }
95
+ const subject = rollout.by !== undefined ? context.attributes?.[rollout.by] : context.subjectRef;
96
+ if (subject === undefined) {
97
+ return null;
98
+ }
99
+ return pickSplit(flagKey, String(subject), rollout.splits);
100
+ }
101
+ /**
102
+ * Evaluate a flag against context. Pure — given the same flag document and
103
+ * context it always returns the same result.
104
+ */
105
+ export function evaluateFlag(flagKey, flag, context) {
106
+ if (flag.status === "archived") {
107
+ return { value: flag.value, reason: EVAL_REASON.disabled };
108
+ }
109
+ for (const rule of flag.rules ?? []) {
110
+ if (matchesRule(rule, context)) {
111
+ if (rule.value !== undefined) {
112
+ return { value: rule.value, reason: EVAL_REASON.rule };
113
+ }
114
+ const picked = resolveRollout(flagKey, rule.rollout, context);
115
+ if (picked !== null) {
116
+ return { value: picked, reason: EVAL_REASON.rollout };
117
+ }
118
+ return { value: flag.value, reason: EVAL_REASON.flag };
119
+ }
120
+ }
121
+ const picked = resolveRollout(flagKey, flag.rollout, context);
122
+ if (picked !== null) {
123
+ return { value: picked, reason: EVAL_REASON.rollout };
124
+ }
125
+ return { value: flag.value, reason: EVAL_REASON.flag };
126
+ }
127
+ /**
128
+ * Materialize a flag's lifecycle status for return to callers: a legacy row
129
+ * written before `status` existed has none and reads as `"active"`. Keeps the
130
+ * stored column optional (deploy-safe) while the public shape stays concrete.
131
+ */
132
+ export function withStatus(flag) {
133
+ return { ...flag, status: flag.status ?? "active" };
134
+ }
12
135
  //# sourceMappingURL=shared.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"shared.js","sourceRoot":"","sources":["../src/shared.ts"],"names":[],"mappings":"AAAA,wEAAwE;AAExE;;;GAGG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG;IACzB,+CAA+C;IAC/C,IAAI,EAAE,MAAM;IACZ,yEAAyE;IACzE,OAAO,EAAE,SAAS;CACV,CAAC"}
1
+ {"version":3,"file":"shared.js","sourceRoot":"","sources":["../src/shared.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH;;;GAGG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG;IACzB,wEAAwE;IACxE,IAAI,EAAE,MAAM;IACZ,yDAAyD;IACzD,IAAI,EAAE,MAAM;IACZ,iEAAiE;IACjE,OAAO,EAAE,SAAS;IAClB,+CAA+C;IAC/C,QAAQ,EAAE,UAAU;IACpB,6EAA6E;IAC7E,QAAQ,EAAE,UAAU;IACpB,2D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H,MAAM,UAAU,UAAU,CACxB,IAAO;IAEP,OAAO,EAAE,GAAG,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,IAAI,QAAQ,EAAE,CAAC;AACtD,CAAC"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@vllnt/convex-flags",
3
- "version": "0.1.0-canary.bf53746",
4
- "description": "Feature flags as a Convex component - backend-evaluated, reactive kill-switches",
3
+ "version": "0.1.0",
4
+ "description": "Feature flags as a Convex component — variants, targeting, percentage rollouts, and per-subject overrides, evaluated on the backend and streamed live to clients.",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "packageManager": "pnpm@9.15.4",
@@ -15,6 +15,10 @@
15
15
  "types": "./dist/client/index.d.ts",
16
16
  "default": "./dist/client/index.js"
17
17
  },
18
+ "./react": {
19
+ "types": "./dist/react/index.d.ts",
20
+ "default": "./dist/react/index.js"
21
+ },
18
22
  "./test": "./src/test.ts",
19
23
  "./_generated/component.js": {
20
24
  "types": "./dist/component/_generated/component.d.ts"
@@ -35,11 +39,11 @@
35
39
  "module": "./dist/client/index.js",
36
40
  "scripts": {
37
41
  "build": "tsc --project ./tsconfig.build.json",
38
- "build:codegen": "pnpm convex codegen --component-dir ./src/component && pnpm build",
42
+ "build:codegen": "pnpm codegen && pnpm build",
39
43
  "build:clean": "rm -rf dist *.tsbuildinfo && pnpm build:codegen",
40
44
  "typecheck": "tsc --noEmit",
41
45
  "typecheck:ci": "tsc --noEmit --project tsconfig.ci.json",
42
- "lint": "eslint .",
46
+ "lint": "pnpm check:agents && eslint .",
43
47
  "test": "vitest run --passWithNoTests",
44
48
  "test:watch": "vitest --typecheck --clearScreen false",
45
49
  "test:coverage": "vitest run --coverage --coverage.reporter=text",
@@ -47,24 +51,38 @@
47
51
  "preversion": "pnpm install --frozen-lockfile && pnpm build && pnpm test:coverage && pnpm typecheck && pnpm generate:llms",
48
52
  "prepublishOnly": "npm whoami || npm login",
49
53
  "alpha": "npm version prerelease --preid alpha && npm publish --tag alpha && git push --follow-tags",
50
- "release": "npm version patch && npm publish && git push --follow-tags"
54
+ "release": "npm version patch && npm publish && git push --follow-tags",
55
+ "check:agents": "node -e \"const f=require('node:fs');if(!f.existsSync('AGENTS.md')||f.existsSync('CLAUDE.md')||f.existsSync('.claude'))process.exit(1)\"",
56
+ "codegen": "pnpm convex codegen --component-dir ./src/component"
51
57
  },
52
- "dependencies": {},
53
58
  "peerDependencies": {
54
- "convex": "^1.36.1"
59
+ "convex": "^1.45.0",
60
+ "react": "^18.0.0 || ^19.0.0"
61
+ },
62
+ "peerDependenciesMeta": {
63
+ "react": {
64
+ "optional": true
65
+ }
55
66
  },
56
67
  "devDependencies": {
57
- "@edge-runtime/vm": "^4.0.0",
58
- "@vitest/coverage-v8": "^3.0.0",
59
- "@vllnt/eslint-config": "^1.0.0",
60
- "@vllnt/typescript": "^1.0.0",
61
- "convex": "^1.36.1",
62
- "convex-test": "^0.0.50",
63
- "eslint": "^9.0.0",
64
- "prettier": "^3.4.0",
65
- "typescript": "^5.7.0",
66
- "vite": "^7.3.5",
67
- "vitest": "^3.0.0"
68
+ "@edge-runtime/vm": "^5.0.0",
69
+ "@testing-library/react": "^16.3.3",
70
+ "@types/react": "^19.2.18",
71
+ "@types/react-dom": "^19.2.5",
72
+ "@typescript/native": "npm:typescript@7.0.2",
73
+ "@vitest/coverage-v8": "^4.1.11",
74
+ "@vllnt/eslint-config": "2.0.0",
75
+ "@vllnt/typescript": "2.0.0",
76
+ "convex": "^1.45.0",
77
+ "convex-test": "^0.0.56",
78
+ "eslint": "^9.39.5",
79
+ "jsdom": "^29.1.1",
80
+ "prettier": "^3.9.6",
81
+ "react": "^19.2.8",
82
+ "react-dom": "^19.2.8",
83
+ "typescript": "npm:@typescript/typescript6@^6.0.2",
84
+ "vite": "^8.2.2",
85
+ "vitest": "^4.1.11"
68
86
  },
69
87
  "homepage": "https://github.com/vllnt/convex-flags#readme",
70
88
  "bugs": {
@@ -3,7 +3,18 @@ import type {
3
3
  FunctionReference,
4
4
  FunctionReturnType,
5
5
  } from "convex/server";
6
- import type { FlagDefinition, FlagDoc, FlagEvaluation } from "./types.js";
6
+ import type {
7
+ EvalContext,
8
+ EvalOptions,
9
+ FlagDefinition,
10
+ FlagDoc,
11
+ FlagEvaluation,
12
+ FlagUpdate,
13
+ Rollout,
14
+ Rule,
15
+ Variant,
16
+ VariantValue,
17
+ } from "./types.js";
7
18
 
8
19
  /**
9
20
  * The component's function references, as exposed on the host via
@@ -14,12 +25,46 @@ export interface FlagsComponent {
14
25
  define: FunctionReference<
15
26
  "mutation",
16
27
  "internal",
17
- { key: string; value: boolean; description?: string },
28
+ {
29
+ key: string;
30
+ value: VariantValue;
31
+ description?: string;
32
+ variants?: Variant[];
33
+ rules?: Rule[];
34
+ rollout?: Rollout;
35
+ },
18
36
  string
19
37
  >;
38
+ update: FunctionReference<
39
+ "mutation",
40
+ "internal",
41
+ {
42
+ key: string;
43
+ value?: VariantValue;
44
+ description?: string;
45
+ variants?: Variant[];
46
+ rules?: Rule[];
47
+ rollout?: Rollout;
48
+ },
49
+ null
50
+ >;
20
51
  enable: FunctionReference<"mutation", "internal", { key: string }, null>;
21
52
  disable: FunctionReference<"mutation", "internal", { key: string }, null>;
22
53
  remove: FunctionReference<"mutation", "internal", { key: string }, null>;
54
+ archive: FunctionReference<"mutation", "internal", { key: string }, null>;
55
+ restore: FunctionReference<"mutation", "internal", { key: string }, null>;
56
+ setOverride: FunctionReference<
57
+ "mutation",
58
+ "internal",
59
+ { key: string; subjectRef: string; value: VariantValue },
60
+ null
61
+ >;
62
+ clearOverride: FunctionReference<
63
+ "mutation",
64
+ "internal",
65
+ { key: string; subjectRef: string },
66
+ null
67
+ >;
23
68
  };
24
69
  queries: {
25
70
  get: FunctionReference<"query", "internal", { key: string }, FlagDoc | null>;
@@ -27,13 +72,13 @@ export interface FlagsComponent {
27
72
  evaluate: FunctionReference<
28
73
  "query",
29
74
  "internal",
30
- { key: string },
75
+ { key: string; context?: EvalContext; default?: VariantValue },
31
76
  FlagEvaluation
32
77
  >;
33
78
  all: FunctionReference<
34
79
  "query",
35
80
  "internal",
36
- Record<string, never>,
81
+ { context?: EvalContext },
37
82
  Record<string, FlagEvaluation>
38
83
  >;
39
84
  };
@@ -56,38 +101,83 @@ interface RunMutationCtx {
56
101
  /**
57
102
  * Consumer-facing client for `@vllnt/convex-flags`. Construct with the mounted
58
103
  * component ref, then call from host queries/mutations/actions. The host owns
59
- * auth: gate the management methods (`define`, `enable`, `disable`, `remove`)
60
- * behind your own authorized mutations.
104
+ * auth: gate the management methods (`define`, `update`, `enable`, `disable`,
105
+ * `archive`, `restore`, `remove`, `setOverride`, `clearOverride`) behind your
106
+ * own authorized mutations.
61
107
  *
62
108
  * @example
63
109
  * ```ts
64
110
  * const flags = new Flags(components.flags);
65
- * if (await flags.isEnabled(ctx, "new-checkout")) { ... }
111
+ * if (await flags.isEnabled(ctx, "new-checkout", { subjectRef: userId })) { ... }
66
112
  * ```
67
113
  */
68
114
  export class Flags {
69
115
  constructor(private readonly component: FlagsComponent) {}
70
116
 
71
- /** Create a flag, or update it if the key already exists. Returns its id. */
117
+ /** Create a flag, or replace its definition if the key already exists. */
72
118
  define(ctx: RunMutationCtx, definition: FlagDefinition): Promise<string> {
73
119
  return ctx.runMutation(this.component.mutations.define, definition);
74
120
  }
75
121
 
76
- /** Turn a flag on. Throws `FLAG_NOT_FOUND` if the key is undefined. */
122
+ /**
123
+ * Partially update a flag: only the supplied fields change, the rest are left
124
+ * untouched (unlike `define`, which fully replaces). Throws `FLAG_NOT_FOUND`.
125
+ */
126
+ update(ctx: RunMutationCtx, key: string, patch: FlagUpdate): Promise<null> {
127
+ return ctx.runMutation(this.component.mutations.update, { key, ...patch });
128
+ }
129
+
130
+ /** Turn a boolean flag on. Throws `FLAG_NOT_FOUND` if the key is undefined. */
77
131
  enable(ctx: RunMutationCtx, key: string): Promise<null> {
78
132
  return ctx.runMutation(this.component.mutations.enable, { key });
79
133
  }
80
134
 
81
- /** Turn a flag off. Throws `FLAG_NOT_FOUND` if the key is undefined. */
135
+ /** Turn a boolean flag off. Throws `FLAG_NOT_FOUND` if the key is undefined. */
82
136
  disable(ctx: RunMutationCtx, key: string): Promise<null> {
83
137
  return ctx.runMutation(this.component.mutations.disable, { key });
84
138
  }
85
139
 
86
- /** Permanently delete a flag. Throws `FLAG_NOT_FOUND` if the key is undefined. */
140
+ /** Archive a flag (reversible). Throws `FLAG_NOT_FOUND` if the key is undefined. */
141
+ archive(ctx: RunMutationCtx, key: string): Promise<null> {
142
+ return ctx.runMutation(this.component.mutations.archive, { key });
143
+ }
144
+
145
+ /** Restore an archived flag. Throws `FLAG_NOT_FOUND` if the key is undefined. */
146
+ restore(ctx: RunMutationCtx, key: string): Promise<null> {
147
+ return ctx.runMutation(this.component.mutations.restore, { key });
148
+ }
149
+
150
+ /** Permanently delete a flag and its overrides. Throws `FLAG_NOT_FOUND`. */
87
151
  remove(ctx: RunMutationCtx, key: string): Promise<null> {
88
152
  return ctx.runMutation(this.component.mutations.remove, { key });
89
153
  }
90
154
 
155
+ /** Force a flag's value for one subject. Throws `FLAG_NOT_FOUND`. */
156
+ setOverride(
157
+ ctx: RunMutationCtx,
158
+ key: string,
159
+ subjectRef: string,
160
+ value: VariantValue,
161
+ ): Promise<null> {
162
+ return ctx.runMutation(this.component.mutations.setOverride, {
163
+ key,
164
+ subjectRef,
165
+ value,
166
+ });
167
+ }
168
+
169
+ /** Clear a subject's override for a flag. No-op if none exists. */
170
+ clearOverride(
171
+ ctx: RunMutationCtx,
172
+ key: string,
173
+ subjectRef: string,
174
+ ): Promise<null> {
175
+ return ctx.runMutation(this.component.mutations.clearOverride, {
176
+ key,
177
+ subjectRef,
178
+ });
179
+ }
180
+
91
181
  /** Fetch a single flag definition, or `null` if undefined. */
92
182
  get(ctx: RunQueryCtx, key: string): Promise<FlagDoc | null> {
93
183
  return ctx.runQuery(this.component.queries.get, { key });
@@ -99,19 +189,54 @@ export class Flags {
99
189
  }
100
190
 
101
191
  /** Evaluate a flag, returning its value and the reason it was served. */
102
- evaluate(ctx: RunQueryCtx, key: string): Promise<FlagEvaluation> {
103
- return ctx.runQuery(this.component.queries.evaluate, { key });
192
+ evaluate(
193
+ ctx: RunQueryCtx,
194
+ key: string,
195
+ options?: EvalOptions,
196
+ ): Promise<FlagEvaluation> {
197
+ return ctx.runQuery(this.component.queries.evaluate, {
198
+ key,
199
+ context: options?.context,
200
+ default: options?.default,
201
+ });
202
+ }
203
+
204
+ /** Evaluate a flag and return just its value. */
205
+ async variant(
206
+ ctx: RunQueryCtx,
207
+ key: string,
208
+ options?: EvalOptions,
209
+ ): Promise<VariantValue> {
210
+ return (await this.evaluate(ctx, key, options)).value;
104
211
  }
105
212
 
106
- /** Evaluate a flag and return just its boolean value (default `false`). */
107
- async isEnabled(ctx: RunQueryCtx, key: string): Promise<boolean> {
108
- return (await this.evaluate(ctx, key)).value;
213
+ /** Evaluate a boolean flag and return whether it is on (value `=== true`). */
214
+ async isEnabled(
215
+ ctx: RunQueryCtx,
216
+ key: string,
217
+ context?: EvalContext,
218
+ ): Promise<boolean> {
219
+ return (await this.evaluate(ctx, key, { context })).value === true;
109
220
  }
110
221
 
111
- /** Evaluate every flag — the bootstrap payload for a reactive client. */
112
- all(ctx: RunQueryCtx): Promise<Record<string, FlagEvaluation>> {
113
- return ctx.runQuery(this.component.queries.all, {});
222
+ /** Evaluate every flag against optional context — the reactive bootstrap. */
223
+ all(
224
+ ctx: RunQueryCtx,
225
+ context?: EvalContext,
226
+ ): Promise<Record<string, FlagEvaluation>> {
227
+ return ctx.runQuery(this.component.queries.all, { context });
114
228
  }
115
229
  }
116
230
 
117
- export type { FlagDefinition, FlagDoc, FlagEvaluation };
231
+ export type {
232
+ EvalContext,
233
+ EvalOptions,
234
+ FlagDefinition,
235
+ FlagDoc,
236
+ FlagEvaluation,
237
+ FlagUpdate,
238
+ Rollout,
239
+ Rule,
240
+ Variant,
241
+ VariantValue,
242
+ };