@vllnt/convex-analytics 0.1.0 → 0.1.1-canary.46dc78e

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.
@@ -1,6 +1,9 @@
1
1
  import { httpRouter } from "convex/server";
2
- import { httpAction } from "./_generated/server";
3
- import { api } from "./_generated/api";
2
+ import { ConvexError } from "convex/values";
3
+ import { httpAction } from "./_generated/server.js";
4
+ import type { ActionCtx } from "./_generated/server.js";
5
+ import { assertProps } from "./validators.js";
6
+ import { api } from "./_generated/api.js";
4
7
 
5
8
  function json(data: unknown, status = 200): Response {
6
9
  return new Response(JSON.stringify(data), {
@@ -13,6 +16,27 @@ function error(message: string, status = 400): Response {
13
16
  return json({ error: message }, status);
14
17
  }
15
18
 
19
+ /**
20
+ * Run a handler body and turn a typed input error from the component (a `ConvexError`
21
+ * with `{ code, message }`) into `400 { error, code }`. Anything else still fails the action.
22
+ */
23
+ export async function withInputErrors(run: () => Promise<Response>): Promise<Response> {
24
+ try {
25
+ return await run();
26
+ } catch (e) {
27
+ const data: unknown = e instanceof ConvexError ? e.data : undefined;
28
+ if (typeof data === "object" && data !== null && "code" in data && "message" in data) {
29
+ return json({ error: String(data.message), code: String(data.code) }, 400);
30
+ }
31
+ throw e;
32
+ }
33
+ }
34
+
35
+ /** An `httpAction` whose typed input errors are returned as 400 responses. */
36
+ function handle(fn: (ctx: ActionCtx, request: Request) => Promise<Response>) {
37
+ return httpAction((ctx, request) => withInputErrors(() => fn(ctx, request)));
38
+ }
39
+
16
40
  function timingSafeEqual(a: string, b: string): boolean {
17
41
  if (a.length !== b.length) return false;
18
42
  let result = 0;
@@ -26,6 +50,16 @@ function scopeOf(value: unknown): string {
26
50
  return typeof value === "string" && value.length > 0 ? value : "default";
27
51
  }
28
52
 
53
+ /** The stored `apiKeys` value as a string array, or `null` when it is not one. */
54
+ function parseApiKeys(raw: string): string[] | null {
55
+ try {
56
+ const keys: unknown = JSON.parse(raw);
57
+ return Array.isArray(keys) && keys.every((k) => typeof k === "string") ? keys : null;
58
+ } catch {
59
+ return null;
60
+ }
61
+ }
62
+
29
63
  /**
30
64
  * Gate a request by API key. Keys are a JSON string array stored at config
31
65
  * `(scope, "apiKeys")`. Returns an error Response on failure, else null.
@@ -42,7 +76,8 @@ async function requireApiKey(
42
76
  key: "apiKeys",
43
77
  } as never);
44
78
  if (!config) return error("API keys not configured", 401);
45
- const keys = JSON.parse(config as string) as string[];
79
+ const keys = parseApiKeys(config as string);
80
+ if (keys === null) return error("API keys misconfigured", 500);
46
81
  const matched = keys.some((stored) => timingSafeEqual(stored, key));
47
82
  if (!matched) return error("Invalid API key", 401);
48
83
  return null;
@@ -61,19 +96,32 @@ function getParams(request: Request): URLSearchParams {
61
96
  return new URL(request.url).searchParams;
62
97
  }
63
98
 
99
+ /** A numeric query param; blank or malformed values become NaN so the component rejects them. */
100
+ function numberParam(params: URLSearchParams, name: string): number | undefined {
101
+ const raw = params.get(name);
102
+ if (raw === null) return undefined;
103
+ return raw.trim() === "" ? NaN : Number(raw);
104
+ }
105
+
64
106
  function range(params: URLSearchParams): { from?: number; to?: number } | undefined {
65
- const from = params.get("from");
66
- const to = params.get("to");
67
- if (from === null && to === null) return undefined;
68
- return {
69
- from: from !== null ? Number(from) : undefined,
70
- to: to !== null ? Number(to) : undefined,
71
- };
107
+ const from = numberParam(params, "from");
108
+ const to = numberParam(params, "to");
109
+ if (from === undefined && to === undefined) return undefined;
110
+ return { from, to };
72
111
  }
73
112
 
74
- export const trackEndpoint = httpAction(async (ctx, request) => {
113
+ const GRANULARITIES = ["minute", "hour", "day"];
114
+
115
+ function isStringArray(value: unknown): value is string[] {
116
+ return Array.isArray(value) && value.every((item) => typeof item === "string");
117
+ }
118
+
119
+ export const trackEndpoint = handle(async (ctx, request) => {
75
120
  const parsed = await parseJsonSafe(request);
76
121
  if (!parsed.ok) return error("Invalid JSON body");
122
+ if (typeof parsed.data !== "object" || parsed.data === null || Array.isArray(parsed.data)) {
123
+ return error("Body must be a JSON object");
124
+ }
77
125
  const body = parsed.data as Record<string, unknown>;
78
126
 
79
127
  const scope = scopeOf(body["scope"]);
@@ -83,27 +131,36 @@ export const trackEndpoint = httpAction(async (ctx, request) => {
83
131
  if (typeof body["name"] !== "string" || body["name"].length === 0) {
84
132
  return error("name is required");
85
133
  }
86
- if (!Array.isArray(body["dimensions"])) {
134
+ if (!isStringArray(body["dimensions"])) {
87
135
  return error("dimensions (string[]) is required");
88
136
  }
137
+ const props = body["props"] ?? undefined;
138
+ if (props !== undefined && (typeof props !== "object" || Array.isArray(props))) {
139
+ return error("props must be a flat object of scalar values");
140
+ }
141
+ if (props !== undefined) assertProps(props as Record<string, unknown>);
142
+ const granularities = body["granularities"] ?? ["day"];
143
+ if (!isStringArray(granularities) || !granularities.every((g) => GRANULARITIES.includes(g))) {
144
+ return error("granularities must be an array of minute, hour, or day");
145
+ }
89
146
 
90
147
  const result = await ctx.runMutation(api.mutations.track as never, {
91
148
  scope,
92
149
  name: body["name"],
93
150
  subjectRef: typeof body["subjectRef"] === "string" ? body["subjectRef"] : undefined,
94
151
  sessionRef: typeof body["sessionRef"] === "string" ? body["sessionRef"] : undefined,
95
- props: body["props"] ?? undefined,
152
+ props,
96
153
  ts: typeof body["ts"] === "number" ? body["ts"] : undefined,
97
154
  dedupeKey: typeof body["dedupeKey"] === "string" ? body["dedupeKey"] : undefined,
98
155
  dimensions: body["dimensions"],
99
- granularities: Array.isArray(body["granularities"]) ? body["granularities"] : ["day"],
156
+ granularities,
100
157
  sampleRate: typeof body["sampleRate"] === "number" ? body["sampleRate"] : undefined,
101
158
  } as never);
102
159
 
103
160
  return json({ result }, 201);
104
161
  });
105
162
 
106
- export const metricEndpoint = httpAction(async (ctx, request) => {
163
+ export const metricEndpoint = handle(async (ctx, request) => {
107
164
  const params = getParams(request);
108
165
  const scope = scopeOf(params.get("scope"));
109
166
  const authError = await requireApiKey(ctx, request, scope);
@@ -124,7 +181,7 @@ export const metricEndpoint = httpAction(async (ctx, request) => {
124
181
  return json({ name, count });
125
182
  });
126
183
 
127
- export const topEndpoint = httpAction(async (ctx, request) => {
184
+ export const topEndpoint = handle(async (ctx, request) => {
128
185
  const params = getParams(request);
129
186
  const scope = scopeOf(params.get("scope"));
130
187
  const authError = await requireApiKey(ctx, request, scope);
@@ -140,13 +197,13 @@ export const topEndpoint = httpAction(async (ctx, request) => {
140
197
  name,
141
198
  dimension,
142
199
  range: range(params),
143
- limit: params.get("limit") ? Number(params.get("limit")) : undefined,
200
+ limit: numberParam(params, "limit"),
144
201
  } as never);
145
202
 
146
203
  return json(result);
147
204
  });
148
205
 
149
- export const timeseriesEndpoint = httpAction(async (ctx, request) => {
206
+ export const timeseriesEndpoint = handle(async (ctx, request) => {
150
207
  const params = getParams(request);
151
208
  const scope = scopeOf(params.get("scope"));
152
209
  const authError = await requireApiKey(ctx, request, scope);
@@ -155,7 +212,7 @@ export const timeseriesEndpoint = httpAction(async (ctx, request) => {
155
212
  const name = params.get("name");
156
213
  if (!name) return error("name parameter required");
157
214
  const granularity = params.get("granularity") ?? "day";
158
- if (granularity !== "minute" && granularity !== "hour" && granularity !== "day") {
215
+ if (!GRANULARITIES.includes(granularity)) {
159
216
  return error("granularity must be minute, hour, or day");
160
217
  }
161
218
 
@@ -169,14 +226,14 @@ export const timeseriesEndpoint = httpAction(async (ctx, request) => {
169
226
  return json(result);
170
227
  });
171
228
 
172
- export const uniquesEndpoint = httpAction(async (ctx, request) => {
229
+ export const uniquesEndpoint = handle(async (ctx, request) => {
173
230
  const params = getParams(request);
174
231
  const scope = scopeOf(params.get("scope"));
175
232
  const authError = await requireApiKey(ctx, request, scope);
176
233
  if (authError) return authError;
177
234
 
178
235
  const granularity = params.get("granularity") ?? "day";
179
- if (granularity !== "minute" && granularity !== "hour" && granularity !== "day") {
236
+ if (!GRANULARITIES.includes(granularity)) {
180
237
  return error("granularity must be minute, hour, or day");
181
238
  }
182
239
 
@@ -1,6 +1,6 @@
1
- import { internal } from "./_generated/api";
2
- import { internalMutation } from "./_generated/server";
3
- import type { MutationCtx } from "./_generated/server";
1
+ import { internal } from "./_generated/api.js";
2
+ import { internalMutation } from "./_generated/server.js";
3
+ import type { MutationCtx } from "./_generated/server.js";
4
4
  import { v } from "convex/values";
5
5
  import { granularitiesValidator } from "./validators.js";
6
6
  import { bucketStart, valKey } from "../shared.js";
@@ -185,7 +185,7 @@ export const backfill = internalMutation({
185
185
  const bucket = bucketStart(e.ts, gran);
186
186
  bump(gran, bucket, TOTAL, TOTAL);
187
187
  for (const dim of args.dimensions) {
188
- if (dim in e.props) {
188
+ if (Object.hasOwn(e.props, dim)) {
189
189
  bump(gran, bucket, dim, valKey(e.props[dim]!));
190
190
  }
191
191
  }
@@ -1,11 +1,19 @@
1
- import { mutation } from "./_generated/server";
2
- import type { MutationCtx } from "./_generated/server";
3
- import { components } from "./_generated/api";
1
+ import { mutation } from "./_generated/server.js";
2
+ import type { MutationCtx } from "./_generated/server.js";
3
+ import { components } from "./_generated/api.js";
4
4
  import { v } from "convex/values";
5
5
  import { DirectAggregate } from "@convex-dev/aggregate";
6
6
  import { ShardedCounter } from "@convex-dev/sharded-counter";
7
7
  import { RateLimiter, MINUTE } from "@convex-dev/rate-limiter";
8
- import { propsValidator, granularitiesValidator } from "./validators.js";
8
+ import {
9
+ propsValidator,
10
+ granularitiesValidator,
11
+ assertProps,
12
+ assertFiniteTs,
13
+ assertNonEmpty,
14
+ assertSampleRate,
15
+ invalidInput,
16
+ } from "./validators.js";
9
17
  import { bucketStart, tupleKey, valKey } from "../shared.js";
10
18
  import type { Granularity, Scalar } from "../shared.js";
11
19
 
@@ -87,10 +95,20 @@ export const track = mutation({
87
95
  },
88
96
  returns: v.union(v.literal("tracked"), v.literal("dropped"), v.literal("duplicate")),
89
97
  handler: async (ctx, args) => {
98
+ assertNonEmpty("scope", args.scope);
99
+ assertNonEmpty("name", args.name);
100
+ assertNonEmpty("subjectRef", args.subjectRef);
101
+ assertNonEmpty("sessionRef", args.sessionRef);
102
+ assertNonEmpty("dedupeKey", args.dedupeKey);
103
+ for (const dim of args.dimensions) assertNonEmpty("dimensions[]", dim);
104
+ assertFiniteTs("ts", args.ts);
105
+ assertSampleRate(args.sampleRate);
106
+ const props: Record<string, Scalar> = args.props ?? {};
107
+ assertProps(props);
108
+
90
109
  const now = Date.now();
91
110
  const scope = args.scope;
92
111
  const ts = args.ts ?? now;
93
- const props: Record<string, Scalar> = args.props ?? {};
94
112
  const grans = args.granularities.length > 0 ? args.granularities : (["day"] as const);
95
113
 
96
114
  if (args.sessionRef !== undefined) {
@@ -191,7 +209,7 @@ export const track = mutation({
191
209
  const bucket = bucketStart(ts, granularity);
192
210
  await bumpRollup(ctx, scope, args.name, granularity, bucket, TOTAL, TOTAL);
193
211
  for (const dim of args.dimensions) {
194
- if (dim in props) {
212
+ if (Object.hasOwn(props, dim)) {
195
213
  await bumpRollup(
196
214
  ctx,
197
215
  scope,
@@ -238,6 +256,8 @@ export const configSet = mutation({
238
256
  args: { scope: v.string(), key: v.string(), value: v.string() },
239
257
  returns: v.null(),
240
258
  handler: async (ctx, args) => {
259
+ assertNonEmpty("scope", args.scope);
260
+ assertNonEmpty("key", args.key);
241
261
  await ensureScope(ctx, args.scope);
242
262
  await upsertConfig(ctx, args.scope, args.key, args.value);
243
263
  return null;
@@ -253,6 +273,16 @@ export const configure = mutation({
253
273
  },
254
274
  returns: v.null(),
255
275
  handler: async (ctx, args) => {
276
+ assertNonEmpty("scope", args.scope);
277
+ assertSampleRate(args.sampleRate);
278
+ for (const [field, value] of [
279
+ ["retentionDays", args.retentionDays],
280
+ ["sessionIdleMs", args.sessionIdleMs],
281
+ ] as const) {
282
+ if (value !== undefined && !(Number.isFinite(value) && value > 0)) {
283
+ throw invalidInput("INVALID_CONFIG", `${field} must be a positive finite number`);
284
+ }
285
+ }
256
286
  await ensureScope(ctx, args.scope);
257
287
  const entries: Array<[string, string]> = [];
258
288
  if (args.retentionDays !== undefined) {
@@ -1,5 +1,7 @@
1
- import { query } from "./_generated/server";
2
- import { components } from "./_generated/api";
1
+ import { query } from "./_generated/server.js";
2
+ import type { QueryCtx } from "./_generated/server.js";
3
+ import type { Doc } from "./_generated/dataModel.js";
4
+ import { components } from "./_generated/api.js";
3
5
  import { v } from "convex/values";
4
6
  import { ShardedCounter } from "@convex-dev/sharded-counter";
5
7
  import {
@@ -13,6 +15,9 @@ import {
13
15
  retentionCohort,
14
16
  eventPage,
15
17
  distributionView,
18
+ assertCount,
19
+ assertRange,
20
+ invalidInput,
16
21
  } from "./validators.js";
17
22
  import { bucketStart, bucketSize, tupleKey, valKey } from "../shared.js";
18
23
  import type { Granularity } from "../shared.js";
@@ -23,6 +28,32 @@ const counter = new ShardedCounter(components.shardedCounter as never, {
23
28
 
24
29
  const TOTAL = "";
25
30
 
31
+ /**
32
+ * Rollup rows for `(scope, name, granularity)` with `bucket` inside the range, read through
33
+ * the index so only buckets in range are loaded. Bounds are inclusive and bucket-aligned.
34
+ */
35
+ async function rollupsInRange(
36
+ ctx: QueryCtx,
37
+ scope: string,
38
+ name: string,
39
+ granularity: Granularity,
40
+ range: { from?: number; to?: number } | undefined,
41
+ ): Promise<Doc<"rollups">[]> {
42
+ const lo = range?.from === undefined ? -Infinity : bucketStart(range.from, granularity);
43
+ const hi = range?.to === undefined ? Infinity : bucketStart(range.to, granularity);
44
+ return await ctx.db
45
+ .query("rollups")
46
+ .withIndex("by_scope_name_gran_bucket_dim", (q) =>
47
+ q
48
+ .eq("scope", scope)
49
+ .eq("name", name)
50
+ .eq("granularity", granularity)
51
+ .gte("bucket", lo)
52
+ .lte("bucket", hi),
53
+ )
54
+ .collect();
55
+ }
56
+
26
57
  /** Total event count over a range, optionally filtered by one dimension value. */
27
58
  export const metric = query({
28
59
  args: {
@@ -33,6 +64,7 @@ export const metric = query({
33
64
  },
34
65
  returns: v.number(),
35
66
  handler: async (ctx, args) => {
67
+ assertRange(args.range);
36
68
  const dim = args.where ? args.where.dim : TOTAL;
37
69
  const val = args.where ? valKey(args.where.val) : TOTAL;
38
70
 
@@ -40,25 +72,11 @@ export const metric = query({
40
72
  return await counter.count(ctx, tupleKey(args.scope, args.name));
41
73
  }
42
74
 
43
- const rollups = await ctx.db
44
- .query("rollups")
45
- .withIndex("by_scope_name_gran_bucket_dim", (q) =>
46
- q
47
- .eq("scope", args.scope)
48
- .eq("name", args.name)
49
- .eq("granularity", "day"),
50
- )
51
- .collect();
75
+ const rollups = await rollupsInRange(ctx, args.scope, args.name, "day", args.range);
52
76
 
53
77
  let total = 0;
54
78
  for (const r of rollups) {
55
79
  if (r.dim !== dim || r.val !== val) continue;
56
- if (args.range?.from !== undefined && r.bucket < bucketStart(args.range.from, "day")) {
57
- continue;
58
- }
59
- if (args.range?.to !== undefined && r.bucket > bucketStart(args.range.to, "day")) {
60
- continue;
61
- }
62
80
  total += r.count;
63
81
  }
64
82
  return total;
@@ -76,26 +94,14 @@ export const top = query({
76
94
  },
77
95
  returns: v.array(topRow),
78
96
  handler: async (ctx, args) => {
97
+ assertRange(args.range);
98
+ assertCount("limit", args.limit);
79
99
  const limit = Math.min(args.limit ?? 20, 100);
80
- const rollups = await ctx.db
81
- .query("rollups")
82
- .withIndex("by_scope_name_gran_bucket_dim", (q) =>
83
- q
84
- .eq("scope", args.scope)
85
- .eq("name", args.name)
86
- .eq("granularity", "day"),
87
- )
88
- .collect();
100
+ const rollups = await rollupsInRange(ctx, args.scope, args.name, "day", args.range);
89
101
 
90
102
  const counts = new Map<string, number>();
91
103
  for (const r of rollups) {
92
104
  if (r.dim !== args.dimension) continue;
93
- if (args.range?.from !== undefined && r.bucket < bucketStart(args.range.from, "day")) {
94
- continue;
95
- }
96
- if (args.range?.to !== undefined && r.bucket > bucketStart(args.range.to, "day")) {
97
- continue;
98
- }
99
105
  counts.set(r.val, (counts.get(r.val) ?? 0) + r.count);
100
106
  }
101
107
 
@@ -117,27 +123,16 @@ export const timeseries = query({
117
123
  },
118
124
  returns: v.array(timeseriesPoint),
119
125
  handler: async (ctx, args) => {
126
+ assertRange(args.range);
120
127
  const gran: Granularity = args.granularity;
121
128
  const dim = args.where ? args.where.dim : TOTAL;
122
129
  const val = args.where ? valKey(args.where.val) : TOTAL;
123
130
 
124
- const rollups = await ctx.db
125
- .query("rollups")
126
- .withIndex("by_scope_name_gran_bucket_dim", (q) =>
127
- q.eq("scope", args.scope).eq("name", args.name).eq("granularity", gran),
128
- )
129
- .collect();
130
-
131
- const fromBucket =
132
- args.range.from !== undefined ? bucketStart(args.range.from, gran) : undefined;
133
- const toBucket =
134
- args.range.to !== undefined ? bucketStart(args.range.to, gran) : undefined;
131
+ const rollups = await rollupsInRange(ctx, args.scope, args.name, gran, args.range);
135
132
 
136
133
  const counts = new Map<number, number>();
137
134
  for (const r of rollups) {
138
135
  if (r.dim !== dim || r.val !== val) continue;
139
- if (fromBucket !== undefined && r.bucket < fromBucket) continue;
140
- if (toBucket !== undefined && r.bucket > toBucket) continue;
141
136
  counts.set(r.bucket, (counts.get(r.bucket) ?? 0) + r.count);
142
137
  }
143
138
 
@@ -156,13 +151,16 @@ export const uniques = query({
156
151
  },
157
152
  returns: uniquesView,
158
153
  handler: async (ctx, args) => {
154
+ assertRange(args.range);
159
155
  const now = Date.now();
160
156
  const to = args.range.to ?? now;
161
157
  const from = args.range.from ?? to - 30 * 24 * 60 * 60 * 1000;
162
158
 
163
159
  const subjects = await ctx.db
164
160
  .query("subjects")
165
- .withIndex("by_scope_firstSeen", (q) => q.eq("scope", args.scope))
161
+ .withIndex("by_scope_lastSeen", (q) =>
162
+ q.eq("scope", args.scope).gte("lastSeen", from).lte("lastSeen", to),
163
+ )
166
164
  .collect();
167
165
 
168
166
  const size = bucketSize(args.granularity);
@@ -174,7 +172,6 @@ export const uniques = query({
174
172
  const mauCutoff = to - 30 * dayMs;
175
173
 
176
174
  for (const s of subjects) {
177
- if (s.lastSeen < from || s.lastSeen > to) continue;
178
175
  mau += s.lastSeen >= mauCutoff ? 1 : 0;
179
176
  wau += s.lastSeen >= wauCutoff ? 1 : 0;
180
177
  const bucket = Math.floor(s.lastSeen / size) * size;
@@ -208,6 +205,7 @@ export const funnel = query({
208
205
  if (args.steps.length < 2) {
209
206
  throw new Error("Funnel requires at least 2 steps");
210
207
  }
208
+ assertRange(args.range);
211
209
  const now = Date.now();
212
210
  const to = args.range.to ?? now;
213
211
  const from = args.range.from ?? to - 30 * 24 * 60 * 60 * 1000;
@@ -272,6 +270,8 @@ export const retention = query({
272
270
  },
273
271
  returns: v.array(retentionCohort),
274
272
  handler: async (ctx, args) => {
273
+ assertRange(args.cohortRange);
274
+ assertCount("periods", args.periods);
275
275
  const gran: Granularity = args.granularity ?? "day";
276
276
  const size = bucketSize(gran);
277
277
  const now = Date.now();
@@ -334,6 +334,10 @@ export const distribution = query({
334
334
  },
335
335
  returns: distributionView,
336
336
  handler: async (ctx, args) => {
337
+ assertRange(args.range);
338
+ if (!args.buckets.every(Number.isFinite)) {
339
+ throw invalidInput("INVALID_BUCKETS", "buckets must be finite numbers");
340
+ }
337
341
  const bins = [...args.buckets]
338
342
  .sort((a, b) => a - b)
339
343
  .map((upper) => ({ upper, count: 0 }));
@@ -390,7 +394,11 @@ export const list = query({
390
394
  // Note: events sharing the exact boundary `ts` may be skipped across a page
391
395
  // edge — adequate for a raw-event peek; precise feeds belong in the host.
392
396
  const { numItems, cursor } = args.paginationOpts;
397
+ assertCount("numItems", numItems);
393
398
  const before = cursor ? Number(cursor) : null;
399
+ if (before !== null && !Number.isFinite(before)) {
400
+ throw invalidInput("INVALID_CURSOR", "cursor is not a value returned by list");
401
+ }
394
402
  const rows = await ctx.db
395
403
  .query("events")
396
404
  .withIndex("by_scope_name_ts", (q) => {
@@ -55,7 +55,8 @@ export default defineSchema({
55
55
  eventCount: v.number(),
56
56
  })
57
57
  .index("by_scope_subject", ["scope", "subjectRef"])
58
- .index("by_scope_firstSeen", ["scope", "firstSeen"]),
58
+ .index("by_scope_firstSeen", ["scope", "firstSeen"])
59
+ .index("by_scope_lastSeen", ["scope", "lastSeen"]),
59
60
 
60
61
  sessions: defineTable({
61
62
  scope: v.string(),
@@ -1,4 +1,4 @@
1
- import { v } from "convex/values";
1
+ import { ConvexError, v } from "convex/values";
2
2
 
3
3
  /** A single property value — string, number, boolean, or null. No nested objects/arrays. */
4
4
  export const scalarValidator = v.union(
@@ -92,3 +92,82 @@ export const distributionView = v.object({
92
92
  count: v.number(),
93
93
  sum: v.number(),
94
94
  });
95
+
96
+ /** Stable machine-readable codes carried in `ConvexError.data.code`. */
97
+ export type AnalyticsErrorCode =
98
+ | "EMPTY_STRING"
99
+ | "INVALID_TIMESTAMP"
100
+ | "INVALID_SAMPLE_RATE"
101
+ | "INVALID_PROP_KEY"
102
+ | "INVALID_PROP_VALUE"
103
+ | "INVALID_COUNT"
104
+ | "INVALID_CURSOR"
105
+ | "INVALID_BUCKETS"
106
+ | "INVALID_CONFIG";
107
+
108
+ /** Typed input error: `ConvexError` whose data is `{ code, message }`. */
109
+ export function invalidInput(
110
+ code: AnalyticsErrorCode,
111
+ message: string,
112
+ ): ConvexError<{ code: AnalyticsErrorCode; message: string }> {
113
+ return new ConvexError({ code, message });
114
+ }
115
+
116
+ /** Reject an empty string. `undefined` (an omitted optional field) passes. */
117
+ export function assertNonEmpty(field: string, value: string | undefined): void {
118
+ if (value === "") {
119
+ throw invalidInput("EMPTY_STRING", `${field} must not be empty`);
120
+ }
121
+ }
122
+
123
+ /** Reject NaN and +/-Infinity epoch-millis values. `undefined` passes. */
124
+ export function assertFiniteTs(field: string, value: number | undefined): void {
125
+ if (value !== undefined && !Number.isFinite(value)) {
126
+ throw invalidInput("INVALID_TIMESTAMP", `${field} must be a finite number`);
127
+ }
128
+ }
129
+
130
+ /** Reject non-finite `from` / `to` bounds of an optional range. */
131
+ export function assertRange(range: { from?: number; to?: number } | undefined): void {
132
+ assertFiniteTs("range.from", range?.from);
133
+ assertFiniteTs("range.to", range?.to);
134
+ }
135
+
136
+ /** Reject anything but a positive integer. `undefined` passes. */
137
+ export function assertCount(field: string, value: number | undefined): void {
138
+ if (value !== undefined && !(Number.isInteger(value) && value > 0)) {
139
+ throw invalidInput("INVALID_COUNT", `${field} must be a positive integer`);
140
+ }
141
+ }
142
+
143
+ /** Reject a sample rate that is not a finite number in `[0, 1]`. `undefined` passes. */
144
+ export function assertSampleRate(value: number | undefined): void {
145
+ if (value !== undefined && !(value >= 0 && value <= 1)) {
146
+ throw invalidInput("INVALID_SAMPLE_RATE", "sampleRate must be a number between 0 and 1");
147
+ }
148
+ }
149
+
150
+ /** Convex field names: 1-1024 printable ASCII characters, not starting with `$` (or empty). */
151
+ const PROP_KEY = /^(?!\$)[\x20-\x7e]{0,1024}$/;
152
+
153
+ /**
154
+ * Reject NaN / +/-Infinity numbers and prop keys Convex cannot store (non-ASCII, control
155
+ * characters, leading `$`, over 1024 characters). Convex rejects bad keys before a mutation
156
+ * runs, so the key check matters for callers that validate first, such as the HTTP route.
157
+ */
158
+ export function assertProps(props: Record<string, unknown>): void {
159
+ for (const [key, value] of Object.entries(props)) {
160
+ if (!PROP_KEY.test(key)) {
161
+ throw invalidInput(
162
+ "INVALID_PROP_KEY",
163
+ "props keys must be printable ASCII, at most 1024 characters, and not start with $",
164
+ );
165
+ }
166
+ if (value !== null && typeof value === "object") {
167
+ throw invalidInput("INVALID_PROP_VALUE", `props.${key} must be a scalar, not an object or array`);
168
+ }
169
+ if (typeof value === "number" && !Number.isFinite(value)) {
170
+ throw invalidInput("INVALID_PROP_VALUE", `props.${key} must be a finite number`);
171
+ }
172
+ }
173
+ }