@vllnt/convex-flags 0.1.0-canary.0e432b5

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 (70) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +182 -0
  3. package/dist/client/index.d.ts +122 -0
  4. package/dist/client/index.d.ts.map +1 -0
  5. package/dist/client/index.js +94 -0
  6. package/dist/client/index.js.map +1 -0
  7. package/dist/client/types.d.ts +45 -0
  8. package/dist/client/types.d.ts.map +1 -0
  9. package/dist/client/types.js +2 -0
  10. package/dist/client/types.js.map +1 -0
  11. package/dist/component/_generated/api.d.ts +38 -0
  12. package/dist/component/_generated/api.d.ts.map +1 -0
  13. package/dist/component/_generated/api.js +31 -0
  14. package/dist/component/_generated/api.js.map +1 -0
  15. package/dist/component/_generated/component.d.ts +207 -0
  16. package/dist/component/_generated/component.d.ts.map +1 -0
  17. package/dist/component/_generated/component.js +11 -0
  18. package/dist/component/_generated/component.js.map +1 -0
  19. package/dist/component/_generated/dataModel.d.ts +46 -0
  20. package/dist/component/_generated/dataModel.d.ts.map +1 -0
  21. package/dist/component/_generated/dataModel.js +11 -0
  22. package/dist/component/_generated/dataModel.js.map +1 -0
  23. package/dist/component/_generated/server.d.ts +121 -0
  24. package/dist/component/_generated/server.d.ts.map +1 -0
  25. package/dist/component/_generated/server.js +78 -0
  26. package/dist/component/_generated/server.js.map +1 -0
  27. package/dist/component/convex.config.d.ts +3 -0
  28. package/dist/component/convex.config.d.ts.map +1 -0
  29. package/dist/component/convex.config.js +7 -0
  30. package/dist/component/convex.config.js.map +1 -0
  31. package/dist/component/mutations.d.ts +104 -0
  32. package/dist/component/mutations.d.ts.map +1 -0
  33. package/dist/component/mutations.js +209 -0
  34. package/dist/component/mutations.js.map +1 -0
  35. package/dist/component/queries.d.ts +103 -0
  36. package/dist/component/queries.d.ts.map +1 -0
  37. package/dist/component/queries.js +97 -0
  38. package/dist/component/queries.js.map +1 -0
  39. package/dist/component/schema.d.ts +157 -0
  40. package/dist/component/schema.d.ts.map +1 -0
  41. package/dist/component/schema.js +16 -0
  42. package/dist/component/schema.js.map +1 -0
  43. package/dist/component/validators.d.ts +376 -0
  44. package/dist/component/validators.d.ts.map +1 -0
  45. package/dist/component/validators.js +72 -0
  46. package/dist/component/validators.js.map +1 -0
  47. package/dist/react/index.d.ts +29 -0
  48. package/dist/react/index.d.ts.map +1 -0
  49. package/dist/react/index.js +35 -0
  50. package/dist/react/index.js.map +1 -0
  51. package/dist/shared.d.ts +107 -0
  52. package/dist/shared.d.ts.map +1 -0
  53. package/dist/shared.js +127 -0
  54. package/dist/shared.js.map +1 -0
  55. package/package.json +112 -0
  56. package/src/client/index.ts +242 -0
  57. package/src/client/types.ts +65 -0
  58. package/src/component/_generated/api.ts +54 -0
  59. package/src/component/_generated/component.ts +310 -0
  60. package/src/component/_generated/dataModel.ts +60 -0
  61. package/src/component/_generated/server.ts +156 -0
  62. package/src/component/convex.config.ts +9 -0
  63. package/src/component/mutations.ts +230 -0
  64. package/src/component/queries.ts +115 -0
  65. package/src/component/schema.ts +16 -0
  66. package/src/component/validators.ts +104 -0
  67. package/src/react/index.test.ts +52 -0
  68. package/src/react/index.ts +69 -0
  69. package/src/shared.ts +241 -0
  70. package/src/test.ts +17 -0
@@ -0,0 +1,107 @@
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
+ */
10
+ /**
11
+ * Why an evaluation returned the value it did. Stable string codes so hosts can
12
+ * branch on the reason without parsing prose.
13
+ */
14
+ export declare const EVAL_REASON: {
15
+ /** Served the flag's fallthrough value — no rule or rollout matched. */
16
+ readonly flag: "flag";
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. */
28
+ readonly unknown: "unknown";
29
+ };
30
+ /** The set of evaluation reason codes. */
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
+ }
49
+ /** Result of evaluating a single flag. */
50
+ export interface FlagEvaluation {
51
+ value: VariantValue;
52
+ reason: EvalReason;
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
+ //# sourceMappingURL=shared.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shared.d.ts","sourceRoot":"","sources":["../src/shared.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH;;;GAGG;AACH,eAAO,MAAM,WAAW;IACtB,wEAAwE;;IAExE,yDAAyD;;IAEzD,iEAAiE;;IAEjE,+CAA+C;;IAE/C,6EAA6E;;IAE7E,2DAA2D;;IAE3D,gFAAgF;;CAExE,CAAC;AAEX,0CAA0C;AAC1C,MAAM,MAAM,UAAU,GAAG,CAAC,OAAO,WAAW,CAAC,CAAC,MAAM,OAAO,WAAW,CAAC,CAAC;AAExE;;;GAGG;AACH,MAAM,MAAM,YAAY,GAAG,OAAO,GAAG,MAAM,GAAG,MAAM,CAAC;AAErD,2DAA2D;AAC3D,MAAM,MA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AAG,UAAU,CAAC;IAC9B,KAAK,CAAC,EAAE,IAAI,EAAE,CAAC;IACf,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB;AA0CD,6DAA6D;AAC7D,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAOhD;AAED;;;GAGG;AACH,wBAAgB,SAAS,CACvB,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,MAAM,EACf,MAAM,EAAE,KAAK,EAAE,GACd,YAAY,GAAG,IAAI,CAgBrB;AAoBD;;;GAGG;AACH,wBAAgB,YAAY,CAC1B,OAAO,EAAE,MAAM,EACf,IAAI,EAAE,aAAa,EACnB,OAAO,EAAE,WAAW,GACnB,cAAc,CAqBhB"}
package/dist/shared.js ADDED
@@ -0,0 +1,127 @@
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
+ */
10
+ /**
11
+ * Why an evaluation returned the value it did. Stable string codes so hosts can
12
+ * branch on the reason without parsing prose.
13
+ */
14
+ export const EVAL_REASON = {
15
+ /** Served the flag's fallthrough value — no rule or rollout matched. */
16
+ flag: "flag",
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. */
28
+ unknown: "unknown",
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
+ //# sourceMappingURL=shared.js.map
@@ -0,0 +1 @@
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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AACzD,CAAC"}
package/package.json ADDED
@@ -0,0 +1,112 @@
1
+ {
2
+ "name": "@vllnt/convex-flags",
3
+ "version": "0.1.0-canary.0e432b5",
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
+ "license": "MIT",
6
+ "type": "module",
7
+ "packageManager": "pnpm@9.15.4",
8
+ "files": [
9
+ "dist",
10
+ "src"
11
+ ],
12
+ "exports": {
13
+ "./package.json": "./package.json",
14
+ ".": {
15
+ "types": "./dist/client/index.d.ts",
16
+ "default": "./dist/client/index.js"
17
+ },
18
+ "./react": {
19
+ "types": "./dist/react/index.d.ts",
20
+ "default": "./dist/react/index.js"
21
+ },
22
+ "./test": "./src/test.ts",
23
+ "./_generated/component.js": {
24
+ "types": "./dist/component/_generated/component.d.ts"
25
+ },
26
+ "./_generated/component": {
27
+ "types": "./dist/component/_generated/component.d.ts"
28
+ },
29
+ "./convex.config": {
30
+ "types": "./dist/component/convex.config.d.ts",
31
+ "default": "./dist/component/convex.config.js"
32
+ },
33
+ "./convex.config.js": {
34
+ "types": "./dist/component/convex.config.d.ts",
35
+ "default": "./dist/component/convex.config.js"
36
+ }
37
+ },
38
+ "types": "./dist/client/index.d.ts",
39
+ "module": "./dist/client/index.js",
40
+ "scripts": {
41
+ "build": "tsc --project ./tsconfig.build.json",
42
+ "build:codegen": "pnpm convex codegen --component-dir ./src/component && pnpm build",
43
+ "build:clean": "rm -rf dist *.tsbuildinfo && pnpm build:codegen",
44
+ "typecheck": "tsc --noEmit",
45
+ "typecheck:ci": "tsc --noEmit --project tsconfig.ci.json",
46
+ "lint": "eslint .",
47
+ "test": "vitest run --passWithNoTests",
48
+ "test:watch": "vitest --typecheck --clearScreen false",
49
+ "test:coverage": "vitest run --coverage --coverage.reporter=text",
50
+ "generate:llms": "node scripts/generate-llms.mjs",
51
+ "preversion": "pnpm install --frozen-lockfile && pnpm build && pnpm test:coverage && pnpm typecheck && pnpm generate:llms",
52
+ "prepublishOnly": "npm whoami || npm login",
53
+ "alpha": "npm version prerelease --preid alpha && npm publish --tag alpha && git push --follow-tags",
54
+ "release": "npm version patch && npm publish && git push --follow-tags"
55
+ },
56
+ "peerDependencies": {
57
+ "convex": "^1.36.1",
58
+ "react": "^18.0.0 || ^19.0.0"
59
+ },
60
+ "peerDependenciesMeta": {
61
+ "react": {
62
+ "optional": true
63
+ }
64
+ },
65
+ "devDependencies": {
66
+ "@edge-runtime/vm": "^4.0.0",
67
+ "@testing-library/react": "^16",
68
+ "@types/react": "^18",
69
+ "@types/react-dom": "^18",
70
+ "@vitest/coverage-v8": "^3.0.0",
71
+ "@vllnt/eslint-config": "^1.0.0",
72
+ "@vllnt/typescript": "^1.0.0",
73
+ "convex": "^1.36.1",
74
+ "convex-test": "^0.0.50",
75
+ "eslint": "^9.0.0",
76
+ "jsdom": "^25",
77
+ "prettier": "^3.4.0",
78
+ "react": "^18",
79
+ "react-dom": "^18",
80
+ "typescript": "^5.7.0",
81
+ "vite": "^7.3.5",
82
+ "vitest": "^3.0.0"
83
+ },
84
+ "homepage": "https://github.com/vllnt/convex-flags#readme",
85
+ "bugs": {
86
+ "url": "https://github.com/vllnt/convex-flags/issues"
87
+ },
88
+ "author": {
89
+ "name": "bntvllnt",
90
+ "url": "https://bntvllnt.com"
91
+ },
92
+ "funding": {
93
+ "type": "github",
94
+ "url": "https://github.com/sponsors/bntvllnt"
95
+ },
96
+ "repository": {
97
+ "type": "git",
98
+ "url": "https://github.com/vllnt/convex-flags"
99
+ },
100
+ "engines": {
101
+ "node": ">=18"
102
+ },
103
+ "publishConfig": {
104
+ "access": "public"
105
+ },
106
+ "sideEffects": false,
107
+ "keywords": [
108
+ "convex",
109
+ "convex-component",
110
+ "flags"
111
+ ]
112
+ }
@@ -0,0 +1,242 @@
1
+ import type {
2
+ FunctionArgs,
3
+ FunctionReference,
4
+ FunctionReturnType,
5
+ } from "convex/server";
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";
18
+
19
+ /**
20
+ * The component's function references, as exposed on the host via
21
+ * `components.flags`.
22
+ */
23
+ export interface FlagsComponent {
24
+ mutations: {
25
+ define: FunctionReference<
26
+ "mutation",
27
+ "internal",
28
+ {
29
+ key: string;
30
+ value: VariantValue;
31
+ description?: string;
32
+ variants?: Variant[];
33
+ rules?: Rule[];
34
+ rollout?: Rollout;
35
+ },
36
+ string
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
+ >;
51
+ enable: FunctionReference<"mutation", "internal", { key: string }, null>;
52
+ disable: FunctionReference<"mutation", "internal", { key: string }, null>;
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
+ >;
68
+ };
69
+ queries: {
70
+ get: FunctionReference<"query", "internal", { key: string }, FlagDoc | null>;
71
+ list: FunctionReference<"query", "internal", Record<string, never>, FlagDoc[]>;
72
+ evaluate: FunctionReference<
73
+ "query",
74
+ "internal",
75
+ { key: string; context?: EvalContext; default?: VariantValue },
76
+ FlagEvaluation
77
+ >;
78
+ all: FunctionReference<
79
+ "query",
80
+ "internal",
81
+ { context?: EvalContext },
82
+ Record<string, FlagEvaluation>
83
+ >;
84
+ };
85
+ }
86
+
87
+ interface RunQueryCtx {
88
+ runQuery<Q extends FunctionReference<"query", "internal">>(
89
+ reference: Q,
90
+ args: FunctionArgs<Q>,
91
+ ): Promise<FunctionReturnType<Q>>;
92
+ }
93
+
94
+ interface RunMutationCtx {
95
+ runMutation<M extends FunctionReference<"mutation", "internal">>(
96
+ reference: M,
97
+ args: FunctionArgs<M>,
98
+ ): Promise<FunctionReturnType<M>>;
99
+ }
100
+
101
+ /**
102
+ * Consumer-facing client for `@vllnt/convex-flags`. Construct with the mounted
103
+ * component ref, then call from host queries/mutations/actions. The host owns
104
+ * auth: gate the management methods (`define`, `update`, `enable`, `disable`,
105
+ * `archive`, `restore`, `remove`, `setOverride`, `clearOverride`) behind your
106
+ * own authorized mutations.
107
+ *
108
+ * @example
109
+ * ```ts
110
+ * const flags = new Flags(components.flags);
111
+ * if (await flags.isEnabled(ctx, "new-checkout", { subjectRef: userId })) { ... }
112
+ * ```
113
+ */
114
+ export class Flags {
115
+ constructor(private readonly component: FlagsComponent) {}
116
+
117
+ /** Create a flag, or replace its definition if the key already exists. */
118
+ define(ctx: RunMutationCtx, definition: FlagDefinition): Promise<string> {
119
+ return ctx.runMutation(this.component.mutations.define, definition);
120
+ }
121
+
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. */
131
+ enable(ctx: RunMutationCtx, key: string): Promise<null> {
132
+ return ctx.runMutation(this.component.mutations.enable, { key });
133
+ }
134
+
135
+ /** Turn a boolean flag off. Throws `FLAG_NOT_FOUND` if the key is undefined. */
136
+ disable(ctx: RunMutationCtx, key: string): Promise<null> {
137
+ return ctx.runMutation(this.component.mutations.disable, { key });
138
+ }
139
+
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`. */
151
+ remove(ctx: RunMutationCtx, key: string): Promise<null> {
152
+ return ctx.runMutation(this.component.mutations.remove, { key });
153
+ }
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
+
181
+ /** Fetch a single flag definition, or `null` if undefined. */
182
+ get(ctx: RunQueryCtx, key: string): Promise<FlagDoc | null> {
183
+ return ctx.runQuery(this.component.queries.get, { key });
184
+ }
185
+
186
+ /** List every flag definition. */
187
+ list(ctx: RunQueryCtx): Promise<FlagDoc[]> {
188
+ return ctx.runQuery(this.component.queries.list, {});
189
+ }
190
+
191
+ /** Evaluate a flag, returning its value and the reason it was served. */
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;
211
+ }
212
+
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;
220
+ }
221
+
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 });
228
+ }
229
+ }
230
+
231
+ export type {
232
+ EvalContext,
233
+ EvalOptions,
234
+ FlagDefinition,
235
+ FlagDoc,
236
+ FlagEvaluation,
237
+ FlagUpdate,
238
+ Rollout,
239
+ Rule,
240
+ Variant,
241
+ VariantValue,
242
+ };
@@ -0,0 +1,65 @@
1
+ import type {
2
+ EvalContext,
3
+ EvalReason,
4
+ FlagEvaluation,
5
+ Rollout,
6
+ Rule,
7
+ Variant,
8
+ VariantValue,
9
+ } from "../shared.js";
10
+
11
+ /** A flag document as returned by the component queries. */
12
+ export interface FlagDoc {
13
+ _id: string;
14
+ _creationTime: number;
15
+ key: string;
16
+ description?: string;
17
+ value: VariantValue;
18
+ variants?: Variant[];
19
+ rules?: Rule[];
20
+ rollout?: Rollout;
21
+ status: "active" | "archived";
22
+ createdAt: number;
23
+ updatedAt: number;
24
+ }
25
+
26
+ /** A flag definition passed to {@link Flags.define}. */
27
+ export interface FlagDefinition {
28
+ key: string;
29
+ value: VariantValue;
30
+ description?: string;
31
+ variants?: Variant[];
32
+ rules?: Rule[];
33
+ rollout?: Rollout;
34
+ }
35
+
36
+ /**
37
+ * A partial patch passed to {@link Flags.update}. Only the supplied fields are
38
+ * changed; omitted fields are left untouched (unlike {@link FlagDefinition},
39
+ * which fully replaces the definition). The key is passed separately.
40
+ */
41
+ export interface FlagUpdate {
42
+ value?: VariantValue;
43
+ description?: string;
44
+ variants?: Variant[];
45
+ rules?: Rule[];
46
+ rollout?: Rollout;
47
+ }
48
+
49
+ /** Options for {@link Flags.evaluate} / {@link Flags.variant}. */
50
+ export interface EvalOptions {
51
+ /** Host-supplied targeting/bucketing context. */
52
+ context?: EvalContext;
53
+ /** Value to serve when the key is unknown (reason `default`). */
54
+ default?: VariantValue;
55
+ }
56
+
57
+ export type {
58
+ EvalContext,
59
+ EvalReason,
60
+ FlagEvaluation,
61
+ Rollout,
62
+ Rule,
63
+ Variant,
64
+ VariantValue,
65
+ };