@vllnt/convex-flags 0.1.0 → 0.1.1-canary.0e54429

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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,104 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented here. The format is based on
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to
5
+ [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
+
7
+
8
+ ## [0.1.1] - Unreleased
9
+
10
+ ### Fixed
11
+
12
+ - The published tarball no longer includes the React and status test files.
13
+ - Management mutations reject an empty flag `key`, and `setOverride` / `clearOverride` an empty
14
+ `subjectRef`, with `ConvexError({ code: "INVALID_ARGUMENT" })`.
15
+ - `define` and `update` reject rollout weights (flag-level and rule-level) that are `NaN`,
16
+ infinite or negative with `INVALID_ARGUMENT`; previously they were silently ignored or skewed
17
+ bucketing.
18
+ - Rollouts with a non-whole-number weight now split subjects by their weights. In 0.1.0 some of
19
+ these weights bucketed unevenly: weights summing to 1 (such as `0.5` / `0.5`) sent every subject
20
+ to the first split, other sets were skewed (`1.5` / `1.5` served about 67% / 33%), and a split
21
+ could get no subjects at all (`0.25` / `0.75` / `1` never served its middle split). These
22
+ rollouts are re-bucketed once on upgrade, so some of their subjects change value. Rollouts whose
23
+ weights are all whole numbers, and rows stored with an `Infinity` weight before weights were
24
+ validated, bucket exactly as before.
25
+
26
+ ### Changed
27
+
28
+ - Management mutations (`define`, `update`, `enable`, `disable`, `archive`, `restore`,
29
+ `setOverride`) skip the write when nothing changed, so idempotent re-defines no longer bump
30
+ `updatedAt` or re-run every `evaluate`/`all` subscription.
31
+ - Upgrade dev tooling (vitest 5.1.1, vite 8.3, convex 1.51, convex-test 0.0.73, prettier 3.10,
32
+ jsdom 31, `@vllnt/typescript` 3 with `exactOptionalPropertyTypes` kept off), and override the
33
+ vulnerable transitive `handlebars`, `deepmerge-ts` and `minimatch` releases.
34
+ - Adopt pnpm 10 with a release-age gate; releases are published only from CI with npm trusted
35
+ publishing and provenance.
36
+ - Document the component error codes and how to use `/test` in a consuming app.
37
+ - The package now ships `docs/API.md`, `CHANGELOG.md` and `llms.txt`, so the docs in
38
+ `node_modules/@vllnt/convex-flags/` match the installed version. `llms.txt` links to these
39
+ files with relative paths, and a `test:package` CI check fails when a required file is missing
40
+ from the tarball or a contributor-only file is included.
41
+ - `docs/API.md` lists every entry point and its exports, the `./react` option and ref types, and
42
+ how a rollout that cannot bucket inside a matched rule falls back to the flag value.
43
+ - Canary builds publish on every qualifying push to `main` (dist-tag `canary` only, never
44
+ `latest`), including docs-only changes to the shipped files.
45
+
46
+ ## [0.1.0] - 2026-09-01
47
+
48
+ ### Added
49
+
50
+ - First release of `@vllnt/convex-flags` — feature flags as a sandboxed Convex component, evaluated
51
+ on the backend and streamed to clients over Convex's reactive queries.
52
+ - `Flags` client class: `define`, `enable`, `disable`, `remove`, `get`, `list`, `evaluate`,
53
+ `isEnabled`, and `all`.
54
+ - Sandboxed `flags` table keyed by an opaque, host-chosen flag key (`by_key` index).
55
+ - `example/convex/` host-app harness with 100% end-to-end coverage via `convex-test`.
56
+
57
+ - **Multivariate variants** — a flag value is now a typed primitive (`boolean | string | number`);
58
+ `define` accepts `variants` metadata. Added `variant(ctx, key, options?)` returning just the value.
59
+ - **Attribute targeting** — `define` accepts ordered `rules` (`{ conditions, value | rollout }`) with
60
+ operators `eq`, `neq`, `in`, `nin`, `contains`, `gt`, `gte`, `lt`, `lte`. First matching rule wins;
61
+ conditions within a rule AND together; an empty condition list is a catch-all.
62
+ - **Percentage rollouts** — `define` accepts a `rollout` of weighted `splits`, bucketed
63
+ deterministically (FNV-1a) by `context.subjectRef` or a named `by` attribute, so a subject always
64
+ resolves to the same value.
65
+ - **Evaluation context** — `evaluate` / `isEnabled` / `all` / `variant` take an optional host-supplied
66
+ `EvalContext` (`{ subjectRef?, attributes? }`); `evaluate` takes an optional `default` for unknown keys.
67
+ - **Per-subject overrides** — `setOverride(key, subjectRef, value)` / `clearOverride(key, subjectRef)`;
68
+ an override wins over targeting in `evaluate` and `all`.
69
+ - **Lifecycle** — `archive(key)` (reversible; serves the base value with reason `disabled`) and
70
+ `restore(key)`, distinct from `remove` (which now also deletes a flag's overrides).
71
+ - **React** — optional `@vllnt/convex-flags/react` entry exporting `useFlag` / `useFlags`; `react` is
72
+ an optional peer dependency.
73
+ - New evaluation reason codes: `rule`, `rollout`, `override`, `disabled`, `default` (alongside
74
+ `flag`, `unknown`).
75
+ - **Partial update** — `update(ctx, key, patch)` patches only the supplied fields, leaving the rest
76
+ untouched (the opposite of `define`, which fully replaces a definition).
77
+
78
+ ### Changed
79
+
80
+ - Treat Convex `_generated` output as CLI-owned, exclude it from formatting, and expose a
81
+ dedicated codegen script.
82
+ - Refresh all direct dependencies to their latest compatible releases for canary validation.
83
+ - Require `convex@^1.45.0` and update `convex-test` to `^0.0.56`.
84
+ - **Docs polish** — refreshed the package tagline; the README Usage section now shows a complete
85
+ `convex/flags.ts` host module (the `evaluate`/`all` queries the React hooks consume, plus gated
86
+ management wrappers); documented `define` (full replace) vs `update` (partial) and that
87
+ `enable`/`disable` are boolean convenience.
88
+
89
+ ### Fixed
90
+
91
+ - **Backward-compatible `status`** — the stored `flags.status` column is now optional, so a
92
+ deployment holding flag rows written before `status` existed no longer fails schema validation on
93
+ the next `convex deploy` (`Object is missing the required field status`). Reads materialize an
94
+ absent status as `"active"` — `get`/`list` return a concrete `status` and evaluation treats a
95
+ legacy flag as active — so the public `FlagDoc` shape is unchanged. `define` still writes
96
+ `status: "active"` for new flags; `restore(key)` stamps it onto legacy rows in storage.
97
+ ([#5](https://github.com/vllnt/convex-flags/issues/5))
98
+
99
+ ### Notes
100
+
101
+ - Backward compatible: the boolean kill-switch API (`define({ key, value })`, `enable`/`disable`,
102
+ `isEnabled(key)`, `evaluate(key)`, `get`/`list`/`all`/`remove`) is unchanged.
103
+ - Deferred: named reusable segments, JSON-object variant values, scheduled/progressive rollouts,
104
+ stale-flag detection, and audit-event emission — see `ROADMAP.md`.
package/README.md CHANGED
@@ -1,4 +1,5 @@
1
1
  <!-- Badges -->
2
+
2
3
  [![Convex Component](https://img.shields.io/badge/convex-component-EE342F.svg)](https://www.convex.dev/components)
3
4
  [![npm](https://img.shields.io/npm/v/@vllnt/convex-flags.svg)](https://www.npmjs.com/package/@vllnt/convex-flags)
4
5
  [![CI](https://img.shields.io/github/actions/workflow/status/vllnt/convex-flags/ci.yml?branch=main&label=CI)](https://github.com/vllnt/convex-flags/actions/workflows/ci.yml)
@@ -6,7 +7,10 @@
6
7
 
7
8
  # @vllnt/convex-flags
8
9
 
9
- Feature flags as a Convex component — backend-evaluated and streamed to every connected client in real time: boolean kill-switches, multivariate variants, percentage rollouts, attribute targeting, and per-subject overrides, with no redeploy and no third-party flag SaaS.
10
+ Feature flags as a Convex component — backend-evaluated and streamed to every
11
+ connected client in real time: boolean kill-switches, multivariate variants,
12
+ percentage rollouts, attribute targeting, and per-subject overrides, with no
13
+ redeploy and no third-party flag SaaS.
10
14
 
11
15
  ```ts
12
16
  const flags = new Flags(components.flags);
@@ -17,14 +21,20 @@ const on = await flags.isEnabled(ctx, "new-checkout", { subjectRef: userId }); /
17
21
 
18
22
  ## Features
19
23
 
20
- - **Boolean, multivariate & rollouts** — boolean kill-switches, string/number variants, and weighted percentage rollouts with stable per-subject bucketing.
21
- - **Attribute targeting** — ordered rules (`eq`, `in`, `contains`, `gt`, …) over a host-supplied typed context.
24
+ - **Boolean, multivariate & rollouts** — boolean kill-switches, string/number
25
+ variants, and weighted percentage rollouts with stable per-subject bucketing.
26
+ - **Attribute targeting** — ordered rules (`eq`, `in`, `contains`, `gt`, …) over
27
+ a host-supplied typed context.
22
28
  - **Per-subject overrides** — force any flag's value for one subject.
23
29
  - **Lifecycle** — archive (reversible) distinct from permanent delete.
24
- - **Real-time** — evaluated in Convex queries, so changes stream to clients over the same reactive subscriptions as your app data.
25
- - **Data isolation** — definitions and overrides live in the component's own sandboxed tables; no blast radius into your schema.
26
- - **Reactive React hooks** — optional `./react` entry (`useFlag`/`useFlags`); backend-only consumers pull in zero React.
27
- - **Auth-agnostic & dual-target** — the host gates every management call; runs unchanged on Convex Cloud and self-hosted `convex-backend`.
30
+ - **Real-time** — evaluated in Convex queries, so changes stream to clients over
31
+ the same reactive subscriptions as your app data.
32
+ - **Data isolation** — definitions and overrides live in the component's own
33
+ sandboxed tables; no blast radius into your schema.
34
+ - **Reactive React hooks** — optional `./react` entry (`useFlag`/`useFlags`);
35
+ backend-only consumers pull in zero React.
36
+ - **Auth-agnostic & dual-target** — the host gates every management call; runs
37
+ unchanged on Convex Cloud and self-hosted `convex-backend`.
28
38
 
29
39
  ## Installation
30
40
 
@@ -43,7 +53,24 @@ app.use(flags);
43
53
  export default app;
44
54
  ```
45
55
 
46
- Peer dependency: `convex@^1.36.1`. `react` is an optional peer dependency, needed only for the `./react` entry.
56
+ Peer dependency: `convex@^1.45.0`. `react` is an optional peer dependency,
57
+ needed only for the `./react` entry.
58
+
59
+ The untagged install selects the npm `latest` release; `@canary` tracks `main`.
60
+ Check the installed version's peer range before upgrading.
61
+
62
+ For isolated flag sets, mount twice with names, for example
63
+ `app.use(flags, { name: "webFlags" })` and
64
+ `app.use(flags, { name: "mobileFlags" })`, then construct clients with
65
+ `components.webFlags` and `components.mobileFlags`. Run `npx convex dev` after
66
+ mounting to generate these references.
67
+
68
+ ## For coding agents
69
+
70
+ The docs are bundled in the package at
71
+ `node_modules/@vllnt/convex-flags/docs/` (`llms.txt` and `CHANGELOG.md` sit at
72
+ the package root) and match the installed version. Read them before writing code
73
+ against this package.
47
74
 
48
75
  ## Usage
49
76
 
@@ -54,104 +81,156 @@ Peer dependency: `convex@^1.36.1`. `react` is an optional peer dependency, neede
54
81
  import { v } from "convex/values";
55
82
  import { Flags } from "@vllnt/convex-flags";
56
83
  import { components } from "./_generated/api";
57
- import { mutation, query } from "./_generated/server";
84
+ import { internalMutation, query } from "./_generated/server";
58
85
 
59
86
  export const flags = new Flags(components.flags);
87
+ const value = v.union(v.boolean(), v.string(), v.number());
88
+ const context = v.object({
89
+ subjectRef: v.optional(v.string()),
90
+ attributes: v.optional(v.record(v.string(), value)),
91
+ });
92
+ const evaluation = v.object({
93
+ value,
94
+ reason: v.union(
95
+ v.literal("flag"),
96
+ v.literal("rule"),
97
+ v.literal("rollout"),
98
+ v.literal("override"),
99
+ v.literal("disabled"),
100
+ v.literal("default"),
101
+ v.literal("unknown"),
102
+ ),
103
+ });
60
104
 
61
105
  // Evaluation queries — reactive; `api.flags.evaluate` is what the React hooks below use.
62
106
  export const evaluate = query({
63
- args: { key: v.string(), context: v.optional(v.any()), default: v.optional(v.any()) },
107
+ args: {
108
+ key: v.string(),
109
+ context: v.optional(context),
110
+ default: v.optional(value),
111
+ },
112
+ returns: evaluation,
64
113
  handler: (ctx, args) =>
65
- flags.evaluate(ctx, args.key, { context: args.context, default: args.default }),
114
+ flags.evaluate(ctx, args.key, {
115
+ context: args.context,
116
+ default: args.default,
117
+ }),
66
118
  });
67
119
 
68
120
  export const all = query({
69
- args: { context: v.optional(v.any()) },
121
+ args: { context: v.optional(context) },
122
+ returns: v.record(v.string(), evaluation),
70
123
  handler: (ctx, args) => flags.all(ctx, args.context),
71
124
  });
72
125
 
73
- // Management mutations — apply your own auth check before delegating.
74
- export const define = mutation({
75
- args: { key: v.string(), value: v.any() /* + description/variants/rules/rollout */ },
76
- handler: (ctx, args) => {
77
- // assertAdmin(ctx);
78
- return flags.define(ctx, args);
79
- },
126
+ // Internal-only management: not callable directly from a browser.
127
+ // If exposing a public mutation, enforce your application's admin policy first.
128
+ export const define = internalMutation({
129
+ args: { key: v.string(), value },
130
+ returns: v.string(),
131
+ handler: (ctx, args) => flags.define(ctx, args),
80
132
  });
81
133
 
82
134
  // Wrap the rest the same way — `update`, `enable`, `disable`, `archive`,
83
- // `restore`, `setOverride`, `clearOverride` — each gated then delegated.
135
+ // `restore`, `remove`, `setOverride`, `clearOverride` — each gated then delegated.
84
136
  ```
85
137
 
86
138
  ```ts
87
- // Flags are data — create them from your own authorized mutations (host owns auth),
88
- // then evaluate inside any query, mutation, or action.
89
- import { query } from "./_generated/server";
139
+ // convex/checkout.ts
140
+ import { v } from "convex/values";
141
+ import { internalMutation, query } from "./_generated/server";
90
142
  import { flags } from "./flags";
91
143
 
92
144
  // A targeted rollout: pro users get the new checkout; everyone else is a 50/50 split.
93
- export const setup = async (ctx) => {
94
- await flags.define(ctx, {
95
- key: "new-checkout",
96
- value: false,
97
- rules: [{ conditions: [{ attribute: "plan", op: "eq", values: ["pro"] }], value: true }],
98
- rollout: { splits: [{ value: true, weight: 50 }, { value: false, weight: 50 }] },
99
- });
100
- };
145
+ export const setup = internalMutation({
146
+ args: {},
147
+ returns: v.string(),
148
+ handler: (ctx) =>
149
+ flags.define(ctx, {
150
+ key: "new-checkout",
151
+ value: false,
152
+ rules: [
153
+ {
154
+ conditions: [{ attribute: "plan", op: "eq", values: ["pro"] }],
155
+ value: true,
156
+ },
157
+ ],
158
+ rollout: {
159
+ splits: [
160
+ { value: true, weight: 50 },
161
+ { value: false, weight: 50 },
162
+ ],
163
+ },
164
+ }),
165
+ });
101
166
 
102
167
  export const checkout = query({
103
168
  args: {},
104
- handler: async (ctx) =>
105
- (await flags.isEnabled(ctx, "new-checkout", { subjectRef: "user-123", attributes: { plan: "free" } }))
106
- ? loadNewCheckout(ctx)
107
- : loadLegacyCheckout(ctx),
169
+ returns: v.boolean(),
170
+ // Demo identity; derive these values from trusted host data in your app.
171
+ handler: (ctx) =>
172
+ flags.isEnabled(ctx, "new-checkout", {
173
+ subjectRef: "user-123",
174
+ attributes: { plan: "free" },
175
+ }),
108
176
  });
109
177
  ```
110
178
 
111
179
  ## API Reference
112
180
 
113
- | Method | Kind | Result |
114
- |--------|------|--------|
115
- | `isEnabled(ctx, key, context?)` | query | `boolean` (value `=== true`) |
116
- | `evaluate(ctx, key, options?)` | query | `FlagEvaluation` (`value` + `reason`) |
117
- | `variant(ctx, key, options?)` | query | the resolved value |
118
- | `get(ctx, key)` / `list(ctx)` | query | `FlagDoc \| null` / `FlagDoc[]` |
119
- | `all(ctx, context?)` | query | `Record<string, FlagEvaluation>` (reactive bootstrap) |
120
- | `define(ctx, definition)` | mutation | Create or **fully replace** a flag (value, variants, rules, rollout) |
121
- | `update(ctx, key, patch)` | mutation | **Partially** update a flag — only supplied fields change, the rest are kept |
122
- | `enable(ctx, key)` / `disable(ctx, key)` | mutation | Toggle a boolean flag (sets value `true`/`false`) |
123
- | `archive(ctx, key)` / `restore(ctx, key)` | mutation | Reversibly retire / re-activate a flag |
124
- | `setOverride(ctx, key, subjectRef, value)` / `clearOverride(ctx, key, subjectRef)` | mutation | Force / clear a per-subject value |
125
- | `remove(ctx, key)` | mutation | Hard-delete a flag and its overrides |
126
-
127
- `evaluate` resolves in order: override → archived → targeting rules → fallthrough rollout → flag
128
- value; an unknown key serves the caller `default` or `false`. `enable`/`disable` are boolean
129
- convenience (they set the value to `true`/`false`) — use `define`/`update` for multivariate flags.
130
- Full reference, types, operators, and the React hooks: [docs/API.md](docs/API.md).
181
+ | Method | Kind | Result |
182
+ | ---------------------------------------------------------------------------------- | -------- | ---------------------------------------------------------------------------- |
183
+ | `isEnabled(ctx, key, context?)` | query | `boolean` (value `=== true`) |
184
+ | `evaluate(ctx, key, options?)` | query | `FlagEvaluation` (`value` + `reason`) |
185
+ | `variant(ctx, key, options?)` | query | the resolved value |
186
+ | `get(ctx, key)` / `list(ctx)` | query | `FlagDoc \| null` / `FlagDoc[]` |
187
+ | `all(ctx, context?)` | query | `Record<string, FlagEvaluation>` (reactive bootstrap) |
188
+ | `define(ctx, definition)` | mutation | Create or **fully replace** a flag (value, variants, rules, rollout) |
189
+ | `update(ctx, key, patch)` | mutation | **Partially** update a flag — only supplied fields change, the rest are kept |
190
+ | `enable(ctx, key)` / `disable(ctx, key)` | mutation | Toggle a boolean flag (sets value `true`/`false`) |
191
+ | `archive(ctx, key)` / `restore(ctx, key)` | mutation | Reversibly retire / re-activate a flag |
192
+ | `setOverride(ctx, key, subjectRef, value)` / `clearOverride(ctx, key, subjectRef)` | mutation | Force / clear a per-subject value |
193
+ | `remove(ctx, key)` | mutation | Hard-delete a flag and its overrides |
194
+
195
+ `evaluate` resolves in order: override → archived → targeting rules →
196
+ fallthrough rollout → flag value; an unknown key serves the caller `default` or
197
+ `false`. `enable`/`disable` are boolean convenience (they set the value to
198
+ `true`/`false`) — use `define`/`update` for multivariate flags. Full reference,
199
+ types, operators, and the React hooks: [docs/API.md](docs/API.md).
131
200
 
132
201
  ## React
133
202
 
134
- Optional reactive hooks via the `./react` entry (`react` is an optional peer dependency). Pass the
135
- `evaluate` query you exported from `convex/flags.ts` above — `api.flags.evaluate`:
203
+ Optional reactive hooks via the `./react` entry (`react` is an optional peer
204
+ dependency). Pass the `evaluate` query you exported from `convex/flags.ts` above
205
+ — `api.flags.evaluate`:
136
206
 
137
207
  ```tsx
138
208
  import { useFlag } from "@vllnt/convex-flags/react";
139
209
  import { api } from "../convex/_generated/api";
140
210
 
141
211
  // api.flags.evaluate is the query exported in convex/flags.ts (Usage, above).
142
- const checkout = useFlag(api.flags.evaluate, "new-checkout", { context: { subjectRef: userId } });
143
- if (checkout?.value === true) { /* render the new checkout */ }
212
+ const checkout = useFlag(api.flags.evaluate, "new-checkout", {
213
+ context: { subjectRef: userId },
214
+ });
215
+ if (checkout?.value === true) {
216
+ /* render the new checkout */
217
+ }
144
218
  ```
145
219
 
146
- | Hook | Returns |
147
- |------|---------|
148
- | `useFlag(query, key, options?)` | `FlagEvaluation \| undefined` |
149
- | `useFlags(query, context?)` | `Record<string, FlagEvaluation> \| undefined` |
220
+ | Hook | Returns |
221
+ | ------------------------------- | --------------------------------------------- |
222
+ | `useFlag(query, key, options?)` | `FlagEvaluation \| undefined` |
223
+ | `useFlags(query, context?)` | `Record<string, FlagEvaluation> \| undefined` |
150
224
 
151
225
  ## Security
152
226
 
153
- - Auth-agnostic — all management mutations are internal; wrap them in your own authorized mutations and apply auth there.
154
- - Flag keys are opaque host-chosen strings; the component never interprets or validates their structure.
227
+ - Auth-agnostic — all management mutations are internal; wrap them in your own
228
+ authorized mutations and apply auth there.
229
+ - The example evaluation queries accept client-supplied context. For trusted
230
+ targeting, derive identity and attributes server-side and gate reads; a flag
231
+ is not an authorization check.
232
+ - Flag keys are opaque host-chosen strings; the component never interprets or
233
+ validates their structure.
155
234
  - Tables are sandboxed — the component never reads host or sibling tables.
156
235
 
157
236
  See [docs/API.md](docs/API.md).
@@ -163,7 +242,39 @@ pnpm test # single run
163
242
  pnpm test:coverage # enforced 100% on covered files
164
243
  ```
165
244
 
166
- Tests run against the real component runtime via `convex-test` (`@edge-runtime/vm`), not mocks.
245
+ Tests run against the real component runtime via `convex-test`
246
+ (`@edge-runtime/vm`), not mocks.
247
+
248
+ ### Testing your app
249
+
250
+ `@vllnt/convex-flags/test` exports `register(t, name = "flags")` to mount the
251
+ component in a `convex-test` instance. It needs `convex-test` and `vitest`
252
+ (with Vite's `import.meta.glob`) in the consuming app:
253
+
254
+ ```ts
255
+ /// <reference types="vite/client" />
256
+ import { convexTest } from "convex-test";
257
+ import { register } from "@vllnt/convex-flags/test";
258
+ import schema from "./schema";
259
+
260
+ const t = convexTest(schema, import.meta.glob("./**/*.ts"));
261
+ register(t);
262
+ ```
263
+
264
+ ## Related packages
265
+
266
+ - [`@vllnt/convex-experiments`](https://www.npmjs.com/package/@vllnt/convex-experiments) —
267
+ A/B experiments with sticky variant assignment stored per subject and deduped
268
+ exposure counts per variant. Use flags to gate or roll out a feature (a flag
269
+ rollout hashes the subject and stores nothing); use experiments to compare
270
+ variants and read exposure counts.
271
+ - [`@vllnt/convex-analytics`](https://www.npmjs.com/package/@vllnt/convex-analytics) —
272
+ events, funnels and retention. Flags record no events or outcomes; use
273
+ analytics to measure a flagged feature, for example by sending the evaluated
274
+ value as an event property.
275
+ - [`@vllnt/convex-events`](https://www.npmjs.com/package/@vllnt/convex-events) —
276
+ append-only per-subject event ledger. Flags keep no change history; record
277
+ changes from your management wrappers into events for an audit trail.
167
278
 
168
279
  ## Contributing
169
280
 
@@ -171,12 +282,15 @@ See [CONTRIBUTING.md](CONTRIBUTING.md).
171
282
 
172
283
  ## Author
173
284
 
174
- Built by [bntvllnt](https://github.com/bntvllnt) · [bntvllnt.com](https://bntvllnt.com) · [X @bntvllnt](https://x.com/bntvllnt)
175
-
176
- Part of the [@vllnt](https://github.com/vllnt) Convex component fleet — [vllnt.com](https://vllnt.com)
285
+ Built by [bntvllnt](https://github.com/bntvllnt) ·
286
+ [bntvllnt.com](https://bntvllnt.com) · [X @bntvllnt](https://x.com/bntvllnt)
177
287
 
178
288
  If this is useful, [sponsor the work](https://github.com/sponsors/bntvllnt).
179
289
 
180
290
  ## License
181
291
 
182
292
  MIT
293
+
294
+ ---
295
+
296
+ Part of vllnt oss: https://oss.vllnt.com
@@ -1 +1 @@
1
- {"version":3,"file":"mutations.d.ts","sourceRoot":"","sources":["../../src/component/mutations.ts"],"names":[],"mappings":"AAmBA;;;GAGG;AACH,eAAO,MAAM,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;uDAoCjB,CAAC;AAEH;;;;GAIG;AACH,eAAO,MAAM,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAkCjB,CAAC;AAUH,wDAAwD;AACxD,eAAO,MAAM,MAAM;;iBAOjB,CAAC;AAEH,0DAA0D;AAC1D,eAAO,MAAM,OAAO;;iBAOlB,CAAC;AAcH;mDACmD;AACnD,eAAO,MAAM,OAAO;;iBAOlB,CAAC;AAEH,0CAA0C;AAC1C,eAAO,MAAM,OAAO;;iBAOlB,CAAC;AAEH,uEAAuE;AACvE,eAAO,MAAM,MAAM;;iBAkBjB,CAAC;AAEH,iEAAiE;AACjE,eAAO,MAAM,WAAW;;;;iBA0BtB,CAAC;AAEH,mEAAmE;AACnE,eAAO,MAAM,aAAa;;;iBAexB,CAAC"}
1
+ {"version":3,"file":"mutations.d.ts","sourceRoot":"","sources":["../../src/component/mutations.ts"],"names":[],"mappings":"AA4FA;;;GAGG;AACH,eAAO,MAAM,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;uDAyCjB,CAAC;AAEH;;;;GAIG;AACH,eAAO,MAAM,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA0BjB,CAAC;AAWH,wDAAwD;AACxD,eAAO,MAAM,MAAM;;iBAOjB,CAAC;AAEH,0DAA0D;AAC1D,eAAO,MAAM,OAAO;;iBAOlB,CAAC;AAiBH;mDACmD;AACnD,eAAO,MAAM,OAAO;;iBAOlB,CAAC;AAEH,0CAA0C;AAC1C,eAAO,MAAM,OAAO;;iBAOlB,CAAC;AAEH,uEAAuE;AACvE,eAAO,MAAM,MAAM;;iBAmBjB,CAAC;AAEH,iEAAiE;AACjE,eAAO,MAAM,WAAW;;;;iBA6BtB,CAAC;AAEH,mEAAmE;AACnE,eAAO,MAAM,aAAa;;;iBAgBxB,CAAC"}
@@ -1,4 +1,4 @@
1
- import { v } from "convex/values";
1
+ import { ConvexError, v } from "convex/values";
2
2
  import { mutation } from "./_generated/server.js";
3
3
  import { rollout, rule, variant, variantValue } from "./validators.js";
4
4
  async function findByKey(ctx, key) {
@@ -7,6 +7,58 @@ async function findByKey(ctx, key) {
7
7
  .withIndex("by_key", (q) => q.eq("key", key))
8
8
  .unique();
9
9
  }
10
+ function invalidArgument(message) {
11
+ throw new ConvexError({ code: "INVALID_ARGUMENT", message });
12
+ }
13
+ /** Reject empty identifiers: an empty key or subject ref can never be targeted
14
+ * meaningfully and would store an unreachable row. */
15
+ function assertNonEmpty(fields) {
16
+ for (const [name, value] of Object.entries(fields)) {
17
+ if (value === "") {
18
+ invalidArgument(`${name} must be non-empty`);
19
+ }
20
+ }
21
+ }
22
+ /** Reject rollout weights that cannot bucket: NaN, infinite, or negative. Zero
23
+ * is allowed (it excludes a split). */
24
+ function assertRollouts(rollouts, rules) {
25
+ const all = [...rollouts, ...(rules ?? []).map((r) => r.rollout)];
26
+ for (const r of all) {
27
+ for (const { weight } of r?.splits ?? []) {
28
+ if (!Number.isFinite(weight) || weight < 0) {
29
+ invalidArgument("rollout weights must be finite and non-negative");
30
+ }
31
+ }
32
+ }
33
+ }
34
+ function sameValue(a, b) {
35
+ if (Array.isArray(a) && Array.isArray(b)) {
36
+ return a.length === b.length && a.every((item, i) => sameValue(item, b[i]));
37
+ }
38
+ if (isRecord(a) && isRecord(b)) {
39
+ const keys = new Set([...Object.keys(a), ...Object.keys(b)]);
40
+ return [...keys].every((k) => sameValue(a[k], b[k]));
41
+ }
42
+ return Object.is(a, b);
43
+ }
44
+ function isRecord(value) {
45
+ return typeof value === "object" && value !== null && !Array.isArray(value);
46
+ }
47
+ const FLAG_FIELDS = ["value", "description", "variants", "rules", "rollout"];
48
+ function changedFields(flag, fields) {
49
+ const patch = {};
50
+ for (const name of FLAG_FIELDS) {
51
+ if (name in fields && !sameValue(flag[name], fields[name])) {
52
+ Object.assign(patch, { [name]: fields[name] });
53
+ }
54
+ }
55
+ return patch;
56
+ }
57
+ async function patchIfChanged(ctx, flag, patch) {
58
+ if (Object.keys(patch).length > 0) {
59
+ await ctx.db.patch("flags", flag._id, { ...patch, updatedAt: Date.now() });
60
+ }
61
+ }
10
62
  /** Throws the component's single code-tagged error. Returns `never` so callers
11
63
  * narrow the flag to non-null after the guard. */
12
64
  function flagNotFound() {
@@ -27,17 +79,18 @@ export const define = mutation({
27
79
  },
28
80
  returns: v.id("flags"),
29
81
  handler: async (ctx, args) => {
82
+ assertNonEmpty({ key: args.key });
83
+ assertRollouts([args.rollout], args.rules);
30
84
  const now = Date.now();
31
85
  const existing = await findByKey(ctx, args.key);
32
86
  if (existing !== null) {
33
- await ctx.db.patch("flags", existing._id, {
87
+ await patchIfChanged(ctx, existing, changedFields(existing, {
34
88
  value: args.value,
35
89
  description: args.description,
36
90
  variants: args.variants,
37
91
  rules: args.rules,
38
92
  rollout: args.rollout,
39
- updatedAt: now,
40
- });
93
+ }));
41
94
  return existing._id;
42
95
  }
43
96
  return await ctx.db.insert("flags", {
@@ -69,36 +122,29 @@ export const update = mutation({
69
122
  },
70
123
  returns: v.null(),
71
124
  handler: async (ctx, args) => {
125
+ assertNonEmpty({ key: args.key });
126
+ assertRollouts([args.rollout], args.rules);
72
127
  const flag = await findByKey(ctx, args.key);
73
128
  if (flag === null) {
74
129
  flagNotFound();
75
130
  }
76
- const patch = { updatedAt: Date.now() };
77
- if (args.value !== undefined) {
78
- patch.value = args.value;
131
+ const fields = {};
132
+ for (const name of FLAG_FIELDS) {
133
+ if (args[name] !== undefined) {
134
+ Object.assign(fields, { [name]: args[name] });
135
+ }
79
136
  }
80
- if (args.description !== undefined) {
81
- patch.description = args.description;
82
- }
83
- if (args.variants !== undefined) {
84
- patch.variants = args.variants;
85
- }
86
- if (args.rules !== undefined) {
87
- patch.rules = args.rules;
88
- }
89
- if (args.rollout !== undefined) {
90
- patch.rollout = args.rollout;
91
- }
92
- await ctx.db.patch("flags", flag._id, patch);
137
+ await patchIfChanged(ctx, flag, changedFields(flag, fields));
93
138
  return null;
94
139
  },
95
140
  });
96
141
  async function setValue(ctx, key, value) {
142
+ assertNonEmpty({ key });
97
143
  const flag = await findByKey(ctx, key);
98
144
  if (flag === null) {
99
145
  flagNotFound();
100
146
  }
101
- await ctx.db.patch("flags", flag._id, { value, updatedAt: Date.now() });
147
+ await patchIfChanged(ctx, flag, changedFields(flag, { value }));
102
148
  }
103
149
  /** Turn a boolean flag on (set its value to `true`). */
104
150
  export const enable = mutation({
@@ -119,11 +165,14 @@ export const disable = mutation({
119
165
  },
120
166
  });
121
167
  async function setStatus(ctx, key, status) {
168
+ assertNonEmpty({ key });
122
169
  const flag = await findByKey(ctx, key);
123
170
  if (flag === null) {
124
171
  flagNotFound();
125
172
  }
126
- await ctx.db.patch("flags", flag._id, { status, updatedAt: Date.now() });
173
+ if (flag.status !== status) {
174
+ await ctx.db.patch("flags", flag._id, { status, updatedAt: Date.now() });
175
+ }
127
176
  }
128
177
  /** Archive a flag: reversible retirement. Evaluation skips targeting and serves
129
178
  * the flag's base value with reason `disabled`. */
@@ -149,6 +198,7 @@ export const remove = mutation({
149
198
  args: { key: v.string() },
150
199
  returns: v.null(),
151
200
  handler: async (ctx, args) => {
201
+ assertNonEmpty({ key: args.key });
152
202
  const flag = await findByKey(ctx, args.key);
153
203
  if (flag === null) {
154
204
  flagNotFound();
@@ -169,6 +219,7 @@ export const setOverride = mutation({
169
219
  args: { key: v.string(), subjectRef: v.string(), value: variantValue },
170
220
  returns: v.null(),
171
221
  handler: async (ctx, args) => {
222
+ assertNonEmpty({ key: args.key, subjectRef: args.subjectRef });
172
223
  const flag = await findByKey(ctx, args.key);
173
224
  if (flag === null) {
174
225
  flagNotFound();
@@ -178,7 +229,9 @@ export const setOverride = mutation({
178
229
  .withIndex("by_key_subject", (q) => q.eq("key", args.key).eq("subjectRef", args.subjectRef))
179
230
  .unique();
180
231
  if (existing !== null) {
181
- await ctx.db.patch("overrides", existing._id, { value: args.value });
232
+ if (!Object.is(existing.value, args.value)) {
233
+ await ctx.db.patch("overrides", existing._id, { value: args.value });
234
+ }
182
235
  }
183
236
  else {
184
237
  await ctx.db.insert("overrides", {
@@ -196,6 +249,7 @@ export const clearOverride = mutation({
196
249
  args: { key: v.string(), subjectRef: v.string() },
197
250
  returns: v.null(),
198
251
  handler: async (ctx, args) => {
252
+ assertNonEmpty({ key: args.key, subjectRef: args.subjectRef });
199
253
  const existing = await ctx.db
200
254
  .query("overrides")
201
255
  .withIndex("by_key_subject", (q) => q.eq("key", args.key).eq("subjectRef", args.subjectRef))