faire-auth 1.0.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 (221) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +34 -0
  3. package/dist/access-B5bBI4uT.mjs +39 -0
  4. package/dist/access-Crt-IJ2P.cjs +51 -0
  5. package/dist/adapter-factory-BXei1QRX.mjs +881 -0
  6. package/dist/adapter-factory-DT-_2aHJ.cjs +893 -0
  7. package/dist/adapters/drizzle-adapter/index.cjs +208 -0
  8. package/dist/adapters/drizzle-adapter/index.d.cts +48 -0
  9. package/dist/adapters/drizzle-adapter/index.d.mts +48 -0
  10. package/dist/adapters/drizzle-adapter/index.mjs +207 -0
  11. package/dist/adapters/index.cjs +23 -0
  12. package/dist/adapters/index.d.cts +157 -0
  13. package/dist/adapters/index.d.mts +157 -0
  14. package/dist/adapters/index.mjs +17 -0
  15. package/dist/adapters/kysely-adapter/index.cjs +11 -0
  16. package/dist/adapters/kysely-adapter/index.d.cts +52 -0
  17. package/dist/adapters/kysely-adapter/index.d.mts +52 -0
  18. package/dist/adapters/kysely-adapter/index.mjs +9 -0
  19. package/dist/adapters/memory-adapter/index.cjs +9 -0
  20. package/dist/adapters/memory-adapter/index.d.cts +15 -0
  21. package/dist/adapters/memory-adapter/index.d.mts +15 -0
  22. package/dist/adapters/memory-adapter/index.mjs +9 -0
  23. package/dist/adapters/mongodb-adapter/index.cjs +9 -0
  24. package/dist/adapters/mongodb-adapter/index.d.cts +4 -0
  25. package/dist/adapters/mongodb-adapter/index.d.mts +4 -0
  26. package/dist/adapters/mongodb-adapter/index.mjs +9 -0
  27. package/dist/adapters/prisma-adapter/index.cjs +156 -0
  28. package/dist/adapters/prisma-adapter/index.d.cts +35 -0
  29. package/dist/adapters/prisma-adapter/index.d.mts +35 -0
  30. package/dist/adapters/prisma-adapter/index.mjs +155 -0
  31. package/dist/adapters/test.cjs +797 -0
  32. package/dist/adapters/test.d.cts +82 -0
  33. package/dist/adapters/test.d.mts +82 -0
  34. package/dist/adapters/test.mjs +793 -0
  35. package/dist/api/index.cjs +20 -0
  36. package/dist/api/index.d.cts +3 -0
  37. package/dist/api/index.d.mts +3 -0
  38. package/dist/api/index.mjs +20 -0
  39. package/dist/api/middleware/index.cjs +16 -0
  40. package/dist/api/middleware/index.d.cts +16 -0
  41. package/dist/api/middleware/index.d.mts +16 -0
  42. package/dist/api/middleware/index.mjs +11 -0
  43. package/dist/api-Bm89BLgN.cjs +1899 -0
  44. package/dist/api-_B7qO28y.mjs +1892 -0
  45. package/dist/auth-Bo9PDt5j.cjs +739 -0
  46. package/dist/auth-Ds4AG4h4.mjs +709 -0
  47. package/dist/bearer-0SeEmaS4.mjs +54 -0
  48. package/dist/bearer-CHeREcGT.cjs +60 -0
  49. package/dist/bun-sqlite-dialect-CfkBo2v5.mjs +155 -0
  50. package/dist/bun-sqlite-dialect-wuaC2-gh.cjs +156 -0
  51. package/dist/chunk-Ceigfy4P.mjs +39 -0
  52. package/dist/chunk-oakRccI5.cjs +60 -0
  53. package/dist/client/index.cjs +22 -0
  54. package/dist/client/index.d.cts +8 -0
  55. package/dist/client/index.d.mts +8 -0
  56. package/dist/client/index.mjs +19 -0
  57. package/dist/client/lynx/index.cjs +79 -0
  58. package/dist/client/lynx/index.d.cts +156 -0
  59. package/dist/client/lynx/index.d.mts +156 -0
  60. package/dist/client/lynx/index.mjs +76 -0
  61. package/dist/client/plugins/index.cjs +11 -0
  62. package/dist/client/plugins/index.d.cts +17 -0
  63. package/dist/client/plugins/index.d.mts +17 -0
  64. package/dist/client/plugins/index.mjs +10 -0
  65. package/dist/client/react/index.cjs +79 -0
  66. package/dist/client/react/index.d.cts +156 -0
  67. package/dist/client/react/index.d.mts +156 -0
  68. package/dist/client/react/index.mjs +76 -0
  69. package/dist/client/solid/index.cjs +51 -0
  70. package/dist/client/solid/index.d.cts +90 -0
  71. package/dist/client/solid/index.d.mts +90 -0
  72. package/dist/client/solid/index.mjs +50 -0
  73. package/dist/client/svelte/index.cjs +28 -0
  74. package/dist/client/svelte/index.d.cts +110 -0
  75. package/dist/client/svelte/index.d.mts +110 -0
  76. package/dist/client/svelte/index.mjs +28 -0
  77. package/dist/client/vue/index.cjs +68 -0
  78. package/dist/client/vue/index.d.cts +123 -0
  79. package/dist/client/vue/index.d.mts +123 -0
  80. package/dist/client/vue/index.mjs +67 -0
  81. package/dist/cookies-B5xeA6i8.cjs +456 -0
  82. package/dist/cookies-Ch1JfQIz.mjs +367 -0
  83. package/dist/crypto/index.cjs +11 -0
  84. package/dist/crypto/index.d.cts +22 -0
  85. package/dist/crypto/index.d.mts +22 -0
  86. package/dist/crypto/index.mjs +5 -0
  87. package/dist/crypto-CcTxYH82.cjs +57 -0
  88. package/dist/crypto-CyQRFtkq.mjs +41 -0
  89. package/dist/db/index.cjs +40 -0
  90. package/dist/db/index.d.cts +4 -0
  91. package/dist/db/index.d.mts +4 -0
  92. package/dist/db/index.mjs +16 -0
  93. package/dist/db-BTKyYu-_.cjs +1180 -0
  94. package/dist/db-xiJtoDgz.mjs +1119 -0
  95. package/dist/defu-B0Svx_x4.cjs +34 -0
  96. package/dist/defu-SZkpHhbR.mjs +28 -0
  97. package/dist/email-verification-C-AsfJsb.cjs +247 -0
  98. package/dist/email-verification-CWhj2qfb.mjs +228 -0
  99. package/dist/hono-BEq1NYVX.cjs +526 -0
  100. package/dist/hono-Cdukwu5K.cjs +13 -0
  101. package/dist/hono-CoKYWnXA.mjs +7 -0
  102. package/dist/hono-Covz10jU.mjs +508 -0
  103. package/dist/hono-DOM31WQz.d.cts +18 -0
  104. package/dist/hono-DuE14mmj.d.mts +18 -0
  105. package/dist/index-B-WeOMzg.d.cts +13350 -0
  106. package/dist/index-B09P9p5_.d.cts +33 -0
  107. package/dist/index-B5_0QTLg.d.mts +3 -0
  108. package/dist/index-B7SKyR_a.d.cts +3 -0
  109. package/dist/index-BVHscLQl.d.cts +992 -0
  110. package/dist/index-C2-2QDyS.d.cts +35 -0
  111. package/dist/index-CTwrVluH.d.mts +41 -0
  112. package/dist/index-CWAqWfoZ.d.cts +27 -0
  113. package/dist/index-CYSShrFx.d.mts +27 -0
  114. package/dist/index-Qu-iJGNr.d.mts +992 -0
  115. package/dist/index-cs4Sh0En.d.cts +41 -0
  116. package/dist/index-jlessPI0.d.mts +13350 -0
  117. package/dist/index-ppgcFe12.d.mts +33 -0
  118. package/dist/index-to0RO38U.d.mts +35 -0
  119. package/dist/index.cjs +85 -0
  120. package/dist/index.d.cts +5 -0
  121. package/dist/index.d.mts +5 -0
  122. package/dist/index.mjs +27 -0
  123. package/dist/integrations/next-js.cjs +50 -0
  124. package/dist/integrations/next-js.d.cts +23 -0
  125. package/dist/integrations/next-js.d.mts +23 -0
  126. package/dist/integrations/next-js.mjs +49 -0
  127. package/dist/integrations/node.cjs +139 -0
  128. package/dist/integrations/node.d.cts +22 -0
  129. package/dist/integrations/node.d.mts +22 -0
  130. package/dist/integrations/node.mjs +134 -0
  131. package/dist/integrations/react-start.cjs +37 -0
  132. package/dist/integrations/react-start.d.cts +17 -0
  133. package/dist/integrations/react-start.d.mts +17 -0
  134. package/dist/integrations/react-start.mjs +37 -0
  135. package/dist/integrations/solid-start.cjs +14 -0
  136. package/dist/integrations/solid-start.d.cts +13 -0
  137. package/dist/integrations/solid-start.d.mts +13 -0
  138. package/dist/integrations/solid-start.mjs +13 -0
  139. package/dist/integrations/svelte-kit.cjs +52 -0
  140. package/dist/integrations/svelte-kit.d.cts +42 -0
  141. package/dist/integrations/svelte-kit.d.mts +42 -0
  142. package/dist/integrations/svelte-kit.mjs +49 -0
  143. package/dist/ip-B5SwXaMB.cjs +54 -0
  144. package/dist/ip-BjNYspCH.mjs +36 -0
  145. package/dist/json-B1v2qRTQ.mjs +24 -0
  146. package/dist/json-CcJ2HjGo.cjs +30 -0
  147. package/dist/kysely-adapter-Bxi7sPdG.cjs +288 -0
  148. package/dist/kysely-adapter-DRuoT_X8.mjs +270 -0
  149. package/dist/logged-CyGfp8_H.mjs +187 -0
  150. package/dist/logged-DQK3C64b.cjs +193 -0
  151. package/dist/memory-adapter-BlnDIAAX.cjs +154 -0
  152. package/dist/memory-adapter-Db3tsJTn.mjs +148 -0
  153. package/dist/middleware-CE6OhDkq.mjs +29 -0
  154. package/dist/middleware-CWvRH4EW.cjs +47 -0
  155. package/dist/mongodb-adapter-C_qGQED5.mjs +291 -0
  156. package/dist/mongodb-adapter-C_qfK87x.cjs +297 -0
  157. package/dist/node-sqlite-dialect-BfBzyOAg.mjs +155 -0
  158. package/dist/node-sqlite-dialect-mJWC8LWQ.cjs +156 -0
  159. package/dist/oauth2/index.cjs +25 -0
  160. package/dist/oauth2/index.d.cts +42 -0
  161. package/dist/oauth2/index.d.mts +42 -0
  162. package/dist/oauth2/index.mjs +16 -0
  163. package/dist/oauth2-B8M0lW9l.mjs +159 -0
  164. package/dist/oauth2-BLeOEi7Y.cjs +177 -0
  165. package/dist/origin-check-8Gajklvh.mjs +228 -0
  166. package/dist/origin-check-id9lTnqZ.cjs +246 -0
  167. package/dist/parser-CdncAl9i.cjs +83 -0
  168. package/dist/parser-CeAer-RM.mjs +71 -0
  169. package/dist/passkey-B6N20LSS.cjs +512 -0
  170. package/dist/passkey-DJsR_GX3.mjs +505 -0
  171. package/dist/plugins/access/index.cjs +4 -0
  172. package/dist/plugins/access/index.d.cts +2 -0
  173. package/dist/plugins/access/index.d.mts +2 -0
  174. package/dist/plugins/access/index.mjs +3 -0
  175. package/dist/plugins/bearer/index.cjs +7 -0
  176. package/dist/plugins/bearer/index.d.cts +4 -0
  177. package/dist/plugins/bearer/index.d.mts +4 -0
  178. package/dist/plugins/bearer/index.mjs +7 -0
  179. package/dist/plugins/index.cjs +49 -0
  180. package/dist/plugins/index.d.cts +9326 -0
  181. package/dist/plugins/index.d.mts +9326 -0
  182. package/dist/plugins/index.mjs +26 -0
  183. package/dist/plugins/passkey/index.cjs +15 -0
  184. package/dist/plugins/passkey/index.d.cts +4 -0
  185. package/dist/plugins/passkey/index.d.mts +4 -0
  186. package/dist/plugins/passkey/index.mjs +15 -0
  187. package/dist/plugins-C1lm2Wj3.cjs +5254 -0
  188. package/dist/plugins-Dai1QkRU.mjs +5199 -0
  189. package/dist/request-1NL_1lyJ.mjs +58 -0
  190. package/dist/request-CPNlp-DK.cjs +100 -0
  191. package/dist/schema-D-qjygfE.cjs +179 -0
  192. package/dist/schema-DTIwLLmf.mjs +125 -0
  193. package/dist/session-De9POJTW.cjs +641 -0
  194. package/dist/session-rH8ougDl.mjs +538 -0
  195. package/dist/social-providers/index.cjs +10 -0
  196. package/dist/social-providers/index.d.cts +2 -0
  197. package/dist/social-providers/index.d.mts +2 -0
  198. package/dist/social-providers/index.mjs +5 -0
  199. package/dist/social-providers-DcFNUT0S.cjs +13 -0
  200. package/dist/social-providers-DoYJhBe3.mjs +9 -0
  201. package/dist/state--f7fwIGh.cjs +99 -0
  202. package/dist/state-CqJfCIl9.mjs +86 -0
  203. package/dist/test-utils/index.cjs +27492 -0
  204. package/dist/test-utils/index.d.cts +4584 -0
  205. package/dist/test-utils/index.d.mts +4584 -0
  206. package/dist/test-utils/index.mjs +27490 -0
  207. package/dist/types/index.cjs +0 -0
  208. package/dist/types/index.d.cts +3 -0
  209. package/dist/types/index.d.mts +3 -0
  210. package/dist/types/index.mjs +1 -0
  211. package/dist/url-BoUuoIwZ.mjs +88 -0
  212. package/dist/url-D2yvKaM7.cjs +118 -0
  213. package/dist/utils/cookies.cjs +51 -0
  214. package/dist/utils/cookies.d.cts +179 -0
  215. package/dist/utils/cookies.d.mts +179 -0
  216. package/dist/utils/cookies.mjs +7 -0
  217. package/dist/utils-44aDDP8f.cjs +2 -0
  218. package/dist/utils-D4vZd1-9.mjs +4 -0
  219. package/dist/vanilla-Bu2PmFzE.cjs +30 -0
  220. package/dist/vanilla-TfHqeiC7.mjs +25 -0
  221. package/package.json +470 -0
@@ -0,0 +1,881 @@
1
+ import { t as safeJSONParse } from "./json-B1v2qRTQ.mjs";
2
+ import { r as generateId } from "./utils-D4vZd1-9.mjs";
3
+ import { TTY_COLORS, getColorDepth, logger } from "@faire-auth/core/env";
4
+ import { FaireAuthError } from "@faire-auth/core/error";
5
+ import { isPromise } from "@faire-auth/core/static";
6
+
7
+ //#region src/adapters/utils.ts
8
+ function withApplyDefault(value, field, action) {
9
+ if (action === "update") {
10
+ if (value === void 0 && field.onUpdate !== void 0) {
11
+ if (typeof field.onUpdate === "function") return field.onUpdate();
12
+ return field.onUpdate;
13
+ }
14
+ return value;
15
+ }
16
+ if (value === void 0 || value === null) {
17
+ if (field.defaultValue !== void 0) {
18
+ if (typeof field.defaultValue === "function") return field.defaultValue();
19
+ return field.defaultValue;
20
+ }
21
+ }
22
+ return value;
23
+ }
24
+
25
+ //#endregion
26
+ //#region src/db/get-tables.ts
27
+ const getAuthTables = (options) => {
28
+ const pluginSchema = (options.plugins ?? []).reduce((acc, plugin) => {
29
+ const schema = plugin.schema;
30
+ if (!schema) return acc;
31
+ for (const [key, value] of Object.entries(schema)) acc[key] = {
32
+ fields: {
33
+ ...acc[key]?.fields,
34
+ ...value.fields
35
+ },
36
+ modelName: value.modelName || key
37
+ };
38
+ return acc;
39
+ }, {});
40
+ const shouldAddRateLimitTable = options.rateLimit?.storage === "database";
41
+ const rateLimitTable = { rateLimit: {
42
+ modelName: options.rateLimit?.modelName || "rateLimit",
43
+ fields: {
44
+ key: {
45
+ type: "string",
46
+ fieldName: options.rateLimit?.fields?.key || "key"
47
+ },
48
+ count: {
49
+ type: "number",
50
+ fieldName: options.rateLimit?.fields?.count || "count"
51
+ },
52
+ lastRequest: {
53
+ type: "number",
54
+ bigint: true,
55
+ fieldName: options.rateLimit?.fields?.lastRequest || "lastRequest"
56
+ }
57
+ }
58
+ } };
59
+ const { user, session, account,...pluginTables } = pluginSchema;
60
+ const sessionTable = { session: {
61
+ modelName: options.session?.modelName || "session",
62
+ fields: {
63
+ expiresAt: {
64
+ type: "date",
65
+ required: true,
66
+ fieldName: options.session?.fields?.expiresAt || "expiresAt"
67
+ },
68
+ token: {
69
+ type: "string",
70
+ required: true,
71
+ fieldName: options.session?.fields?.token || "token",
72
+ unique: true
73
+ },
74
+ createdAt: {
75
+ type: "date",
76
+ required: true,
77
+ fieldName: options.session?.fields?.createdAt || "createdAt",
78
+ defaultValue: () => /* @__PURE__ */ new Date()
79
+ },
80
+ updatedAt: {
81
+ type: "date",
82
+ required: true,
83
+ fieldName: options.session?.fields?.updatedAt || "updatedAt",
84
+ onUpdate: () => /* @__PURE__ */ new Date()
85
+ },
86
+ ipAddress: {
87
+ type: "string",
88
+ required: false,
89
+ fieldName: options.session?.fields?.ipAddress || "ipAddress"
90
+ },
91
+ userAgent: {
92
+ type: "string",
93
+ required: false,
94
+ fieldName: options.session?.fields?.userAgent || "userAgent"
95
+ },
96
+ userId: {
97
+ type: "string",
98
+ fieldName: options.session?.fields?.userId || "userId",
99
+ references: {
100
+ model: options.user?.modelName || "user",
101
+ field: "id",
102
+ onDelete: "cascade"
103
+ },
104
+ required: true
105
+ },
106
+ ...session?.fields,
107
+ ...options.session?.additionalFields
108
+ },
109
+ order: 2
110
+ } };
111
+ return {
112
+ user: {
113
+ modelName: options.user?.modelName || "user",
114
+ fields: {
115
+ name: {
116
+ type: "string",
117
+ required: true,
118
+ fieldName: options.user?.fields?.name || "name",
119
+ sortable: true
120
+ },
121
+ email: {
122
+ type: "string",
123
+ unique: true,
124
+ required: true,
125
+ fieldName: options.user?.fields?.email || "email",
126
+ sortable: true
127
+ },
128
+ emailVerified: {
129
+ type: "boolean",
130
+ defaultValue: false,
131
+ required: true,
132
+ fieldName: options.user?.fields?.emailVerified || "emailVerified"
133
+ },
134
+ image: {
135
+ type: "string",
136
+ required: false,
137
+ fieldName: options.user?.fields?.image || "image"
138
+ },
139
+ createdAt: {
140
+ type: "date",
141
+ defaultValue: () => /* @__PURE__ */ new Date(),
142
+ required: true,
143
+ fieldName: options.user?.fields?.createdAt || "createdAt"
144
+ },
145
+ updatedAt: {
146
+ type: "date",
147
+ defaultValue: () => /* @__PURE__ */ new Date(),
148
+ onUpdate: () => /* @__PURE__ */ new Date(),
149
+ required: true,
150
+ fieldName: options.user?.fields?.updatedAt || "updatedAt"
151
+ },
152
+ ...user?.fields,
153
+ ...options.user?.additionalFields
154
+ },
155
+ order: 1
156
+ },
157
+ ...!options.secondaryStorage || options.session?.storeSessionInDatabase ? sessionTable : {},
158
+ account: {
159
+ modelName: options.account?.modelName || "account",
160
+ fields: {
161
+ accountId: {
162
+ type: "string",
163
+ required: true,
164
+ fieldName: options.account?.fields?.accountId || "accountId"
165
+ },
166
+ providerId: {
167
+ type: "string",
168
+ required: true,
169
+ fieldName: options.account?.fields?.providerId || "providerId"
170
+ },
171
+ userId: {
172
+ type: "string",
173
+ references: {
174
+ model: options.user?.modelName || "user",
175
+ field: "id",
176
+ onDelete: "cascade"
177
+ },
178
+ required: true,
179
+ fieldName: options.account?.fields?.userId || "userId"
180
+ },
181
+ accessToken: {
182
+ type: "string",
183
+ required: false,
184
+ fieldName: options.account?.fields?.accessToken || "accessToken"
185
+ },
186
+ refreshToken: {
187
+ type: "string",
188
+ required: false,
189
+ fieldName: options.account?.fields?.refreshToken || "refreshToken"
190
+ },
191
+ idToken: {
192
+ type: "string",
193
+ required: false,
194
+ fieldName: options.account?.fields?.idToken || "idToken"
195
+ },
196
+ accessTokenExpiresAt: {
197
+ type: "date",
198
+ required: false,
199
+ fieldName: options.account?.fields?.accessTokenExpiresAt || "accessTokenExpiresAt"
200
+ },
201
+ refreshTokenExpiresAt: {
202
+ type: "date",
203
+ required: false,
204
+ fieldName: options.account?.fields?.refreshTokenExpiresAt || "refreshTokenExpiresAt"
205
+ },
206
+ scope: {
207
+ type: "string",
208
+ required: false,
209
+ fieldName: options.account?.fields?.scope || "scope"
210
+ },
211
+ password: {
212
+ type: "string",
213
+ required: false,
214
+ fieldName: options.account?.fields?.password || "password"
215
+ },
216
+ createdAt: {
217
+ type: "date",
218
+ required: true,
219
+ fieldName: options.account?.fields?.createdAt || "createdAt",
220
+ defaultValue: () => /* @__PURE__ */ new Date()
221
+ },
222
+ updatedAt: {
223
+ type: "date",
224
+ required: true,
225
+ fieldName: options.account?.fields?.updatedAt || "updatedAt",
226
+ onUpdate: () => /* @__PURE__ */ new Date()
227
+ },
228
+ ...account?.fields,
229
+ ...options.account?.additionalFields
230
+ },
231
+ order: 3
232
+ },
233
+ verification: {
234
+ modelName: options.verification?.modelName || "verification",
235
+ fields: {
236
+ identifier: {
237
+ type: "string",
238
+ required: true,
239
+ fieldName: options.verification?.fields?.identifier || "identifier"
240
+ },
241
+ value: {
242
+ type: "string",
243
+ required: true,
244
+ fieldName: options.verification?.fields?.value || "value"
245
+ },
246
+ expiresAt: {
247
+ type: "date",
248
+ required: true,
249
+ fieldName: options.verification?.fields?.expiresAt || "expiresAt"
250
+ },
251
+ createdAt: {
252
+ type: "date",
253
+ required: true,
254
+ defaultValue: () => /* @__PURE__ */ new Date(),
255
+ fieldName: options.verification?.fields?.createdAt || "createdAt"
256
+ },
257
+ updatedAt: {
258
+ type: "date",
259
+ required: true,
260
+ defaultValue: () => /* @__PURE__ */ new Date(),
261
+ onUpdate: () => /* @__PURE__ */ new Date(),
262
+ fieldName: options.verification?.fields?.updatedAt || "updatedAt"
263
+ }
264
+ },
265
+ order: 4
266
+ },
267
+ ...pluginTables,
268
+ ...shouldAddRateLimitTable ? rateLimitTable : {}
269
+ };
270
+ };
271
+
272
+ //#endregion
273
+ //#region src/adapters/adapter-factory/index.ts
274
+ let debugLogs = [];
275
+ let transactionId = -1;
276
+ const createAsIsTransaction = (adapter) => (fn) => {
277
+ const res = fn(adapter);
278
+ return isPromise(res) ? res : Promise.resolve(res);
279
+ };
280
+ const createAdapterFactory = ({ adapter: customAdapter, config: cfg }) => (options) => {
281
+ const uniqueAdapterFactoryInstanceId = Math.random().toString(36).substring(2, 15);
282
+ const config = {
283
+ ...cfg,
284
+ supportsBooleans: cfg.supportsBooleans ?? true,
285
+ supportsDates: cfg.supportsDates ?? true,
286
+ supportsJSON: cfg.supportsJSON ?? false,
287
+ adapterName: cfg.adapterName ?? cfg.adapterId,
288
+ supportsNumericIds: cfg.supportsNumericIds ?? true,
289
+ transaction: cfg.transaction ?? false,
290
+ disableTransformInput: cfg.disableTransformInput ?? false,
291
+ disableTransformOutput: cfg.disableTransformOutput ?? false
292
+ };
293
+ if (options.advanced?.database?.useNumberId === true && config.supportsNumericIds === false) throw new FaireAuthError(`[${config.adapterName}] Your database or database adapter does not support numeric ids. Please disable "useNumberId" in your config.`);
294
+ const schema = getAuthTables(options);
295
+ /**
296
+ * This function helps us get the default field name from the schema defined by devs.
297
+ * Often times, the user will be using the `fieldName` which could had been customized by the users.
298
+ * This function helps us get the actual field name useful to match against the schema. (eg: schema[model].fields[field])
299
+ *
300
+ * If it's still unclear what this does:
301
+ *
302
+ * 1. User can define a custom fieldName.
303
+ * 2. When using a custom fieldName, doing something like `schema[model].fields[field]` will not work.
304
+ */
305
+ const getDefaultFieldName = ({ field, model: unsafe_model }) => {
306
+ if (field === "id" || field === "_id") return "id";
307
+ const model = getDefaultModelName(unsafe_model);
308
+ let f = schema[model]?.fields[field];
309
+ if (!f) {
310
+ const result = Object.entries(schema[model].fields).find(([_, f$1]) => f$1.fieldName === field);
311
+ if (result) {
312
+ f = result[1];
313
+ field = result[0];
314
+ }
315
+ }
316
+ if (!f) {
317
+ debugLog(`Field ${field} not found in model ${model}`);
318
+ debugLog(`Schema:`, schema);
319
+ throw new FaireAuthError(`Field ${field} not found in model ${model}`);
320
+ }
321
+ return field;
322
+ };
323
+ /**
324
+ * This function helps us get the default model name from the schema defined by devs.
325
+ * Often times, the user will be using the `modelName` which could had been customized by the users.
326
+ * This function helps us get the actual model name useful to match against the schema. (eg: schema[model])
327
+ *
328
+ * If it's still unclear what this does:
329
+ *
330
+ * 1. User can define a custom modelName.
331
+ * 2. When using a custom modelName, doing something like `schema[model]` will not work.
332
+ * 3. Using this function helps us get the actual model name based on the user's defined custom modelName.
333
+ */
334
+ const getDefaultModelName = (model) => {
335
+ if (config.usePlural && model.charAt(model.length - 1) === "s") {
336
+ let pluralessModel = model.slice(0, -1);
337
+ let m$1 = schema[pluralessModel] ? pluralessModel : void 0;
338
+ if (!m$1) m$1 = Object.entries(schema).find(([_, f]) => f.modelName === pluralessModel)?.[0];
339
+ if (m$1) return m$1;
340
+ }
341
+ let m = schema[model] ? model : void 0;
342
+ if (!m) m = Object.entries(schema).find(([_, f]) => f.modelName === model)?.[0];
343
+ if (!m) {
344
+ debugLog(`Model "${model}" not found in schema`);
345
+ debugLog(`Schema:`, schema);
346
+ throw new FaireAuthError(`Model "${model}" not found in schema`);
347
+ }
348
+ return m;
349
+ };
350
+ /**
351
+ * Users can overwrite the default model of some tables. This function helps find the correct model name.
352
+ * Furthermore, if the user passes `usePlural` as true in their adapter config,
353
+ * then we should return the model name ending with an `s`.
354
+ */
355
+ const getModelName = (model) => {
356
+ const defaultModelKey = getDefaultModelName(model);
357
+ const usePlural = config && config.usePlural;
358
+ if (schema && schema[defaultModelKey] && schema[defaultModelKey].modelName !== model) return usePlural ? `${schema[defaultModelKey].modelName}s` : schema[defaultModelKey].modelName;
359
+ return usePlural ? `${model}s` : model;
360
+ };
361
+ /**
362
+ * Get the field name which is expected to be saved in the database based on the user's schema.
363
+ *
364
+ * This function is useful if you need to save the field name to the database.
365
+ *
366
+ * For example, if the user has defined a custom field name for the `user` model, then you can use this function to get the actual field name from the schema.
367
+ */
368
+ function getFieldName({ model: model_name, field: field_name }) {
369
+ const model = getDefaultModelName(model_name);
370
+ const field = getDefaultFieldName({
371
+ model,
372
+ field: field_name
373
+ });
374
+ return schema[model]?.fields[field]?.fieldName || field;
375
+ }
376
+ const debugLog = (...args) => {
377
+ if (config.debugLogs === true || typeof config.debugLogs === "object") {
378
+ if (typeof config.debugLogs === "object" && "isRunningAdapterTests" in config.debugLogs) {
379
+ if (config.debugLogs.isRunningAdapterTests) {
380
+ args.shift();
381
+ debugLogs.push({
382
+ instance: uniqueAdapterFactoryInstanceId,
383
+ args
384
+ });
385
+ }
386
+ return;
387
+ }
388
+ if (typeof config.debugLogs === "object" && config.debugLogs.logCondition && !config.debugLogs.logCondition?.()) return;
389
+ if (typeof args[0] === "object" && "method" in args[0]) {
390
+ const method = args.shift().method;
391
+ if (typeof config.debugLogs === "object") {
392
+ if (method === "create" && !config.debugLogs.create) return;
393
+ else if (method === "update" && !config.debugLogs.update) return;
394
+ else if (method === "updateMany" && !config.debugLogs.updateMany) return;
395
+ else if (method === "findOne" && !config.debugLogs.findOne) return;
396
+ else if (method === "findMany" && !config.debugLogs.findMany) return;
397
+ else if (method === "delete" && !config.debugLogs.delete) return;
398
+ else if (method === "deleteMany" && !config.debugLogs.deleteMany) return;
399
+ else if (method === "count" && !config.debugLogs.count) return;
400
+ }
401
+ logger.info(`[${config.adapterName}]`, ...args);
402
+ } else logger.info(`[${config.adapterName}]`, ...args);
403
+ }
404
+ };
405
+ const idField = ({ customModelName, forceAllowId }) => {
406
+ const shouldGenerateId = !config.disableIdGeneration && !options.advanced?.database?.useNumberId && !forceAllowId;
407
+ const model = getDefaultModelName(customModelName ?? "id");
408
+ return {
409
+ type: options.advanced?.database?.useNumberId ? "number" : "string",
410
+ required: shouldGenerateId ? true : false,
411
+ ...shouldGenerateId ? { defaultValue() {
412
+ if (config.disableIdGeneration) return void 0;
413
+ const useNumberId = options.advanced?.database?.useNumberId;
414
+ let generateId$1 = options.advanced?.database?.generateId;
415
+ if (options.advanced?.generateId !== void 0) {
416
+ logger.warn("Your Faire Auth config includes advanced.generateId which is deprecated. Please use advanced.database.generateId instead. This will be removed in future releases.");
417
+ generateId$1 = options.advanced?.generateId;
418
+ }
419
+ if (generateId$1 === false || useNumberId) return void 0;
420
+ if (generateId$1) return generateId$1({ model });
421
+ if (config.customIdGenerator) return config.customIdGenerator({ model });
422
+ return generateId();
423
+ } } : {}
424
+ };
425
+ };
426
+ const getFieldAttributes = ({ model, field }) => {
427
+ const defaultModelName = getDefaultModelName(model);
428
+ const defaultFieldName = getDefaultFieldName({
429
+ field,
430
+ model: defaultModelName
431
+ });
432
+ const fields = schema[defaultModelName].fields;
433
+ fields.id = idField({ customModelName: defaultModelName });
434
+ const fieldAttributes = fields[defaultFieldName];
435
+ if (!fieldAttributes) throw new FaireAuthError(`Field ${field} not found in model ${model}`);
436
+ return fieldAttributes;
437
+ };
438
+ const transformInput = async (data, defaultModelName, action, forceAllowId) => {
439
+ const transformedData = {};
440
+ const fields = schema[defaultModelName].fields;
441
+ const newMappedKeys = config.mapKeysTransformInput ?? {};
442
+ if (!config.disableIdGeneration && !options.advanced?.database?.useNumberId) fields.id = idField({
443
+ customModelName: defaultModelName,
444
+ forceAllowId: !!forceAllowId && "id" in data
445
+ });
446
+ for (const field in fields) {
447
+ const value = data[field];
448
+ const fieldAttributes = fields[field];
449
+ let newFieldName = newMappedKeys[field] || fields[field].fieldName || field;
450
+ if (value === void 0 && (fieldAttributes.defaultValue === void 0 && !fieldAttributes.transform?.input && !(action === "update" && fieldAttributes.onUpdate) || action === "update" && !fieldAttributes.onUpdate)) continue;
451
+ let newValue = withApplyDefault(value, fieldAttributes, action);
452
+ if (fieldAttributes.transform?.input) newValue = await fieldAttributes.transform.input(newValue);
453
+ if (fieldAttributes.references?.field === "id" && options.advanced?.database?.useNumberId) if (Array.isArray(newValue)) newValue = newValue.map((x) => x !== null ? Number(x) : null);
454
+ else newValue = newValue !== null ? Number(newValue) : null;
455
+ else if (config.supportsJSON === false && typeof newValue === "object" && fieldAttributes.type === "json") newValue = JSON.stringify(newValue);
456
+ else if (config.supportsDates === false && newValue instanceof Date && fieldAttributes.type === "date") newValue = newValue.toISOString();
457
+ else if (config.supportsBooleans === false && typeof newValue === "boolean") newValue = newValue ? 1 : 0;
458
+ if (config.customTransformInput) newValue = config.customTransformInput({
459
+ data: newValue,
460
+ action,
461
+ field: newFieldName,
462
+ fieldAttributes,
463
+ model: defaultModelName,
464
+ schema,
465
+ options
466
+ });
467
+ if (newValue !== void 0) transformedData[newFieldName] = newValue;
468
+ }
469
+ return transformedData;
470
+ };
471
+ const transformOutput = async (data, unsafe_model, select = []) => {
472
+ if (!data) return null;
473
+ const newMappedKeys = config.mapKeysTransformOutput ?? {};
474
+ const transformedData = {};
475
+ const tableSchema = schema[unsafe_model].fields;
476
+ const idKey = Object.entries(newMappedKeys).find(([_, v]) => v === "id")?.[0];
477
+ tableSchema[idKey ?? "id"] = { type: options.advanced?.database?.useNumberId ? "number" : "string" };
478
+ for (const key in tableSchema) {
479
+ if (select.length && !select.includes(key)) continue;
480
+ const field = tableSchema[key];
481
+ if (field) {
482
+ const originalKey = field.fieldName || key;
483
+ let newValue = data[Object.entries(newMappedKeys).find(([_, v]) => v === originalKey)?.[0] || originalKey];
484
+ if (field.transform?.output) newValue = await field.transform.output(newValue);
485
+ let newFieldName = newMappedKeys[key] || key;
486
+ if (originalKey === "id" || field.references?.field === "id") {
487
+ if (typeof newValue !== "undefined" && newValue !== null) newValue = String(newValue);
488
+ } else if (config.supportsJSON === false && typeof newValue === "string" && field.type === "json") newValue = safeJSONParse(newValue);
489
+ else if (config.supportsDates === false && typeof newValue === "string" && field.type === "date") newValue = new Date(newValue);
490
+ else if (config.supportsBooleans === false && typeof newValue === "number" && field.type === "boolean") newValue = newValue === 1;
491
+ if (config.customTransformOutput) newValue = config.customTransformOutput({
492
+ data: newValue,
493
+ field: newFieldName,
494
+ fieldAttributes: field,
495
+ select,
496
+ model: unsafe_model,
497
+ schema,
498
+ options
499
+ });
500
+ transformedData[newFieldName] = newValue;
501
+ }
502
+ }
503
+ return transformedData;
504
+ };
505
+ const transformWhereClause = ({ model, where }) => {
506
+ if (!where) return void 0;
507
+ const newMappedKeys = config.mapKeysTransformInput ?? {};
508
+ return where.map((w) => {
509
+ const { field: unsafe_field, value, operator = "eq", connector = "AND" } = w;
510
+ if (operator === "in") {
511
+ if (!Array.isArray(value)) throw new FaireAuthError("Value must be an array");
512
+ }
513
+ let newValue = value;
514
+ const defaultModelName = getDefaultModelName(model);
515
+ const defaultFieldName = getDefaultFieldName({
516
+ field: unsafe_field,
517
+ model
518
+ });
519
+ const fieldName = newMappedKeys[defaultFieldName] || getFieldName({
520
+ field: defaultFieldName,
521
+ model: defaultModelName
522
+ });
523
+ const fieldAttr = getFieldAttributes({
524
+ field: defaultFieldName,
525
+ model: defaultModelName
526
+ });
527
+ if (defaultFieldName === "id" || fieldAttr.references?.field === "id") {
528
+ if (options.advanced?.database?.useNumberId) if (Array.isArray(value)) newValue = value.map(Number);
529
+ else newValue = Number(value);
530
+ }
531
+ if (fieldAttr.type === "date" && value instanceof Date && !config.supportsDates) newValue = value.toISOString();
532
+ if (fieldAttr.type === "boolean" && typeof value === "boolean" && !config.supportsBooleans) newValue = value ? 1 : 0;
533
+ if (fieldAttr.type === "json" && typeof value === "object" && !config.supportsJSON) try {
534
+ newValue = JSON.stringify(value);
535
+ } catch (error) {
536
+ throw new Error(`Failed to stringify JSON value for field ${fieldName}`, { cause: error });
537
+ }
538
+ return {
539
+ operator,
540
+ connector,
541
+ field: fieldName,
542
+ value: newValue
543
+ };
544
+ });
545
+ };
546
+ const adapterInstance = customAdapter({
547
+ options,
548
+ schema,
549
+ debugLog,
550
+ getFieldName,
551
+ getModelName,
552
+ getDefaultModelName,
553
+ getDefaultFieldName,
554
+ getFieldAttributes,
555
+ transformInput,
556
+ transformOutput,
557
+ transformWhereClause
558
+ });
559
+ let lazyLoadTransaction = null;
560
+ const adapter = {
561
+ transaction: (cb) => {
562
+ if (!lazyLoadTransaction) if (!config.transaction) {
563
+ if (typeof config.debugLogs === "object" && "isRunningAdapterTests" in config.debugLogs && config.debugLogs.isRunningAdapterTests) {} else logger.warn(`[${config.adapterName}] - Transactions are not supported. Executing operations sequentially.`);
564
+ lazyLoadTransaction = createAsIsTransaction(adapter);
565
+ } else {
566
+ logger.debug(`[${config.adapterName}] - Using provided transaction implementation.`);
567
+ lazyLoadTransaction = config.transaction;
568
+ }
569
+ return lazyLoadTransaction(cb);
570
+ },
571
+ create: async ({ data: unsafeData, model: unsafeModel, select, forceAllowId = false }) => {
572
+ transactionId++;
573
+ let thisTransactionId = transactionId;
574
+ const model = getModelName(unsafeModel);
575
+ unsafeModel = getDefaultModelName(unsafeModel);
576
+ if ("id" in unsafeData && !forceAllowId) {
577
+ logger.warn(`[${config.adapterName}] - You are trying to create a record with an id. This is not allowed as we handle id generation for you, unless you pass in the \`forceAllowId\` parameter. The id will be ignored.`);
578
+ const stack = (/* @__PURE__ */ new Error()).stack?.split("\n").filter((_, i) => i !== 1).join("\n").replace("Error:", "Create method with `id` being called at:");
579
+ console.log(stack);
580
+ unsafeData.id = void 0;
581
+ }
582
+ debugLog({ method: "create" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 4)}`, `${formatMethod("create")} ${formatAction("Unsafe Input")}:`, {
583
+ model,
584
+ data: unsafeData
585
+ });
586
+ let data = unsafeData;
587
+ if (!config.disableTransformInput) data = await transformInput(unsafeData, unsafeModel, "create", forceAllowId);
588
+ debugLog({ method: "create" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 4)}`, `${formatMethod("create")} ${formatAction("Parsed Input")}:`, {
589
+ model,
590
+ data
591
+ });
592
+ const res = await adapterInstance.create({
593
+ data,
594
+ model
595
+ });
596
+ debugLog({ method: "create" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 4)}`, `${formatMethod("create")} ${formatAction("DB Result")}:`, {
597
+ model,
598
+ res
599
+ });
600
+ let transformed = res;
601
+ if (!config.disableTransformOutput) transformed = await transformOutput(res, unsafeModel, select);
602
+ debugLog({ method: "create" }, `${formatTransactionId(thisTransactionId)} ${formatStep(4, 4)}`, `${formatMethod("create")} ${formatAction("Parsed Result")}:`, {
603
+ model,
604
+ data: transformed
605
+ });
606
+ return transformed;
607
+ },
608
+ update: async ({ model: unsafeModel, where: unsafeWhere, update: unsafeData }) => {
609
+ transactionId++;
610
+ let thisTransactionId = transactionId;
611
+ unsafeModel = getDefaultModelName(unsafeModel);
612
+ const model = getModelName(unsafeModel);
613
+ const where = transformWhereClause({
614
+ model: unsafeModel,
615
+ where: unsafeWhere
616
+ });
617
+ debugLog({ method: "update" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 4)}`, `${formatMethod("update")} ${formatAction("Unsafe Input")}:`, {
618
+ model,
619
+ data: unsafeData
620
+ });
621
+ let data = unsafeData;
622
+ if (!config.disableTransformInput) data = await transformInput(unsafeData, unsafeModel, "update");
623
+ debugLog({ method: "update" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 4)}`, `${formatMethod("update")} ${formatAction("Parsed Input")}:`, {
624
+ model,
625
+ data
626
+ });
627
+ const res = await adapterInstance.update({
628
+ model,
629
+ where,
630
+ update: data
631
+ });
632
+ debugLog({ method: "update" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 4)}`, `${formatMethod("update")} ${formatAction("DB Result")}:`, {
633
+ model,
634
+ data: res
635
+ });
636
+ let transformed = res;
637
+ if (!config.disableTransformOutput) transformed = await transformOutput(res, unsafeModel);
638
+ debugLog({ method: "update" }, `${formatTransactionId(thisTransactionId)} ${formatStep(4, 4)}`, `${formatMethod("update")} ${formatAction("Parsed Result")}:`, {
639
+ model,
640
+ data: transformed
641
+ });
642
+ return transformed;
643
+ },
644
+ updateMany: async ({ model: unsafeModel, where: unsafeWhere, update: unsafeData }) => {
645
+ transactionId++;
646
+ let thisTransactionId = transactionId;
647
+ const model = getModelName(unsafeModel);
648
+ const where = transformWhereClause({
649
+ model: unsafeModel,
650
+ where: unsafeWhere
651
+ });
652
+ unsafeModel = getDefaultModelName(unsafeModel);
653
+ debugLog({ method: "updateMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 4)}`, `${formatMethod("updateMany")} ${formatAction("Unsafe Input")}:`, {
654
+ model,
655
+ data: unsafeData
656
+ });
657
+ let data = unsafeData;
658
+ if (!config.disableTransformInput) data = await transformInput(unsafeData, unsafeModel, "update");
659
+ debugLog({ method: "updateMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 4)}`, `${formatMethod("updateMany")} ${formatAction("Parsed Input")}:`, {
660
+ model,
661
+ data
662
+ });
663
+ const updatedCount = await adapterInstance.updateMany({
664
+ model,
665
+ where,
666
+ update: data
667
+ });
668
+ debugLog({ method: "updateMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 4)}`, `${formatMethod("updateMany")} ${formatAction("DB Result")}:`, {
669
+ model,
670
+ data: updatedCount
671
+ });
672
+ debugLog({ method: "updateMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(4, 4)}`, `${formatMethod("updateMany")} ${formatAction("Parsed Result")}:`, {
673
+ model,
674
+ data: updatedCount
675
+ });
676
+ return updatedCount;
677
+ },
678
+ findOne: async ({ model: unsafeModel, where: unsafeWhere, select }) => {
679
+ transactionId++;
680
+ let thisTransactionId = transactionId;
681
+ const model = getModelName(unsafeModel);
682
+ const where = transformWhereClause({
683
+ model: unsafeModel,
684
+ where: unsafeWhere
685
+ });
686
+ unsafeModel = getDefaultModelName(unsafeModel);
687
+ debugLog({ method: "findOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 3)}`, `${formatMethod("findOne")}:`, {
688
+ model,
689
+ where,
690
+ select
691
+ });
692
+ const res = await adapterInstance.findOne({
693
+ model,
694
+ where,
695
+ ...select && { select }
696
+ });
697
+ debugLog({ method: "findOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 3)}`, `${formatMethod("findOne")} ${formatAction("DB Result")}:`, {
698
+ model,
699
+ data: res
700
+ });
701
+ let transformed = res;
702
+ if (!config.disableTransformOutput) transformed = await transformOutput(res, unsafeModel, select);
703
+ debugLog({ method: "findOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 3)}`, `${formatMethod("findOne")} ${formatAction("Parsed Result")}:`, {
704
+ model,
705
+ data: transformed
706
+ });
707
+ return transformed;
708
+ },
709
+ findMany: async ({ model: unsafeModel, where: unsafeWhere, limit: unsafeLimit, sortBy, offset }) => {
710
+ transactionId++;
711
+ let thisTransactionId = transactionId;
712
+ const limit = unsafeLimit ?? options.advanced?.database?.defaultFindManyLimit ?? 100;
713
+ const model = getModelName(unsafeModel);
714
+ const where = transformWhereClause({
715
+ model: unsafeModel,
716
+ where: unsafeWhere
717
+ });
718
+ unsafeModel = getDefaultModelName(unsafeModel);
719
+ debugLog({ method: "findMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 3)}`, `${formatMethod("findMany")}:`, {
720
+ model,
721
+ where,
722
+ limit,
723
+ sortBy,
724
+ offset
725
+ });
726
+ const res = await adapterInstance.findMany({
727
+ model,
728
+ ...where && { where },
729
+ limit,
730
+ ...sortBy && { sortBy },
731
+ ...offset && { offset }
732
+ });
733
+ debugLog({ method: "findMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 3)}`, `${formatMethod("findMany")} ${formatAction("DB Result")}:`, {
734
+ model,
735
+ data: res
736
+ });
737
+ let transformed = res;
738
+ if (!config.disableTransformOutput) transformed = await Promise.all(res.map(async (r) => await transformOutput(r, unsafeModel)));
739
+ debugLog({ method: "findMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 3)}`, `${formatMethod("findMany")} ${formatAction("Parsed Result")}:`, {
740
+ model,
741
+ data: transformed
742
+ });
743
+ return transformed;
744
+ },
745
+ delete: async ({ model: unsafeModel, where: unsafeWhere }) => {
746
+ transactionId++;
747
+ let thisTransactionId = transactionId;
748
+ const model = getModelName(unsafeModel);
749
+ const where = transformWhereClause({
750
+ model: unsafeModel,
751
+ where: unsafeWhere
752
+ });
753
+ unsafeModel = getDefaultModelName(unsafeModel);
754
+ debugLog({ method: "delete" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 2)}`, `${formatMethod("delete")}:`, {
755
+ model,
756
+ where
757
+ });
758
+ await adapterInstance.delete({
759
+ model,
760
+ where
761
+ });
762
+ debugLog({ method: "delete" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 2)}`, `${formatMethod("delete")} ${formatAction("DB Result")}:`, { model });
763
+ },
764
+ deleteMany: async ({ model: unsafeModel, where: unsafeWhere }) => {
765
+ transactionId++;
766
+ let thisTransactionId = transactionId;
767
+ const model = getModelName(unsafeModel);
768
+ const where = transformWhereClause({
769
+ model: unsafeModel,
770
+ where: unsafeWhere
771
+ });
772
+ unsafeModel = getDefaultModelName(unsafeModel);
773
+ debugLog({ method: "deleteMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 2)}`, `${formatMethod("deleteMany")} ${formatAction("DeleteMany")}:`, {
774
+ model,
775
+ where
776
+ });
777
+ const res = await adapterInstance.deleteMany({
778
+ model,
779
+ where
780
+ });
781
+ debugLog({ method: "deleteMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 2)}`, `${formatMethod("deleteMany")} ${formatAction("DB Result")}:`, {
782
+ model,
783
+ data: res
784
+ });
785
+ return res;
786
+ },
787
+ count: async ({ model: unsafeModel, where: unsafeWhere }) => {
788
+ transactionId++;
789
+ let thisTransactionId = transactionId;
790
+ const model = getModelName(unsafeModel);
791
+ const where = transformWhereClause({
792
+ model: unsafeModel,
793
+ where: unsafeWhere
794
+ });
795
+ unsafeModel = getDefaultModelName(unsafeModel);
796
+ debugLog({ method: "count" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 2)}`, `${formatMethod("count")}:`, {
797
+ model,
798
+ where
799
+ });
800
+ const res = await adapterInstance.count({
801
+ model,
802
+ ...where && { where }
803
+ });
804
+ debugLog({ method: "count" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 2)}`, `${formatMethod("count")}:`, {
805
+ model,
806
+ data: res
807
+ });
808
+ return res;
809
+ },
810
+ createSchema: adapterInstance.createSchema ? async (_, file) => {
811
+ const tables = getAuthTables(options);
812
+ if (options.secondaryStorage && !options.session?.storeSessionInDatabase) delete tables.session;
813
+ if (options.rateLimit && options.rateLimit.storage === "database" && (typeof options.rateLimit.enabled === "undefined" || options.rateLimit.enabled === true)) tables.ratelimit = {
814
+ modelName: options.rateLimit.modelName ?? "ratelimit",
815
+ fields: {
816
+ key: {
817
+ type: "string",
818
+ unique: true,
819
+ required: true,
820
+ fieldName: options.rateLimit.fields?.key ?? "key"
821
+ },
822
+ count: {
823
+ type: "number",
824
+ required: true,
825
+ fieldName: options.rateLimit.fields?.count ?? "count"
826
+ },
827
+ lastRequest: {
828
+ type: "number",
829
+ required: true,
830
+ bigint: true,
831
+ defaultValue: () => Date.now(),
832
+ fieldName: options.rateLimit.fields?.lastRequest ?? "lastRequest"
833
+ }
834
+ }
835
+ };
836
+ return adapterInstance.createSchema({
837
+ ...file && { file },
838
+ tables
839
+ });
840
+ } : void 0,
841
+ options: {
842
+ adapterConfig: config,
843
+ ...adapterInstance.options ?? {}
844
+ },
845
+ id: config.adapterId,
846
+ ...config.debugLogs?.isRunningAdapterTests ? { adapterTestDebugLogs: {
847
+ resetDebugLogs() {
848
+ debugLogs = debugLogs.filter((log) => log.instance !== uniqueAdapterFactoryInstanceId);
849
+ },
850
+ printDebugLogs() {
851
+ const separator = `─`.repeat(80);
852
+ const logs = debugLogs.filter((log$1) => log$1.instance === uniqueAdapterFactoryInstanceId);
853
+ if (logs.length === 0) return;
854
+ let log = logs.reverse().map((log$1) => {
855
+ log$1.args[0] = `\n${log$1.args[0]}`;
856
+ return [...log$1.args, "\n"];
857
+ }).reduce((prev, curr) => {
858
+ return [...curr, ...prev];
859
+ }, [`\n${separator}`]);
860
+ console.log(...log);
861
+ }
862
+ } } : {}
863
+ };
864
+ return adapter;
865
+ };
866
+ function formatTransactionId(transactionId$1) {
867
+ if (getColorDepth() < 8) return `#${transactionId$1}`;
868
+ return `${TTY_COLORS.fg.magenta}#${transactionId$1}${TTY_COLORS.reset}`;
869
+ }
870
+ function formatStep(step, total) {
871
+ return `${TTY_COLORS.bg.black}${TTY_COLORS.fg.yellow}[${step}/${total}]${TTY_COLORS.reset}`;
872
+ }
873
+ function formatMethod(method) {
874
+ return `${TTY_COLORS.bright}${method}${TTY_COLORS.reset}`;
875
+ }
876
+ function formatAction(action) {
877
+ return `${TTY_COLORS.dim}(${action})${TTY_COLORS.reset}`;
878
+ }
879
+
880
+ //#endregion
881
+ export { getAuthTables as n, createAdapterFactory as t };