@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,230 @@
1
+ import { v } from "convex/values";
2
+ import { mutation } from "./_generated/server.js";
3
+ import type { Doc } from "./_generated/dataModel.js";
4
+ import type { MutationCtx } from "./_generated/server.js";
5
+ import { rollout, rule, variant, variantValue } from "./validators.js";
6
+
7
+ async function findByKey(ctx: MutationCtx, key: string): Promise<Doc<"flags"> | null> {
8
+ return await ctx.db
9
+ .query("flags")
10
+ .withIndex("by_key", (q) => q.eq("key", key))
11
+ .unique();
12
+ }
13
+
14
+ /** Throws the component's single code-tagged error. Returns `never` so callers
15
+ * narrow the flag to non-null after the guard. */
16
+ function flagNotFound(): never {
17
+ throw new Error("FLAG_NOT_FOUND");
18
+ }
19
+
20
+ /**
21
+ * Create a flag, or fully replace its definition if the key already exists
22
+ * (value, description, variants, rules, rollout). Status is preserved on update.
23
+ */
24
+ export const define = mutation({
25
+ args: {
26
+ key: v.string(),
27
+ value: variantValue,
28
+ description: v.optional(v.string()),
29
+ variants: v.optional(v.array(variant)),
30
+ rules: v.optional(v.array(rule)),
31
+ rollout: v.optional(rollout),
32
+ },
33
+ returns: v.id("flags"),
34
+ handler: async (ctx, args) => {
35
+ const now = Date.now();
36
+ const existing = await findByKey(ctx, args.key);
37
+ if (existing !== null) {
38
+ await ctx.db.patch(existing._id, {
39
+ value: args.value,
40
+ description: args.description,
41
+ variants: args.variants,
42
+ rules: args.rules,
43
+ rollout: args.rollout,
44
+ updatedAt: now,
45
+ });
46
+ return existing._id;
47
+ }
48
+ return await ctx.db.insert("flags", {
49
+ key: args.key,
50
+ value: args.value,
51
+ description: args.description,
52
+ variants: args.variants,
53
+ rules: args.rules,
54
+ rollout: args.rollout,
55
+ status: "active",
56
+ createdAt: now,
57
+ updatedAt: now,
58
+ });
59
+ },
60
+ });
61
+
62
+ /**
63
+ * Partially update a flag: patch ONLY the fields supplied (the opposite of
64
+ * `define`, which fully replaces). Omitted fields are left untouched, so
65
+ * re-sending one field never wipes rules/rollout/variants.
66
+ */
67
+ export const update = mutation({
68
+ args: {
69
+ key: v.string(),
70
+ value: v.optional(variantValue),
71
+ description: v.optional(v.string()),
72
+ variants: v.optional(v.array(variant)),
73
+ rules: v.optional(v.array(rule)),
74
+ rollout: v.optional(rollout),
75
+ },
76
+ returns: v.null(),
77
+ handler: async (ctx, args) => {
78
+ const flag = await findByKey(ctx, args.key);
79
+ if (flag === null) {
80
+ flagNotFound();
81
+ }
82
+ const patch: Partial<Doc<"flags">> = { updatedAt: Date.now() };
83
+ if (args.value !== undefined) {
84
+ patch.value = args.value;
85
+ }
86
+ if (args.description !== undefined) {
87
+ patch.description = args.description;
88
+ }
89
+ if (args.variants !== undefined) {
90
+ patch.variants = args.variants;
91
+ }
92
+ if (args.rules !== undefined) {
93
+ patch.rules = args.rules;
94
+ }
95
+ if (args.rollout !== undefined) {
96
+ patch.rollout = args.rollout;
97
+ }
98
+ await ctx.db.patch(flag._id, patch);
99
+ return null;
100
+ },
101
+ });
102
+
103
+ async function setValue(ctx: MutationCtx, key: string, value: boolean): Promise<void> {
104
+ const flag = await findByKey(ctx, key);
105
+ if (flag === null) {
106
+ flagNotFound();
107
+ }
108
+ await ctx.db.patch(flag._id, { value, updatedAt: Date.now() });
109
+ }
110
+
111
+ /** Turn a boolean flag on (set its value to `true`). */
112
+ export const enable = mutation({
113
+ args: { key: v.string() },
114
+ returns: v.null(),
115
+ handler: async (ctx, args) => {
116
+ await setValue(ctx, args.key, true);
117
+ return null;
118
+ },
119
+ });
120
+
121
+ /** Turn a boolean flag off (set its value to `false`). */
122
+ export const disable = mutation({
123
+ args: { key: v.string() },
124
+ returns: v.null(),
125
+ handler: async (ctx, args) => {
126
+ await setValue(ctx, args.key, false);
127
+ return null;
128
+ },
129
+ });
130
+
131
+ async function setStatus(
132
+ ctx: MutationCtx,
133
+ key: string,
134
+ status: "active" | "archived",
135
+ ): Promise<void> {
136
+ const flag = await findByKey(ctx, key);
137
+ if (flag === null) {
138
+ flagNotFound();
139
+ }
140
+ await ctx.db.patch(flag._id, { status, updatedAt: Date.now() });
141
+ }
142
+
143
+ /** Archive a flag: reversible retirement. Evaluation skips targeting and serves
144
+ * the flag's base value with reason `disabled`. */
145
+ export const archive = mutation({
146
+ args: { key: v.string() },
147
+ returns: v.null(),
148
+ handler: async (ctx, args) => {
149
+ await setStatus(ctx, args.key, "archived");
150
+ return null;
151
+ },
152
+ });
153
+
154
+ /** Restore an archived flag to active. */
155
+ export const restore = mutation({
156
+ args: { key: v.string() },
157
+ returns: v.null(),
158
+ handler: async (ctx, args) => {
159
+ await setStatus(ctx, args.key, "active");
160
+ return null;
161
+ },
162
+ });
163
+
164
+ /** Permanently delete a flag and any per-subject overrides it owns. */
165
+ export const remove = mutation({
166
+ args: { key: v.string() },
167
+ returns: v.null(),
168
+ handler: async (ctx, args) => {
169
+ const flag = await findByKey(ctx, args.key);
170
+ if (flag === null) {
171
+ flagNotFound();
172
+ }
173
+ const overrides = await ctx.db
174
+ .query("overrides")
175
+ .withIndex("by_key_subject", (q) => q.eq("key", args.key))
176
+ .collect();
177
+ for (const override of overrides) {
178
+ await ctx.db.delete(override._id);
179
+ }
180
+ await ctx.db.delete(flag._id);
181
+ return null;
182
+ },
183
+ });
184
+
185
+ /** Force a flag's value for one subject. The flag must exist. */
186
+ export const setOverride = mutation({
187
+ args: { key: v.string(), subjectRef: v.string(), value: variantValue },
188
+ returns: v.null(),
189
+ handler: async (ctx, args) => {
190
+ const flag = await findByKey(ctx, args.key);
191
+ if (flag === null) {
192
+ flagNotFound();
193
+ }
194
+ const existing = await ctx.db
195
+ .query("overrides")
196
+ .withIndex("by_key_subject", (q) =>
197
+ q.eq("key", args.key).eq("subjectRef", args.subjectRef),
198
+ )
199
+ .unique();
200
+ if (existing !== null) {
201
+ await ctx.db.patch(existing._id, { value: args.value });
202
+ } else {
203
+ await ctx.db.insert("overrides", {
204
+ key: args.key,
205
+ subjectRef: args.subjectRef,
206
+ value: args.value,
207
+ createdAt: Date.now(),
208
+ });
209
+ }
210
+ return null;
211
+ },
212
+ });
213
+
214
+ /** Clear a subject's override for a flag. No-op if none exists. */
215
+ export const clearOverride = mutation({
216
+ args: { key: v.string(), subjectRef: v.string() },
217
+ returns: v.null(),
218
+ handler: async (ctx, args) => {
219
+ const existing = await ctx.db
220
+ .query("overrides")
221
+ .withIndex("by_key_subject", (q) =>
222
+ q.eq("key", args.key).eq("subjectRef", args.subjectRef),
223
+ )
224
+ .unique();
225
+ if (existing !== null) {
226
+ await ctx.db.delete(existing._id);
227
+ }
228
+ return null;
229
+ },
230
+ });
@@ -0,0 +1,115 @@
1
+ import { v } from "convex/values";
2
+ import { query } from "./_generated/server.js";
3
+ import type { Doc } from "./_generated/dataModel.js";
4
+ import type { QueryCtx } from "./_generated/server.js";
5
+ import { evalContext, evaluation, flagDoc, variantValue } from "./validators.js";
6
+ import {
7
+ EVAL_REASON,
8
+ evaluateFlag,
9
+ type EvalContext,
10
+ type FlagEvaluation,
11
+ type VariantValue,
12
+ } from "../shared.js";
13
+
14
+ /** Resolve a single flag: a per-subject override wins, otherwise the engine. */
15
+ async function resolve(
16
+ ctx: QueryCtx,
17
+ flag: Doc<"flags">,
18
+ context: EvalContext,
19
+ ): Promise<FlagEvaluation> {
20
+ const subjectRef = context.subjectRef;
21
+ if (subjectRef !== undefined) {
22
+ const override = await ctx.db
23
+ .query("overrides")
24
+ .withIndex("by_key_subject", (q) =>
25
+ q.eq("key", flag.key).eq("subjectRef", subjectRef),
26
+ )
27
+ .unique();
28
+ if (override !== null) {
29
+ return { value: override.value, reason: EVAL_REASON.override };
30
+ }
31
+ }
32
+ return evaluateFlag(flag.key, flag, context);
33
+ }
34
+
35
+ /** Fetch a single flag definition by key. */
36
+ export const get = query({
37
+ args: { key: v.string() },
38
+ returns: v.union(v.null(), flagDoc),
39
+ handler: async (ctx, args) => {
40
+ return await ctx.db
41
+ .query("flags")
42
+ .withIndex("by_key", (q) => q.eq("key", args.key))
43
+ .unique();
44
+ },
45
+ });
46
+
47
+ /** List every flag definition. */
48
+ export const list = query({
49
+ args: {},
50
+ returns: v.array(flagDoc),
51
+ handler: async (ctx) => {
52
+ return await ctx.db.query("flags").collect();
53
+ },
54
+ });
55
+
56
+ /**
57
+ * Evaluate one flag against optional context. Resolution order: per-subject
58
+ * override → archived → targeting rules → fallthrough rollout → flag value. An
59
+ * unknown key serves the caller `default` (reason `default`) or `false`
60
+ * (reason `unknown`).
61
+ */
62
+ export const evaluate = query({
63
+ args: {
64
+ key: v.string(),
65
+ context: v.optional(evalContext),
66
+ default: v.optional(variantValue),
67
+ },
68
+ returns: evaluation,
69
+ handler: async (ctx, args): Promise<FlagEvaluation> => {
70
+ const flag = await ctx.db
71
+ .query("flags")
72
+ .withIndex("by_key", (q) => q.eq("key", args.key))
73
+ .unique();
74
+ if (flag === null) {
75
+ return args.default !== undefined
76
+ ? { value: args.default, reason: EVAL_REASON.default }
77
+ : { value: false, reason: EVAL_REASON.unknown };
78
+ }
79
+ return await resolve(ctx, flag, args.context ?? {});
80
+ },
81
+ });
82
+
83
+ /**
84
+ * Evaluate every flag at once against optional context — the bootstrap payload
85
+ * for a reactive client. Per-subject overrides for the context's `subjectRef`
86
+ * are applied (loaded in a single query, never inside the loop).
87
+ */
88
+ export const all = query({
89
+ args: { context: v.optional(evalContext) },
90
+ returns: v.record(v.string(), evaluation),
91
+ handler: async (ctx, args) => {
92
+ const context = args.context ?? {};
93
+ const flags = await ctx.db.query("flags").collect();
94
+ const overrideValues: Record<string, VariantValue> = {};
95
+ const subjectRef = context.subjectRef;
96
+ if (subjectRef !== undefined) {
97
+ const overrides = await ctx.db
98
+ .query("overrides")
99
+ .withIndex("by_subject", (q) => q.eq("subjectRef", subjectRef))
100
+ .collect();
101
+ for (const override of overrides) {
102
+ overrideValues[override.key] = override.value;
103
+ }
104
+ }
105
+ const result: Record<string, FlagEvaluation> = {};
106
+ for (const flag of flags) {
107
+ const overridden = overrideValues[flag.key];
108
+ result[flag.key] =
109
+ overridden !== undefined
110
+ ? { value: overridden, reason: EVAL_REASON.override }
111
+ : evaluateFlag(flag.key, flag, context);
112
+ }
113
+ return result;
114
+ },
115
+ });
@@ -0,0 +1,16 @@
1
+ import { defineSchema, defineTable } from "convex/server";
2
+ import { flagFields, overrideFields } from "./validators.js";
3
+
4
+ /**
5
+ * Sandboxed tables — the component's own concern only. A flag is keyed by an
6
+ * opaque, host-chosen string; the component never models the host's domain.
7
+ */
8
+ export default defineSchema({
9
+ flags: defineTable(flagFields).index("by_key", ["key"]),
10
+ // Per-subject overrides: force a flag's value for one subject. Indexed for
11
+ // both the single-flag read (by_key_subject) and the bulk `all` read
12
+ // (by_subject), so neither path queries inside a loop.
13
+ overrides: defineTable(overrideFields)
14
+ .index("by_key_subject", ["key", "subjectRef"])
15
+ .index("by_subject", ["subjectRef"]),
16
+ });
@@ -0,0 +1,104 @@
1
+ import { v } from "convex/values";
2
+
3
+ /**
4
+ * A flag/variant value — typed primitives only (boolean, string, number). The
5
+ * client class is generic over the host's concrete value type; the component
6
+ * stores the typed union. No `v.any()`.
7
+ */
8
+ export const variantValue = v.union(v.boolean(), v.string(), v.number());
9
+
10
+ /** An attribute value usable in a targeting comparison. */
11
+ export const attributeValue = v.union(v.boolean(), v.string(), v.number());
12
+
13
+ /** Comparison operators available to a targeting condition. */
14
+ export const conditionOp = v.union(
15
+ v.literal("eq"),
16
+ v.literal("neq"),
17
+ v.literal("in"),
18
+ v.literal("nin"),
19
+ v.literal("contains"),
20
+ v.literal("gt"),
21
+ v.literal("gte"),
22
+ v.literal("lt"),
23
+ v.literal("lte"),
24
+ );
25
+
26
+ /** One targeting condition: `<attribute> <op> <values>`. */
27
+ export const condition = v.object({
28
+ attribute: v.string(),
29
+ op: conditionOp,
30
+ values: v.array(attributeValue),
31
+ });
32
+
33
+ /** One weighted entry in a rollout's distribution. */
34
+ export const split = v.object({ value: variantValue, weight: v.number() });
35
+
36
+ /** A deterministic weighted distribution across variant values. */
37
+ export const rollout = v.object({
38
+ splits: v.array(split),
39
+ by: v.optional(v.string()),
40
+ });
41
+
42
+ /** A declared variant (metadata for tooling / labels). */
43
+ export const variant = v.object({ value: variantValue, label: v.optional(v.string()) });
44
+
45
+ /** A targeting rule: all conditions AND; first matching rule (in order) wins. */
46
+ export const rule = v.object({
47
+ conditions: v.array(condition),
48
+ value: v.optional(variantValue),
49
+ rollout: v.optional(rollout),
50
+ });
51
+
52
+ /** Lifecycle status of a flag. */
53
+ export const flagStatus = v.union(v.literal("active"), v.literal("archived"));
54
+
55
+ /**
56
+ * Column validators for a stored flag document (excluding Convex system fields).
57
+ * Shared between the schema and the query return validators.
58
+ */
59
+ export const flagFields = {
60
+ key: v.string(),
61
+ description: v.optional(v.string()),
62
+ value: variantValue,
63
+ variants: v.optional(v.array(variant)),
64
+ rules: v.optional(v.array(rule)),
65
+ rollout: v.optional(rollout),
66
+ status: flagStatus,
67
+ createdAt: v.number(),
68
+ updatedAt: v.number(),
69
+ };
70
+
71
+ /** Public shape of a flag document returned by queries. */
72
+ export const flagDoc = v.object({
73
+ _id: v.id("flags"),
74
+ _creationTime: v.number(),
75
+ ...flagFields,
76
+ });
77
+
78
+ /** Column validators for a stored per-subject override. */
79
+ export const overrideFields = {
80
+ key: v.string(),
81
+ subjectRef: v.string(),
82
+ value: variantValue,
83
+ createdAt: v.number(),
84
+ };
85
+
86
+ /** Host-supplied, per-evaluation context. */
87
+ export const evalContext = v.object({
88
+ subjectRef: v.optional(v.string()),
89
+ attributes: v.optional(v.record(v.string(), attributeValue)),
90
+ });
91
+
92
+ /** Stable evaluation reason codes (kept in sync with `EVAL_REASON` in shared.ts). */
93
+ export const evalReason = v.union(
94
+ v.literal("flag"),
95
+ v.literal("rule"),
96
+ v.literal("rollout"),
97
+ v.literal("override"),
98
+ v.literal("disabled"),
99
+ v.literal("default"),
100
+ v.literal("unknown"),
101
+ );
102
+
103
+ /** Result of evaluating one flag: the value plus a reason code. */
104
+ export const evaluation = v.object({ value: variantValue, reason: evalReason });
@@ -0,0 +1,52 @@
1
+ // @vitest-environment jsdom
2
+ import { renderHook } from "@testing-library/react";
3
+ import { makeFunctionReference } from "convex/server";
4
+ import { beforeEach, expect, test, vi } from "vitest";
5
+ import { useFlag, useFlags, type AllRef, type EvaluateRef } from "./index.js";
6
+
7
+ const { useQuerySpy } = vi.hoisted(() => ({ useQuerySpy: vi.fn() }));
8
+ vi.mock("convex/react", () => ({ useQuery: useQuerySpy }));
9
+
10
+ const evalRef: EvaluateRef = makeFunctionReference<"query">("flags:evaluate");
11
+ const allRef: AllRef = makeFunctionReference<"query">("flags:all");
12
+
13
+ beforeEach(() => {
14
+ useQuerySpy.mockReset();
15
+ useQuerySpy.mockReturnValue({ value: true, reason: "flag" });
16
+ });
17
+
18
+ test("useFlag forwards key + context + default and returns the query result", () => {
19
+ const { result } = renderHook(() =>
20
+ useFlag(evalRef, "new-checkout", {
21
+ context: { subjectRef: "u1", attributes: { plan: "pro" } },
22
+ default: "off",
23
+ }),
24
+ );
25
+ expect(useQuerySpy).toHaveBeenCalledWith(evalRef, {
26
+ key: "new-checkout",
27
+ context: { subjectRef: "u1", attributes: { plan: "pro" } },
28
+ default: "off",
29
+ });
30
+ expect(result.current).toEqual({ value: true, reason: "flag" });
31
+ });
32
+
33
+ test("useFlag works with no options", () => {
34
+ renderHook(() => useFlag(evalRef, "k"));
35
+ expect(useQuerySpy).toHaveBeenCalledWith(evalRef, {
36
+ key: "k",
37
+ context: undefined,
38
+ default: undefined,
39
+ });
40
+ });
41
+
42
+ test("useFlags forwards context", () => {
43
+ useQuerySpy.mockReturnValue({ k: { value: true, reason: "flag" } });
44
+ const { result } = renderHook(() => useFlags(allRef, { subjectRef: "u1" }));
45
+ expect(useQuerySpy).toHaveBeenCalledWith(allRef, { context: { subjectRef: "u1" } });
46
+ expect(result.current).toEqual({ k: { value: true, reason: "flag" } });
47
+ });
48
+
49
+ test("useFlags works with no context", () => {
50
+ renderHook(() => useFlags(allRef));
51
+ expect(useQuerySpy).toHaveBeenCalledWith(allRef, { context: undefined });
52
+ });
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Optional React layer for `@vllnt/convex-flags`.
3
+ *
4
+ * Thin, tree-shakeable hooks over `convex/react`'s `useQuery`. They wrap the
5
+ * host's own re-exported `evaluate` / `all` query refs — the component never
6
+ * owns the host's `api`. `react` and `convex/react` are optional peer deps: a
7
+ * backend-only consumer never imports this entry and pulls in zero React.
8
+ *
9
+ * @example
10
+ * ```tsx
11
+ * // convex/flags.ts (host) re-exports the query refs from its wrappers, then:
12
+ * const evaluation = useFlag(api.flags.evaluate, "new-checkout", { context: { subjectRef } });
13
+ * if (evaluation?.value === true) { ... }
14
+ * ```
15
+ */
16
+ import { useQuery } from "convex/react";
17
+ import type { FunctionReference } from "convex/server";
18
+ import type { EvalContext, FlagEvaluation, VariantValue } from "../shared.js";
19
+
20
+ /** The host's re-exported `evaluate` query reference. */
21
+ export type EvaluateRef = FunctionReference<
22
+ "query",
23
+ "public",
24
+ { key: string; context?: EvalContext; default?: VariantValue },
25
+ FlagEvaluation
26
+ >;
27
+
28
+ /** The host's re-exported `all` query reference. */
29
+ export type AllRef = FunctionReference<
30
+ "query",
31
+ "public",
32
+ { context?: EvalContext },
33
+ Record<string, FlagEvaluation>
34
+ >;
35
+
36
+ /** Options for {@link useFlag}. */
37
+ export interface UseFlagOptions {
38
+ context?: EvalContext;
39
+ default?: VariantValue;
40
+ }
41
+
42
+ /**
43
+ * Reactively evaluate a single flag. Returns `undefined` while the query loads,
44
+ * then the {@link FlagEvaluation}. Re-renders whenever the flag changes.
45
+ */
46
+ export function useFlag(
47
+ query: EvaluateRef,
48
+ key: string,
49
+ options?: UseFlagOptions,
50
+ ): FlagEvaluation | undefined {
51
+ return useQuery(query, {
52
+ key,
53
+ context: options?.context,
54
+ default: options?.default,
55
+ });
56
+ }
57
+
58
+ /**
59
+ * Reactively evaluate every flag against optional context. Returns `undefined`
60
+ * while loading, then a map of flag key → {@link FlagEvaluation}.
61
+ */
62
+ export function useFlags(
63
+ query: AllRef,
64
+ context?: EvalContext,
65
+ ): Record<string, FlagEvaluation> | undefined {
66
+ return useQuery(query, { context });
67
+ }
68
+
69
+ export type { EvalContext, FlagEvaluation, VariantValue };