@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,475 @@
1
+ /**
2
+ * @module @vllnt/convex-helpers/builders
3
+ * Wrap Convex `query` / `mutation` / `action` builders so every function made
4
+ * with them gets extra `ctx` fields (and optionally consumes extra args), e.g.
5
+ * an authenticated user resolved once in a shared `input`.
6
+ *
7
+ * Adapted, with changes, from `convex-helpers/server/customFunctions` 0.1.124
8
+ * (Apache-2.0, see NOTICE): same signatures and runtime behaviour for
9
+ * `customQuery`, `customMutation`, `customAction` and `customCtx`; the
10
+ * `CustomBuilder`, `Customization` and `Registration` types follow upstream's.
11
+ * Unlike upstream, a customization must supply both `args` and `input` (the
12
+ * types already require them). `tests/builders-parity.test.ts`
13
+ * runs both side by side.
14
+ */
15
+
16
+ import type {
17
+ ActionBuilder,
18
+ ArgsArrayForOptionalValidator,
19
+ ArgsArrayToObject,
20
+ DefaultArgsForOptionalValidator,
21
+ DefaultFunctionArgs,
22
+ FunctionVisibility,
23
+ GenericActionCtx,
24
+ GenericDataModel,
25
+ GenericMutationCtx,
26
+ GenericQueryCtx,
27
+ MutationBuilder,
28
+ QueryBuilder,
29
+ RegisteredAction,
30
+ RegisteredMutation,
31
+ RegisteredQuery,
32
+ ReturnValueForOptionalValidator,
33
+ } from "convex/server";
34
+ import type {
35
+ GenericValidator,
36
+ ObjectType,
37
+ PropertyValidators,
38
+ Validator,
39
+ } from "convex/values";
40
+ import { asObjectValidator, v } from "convex/values";
41
+
42
+ /* eslint-disable @typescript-eslint/no-explicit-any -- the public convex-helpers signatures constrain on Record<string, any> and Validator<any, any, any> */
43
+ type AnyRecord = Record<string, any>;
44
+ type AnyValidator = Validator<any, any, any>;
45
+
46
+ /** What a customization's `input` returns. */
47
+ export type CustomInput<TCtx, TCustomCtx, TCustomMadeArguments> = {
48
+ args: TCustomMadeArguments;
49
+ ctx: TCustomCtx;
50
+ /** Runs after the handler succeeds, with the original ctx and args. */
51
+ onSuccess?: (outcome: {
52
+ args: Record<string, unknown>;
53
+ ctx: TCtx;
54
+ result: unknown;
55
+ }) => Promise<void> | void;
56
+ };
57
+
58
+ /**
59
+ * How a custom builder changes each function: the `args` it consumes (taken
60
+ * out of the handler's args) and an `input` that returns ctx fields and args
61
+ * to add.
62
+ */
63
+ export type Customization<
64
+ TCtx extends AnyRecord,
65
+ TCustomArgumentsValidator extends PropertyValidators,
66
+ TCustomCtx extends AnyRecord,
67
+ TCustomMadeArguments extends AnyRecord,
68
+ TExtraArguments extends AnyRecord = AnyRecord,
69
+ > = {
70
+ args: TCustomArgumentsValidator;
71
+ input: (
72
+ ctx: TCtx,
73
+ arguments_: ObjectType<TCustomArgumentsValidator>,
74
+ extra: TExtraArguments,
75
+ ) =>
76
+ | CustomInput<TCtx, TCustomCtx, TCustomMadeArguments>
77
+ | Promise<CustomInput<TCtx, TCustomCtx, TCustomMadeArguments>>;
78
+ };
79
+
80
+ /**
81
+ * Builds a customization that adds ctx fields and leaves args alone.
82
+ * `modifyCtx` receives the original ctx and the definition's extra properties
83
+ * (all keys but `args`, `handler` and `returns`).
84
+ *
85
+ * @param modifyCtx - Returns the ctx fields to add (may be async)
86
+ * @returns A customization for {@link customQuery}, {@link customMutation} or {@link customAction}
87
+ * @example
88
+ * const authQuery = customQuery(query, customCtx(async (ctx) => ({ user: await requireUser(ctx) })));
89
+ */
90
+ export function customCtx<
91
+ TInCtx extends AnyRecord,
92
+ TOutCtx extends AnyRecord,
93
+ TExtraArguments extends AnyRecord = AnyRecord,
94
+ >(
95
+ modifyCtx: (
96
+ original: TInCtx,
97
+ extra: TExtraArguments,
98
+ ) => Promise<TOutCtx> | TOutCtx,
99
+ ): Customization<
100
+ TInCtx,
101
+ Record<string, never>,
102
+ TOutCtx,
103
+ Record<string, never>,
104
+ TExtraArguments
105
+ > {
106
+ return {
107
+ args: {},
108
+ input: async (ctx, _ignored, extra) => ({
109
+ args: {},
110
+ ctx: await modifyCtx(ctx, extra),
111
+ }),
112
+ };
113
+ }
114
+
115
+ type Expand<TObject extends AnyRecord> = {
116
+ [Key in keyof TObject]: TObject[Key];
117
+ };
118
+
119
+ type Overwrite<TBase, TPatch> = keyof TPatch extends never
120
+ ? TBase
121
+ : Omit<TBase, keyof TPatch> & TPatch;
122
+
123
+ type ArgumentsForHandlerType<
124
+ TOneOrZeroArguments extends [] | [AnyRecord],
125
+ TCustomMadeArguments extends AnyRecord,
126
+ > =
127
+ TCustomMadeArguments extends Record<string, never>
128
+ ? TOneOrZeroArguments
129
+ : TOneOrZeroArguments extends [infer TArguments extends AnyRecord]
130
+ ? [Expand<TArguments & TCustomMadeArguments>]
131
+ : [TCustomMadeArguments];
132
+
133
+ /** The registered function type a custom builder returns. */
134
+ export type Registration<
135
+ TFunctionType extends "action" | "mutation" | "query",
136
+ TVisibility extends FunctionVisibility,
137
+ TArguments extends DefaultFunctionArgs,
138
+ TOutput,
139
+ > = {
140
+ action: RegisteredAction<TVisibility, TArguments, TOutput>;
141
+ mutation: RegisteredMutation<TVisibility, TArguments, TOutput>;
142
+ query: RegisteredQuery<TVisibility, TArguments, TOutput>;
143
+ }[TFunctionType];
144
+
145
+ /** A function builder made by {@link customQuery}, {@link customMutation} or {@link customAction}. */
146
+ export type CustomBuilder<
147
+ TFunctionType extends "action" | "mutation" | "query",
148
+ TCustomArgumentsValidator extends PropertyValidators,
149
+ TCustomCtx extends AnyRecord,
150
+ TCustomMadeArguments extends AnyRecord,
151
+ TInputCtx,
152
+ TVisibility extends FunctionVisibility,
153
+ TExtraArguments extends AnyRecord,
154
+ > = <
155
+ /* eslint-disable @typescript-eslint/no-invalid-void-type -- `void` means "no validator", as in convex/server's ArgsArrayForOptionalValidator */
156
+ TArgumentsValidator extends
157
+ PropertyValidators | Validator<any, any, any> | void,
158
+ TReturnsValidator extends GenericValidator | PropertyValidators | void,
159
+ /* eslint-enable @typescript-eslint/no-invalid-void-type */
160
+ TReturnValue extends ReturnValueForOptionalValidator<TReturnsValidator> = any,
161
+ TOneOrZeroArguments extends
162
+ ArgsArrayForOptionalValidator<TArgumentsValidator> =
163
+ DefaultArgsForOptionalValidator<TArgumentsValidator>,
164
+ >(
165
+ function_:
166
+ | ((
167
+ ctx: Overwrite<TInputCtx, TCustomCtx>,
168
+ ...arguments_: ArgumentsForHandlerType<
169
+ TOneOrZeroArguments,
170
+ TCustomMadeArguments
171
+ >
172
+ ) => TReturnValue)
173
+ | ({
174
+ args?: TArgumentsValidator;
175
+ handler: (
176
+ ctx: Overwrite<TInputCtx, TCustomCtx>,
177
+ ...arguments_: ArgumentsForHandlerType<
178
+ TOneOrZeroArguments,
179
+ TCustomMadeArguments
180
+ >
181
+ ) => TReturnValue;
182
+ returns?: TReturnsValidator;
183
+ } & {
184
+ [
185
+ Key in keyof TExtraArguments as Key extends
186
+ "args" | "handler" | "returns"
187
+ ? never
188
+ : Key
189
+ ]: TExtraArguments[Key];
190
+ }),
191
+ ) => Registration<
192
+ TFunctionType,
193
+ TVisibility,
194
+ ArgsArrayToObject<
195
+ TCustomArgumentsValidator extends Record<string, never>
196
+ ? TOneOrZeroArguments
197
+ : TOneOrZeroArguments extends [infer TArguments extends AnyRecord]
198
+ ? [Expand<ObjectType<TCustomArgumentsValidator> & TArguments>]
199
+ : [ObjectType<TCustomArgumentsValidator>]
200
+ >,
201
+ TReturnValue
202
+ >;
203
+
204
+ /** The ctx type a custom builder's handlers receive. */
205
+ export type CustomCtx<TBuilder> =
206
+ TBuilder extends CustomBuilder<
207
+ any,
208
+ any,
209
+ infer TCustom,
210
+ any,
211
+ infer TInputCtx,
212
+ any,
213
+ any
214
+ >
215
+ ? Overwrite<TInputCtx, TCustom>
216
+ : never;
217
+ /* eslint-enable @typescript-eslint/no-explicit-any */
218
+
219
+ type AnyCustomization = Customization<
220
+ AnyRecord,
221
+ PropertyValidators,
222
+ AnyRecord,
223
+ AnyRecord
224
+ >;
225
+
226
+ type Handler = (ctx: AnyRecord, arguments_: AnyRecord) => unknown;
227
+
228
+ type FunctionDefinition =
229
+ | (AnyRecord & {
230
+ args?: AnyValidator | PropertyValidators;
231
+ handler: Handler;
232
+ returns?: unknown;
233
+ })
234
+ | Handler;
235
+
236
+ function mergeFields(
237
+ fields: PropertyValidators,
238
+ added: PropertyValidators,
239
+ ): PropertyValidators {
240
+ return Object.entries(added).reduce<Record<string, GenericValidator>>(
241
+ (merged, [key, validator]) => {
242
+ const existing = merged[key];
243
+ if (existing === undefined) return { ...merged, [key]: validator };
244
+ if (existing.kind !== validator.kind) {
245
+ throw new Error(
246
+ `Cannot intersect validators with different kinds: ${existing.kind} and ${validator.kind}`,
247
+ );
248
+ }
249
+ // Keep the required side when one side is optional; else keep the function's.
250
+ return existing.isOptional === "optional" &&
251
+ validator.isOptional !== "optional"
252
+ ? { ...merged, [key]: validator }
253
+ : merged;
254
+ },
255
+ { ...fields },
256
+ );
257
+ }
258
+
259
+ function addInputArguments(
260
+ functionArguments: AnyValidator | PropertyValidators,
261
+ inputArguments: PropertyValidators,
262
+ ): AnyValidator {
263
+ const validator: AnyValidator = asObjectValidator(functionArguments);
264
+ if (Object.keys(inputArguments).length === 0) return validator;
265
+ if (validator.kind === "object") {
266
+ return v.object(mergeFields(validator.fields, inputArguments));
267
+ }
268
+ if (validator.kind === "union") {
269
+ return v.union(
270
+ ...validator.members.map((member: AnyValidator) =>
271
+ addInputArguments(member, inputArguments),
272
+ ),
273
+ );
274
+ }
275
+ throw new Error(
276
+ "Cannot add arguments to a validator that is not an object or union.",
277
+ );
278
+ }
279
+
280
+ function splitKeys(
281
+ source: AnyRecord,
282
+ keys: string[],
283
+ ): { picked: AnyRecord; rest: AnyRecord } {
284
+ const entries = Object.entries(source);
285
+ return {
286
+ picked: Object.fromEntries(entries.filter(([key]) => keys.includes(key))),
287
+ rest: Object.fromEntries(entries.filter(([key]) => !keys.includes(key))),
288
+ };
289
+ }
290
+
291
+ function wrapHandler(options: {
292
+ customization: AnyCustomization;
293
+ extra: AnyRecord;
294
+ handler: Handler;
295
+ splitArgs: boolean;
296
+ }): Handler {
297
+ const { customization, extra, handler, splitArgs } = options;
298
+ const inputKeys = Object.keys(customization.args);
299
+ return async (ctx, allArguments) => {
300
+ const { picked, rest } = splitArgs
301
+ ? splitKeys(allArguments, inputKeys)
302
+ : { picked: allArguments, rest: allArguments };
303
+ const added = await customization.input(ctx, picked, extra);
304
+ const result = await handler(
305
+ { ...ctx, ...added.ctx },
306
+ { ...rest, ...added.args },
307
+ );
308
+ if (added.onSuccess) await added.onSuccess({ args: rest, ctx, result });
309
+ return result;
310
+ };
311
+ }
312
+
313
+ function assertNoInputArguments(customization: AnyCustomization): void {
314
+ if (Object.keys(customization.args).length > 0) {
315
+ throw new Error(
316
+ "If you're using a custom function with arguments for the input " +
317
+ "customization, you must declare the arguments for the function too.",
318
+ );
319
+ }
320
+ }
321
+
322
+ function customFunctionBuilder(
323
+ builder: (definition: AnyRecord) => unknown,
324
+ customization: AnyCustomization,
325
+ ): (definition: FunctionDefinition) => unknown {
326
+ return (definition) => {
327
+ // A bare function is its own handler, with no args validator or extras.
328
+ const {
329
+ args,
330
+ handler = definition as Handler,
331
+ returns,
332
+ ...extra
333
+ } = definition as Partial<Exclude<FunctionDefinition, Handler>>;
334
+ if (args) {
335
+ return builder({
336
+ args: addInputArguments(args, customization.args),
337
+ handler: wrapHandler({
338
+ customization,
339
+ extra,
340
+ handler,
341
+ splitArgs: true,
342
+ }),
343
+ returns,
344
+ });
345
+ }
346
+ assertNoInputArguments(customization);
347
+ return builder({
348
+ handler: wrapHandler({ customization, extra, handler, splitArgs: false }),
349
+ returns,
350
+ });
351
+ };
352
+ }
353
+
354
+ /**
355
+ * Wraps a query builder (`query`, `internalQuery`, `queryGeneric`) with a
356
+ * customization.
357
+ *
358
+ * @param query - The Convex query builder to wrap
359
+ * @param customization - `{ args, input }`, or `customCtx(...)`
360
+ * @returns A builder used like `query({ args, returns, handler })`
361
+ * @example
362
+ * export const userQuery = customQuery(query, customCtx(async (ctx) => ({ user: await requireUser(ctx) })));
363
+ */
364
+ export function customQuery<
365
+ TCustomArgumentsValidator extends PropertyValidators,
366
+ TCustomCtx extends AnyRecord,
367
+ TCustomMadeArguments extends AnyRecord,
368
+ TVisibility extends FunctionVisibility,
369
+ TDataModel extends GenericDataModel,
370
+ TExtraArguments extends AnyRecord = object,
371
+ >(
372
+ query: QueryBuilder<TDataModel, TVisibility>,
373
+ customization: Customization<
374
+ GenericQueryCtx<TDataModel>,
375
+ TCustomArgumentsValidator,
376
+ TCustomCtx,
377
+ TCustomMadeArguments,
378
+ TExtraArguments
379
+ >,
380
+ ): CustomBuilder<
381
+ "query",
382
+ TCustomArgumentsValidator,
383
+ TCustomCtx,
384
+ TCustomMadeArguments,
385
+ GenericQueryCtx<TDataModel>,
386
+ TVisibility,
387
+ TExtraArguments
388
+ > {
389
+ return customFunctionBuilder(
390
+ query as (definition: AnyRecord) => unknown,
391
+ customization as unknown as AnyCustomization,
392
+ ) as never;
393
+ }
394
+
395
+ /**
396
+ * Wraps a mutation builder (`mutation`, `internalMutation`, `mutationGeneric`)
397
+ * with a customization.
398
+ *
399
+ * @param mutation - The Convex mutation builder to wrap
400
+ * @param customization - `{ args, input }`, or `customCtx(...)`
401
+ * @returns A builder used like `mutation({ args, returns, handler })`
402
+ * @example
403
+ * export const userMutation = customMutation(mutation, { args: {}, input: async (ctx) => ({ args: {}, ctx: { user: await requireUser(ctx) } }) });
404
+ */
405
+ export function customMutation<
406
+ TCustomArgumentsValidator extends PropertyValidators,
407
+ TCustomCtx extends AnyRecord,
408
+ TCustomMadeArguments extends AnyRecord,
409
+ TVisibility extends FunctionVisibility,
410
+ TDataModel extends GenericDataModel,
411
+ TExtraArguments extends AnyRecord = object,
412
+ >(
413
+ mutation: MutationBuilder<TDataModel, TVisibility>,
414
+ customization: Customization<
415
+ GenericMutationCtx<TDataModel>,
416
+ TCustomArgumentsValidator,
417
+ TCustomCtx,
418
+ TCustomMadeArguments,
419
+ TExtraArguments
420
+ >,
421
+ ): CustomBuilder<
422
+ "mutation",
423
+ TCustomArgumentsValidator,
424
+ TCustomCtx,
425
+ TCustomMadeArguments,
426
+ GenericMutationCtx<TDataModel>,
427
+ TVisibility,
428
+ TExtraArguments
429
+ > {
430
+ return customFunctionBuilder(
431
+ mutation as (definition: AnyRecord) => unknown,
432
+ customization as unknown as AnyCustomization,
433
+ ) as never;
434
+ }
435
+
436
+ /**
437
+ * Wraps an action builder (`action`, `internalAction`, `actionGeneric`) with a
438
+ * customization.
439
+ *
440
+ * @param action - The Convex action builder to wrap
441
+ * @param customization - `{ args, input }`, or `customCtx(...)`
442
+ * @returns A builder used like `action({ args, returns, handler })`
443
+ * @example
444
+ * export const keyedAction = customAction(action, { args: { key: v.string() }, input: async (_ctx, { key }) => ({ args: {}, ctx: { key } }) });
445
+ */
446
+ export function customAction<
447
+ TCustomArgumentsValidator extends PropertyValidators,
448
+ TCustomCtx extends AnyRecord,
449
+ TCustomMadeArguments extends AnyRecord,
450
+ TVisibility extends FunctionVisibility,
451
+ TDataModel extends GenericDataModel,
452
+ TExtraArguments extends AnyRecord = object,
453
+ >(
454
+ action: ActionBuilder<TDataModel, TVisibility>,
455
+ customization: Customization<
456
+ GenericActionCtx<TDataModel>,
457
+ TCustomArgumentsValidator,
458
+ TCustomCtx,
459
+ TCustomMadeArguments,
460
+ TExtraArguments
461
+ >,
462
+ ): CustomBuilder<
463
+ "action",
464
+ TCustomArgumentsValidator,
465
+ TCustomCtx,
466
+ TCustomMadeArguments,
467
+ GenericActionCtx<TDataModel>,
468
+ TVisibility,
469
+ TExtraArguments
470
+ > {
471
+ return customFunctionBuilder(
472
+ action as (definition: AnyRecord) => unknown,
473
+ customization as unknown as AnyCustomization,
474
+ ) as never;
475
+ }