@vllnt/convex-quota 0.1.0 → 0.1.1-canary.0ef820d

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 CHANGED
@@ -4,7 +4,37 @@ All notable changes to this project are documented here. The format is based on
4
4
  [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project
5
5
  adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
- ## [Unreleased]
7
+ ## [0.1.1] - 2026-11-29
8
+
9
+ ### Added
10
+
11
+ - The npm package's `llms.txt` and README tell coding agents that the docs are
12
+ bundled at `node_modules/@vllnt/convex-quota/docs/` (with `README.md`,
13
+ `CHANGELOG.md` and `llms.txt` in the package root) and match the installed
14
+ version. `llms.txt` links shipped files with relative paths and adds an
15
+ Ecosystem link; the README adds Related packages. `docs/API.md` lists the
16
+ package entry points and exported types.
17
+ - The README is rewritten for coding agents: install and a quick start first, an
18
+ API table linked to `docs/API.md`, common tasks, an errors-and-fixes table for
19
+ every `ConvexError` code, limits and gotchas, and compatibility. `docs/API.md`
20
+ documents every public export with its signature, defaults, result shape and
21
+ error codes; `llms.txt` carries the same summary and ends with an Ecosystem
22
+ block. The README shows a listing image.
23
+ - Every public export and `Quota` method has a TSDoc summary.
24
+
25
+ ### Changed
26
+
27
+ - `homepage` points to https://oss.vllnt.com/packages/convex-quota.
28
+ - The `package.json` description and keywords name the problem and the stack
29
+ (Convex, TypeScript, quota, allowance, reset windows).
30
+ - A `canary` build is published to npm on every push to `main`.
31
+ - `refund` skips the write when the allowance's `used` would not change (already
32
+ zero), so a no-op refund no longer re-runs `remaining` subscribers.
33
+ - Internal: dev dependencies upgraded; CI sets up pnpm through Corepack with
34
+ pinned actions and no update bot; `pnpm lint` checks the docs; `pnpm check:pack`
35
+ checks required tarball files, `llms.txt` links and every TypeScript doc
36
+ example against the packed package; tests cover every public function's
37
+ documented behaviour and failure path.
8
38
 
9
39
  ## [0.1.0] - 2026-11-23
10
40
 
package/README.md CHANGED
@@ -1,63 +1,32 @@
1
- <!-- Badges -->
2
-
3
- [![convex-component](https://img.shields.io/badge/convex-component-EE342F.svg)](https://www.convex.dev/components)
4
- [![npm](https://img.shields.io/npm/v/@vllnt/convex-quota.svg)](https://www.npmjs.com/package/@vllnt/convex-quota)
5
- [![CI](https://github.com/vllnt/convex-quota/actions/workflows/ci.yml/badge.svg)](https://github.com/vllnt/convex-quota/actions/workflows/ci.yml)
6
- [![license](https://img.shields.io/npm/l/@vllnt/convex-quota.svg)](./LICENSE)
7
-
8
1
  # @vllnt/convex-quota
9
2
 
10
- Scheduled-reset per-subject allowances as a Convex component.
3
+ TypeScript Convex component for quotas and allowances: daily, weekly, monthly, rolling or epoch reset windows per user or key, with a readable remaining count.
11
4
 
12
- Readable remaining in a window — calendar day/week/month, rolling, or epoch.
13
- Daily/weekly play caps, free-tier slots, Codex-style limits.
5
+ ## For coding agents
14
6
 
15
- ## When to use it
7
+ Docs for the installed version ship in the package: `README.md`, `CHANGELOG.md`, `llms.txt`, `docs/API.md` and typed `src/` under `node_modules/@vllnt/convex-quota/`. Read them before writing code.
16
8
 
17
- Use it for allowances that reset on a schedule and that your UI needs to read:
18
- "3 plays left today", a weekly cap in the subject's own timezone, free-tier
19
- slots, a refund when an action is cancelled.
9
+ ## When to use
20
10
 
21
- - General throttling (token buckets, fixed windows, React hooks): use the
22
- official `@convex-dev/rate-limiter`.
23
- - Billable usage records: use `@vllnt/convex-metering`.
24
- - Balances that persist and are spent down: use `@vllnt/convex-wallet`.
11
+ Use it when:
25
12
 
26
- ```ts
27
- const quota = new Quota(components.quota);
28
- const r = await quota.consume(ctx, subjectRef, "plays", 3, {
29
- kind: "calendar",
30
- period: "day",
31
- timeZone: "Europe/Paris",
32
- });
33
- if (!r.allowed) throw new Error(`try again at ${r.resetsAt}`);
34
- ```
13
+ - A user, API key or tenant gets a number of actions per calendar day, week or month in a given IANA timezone, and the UI shows how many are left and when they reset.
14
+ - An allowance resets on a rolling duration that starts at first use, or on fixed epoch-aligned buckets such as every hour.
15
+ - A cancelled action should give its units back within the same window.
35
16
 
36
- ## Features
17
+ Do not use it when:
37
18
 
38
- - **Readable remaining** — `consume` and `remaining` both return
39
- `{ used, remaining, limit, periodKey, resetsAt }`; only `consume` includes
40
- `allowed`.
41
- - **Window kinds** — calendar (`day` / `week` / `month` + IANA timezone),
42
- rolling (from first consume), epoch (`floor(now / durationMs)`).
43
- - **Server-sourced time** — window math uses `Date.now()` inside the component.
44
- - **Opaque refs** — `subjectRef`, `key`, and `scope` are host strings (1..256
45
- UTF-16 code units).
46
- - **Bounded erase** — `eraseSubject` deletes in batches and reschedules until
47
- clean.
48
- - **Scopes** — default `"global"`, or namespace per tenant / product.
19
+ - You need throttling or rate limiting of bursts: use `@convex-dev/rate-limiter`.
20
+ - The count never resets: a balance that is spent and topped up (`@vllnt/convex-wallet`), or an API key's lifetime use limit (`@vllnt/convex-api-keys`).
21
+ - You need billable usage records rolled up per billing period: use `@vllnt/convex-metering`.
49
22
 
50
- ## Installation
23
+ ## Install
51
24
 
52
25
  ```bash
53
26
  pnpm add @vllnt/convex-quota
54
27
  ```
55
28
 
56
- Node.js >=22.12.0; required peer: `convex@^1.45.0`. Stable releases are
57
- published to the `latest` dist-tag with npm provenance. Unreleased builds from
58
- `main` go to the `canary` dist-tag (`pnpm add @vllnt/convex-quota@canary`).
59
-
60
- ## Usage
29
+ ## Quick start
61
30
 
62
31
  ```ts
63
32
  // convex/convex.config.ts
@@ -69,15 +38,12 @@ app.use(quota);
69
38
  export default app;
70
39
  ```
71
40
 
72
- The host authenticates, derives the `subjectRef`, and owns the limit and window.
73
- The component never sees the end-user's request.
74
-
75
41
  ```ts
76
42
  // convex/plays.ts
77
43
  import { v } from "convex/values";
44
+ import { Quota } from "@vllnt/convex-quota";
78
45
  import { components } from "./_generated/api";
79
46
  import { mutation, query } from "./_generated/server";
80
- import { Quota } from "@vllnt/convex-quota";
81
47
 
82
48
  const quota = new Quota(components.quota);
83
49
  const DAILY_PLAYS = 5; // host-owned, never from the client
@@ -93,9 +59,14 @@ export const play = mutation({
93
59
  handler: async (ctx) => {
94
60
  const identity = await ctx.auth.getUserIdentity();
95
61
  if (!identity) throw new Error("Unauthenticated");
96
- const subjectRef = identity.tokenIdentifier;
97
- const r = await quota.consume(ctx, subjectRef, "plays", DAILY_PLAYS, daily);
98
- if (!r.allowed) throw new Error("daily cap reached");
62
+ const r = await quota.consume(
63
+ ctx,
64
+ identity.tokenIdentifier,
65
+ "plays",
66
+ DAILY_PLAYS,
67
+ daily,
68
+ );
69
+ if (!r.allowed) throw new Error(`Daily cap reached until ${r.resetsAt}`);
99
70
  return null;
100
71
  },
101
72
  });
@@ -118,70 +89,131 @@ export const playsLeft = query({
118
89
  });
119
90
  ```
120
91
 
121
- After mounting, run `pnpm convex dev` to generate the host's component
122
- references.
123
-
124
- **Host rules:**
125
-
126
- - Never take `limit` or `amount` from the end-user. The host supplies them.
127
- - `consume` is not idempotent. Pair it with `@vllnt/convex-idempotency` (see
128
- [Retries and idempotency](#retries-and-idempotency)).
129
- - `refund` is privileged and **not idempotent**. Deduplicate refund events in
130
- the host transaction; `periodKey` is a window label, not a receipt or replay
131
- token.
132
- - Keep window policy fixed for each `(scope, subjectRef, key)`; changes throw
133
- `POLICY_MISMATCH`. Use a new key for a new policy. Limits may change without
134
- resetting usage.
135
- - Stop new consumes before erasing a subject and keep them stopped until
136
- scheduled passes drain. Erasure is not a tombstone; concurrent writes can
137
- survive or be swept.
138
- - The example wrappers are unauthenticated test fixtures, not production
139
- endpoints.
140
-
141
- ## Configuration and limits
142
-
143
- `new Quota(component, { defaultScope: "global" })` sets the only client option.
144
- `consume` accepts `{ amount?: number, scope?: string }`; amount defaults to 1.
145
- Limits and amounts must be positive safe integers. Erase batches default to 200
146
- and are capped at 500. Calendar weeks default to Monday; set `weekStartsOn` to
147
- `"sunday"` when needed. Rolling and epoch windows require a positive safe
148
- integer `durationMs`. See the API reference for timezone transitions and error
149
- codes.
150
-
151
- ## API Reference
152
-
153
- | Method | Kind | Result |
154
- | --------------------------------------------------------- | -------- | ---------------------------------------------------------- |
155
- | `consume(ctx, subjectRef, key, limit, window, opts?)` | mutation | `{ allowed, remaining, used, limit, periodKey, resetsAt }` |
156
- | `remaining(ctx, subjectRef, key, limit, window, scope?)` | query | same fields without `allowed` |
157
- | `refund(ctx, subjectRef, key, amount, periodKey, scope?)` | mutation | `{ refunded, used, remaining }` |
158
- | `eraseSubject(ctx, subjectRef, scope?, batch?)` | mutation | `number` deleted this pass |
159
-
160
- Full reference: [docs/API.md](docs/API.md).
161
-
162
- ## Retries and idempotency
163
-
164
- `consume` is not idempotent: a retried mutation consumes again. When a retry
165
- must not double-count, claim the request with `@vllnt/convex-idempotency` inside
166
- the **same host mutation**. The claim, the consume and the completion commit or
167
- roll back together, so a failed attempt leaves nothing behind and a successful
168
- one is replayed instead of re-run.
169
-
170
- Install it next to this component:
92
+ ![Quotas — @vllnt/convex-quota](https://raw.githubusercontent.com/vllnt/convex-quota/main/.github/assets/thumbnail.png)
171
93
 
172
- ```bash
173
- pnpm add @vllnt/convex-idempotency
94
+ Run `npx convex dev` after mounting so `components.quota` is generated. The host
95
+ authenticates, derives the `subjectRef` (here the caller's `tokenIdentifier`)
96
+ and owns the limit and the window; the component never sees the end user's
97
+ request.
98
+
99
+ [![Convex component](https://img.shields.io/badge/convex-component-EE342F.svg)](https://www.convex.dev/components)
100
+ [![npm version](https://img.shields.io/npm/v/@vllnt/convex-quota.svg)](https://www.npmjs.com/package/@vllnt/convex-quota)
101
+ [![CI status](https://github.com/vllnt/convex-quota/actions/workflows/ci.yml/badge.svg)](https://github.com/vllnt/convex-quota/actions/workflows/ci.yml)
102
+ [![MIT license](https://img.shields.io/npm/l/@vllnt/convex-quota.svg)](./LICENSE)
103
+
104
+ ## API
105
+
106
+ Full reference: [docs/API.md](./docs/API.md).
107
+
108
+ | Export | Kind | What it does |
109
+ | ----------------------------------------------------- | ------------------------------ | -------------------------------------------------------------------------------------------------- |
110
+ | [`Quota`](./docs/API.md#quota) | class (`@vllnt/convex-quota`) | Client: `new Quota(components.quota, options?)` |
111
+ | [`consume`](./docs/API.md#consume) | method, `runMutation` ctx | Use `amount` units if they fit; returns `{ allowed, used, remaining, limit, periodKey, resetsAt }` |
112
+ | [`remaining`](./docs/API.md#remaining) | method, `runQuery` ctx | Read the current window without writing; returns `{ used, remaining, limit, periodKey, resetsAt }` |
113
+ | [`refund`](./docs/API.md#refund) | method, `runMutation` ctx | Give units back to the stored, unexpired window; returns `{ refunded, used, remaining }` |
114
+ | [`eraseSubject`](./docs/API.md#erasesubject) | method, `runMutation` ctx | Delete a subject's rows in one scope in batches; returns the count deleted in the first pass |
115
+ | [`QuotaOptions`](./docs/API.md#quotaoptions) | type | Constructor options: `{ defaultScope?: string }` |
116
+ | [`ConsumeOptions`](./docs/API.md#consumeoptions) | type | `consume` options: `{ amount?: number; scope?: string }` |
117
+ | [`WindowSpec`](./docs/API.md#windowspec) | type | Window policy: `calendar` (`day` / `week` / `month` in a timezone), `rolling` or `epoch` |
118
+ | [`ConsumeResult`](./docs/API.md#consumeresult) | type | Return type of `consume` |
119
+ | [`RemainingState`](./docs/API.md#remainingstate) | type | Return type of `remaining` |
120
+ | [`RefundResult`](./docs/API.md#refundresult) | type | Return type of `refund` |
121
+ | [`QuotaComponent`](./docs/API.md#quotacomponent) | type | The function references the client needs (`components.quota`) |
122
+ | [`convex.config` default](./docs/API.md#convexconfig) | component (`/convex.config`) | The component definition for `app.use(...)`, mounted as `quota` by default |
123
+ | [`register`](./docs/API.md#register) | function (`/test`) | `register(t, name = "quota")` mounts the component in a `convex-test` instance |
124
+ | [`ComponentApi`](./docs/API.md#componentapi) | type (`/_generated/component`) | Generated type of the mounted component's functions |
125
+
126
+ ## Common tasks
127
+
128
+ **Pick a window.** A `WindowSpec` is fixed per `(scope, subjectRef, key)`:
129
+
130
+ ```ts
131
+ // convex/windows.ts
132
+ import type { WindowSpec } from "@vllnt/convex-quota";
133
+
134
+ // Resets at local midnight in Paris.
135
+ export const daily: WindowSpec = {
136
+ kind: "calendar",
137
+ period: "day",
138
+ timeZone: "Europe/Paris",
139
+ };
140
+ // Resets on Sunday at local midnight (the default week start is Monday).
141
+ export const weekly: WindowSpec = {
142
+ kind: "calendar",
143
+ period: "week",
144
+ timeZone: "America/New_York",
145
+ weekStartsOn: "sunday",
146
+ };
147
+ // Resets on the 1st of each month at UTC midnight.
148
+ export const monthly: WindowSpec = {
149
+ kind: "calendar",
150
+ period: "month",
151
+ timeZone: "UTC",
152
+ };
153
+ // 24 hours from the first allowed consume.
154
+ export const rolling: WindowSpec = { kind: "rolling", durationMs: 86_400_000 };
155
+ // Fixed hourly buckets aligned to the Unix epoch.
156
+ export const hourly: WindowSpec = { kind: "epoch", durationMs: 3_600_000 };
157
+ ```
158
+
159
+ **Consume several units or use a tenant scope.** Pass `{ amount, scope }` as
160
+ the last argument of `consume`, or set `defaultScope` once with
161
+ `new Quota(components.quota, { defaultScope: "tenant-a" })`. `remaining`,
162
+ `refund` and `eraseSubject` take `scope` as their last optional argument.
163
+
164
+ ```ts
165
+ // convex/exports.ts
166
+ import { v } from "convex/values";
167
+ import { Quota } from "@vllnt/convex-quota";
168
+ import { components } from "./_generated/api";
169
+ import { mutation } from "./_generated/server";
170
+
171
+ const quota = new Quota(components.quota);
172
+ const MONTHLY_CREDITS = 100;
173
+ const EXPORT_COST = 10; // host-owned, never from the client
174
+ const monthly = { kind: "calendar", period: "month", timeZone: "UTC" } as const;
175
+
176
+ export const startExport = mutation({
177
+ args: {},
178
+ returns: v.object({ allowed: v.boolean(), remaining: v.number() }),
179
+ handler: async (ctx) => {
180
+ const identity = await ctx.auth.getUserIdentity();
181
+ if (!identity) throw new Error("Unauthenticated");
182
+ const { allowed, remaining } = await quota.consume(
183
+ ctx,
184
+ identity.tokenIdentifier,
185
+ "credits",
186
+ MONTHLY_CREDITS,
187
+ monthly,
188
+ { amount: EXPORT_COST, scope: "exports" },
189
+ );
190
+ return { allowed, remaining };
191
+ },
192
+ });
174
193
  ```
175
194
 
195
+ An `amount` larger than what is left is denied in full; nothing is consumed
196
+ partially.
197
+
198
+ **Make `consume` and `refund` retry-safe.** `consume` and `refund` are not
199
+ idempotent: a retried mutation consumes again. Claim the request with
200
+ `@vllnt/convex-idempotency` inside the same host mutation; the claim, the
201
+ consume and the completion commit or roll back together. Mount both components:
202
+
176
203
  ```ts
177
- // convex/convex.config.ts — mount both components
204
+ // convex/convex.config.ts
205
+ import { defineApp } from "convex/server";
178
206
  import idempotency from "@vllnt/convex-idempotency/convex.config";
207
+ import quota from "@vllnt/convex-quota/convex.config";
208
+
209
+ const app = defineApp();
179
210
  app.use(quota);
180
211
  app.use(idempotency);
212
+ export default app;
181
213
  ```
182
214
 
183
215
  ```ts
184
- // convex/plays.ts
216
+ // convex/safe_plays.ts
185
217
  import { v } from "convex/values";
186
218
  import { Idempotency } from "@vllnt/convex-idempotency";
187
219
  import {
@@ -196,6 +228,7 @@ const quota = new Quota(components.quota);
196
228
  const consumeIdempotency = new Idempotency<ConsumeResult>(
197
229
  components.idempotency,
198
230
  );
231
+ const refundIdempotency = new Idempotency<RefundResult>(components.idempotency);
199
232
  const DAILY_PLAYS = 5;
200
233
  const daily = {
201
234
  kind: "calendar",
@@ -239,21 +272,15 @@ export const play = mutation({
239
272
  return result;
240
273
  },
241
274
  });
242
- ```
243
-
244
- Refunds are privileged; trigger them only from verified host events. Expose them
245
- as an `internalMutation` that a trusted caller (a webhook or a scheduled job
246
- after a verified cancellation) invokes with values from the host's own record of
247
- the play, never with a public argument chosen by the end user:
248
-
249
- ```ts
250
- const refundIdempotency = new Idempotency<RefundResult>(components.idempotency);
251
275
 
276
+ // Privileged: only trusted host code (a webhook handler or a scheduled job
277
+ // after a verified cancellation) calls this, with values from the host's own
278
+ // record of the play, never from an end-user argument.
252
279
  export const refundPlay = internalMutation({
253
280
  args: {
254
- subjectRef: v.string(), // from the host's record of the play
255
- requestId: v.string(), // the request being cancelled
256
- periodKey: v.string(), // from the same record
281
+ subjectRef: v.string(),
282
+ requestId: v.string(),
283
+ periodKey: v.string(),
257
284
  },
258
285
  returns: v.object({
259
286
  refunded: v.boolean(),
@@ -279,103 +306,212 @@ export const refundPlay = internalMutation({
279
306
  });
280
307
  ```
281
308
 
282
- This exact pattern is exercised in
283
- [`example/convex/idempotency.test.ts`](example/convex/idempotency.test.ts): a
284
- duplicate `requestId` replays the stored result and consumes once, a new
285
- `requestId` consumes again, the caller `scope` isolates identical request ids, a
286
- host failure after `consume` rolls back both the allowance and the claim, and a
287
- refund event deduplicated by `requestId` refunds once.
288
-
289
- Caveats:
309
+ The same `play` and `refundPlay` are tested in
310
+ [`example/convex/idempotency.test.ts`](https://github.com/vllnt/convex-quota/blob/main/example/convex/idempotency.test.ts):
311
+ a duplicate `requestId` replays the stored result and consumes once, a new
312
+ `requestId` consumes again, the caller `scope` isolates identical request IDs,
313
+ a host failure after `consume` rolls back both the allowance and the claim, and
314
+ a refund deduplicated by `requestId` refunds once. Caveats:
290
315
 
291
316
  - A denied consume (`allowed: false`) is recorded too, so a replay returns the
292
- same denial even if the allowance was freed in between.
293
- - The claim lives for the idempotency component's done-grace TTL (24 hours by
294
- default). A retry after that is a new request and consumes again, so pick a
295
- TTL longer than your clients' retry horizon.
296
- - Do no external work between `begin` and `complete`. Keep it to transactional
297
- host writes; use a separate action for network calls.
317
+ same denial even if units were freed in between.
318
+ - The claim lives for the idempotency component's done grace (24 hours by
319
+ default). A retry after that is a new request and consumes again.
320
+ - Do no external work between `begin` and `complete`; use a separate action
321
+ for network calls.
298
322
  - Namespace the idempotency key per operation (`consume:${requestId}`,
299
- `refund:${requestId}`). The ledger is keyed by caller scope and key only, so
300
- two operations sharing a key would replay each other's stored result.
301
- - Never accept refund ids or a `periodKey` from the end user: a public refund
323
+ `refund:${requestId}`). The ledger is keyed by scope and key only, so two
324
+ operations sharing a key would replay each other's stored result.
325
+ - Never accept refund IDs or a `periodKey` from the end user: a public refund
302
326
  endpoint lets a caller fabricate cancellations and clear their own quota.
303
327
 
304
- ## Multiple mounts
328
+ **Mount the component more than once.** Each named mount has its own tables:
305
329
 
306
330
  ```ts
331
+ // convex/convex.config.ts
332
+ import { defineApp } from "convex/server";
333
+ import quota from "@vllnt/convex-quota/convex.config";
334
+
335
+ const app = defineApp();
307
336
  app.use(quota, { name: "webQuota" });
308
337
  app.use(quota, { name: "mobileQuota" });
309
- // new Quota(components.webQuota), new Quota(components.mobileQuota)
338
+ export default app;
310
339
  ```
311
340
 
312
- Each mount has independent sandboxed tables. Use `scope` for runtime namespaces.
313
-
314
- ## Operational behavior
315
-
316
- `remaining` is a snapshot when its query executes: **time passing alone does not
317
- invalidate a Convex subscription**. Treat `resetsAt` as an expiry hint, not a
318
- scheduled notification; `consume` always rechecks server time. Rolling windows
319
- start on the first **allowed** consume. No history or audit events are retained.
320
- Hosts should record denied decisions and privileged refunds in their own audit
321
- system without logging sensitive refs. A hot allowance is one contended row;
322
- different indexed keys remain independent. Monitor Convex OCC retries and
323
- scheduled-function failures. Erasure returns only its first pass count.
324
-
325
- ## React
326
-
327
- Backend-only — no `./react` entry. Remaining is typically shown through the
328
- host's own query.
329
-
330
- ## Security
341
+ ```ts
342
+ // convex/mounts.ts
343
+ import { Quota } from "@vllnt/convex-quota";
344
+ import { components } from "./_generated/api";
331
345
 
332
- - Auth-agnostic — the host resolves identity and passes an opaque `subjectRef`.
333
- - Tables sandboxed — reached only through the exported functions.
334
- - Server-sourced windows — a skewed client clock cannot pick the period.
346
+ export const webQuota = new Quota(components.webQuota);
347
+ export const mobileQuota = new Quota(components.mobileQuota);
348
+ ```
335
349
 
336
- See [docs/API.md](docs/API.md).
350
+ Use `scope` instead when you need namespaces at runtime inside one mount.
351
+
352
+ **Erase a subject.** `quota.eraseSubject(ctx, subjectRef, scope?, batch?)`
353
+ deletes that subject's rows in one scope and schedules further passes until a
354
+ pass deletes fewer than `batch` rows. Stop new consumes for the subject first.
355
+
356
+ **Show the remaining count in a UI.** Read it through your own query, as
357
+ `playsLeft` does in the [Quick start](#quick-start). There is no React entry
358
+ point. A subscription does not refresh when the window resets on its own; use
359
+ `resetsAt` to know when to read again.
360
+
361
+ **Test your app.** Mount the component in `convex-test`; see
362
+ [Testing your app](#testing-your-app).
363
+
364
+ ## Errors and fixes
365
+
366
+ Invalid input throws a `ConvexError` whose `data` is `{ code, message }`:
367
+
368
+ | Error (`data.code`) | Message | Cause | Fix |
369
+ | ------------------- | ------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
370
+ | `INVALID_REF` | `subjectRef must be 1..256 UTF-16 code units` (or `key`, `scope`, `periodKey`) | An empty string or more than 256 UTF-16 code units in `subjectRef`, `key`, `scope` or the refund `periodKey` | Pass a non-empty value of at most 256 code units; hash longer identifiers |
371
+ | `INVALID_LIMIT` | `limit must be a positive safe integer` | `consume` or `remaining` got a `limit` that is 0, negative, fractional, `NaN`, infinite or above `Number.MAX_SAFE_INTEGER` | Pass a positive integer limit from host config |
372
+ | `INVALID_AMOUNT` | `amount must be a positive safe integer` | `consume` or `refund` got an `amount` that is 0, negative, fractional or not a safe integer | Pass a positive integer, or omit it on `consume` (default 1) |
373
+ | `INVALID_DURATION` | `durationMs must be a positive safe integer` | A `rolling` or `epoch` window has a `durationMs` that is 0, negative, fractional or not a safe integer | Pass whole milliseconds, for example `86_400_000` for one day |
374
+ | `INVALID_DURATION` | `window end must be a positive safe integer` | The server time plus `durationMs` is above `Number.MAX_SAFE_INTEGER` | Use a shorter `durationMs` |
375
+ | `INVALID_TIME_ZONE` | the `timeZone` value, for example `Not/AZone` | A `calendar` window's `timeZone` is not accepted by `Intl.DateTimeFormat` | Pass an IANA name such as `Europe/Paris` or `UTC` |
376
+ | `INVALID_BATCH` | `batch must be a positive integer` | `eraseSubject` got a `batch` that is 0, negative, fractional, `NaN` or infinite | Pass a positive integer or omit it (default 200); values above 500 are capped to 500 |
377
+ | `POLICY_MISMATCH` | `Use a new key to change window policy` | `consume` or `remaining` got a different window policy than the stored row for this `(scope, subjectRef, key)` | Keep the window fixed per key, or use a new `key` for the new policy |
378
+
379
+ ## Limits and gotchas
380
+
381
+ - Defaults: `scope` `"global"`, `amount` 1, `weekStartsOn` `"monday"`,
382
+ `eraseSubject` batch 200. A batch above 500 is capped to 500, not rejected.
383
+ - Refs (`subjectRef`, `key`, `scope`, refund `periodKey`) are 1 to 256 UTF-16
384
+ code units. Limits and amounts are positive safe integers. Durations are
385
+ positive safe integer milliseconds.
386
+ - `consume` and `refund` are not idempotent. A retried mutation consumes or
387
+ refunds again; see [Common tasks](#common-tasks) for the idempotency pattern.
388
+ - A denied `consume` writes nothing: it does not start a rolling window and
389
+ does not store the new limit. An `amount` above what is left is denied in full.
390
+ - The window policy is fixed per `(scope, subjectRef, key)`. Changing the kind,
391
+ `durationMs`, calendar `period`, `timeZone` spelling, or the week start of a
392
+ `week` window throws `POLICY_MISMATCH`, even after the window expired. The
393
+ limit may change at any time without resetting usage; a lower limit can
394
+ return `used` above `limit` with `remaining: 0`.
395
+ - `refund` only applies when `periodKey` matches the stored row and that window
396
+ has not ended. Otherwise it returns `refunded: false` with the stored row's
397
+ `used` and `remaining` (zeros if there is no row) and writes nothing. Those
398
+ numbers are not recomputed for the current window.
399
+ - `refund`'s `remaining` uses the limit stored by the last allowed `consume`. A
400
+ refund on a matching row with `used: 0` returns `refunded: true` and writes
401
+ nothing.
402
+ - `remaining` is a query: it never writes, never starts a rolling window, and
403
+ reports an expired row as zero usage. Time passing alone does not invalidate a
404
+ Convex query subscription, so treat `resetsAt` as an expiry hint; `consume`
405
+ always rechecks server time.
406
+ - Rolling windows start at the first allowed `consume`. Epoch windows are
407
+ `floor(now / durationMs)` buckets. Calendar days are not always 24 hours (for
408
+ example 23 or 25 on a DST change); a
409
+ repeated local midnight uses the earlier instant, and a skipped midnight or
410
+ date advances through the gap.
411
+ - `periodKey` is an opaque window label, not a receipt or idempotency token. Do
412
+ not parse it. After `eraseSubject`, the same calendar period can produce the
413
+ same label again, so never replay old refunds against it.
414
+ - `eraseSubject` returns the count from its first pass only and schedules more
415
+ passes while a pass is full, including a possible final empty pass. It is not
416
+ a tombstone: a `consume` that races the sweep can survive or be deleted.
417
+ - One row per `(scope, subjectRef, key)`: concurrent consumes on the same key
418
+ contend on that row (Convex retries conflicting mutations); different keys are independent.
419
+ - No usage history, receipts or audit events are stored. Record denials and
420
+ refunds in your own tables if you need them.
421
+
422
+ ## Compatibility
423
+
424
+ - Peer dependency: `convex@^1.45.0`. CI builds and tests against the locked
425
+ dev version, `convex` 1.51.0.
426
+ - Node: `engines.node` is `>=22.12.0`. The package is ESM only.
427
+ - `@vllnt/convex-quota/test` ships as TypeScript source and needs `convex-test`
428
+ (tested with 0.0.73, which itself needs `convex@^1.46.0`), `vitest` and
429
+ `vite` in your app: it calls Vite's `import.meta.glob`, so add
430
+ `/// <reference types="vite/client" />` to the test file.
431
+ - TypeScript: the packed exports and the `./test` helper type-check under both
432
+ `bundler` and `nodenext` module resolution (`pnpm check:pack`).
433
+ - No React entry point: the package is backend only.
434
+ - Releases: stable versions are published to the `latest` dist-tag with npm
435
+ provenance; builds from `main` go to `canary`
436
+ (`pnpm add @vllnt/convex-quota@canary`).
337
437
 
338
438
  ## Testing
339
439
 
340
440
  ```bash
341
- pnpm test
342
- pnpm test:coverage
441
+ pnpm test # single run
442
+ pnpm test:coverage # 100% enforced on the source files listed in vitest.config.mts
343
443
  ```
344
444
 
345
- Unit/integration tests use the **mock backend** `convex-test`
346
- (`@edge-runtime/vm`). They do not establish real-backend OCC or scheduler
347
- guarantees.
445
+ Tests run the component's real functions in `convex-test`'s in-memory backend
446
+ (`@edge-runtime/vm`), including adversarial input, civil-time transitions and
447
+ scheduled erase batches. They do not prove real Convex OCC retries or real
448
+ scheduler delivery.
348
449
 
349
450
  ### Testing your app
350
451
 
351
452
  `@vllnt/convex-quota/test` exports `register(t, name = "quota")` to mount the
352
- component in a `convex-test` instance. It needs `convex-test` and `vitest` (with
353
- Vite's `import.meta.glob`) in the consuming app:
453
+ component in a `convex-test` instance built from your app's schema:
354
454
 
355
455
  ```ts
456
+ // convex/plays.test.ts
356
457
  /// <reference types="vite/client" />
357
458
  import { convexTest } from "convex-test";
358
459
  import { register } from "@vllnt/convex-quota/test";
460
+ import { expect, test } from "vitest";
461
+ import { api } from "./_generated/api";
359
462
  import schema from "./schema";
360
463
 
361
- const t = convexTest(schema, import.meta.glob("./**/*.ts"));
362
- register(t);
464
+ test("a play uses one unit of the daily allowance", async () => {
465
+ const t = convexTest(schema, import.meta.glob("./**/*.ts"));
466
+ register(t);
467
+ const user = t.withIdentity({ tokenIdentifier: "user|1" });
468
+ await user.mutation(api.plays.play, {});
469
+ const left = await user.query(api.plays.playsLeft, {});
470
+ expect(left.remaining).toBe(4);
471
+ });
472
+ ```
473
+
474
+ ```ts
475
+ // convex/schema.ts
476
+ import { defineSchema } from "convex/server";
477
+
478
+ export default defineSchema({});
363
479
  ```
364
480
 
365
- ## Contributing
481
+ ## Security
366
482
 
367
- See [CONTRIBUTING.md](CONTRIBUTING.md).
483
+ - Auth-agnostic: the host resolves identity and passes an opaque `subjectRef`.
484
+ - Tables are sandboxed: they are reached only through the exported functions.
485
+ - Server-sourced windows: a skewed client clock cannot pick the period.
486
+ - Never take `limit`, `amount`, `scope` or the window from an untrusted caller,
487
+ and call `refund` only from verified host records.
488
+ - The functions in the repository's `example/convex/example.ts` are
489
+ unauthenticated test fixtures, not production endpoints.
368
490
 
369
- ## Author
491
+ See [docs/API.md](./docs/API.md).
370
492
 
371
- Built by [bntvllnt](https://github.com/bntvllnt) ·
372
- [bntvllnt.com](https://bntvllnt.com) · [X @bntvllnt](https://x.com/bntvllnt)
493
+ ## Related packages
373
494
 
374
- Part of the [@vllnt](https://github.com/vllnt) Convex component fleet —
375
- [vllnt.com](https://vllnt.com)
495
+ - [`@vllnt/convex-idempotency`](https://oss.vllnt.com/packages/convex-idempotency): the example app mounts both components and wraps `quota.consume` and `quota.refund` in `begin` → `complete` inside one host mutation, so a retried request is not counted twice.
376
496
 
377
- If this is useful, [sponsor the work](https://github.com/sponsors/bntvllnt).
497
+ ## Contributing
498
+
499
+ See
500
+ [CONTRIBUTING.md](https://github.com/vllnt/convex-quota/blob/main/CONTRIBUTING.md).
501
+
502
+ ## Links
503
+
504
+ - Docs and changelog: [oss.vllnt.com/packages/convex-quota](https://oss.vllnt.com/packages/convex-quota) · [release feed](https://oss.vllnt.com/packages/convex-quota/rss.xml)
505
+ - All @vllnt packages: [oss.vllnt.com](https://oss.vllnt.com) · [search packages and docs on index.vllnt.com](https://index.vllnt.com)
506
+ - Source and issues: [GitHub](https://github.com/vllnt/convex-quota) · [issues](https://github.com/vllnt/convex-quota/issues) · [npm](https://www.npmjs.com/package/@vllnt/convex-quota)
507
+ - Questions and updates: [Discord](https://bntvllnt.com/discord) · [X @bntvllnt](https://x.com/bntvllnt)
508
+ - Company and author: [vllnt.com](https://vllnt.com) · [bntvllnt.com](https://bntvllnt.com) · [GitHub @bntvllnt](https://github.com/bntvllnt) · [LinkedIn](https://linkedin.com/in/bntvllnt)
509
+ - Sponsor: [GitHub Sponsors](https://github.com/sponsors/bntvllnt)
378
510
 
379
511
  ## License
380
512
 
381
- MIT — see [LICENSE](LICENSE).
513
+ MIT, see [LICENSE](./LICENSE).
514
+
515
+ ---
516
+
517
+ Part of [vllnt open source](https://oss.vllnt.com) · [Package page](https://oss.vllnt.com/packages/convex-quota) · [vllnt.com](https://vllnt.com) · Built by [bntvllnt](https://bntvllnt.com)