@vllnt/convex-helpers 0.2.0-canary.487d828 → 0.2.0

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.
@@ -0,0 +1,446 @@
1
+ /**
2
+ * @module @vllnt/convex-helpers/validators
3
+ * Runtime checks against Convex validators, and whole-document validators
4
+ * for schema tables.
5
+ *
6
+ * Adapted, with changes, from `convex-helpers/validators` 0.1.124
7
+ * (Apache-2.0, see NOTICE): same behaviour for these functions, which
8
+ * `src/validators.test.ts` checks side by side, plus two fail-closed
9
+ * differences. Declared object fields must be own properties (upstream also
10
+ * treats inherited names such as `constructor` as declared), and the runtime
11
+ * check throws on the `db` option, which checks a `v.id`'s table, instead of
12
+ * supporting it. The `AddFieldsToValidator` type follows upstream's.
13
+ */
14
+
15
+ import type {
16
+ DataModelFromSchemaDefinition,
17
+ SchemaDefinition,
18
+ TableNamesInDataModel,
19
+ } from "convex/server";
20
+ import type {
21
+ GenericId,
22
+ Infer,
23
+ ObjectType,
24
+ PropertyValidators,
25
+ Validator,
26
+ VFloat64,
27
+ VId,
28
+ VObject,
29
+ } from "convex/values";
30
+ import { v } from "convex/values";
31
+
32
+ /* eslint-disable @typescript-eslint/no-explicit-any -- Convex's own validator constraints are `Validator<any, any, any>` */
33
+ /** Any Convex validator. */
34
+ export type AnyValidator = Validator<any, any, any>;
35
+ type AnySchema = SchemaDefinition<any, boolean>;
36
+ /* eslint-enable @typescript-eslint/no-explicit-any */
37
+
38
+ type Expand<TObject> =
39
+ TObject extends Record<string, unknown>
40
+ ? { [Key in keyof TObject]: TObject[Key] }
41
+ : never;
42
+
43
+ /** Options for the runtime check. */
44
+ export type ValidateOptions = {
45
+ /** Accept object fields the validator does not declare. */
46
+ allowUnknownFields?: boolean;
47
+ /** Throw a {@link ValidationError} instead of returning `false`. */
48
+ throw?: boolean;
49
+ };
50
+
51
+ /** Thrown on a mismatch when called with `throw: true`, and by {@link parse}. */
52
+ export class ValidationError extends Error {
53
+ /**
54
+ * @param expected - The expected kind or literal value
55
+ * @param got - What the value held instead
56
+ * @param path - Path of the failing value inside the checked value
57
+ */
58
+ constructor(
59
+ public expected: string,
60
+ public got: string,
61
+ public path?: string,
62
+ ) {
63
+ const where = path === undefined || path === "" ? "" : ` for ${path}`;
64
+ super(`Validator error${where}: Expected \`${expected}\`, got \`${got}\``);
65
+ this.name = "ValidationError";
66
+ }
67
+ }
68
+
69
+ type Walk = ValidateOptions & { path?: string };
70
+
71
+ /** What a failed check expected and, when set, what to report it got. */
72
+ type Failure = { expected: string; got?: string };
73
+
74
+ type Kind = AnyValidator["kind"];
75
+
76
+ type Checker<TKind extends Kind> = (
77
+ validator: Extract<AnyValidator, { kind: TKind }>,
78
+ value: unknown,
79
+ walk: Walk,
80
+ ) => Failure | undefined;
81
+
82
+ function joinPath(path: string | undefined, key: string): string {
83
+ return path === undefined || path === "" ? key : `${path}.${key}`;
84
+ }
85
+
86
+ function describeValue(value: unknown): string {
87
+ return value === null ? "null" : typeof value;
88
+ }
89
+
90
+ /** The first failure `check` returns over `items`, checking in order and stopping there. */
91
+ function firstFailure<TItem>(
92
+ items: readonly TItem[],
93
+ check: (item: TItem, index: number) => Failure | undefined,
94
+ ): Failure | undefined {
95
+ let failure: Failure | undefined;
96
+ items.some((item, index) => {
97
+ failure = check(item, index);
98
+ return failure !== undefined;
99
+ });
100
+ return failure;
101
+ }
102
+
103
+ function plainObjectFailure(value: object): Failure | undefined {
104
+ const prototype: unknown = Object.getPrototypeOf(value);
105
+ if (prototype === null || prototype === Object.prototype) return undefined;
106
+ const name = (prototype as { constructor?: { name?: unknown } }).constructor
107
+ ?.name;
108
+ // Objects from another realm (a Node.js `vm` context) are still plain.
109
+ if (name === "Object") return undefined;
110
+ return {
111
+ expected: typeof name === "string" && name !== "" ? name : "object",
112
+ };
113
+ }
114
+
115
+ function primitive<TKind extends Kind>(
116
+ test: (value: unknown) => boolean,
117
+ expected?: string,
118
+ ): Checker<TKind> {
119
+ return (validator, value) =>
120
+ test(value) ? undefined : { expected: expected ?? validator.kind };
121
+ }
122
+
123
+ const accept = (): undefined => undefined;
124
+
125
+ function walkValue(
126
+ validator: AnyValidator,
127
+ value: unknown,
128
+ walk: Walk,
129
+ ): boolean {
130
+ const failure = check(validator, value, walk);
131
+ if (failure === undefined) return true;
132
+ if (walk.throw === true) {
133
+ throw new ValidationError(
134
+ failure.expected,
135
+ failure.got ?? describeValue(value),
136
+ walk.path,
137
+ );
138
+ }
139
+ return false;
140
+ }
141
+
142
+ const checkArray: Checker<"array"> = (validator, value, walk) => {
143
+ if (!Array.isArray(value)) return { expected: "array" };
144
+ // Array.from turns holes into `undefined`, so every slot of a sparse array
145
+ // goes through the element check.
146
+ return firstFailure([...(value as unknown[])], (element, index) =>
147
+ walkValue(validator.element, element, {
148
+ ...walk,
149
+ path: `${walk.path ?? ""}[${String(index)}]`,
150
+ })
151
+ ? undefined
152
+ : { expected: validator.element.kind },
153
+ );
154
+ };
155
+
156
+ const checkLiteral: Checker<"literal"> = (validator, value) => {
157
+ if (value === validator.value) return;
158
+ const scalar = ["bigint", "boolean", "number", "string"].includes(
159
+ typeof value,
160
+ );
161
+ return {
162
+ expected: String(validator.value),
163
+ ...(scalar ? { got: `"${String(value)}"` } : {}),
164
+ };
165
+ };
166
+
167
+ function unknownFieldFailure(
168
+ fields: Record<string, AnyValidator | undefined>,
169
+ record: Record<string, unknown>,
170
+ walk: Walk,
171
+ ): Failure | undefined {
172
+ const unknown = Object.entries(record).find(
173
+ ([key, item]) => !Object.hasOwn(fields, key) && item !== undefined,
174
+ );
175
+ if (unknown === undefined) return undefined;
176
+ const [key, item] = unknown;
177
+ if (walk.throw === true) {
178
+ throw new ValidationError("nothing", typeof item, joinPath(walk.path, key));
179
+ }
180
+ return { expected: "object" };
181
+ }
182
+
183
+ const checkObject: Checker<"object"> = (validator, value, walk) => {
184
+ if (typeof value !== "object" || value === null)
185
+ return { expected: "object" };
186
+ const notPlain = plainObjectFailure(value);
187
+ if (notPlain) return notPlain;
188
+ const record = value as Record<string, unknown>;
189
+ const fields: Record<string, AnyValidator> = validator.fields;
190
+ const fieldFailure = firstFailure(Object.entries(fields), ([key, field]) =>
191
+ walkValue(field, record[key], { ...walk, path: joinPath(walk.path, key) })
192
+ ? undefined
193
+ : { expected: "object" },
194
+ );
195
+ if (fieldFailure !== undefined || walk.allowUnknownFields === true) {
196
+ return fieldFailure;
197
+ }
198
+ return unknownFieldFailure(fields, record, walk);
199
+ };
200
+
201
+ const checkUnion: Checker<"union"> = (validator, value, walk) => {
202
+ const members: AnyValidator[] = validator.members;
203
+ const errors: ValidationError[] = [];
204
+ const matched = members.some((member) => {
205
+ try {
206
+ return walkValue(member, value, walk);
207
+ } catch (error) {
208
+ // walkValue throws ValidationError and nothing else.
209
+ errors.push(error as ValidationError);
210
+ return false;
211
+ }
212
+ });
213
+ if (matched) return;
214
+ // With `throw: true`, report the last member's error, as convex-helpers does.
215
+ const last = errors.at(-1);
216
+ if (last !== undefined) throw last;
217
+ return { expected: "union" };
218
+ };
219
+
220
+ const checkRecord: Checker<"record"> = (validator, value, walk) => {
221
+ if (typeof value !== "object" || value === null)
222
+ return { expected: "record" };
223
+ const keyValidator: AnyValidator = validator.key;
224
+ const entryValidator: AnyValidator = validator.value;
225
+ return firstFailure(Object.entries(value), ([key, entry]) => {
226
+ // The wire format drops `undefined` entries, so they pass.
227
+ if (entry === undefined) return;
228
+ const entryWalk = { ...walk, path: joinPath(walk.path, key) };
229
+ if (!walkValue(keyValidator, key, entryWalk)) {
230
+ return { expected: keyValidator.kind };
231
+ }
232
+ return walkValue(entryValidator, entry, entryWalk)
233
+ ? undefined
234
+ : { expected: entryValidator.kind };
235
+ });
236
+ };
237
+
238
+ const checkers: { [TKind in Kind]: Checker<TKind> } = {
239
+ any: accept,
240
+ array: checkArray,
241
+ boolean: primitive((value) => typeof value === "boolean"),
242
+ bytes: primitive((value) => value instanceof ArrayBuffer),
243
+ commitTs: accept,
244
+ float64: primitive((value) => typeof value === "number", "number"),
245
+ function: accept,
246
+ id: primitive((value) => typeof value === "string"),
247
+ int64: primitive((value) => typeof value === "bigint", "bigint"),
248
+ literal: checkLiteral,
249
+ null: primitive((value) => value === null),
250
+ object: checkObject,
251
+ record: checkRecord,
252
+ string: primitive((value) => typeof value === "string"),
253
+ union: checkUnion,
254
+ };
255
+
256
+ function check(
257
+ validator: AnyValidator,
258
+ value: unknown,
259
+ walk: Walk,
260
+ ): Failure | undefined {
261
+ if (value === undefined) {
262
+ return validator.isOptional === "optional"
263
+ ? undefined
264
+ : { expected: validator.kind };
265
+ }
266
+ // Kinds this module does not know (from a newer Convex) accept any value.
267
+ const checker = checkers[validator.kind] as Checker<Kind> | undefined;
268
+ return checker === undefined ? undefined : checker(validator, value, walk);
269
+ }
270
+
271
+ // eslint-disable-next-line write-good-comments/write-good-comments -- the example calls the public function by its name
272
+ /**
273
+ * Checks a value against a Convex validator at runtime.
274
+ *
275
+ * @param validator - Any Convex validator (`v.*`)
276
+ * @param value - The value to check
277
+ * @param options - `throw` to throw instead of returning `false`;
278
+ * `allowUnknownFields` to accept object fields the validator does not declare
279
+ * @returns Whether the value matches; narrows the value's type
280
+ * @throws {ValidationError} With `throw: true`, on the first mismatch
281
+ * @example
282
+ * if (validate(policyValidator, reply, { throw: true })) use(reply);
283
+ */
284
+ export function validate<TValidator extends AnyValidator>(
285
+ validator: TValidator,
286
+ value: unknown,
287
+ options?: ValidateOptions,
288
+ ): value is TValidator["type"] {
289
+ if (options !== undefined && "db" in options) {
290
+ throw new Error("validate: the db option is not supported");
291
+ }
292
+ return walkValue(validator, value, {
293
+ ...(options?.allowUnknownFields === undefined
294
+ ? {}
295
+ : { allowUnknownFields: options.allowUnknownFields }),
296
+ ...(options?.throw === undefined ? {} : { throw: options.throw }),
297
+ });
298
+ }
299
+
300
+ function stripEntries(
301
+ value: unknown,
302
+ fieldFor: (key: string) => AnyValidator | undefined,
303
+ ): Record<string, unknown> {
304
+ const kept = Object.entries(value as object).flatMap(([key, item]) => {
305
+ const field = fieldFor(key);
306
+ return field === undefined || item === undefined
307
+ ? []
308
+ : [[key, stripUnknownFields(field, item)] as const];
309
+ });
310
+ return Object.fromEntries(kept);
311
+ }
312
+
313
+ function stripUnknownFields(validator: AnyValidator, value: unknown): unknown {
314
+ if (value === undefined) return value;
315
+ if (validator.kind === "array") {
316
+ const element: AnyValidator = validator.element;
317
+ return (value as unknown[]).map((item) =>
318
+ stripUnknownFields(element, item),
319
+ );
320
+ }
321
+ if (validator.kind === "object") {
322
+ const fields: Record<string, AnyValidator | undefined> = validator.fields;
323
+ return stripEntries(value, (key) =>
324
+ Object.hasOwn(fields, key) ? fields[key] : undefined,
325
+ );
326
+ }
327
+ if (validator.kind === "record") {
328
+ const entryValidator: AnyValidator = validator.value;
329
+ return stripEntries(value, () => entryValidator);
330
+ }
331
+ if (validator.kind === "union") {
332
+ const members: AnyValidator[] = validator.members;
333
+ // Prefer a member with no undeclared fields, then any member that matches.
334
+ const member =
335
+ members.find((candidate) => validate(candidate, value)) ??
336
+ members.find((candidate) =>
337
+ validate(candidate, value, { allowUnknownFields: true }),
338
+ );
339
+ /* v8 ignore start -- parse() validated the union first, so one member matches */
340
+ if (member === undefined) throw new Error("No matching member in union");
341
+ /* v8 ignore stop */
342
+ return stripUnknownFields(member, value);
343
+ }
344
+ return value;
345
+ }
346
+
347
+ /**
348
+ * Validates a value and returns a copy without the object fields the validator
349
+ * does not declare (recursively, through arrays, records and unions).
350
+ *
351
+ * @param validator - Any Convex validator (`v.*`)
352
+ * @param value - The value to parse
353
+ * @returns The value with undeclared fields removed
354
+ * @throws {ValidationError} When the value does not match
355
+ * @example
356
+ * const seed = parse(seedValidator, JSON.parse(raw));
357
+ */
358
+ export function parse<TValidator extends AnyValidator>(
359
+ validator: TValidator,
360
+ value: unknown,
361
+ ): Infer<TValidator> {
362
+ validate(validator, value, { allowUnknownFields: true, throw: true });
363
+ return stripUnknownFields(validator, value);
364
+ }
365
+
366
+ /** The `_id` and `_creationTime` validators of a table's documents. */
367
+ export type SystemFields<TTableName extends string> = {
368
+ _creationTime: VFloat64;
369
+ _id: VId<GenericId<TTableName>>;
370
+ };
371
+
372
+ /** The validator {@link doc} returns: the table validator plus `TFields`. */
373
+ export type AddFieldsToValidator<
374
+ TValidator extends AnyValidator,
375
+ TFields extends PropertyValidators,
376
+ > =
377
+ TValidator extends VObject<infer TType, infer TObjectFields, infer TOptional>
378
+ ? VObject<
379
+ Expand<ObjectType<TFields> & TType>,
380
+ Expand<TFields & TObjectFields>,
381
+ TOptional
382
+ >
383
+ : Validator<
384
+ Expand<ObjectType<TFields> & TValidator["type"]>,
385
+ TValidator["isOptional"],
386
+ {
387
+ [TProperty in keyof TFields & string]:
388
+ `${TProperty}.${TFields[TProperty]["fieldPaths"]}` | TProperty;
389
+ }[keyof TFields & string] &
390
+ string &
391
+ TValidator["fieldPaths"]
392
+ >;
393
+
394
+ function withSystemFields(
395
+ validator: AnyValidator,
396
+ system: PropertyValidators,
397
+ ): AnyValidator {
398
+ if (validator.kind === "object") {
399
+ return v.object({ ...validator.fields, ...system });
400
+ }
401
+ if (validator.kind !== "union") {
402
+ throw new Error(
403
+ "Only object and union validators are supported for documents",
404
+ );
405
+ }
406
+ const members: AnyValidator[] = validator.members;
407
+ return v.union(...members.map((member) => withSystemFields(member, system)));
408
+ }
409
+
410
+ /**
411
+ * Builds the validator for a whole document of a schema table: the table's
412
+ * validator plus `_id` and `_creationTime`. A union table gets the system
413
+ * fields on every member.
414
+ *
415
+ * @param schema - The `defineSchema(...)` result
416
+ * @param tableName - A table of that schema
417
+ * @returns An object (or union of objects) validator for the table's documents
418
+ * @throws {Error} When the table validator is neither an object nor a union
419
+ * @example
420
+ * returns: v.array(doc(schema, "users"))
421
+ */
422
+ // eslint-disable-next-line unicorn/prevent-abbreviations -- public name kept from convex-helpers, so imports change their path and nothing else
423
+ export function doc<
424
+ TSchema extends AnySchema,
425
+ TTableName extends TableNamesInDataModel<
426
+ DataModelFromSchemaDefinition<TSchema>
427
+ >,
428
+ >(
429
+ schema: TSchema,
430
+ tableName: TTableName,
431
+ ): AddFieldsToValidator<
432
+ TSchema["tables"][TTableName]["validator"],
433
+ SystemFields<TTableName>
434
+ > {
435
+ // Same field order as convex-helpers: `_id` first.
436
+ // eslint-disable-next-line perfectionist/sort-objects -- keeps upstream's field order in the generated validator
437
+ const system = { _id: v.id(tableName), _creationTime: v.number() };
438
+ const tables = schema.tables as Record<string, { validator: AnyValidator }>;
439
+ return withSystemFields(
440
+ (tables[tableName] as { validator: AnyValidator }).validator,
441
+ system,
442
+ ) as AddFieldsToValidator<
443
+ TSchema["tables"][TTableName]["validator"],
444
+ SystemFields<TTableName>
445
+ >;
446
+ }