@vllnt/convex-helpers 0.2.0-canary.578a409 → 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.
- package/CHANGELOG.md +12 -1
- package/NOTICE +214 -0
- package/README.md +66 -9
- package/dist/builders.d.ts +104 -0
- package/dist/builders.d.ts.map +1 -0
- package/dist/builders.js +151 -0
- package/dist/builders.js.map +1 -0
- package/dist/validators.d.ts +89 -0
- package/dist/validators.d.ts.map +1 -0
- package/dist/validators.js +294 -0
- package/dist/validators.js.map +1 -0
- package/docs/API.md +63 -19
- package/llms.txt +5 -4
- package/package.json +11 -1
- package/src/builders.ts +475 -0
- package/src/validators.ts +446 -0
|
@@ -0,0 +1,89 @@
|
|
|
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
|
+
import type { DataModelFromSchemaDefinition, SchemaDefinition, TableNamesInDataModel } from "convex/server";
|
|
15
|
+
import type { GenericId, Infer, ObjectType, PropertyValidators, Validator, VFloat64, VId, VObject } from "convex/values";
|
|
16
|
+
/** Any Convex validator. */
|
|
17
|
+
export type AnyValidator = Validator<any, any, any>;
|
|
18
|
+
type AnySchema = SchemaDefinition<any, boolean>;
|
|
19
|
+
type Expand<TObject> = TObject extends Record<string, unknown> ? {
|
|
20
|
+
[Key in keyof TObject]: TObject[Key];
|
|
21
|
+
} : never;
|
|
22
|
+
/** Options for the runtime check. */
|
|
23
|
+
export type ValidateOptions = {
|
|
24
|
+
/** Accept object fields the validator does not declare. */
|
|
25
|
+
allowUnknownFields?: boolean;
|
|
26
|
+
/** Throw a {@link ValidationError} instead of returning `false`. */
|
|
27
|
+
throw?: boolean;
|
|
28
|
+
};
|
|
29
|
+
/** Thrown on a mismatch when called with `throw: true`, and by {@link parse}. */
|
|
30
|
+
export declare class ValidationError extends Error {
|
|
31
|
+
expected: string;
|
|
32
|
+
got: string;
|
|
33
|
+
path?: string | undefined;
|
|
34
|
+
/**
|
|
35
|
+
* @param expected - The expected kind or literal value
|
|
36
|
+
* @param got - What the value held instead
|
|
37
|
+
* @param path - Path of the failing value inside the checked value
|
|
38
|
+
*/
|
|
39
|
+
constructor(expected: string, got: string, path?: string | undefined);
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Checks a value against a Convex validator at runtime.
|
|
43
|
+
*
|
|
44
|
+
* @param validator - Any Convex validator (`v.*`)
|
|
45
|
+
* @param value - The value to check
|
|
46
|
+
* @param options - `throw` to throw instead of returning `false`;
|
|
47
|
+
* `allowUnknownFields` to accept object fields the validator does not declare
|
|
48
|
+
* @returns Whether the value matches; narrows the value's type
|
|
49
|
+
* @throws {ValidationError} With `throw: true`, on the first mismatch
|
|
50
|
+
* @example
|
|
51
|
+
* if (validate(policyValidator, reply, { throw: true })) use(reply);
|
|
52
|
+
*/
|
|
53
|
+
export declare function validate<TValidator extends AnyValidator>(validator: TValidator, value: unknown, options?: ValidateOptions): value is TValidator["type"];
|
|
54
|
+
/**
|
|
55
|
+
* Validates a value and returns a copy without the object fields the validator
|
|
56
|
+
* does not declare (recursively, through arrays, records and unions).
|
|
57
|
+
*
|
|
58
|
+
* @param validator - Any Convex validator (`v.*`)
|
|
59
|
+
* @param value - The value to parse
|
|
60
|
+
* @returns The value with undeclared fields removed
|
|
61
|
+
* @throws {ValidationError} When the value does not match
|
|
62
|
+
* @example
|
|
63
|
+
* const seed = parse(seedValidator, JSON.parse(raw));
|
|
64
|
+
*/
|
|
65
|
+
export declare function parse<TValidator extends AnyValidator>(validator: TValidator, value: unknown): Infer<TValidator>;
|
|
66
|
+
/** The `_id` and `_creationTime` validators of a table's documents. */
|
|
67
|
+
export type SystemFields<TTableName extends string> = {
|
|
68
|
+
_creationTime: VFloat64;
|
|
69
|
+
_id: VId<GenericId<TTableName>>;
|
|
70
|
+
};
|
|
71
|
+
/** The validator {@link doc} returns: the table validator plus `TFields`. */
|
|
72
|
+
export type AddFieldsToValidator<TValidator extends AnyValidator, TFields extends PropertyValidators> = TValidator extends VObject<infer TType, infer TObjectFields, infer TOptional> ? VObject<Expand<ObjectType<TFields> & TType>, Expand<TFields & TObjectFields>, TOptional> : Validator<Expand<ObjectType<TFields> & TValidator["type"]>, TValidator["isOptional"], {
|
|
73
|
+
[TProperty in keyof TFields & string]: `${TProperty}.${TFields[TProperty]["fieldPaths"]}` | TProperty;
|
|
74
|
+
}[keyof TFields & string] & string & TValidator["fieldPaths"]>;
|
|
75
|
+
/**
|
|
76
|
+
* Builds the validator for a whole document of a schema table: the table's
|
|
77
|
+
* validator plus `_id` and `_creationTime`. A union table gets the system
|
|
78
|
+
* fields on every member.
|
|
79
|
+
*
|
|
80
|
+
* @param schema - The `defineSchema(...)` result
|
|
81
|
+
* @param tableName - A table of that schema
|
|
82
|
+
* @returns An object (or union of objects) validator for the table's documents
|
|
83
|
+
* @throws {Error} When the table validator is neither an object nor a union
|
|
84
|
+
* @example
|
|
85
|
+
* returns: v.array(doc(schema, "users"))
|
|
86
|
+
*/
|
|
87
|
+
export declare function doc<TSchema extends AnySchema, TTableName extends TableNamesInDataModel<DataModelFromSchemaDefinition<TSchema>>>(schema: TSchema, tableName: TTableName): AddFieldsToValidator<TSchema["tables"][TTableName]["validator"], SystemFields<TTableName>>;
|
|
88
|
+
export {};
|
|
89
|
+
//# sourceMappingURL=validators.d.ts.map
|
|
@@ -0,0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AAO,CAAC,QAAQ,CAAC,CAAC,UAAU,CAAC,CAAC,WAAW,CAAC,EAC1C,YAAY,CAAC,UAAU,CAAC,CACzB,CAYA"}
|
|
@@ -0,0 +1,294 @@
|
|
|
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
|
+
import { v } from "convex/values";
|
|
15
|
+
/** Thrown on a mismatch when called with `throw: true`, and by {@link parse}. */
|
|
16
|
+
export class ValidationError extends Error {
|
|
17
|
+
expected;
|
|
18
|
+
got;
|
|
19
|
+
path;
|
|
20
|
+
/**
|
|
21
|
+
* @param expected - The expected kind or literal value
|
|
22
|
+
* @param got - What the value held instead
|
|
23
|
+
* @param path - Path of the failing value inside the checked value
|
|
24
|
+
*/
|
|
25
|
+
constructor(expected, got, path) {
|
|
26
|
+
const where = path === undefined || path === "" ? "" : ` for ${path}`;
|
|
27
|
+
super(`Validator error${where}: Expected \`${expected}\`, got \`${got}\``);
|
|
28
|
+
this.expected = expected;
|
|
29
|
+
this.got = got;
|
|
30
|
+
this.path = path;
|
|
31
|
+
this.name = "ValidationError";
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
function joinPath(path, key) {
|
|
35
|
+
return path === undefined || path === "" ? key : `${path}.${key}`;
|
|
36
|
+
}
|
|
37
|
+
function describeValue(value) {
|
|
38
|
+
return value === null ? "null" : typeof value;
|
|
39
|
+
}
|
|
40
|
+
/** The first failure `check` returns over `items`, checking in order and stopping there. */
|
|
41
|
+
function firstFailure(items, check) {
|
|
42
|
+
let failure;
|
|
43
|
+
items.some((item, index) => {
|
|
44
|
+
failure = check(item, index);
|
|
45
|
+
return failure !== undefined;
|
|
46
|
+
});
|
|
47
|
+
return failure;
|
|
48
|
+
}
|
|
49
|
+
function plainObjectFailure(value) {
|
|
50
|
+
const prototype = Object.getPrototypeOf(value);
|
|
51
|
+
if (prototype === null || prototype === Object.prototype)
|
|
52
|
+
return undefined;
|
|
53
|
+
const name = prototype.constructor
|
|
54
|
+
?.name;
|
|
55
|
+
// Objects from another realm (a Node.js `vm` context) are still plain.
|
|
56
|
+
if (name === "Object")
|
|
57
|
+
return undefined;
|
|
58
|
+
return {
|
|
59
|
+
expected: typeof name === "string" && name !== "" ? name : "object",
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
function primitive(test, expected) {
|
|
63
|
+
return (validator, value) => test(value) ? undefined : { expected: expected ?? validator.kind };
|
|
64
|
+
}
|
|
65
|
+
const accept = () => undefined;
|
|
66
|
+
function walkValue(validator, value, walk) {
|
|
67
|
+
const failure = check(validator, value, walk);
|
|
68
|
+
if (failure === undefined)
|
|
69
|
+
return true;
|
|
70
|
+
if (walk.throw === true) {
|
|
71
|
+
throw new ValidationError(failure.expected, failure.got ?? describeValue(value), walk.path);
|
|
72
|
+
}
|
|
73
|
+
return false;
|
|
74
|
+
}
|
|
75
|
+
const checkArray = (validator, value, walk) => {
|
|
76
|
+
if (!Array.isArray(value))
|
|
77
|
+
return { expected: "array" };
|
|
78
|
+
// Array.from turns holes into `undefined`, so every slot of a sparse array
|
|
79
|
+
// goes through the element check.
|
|
80
|
+
return firstFailure([...value], (element, index) => walkValue(validator.element, element, {
|
|
81
|
+
...walk,
|
|
82
|
+
path: `${walk.path ?? ""}[${String(index)}]`,
|
|
83
|
+
})
|
|
84
|
+
? undefined
|
|
85
|
+
: { expected: validator.element.kind });
|
|
86
|
+
};
|
|
87
|
+
const checkLiteral = (validator, value) => {
|
|
88
|
+
if (value === validator.value)
|
|
89
|
+
return;
|
|
90
|
+
const scalar = ["bigint", "boolean", "number", "string"].includes(typeof value);
|
|
91
|
+
return {
|
|
92
|
+
expected: String(validator.value),
|
|
93
|
+
...(scalar ? { got: `"${String(value)}"` } : {}),
|
|
94
|
+
};
|
|
95
|
+
};
|
|
96
|
+
function unknownFieldFailure(fields, record, walk) {
|
|
97
|
+
const unknown = Object.entries(record).find(([key, item]) => !Object.hasOwn(fields, key) && item !== undefined);
|
|
98
|
+
if (unknown === undefined)
|
|
99
|
+
return undefined;
|
|
100
|
+
const [key, item] = unknown;
|
|
101
|
+
if (walk.throw === true) {
|
|
102
|
+
throw new ValidationError("nothing", typeof item, joinPath(walk.path, key));
|
|
103
|
+
}
|
|
104
|
+
return { expected: "object" };
|
|
105
|
+
}
|
|
106
|
+
const checkObject = (validator, value, walk) => {
|
|
107
|
+
if (typeof value !== "object" || value === null)
|
|
108
|
+
return { expected: "object" };
|
|
109
|
+
const notPlain = plainObjectFailure(value);
|
|
110
|
+
if (notPlain)
|
|
111
|
+
return notPlain;
|
|
112
|
+
const record = value;
|
|
113
|
+
const fields = validator.fields;
|
|
114
|
+
const fieldFailure = firstFailure(Object.entries(fields), ([key, field]) => walkValue(field, record[key], { ...walk, path: joinPath(walk.path, key) })
|
|
115
|
+
? undefined
|
|
116
|
+
: { expected: "object" });
|
|
117
|
+
if (fieldFailure !== undefined || walk.allowUnknownFields === true) {
|
|
118
|
+
return fieldFailure;
|
|
119
|
+
}
|
|
120
|
+
return unknownFieldFailure(fields, record, walk);
|
|
121
|
+
};
|
|
122
|
+
const checkUnion = (validator, value, walk) => {
|
|
123
|
+
const members = validator.members;
|
|
124
|
+
const errors = [];
|
|
125
|
+
const matched = members.some((member) => {
|
|
126
|
+
try {
|
|
127
|
+
return walkValue(member, value, walk);
|
|
128
|
+
}
|
|
129
|
+
catch (error) {
|
|
130
|
+
// walkValue throws ValidationError and nothing else.
|
|
131
|
+
errors.push(error);
|
|
132
|
+
return false;
|
|
133
|
+
}
|
|
134
|
+
});
|
|
135
|
+
if (matched)
|
|
136
|
+
return;
|
|
137
|
+
// With `throw: true`, report the last member's error, as convex-helpers does.
|
|
138
|
+
const last = errors.at(-1);
|
|
139
|
+
if (last !== undefined)
|
|
140
|
+
throw last;
|
|
141
|
+
return { expected: "union" };
|
|
142
|
+
};
|
|
143
|
+
const checkRecord = (validator, value, walk) => {
|
|
144
|
+
if (typeof value !== "object" || value === null)
|
|
145
|
+
return { expected: "record" };
|
|
146
|
+
const keyValidator = validator.key;
|
|
147
|
+
const entryValidator = validator.value;
|
|
148
|
+
return firstFailure(Object.entries(value), ([key, entry]) => {
|
|
149
|
+
// The wire format drops `undefined` entries, so they pass.
|
|
150
|
+
if (entry === undefined)
|
|
151
|
+
return;
|
|
152
|
+
const entryWalk = { ...walk, path: joinPath(walk.path, key) };
|
|
153
|
+
if (!walkValue(keyValidator, key, entryWalk)) {
|
|
154
|
+
return { expected: keyValidator.kind };
|
|
155
|
+
}
|
|
156
|
+
return walkValue(entryValidator, entry, entryWalk)
|
|
157
|
+
? undefined
|
|
158
|
+
: { expected: entryValidator.kind };
|
|
159
|
+
});
|
|
160
|
+
};
|
|
161
|
+
const checkers = {
|
|
162
|
+
any: accept,
|
|
163
|
+
array: checkArray,
|
|
164
|
+
boolean: primitive((value) => typeof value === "boolean"),
|
|
165
|
+
bytes: primitive((value) => value instanceof ArrayBuffer),
|
|
166
|
+
commitTs: accept,
|
|
167
|
+
float64: primitive((value) => typeof value === "number", "number"),
|
|
168
|
+
function: accept,
|
|
169
|
+
id: primitive((value) => typeof value === "string"),
|
|
170
|
+
int64: primitive((value) => typeof value === "bigint", "bigint"),
|
|
171
|
+
literal: checkLiteral,
|
|
172
|
+
null: primitive((value) => value === null),
|
|
173
|
+
object: checkObject,
|
|
174
|
+
record: checkRecord,
|
|
175
|
+
string: primitive((value) => typeof value === "string"),
|
|
176
|
+
union: checkUnion,
|
|
177
|
+
};
|
|
178
|
+
function check(validator, value, walk) {
|
|
179
|
+
if (value === undefined) {
|
|
180
|
+
return validator.isOptional === "optional"
|
|
181
|
+
? undefined
|
|
182
|
+
: { expected: validator.kind };
|
|
183
|
+
}
|
|
184
|
+
// Kinds this module does not know (from a newer Convex) accept any value.
|
|
185
|
+
const checker = checkers[validator.kind];
|
|
186
|
+
return checker === undefined ? undefined : checker(validator, value, walk);
|
|
187
|
+
}
|
|
188
|
+
// eslint-disable-next-line write-good-comments/write-good-comments -- the example calls the public function by its name
|
|
189
|
+
/**
|
|
190
|
+
* Checks a value against a Convex validator at runtime.
|
|
191
|
+
*
|
|
192
|
+
* @param validator - Any Convex validator (`v.*`)
|
|
193
|
+
* @param value - The value to check
|
|
194
|
+
* @param options - `throw` to throw instead of returning `false`;
|
|
195
|
+
* `allowUnknownFields` to accept object fields the validator does not declare
|
|
196
|
+
* @returns Whether the value matches; narrows the value's type
|
|
197
|
+
* @throws {ValidationError} With `throw: true`, on the first mismatch
|
|
198
|
+
* @example
|
|
199
|
+
* if (validate(policyValidator, reply, { throw: true })) use(reply);
|
|
200
|
+
*/
|
|
201
|
+
export function validate(validator, value, options) {
|
|
202
|
+
if (options !== undefined && "db" in options) {
|
|
203
|
+
throw new Error("validate: the db option is not supported");
|
|
204
|
+
}
|
|
205
|
+
return walkValue(validator, value, {
|
|
206
|
+
...(options?.allowUnknownFields === undefined
|
|
207
|
+
? {}
|
|
208
|
+
: { allowUnknownFields: options.allowUnknownFields }),
|
|
209
|
+
...(options?.throw === undefined ? {} : { throw: options.throw }),
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
function stripEntries(value, fieldFor) {
|
|
213
|
+
const kept = Object.entries(value).flatMap(([key, item]) => {
|
|
214
|
+
const field = fieldFor(key);
|
|
215
|
+
return field === undefined || item === undefined
|
|
216
|
+
? []
|
|
217
|
+
: [[key, stripUnknownFields(field, item)]];
|
|
218
|
+
});
|
|
219
|
+
return Object.fromEntries(kept);
|
|
220
|
+
}
|
|
221
|
+
function stripUnknownFields(validator, value) {
|
|
222
|
+
if (value === undefined)
|
|
223
|
+
return value;
|
|
224
|
+
if (validator.kind === "array") {
|
|
225
|
+
const element = validator.element;
|
|
226
|
+
return value.map((item) => stripUnknownFields(element, item));
|
|
227
|
+
}
|
|
228
|
+
if (validator.kind === "object") {
|
|
229
|
+
const fields = validator.fields;
|
|
230
|
+
return stripEntries(value, (key) => Object.hasOwn(fields, key) ? fields[key] : undefined);
|
|
231
|
+
}
|
|
232
|
+
if (validator.kind === "record") {
|
|
233
|
+
const entryValidator = validator.value;
|
|
234
|
+
return stripEntries(value, () => entryValidator);
|
|
235
|
+
}
|
|
236
|
+
if (validator.kind === "union") {
|
|
237
|
+
const members = validator.members;
|
|
238
|
+
// Prefer a member with no undeclared fields, then any member that matches.
|
|
239
|
+
const member = members.find((candidate) => validate(candidate, value)) ??
|
|
240
|
+
members.find((candidate) => validate(candidate, value, { allowUnknownFields: true }));
|
|
241
|
+
/* v8 ignore start -- parse() validated the union first, so one member matches */
|
|
242
|
+
if (member === undefined)
|
|
243
|
+
throw new Error("No matching member in union");
|
|
244
|
+
/* v8 ignore stop */
|
|
245
|
+
return stripUnknownFields(member, value);
|
|
246
|
+
}
|
|
247
|
+
return value;
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* Validates a value and returns a copy without the object fields the validator
|
|
251
|
+
* does not declare (recursively, through arrays, records and unions).
|
|
252
|
+
*
|
|
253
|
+
* @param validator - Any Convex validator (`v.*`)
|
|
254
|
+
* @param value - The value to parse
|
|
255
|
+
* @returns The value with undeclared fields removed
|
|
256
|
+
* @throws {ValidationError} When the value does not match
|
|
257
|
+
* @example
|
|
258
|
+
* const seed = parse(seedValidator, JSON.parse(raw));
|
|
259
|
+
*/
|
|
260
|
+
export function parse(validator, value) {
|
|
261
|
+
validate(validator, value, { allowUnknownFields: true, throw: true });
|
|
262
|
+
return stripUnknownFields(validator, value);
|
|
263
|
+
}
|
|
264
|
+
function withSystemFields(validator, system) {
|
|
265
|
+
if (validator.kind === "object") {
|
|
266
|
+
return v.object({ ...validator.fields, ...system });
|
|
267
|
+
}
|
|
268
|
+
if (validator.kind !== "union") {
|
|
269
|
+
throw new Error("Only object and union validators are supported for documents");
|
|
270
|
+
}
|
|
271
|
+
const members = validator.members;
|
|
272
|
+
return v.union(...members.map((member) => withSystemFields(member, system)));
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* Builds the validator for a whole document of a schema table: the table's
|
|
276
|
+
* validator plus `_id` and `_creationTime`. A union table gets the system
|
|
277
|
+
* fields on every member.
|
|
278
|
+
*
|
|
279
|
+
* @param schema - The `defineSchema(...)` result
|
|
280
|
+
* @param tableName - A table of that schema
|
|
281
|
+
* @returns An object (or union of objects) validator for the table's documents
|
|
282
|
+
* @throws {Error} When the table validator is neither an object nor a union
|
|
283
|
+
* @example
|
|
284
|
+
* returns: v.array(doc(schema, "users"))
|
|
285
|
+
*/
|
|
286
|
+
// eslint-disable-next-line unicorn/prevent-abbreviations -- public name kept from convex-helpers, so imports change their path and nothing else
|
|
287
|
+
export function doc(schema, tableName) {
|
|
288
|
+
// Same field order as convex-helpers: `_id` first.
|
|
289
|
+
// eslint-disable-next-line perfectionist/sort-objects -- keeps upstream's field order in the generated validator
|
|
290
|
+
const system = { _id: v.id(tableName), _creationTime: v.number() };
|
|
291
|
+
const tables = schema.tables;
|
|
292
|
+
return withSystemFields(tables[tableName].validator, system);
|
|
293
|
+
}
|
|
294
|
+
//# sourceMappingURL=validators.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"validators.js","sourceRoot":"","sources":["../src/validators.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAiBH,OAAO,EAAE,CAAC,EAAE,MAAM,eAAe,CAAC;AAqBlC,iFAAiF;AACjF,MAAM,OAAO,eAAgB,SAAQ,KAAK;IAO/B,QAAQ;IAC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,CAAC,MAAM,EAAE,EAAE,CAAC,gBAAgB,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC;AAC/E,CAAC;AAED;;;;;;;;;;;GAWG;AACH,gJAAgJ;AAChJ,MAAM,UAAU,GAAG,CAMjB,MAAe,EACf,SAAqB;IAKrB,mDAAmD;IACnD,iHAAiH;IACjH,MAAM,MAAM,GAAG,EAAE,GAAG,EAAE,CAAC,CAAC,EAAE,CAAC,SAAS,CAAC,EAAE,aAAa,EAAE,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC;IACnE,MAAM,MAAM,GAAG,MAAM,CAAC,MAAqD,CAAC;IAC5E,OAAO,gBAAgB,CACpB,MAAM,CAAC,SAAS,CAAiC,CAAC,SAAS,EAC5D,MAAM,CAIP,CAAC;AACJ,CAAC"}
|
package/docs/API.md
CHANGED
|
@@ -2,10 +2,11 @@
|
|
|
2
2
|
|
|
3
3
|
**Compatibility:** `convex@^1.45.0`; ESM-only.
|
|
4
4
|
|
|
5
|
-
**Availability:** this reference follows current main. `./better-auth
|
|
6
|
-
`./identity` first ship in `0.2.0`; `0.1.0` has
|
|
7
|
-
`./mcp`. See the
|
|
8
|
-
modules are not
|
|
5
|
+
**Availability:** this reference follows current main. `./better-auth`,
|
|
6
|
+
`./identity`, `./builders` and `./validators` first ship in `0.2.0`; `0.1.0` has
|
|
7
|
+
only the root utilities and `./mcp`. See the
|
|
8
|
+
[installation guide](../README.md#installation). Planned modules are not
|
|
9
|
+
exports.
|
|
9
10
|
|
|
10
11
|
This library provides pure functions and host-`ctx` glue utilities. It is a
|
|
11
12
|
type-B helpers library — not a sandboxed Convex component — and runs with the
|
|
@@ -282,23 +283,66 @@ const user = await getOrCreateFromAuth(ctx, {
|
|
|
282
283
|
});
|
|
283
284
|
```
|
|
284
285
|
|
|
286
|
+
## `./builders` (shipped)
|
|
287
|
+
|
|
288
|
+
Wrap a Convex function builder so every function made with it receives extra
|
|
289
|
+
`ctx` fields and, optionally, consumes extra args. Signatures and runtime
|
|
290
|
+
behaviour match `convex-helpers/server/customFunctions` 0.1.124; a parity test
|
|
291
|
+
runs both on the same convex-test backend.
|
|
292
|
+
|
|
293
|
+
| Export | Contract |
|
|
294
|
+
| ----------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
295
|
+
| `customQuery(query, customization)` | Returns a builder used like `query(...)`. Accepts `query`, `internalQuery` or `queryGeneric`. |
|
|
296
|
+
| `customMutation(mutation, customization)` | Same for mutation builders. |
|
|
297
|
+
| `customAction(action, customization)` | Same for action builders. |
|
|
298
|
+
| `customCtx(modifyCtx)` | Customization with no args: `modifyCtx(ctx, extra)` returns the ctx fields to add. `extra` holds the definition's keys other than `args`, `handler` and `returns`. |
|
|
299
|
+
| `Customization` | `{ args, input }`. `args` (property validators) are merged into the function's args and taken out of the handler's args; `input(ctx, consumedArgs, extra)` returns `{ ctx, args, onSuccess? }`. `onSuccess` runs after the handler. |
|
|
300
|
+
| `CustomBuilder`, `CustomCtx<Builder>` | Types of a custom builder and of the ctx its handlers receive. |
|
|
301
|
+
|
|
302
|
+
Merging fails with an error when a consumed arg and a function arg share a name
|
|
303
|
+
but not a validator kind, when the function's args validator is neither an
|
|
304
|
+
object nor a union, or when the customization consumes args but the function
|
|
305
|
+
declares none. Builders add no authorization of their own.
|
|
306
|
+
|
|
307
|
+
## `./validators` (shipped)
|
|
308
|
+
|
|
309
|
+
| Export | Contract |
|
|
310
|
+
| -------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
311
|
+
| `validate(validator, value, options?)` | `true` when `value` matches (type guard). `options.throw` throws `ValidationError` on the first mismatch; `options.allowUnknownFields` accepts undeclared object fields. Undefined fields pass. |
|
|
312
|
+
| `parse(validator, value)` | Validates with unknown fields allowed, throws `ValidationError` on mismatch, and returns a copy without undeclared fields (through arrays, records and unions). |
|
|
313
|
+
| `doc(schema, tableName)` | The table's validator plus `_id` and `_creationTime`; union tables get them on every member. Throws for other validator kinds. |
|
|
314
|
+
| `ValidationError` | Has `expected`, `got` and an optional `path`; the message names all three. |
|
|
315
|
+
|
|
316
|
+
Behaviour matches `convex-helpers/validators` 0.1.124 for these exports, held by
|
|
317
|
+
a parity test, with two fail-closed differences:
|
|
318
|
+
|
|
319
|
+
- Declared object fields are looked up as own properties. Upstream also treats
|
|
320
|
+
inherited names (`constructor`, `toString`, `__proto__`) as declared, so it
|
|
321
|
+
accepts and keeps them; here they are unknown fields (rejected by a strict
|
|
322
|
+
`validate`, dropped by `parse`).
|
|
323
|
+
- The `db` option (checking a `v.id`'s table) is refused with an error instead
|
|
324
|
+
of supported; `v.id` checks for a string.
|
|
325
|
+
|
|
326
|
+
`ValidationError.expected` is always a string (upstream passes a literal's raw
|
|
327
|
+
value); messages are identical.
|
|
328
|
+
|
|
285
329
|
## Planned modules
|
|
286
330
|
|
|
287
331
|
The following modules are on the roadmap but not yet shipped. See
|
|
288
332
|
[ROADMAP.md](../ROADMAP.md) for milestones and exit criteria.
|
|
289
333
|
|
|
290
|
-
| Module | Status
|
|
291
|
-
| ----------------- |
|
|
292
|
-
| `./builders` |
|
|
293
|
-
| `./errors` | [planned]
|
|
294
|
-
| `./auth` | shipped as `./identity`
|
|
295
|
-
| `./env` | [planned]
|
|
296
|
-
| `./tracing` | [planned]
|
|
297
|
-
| `./testing` | [planned]
|
|
298
|
-
| `./relationships` | [planned]
|
|
299
|
-
| `./validators` |
|
|
300
|
-
| `./pagination` | [planned]
|
|
301
|
-
| `./rls` | [planned]
|
|
302
|
-
| `./triggers` | [planned]
|
|
303
|
-
| `./http` | [planned]
|
|
304
|
-
| `./react` | [planned]
|
|
334
|
+
| Module | Status | Description |
|
|
335
|
+
| ----------------- | ------------------------ | --------------------------------------------------------- |
|
|
336
|
+
| `./builders` | shipped (`0.2.0`) | composition helpers remain planned |
|
|
337
|
+
| `./errors` | [planned] | `AppError(code)` + HTTP-status map + `toResponse()` |
|
|
338
|
+
| `./auth` | shipped as `./identity` | see `./identity` |
|
|
339
|
+
| `./env` | [planned] | `defineEnv(zodSchema)` cold-start validation |
|
|
340
|
+
| `./tracing` | [planned] | span emit + `traceparent` propagation |
|
|
341
|
+
| `./testing` | [planned] | `register(t)` + fixture factories + `withIdentity` |
|
|
342
|
+
| `./relationships` | [planned] | `getOneFrom`/`getManyFrom`/`getManyVia` + `asyncMap` |
|
|
343
|
+
| `./validators` | partly shipped (`0.2.0`) | `partial`/`typedV`/`literals` + zod bridge remain planned |
|
|
344
|
+
| `./pagination` | [planned] | `getPage`/`mergedStream`/`filter` |
|
|
345
|
+
| `./rls` | [planned] | `RowLevelSecurity` reader/writer wrappers |
|
|
346
|
+
| `./triggers` | [planned] | atomic in-transaction denormalization / cascade delete |
|
|
347
|
+
| `./http` | [planned] | `corsRouter`/`jsonResponse`/`resolveBearer`/hono adapter |
|
|
348
|
+
| `./react` | [planned] | optional tree-shakeable front-end tooling layer |
|
package/llms.txt
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
Convex backends. It provides pure functions and host-`ctx` glue utilities that run with the host's
|
|
8
8
|
`ctx` — no own tables, no `app.use()` mounting. The library targets `convex@^1.45.0`. Stateful
|
|
9
9
|
concerns (rate limiting, idempotency, flags, etc.) belong in `@convex-dev/*` or `@vllnt/convex-*`
|
|
10
|
-
components. Optional entries: `./better-auth` (trusted origins + HTTPS cookies), `./identity` (`getOrCreateFromAuth` / `retargetRows`), and a tree-shakeable `./mcp` entry exposes Convex functions as Model Context
|
|
10
|
+
components. Optional entries: `./better-auth` (trusted origins + HTTPS cookies), `./identity` (`getOrCreateFromAuth` / `retargetRows`), `./builders` (`customQuery` / `customMutation` / `customAction` / `customCtx`, matching `convex-helpers/server/customFunctions`), `./validators` (`validate` / `parse` / `doc`, matching `convex-helpers/validators`; it refuses the `db` id-table option and treats inherited names such as `constructor` as unknown fields), and a tree-shakeable `./mcp` entry exposes Convex functions as Model Context
|
|
11
11
|
Protocol tools (`@vllnt/convex-helpers/mcp`); it needs the optional peer deps
|
|
12
12
|
`@modelcontextprotocol/sdk` and `zod`, so backend-only consumers pull neither.
|
|
13
13
|
|
|
@@ -20,12 +20,13 @@ before hooks deny dispatch and raw exceptions are not logged. `retargetRows` pro
|
|
|
20
20
|
is not an authorized account merge. Hosts install/configure Better Auth themselves.
|
|
21
21
|
Origin helpers validate syntax, not deployment ownership; cross-site cookie attributes
|
|
22
22
|
are not CSRF protection. Existing identity integration tests use convex-test mocks,
|
|
23
|
-
not real Better Auth or backend OCC proof.
|
|
23
|
+
not real Better Auth or backend OCC proof. Errors/env/tracing remain planned. Builders add no authorization: the host's
|
|
24
|
+
`input` decides who may call.
|
|
24
25
|
|
|
25
26
|
## Release channels
|
|
26
27
|
|
|
27
|
-
This index describes current main. `./better-auth
|
|
28
|
-
`0.2.0`; `0.1.0` has only the root utilities and `./mcp`. Prereleases are published
|
|
28
|
+
This index describes current main. `./better-auth`, `./identity`, `./builders` and
|
|
29
|
+
`./validators` first ship in `0.2.0`; `0.1.0` has only the root utilities and `./mcp`. Prereleases are published
|
|
29
30
|
to the `canary` dist-tag; pin and test them before deployment.
|
|
30
31
|
MCP requires optional peers `@modelcontextprotocol/sdk@^1.29.0` and `zod@^4.3.6`;
|
|
31
32
|
the package is ESM-only and requires `convex@^1.45.0`.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vllnt/convex-helpers",
|
|
3
|
-
"version": "0.2.0
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Typed Convex host-side utilities, trusted-origin and cookie configuration helpers, identity-row glue, and optional MCP tools.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
"!src/**/*.test.ts",
|
|
12
12
|
"docs",
|
|
13
13
|
"CHANGELOG.md",
|
|
14
|
+
"NOTICE",
|
|
14
15
|
"llms.txt",
|
|
15
16
|
"!src/**/*.spec.*"
|
|
16
17
|
],
|
|
@@ -31,6 +32,14 @@
|
|
|
31
32
|
"./identity": {
|
|
32
33
|
"types": "./dist/identity.d.ts",
|
|
33
34
|
"default": "./dist/identity.js"
|
|
35
|
+
},
|
|
36
|
+
"./builders": {
|
|
37
|
+
"types": "./dist/builders.d.ts",
|
|
38
|
+
"default": "./dist/builders.js"
|
|
39
|
+
},
|
|
40
|
+
"./validators": {
|
|
41
|
+
"types": "./dist/validators.d.ts",
|
|
42
|
+
"default": "./dist/validators.js"
|
|
34
43
|
}
|
|
35
44
|
},
|
|
36
45
|
"types": "./dist/index.d.ts",
|
|
@@ -70,6 +79,7 @@
|
|
|
70
79
|
"@vllnt/eslint-config": "2.1.0",
|
|
71
80
|
"@vllnt/typescript": "2.0.0",
|
|
72
81
|
"convex": "^1.50.0",
|
|
82
|
+
"convex-helpers": "0.1.124",
|
|
73
83
|
"convex-test": "^0.0.71",
|
|
74
84
|
"eslint": "^9.39.5",
|
|
75
85
|
"prettier": "^3.10.1",
|