better-convex 0.2.1 → 0.3.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/dist/auth/index.d.ts +76 -59
- package/dist/auth/index.js +32 -69
- package/dist/auth-nextjs/index.d.ts +1 -1
- package/dist/cli.cjs +1 -1
- package/dist/{codegen-Cca0gj6d.cjs → codegen-CdL9lB4u.cjs} +10 -5
- package/dist/crpc/index.d.ts +3 -41
- package/dist/crpc/index.js +1 -103
- package/dist/{http-types-BwEQgYV1.d.ts → http-types-CZo9Xx5R.d.ts} +41 -103
- package/dist/react/index.d.ts +0 -9
- package/dist/react/index.js +2 -1
- package/dist/rsc/index.d.ts +2 -2
- package/dist/server/index.d.ts +30 -31
- package/dist/server/index.js +133 -255
- package/dist/{types-DLVNrXKq.d.ts → types-U9pc_wi1.d.ts} +1 -1
- package/dist/watcher.cjs +8 -3
- package/package.json +2 -1
package/dist/auth/index.d.ts
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import * as
|
|
1
|
+
import * as better_auth_adapters1 from "better-auth/adapters";
|
|
2
2
|
import { DBAdapterDebugLogOption } from "better-auth/adapters";
|
|
3
3
|
import { BetterAuthDBSchema } from "better-auth/db";
|
|
4
|
-
import * as
|
|
5
|
-
import { DocumentByName, FunctionReference, GenericDataModel, GenericMutationCtx, GenericQueryCtx, GenericSchema,
|
|
4
|
+
import * as convex_server24 from "convex/server";
|
|
5
|
+
import { DocumentByName, FunctionReference, GenericDataModel, GenericMutationCtx, GenericQueryCtx, GenericSchema, IdField, PaginationOptions, PaginationResult, SchemaDefinition, SystemFields, TableNamesInDataModel, internalMutationGeneric } from "convex/server";
|
|
6
6
|
import * as convex_values0 from "convex/values";
|
|
7
7
|
import { Infer } from "convex/values";
|
|
8
|
+
import { MiddlewareHandler } from "hono";
|
|
8
9
|
import * as better_auth0 from "better-auth";
|
|
9
10
|
import { BetterAuthOptions, Where, betterAuth } from "better-auth";
|
|
10
11
|
import { GenericCtx } from "@convex-dev/better-auth";
|
|
@@ -44,31 +45,31 @@ declare const createClient: <DataModel extends GenericDataModel, Schema$1 extend
|
|
|
44
45
|
}) => {
|
|
45
46
|
authFunctions: AuthFunctions;
|
|
46
47
|
triggers: Triggers<DataModel, Schema$1> | undefined;
|
|
47
|
-
adapter: (ctx: GenericCtx<DataModel>, createAuthOptions: (ctx: any) => BetterAuthOptions) =>
|
|
48
|
-
httpAdapter: (ctx: GenericCtx<DataModel>) =>
|
|
48
|
+
adapter: (ctx: GenericCtx<DataModel>, createAuthOptions: (ctx: any) => BetterAuthOptions) => better_auth_adapters1.AdapterFactory;
|
|
49
|
+
httpAdapter: (ctx: GenericCtx<DataModel>) => better_auth_adapters1.AdapterFactory;
|
|
49
50
|
triggersApi: () => {
|
|
50
|
-
beforeCreate:
|
|
51
|
+
beforeCreate: convex_server24.RegisteredMutation<"internal", {
|
|
51
52
|
data: any;
|
|
52
53
|
model: string;
|
|
53
54
|
}, Promise<any>>;
|
|
54
|
-
beforeDelete:
|
|
55
|
+
beforeDelete: convex_server24.RegisteredMutation<"internal", {
|
|
55
56
|
model: string;
|
|
56
57
|
doc: any;
|
|
57
58
|
}, Promise<any>>;
|
|
58
|
-
beforeUpdate:
|
|
59
|
+
beforeUpdate: convex_server24.RegisteredMutation<"internal", {
|
|
59
60
|
update: any;
|
|
60
61
|
model: string;
|
|
61
62
|
doc: any;
|
|
62
63
|
}, Promise<any>>;
|
|
63
|
-
onCreate:
|
|
64
|
+
onCreate: convex_server24.RegisteredMutation<"internal", {
|
|
64
65
|
model: string;
|
|
65
66
|
doc: any;
|
|
66
67
|
}, Promise<void>>;
|
|
67
|
-
onDelete:
|
|
68
|
+
onDelete: convex_server24.RegisteredMutation<"internal", {
|
|
68
69
|
model: string;
|
|
69
70
|
doc: any;
|
|
70
71
|
}, Promise<void>>;
|
|
71
|
-
onUpdate:
|
|
72
|
+
onUpdate: convex_server24.RegisteredMutation<"internal", {
|
|
72
73
|
model: string;
|
|
73
74
|
newDoc: any;
|
|
74
75
|
oldDoc: any;
|
|
@@ -148,7 +149,7 @@ declare const httpAdapter: <DataModel extends GenericDataModel, Schema$1 extends
|
|
|
148
149
|
authFunctions: AuthFunctions;
|
|
149
150
|
debugLogs?: DBAdapterDebugLogOption;
|
|
150
151
|
triggers?: Triggers<DataModel, Schema$1>;
|
|
151
|
-
}) =>
|
|
152
|
+
}) => better_auth_adapters1.AdapterFactory;
|
|
152
153
|
declare const dbAdapter: <DataModel extends GenericDataModel, Schema$1 extends SchemaDefinition<any, any>>(ctx: GenericCtx<DataModel>, createAuthOptions: (ctx: any) => BetterAuthOptions, {
|
|
153
154
|
authFunctions,
|
|
154
155
|
debugLogs,
|
|
@@ -159,7 +160,7 @@ declare const dbAdapter: <DataModel extends GenericDataModel, Schema$1 extends S
|
|
|
159
160
|
schema: Schema$1;
|
|
160
161
|
debugLogs?: DBAdapterDebugLogOption;
|
|
161
162
|
triggers?: Triggers<DataModel, Schema$1>;
|
|
162
|
-
}) =>
|
|
163
|
+
}) => better_auth_adapters1.AdapterFactory;
|
|
163
164
|
//#endregion
|
|
164
165
|
//#region src/auth/adapter-utils.d.ts
|
|
165
166
|
declare const adapterWhereValidator: convex_values0.VObject<{
|
|
@@ -175,18 +176,18 @@ declare const adapterWhereValidator: convex_values0.VObject<{
|
|
|
175
176
|
}, "required", "operator" | "value" | "field" | "connector">;
|
|
176
177
|
declare const adapterArgsValidator: convex_values0.VObject<{
|
|
177
178
|
limit?: number | undefined;
|
|
178
|
-
offset?: number | undefined;
|
|
179
|
-
select?: string[] | undefined;
|
|
180
|
-
sortBy?: {
|
|
181
|
-
field: string;
|
|
182
|
-
direction: "asc" | "desc";
|
|
183
|
-
} | undefined;
|
|
184
179
|
where?: {
|
|
185
180
|
operator?: "eq" | "ne" | "lt" | "lte" | "gt" | "gte" | "in" | "not_in" | "contains" | "starts_with" | "ends_with" | undefined;
|
|
186
181
|
connector?: "AND" | "OR" | undefined;
|
|
187
182
|
value: string | number | boolean | string[] | number[] | null;
|
|
188
183
|
field: string;
|
|
189
184
|
}[] | undefined;
|
|
185
|
+
select?: string[] | undefined;
|
|
186
|
+
offset?: number | undefined;
|
|
187
|
+
sortBy?: {
|
|
188
|
+
field: string;
|
|
189
|
+
direction: "asc" | "desc";
|
|
190
|
+
} | undefined;
|
|
190
191
|
model: string;
|
|
191
192
|
}, {
|
|
192
193
|
limit: convex_values0.VFloat64<number | undefined, "optional">;
|
|
@@ -216,7 +217,7 @@ declare const adapterArgsValidator: convex_values0.VObject<{
|
|
|
216
217
|
operator: convex_values0.VUnion<"eq" | "ne" | "lt" | "lte" | "gt" | "gte" | "in" | "not_in" | "contains" | "starts_with" | "ends_with" | undefined, [convex_values0.VLiteral<"lt", "required">, convex_values0.VLiteral<"lte", "required">, convex_values0.VLiteral<"gt", "required">, convex_values0.VLiteral<"gte", "required">, convex_values0.VLiteral<"eq", "required">, convex_values0.VLiteral<"in", "required">, convex_values0.VLiteral<"not_in", "required">, convex_values0.VLiteral<"ne", "required">, convex_values0.VLiteral<"contains", "required">, convex_values0.VLiteral<"starts_with", "required">, convex_values0.VLiteral<"ends_with", "required">], "optional", never>;
|
|
217
218
|
value: convex_values0.VUnion<string | number | boolean | string[] | number[] | null, [convex_values0.VString<string, "required">, convex_values0.VFloat64<number, "required">, convex_values0.VBoolean<boolean, "required">, convex_values0.VArray<string[], convex_values0.VString<string, "required">, "required">, convex_values0.VArray<number[], convex_values0.VFloat64<number, "required">, "required">, convex_values0.VNull<null, "required">], "required", never>;
|
|
218
219
|
}, "required", "operator" | "value" | "field" | "connector">, "optional">;
|
|
219
|
-
}, "required", "limit" | "
|
|
220
|
+
}, "required", "limit" | "where" | "model" | "select" | "offset" | "sortBy" | "sortBy.field" | "sortBy.direction">;
|
|
220
221
|
declare const hasUniqueFields: (betterAuthSchema: BetterAuthDBSchema, model: string, input: Record<string, any>) => boolean;
|
|
221
222
|
declare const checkUniqueFields: <Schema$1 extends SchemaDefinition<any, any>>(ctx: GenericQueryCtx<GenericDataModel>, schema: Schema$1, betterAuthSchema: BetterAuthDBSchema, table: string, input: Record<string, any>, doc?: Record<string, any>) => Promise<void>;
|
|
222
223
|
declare const selectFields: <T extends TableNamesInDataModel<GenericDataModel>, D extends DocumentByName<GenericDataModel, T>>(doc: D | null, select?: string[]) => Promise<D | null>;
|
|
@@ -244,7 +245,7 @@ declare const findOneHandler: (ctx: any, args: {
|
|
|
244
245
|
model: string;
|
|
245
246
|
select?: string[];
|
|
246
247
|
where?: any[];
|
|
247
|
-
}, schema: Schema, betterAuthSchema: any) => Promise<
|
|
248
|
+
}, schema: Schema, betterAuthSchema: any) => Promise<convex_server24.GenericDocument | null>;
|
|
248
249
|
declare const findManyHandler: (ctx: any, args: {
|
|
249
250
|
model: string;
|
|
250
251
|
paginationOpts: any;
|
|
@@ -255,7 +256,7 @@ declare const findManyHandler: (ctx: any, args: {
|
|
|
255
256
|
field: string;
|
|
256
257
|
};
|
|
257
258
|
where?: any[];
|
|
258
|
-
}, schema: Schema, betterAuthSchema: any) => Promise<
|
|
259
|
+
}, schema: Schema, betterAuthSchema: any) => Promise<convex_server24.PaginationResult<convex_server24.GenericDocument>>;
|
|
259
260
|
declare const updateOneHandler: (ctx: any, args: {
|
|
260
261
|
input: {
|
|
261
262
|
model: string;
|
|
@@ -278,8 +279,8 @@ declare const updateManyHandler: (ctx: any, args: {
|
|
|
278
279
|
count: number;
|
|
279
280
|
ids: any[];
|
|
280
281
|
isDone: boolean;
|
|
281
|
-
continueCursor:
|
|
282
|
-
splitCursor?:
|
|
282
|
+
continueCursor: convex_server24.Cursor;
|
|
283
|
+
splitCursor?: convex_server24.Cursor | null;
|
|
283
284
|
pageStatus?: "SplitRecommended" | "SplitRequired" | null;
|
|
284
285
|
}>;
|
|
285
286
|
declare const deleteOneHandler: (ctx: any, args: {
|
|
@@ -290,7 +291,7 @@ declare const deleteOneHandler: (ctx: any, args: {
|
|
|
290
291
|
beforeDeleteHandle?: string;
|
|
291
292
|
skipBeforeHooks?: boolean;
|
|
292
293
|
onDeleteHandle?: string;
|
|
293
|
-
}, schema: Schema, betterAuthSchema: any) => Promise<
|
|
294
|
+
}, schema: Schema, betterAuthSchema: any) => Promise<convex_server24.GenericDocument | undefined>;
|
|
294
295
|
declare const deleteManyHandler: (ctx: any, args: {
|
|
295
296
|
input: {
|
|
296
297
|
model: string;
|
|
@@ -304,8 +305,8 @@ declare const deleteManyHandler: (ctx: any, args: {
|
|
|
304
305
|
count: number;
|
|
305
306
|
ids: any[];
|
|
306
307
|
isDone: boolean;
|
|
307
|
-
continueCursor:
|
|
308
|
-
splitCursor?:
|
|
308
|
+
continueCursor: convex_server24.Cursor;
|
|
309
|
+
splitCursor?: convex_server24.Cursor | null;
|
|
309
310
|
pageStatus?: "SplitRecommended" | "SplitRequired" | null;
|
|
310
311
|
}>;
|
|
311
312
|
declare const createApi: <Schema$1 extends SchemaDefinition<any, any>>(schema: Schema$1, createAuth: CreateAuth, options?: {
|
|
@@ -313,7 +314,7 @@ declare const createApi: <Schema$1 extends SchemaDefinition<any, any>>(schema: S
|
|
|
313
314
|
/** Skip input validation for smaller generated types. Since these are internal functions, validation is optional. */
|
|
314
315
|
skipValidation?: boolean;
|
|
315
316
|
}) => {
|
|
316
|
-
create:
|
|
317
|
+
create: convex_server24.RegisteredMutation<"internal", {
|
|
317
318
|
select?: string[] | undefined;
|
|
318
319
|
beforeCreateHandle?: string | undefined;
|
|
319
320
|
onCreateHandle?: string | undefined;
|
|
@@ -329,7 +330,7 @@ declare const createApi: <Schema$1 extends SchemaDefinition<any, any>>(schema: S
|
|
|
329
330
|
model: string;
|
|
330
331
|
};
|
|
331
332
|
}, Promise<any>>;
|
|
332
|
-
deleteMany:
|
|
333
|
+
deleteMany: convex_server24.RegisteredMutation<"internal", {
|
|
333
334
|
beforeDeleteHandle?: string | undefined;
|
|
334
335
|
onDeleteHandle?: string | undefined;
|
|
335
336
|
paginationOpts: {
|
|
@@ -356,11 +357,11 @@ declare const createApi: <Schema$1 extends SchemaDefinition<any, any>>(schema: S
|
|
|
356
357
|
count: number;
|
|
357
358
|
ids: any[];
|
|
358
359
|
isDone: boolean;
|
|
359
|
-
continueCursor:
|
|
360
|
-
splitCursor?:
|
|
360
|
+
continueCursor: convex_server24.Cursor;
|
|
361
|
+
splitCursor?: convex_server24.Cursor | null;
|
|
361
362
|
pageStatus?: "SplitRecommended" | "SplitRequired" | null;
|
|
362
363
|
}>>;
|
|
363
|
-
deleteOne:
|
|
364
|
+
deleteOne: convex_server24.RegisteredMutation<"internal", {
|
|
364
365
|
beforeDeleteHandle?: string | undefined;
|
|
365
366
|
onDeleteHandle?: string | undefined;
|
|
366
367
|
input: {
|
|
@@ -375,21 +376,21 @@ declare const createApi: <Schema$1 extends SchemaDefinition<any, any>>(schema: S
|
|
|
375
376
|
}[] | undefined;
|
|
376
377
|
model: string;
|
|
377
378
|
};
|
|
378
|
-
}, Promise<
|
|
379
|
-
findMany:
|
|
380
|
-
join?: any;
|
|
379
|
+
}, Promise<convex_server24.GenericDocument | undefined>>;
|
|
380
|
+
findMany: convex_server24.RegisteredQuery<"internal", {
|
|
381
381
|
limit?: number | undefined;
|
|
382
|
-
|
|
383
|
-
sortBy?: {
|
|
384
|
-
field: string;
|
|
385
|
-
direction: "asc" | "desc";
|
|
386
|
-
} | undefined;
|
|
382
|
+
join?: any;
|
|
387
383
|
where?: {
|
|
388
384
|
operator?: "eq" | "ne" | "lt" | "lte" | "gt" | "gte" | "in" | "not_in" | "contains" | "starts_with" | "ends_with" | undefined;
|
|
389
385
|
connector?: "AND" | "OR" | undefined;
|
|
390
386
|
value: string | number | boolean | string[] | number[] | null;
|
|
391
387
|
field: string;
|
|
392
388
|
}[] | undefined;
|
|
389
|
+
offset?: number | undefined;
|
|
390
|
+
sortBy?: {
|
|
391
|
+
field: string;
|
|
392
|
+
direction: "asc" | "desc";
|
|
393
|
+
} | undefined;
|
|
393
394
|
paginationOpts: {
|
|
394
395
|
id?: number;
|
|
395
396
|
endCursor?: string | null;
|
|
@@ -399,19 +400,19 @@ declare const createApi: <Schema$1 extends SchemaDefinition<any, any>>(schema: S
|
|
|
399
400
|
cursor: string | null;
|
|
400
401
|
};
|
|
401
402
|
model: string;
|
|
402
|
-
}, Promise<
|
|
403
|
-
findOne:
|
|
403
|
+
}, Promise<convex_server24.PaginationResult<convex_server24.GenericDocument>>>;
|
|
404
|
+
findOne: convex_server24.RegisteredQuery<"internal", {
|
|
404
405
|
join?: any;
|
|
405
|
-
select?: string[] | undefined;
|
|
406
406
|
where?: {
|
|
407
407
|
operator?: "eq" | "ne" | "lt" | "lte" | "gt" | "gte" | "in" | "not_in" | "contains" | "starts_with" | "ends_with" | undefined;
|
|
408
408
|
connector?: "AND" | "OR" | undefined;
|
|
409
409
|
value: string | number | boolean | string[] | number[] | null;
|
|
410
410
|
field: string;
|
|
411
411
|
}[] | undefined;
|
|
412
|
+
select?: string[] | undefined;
|
|
412
413
|
model: string;
|
|
413
|
-
}, Promise<
|
|
414
|
-
updateMany:
|
|
414
|
+
}, Promise<convex_server24.GenericDocument | null>>;
|
|
415
|
+
updateMany: convex_server24.RegisteredMutation<"internal", {
|
|
415
416
|
beforeUpdateHandle?: string | undefined;
|
|
416
417
|
onUpdateHandle?: string | undefined;
|
|
417
418
|
paginationOpts: {
|
|
@@ -444,11 +445,11 @@ declare const createApi: <Schema$1 extends SchemaDefinition<any, any>>(schema: S
|
|
|
444
445
|
count: number;
|
|
445
446
|
ids: any[];
|
|
446
447
|
isDone: boolean;
|
|
447
|
-
continueCursor:
|
|
448
|
-
splitCursor?:
|
|
448
|
+
continueCursor: convex_server24.Cursor;
|
|
449
|
+
splitCursor?: convex_server24.Cursor | null;
|
|
449
450
|
pageStatus?: "SplitRecommended" | "SplitRequired" | null;
|
|
450
451
|
}>>;
|
|
451
|
-
updateOne:
|
|
452
|
+
updateOne: convex_server24.RegisteredMutation<"internal", {
|
|
452
453
|
beforeUpdateHandle?: string | undefined;
|
|
453
454
|
onUpdateHandle?: string | undefined;
|
|
454
455
|
input: {
|
|
@@ -470,8 +471,8 @@ declare const createApi: <Schema$1 extends SchemaDefinition<any, any>>(schema: S
|
|
|
470
471
|
model: string;
|
|
471
472
|
};
|
|
472
473
|
}, Promise<any>>;
|
|
473
|
-
getLatestJwks:
|
|
474
|
-
rotateKeys:
|
|
474
|
+
getLatestJwks: convex_server24.RegisteredAction<"internal", {}, Promise<any>>;
|
|
475
|
+
rotateKeys: convex_server24.RegisteredAction<"internal", {}, Promise<any>>;
|
|
475
476
|
};
|
|
476
477
|
//#endregion
|
|
477
478
|
//#region src/auth/helpers.d.ts
|
|
@@ -503,14 +504,30 @@ declare const getAuthUserId: <DataModel extends GenericDataModel>(ctx: GenericQu
|
|
|
503
504
|
declare const getSession: <DataModel extends GenericDataModel>(ctx: GenericQueryCtx<DataModel>, _sessionId?: DocumentByName<DataModel, "session">["_id"]) => Promise<DocumentByName<DataModel, "session"> | null>;
|
|
504
505
|
declare const getHeaders: <DataModel extends GenericDataModel>(ctx: GenericQueryCtx<DataModel>, session?: DocumentByName<DataModel, "session"> | null) => Promise<Headers>;
|
|
505
506
|
//#endregion
|
|
506
|
-
//#region src/auth/
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
exposedHeaders?: string[];
|
|
512
|
-
} | boolean;
|
|
507
|
+
//#region src/auth/middleware.d.ts
|
|
508
|
+
interface AuthMiddlewareOptions {
|
|
509
|
+
/** Base path for auth routes (default: '/api/auth') */
|
|
510
|
+
basePath?: string;
|
|
511
|
+
/** Log request/response headers for debugging */
|
|
513
512
|
verbose?: boolean;
|
|
514
|
-
}
|
|
513
|
+
}
|
|
514
|
+
/**
|
|
515
|
+
* Create auth middleware that handles auth routes and OpenID well-known redirect.
|
|
516
|
+
*
|
|
517
|
+
* @example
|
|
518
|
+
* ```ts
|
|
519
|
+
* import { Hono } from 'hono';
|
|
520
|
+
* import { cors } from 'hono/cors';
|
|
521
|
+
* import { authMiddleware } from 'better-convex/auth';
|
|
522
|
+
* import { createHttpRouter } from 'better-convex/server';
|
|
523
|
+
*
|
|
524
|
+
* const app = new Hono();
|
|
525
|
+
* app.use('/api/*', cors({ origin: process.env.SITE_URL, credentials: true }));
|
|
526
|
+
* app.use(authMiddleware(createAuth));
|
|
527
|
+
*
|
|
528
|
+
* export default createHttpRouter(app, appRouter);
|
|
529
|
+
* ```
|
|
530
|
+
*/
|
|
531
|
+
declare function authMiddleware(createAuth: CreateAuth, opts?: AuthMiddlewareOptions): MiddlewareHandler;
|
|
515
532
|
//#endregion
|
|
516
|
-
export { AuthFunctions, ConvexCleanedWhere, CreateAuth, Triggers, adapterArgsValidator, adapterConfig, adapterWhereValidator, checkUniqueFields, createApi, createClient, createHandler, dbAdapter, deleteManyHandler, deleteOneHandler, findManyHandler, findOneHandler, getAuthUserId, getAuthUserIdentity, getHeaders, getSession, handlePagination, hasUniqueFields, httpAdapter, listOne, paginate,
|
|
533
|
+
export { AuthFunctions, AuthMiddlewareOptions, ConvexCleanedWhere, CreateAuth, Triggers, adapterArgsValidator, adapterConfig, adapterWhereValidator, authMiddleware, checkUniqueFields, createApi, createClient, createHandler, dbAdapter, deleteManyHandler, deleteOneHandler, findManyHandler, findOneHandler, getAuthUserId, getAuthUserIdentity, getHeaders, getSession, handlePagination, hasUniqueFields, httpAdapter, listOne, paginate, selectFields, updateManyHandler, updateOneHandler };
|
package/dist/auth/index.js
CHANGED
|
@@ -1,14 +1,13 @@
|
|
|
1
1
|
import { isRunMutationCtx } from "@convex-dev/better-auth/utils";
|
|
2
2
|
import { createAdapterFactory } from "better-auth/adapters";
|
|
3
3
|
import { getAuthTables } from "better-auth/db";
|
|
4
|
-
import { createFunctionHandle,
|
|
4
|
+
import { createFunctionHandle, internalActionGeneric, internalMutationGeneric, internalQueryGeneric, paginationOptsValidator } from "convex/server";
|
|
5
5
|
import { asyncMap } from "convex-helpers";
|
|
6
6
|
import { prop, sortBy, unique } from "remeda";
|
|
7
7
|
import { v } from "convex/values";
|
|
8
8
|
import { partial } from "convex-helpers/validators";
|
|
9
9
|
import { stripIndent } from "common-tags";
|
|
10
10
|
import { mergedStream, stream } from "convex-helpers/server/stream";
|
|
11
|
-
import { corsRouter } from "convex-helpers/server/cors";
|
|
12
11
|
|
|
13
12
|
//#region src/auth/adapter-utils.ts
|
|
14
13
|
const adapterWhereValidator = v.object({
|
|
@@ -958,73 +957,37 @@ const getHeaders = async (ctx, session) => {
|
|
|
958
957
|
};
|
|
959
958
|
|
|
960
959
|
//#endregion
|
|
961
|
-
//#region src/auth/
|
|
962
|
-
/**
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
960
|
+
//#region src/auth/middleware.ts
|
|
961
|
+
/**
|
|
962
|
+
* Create auth middleware that handles auth routes and OpenID well-known redirect.
|
|
963
|
+
*
|
|
964
|
+
* @example
|
|
965
|
+
* ```ts
|
|
966
|
+
* import { Hono } from 'hono';
|
|
967
|
+
* import { cors } from 'hono/cors';
|
|
968
|
+
* import { authMiddleware } from 'better-convex/auth';
|
|
969
|
+
* import { createHttpRouter } from 'better-convex/server';
|
|
970
|
+
*
|
|
971
|
+
* const app = new Hono();
|
|
972
|
+
* app.use('/api/*', cors({ origin: process.env.SITE_URL, credentials: true }));
|
|
973
|
+
* app.use(authMiddleware(createAuth));
|
|
974
|
+
*
|
|
975
|
+
* export default createHttpRouter(app, appRouter);
|
|
976
|
+
* ```
|
|
977
|
+
*/
|
|
978
|
+
function authMiddleware(createAuth, opts = {}) {
|
|
979
|
+
const basePath = opts.basePath ?? "/api/auth";
|
|
980
|
+
return async (c, next) => {
|
|
981
|
+
if (c.req.path === "/.well-known/openid-configuration") return c.redirect(`${process.env.CONVEX_SITE_URL}${basePath}/convex/.well-known/openid-configuration`);
|
|
982
|
+
if (c.req.path.startsWith(basePath)) {
|
|
983
|
+
if (opts.verbose) console.log("request headers", c.req.raw.headers);
|
|
984
|
+
const response = await createAuth(c.env).handler(c.req.raw);
|
|
985
|
+
if (opts.verbose) console.log("response headers", response.headers);
|
|
986
|
+
return response;
|
|
970
987
|
}
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
});
|
|
975
|
-
if (!http.lookup("/.well-known/openid-configuration", "GET")) http.route({
|
|
976
|
-
handler: httpActionGeneric(async () => {
|
|
977
|
-
const url = `${process.env.CONVEX_SITE_URL}${path}/convex/.well-known/openid-configuration`;
|
|
978
|
-
return Response.redirect(url);
|
|
979
|
-
}),
|
|
980
|
-
method: "GET",
|
|
981
|
-
path: "/.well-known/openid-configuration"
|
|
982
|
-
});
|
|
983
|
-
if (!opts.cors) {
|
|
984
|
-
http.route({
|
|
985
|
-
handler: authRequestHandler,
|
|
986
|
-
method: "GET",
|
|
987
|
-
pathPrefix: `${path}/`
|
|
988
|
-
});
|
|
989
|
-
http.route({
|
|
990
|
-
handler: authRequestHandler,
|
|
991
|
-
method: "POST",
|
|
992
|
-
pathPrefix: `${path}/`
|
|
993
|
-
});
|
|
994
|
-
return;
|
|
995
|
-
}
|
|
996
|
-
const corsOpts = typeof opts.cors === "boolean" ? {
|
|
997
|
-
allowedHeaders: [],
|
|
998
|
-
allowedOrigins: [],
|
|
999
|
-
exposedHeaders: []
|
|
1000
|
-
} : opts.cors;
|
|
1001
|
-
let trustedOriginsOption;
|
|
1002
|
-
const cors = corsRouter(http, {
|
|
1003
|
-
allowCredentials: true,
|
|
1004
|
-
allowedHeaders: [
|
|
1005
|
-
"Content-Type",
|
|
1006
|
-
"Better-Auth-Cookie",
|
|
1007
|
-
"Authorization"
|
|
1008
|
-
].concat(corsOpts.allowedHeaders ?? []),
|
|
1009
|
-
debug: opts?.verbose,
|
|
1010
|
-
enforceAllowOrigins: false,
|
|
1011
|
-
exposedHeaders: ["Set-Better-Auth-Cookie"].concat(corsOpts.exposedHeaders ?? []),
|
|
1012
|
-
allowedOrigins: async (request) => {
|
|
1013
|
-
trustedOriginsOption = trustedOriginsOption ?? (await staticAuth.$context).options.trustedOrigins ?? [];
|
|
1014
|
-
return (Array.isArray(trustedOriginsOption) ? trustedOriginsOption : await trustedOriginsOption?.(request) ?? []).map((origin) => origin.endsWith("*") && origin.length > 1 ? origin.slice(0, -1) : origin).concat(corsOpts.allowedOrigins ?? []);
|
|
1015
|
-
}
|
|
1016
|
-
});
|
|
1017
|
-
cors.route({
|
|
1018
|
-
handler: authRequestHandler,
|
|
1019
|
-
method: "GET",
|
|
1020
|
-
pathPrefix: `${path}/`
|
|
1021
|
-
});
|
|
1022
|
-
cors.route({
|
|
1023
|
-
handler: authRequestHandler,
|
|
1024
|
-
method: "POST",
|
|
1025
|
-
pathPrefix: `${path}/`
|
|
1026
|
-
});
|
|
1027
|
-
};
|
|
988
|
+
return next();
|
|
989
|
+
};
|
|
990
|
+
}
|
|
1028
991
|
|
|
1029
992
|
//#endregion
|
|
1030
|
-
export { adapterArgsValidator, adapterConfig, adapterWhereValidator, checkUniqueFields, createApi, createClient, createHandler, dbAdapter, deleteManyHandler, deleteOneHandler, findManyHandler, findOneHandler, getAuthUserId, getAuthUserIdentity, getHeaders, getSession, handlePagination, hasUniqueFields, httpAdapter, listOne, paginate,
|
|
993
|
+
export { adapterArgsValidator, adapterConfig, adapterWhereValidator, authMiddleware, checkUniqueFields, createApi, createClient, createHandler, dbAdapter, deleteManyHandler, deleteOneHandler, findManyHandler, findOneHandler, getAuthUserId, getAuthUserIdentity, getHeaders, getSession, handlePagination, hasUniqueFields, httpAdapter, listOne, paginate, selectFields, updateManyHandler, updateOneHandler };
|
package/dist/cli.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
const require_codegen = require('./codegen-
|
|
2
|
+
const require_codegen = require('./codegen-CdL9lB4u.cjs');
|
|
3
3
|
let node_module = require("node:module");
|
|
4
4
|
let node_path = require("node:path");
|
|
5
5
|
node_path = require_codegen.__toESM(node_path);
|
|
@@ -55,11 +55,15 @@ function isCRPCHttpRouter(value) {
|
|
|
55
55
|
async function parseModuleRuntime(filePath, jiti$1) {
|
|
56
56
|
const result = {};
|
|
57
57
|
const httpRoutes = {};
|
|
58
|
+
const isHttp = filePath.endsWith("http.ts");
|
|
58
59
|
const module$1 = await jiti$1.import(filePath);
|
|
59
|
-
if (!module$1 || typeof module$1 !== "object")
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
60
|
+
if (!module$1 || typeof module$1 !== "object") {
|
|
61
|
+
if (isHttp) console.error(" http.ts: module is empty or not an object");
|
|
62
|
+
return {
|
|
63
|
+
meta: null,
|
|
64
|
+
httpRoutes: {}
|
|
65
|
+
};
|
|
66
|
+
}
|
|
63
67
|
for (const [name, value] of Object.entries(module$1)) {
|
|
64
68
|
if (name.startsWith("_")) continue;
|
|
65
69
|
const meta = value?._crpcMeta;
|
|
@@ -117,9 +121,10 @@ async function generateMeta(outputDir, options) {
|
|
|
117
121
|
totalFunctions += fnCount;
|
|
118
122
|
if (debug) console.info(` ✓ ${moduleName}: ${fnCount} functions`);
|
|
119
123
|
}
|
|
124
|
+
if (Object.keys(httpRoutes).length > 0 && debug) console.info(` ✓ ${moduleName}: ${Object.keys(httpRoutes).length} HTTP routes`);
|
|
120
125
|
Object.assign(allHttpRoutes, httpRoutes);
|
|
121
126
|
} catch (error) {
|
|
122
|
-
if (debug) console.error(` ⚠ Failed to parse ${file}:`, error);
|
|
127
|
+
if (debug || file === "http.ts") console.error(` ⚠ Failed to parse ${file}:`, error);
|
|
123
128
|
}
|
|
124
129
|
}
|
|
125
130
|
const metaEntries = Object.entries(meta).map(([module$1, fns]) => {
|
package/dist/crpc/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { C as PaginatedFnMeta, S as Meta, _ as ExtractPaginatedItem, a as ConvexInfiniteQueryMeta, b as InfiniteQueryInput, c as ConvexMutationKey, d as ConvexQueryMeta, f as ConvexQueryOptions, g as DecorateQuery, h as DecorateMutation, i as ConvexActionOptions, l as ConvexQueryHookOptions, m as DecorateInfiniteQuery, n as CRPCClient, o as ConvexInfiniteQueryOptions, p as DecorateAction, r as ConvexActionKey, s as ConvexInfiniteQueryOptionsWithRef, t as AuthType, u as ConvexQueryKey, v as FUNC_REF_SYMBOL, w as PaginationOpts, x as InfiniteQueryOptsParam, y as FnMeta } from "../types-
|
|
1
|
+
import { a as HttpProcedureCall, c as InferHttpInput, i as HttpErrorCode, l as InferHttpOutput, n as HttpClientError, o as HttpRouteInfo, r as HttpClientFromRouter, s as HttpRouteMap, t as HttpClient, u as isHttpClientError } from "../http-types-CZo9Xx5R.js";
|
|
2
|
+
import { C as PaginatedFnMeta, S as Meta, _ as ExtractPaginatedItem, a as ConvexInfiniteQueryMeta, b as InfiniteQueryInput, c as ConvexMutationKey, d as ConvexQueryMeta, f as ConvexQueryOptions, g as DecorateQuery, h as DecorateMutation, i as ConvexActionOptions, l as ConvexQueryHookOptions, m as DecorateInfiniteQuery, n as CRPCClient, o as ConvexInfiniteQueryOptions, p as DecorateAction, r as ConvexActionKey, s as ConvexInfiniteQueryOptionsWithRef, t as AuthType, u as ConvexQueryKey, v as FUNC_REF_SYMBOL, w as PaginationOpts, x as InfiniteQueryOptsParam, y as FnMeta } from "../types-U9pc_wi1.js";
|
|
3
3
|
import { FunctionArgs, FunctionReference } from "convex/server";
|
|
4
4
|
|
|
5
5
|
//#region src/crpc/error.d.ts
|
|
@@ -28,44 +28,6 @@ declare const isCRPCErrorCode: (error: unknown, code: ClientErrorCode) => error
|
|
|
28
28
|
/** Default unauthorized detection - checks UNAUTHORIZED code */
|
|
29
29
|
declare const defaultIsUnauthorized: (error: unknown) => boolean;
|
|
30
30
|
//#endregion
|
|
31
|
-
//#region src/crpc/http-client.d.ts
|
|
32
|
-
|
|
33
|
-
/**
|
|
34
|
-
* Create a typed HTTP client for cRPC HTTP routers
|
|
35
|
-
*
|
|
36
|
-
* Supports nested router access like tRPC:
|
|
37
|
-
* - `http.todos.get({ id })` for nested routers
|
|
38
|
-
* - `http.health()` for flat procedures
|
|
39
|
-
*
|
|
40
|
-
* For React apps, prefer using `createCRPCContext` with HTTP options
|
|
41
|
-
* which provides TanStack Query integration (queryOptions, mutationOptions).
|
|
42
|
-
*
|
|
43
|
-
* @example
|
|
44
|
-
* ```ts
|
|
45
|
-
* import { createHttpClient } from 'better-convex/crpc';
|
|
46
|
-
* import { meta } from '../convex/shared/meta';
|
|
47
|
-
* import type { AppRouter } from '../convex/functions/http';
|
|
48
|
-
*
|
|
49
|
-
* const http = createHttpClient<AppRouter>({
|
|
50
|
-
* convexSiteUrl: process.env.NEXT_PUBLIC_CONVEX_SITE_URL!,
|
|
51
|
-
* routes: meta._http!, // HTTP routes are in meta._http
|
|
52
|
-
* });
|
|
53
|
-
*
|
|
54
|
-
* // Nested access
|
|
55
|
-
* const todo = await http.todos.get({ id: 'abc123' });
|
|
56
|
-
*
|
|
57
|
-
* // Flat access
|
|
58
|
-
* const health = await http.health();
|
|
59
|
-
* ```
|
|
60
|
-
*/
|
|
61
|
-
declare function createHttpClient<TRouter extends CRPCHttpRouter<any>, TRoutes extends HttpRouteMap = HttpRouteMap>(opts: HttpClientOptions<TRoutes>): HttpClientFromRouter<TRouter>;
|
|
62
|
-
/**
|
|
63
|
-
* Create a typed HTTP client for flat HTTP router record
|
|
64
|
-
*
|
|
65
|
-
* @deprecated Prefer passing a CRPCHttpRouter type for nested access
|
|
66
|
-
*/
|
|
67
|
-
declare function createHttpClient<TRouter extends HttpRouterRecord, TRoutes extends HttpRouteMap = HttpRouteMap>(opts: HttpClientOptions<TRoutes>): HttpClient<TRouter>;
|
|
68
|
-
//#endregion
|
|
69
31
|
//#region src/crpc/query-options.d.ts
|
|
70
32
|
/**
|
|
71
33
|
* Query options factory for Convex query function subscriptions.
|
|
@@ -106,4 +68,4 @@ declare function convexAction<T extends FunctionReference<'action'>>(funcRef: T,
|
|
|
106
68
|
*/
|
|
107
69
|
declare function convexInfiniteQueryOptions<T extends FunctionReference<'query'>>(funcRef: T, args: Record<string, unknown> | 'skip', opts?: InfiniteQueryOptsParam<T>, meta?: Meta): ConvexInfiniteQueryOptions<T>;
|
|
108
70
|
//#endregion
|
|
109
|
-
export { AuthType, CRPCClient, CRPCClientError, ConvexActionKey, ConvexActionOptions, ConvexInfiniteQueryMeta, ConvexInfiniteQueryOptions, ConvexInfiniteQueryOptionsWithRef, ConvexMutationKey, ConvexQueryHookOptions, ConvexQueryKey, ConvexQueryMeta, ConvexQueryOptions, DecorateAction, DecorateInfiniteQuery, DecorateMutation, DecorateQuery, ExtractPaginatedItem, FUNC_REF_SYMBOL, FnMeta, HttpClient, HttpClientError, HttpClientFromRouter,
|
|
71
|
+
export { AuthType, CRPCClient, CRPCClientError, ConvexActionKey, ConvexActionOptions, ConvexInfiniteQueryMeta, ConvexInfiniteQueryOptions, ConvexInfiniteQueryOptionsWithRef, ConvexMutationKey, ConvexQueryHookOptions, ConvexQueryKey, ConvexQueryMeta, ConvexQueryOptions, DecorateAction, DecorateInfiniteQuery, DecorateMutation, DecorateQuery, ExtractPaginatedItem, FUNC_REF_SYMBOL, FnMeta, HttpClient, HttpClientError, HttpClientFromRouter, HttpErrorCode, HttpProcedureCall, HttpRouteInfo, HttpRouteMap, InferHttpInput, InferHttpOutput, InfiniteQueryInput, InfiniteQueryOptsParam, Meta, PaginatedFnMeta, PaginationOpts, convexAction, convexInfiniteQueryOptions, convexQuery, defaultIsUnauthorized, isCRPCClientError, isCRPCErrorCode, isHttpClientError };
|
package/dist/crpc/index.js
CHANGED
|
@@ -18,112 +18,10 @@ var HttpClientError = class extends Error {
|
|
|
18
18
|
/** Type guard for HttpClientError */
|
|
19
19
|
const isHttpClientError = (error) => error instanceof HttpClientError;
|
|
20
20
|
|
|
21
|
-
//#endregion
|
|
22
|
-
//#region src/crpc/http-client.ts
|
|
23
|
-
/**
|
|
24
|
-
* Extract path parameter names from a route path
|
|
25
|
-
* e.g., '/users/:id/posts/:postId' -> ['id', 'postId']
|
|
26
|
-
*/
|
|
27
|
-
function extractPathParamNames(path) {
|
|
28
|
-
const matches = path.match(/:([a-zA-Z_][a-zA-Z0-9_]*)/g);
|
|
29
|
-
return matches ? matches.map((m) => m.slice(1)) : [];
|
|
30
|
-
}
|
|
31
|
-
/**
|
|
32
|
-
* Execute an HTTP request to a cRPC endpoint
|
|
33
|
-
*/
|
|
34
|
-
async function executeHttpRequest(opts) {
|
|
35
|
-
const { method, path } = opts.route;
|
|
36
|
-
const input = opts.input;
|
|
37
|
-
const pathParamNames = extractPathParamNames(path);
|
|
38
|
-
let url = opts.convexSiteUrl + path.replace(/:(\w+)/g, (_, key) => {
|
|
39
|
-
const value = input?.[key];
|
|
40
|
-
return value !== null && value !== void 0 ? encodeURIComponent(String(value)) : "";
|
|
41
|
-
});
|
|
42
|
-
const headers = typeof opts.headers === "function" ? await opts.headers() : opts.headers;
|
|
43
|
-
let body;
|
|
44
|
-
if (method === "GET") {
|
|
45
|
-
const queryInput = input ? Object.fromEntries(Object.entries(input).filter(([k]) => !pathParamNames.includes(k))) : {};
|
|
46
|
-
if (Object.keys(queryInput).length > 0) {
|
|
47
|
-
const params = new URLSearchParams();
|
|
48
|
-
for (const [key, value] of Object.entries(queryInput)) if (value !== void 0 && value !== null) params.append(key, String(value));
|
|
49
|
-
const queryString = params.toString();
|
|
50
|
-
if (queryString) url += `?${queryString}`;
|
|
51
|
-
}
|
|
52
|
-
} else {
|
|
53
|
-
const bodyInput = input ? Object.fromEntries(Object.entries(input).filter(([k]) => !pathParamNames.includes(k))) : {};
|
|
54
|
-
if (Object.keys(bodyInput).length > 0) body = JSON.stringify(bodyInput);
|
|
55
|
-
}
|
|
56
|
-
const response = await (opts.fetch ?? globalThis.fetch)(url, {
|
|
57
|
-
method,
|
|
58
|
-
headers: {
|
|
59
|
-
"Content-Type": "application/json",
|
|
60
|
-
...headers
|
|
61
|
-
},
|
|
62
|
-
body
|
|
63
|
-
});
|
|
64
|
-
if (!response.ok) {
|
|
65
|
-
const errorData = await response.json().catch(() => ({ error: {
|
|
66
|
-
code: "UNKNOWN",
|
|
67
|
-
message: response.statusText
|
|
68
|
-
} }));
|
|
69
|
-
const errorCode = errorData?.error?.code || "UNKNOWN";
|
|
70
|
-
const errorMessage = errorData?.error?.message || response.statusText;
|
|
71
|
-
throw new HttpClientError({
|
|
72
|
-
code: errorCode,
|
|
73
|
-
status: response.status,
|
|
74
|
-
procedureName: opts.procedureName,
|
|
75
|
-
message: errorMessage
|
|
76
|
-
});
|
|
77
|
-
}
|
|
78
|
-
if (response.headers.get("content-length") === "0" || response.status === 204) return;
|
|
79
|
-
return response.json();
|
|
80
|
-
}
|
|
81
|
-
/**
|
|
82
|
-
* Create a recursive proxy for nested route access
|
|
83
|
-
* Tracks path segments and executes request when function is called
|
|
84
|
-
*/
|
|
85
|
-
function createRecursiveProxy(opts, path = []) {
|
|
86
|
-
return new Proxy(() => {}, {
|
|
87
|
-
get(_, key) {
|
|
88
|
-
return createRecursiveProxy(opts, [...path, key]);
|
|
89
|
-
},
|
|
90
|
-
apply(_, __, args) {
|
|
91
|
-
const procedureName = path.join(".");
|
|
92
|
-
const route = opts.routes[procedureName];
|
|
93
|
-
if (!route) throw new Error(`Unknown HTTP procedure: ${procedureName}`);
|
|
94
|
-
return (async () => {
|
|
95
|
-
try {
|
|
96
|
-
return await executeHttpRequest({
|
|
97
|
-
convexSiteUrl: opts.convexSiteUrl,
|
|
98
|
-
route,
|
|
99
|
-
procedureName,
|
|
100
|
-
input: args[0],
|
|
101
|
-
headers: opts.headers,
|
|
102
|
-
fetch: opts.fetch
|
|
103
|
-
});
|
|
104
|
-
} catch (error) {
|
|
105
|
-
if (opts.onError && error instanceof HttpClientError) opts.onError(error);
|
|
106
|
-
throw error;
|
|
107
|
-
}
|
|
108
|
-
})();
|
|
109
|
-
}
|
|
110
|
-
});
|
|
111
|
-
}
|
|
112
|
-
function createHttpClient(opts) {
|
|
113
|
-
const { convexSiteUrl, routes, headers, fetch: customFetch, onError } = opts;
|
|
114
|
-
return createRecursiveProxy({
|
|
115
|
-
convexSiteUrl,
|
|
116
|
-
routes,
|
|
117
|
-
headers,
|
|
118
|
-
fetch: customFetch,
|
|
119
|
-
onError
|
|
120
|
-
});
|
|
121
|
-
}
|
|
122
|
-
|
|
123
21
|
//#endregion
|
|
124
22
|
//#region src/crpc/types.ts
|
|
125
23
|
/** Symbol key for attaching FunctionReference to options (non-serializable) */
|
|
126
24
|
const FUNC_REF_SYMBOL = Symbol.for("convex.funcRef");
|
|
127
25
|
|
|
128
26
|
//#endregion
|
|
129
|
-
export { CRPCClientError, FUNC_REF_SYMBOL, HttpClientError, convexAction, convexInfiniteQueryOptions, convexQuery,
|
|
27
|
+
export { CRPCClientError, FUNC_REF_SYMBOL, HttpClientError, convexAction, convexInfiniteQueryOptions, convexQuery, defaultIsUnauthorized, isCRPCClientError, isCRPCErrorCode, isHttpClientError };
|