@convex-dev/better-auth 0.6.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.
Files changed (181) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +44 -0
  3. package/dist/commonjs/client/adapter.d.ts +4 -0
  4. package/dist/commonjs/client/adapter.d.ts.map +1 -0
  5. package/dist/commonjs/client/adapter.js +189 -0
  6. package/dist/commonjs/client/adapter.js.map +1 -0
  7. package/dist/commonjs/client/cors.d.ts +72 -0
  8. package/dist/commonjs/client/cors.d.ts.map +1 -0
  9. package/dist/commonjs/client/cors.js +281 -0
  10. package/dist/commonjs/client/cors.js.map +1 -0
  11. package/dist/commonjs/client/index.d.ts +302 -0
  12. package/dist/commonjs/client/index.d.ts.map +1 -0
  13. package/dist/commonjs/client/index.js +232 -0
  14. package/dist/commonjs/client/index.js.map +1 -0
  15. package/dist/commonjs/client/plugins/index.d.ts +3 -0
  16. package/dist/commonjs/client/plugins/index.d.ts.map +1 -0
  17. package/dist/commonjs/client/plugins/index.js +3 -0
  18. package/dist/commonjs/client/plugins/index.js.map +1 -0
  19. package/dist/commonjs/component/_generated/api.d.ts +12 -0
  20. package/dist/commonjs/component/_generated/api.d.ts.map +1 -0
  21. package/dist/commonjs/component/_generated/api.js +22 -0
  22. package/dist/commonjs/component/_generated/api.js.map +1 -0
  23. package/dist/commonjs/component/_generated/server.d.ts +64 -0
  24. package/dist/commonjs/component/_generated/server.d.ts.map +1 -0
  25. package/dist/commonjs/component/_generated/server.js +74 -0
  26. package/dist/commonjs/component/_generated/server.js.map +1 -0
  27. package/dist/commonjs/component/convex.config.d.ts +3 -0
  28. package/dist/commonjs/component/convex.config.d.ts.map +1 -0
  29. package/dist/commonjs/component/convex.config.js +4 -0
  30. package/dist/commonjs/component/convex.config.js.map +1 -0
  31. package/dist/commonjs/component/lib.d.ts +584 -0
  32. package/dist/commonjs/component/lib.d.ts.map +1 -0
  33. package/dist/commonjs/component/lib.js +323 -0
  34. package/dist/commonjs/component/lib.js.map +1 -0
  35. package/dist/commonjs/component/schema.d.ts +116 -0
  36. package/dist/commonjs/component/schema.d.ts.map +1 -0
  37. package/dist/commonjs/component/schema.js +68 -0
  38. package/dist/commonjs/component/schema.js.map +1 -0
  39. package/dist/commonjs/component/util.d.ts +394 -0
  40. package/dist/commonjs/component/util.d.ts.map +1 -0
  41. package/dist/commonjs/component/util.js +4 -0
  42. package/dist/commonjs/component/util.js.map +1 -0
  43. package/dist/commonjs/nextjs/index.d.ts +10 -0
  44. package/dist/commonjs/nextjs/index.d.ts.map +1 -0
  45. package/dist/commonjs/nextjs/index.js +23 -0
  46. package/dist/commonjs/nextjs/index.js.map +1 -0
  47. package/dist/commonjs/package.json +3 -0
  48. package/dist/commonjs/plugins/convex/client.d.ts +6 -0
  49. package/dist/commonjs/plugins/convex/client.d.ts.map +1 -0
  50. package/dist/commonjs/plugins/convex/client.js +7 -0
  51. package/dist/commonjs/plugins/convex/client.js.map +1 -0
  52. package/dist/commonjs/plugins/convex/index.d.ts +280 -0
  53. package/dist/commonjs/plugins/convex/index.d.ts.map +1 -0
  54. package/dist/commonjs/plugins/convex/index.js +253 -0
  55. package/dist/commonjs/plugins/convex/index.js.map +1 -0
  56. package/dist/commonjs/plugins/cross-domain/client.d.ts +123 -0
  57. package/dist/commonjs/plugins/cross-domain/client.d.ts.map +1 -0
  58. package/dist/commonjs/plugins/cross-domain/client.js +164 -0
  59. package/dist/commonjs/plugins/cross-domain/client.js.map +1 -0
  60. package/dist/commonjs/plugins/cross-domain/index.d.ts +81 -0
  61. package/dist/commonjs/plugins/cross-domain/index.d.ts.map +1 -0
  62. package/dist/commonjs/plugins/cross-domain/index.js +135 -0
  63. package/dist/commonjs/plugins/cross-domain/index.js.map +1 -0
  64. package/dist/commonjs/plugins/index.d.ts +3 -0
  65. package/dist/commonjs/plugins/index.d.ts.map +1 -0
  66. package/dist/commonjs/plugins/index.js +3 -0
  67. package/dist/commonjs/plugins/index.js.map +1 -0
  68. package/dist/commonjs/react/client.d.ts +31 -0
  69. package/dist/commonjs/react/client.d.ts.map +1 -0
  70. package/dist/commonjs/react/client.js +102 -0
  71. package/dist/commonjs/react/client.js.map +1 -0
  72. package/dist/commonjs/react/index.d.ts +9 -0
  73. package/dist/commonjs/react/index.d.ts.map +1 -0
  74. package/dist/commonjs/react/index.js +15 -0
  75. package/dist/commonjs/react/index.js.map +1 -0
  76. package/dist/commonjs/react-start/index.d.ts +10 -0
  77. package/dist/commonjs/react-start/index.d.ts.map +1 -0
  78. package/dist/commonjs/react-start/index.js +32 -0
  79. package/dist/commonjs/react-start/index.js.map +1 -0
  80. package/dist/esm/client/adapter.d.ts +4 -0
  81. package/dist/esm/client/adapter.d.ts.map +1 -0
  82. package/dist/esm/client/adapter.js +189 -0
  83. package/dist/esm/client/adapter.js.map +1 -0
  84. package/dist/esm/client/cors.d.ts +72 -0
  85. package/dist/esm/client/cors.d.ts.map +1 -0
  86. package/dist/esm/client/cors.js +281 -0
  87. package/dist/esm/client/cors.js.map +1 -0
  88. package/dist/esm/client/index.d.ts +302 -0
  89. package/dist/esm/client/index.d.ts.map +1 -0
  90. package/dist/esm/client/index.js +232 -0
  91. package/dist/esm/client/index.js.map +1 -0
  92. package/dist/esm/client/plugins/index.d.ts +3 -0
  93. package/dist/esm/client/plugins/index.d.ts.map +1 -0
  94. package/dist/esm/client/plugins/index.js +3 -0
  95. package/dist/esm/client/plugins/index.js.map +1 -0
  96. package/dist/esm/component/_generated/api.d.ts +12 -0
  97. package/dist/esm/component/_generated/api.d.ts.map +1 -0
  98. package/dist/esm/component/_generated/api.js +22 -0
  99. package/dist/esm/component/_generated/api.js.map +1 -0
  100. package/dist/esm/component/_generated/server.d.ts +64 -0
  101. package/dist/esm/component/_generated/server.d.ts.map +1 -0
  102. package/dist/esm/component/_generated/server.js +74 -0
  103. package/dist/esm/component/_generated/server.js.map +1 -0
  104. package/dist/esm/component/convex.config.d.ts +3 -0
  105. package/dist/esm/component/convex.config.d.ts.map +1 -0
  106. package/dist/esm/component/convex.config.js +4 -0
  107. package/dist/esm/component/convex.config.js.map +1 -0
  108. package/dist/esm/component/lib.d.ts +584 -0
  109. package/dist/esm/component/lib.d.ts.map +1 -0
  110. package/dist/esm/component/lib.js +323 -0
  111. package/dist/esm/component/lib.js.map +1 -0
  112. package/dist/esm/component/schema.d.ts +116 -0
  113. package/dist/esm/component/schema.d.ts.map +1 -0
  114. package/dist/esm/component/schema.js +68 -0
  115. package/dist/esm/component/schema.js.map +1 -0
  116. package/dist/esm/component/util.d.ts +394 -0
  117. package/dist/esm/component/util.d.ts.map +1 -0
  118. package/dist/esm/component/util.js +4 -0
  119. package/dist/esm/component/util.js.map +1 -0
  120. package/dist/esm/nextjs/index.d.ts +10 -0
  121. package/dist/esm/nextjs/index.d.ts.map +1 -0
  122. package/dist/esm/nextjs/index.js +23 -0
  123. package/dist/esm/nextjs/index.js.map +1 -0
  124. package/dist/esm/package.json +3 -0
  125. package/dist/esm/plugins/convex/client.d.ts +6 -0
  126. package/dist/esm/plugins/convex/client.d.ts.map +1 -0
  127. package/dist/esm/plugins/convex/client.js +7 -0
  128. package/dist/esm/plugins/convex/client.js.map +1 -0
  129. package/dist/esm/plugins/convex/index.d.ts +280 -0
  130. package/dist/esm/plugins/convex/index.d.ts.map +1 -0
  131. package/dist/esm/plugins/convex/index.js +253 -0
  132. package/dist/esm/plugins/convex/index.js.map +1 -0
  133. package/dist/esm/plugins/cross-domain/client.d.ts +123 -0
  134. package/dist/esm/plugins/cross-domain/client.d.ts.map +1 -0
  135. package/dist/esm/plugins/cross-domain/client.js +164 -0
  136. package/dist/esm/plugins/cross-domain/client.js.map +1 -0
  137. package/dist/esm/plugins/cross-domain/index.d.ts +81 -0
  138. package/dist/esm/plugins/cross-domain/index.d.ts.map +1 -0
  139. package/dist/esm/plugins/cross-domain/index.js +135 -0
  140. package/dist/esm/plugins/cross-domain/index.js.map +1 -0
  141. package/dist/esm/plugins/index.d.ts +3 -0
  142. package/dist/esm/plugins/index.d.ts.map +1 -0
  143. package/dist/esm/plugins/index.js +3 -0
  144. package/dist/esm/plugins/index.js.map +1 -0
  145. package/dist/esm/react/client.d.ts +31 -0
  146. package/dist/esm/react/client.d.ts.map +1 -0
  147. package/dist/esm/react/client.js +102 -0
  148. package/dist/esm/react/client.js.map +1 -0
  149. package/dist/esm/react/index.d.ts +9 -0
  150. package/dist/esm/react/index.d.ts.map +1 -0
  151. package/dist/esm/react/index.js +15 -0
  152. package/dist/esm/react/index.js.map +1 -0
  153. package/dist/esm/react-start/index.d.ts +10 -0
  154. package/dist/esm/react-start/index.d.ts.map +1 -0
  155. package/dist/esm/react-start/index.js +32 -0
  156. package/dist/esm/react-start/index.js.map +1 -0
  157. package/package.json +161 -0
  158. package/plugins/package.json +5 -0
  159. package/react/package.json +5 -0
  160. package/src/client/adapter.ts +236 -0
  161. package/src/client/cors.ts +403 -0
  162. package/src/client/index.ts +381 -0
  163. package/src/client/plugins/index.ts +2 -0
  164. package/src/component/_generated/api.d.ts +313 -0
  165. package/src/component/_generated/api.js +23 -0
  166. package/src/component/_generated/dataModel.d.ts +60 -0
  167. package/src/component/_generated/server.d.ts +149 -0
  168. package/src/component/_generated/server.js +90 -0
  169. package/src/component/convex.config.ts +5 -0
  170. package/src/component/lib.ts +391 -0
  171. package/src/component/schema.ts +74 -0
  172. package/src/component/util.ts +4 -0
  173. package/src/nextjs/index.ts +30 -0
  174. package/src/plugins/convex/client.ts +9 -0
  175. package/src/plugins/convex/index.ts +296 -0
  176. package/src/plugins/cross-domain/client.ts +209 -0
  177. package/src/plugins/cross-domain/index.ts +156 -0
  178. package/src/plugins/index.ts +2 -0
  179. package/src/react/client.tsx +184 -0
  180. package/src/react/index.tsx +38 -0
  181. package/src/react-start/index.ts +51 -0
@@ -0,0 +1,60 @@
1
+ /* eslint-disable */
2
+ /**
3
+ * Generated data model types.
4
+ *
5
+ * THIS CODE IS AUTOMATICALLY GENERATED.
6
+ *
7
+ * To regenerate, run `npx convex dev`.
8
+ * @module
9
+ */
10
+
11
+ import type {
12
+ DataModelFromSchemaDefinition,
13
+ DocumentByName,
14
+ TableNamesInDataModel,
15
+ SystemTableNames,
16
+ } from "convex/server";
17
+ import type { GenericId } from "convex/values";
18
+ import schema from "../schema.js";
19
+
20
+ /**
21
+ * The names of all of your Convex tables.
22
+ */
23
+ export type TableNames = TableNamesInDataModel<DataModel>;
24
+
25
+ /**
26
+ * The type of a document stored in Convex.
27
+ *
28
+ * @typeParam TableName - A string literal type of the table name (like "users").
29
+ */
30
+ export type Doc<TableName extends TableNames> = DocumentByName<
31
+ DataModel,
32
+ TableName
33
+ >;
34
+
35
+ /**
36
+ * An identifier for a document in Convex.
37
+ *
38
+ * Convex documents are uniquely identified by their `Id`, which is accessible
39
+ * on the `_id` field. To learn more, see [Document IDs](https://docs.convex.dev/using/document-ids).
40
+ *
41
+ * Documents can be loaded using `db.get(id)` in query and mutation functions.
42
+ *
43
+ * IDs are just strings at runtime, but this type can be used to distinguish them from other
44
+ * strings when type checking.
45
+ *
46
+ * @typeParam TableName - A string literal type of the table name (like "users").
47
+ */
48
+ export type Id<TableName extends TableNames | SystemTableNames> =
49
+ GenericId<TableName>;
50
+
51
+ /**
52
+ * A type describing your Convex data model.
53
+ *
54
+ * This type includes information about what tables you have, the type of
55
+ * documents stored in those tables, and the indexes defined on them.
56
+ *
57
+ * This type is used to parameterize methods like `queryGeneric` and
58
+ * `mutationGeneric` to make them type-safe.
59
+ */
60
+ export type DataModel = DataModelFromSchemaDefinition<typeof schema>;
@@ -0,0 +1,149 @@
1
+ /* eslint-disable */
2
+ /**
3
+ * Generated utilities for implementing server-side Convex query and mutation functions.
4
+ *
5
+ * THIS CODE IS AUTOMATICALLY GENERATED.
6
+ *
7
+ * To regenerate, run `npx convex dev`.
8
+ * @module
9
+ */
10
+
11
+ import {
12
+ ActionBuilder,
13
+ AnyComponents,
14
+ HttpActionBuilder,
15
+ MutationBuilder,
16
+ QueryBuilder,
17
+ GenericActionCtx,
18
+ GenericMutationCtx,
19
+ GenericQueryCtx,
20
+ GenericDatabaseReader,
21
+ GenericDatabaseWriter,
22
+ FunctionReference,
23
+ } from "convex/server";
24
+ import type { DataModel } from "./dataModel.js";
25
+
26
+ type GenericCtx =
27
+ | GenericActionCtx<DataModel>
28
+ | GenericMutationCtx<DataModel>
29
+ | GenericQueryCtx<DataModel>;
30
+
31
+ /**
32
+ * Define a query in this Convex app's public API.
33
+ *
34
+ * This function will be allowed to read your Convex database and will be accessible from the client.
35
+ *
36
+ * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
37
+ * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
38
+ */
39
+ export declare const query: QueryBuilder<DataModel, "public">;
40
+
41
+ /**
42
+ * Define a query that is only accessible from other Convex functions (but not from the client).
43
+ *
44
+ * This function will be allowed to read from your Convex database. It will not be accessible from the client.
45
+ *
46
+ * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
47
+ * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
48
+ */
49
+ export declare const internalQuery: QueryBuilder<DataModel, "internal">;
50
+
51
+ /**
52
+ * Define a mutation in this Convex app's public API.
53
+ *
54
+ * This function will be allowed to modify your Convex database and will be accessible from the client.
55
+ *
56
+ * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
57
+ * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
58
+ */
59
+ export declare const mutation: MutationBuilder<DataModel, "public">;
60
+
61
+ /**
62
+ * Define a mutation that is only accessible from other Convex functions (but not from the client).
63
+ *
64
+ * This function will be allowed to modify your Convex database. It will not be accessible from the client.
65
+ *
66
+ * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
67
+ * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
68
+ */
69
+ export declare const internalMutation: MutationBuilder<DataModel, "internal">;
70
+
71
+ /**
72
+ * Define an action in this Convex app's public API.
73
+ *
74
+ * An action is a function which can execute any JavaScript code, including non-deterministic
75
+ * code and code with side-effects, like calling third-party services.
76
+ * They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive.
77
+ * They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}.
78
+ *
79
+ * @param func - The action. It receives an {@link ActionCtx} as its first argument.
80
+ * @returns The wrapped action. Include this as an `export` to name it and make it accessible.
81
+ */
82
+ export declare const action: ActionBuilder<DataModel, "public">;
83
+
84
+ /**
85
+ * Define an action that is only accessible from other Convex functions (but not from the client).
86
+ *
87
+ * @param func - The function. It receives an {@link ActionCtx} as its first argument.
88
+ * @returns The wrapped function. Include this as an `export` to name it and make it accessible.
89
+ */
90
+ export declare const internalAction: ActionBuilder<DataModel, "internal">;
91
+
92
+ /**
93
+ * Define an HTTP action.
94
+ *
95
+ * This function will be used to respond to HTTP requests received by a Convex
96
+ * deployment if the requests matches the path and method where this action
97
+ * is routed. Be sure to route your action in `convex/http.js`.
98
+ *
99
+ * @param func - The function. It receives an {@link ActionCtx} as its first argument.
100
+ * @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up.
101
+ */
102
+ export declare const httpAction: HttpActionBuilder;
103
+
104
+ /**
105
+ * A set of services for use within Convex query functions.
106
+ *
107
+ * The query context is passed as the first argument to any Convex query
108
+ * function run on the server.
109
+ *
110
+ * This differs from the {@link MutationCtx} because all of the services are
111
+ * read-only.
112
+ */
113
+ export type QueryCtx = GenericQueryCtx<DataModel>;
114
+
115
+ /**
116
+ * A set of services for use within Convex mutation functions.
117
+ *
118
+ * The mutation context is passed as the first argument to any Convex mutation
119
+ * function run on the server.
120
+ */
121
+ export type MutationCtx = GenericMutationCtx<DataModel>;
122
+
123
+ /**
124
+ * A set of services for use within Convex action functions.
125
+ *
126
+ * The action context is passed as the first argument to any Convex action
127
+ * function run on the server.
128
+ */
129
+ export type ActionCtx = GenericActionCtx<DataModel>;
130
+
131
+ /**
132
+ * An interface to read from the database within Convex query functions.
133
+ *
134
+ * The two entry points are {@link DatabaseReader.get}, which fetches a single
135
+ * document by its {@link Id}, or {@link DatabaseReader.query}, which starts
136
+ * building a query.
137
+ */
138
+ export type DatabaseReader = GenericDatabaseReader<DataModel>;
139
+
140
+ /**
141
+ * An interface to read from and write to the database within Convex mutation
142
+ * functions.
143
+ *
144
+ * Convex guarantees that all writes within a single mutation are
145
+ * executed atomically, so you never have to worry about partial writes leaving
146
+ * your data in an inconsistent state. See [the Convex Guide](https://docs.convex.dev/understanding/convex-fundamentals/functions#atomicity-and-optimistic-concurrency-control)
147
+ * for the guarantees Convex provides your functions.
148
+ */
149
+ export type DatabaseWriter = GenericDatabaseWriter<DataModel>;
@@ -0,0 +1,90 @@
1
+ /* eslint-disable */
2
+ /**
3
+ * Generated utilities for implementing server-side Convex query and mutation functions.
4
+ *
5
+ * THIS CODE IS AUTOMATICALLY GENERATED.
6
+ *
7
+ * To regenerate, run `npx convex dev`.
8
+ * @module
9
+ */
10
+
11
+ import {
12
+ actionGeneric,
13
+ httpActionGeneric,
14
+ queryGeneric,
15
+ mutationGeneric,
16
+ internalActionGeneric,
17
+ internalMutationGeneric,
18
+ internalQueryGeneric,
19
+ componentsGeneric,
20
+ } from "convex/server";
21
+
22
+ /**
23
+ * Define a query in this Convex app's public API.
24
+ *
25
+ * This function will be allowed to read your Convex database and will be accessible from the client.
26
+ *
27
+ * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
28
+ * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
29
+ */
30
+ export const query = queryGeneric;
31
+
32
+ /**
33
+ * Define a query that is only accessible from other Convex functions (but not from the client).
34
+ *
35
+ * This function will be allowed to read from your Convex database. It will not be accessible from the client.
36
+ *
37
+ * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
38
+ * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
39
+ */
40
+ export const internalQuery = internalQueryGeneric;
41
+
42
+ /**
43
+ * Define a mutation in this Convex app's public API.
44
+ *
45
+ * This function will be allowed to modify your Convex database and will be accessible from the client.
46
+ *
47
+ * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
48
+ * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
49
+ */
50
+ export const mutation = mutationGeneric;
51
+
52
+ /**
53
+ * Define a mutation that is only accessible from other Convex functions (but not from the client).
54
+ *
55
+ * This function will be allowed to modify your Convex database. It will not be accessible from the client.
56
+ *
57
+ * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
58
+ * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
59
+ */
60
+ export const internalMutation = internalMutationGeneric;
61
+
62
+ /**
63
+ * Define an action in this Convex app's public API.
64
+ *
65
+ * An action is a function which can execute any JavaScript code, including non-deterministic
66
+ * code and code with side-effects, like calling third-party services.
67
+ * They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive.
68
+ * They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}.
69
+ *
70
+ * @param func - The action. It receives an {@link ActionCtx} as its first argument.
71
+ * @returns The wrapped action. Include this as an `export` to name it and make it accessible.
72
+ */
73
+ export const action = actionGeneric;
74
+
75
+ /**
76
+ * Define an action that is only accessible from other Convex functions (but not from the client).
77
+ *
78
+ * @param func - The function. It receives an {@link ActionCtx} as its first argument.
79
+ * @returns The wrapped function. Include this as an `export` to name it and make it accessible.
80
+ */
81
+ export const internalAction = internalActionGeneric;
82
+
83
+ /**
84
+ * Define a Convex HTTP action.
85
+ *
86
+ * @param func - The function. It receives an {@link ActionCtx} as its first argument, and a `Request` object
87
+ * as its second.
88
+ * @returns The wrapped endpoint function. Route a URL path to this function in `convex/http.js`.
89
+ */
90
+ export const httpAction = httpActionGeneric;
@@ -0,0 +1,5 @@
1
+ import { defineComponent } from "convex/server";
2
+
3
+ const component = defineComponent("betterAuth");
4
+
5
+ export default component;
@@ -0,0 +1,391 @@
1
+ import {
2
+ action,
3
+ mutation,
4
+ query,
5
+ QueryCtx,
6
+ } from "../component/_generated/server";
7
+ import { asyncMap } from "convex-helpers";
8
+ import { v } from "convex/values";
9
+ import { api } from "../component/_generated/api";
10
+ import { Doc, Id, TableNames } from "../component/_generated/dataModel";
11
+ import schema from "../component/schema";
12
+ import { paginationOptsValidator, PaginationResult } from "convex/server";
13
+ import { paginator } from "convex-helpers/server/pagination";
14
+ import { partial } from "convex-helpers/validators";
15
+
16
+ export const transformInput = (model: string, data: Record<string, any>) => {
17
+ return {
18
+ ...Object.fromEntries(
19
+ Object.entries(data).map(([key, value]) => {
20
+ if (value instanceof Date) {
21
+ return [key, value.getTime()];
22
+ }
23
+ return [key, value];
24
+ })
25
+ ),
26
+ };
27
+ };
28
+
29
+ export const transformOutput = (
30
+ { _id, _creationTime, ...data }: Doc<TableNames>,
31
+ _model: string
32
+ ) => {
33
+ // Provide the expected id field, but it can be overwritten if
34
+ // the model has an id field
35
+ return { id: _id, ...data };
36
+ };
37
+
38
+ // Get the session via sessionId in jwt claims
39
+ export const getCurrentSession = query({
40
+ args: {},
41
+ handler: async (ctx) => {
42
+ const identity = await ctx.auth.getUserIdentity();
43
+ if (!identity) {
44
+ return null;
45
+ }
46
+ return ctx.db.get(identity.sessionId as Id<"session">);
47
+ },
48
+ });
49
+
50
+ export const getByHelper = async (
51
+ ctx: QueryCtx,
52
+ args: {
53
+ table: string;
54
+ field: string;
55
+ value: any;
56
+ unique?: boolean;
57
+ }
58
+ ) => {
59
+ if (args.field === "id") {
60
+ return ctx.db.get(args.value);
61
+ }
62
+ const query = ctx.db
63
+ .query(args.table as any)
64
+ .withIndex(args.field as any, (q) => q.eq(args.field, args.value));
65
+ return args.unique ? await query.unique() : await query.first();
66
+ };
67
+
68
+ export const getByArgsValidator = {
69
+ table: v.string(),
70
+ field: v.string(),
71
+ unique: v.optional(v.boolean()),
72
+ value: v.union(
73
+ v.string(),
74
+ v.number(),
75
+ v.boolean(),
76
+ v.array(v.string()),
77
+ v.array(v.number()),
78
+ v.null()
79
+ ),
80
+ };
81
+
82
+ // Generic functions
83
+ export const getByQuery = query({
84
+ args: getByArgsValidator,
85
+ handler: async (ctx, args) => {
86
+ const doc = await getByHelper(ctx, args);
87
+ if (!doc) {
88
+ return;
89
+ }
90
+ return transformOutput(doc, args.table);
91
+ },
92
+ });
93
+ export { getByQuery as getBy };
94
+
95
+ export const create = mutation({
96
+ args: v.object({
97
+ input: v.union(
98
+ ...Object.values(schema.tables).map((table) =>
99
+ v.object({
100
+ table: v.string(),
101
+ ...table.validator.fields,
102
+ })
103
+ )
104
+ ),
105
+ }),
106
+ handler: async (ctx, args) => {
107
+ const { table, ...input } = args.input;
108
+ const id = await ctx.db.insert(table as any, {
109
+ ...input,
110
+ });
111
+ const doc = await ctx.db.get(id);
112
+ if (!doc) {
113
+ throw new Error(`Failed to create ${table}`);
114
+ }
115
+ return transformOutput(doc, table);
116
+ },
117
+ });
118
+
119
+ export const updateArgsInputValidator = <T extends TableNames>(table: T) => {
120
+ return v.object({
121
+ table: v.literal(table),
122
+ where: v.object({ field: v.string(), value: getByArgsValidator.value }),
123
+ value: v.record(v.string(), v.any()),
124
+ });
125
+ };
126
+
127
+ const updateArgsValidator = {
128
+ input: v.union(
129
+ updateArgsInputValidator("account"),
130
+ updateArgsInputValidator("session"),
131
+ updateArgsInputValidator("verification"),
132
+ updateArgsInputValidator("user")
133
+ ),
134
+ };
135
+
136
+ export const update = mutation({
137
+ args: updateArgsValidator,
138
+ handler: async (ctx, args) => {
139
+ const { table, where, value } = args.input;
140
+ const doc =
141
+ where.field === "id"
142
+ ? await ctx.db.get(where.value as Id<any>)
143
+ : await getByHelper(ctx, { table, ...where });
144
+ if (!doc) {
145
+ throw new Error(`Failed to update ${table}`);
146
+ }
147
+ await ctx.db.patch(doc._id, value as any);
148
+ const updatedDoc = await ctx.db.get(doc._id);
149
+ if (!updatedDoc) {
150
+ throw new Error(`Failed to update ${table}`);
151
+ }
152
+ return transformOutput(updatedDoc, table);
153
+ },
154
+ });
155
+
156
+ export const deleteBy = mutation({
157
+ args: getByArgsValidator,
158
+ handler: async (ctx, args) => {
159
+ const doc = await getByHelper(ctx, args);
160
+ if (!doc) {
161
+ return;
162
+ }
163
+ await ctx.db.delete(doc._id);
164
+ // onDeleteUser requires userId from the doc,
165
+ // so just return the whole thing
166
+ return doc;
167
+ },
168
+ });
169
+
170
+ // Single purpose functions
171
+ export const getAccountsByUserId = query({
172
+ args: { userId: v.string(), limit: v.optional(v.number()) },
173
+ handler: async (ctx, args) => {
174
+ const query = ctx.db
175
+ .query("account")
176
+ .withIndex("userId", (q) => q.eq("userId", args.userId));
177
+ const docs = args.limit
178
+ ? await query.take(args.limit)
179
+ : await query.collect();
180
+ return docs.map((doc) => transformOutput(doc, "account"));
181
+ },
182
+ });
183
+
184
+ export const getJwks = query({
185
+ args: {
186
+ limit: v.optional(v.number()),
187
+ },
188
+ handler: async (ctx, args) => {
189
+ const query = ctx.db.query("jwks");
190
+ const docs = args.limit
191
+ ? await query.take(args.limit)
192
+ : await query.collect();
193
+ return docs.map((doc) => transformOutput(doc, "jwks"));
194
+ },
195
+ });
196
+
197
+ export const listVerificationsByIdentifier = query({
198
+ args: {
199
+ identifier: v.string(),
200
+ sortBy: v.optional(
201
+ v.object({
202
+ field: v.string(),
203
+ direction: v.union(v.literal("asc"), v.literal("desc")),
204
+ })
205
+ ),
206
+ limit: v.optional(v.number()),
207
+ },
208
+ handler: async (ctx, args) => {
209
+ if (args.sortBy && args.sortBy.field !== "createdAt") {
210
+ throw new Error(`Unsupported sortBy field: ${args.sortBy.field}`);
211
+ }
212
+ const query = ctx.db
213
+ .query("verification")
214
+ .withIndex("identifier", (q) => q.eq("identifier", args.identifier))
215
+ .order(
216
+ args.sortBy?.field === "createdAt" && args.sortBy?.direction
217
+ ? args.sortBy.direction
218
+ : "asc"
219
+ );
220
+ const docs = args.limit
221
+ ? await query.take(args.limit)
222
+ : await query.collect();
223
+ return docs.map((doc) => transformOutput(doc, "verification"));
224
+ },
225
+ });
226
+
227
+ export const deleteOldVerificationsPage = mutation({
228
+ args: {
229
+ currentTimestamp: v.number(),
230
+ paginationOpts: v.optional(paginationOptsValidator),
231
+ },
232
+ handler: async (ctx, args) => {
233
+ const paginationOpts = args.paginationOpts ?? {
234
+ numItems: 500,
235
+ cursor: null,
236
+ };
237
+ const { page, ...result } = await paginator(ctx.db, schema)
238
+ .query("verification")
239
+ .withIndex("expiresAt", (q) => q.lt("expiresAt", args.currentTimestamp))
240
+ .paginate(paginationOpts);
241
+ await asyncMap(page, async (doc) => {
242
+ await ctx.db.delete(doc._id);
243
+ });
244
+ return { ...result, count: page.length };
245
+ },
246
+ });
247
+
248
+ export const deleteOldVerifications = action({
249
+ args: {
250
+ currentTimestamp: v.number(),
251
+ },
252
+ handler: async (ctx, args) => {
253
+ let count = 0;
254
+ let cursor = null;
255
+ let isDone = false;
256
+ do {
257
+ const result: Omit<PaginationResult<Doc<"verification">>, "page"> & {
258
+ count: number;
259
+ } = await ctx.runMutation(api.lib.deleteOldVerificationsPage, {
260
+ currentTimestamp: args.currentTimestamp,
261
+ paginationOpts: {
262
+ numItems: 500,
263
+ cursor,
264
+ },
265
+ });
266
+ count += result.count;
267
+ cursor =
268
+ result.pageStatus &&
269
+ result.splitCursor &&
270
+ ["SplitRecommended", "SplitRequired"].includes(result.pageStatus)
271
+ ? result.splitCursor
272
+ : result.continueCursor;
273
+ isDone = result.isDone;
274
+ } while (!isDone);
275
+ return count;
276
+ },
277
+ });
278
+
279
+ export const deleteAllForUserPage = mutation({
280
+ args: {
281
+ table: v.string(),
282
+ userId: v.string(),
283
+ paginationOpts: v.optional(paginationOptsValidator),
284
+ },
285
+ handler: async (ctx, args) => {
286
+ const paginationOpts = args.paginationOpts ?? {
287
+ numItems: 500,
288
+ cursor: null,
289
+ };
290
+ const { page, ...result } = await paginator(ctx.db, schema)
291
+ .query(args.table as any)
292
+ .withIndex("userId", (q) => q.eq("userId", args.userId))
293
+ .paginate(paginationOpts);
294
+ await asyncMap(page, async (doc) => {
295
+ await ctx.db.delete(doc._id);
296
+ });
297
+ return { ...result, count: page.length };
298
+ },
299
+ });
300
+
301
+ export const deleteAllForUser = action({
302
+ args: {
303
+ table: v.string(),
304
+ userId: v.string(),
305
+ },
306
+ handler: async (ctx, args) => {
307
+ let count = 0;
308
+ let cursor = null;
309
+ let isDone = false;
310
+ do {
311
+ const result: Omit<PaginationResult<Doc<"session">>, "page"> & {
312
+ count: number;
313
+ } = await ctx.runMutation(api.lib.deleteAllForUserPage, {
314
+ table: args.table,
315
+ userId: args.userId,
316
+ paginationOpts: {
317
+ numItems: 500,
318
+ cursor,
319
+ },
320
+ });
321
+ count += result.count;
322
+ cursor =
323
+ result.pageStatus &&
324
+ result.splitCursor &&
325
+ ["SplitRecommended", "SplitRequired"].includes(result.pageStatus)
326
+ ? result.splitCursor
327
+ : result.continueCursor;
328
+ isDone = result.isDone;
329
+ } while (!isDone);
330
+ return count;
331
+ },
332
+ });
333
+
334
+ export const getAccountByAccountIdAndProviderId = query({
335
+ args: { accountId: v.string(), providerId: v.string() },
336
+ handler: async (ctx, args) => {
337
+ const doc = await ctx.db
338
+ .query("account")
339
+ .withIndex("providerId_accountId", (q) =>
340
+ q.eq("providerId", args.providerId).eq("accountId", args.accountId)
341
+ )
342
+ .unique();
343
+ if (!doc) {
344
+ return;
345
+ }
346
+ return transformOutput(doc, "account");
347
+ },
348
+ });
349
+
350
+ export const updateUserProviderAccounts = mutation({
351
+ args: {
352
+ userId: v.string(),
353
+ providerId: v.string(),
354
+ update: v.object(partial(schema.tables.account.validator.fields)),
355
+ },
356
+ handler: async (ctx, args) => {
357
+ const docs = await ctx.db
358
+ .query("account")
359
+ .withIndex("userId_providerId", (q) =>
360
+ q.eq("userId", args.userId).eq("providerId", args.providerId)
361
+ )
362
+ .collect();
363
+ if (docs.length === 0) {
364
+ return 0;
365
+ }
366
+ await asyncMap(docs, async (doc) => {
367
+ await ctx.db.patch(doc._id, args.update);
368
+ });
369
+ return docs.length;
370
+ },
371
+ });
372
+
373
+ export const updateTwoFactor = mutation({
374
+ args: {
375
+ userId: v.string(),
376
+ update: v.object(partial(schema.tables.twoFactor.validator.fields)),
377
+ },
378
+ handler: async (ctx, args) => {
379
+ const docs = await ctx.db
380
+ .query("twoFactor")
381
+ .withIndex("userId", (q) => q.eq("userId", args.userId))
382
+ .collect();
383
+ if (docs.length === 0) {
384
+ return 0;
385
+ }
386
+ await asyncMap(docs, async (doc) => {
387
+ await ctx.db.patch(doc._id, args.update);
388
+ });
389
+ return docs.length;
390
+ },
391
+ });