faire-auth 1.0.3 → 1.1.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 (228) hide show
  1. package/dist/{adapter-factory-lKIOf2OR.mjs → adapter-factory-qPVW8x9-.mjs} +34 -36
  2. package/dist/{adapter-factory-D1I7joki.cjs → adapter-factory-u8r3oTez.cjs} +66 -68
  3. package/dist/adapters/drizzle-adapter/index.cjs +34 -40
  4. package/dist/adapters/drizzle-adapter/index.d.cts +4 -9
  5. package/dist/adapters/drizzle-adapter/index.d.mts +4 -9
  6. package/dist/adapters/drizzle-adapter/index.mjs +20 -26
  7. package/dist/adapters/index.cjs +11 -16
  8. package/dist/adapters/index.d.cts +11 -37
  9. package/dist/adapters/index.d.mts +11 -37
  10. package/dist/adapters/index.mjs +4 -13
  11. package/dist/adapters/kysely-adapter/index.cjs +270 -11
  12. package/dist/adapters/kysely-adapter/index.d.cts +9 -19
  13. package/dist/adapters/kysely-adapter/index.d.mts +9 -19
  14. package/dist/adapters/kysely-adapter/index.mjs +267 -9
  15. package/dist/adapters/memory-adapter/index.cjs +146 -9
  16. package/dist/adapters/memory-adapter/index.d.cts +4 -10
  17. package/dist/adapters/memory-adapter/index.d.mts +4 -10
  18. package/dist/adapters/memory-adapter/index.mjs +145 -9
  19. package/dist/adapters/mongodb-adapter/index.cjs +13 -21
  20. package/dist/adapters/mongodb-adapter/index.d.cts +3 -8
  21. package/dist/adapters/mongodb-adapter/index.d.mts +4 -9
  22. package/dist/adapters/mongodb-adapter/index.mjs +12 -20
  23. package/dist/adapters/prisma-adapter/index.cjs +12 -20
  24. package/dist/adapters/prisma-adapter/index.d.cts +4 -8
  25. package/dist/adapters/prisma-adapter/index.d.mts +4 -8
  26. package/dist/adapters/prisma-adapter/index.mjs +5 -13
  27. package/dist/adapters/test.cjs +86 -69
  28. package/dist/adapters/test.d.cts +7 -11
  29. package/dist/adapters/test.d.mts +7 -11
  30. package/dist/adapters/test.mjs +83 -66
  31. package/dist/api/index.cjs +3 -20
  32. package/dist/api/index.d.cts +2 -3
  33. package/dist/api/index.d.mts +2 -3
  34. package/dist/api/index.mjs +1 -20
  35. package/dist/api/middleware/index.cjs +4 -11
  36. package/dist/api/middleware/index.d.cts +3 -9
  37. package/dist/api/middleware/index.d.mts +3 -9
  38. package/dist/api/middleware/index.mjs +3 -11
  39. package/dist/{api-B4RDwBty.mjs → api-0f-F-Fi2.mjs} +292 -189
  40. package/dist/{api-CaRC1Gio.cjs → api-LjfH6hQi.cjs} +557 -452
  41. package/dist/{test-utils/bun-sqlite-dialect-BZBvHchL.cjs → bun-sqlite-dialect-BHkarnxN.cjs} +5 -9
  42. package/dist/{test-utils/bun-sqlite-dialect-BSWhhKNs.mjs → bun-sqlite-dialect-BiZBuEF6.mjs} +6 -9
  43. package/dist/client/index.cjs +8 -15
  44. package/dist/client/index.d.cts +9 -14
  45. package/dist/client/index.d.mts +9 -14
  46. package/dist/client/index.mjs +7 -15
  47. package/dist/client/lynx/index.cjs +10 -18
  48. package/dist/client/lynx/index.d.cts +402 -71
  49. package/dist/client/lynx/index.d.mts +402 -71
  50. package/dist/client/lynx/index.mjs +5 -13
  51. package/dist/client/plugins/index.cjs +3 -5
  52. package/dist/client/plugins/index.d.cts +5 -10
  53. package/dist/client/plugins/index.d.mts +5 -10
  54. package/dist/client/plugins/index.mjs +2 -4
  55. package/dist/client/react/index.cjs +6 -14
  56. package/dist/client/react/index.d.cts +402 -71
  57. package/dist/client/react/index.d.mts +402 -71
  58. package/dist/client/react/index.mjs +5 -13
  59. package/dist/client/solid/index.cjs +6 -14
  60. package/dist/client/solid/index.d.cts +393 -57
  61. package/dist/client/solid/index.d.mts +393 -57
  62. package/dist/client/solid/index.mjs +5 -13
  63. package/dist/client/svelte/index.cjs +5 -10
  64. package/dist/client/svelte/index.d.cts +400 -67
  65. package/dist/client/svelte/index.d.mts +400 -67
  66. package/dist/client/svelte/index.mjs +4 -10
  67. package/dist/client/vue/index.cjs +6 -14
  68. package/dist/client/vue/index.d.cts +401 -68
  69. package/dist/client/vue/index.d.mts +401 -68
  70. package/dist/client/vue/index.mjs +5 -13
  71. package/dist/{cookies-BTs1o992.mjs → cookies-D9aY_gJh.mjs} +25 -21
  72. package/dist/{cookies-BTl72THv.cjs → cookies-DQ52rcOy.cjs} +119 -115
  73. package/dist/crypto/index.cjs +10 -8
  74. package/dist/crypto/index.d.cts +5 -13
  75. package/dist/crypto/index.d.mts +5 -13
  76. package/dist/crypto/index.mjs +2 -5
  77. package/dist/{crypto-DH2Aa7jN.mjs → crypto-BH-hD0lJ.mjs} +7 -10
  78. package/dist/{crypto-DpSCnrTp.cjs → crypto-BITfWVwD.cjs} +24 -27
  79. package/dist/db/index.cjs +1135 -29
  80. package/dist/db/index.d.cts +1 -2
  81. package/dist/db/index.d.mts +1 -2
  82. package/dist/db/index.mjs +1115 -16
  83. package/dist/defu-D2h4S3X-.mjs +87 -0
  84. package/dist/defu-DWS5RPWt.cjs +134 -0
  85. package/dist/{email-verification-DI_0H4JC.cjs → email-verification-DOPnSgbI.cjs} +65 -71
  86. package/dist/{email-verification-C_lBu_JY.mjs → email-verification-YSR5n5lb.mjs} +23 -29
  87. package/dist/{hono-CO-zsqI-.mjs → hono-BAV2wQkK.mjs} +16 -33
  88. package/dist/hono-SVQuc5Ru.mjs +4 -0
  89. package/dist/hono-pgK4H_U1.cjs +9 -0
  90. package/dist/{hono-DnW5crl1.cjs → hono-tyFFJFdS.cjs} +42 -60
  91. package/dist/index-B86Cy0dE.d.cts +2 -0
  92. package/dist/index-B86Cy0dE.d.mts +2 -0
  93. package/dist/index.cjs +115 -150
  94. package/dist/index.d.cts +4 -5
  95. package/dist/index.d.mts +4 -5
  96. package/dist/index.mjs +46 -81
  97. package/dist/integrations/next-js.cjs +5 -9
  98. package/dist/integrations/next-js.d.cts +6 -14
  99. package/dist/integrations/next-js.d.mts +6 -14
  100. package/dist/integrations/next-js.mjs +4 -9
  101. package/dist/integrations/node.cjs +16 -14
  102. package/dist/integrations/node.d.cts +6 -14
  103. package/dist/integrations/node.d.mts +6 -14
  104. package/dist/integrations/node.mjs +15 -13
  105. package/dist/integrations/react-start.cjs +7 -11
  106. package/dist/integrations/react-start.d.cts +5 -13
  107. package/dist/integrations/react-start.d.mts +5 -13
  108. package/dist/integrations/react-start.mjs +6 -11
  109. package/dist/integrations/solid-start.cjs +3 -5
  110. package/dist/integrations/solid-start.d.cts +2 -5
  111. package/dist/integrations/solid-start.d.mts +2 -5
  112. package/dist/integrations/solid-start.mjs +2 -4
  113. package/dist/integrations/svelte-kit.cjs +6 -10
  114. package/dist/integrations/svelte-kit.d.cts +11 -23
  115. package/dist/integrations/svelte-kit.d.mts +11 -23
  116. package/dist/integrations/svelte-kit.mjs +5 -10
  117. package/dist/{ip-BjNYspCH.mjs → ip-6Lv2o42m.mjs} +4 -9
  118. package/dist/{ip-C17Qdq-G.cjs → ip-DPydExzV.cjs} +21 -27
  119. package/dist/{json--tl7Grvs.cjs → json-D3aq-nH2.cjs} +9 -13
  120. package/dist/{json-B1v2qRTQ.mjs → json-DooGMtnJ.mjs} +2 -5
  121. package/dist/{logged-CyGfp8_H.mjs → logged-B83SzMnJ.mjs} +6 -10
  122. package/dist/{logged-Dv3st5qc.cjs → logged-BIpCpnVY.cjs} +13 -18
  123. package/dist/{middleware-CE6OhDkq.mjs → middleware-Cakg4e1D.mjs} +2 -4
  124. package/dist/{middleware-CWvRH4EW.cjs → middleware-Cd-VkNxB.cjs} +17 -20
  125. package/dist/{node-sqlite-dialect-w4DAg0PH.mjs → node-sqlite-dialect-BMVOjEMh.mjs} +6 -9
  126. package/dist/{test-utils/node-sqlite-dialect-BgJqjBOu.cjs → node-sqlite-dialect-D3QPFROH.cjs} +5 -9
  127. package/dist/oauth2/index.cjs +166 -22
  128. package/dist/oauth2/index.d.cts +5 -17
  129. package/dist/oauth2/index.d.mts +5 -17
  130. package/dist/oauth2/index.mjs +156 -16
  131. package/dist/{origin-check-DjLTuZQ8.cjs → origin-check-BflGhEEN.cjs} +34 -38
  132. package/dist/{origin-check-8Gajklvh.mjs → origin-check-CRgs1M7k.mjs} +13 -16
  133. package/dist/{parser-B25ylT5u.mjs → parser-CqwvpF6l.cjs} +12 -10
  134. package/dist/{parser-B_wxvaAr.cjs → parser-DcKDjjHO.mjs} +7 -22
  135. package/dist/plugins/access/index.cjs +38 -4
  136. package/dist/plugins/access/index.d.cts +36 -2
  137. package/dist/plugins/access/index.d.mts +36 -2
  138. package/dist/plugins/access/index.mjs +36 -3
  139. package/dist/plugins/bearer/index.cjs +52 -7
  140. package/dist/plugins/bearer/index.d.cts +27 -4
  141. package/dist/plugins/bearer/index.d.mts +27 -4
  142. package/dist/plugins/bearer/index.mjs +51 -7
  143. package/dist/plugins/index.cjs +1385 -842
  144. package/dist/plugins/index.d.cts +489 -7566
  145. package/dist/plugins/index.d.mts +489 -7566
  146. package/dist/plugins/index.mjs +1118 -576
  147. package/dist/plugins/passkey/index.cjs +551 -15
  148. package/dist/plugins/passkey/index.d.cts +123 -4
  149. package/dist/plugins/passkey/index.d.mts +123 -4
  150. package/dist/plugins/passkey/index.mjs +547 -15
  151. package/dist/{chunk-BFnQceUY.mjs → rolldown-runtime-BKpuH2hG.mjs} +6 -7
  152. package/dist/{chunk-fPmz2rbM.cjs → rolldown-runtime-C_Pgydhf.cjs} +22 -24
  153. package/dist/{schema-DTIwLLmf.mjs → schema-CFCpv0tK.mjs} +3 -6
  154. package/dist/{schema-CirKflVs.cjs → schema-b-lKhMkG.cjs} +51 -55
  155. package/dist/{session-CM3rmOYF.mjs → session-BGjJgihS.mjs} +51 -74
  156. package/dist/{session-Cwrj4GfV.cjs → session-CzZSMmQC.cjs} +197 -219
  157. package/dist/shared.d.cts +1581 -0
  158. package/dist/shared.d.mts +1581 -0
  159. package/dist/social-providers/index.cjs +9 -9
  160. package/dist/social-providers/index.d.cts +1 -1
  161. package/dist/social-providers/index.d.mts +1 -1
  162. package/dist/social-providers/index.mjs +3 -5
  163. package/dist/social-providers-CjPww-qf.mjs +6 -0
  164. package/dist/social-providers-D7w_7Ym8.cjs +10 -0
  165. package/dist/{state-CvSihlVT.cjs → state-2OrNjOO-.cjs} +24 -24
  166. package/dist/{state-CQghgH9I.mjs → state-Dooeisfq.mjs} +17 -17
  167. package/dist/{bun-sqlite-dialect-DPgTzc0w.cjs → test-utils/bun-sqlite-dialect-BHkarnxN.cjs} +5 -9
  168. package/dist/{bun-sqlite-dialect-6NqeV3px.mjs → test-utils/bun-sqlite-dialect-BiZBuEF6.mjs} +6 -9
  169. package/dist/test-utils/index.cjs +8831 -7941
  170. package/dist/test-utils/index.d.cts +310 -12440
  171. package/dist/test-utils/index.d.mts +313 -12440
  172. package/dist/test-utils/index.mjs +8591 -7701
  173. package/dist/test-utils/{node-sqlite-dialect-DAQXiobH.mjs → node-sqlite-dialect-BMVOjEMh.mjs} +6 -9
  174. package/dist/{node-sqlite-dialect-DP11CB0y.cjs → test-utils/node-sqlite-dialect-D3QPFROH.cjs} +5 -9
  175. package/dist/types/index.d.cts +2 -3
  176. package/dist/types/index.d.mts +2 -3
  177. package/dist/types/index.mjs +1 -1
  178. package/dist/{url-BoUuoIwZ.mjs → url-CJtdrrUu.mjs} +12 -13
  179. package/dist/{url-Ce7CVaQD.cjs → url-DjCmCUHS.cjs} +42 -44
  180. package/dist/utils/cookies.cjs +29 -30
  181. package/dist/utils/cookies.d.cts +21 -25
  182. package/dist/utils/cookies.d.mts +20 -24
  183. package/dist/utils/cookies.mjs +2 -7
  184. package/dist/utils-C7OHyfHa.mjs +4 -0
  185. package/dist/utils-iX0Vy_UL.cjs +3 -0
  186. package/package.json +40 -30
  187. package/dist/access-BZ7-AbTM.cjs +0 -51
  188. package/dist/access-D0DRqUKC.mjs +0 -39
  189. package/dist/bearer-DDzrp5M7.cjs +0 -60
  190. package/dist/bearer-WZcs7gxL.mjs +0 -54
  191. package/dist/db-4tUsQJXd.mjs +0 -1119
  192. package/dist/db-ChMbb_U-.cjs +0 -1180
  193. package/dist/defu-BmOYq4PU.cjs +0 -34
  194. package/dist/defu-D9ZTXqlo.mjs +0 -28
  195. package/dist/hono-C14rpOEa.cjs +0 -13
  196. package/dist/hono-CoKYWnXA.mjs +0 -7
  197. package/dist/hono-D0VqxVy1.d.mts +0 -18
  198. package/dist/hono-DOM31WQz.d.cts +0 -18
  199. package/dist/index-BCTFWP_o.d.mts +0 -992
  200. package/dist/index-BDhhaE6Y.d.cts +0 -3
  201. package/dist/index-BVRfQy6L.d.mts +0 -992
  202. package/dist/index-Baarsq5J.d.mts +0 -33
  203. package/dist/index-By364WbF.d.cts +0 -992
  204. package/dist/index-BzWwMgxr.d.cts +0 -992
  205. package/dist/index-CF9iq55a.d.mts +0 -3
  206. package/dist/index-CJD2yB-W.d.cts +0 -33
  207. package/dist/index-CRt_fppq.d.mts +0 -41
  208. package/dist/index-CdLyn7qP.d.cts +0 -41
  209. package/dist/index-CsWF3f7U.d.cts +0 -13350
  210. package/dist/index-CzidsAyA.d.mts +0 -13350
  211. package/dist/index-DvW-GCcI.d.cts +0 -33
  212. package/dist/index-f-5OJ9yV.d.cts +0 -13350
  213. package/dist/index-rFv8Hxld.d.mts +0 -13350
  214. package/dist/index-ztVZPQdV.d.mts +0 -33
  215. package/dist/kysely-adapter-CtIdoHa8.mjs +0 -270
  216. package/dist/kysely-adapter-QZTx077T.cjs +0 -288
  217. package/dist/memory-adapter-17RZd5df.cjs +0 -154
  218. package/dist/memory-adapter-Dp4XdCZK.mjs +0 -148
  219. package/dist/oauth2-5RL4cVNS.cjs +0 -177
  220. package/dist/oauth2-C56wz-n9.mjs +0 -159
  221. package/dist/passkey-BTT-v5c-.cjs +0 -512
  222. package/dist/passkey-CzY_W2us.mjs +0 -505
  223. package/dist/request-1NL_1lyJ.mjs +0 -58
  224. package/dist/request-CPNlp-DK.cjs +0 -100
  225. package/dist/social-providers-B8RK5yqI.mjs +0 -9
  226. package/dist/social-providers-BmFOIIPk.cjs +0 -13
  227. package/dist/utils-44aDDP8f.cjs +0 -2
  228. package/dist/utils-D4vZd1-9.mjs +0 -4
@@ -1,1119 +0,0 @@
1
- import { n as getContext } from "./hono-CoKYWnXA.mjs";
2
- import { n as getCurrentAdapter, r as runWithTransaction, t as getIp } from "./ip-BjNYspCH.mjs";
3
- import { t as safeJSONParse } from "./json-B1v2qRTQ.mjs";
4
- import { r as generateId } from "./utils-D4vZd1-9.mjs";
5
- import { l as parseUserOutput, s as parseSessionOutput } from "./schema-DTIwLLmf.mjs";
6
- import { n as createKyselyAdapter, t as kyselyAdapter } from "./kysely-adapter-CtIdoHa8.mjs";
7
- import { n as getAuthTables } from "./adapter-factory-lKIOf2OR.mjs";
8
- import { t as memoryAdapter } from "./memory-adapter-Dp4XdCZK.mjs";
9
- import { createLogger, logger } from "@faire-auth/core/env";
10
- import { FaireAuthError } from "@faire-auth/core/error";
11
- import { isPromise } from "@faire-auth/core/static";
12
- import { getDate } from "@faire-auth/core/utils";
13
- import * as z$1 from "zod";
14
- import { sql } from "kysely";
15
-
16
- //#region src/db/field.ts
17
- const createFieldAttribute = (type, config) => {
18
- return {
19
- type,
20
- ...config
21
- };
22
- };
23
-
24
- //#endregion
25
- //#region src/db/get-schema.ts
26
- function getSchema(config) {
27
- const tables = getAuthTables(config);
28
- let schema = {};
29
- for (const key in tables) {
30
- const table = tables[key];
31
- const fields = table.fields;
32
- let actualFields = {};
33
- Object.entries(fields).forEach(([key$1, field]) => {
34
- actualFields[field.fieldName || key$1] = field;
35
- if (field.references) {
36
- const refTable = tables[field.references.model];
37
- if (refTable) actualFields[field.fieldName || key$1].references = {
38
- ...field.references,
39
- model: refTable.modelName,
40
- field: field.references.field
41
- };
42
- }
43
- });
44
- if (schema[table.modelName]) {
45
- schema[table.modelName].fields = {
46
- ...schema[table.modelName].fields,
47
- ...actualFields
48
- };
49
- continue;
50
- }
51
- schema[table.modelName] = {
52
- fields: actualFields,
53
- order: table.order || Infinity
54
- };
55
- }
56
- return schema;
57
- }
58
-
59
- //#endregion
60
- //#region src/db/get-migration.ts
61
- const map = {
62
- postgres: {
63
- string: [
64
- "character varying",
65
- "varchar",
66
- "text"
67
- ],
68
- number: [
69
- "int4",
70
- "integer",
71
- "bigint",
72
- "smallint",
73
- "numeric",
74
- "real",
75
- "double precision"
76
- ],
77
- boolean: ["bool", "boolean"],
78
- date: [
79
- "timestamptz",
80
- "timestamp",
81
- "date"
82
- ],
83
- json: ["json", "jsonb"]
84
- },
85
- mysql: {
86
- string: ["varchar", "text"],
87
- number: [
88
- "integer",
89
- "int",
90
- "bigint",
91
- "smallint",
92
- "decimal",
93
- "float",
94
- "double"
95
- ],
96
- boolean: ["boolean", "tinyint"],
97
- date: [
98
- "timestamp",
99
- "datetime",
100
- "date"
101
- ],
102
- json: ["json"]
103
- },
104
- sqlite: {
105
- string: ["TEXT"],
106
- number: ["INTEGER", "REAL"],
107
- boolean: ["INTEGER", "BOOLEAN"],
108
- date: ["DATE", "INTEGER"],
109
- json: ["TEXT"]
110
- },
111
- mssql: {
112
- string: ["varchar", "nvarchar"],
113
- number: [
114
- "int",
115
- "bigint",
116
- "smallint",
117
- "decimal",
118
- "float",
119
- "double"
120
- ],
121
- boolean: ["bit", "smallint"],
122
- date: [
123
- "datetime2",
124
- "date",
125
- "datetime"
126
- ],
127
- json: ["varchar", "nvarchar"]
128
- }
129
- };
130
- function matchType(columnDataType, fieldType, dbType) {
131
- function normalize(type) {
132
- return type.toLowerCase().split("(")[0].trim();
133
- }
134
- if (fieldType === "string[]" || fieldType === "number[]") return columnDataType.toLowerCase().includes("json");
135
- const types = map[dbType];
136
- return (Array.isArray(fieldType) ? types["string"].map((t) => t.toLowerCase()) : types[fieldType].map((t) => t.toLowerCase())).includes(normalize(columnDataType));
137
- }
138
- /**
139
- * Get the current PostgreSQL schema (search_path) for the database connection
140
- * Returns the first schema in the search_path, defaulting to 'public' if not found
141
- */
142
- async function getPostgresSchema(db) {
143
- try {
144
- const result = await sql`SHOW search_path`.execute(db);
145
- if (result.rows[0]?.search_path) return result.rows[0].search_path.split(",").map((s) => s.trim()).map((s) => s.replace(/^["']|["']$/g, "")).filter((s) => !s.startsWith("$"))[0] || "public";
146
- } catch (error) {}
147
- return "public";
148
- }
149
- async function getMigrations(config) {
150
- const betterAuthSchema = getSchema(config);
151
- const logger$1 = createLogger(config.logger);
152
- const adapter = createKyselyAdapter(config);
153
- if ("initialize" in adapter) await adapter.initialize();
154
- let { kysely: db, databaseType: dbType } = adapter;
155
- if (!dbType) {
156
- logger$1.warn("Could not determine database type, defaulting to sqlite. Please provide a type in the database options to avoid this.");
157
- dbType = "sqlite";
158
- }
159
- if (!db) {
160
- logger$1.error("Only kysely adapter is supported for migrations. You can use `generate` command to generate the schema, if you're using a different adapter.");
161
- process.exit(1);
162
- }
163
- let currentSchema = "public";
164
- if (dbType === "postgres") {
165
- currentSchema = await getPostgresSchema(db);
166
- logger$1.debug(`PostgreSQL migration: Using schema '${currentSchema}' (from search_path)`);
167
- try {
168
- if (!(await sql`
169
- SELECT schema_name
170
- FROM information_schema.schemata
171
- WHERE schema_name = ${currentSchema}
172
- `.execute(db)).rows[0]) logger$1.warn(`Schema '${currentSchema}' does not exist. Tables will be inspected from available schemas. Consider creating the schema first or checking your database configuration.`);
173
- } catch (error) {
174
- logger$1.debug(`Could not verify schema existence: ${error instanceof Error ? error.message : String(error)}`);
175
- }
176
- }
177
- const allTableMetadata = await db.introspection.getTables();
178
- let tableMetadata = allTableMetadata;
179
- if (dbType === "postgres") try {
180
- const tablesInSchema = await sql`
181
- SELECT table_name
182
- FROM information_schema.tables
183
- WHERE table_schema = ${currentSchema}
184
- AND table_type = 'BASE TABLE'
185
- `.execute(db);
186
- const tableNamesInSchema = new Set(tablesInSchema.rows.map((row) => row.table_name));
187
- tableMetadata = allTableMetadata.filter((table) => table.schema === currentSchema && tableNamesInSchema.has(table.name));
188
- logger$1.debug(`Found ${tableMetadata.length} table(s) in schema '${currentSchema}': ${tableMetadata.map((t) => t.name).join(", ") || "(none)"}`);
189
- } catch (error) {
190
- logger$1.warn(`Could not filter tables by schema. Using all discovered tables. Error: ${error instanceof Error ? error.message : String(error)}`);
191
- }
192
- const toBeCreated = [];
193
- const toBeAdded = [];
194
- for (const [key, value] of Object.entries(betterAuthSchema)) {
195
- const table = tableMetadata.find((t) => t.name === key);
196
- if (!table) {
197
- const tIndex = toBeCreated.findIndex((t) => t.table === key);
198
- const tableData = {
199
- table: key,
200
- fields: value.fields,
201
- order: value.order || Infinity
202
- };
203
- const insertIndex = toBeCreated.findIndex((t) => (t.order || Infinity) > tableData.order);
204
- if (insertIndex === -1) if (tIndex === -1) toBeCreated.push(tableData);
205
- else toBeCreated[tIndex].fields = {
206
- ...toBeCreated[tIndex].fields,
207
- ...value.fields
208
- };
209
- else toBeCreated.splice(insertIndex, 0, tableData);
210
- continue;
211
- }
212
- let toBeAddedFields = {};
213
- for (const [fieldName, field] of Object.entries(value.fields)) {
214
- const column = table.columns.find((c) => c.name === fieldName);
215
- if (!column) {
216
- toBeAddedFields[fieldName] = field;
217
- continue;
218
- }
219
- if (matchType(column.dataType, field.type, dbType)) continue;
220
- else logger$1.warn(`Field ${fieldName} in table ${key} has a different type in the database. Expected ${field.type} but got ${column.dataType}.`);
221
- }
222
- if (Object.keys(toBeAddedFields).length > 0) toBeAdded.push({
223
- table: key,
224
- fields: toBeAddedFields,
225
- order: value.order || Infinity
226
- });
227
- }
228
- const migrations = [];
229
- function getType(field, fieldName) {
230
- const type = field.type;
231
- const typeMap = {
232
- string: {
233
- sqlite: "text",
234
- postgres: "text",
235
- mysql: field.unique ? "varchar(255)" : field.references ? "varchar(36)" : "text",
236
- mssql: field.unique || field.sortable ? "varchar(255)" : field.references ? "varchar(36)" : "varchar(8000)"
237
- },
238
- boolean: {
239
- sqlite: "integer",
240
- postgres: "boolean",
241
- mysql: "boolean",
242
- mssql: "smallint"
243
- },
244
- number: {
245
- sqlite: field.bigint ? "bigint" : "integer",
246
- postgres: field.bigint ? "bigint" : "integer",
247
- mysql: field.bigint ? "bigint" : "integer",
248
- mssql: field.bigint ? "bigint" : "integer"
249
- },
250
- date: {
251
- sqlite: "date",
252
- postgres: "timestamptz",
253
- mysql: "timestamp(3)",
254
- mssql: sql`datetime2(3)`
255
- },
256
- json: {
257
- sqlite: "text",
258
- postgres: "jsonb",
259
- mysql: "json",
260
- mssql: "varchar(8000)"
261
- },
262
- id: {
263
- postgres: config.advanced?.database?.useNumberId ? "serial" : "text",
264
- mysql: config.advanced?.database?.useNumberId ? "integer" : "varchar(36)",
265
- mssql: config.advanced?.database?.useNumberId ? "integer" : "varchar(36)",
266
- sqlite: config.advanced?.database?.useNumberId ? "integer" : "text"
267
- },
268
- foreignKeyId: {
269
- postgres: config.advanced?.database?.useNumberId ? "integer" : "text",
270
- mysql: config.advanced?.database?.useNumberId ? "integer" : "varchar(36)",
271
- mssql: config.advanced?.database?.useNumberId ? "integer" : "varchar(36)",
272
- sqlite: config.advanced?.database?.useNumberId ? "integer" : "text"
273
- }
274
- };
275
- if (fieldName === "id" || field.references?.field === "id") {
276
- if (fieldName === "id") return typeMap.id[dbType];
277
- return typeMap.foreignKeyId[dbType];
278
- }
279
- if (dbType === "sqlite" && (type === "string[]" || type === "number[]")) return "text";
280
- if (type === "string[]" || type === "number[]") return "jsonb";
281
- if (Array.isArray(type)) return "text";
282
- return typeMap[type][dbType || "sqlite"];
283
- }
284
- if (toBeAdded.length) for (const table of toBeAdded) for (const [fieldName, field] of Object.entries(table.fields)) {
285
- const type = getType(field, fieldName);
286
- const exec = db.schema.alterTable(table.table).addColumn(fieldName, type, (col) => {
287
- col = field.required !== false ? col.notNull() : col;
288
- if (field.references) col = col.references(`${field.references.model}.${field.references.field}`).onDelete(field.references.onDelete || "cascade");
289
- if (field.unique) col = col.unique();
290
- if (field.type === "date" && typeof field.defaultValue === "function" && (dbType === "postgres" || dbType === "mysql" || dbType === "mssql")) if (dbType === "mysql") col = col.defaultTo(sql`CURRENT_TIMESTAMP(3)`);
291
- else col = col.defaultTo(sql`CURRENT_TIMESTAMP`);
292
- return col;
293
- });
294
- migrations.push(exec);
295
- }
296
- if (toBeCreated.length) for (const table of toBeCreated) {
297
- let dbT = db.schema.createTable(table.table).addColumn("id", config.advanced?.database?.useNumberId ? dbType === "postgres" ? "serial" : "integer" : dbType === "mysql" || dbType === "mssql" ? "varchar(36)" : "text", (col) => {
298
- if (config.advanced?.database?.useNumberId) {
299
- if (dbType === "postgres" || dbType === "sqlite") return col.primaryKey().notNull();
300
- else if (dbType === "mssql") return col.identity().primaryKey().notNull();
301
- return col.autoIncrement().primaryKey().notNull();
302
- }
303
- return col.primaryKey().notNull();
304
- });
305
- for (const [fieldName, field] of Object.entries(table.fields)) {
306
- const type = getType(field, fieldName);
307
- dbT = dbT.addColumn(fieldName, type, (col) => {
308
- col = field.required !== false ? col.notNull() : col;
309
- if (field.references) col = col.references(`${field.references.model}.${field.references.field}`).onDelete(field.references.onDelete || "cascade");
310
- if (field.unique) col = col.unique();
311
- if (field.type === "date" && typeof field.defaultValue === "function" && (dbType === "postgres" || dbType === "mysql" || dbType === "mssql")) if (dbType === "mysql") col = col.defaultTo(sql`CURRENT_TIMESTAMP(3)`);
312
- else col = col.defaultTo(sql`CURRENT_TIMESTAMP`);
313
- return col;
314
- });
315
- }
316
- migrations.push(dbT);
317
- }
318
- async function runMigrations() {
319
- for (const migration of migrations) await migration.execute();
320
- }
321
- async function compileMigrations() {
322
- return migrations.map((m) => m.compile().sql).join(";\n\n") + ";";
323
- }
324
- return {
325
- toBeCreated,
326
- toBeAdded,
327
- runMigrations,
328
- compileMigrations
329
- };
330
- }
331
-
332
- //#endregion
333
- //#region src/db/with-hooks.ts
334
- const getWithHooks = (adapter, hooks = []) => ({
335
- async createWithHooks(data, model, customCreateFn) {
336
- const ctx = getContext();
337
- let actualData = data;
338
- for (const hook of hooks) {
339
- const toRun = hook[model]?.create?.before;
340
- if (toRun) {
341
- const result = await toRun(actualData, ctx);
342
- if (result === false) return null;
343
- if (typeof result === "object" && "data" in result) actualData = {
344
- ...actualData,
345
- ...result.data
346
- };
347
- }
348
- }
349
- const customCreated = customCreateFn ? await customCreateFn.fn(actualData) : null;
350
- const created = !customCreateFn || customCreateFn.executeMainFn ? await getCurrentAdapter(adapter).create({
351
- model,
352
- data: actualData,
353
- forceAllowId: true
354
- }) : customCreated;
355
- for (const hook of hooks) {
356
- const toRun = hook[model]?.create?.after;
357
- if (toRun) await toRun(created, ctx);
358
- }
359
- return created;
360
- },
361
- async updateWithHooks(data, where, model, customUpdateFn) {
362
- const ctx = getContext();
363
- let actualData = data;
364
- for (const hook of hooks) {
365
- const toRun = hook[model]?.update?.before;
366
- if (toRun) {
367
- const result = await toRun(data, ctx);
368
- if (result === false) return null;
369
- actualData = typeof result === "object" ? result.data : result;
370
- }
371
- }
372
- const customUpdated = customUpdateFn ? await customUpdateFn.fn(actualData) : null;
373
- const updated = !customUpdateFn || customUpdateFn.executeMainFn ? await getCurrentAdapter(adapter).update({
374
- model,
375
- update: actualData,
376
- where
377
- }) : customUpdated;
378
- for (const hook of hooks) {
379
- const toRun = hook[model]?.update?.after;
380
- if (toRun) await toRun(updated, ctx);
381
- }
382
- return updated;
383
- },
384
- async updateManyWithHooks(data, where, model, customUpdateFn) {
385
- const ctx = getContext();
386
- let actualData = data;
387
- for (const hook of hooks) {
388
- const toRun = hook[model]?.update?.before;
389
- if (toRun) {
390
- const result = await toRun(data, ctx);
391
- if (result === false) return null;
392
- actualData = typeof result === "object" ? result.data : result;
393
- }
394
- }
395
- const customUpdated = customUpdateFn ? await customUpdateFn.fn(actualData) : null;
396
- const updated = !customUpdateFn || customUpdateFn.executeMainFn ? await getCurrentAdapter(adapter).updateMany({
397
- model,
398
- update: actualData,
399
- where
400
- }) : customUpdated;
401
- for (const hook of hooks) {
402
- const toRun = hook[model]?.update?.after;
403
- if (toRun) await toRun(updated, ctx);
404
- }
405
- return updated;
406
- },
407
- async deleteWithHooks(where, model, customDeleteFn) {
408
- const ctx = getContext();
409
- let entityToDelete = null;
410
- try {
411
- entityToDelete = (await getCurrentAdapter(adapter).findMany({
412
- model,
413
- where,
414
- limit: 1
415
- }))[0] ?? null;
416
- } catch (error) {}
417
- if (entityToDelete) for (const hook of hooks) {
418
- const toRun = hook[model]?.delete?.before;
419
- if (toRun) {
420
- if (await toRun(entityToDelete, ctx) === false) return null;
421
- }
422
- }
423
- const customDeleted = customDeleteFn ? await customDeleteFn.fn(where) : null;
424
- const deleted = !customDeleteFn || customDeleteFn.executeMainFn ? await getCurrentAdapter(adapter).delete({
425
- model,
426
- where
427
- }) : customDeleted;
428
- if (entityToDelete) for (const hook of hooks) {
429
- const toRun = hook[model]?.delete?.after;
430
- if (toRun) await toRun(entityToDelete, ctx);
431
- }
432
- return deleted;
433
- },
434
- async deleteManyWithHooks(where, model, customDeleteFn) {
435
- const ctx = getContext();
436
- let entitiesToDelete = [];
437
- try {
438
- entitiesToDelete = await getCurrentAdapter(adapter).findMany({
439
- model,
440
- where
441
- });
442
- } catch (error) {}
443
- for (const entity of entitiesToDelete) for (const hook of hooks) {
444
- const toRun = hook[model]?.delete?.before;
445
- if (toRun) {
446
- if (await toRun(entity, ctx) === false) return null;
447
- }
448
- }
449
- const customDeleted = customDeleteFn ? await customDeleteFn.fn(where) : null;
450
- const deleted = !customDeleteFn || customDeleteFn.executeMainFn ? await getCurrentAdapter(adapter).deleteMany({
451
- model,
452
- where
453
- }) : customDeleted;
454
- for (const entity of entitiesToDelete) for (const hook of hooks) {
455
- const toRun = hook[model]?.delete?.after;
456
- if (toRun) await toRun(entity, ctx);
457
- }
458
- return deleted;
459
- }
460
- });
461
-
462
- //#endregion
463
- //#region src/db/internal-adapter.ts
464
- const createInternalAdapter = (adapter, options, context, hooks) => {
465
- const secondaryStorage = context.secondaryStorage;
466
- const sessionExpiration = context.sessionConfig.expiresIn;
467
- const { createWithHooks, updateWithHooks, updateManyWithHooks, deleteWithHooks, deleteManyWithHooks } = getWithHooks(adapter, hooks);
468
- async function refreshUserSessions(user) {
469
- if (!secondaryStorage) return;
470
- if (!user.id) return;
471
- const listRaw = await secondaryStorage.get(`active-sessions-${user.id}`);
472
- if (!listRaw) return;
473
- const now = Date.now();
474
- const validSessions = (safeJSONParse(listRaw) || []).filter((s) => s.expiresAt > now);
475
- await Promise.all(validSessions.map(async ({ token }) => {
476
- const cached = await secondaryStorage.get(token);
477
- if (!cached) return;
478
- const parsed = safeJSONParse(cached);
479
- if (!parsed) return;
480
- const sessionTTL = Math.max(Math.floor(new Date(parsed.session.expiresAt).getTime() - now) / 1e3, 0);
481
- await secondaryStorage.set(token, JSON.stringify({
482
- session: parsed.session,
483
- user
484
- }), Math.floor(sessionTTL));
485
- }));
486
- }
487
- return {
488
- createOAuthUser: async (user, account) => {
489
- return runWithTransaction(adapter, async () => {
490
- const createdUser = await createWithHooks({
491
- ...user,
492
- createdAt: user.createdAt ? new Date(user.createdAt) : /* @__PURE__ */ new Date(),
493
- updatedAt: user.updatedAt ? new Date(user.updatedAt) : /* @__PURE__ */ new Date()
494
- }, "user");
495
- return {
496
- user: createdUser,
497
- account: await createWithHooks({
498
- ...account,
499
- userId: createdUser.id,
500
- createdAt: account.createdAt ? new Date(account.createdAt) : /* @__PURE__ */ new Date(),
501
- updatedAt: account.updatedAt ? new Date(account.updatedAt) : /* @__PURE__ */ new Date()
502
- }, "account")
503
- };
504
- });
505
- },
506
- createUser: async (user) => {
507
- return await createWithHooks({
508
- ...user,
509
- createdAt: user.createdAt ? new Date(user.createdAt) : /* @__PURE__ */ new Date(),
510
- updatedAt: user.updatedAt ? new Date(user.updatedAt) : /* @__PURE__ */ new Date(),
511
- ...user.email && { email: user.email.toLowerCase() }
512
- }, "user");
513
- },
514
- createAccount: async (account) => {
515
- return await createWithHooks({
516
- ...account,
517
- createdAt: account.createdAt ? new Date(account.createdAt) : /* @__PURE__ */ new Date(),
518
- updatedAt: account.updatedAt ? new Date(account.updatedAt) : /* @__PURE__ */ new Date()
519
- }, "account");
520
- },
521
- listSessions: async (userId) => {
522
- if (secondaryStorage) {
523
- const currentList = await secondaryStorage.get(`active-sessions-${userId}`);
524
- if (!currentList) return [];
525
- const list = safeJSONParse(currentList) || [];
526
- const now = Date.now();
527
- const validSessions = list.filter((s) => s.expiresAt > now);
528
- const sessions = [];
529
- for (const session of validSessions) {
530
- const sessionStringified = await secondaryStorage.get(session.token);
531
- if (sessionStringified) {
532
- const s = safeJSONParse(sessionStringified);
533
- if (!s) return [];
534
- const parsedSession = parseSessionOutput(options, {
535
- ...s.session,
536
- expiresAt: new Date(s.session.expiresAt)
537
- });
538
- sessions.push(parsedSession);
539
- }
540
- }
541
- return sessions;
542
- }
543
- return await getCurrentAdapter(adapter).findMany({
544
- model: "session",
545
- where: [{
546
- field: "userId",
547
- value: userId
548
- }]
549
- });
550
- },
551
- listUsers: async (limit, offset, sortBy, where) => {
552
- return await getCurrentAdapter(adapter).findMany({
553
- model: "user",
554
- ...limit && { limit },
555
- ...offset && { offset },
556
- ...sortBy && { sortBy },
557
- ...where && { where }
558
- });
559
- },
560
- countTotalUsers: async (where) => {
561
- const total = await getCurrentAdapter(adapter).count({
562
- model: "user",
563
- ...where && { where }
564
- });
565
- if (typeof total === "string") return parseInt(total);
566
- return total;
567
- },
568
- deleteUser: async (userId) => {
569
- if (secondaryStorage) await secondaryStorage.delete(`active-sessions-${userId}`);
570
- if (!secondaryStorage || options.session?.storeSessionInDatabase) await deleteManyWithHooks([{
571
- field: "userId",
572
- value: userId
573
- }], "session");
574
- await deleteManyWithHooks([{
575
- field: "userId",
576
- value: userId
577
- }], "account");
578
- await deleteWithHooks([{
579
- field: "id",
580
- value: userId
581
- }], "user");
582
- },
583
- createSession: async (userId, dontRememberMe, override, overrideAll) => {
584
- const ctx = getContext();
585
- const ip = getIp(ctx.req, options);
586
- const ua = ctx.req.header("user-agent");
587
- const { id: _,...rest } = override || {};
588
- const data = {
589
- ...ip && { ipAddress: ip },
590
- ...ua && { userAgent: ua },
591
- ...rest,
592
- expiresAt: dontRememberMe ? getDate(3600 * 24, "sec") : getDate(sessionExpiration, "sec"),
593
- userId,
594
- token: generateId(32),
595
- createdAt: /* @__PURE__ */ new Date(),
596
- updatedAt: /* @__PURE__ */ new Date(),
597
- ...overrideAll ? rest : {}
598
- };
599
- return await createWithHooks(data, "session", secondaryStorage ? {
600
- fn: async (sessionData) => {
601
- /**
602
- * store the session token for the user
603
- * so we can retrieve it later for listing sessions
604
- */
605
- const currentList = await secondaryStorage.get(`active-sessions-${userId}`);
606
- let list = [];
607
- const now = Date.now();
608
- if (currentList) {
609
- list = safeJSONParse(currentList) || [];
610
- list = list.filter((session) => session.expiresAt > now);
611
- }
612
- const sorted = list.sort((a, b) => a.expiresAt - b.expiresAt);
613
- let furthestSessionExp = sorted.at(-1)?.expiresAt;
614
- sorted.push({
615
- token: data.token,
616
- expiresAt: data.expiresAt.getTime()
617
- });
618
- if (!furthestSessionExp || furthestSessionExp < data.expiresAt.getTime()) furthestSessionExp = data.expiresAt.getTime();
619
- const furthestSessionTTL = Math.max(Math.floor((furthestSessionExp - now) / 1e3), 0);
620
- if (furthestSessionTTL > 0) await secondaryStorage.set(`active-sessions-${userId}`, JSON.stringify(sorted), furthestSessionTTL);
621
- const user = await adapter.findOne({
622
- model: "user",
623
- where: [{
624
- field: "id",
625
- value: userId
626
- }]
627
- });
628
- const sessionTTL = Math.max(Math.floor((data.expiresAt.getTime() - now) / 1e3), 0);
629
- if (sessionTTL > 0) await secondaryStorage.set(data.token, JSON.stringify({
630
- session: sessionData,
631
- user
632
- }), sessionTTL);
633
- return sessionData;
634
- },
635
- executeMainFn: options.session?.storeSessionInDatabase === true
636
- } : void 0);
637
- },
638
- findSession: async (token) => {
639
- if (secondaryStorage) {
640
- const sessionStringified = await secondaryStorage.get(token);
641
- if (!sessionStringified && !options.session?.storeSessionInDatabase) return null;
642
- if (sessionStringified) {
643
- const s = safeJSONParse(sessionStringified);
644
- if (!s) return null;
645
- return {
646
- session: parseSessionOutput(options, {
647
- ...s.session,
648
- expiresAt: new Date(s.session.expiresAt),
649
- createdAt: new Date(s.session.createdAt),
650
- updatedAt: new Date(s.session.updatedAt)
651
- }),
652
- user: parseUserOutput(options, {
653
- ...s.user,
654
- createdAt: new Date(s.user.createdAt),
655
- updatedAt: new Date(s.user.updatedAt)
656
- })
657
- };
658
- }
659
- }
660
- const session = await getCurrentAdapter(adapter).findOne({
661
- model: "session",
662
- where: [{
663
- value: token,
664
- field: "token"
665
- }]
666
- });
667
- if (!session) return null;
668
- const user = await getCurrentAdapter(adapter).findOne({
669
- model: "user",
670
- where: [{
671
- value: session.userId,
672
- field: "id"
673
- }]
674
- });
675
- if (!user) return null;
676
- return {
677
- session: parseSessionOutput(options, session),
678
- user: parseUserOutput(options, user)
679
- };
680
- },
681
- findSessions: async (sessionTokens) => {
682
- if (secondaryStorage) {
683
- const sessions$1 = [];
684
- for (const sessionToken of sessionTokens) {
685
- const sessionStringified = await secondaryStorage.get(sessionToken);
686
- if (sessionStringified) {
687
- const s = safeJSONParse(sessionStringified);
688
- if (!s) return [];
689
- const session = {
690
- session: {
691
- ...s.session,
692
- expiresAt: new Date(s.session.expiresAt)
693
- },
694
- user: {
695
- ...s.user,
696
- createdAt: new Date(s.user.createdAt),
697
- updatedAt: new Date(s.user.updatedAt)
698
- }
699
- };
700
- sessions$1.push(session);
701
- }
702
- }
703
- return sessions$1;
704
- }
705
- const sessions = await getCurrentAdapter(adapter).findMany({
706
- model: "session",
707
- where: [{
708
- field: "token",
709
- value: sessionTokens,
710
- operator: "in"
711
- }]
712
- });
713
- const userIds = sessions.map((session) => {
714
- return session.userId;
715
- });
716
- if (!userIds.length) return [];
717
- const users = await getCurrentAdapter(adapter).findMany({
718
- model: "user",
719
- where: [{
720
- field: "id",
721
- value: userIds,
722
- operator: "in"
723
- }]
724
- });
725
- return sessions.map((session) => {
726
- const user = users.find((u) => u.id === session.userId);
727
- if (!user) return null;
728
- return {
729
- session,
730
- user
731
- };
732
- });
733
- },
734
- updateSession: async (sessionToken, session) => {
735
- return await updateWithHooks(session, [{
736
- field: "token",
737
- value: sessionToken
738
- }], "session", secondaryStorage ? {
739
- fn: async (data) => {
740
- const currentSession = await secondaryStorage.get(sessionToken);
741
- let updatedSession;
742
- if (currentSession) {
743
- const parsedSession = safeJSONParse(currentSession);
744
- if (!parsedSession) return;
745
- updatedSession = {
746
- ...parsedSession.session,
747
- ...data
748
- };
749
- return updatedSession;
750
- }
751
- },
752
- executeMainFn: options.session?.storeSessionInDatabase === true
753
- } : void 0);
754
- },
755
- deleteSession: async (token) => {
756
- if (secondaryStorage) {
757
- const data = await secondaryStorage.get(token);
758
- if (data) {
759
- const { session } = safeJSONParse(data) ?? {};
760
- if (!session) {
761
- context.logger.error("Session not found in secondary storage");
762
- return;
763
- }
764
- const userId = session.userId;
765
- const currentList = await secondaryStorage.get(`active-sessions-${userId}`);
766
- if (currentList) {
767
- let list = safeJSONParse(currentList) || [];
768
- const now = Date.now();
769
- const filtered = list.filter((session$1) => session$1.expiresAt > now && session$1.token !== token);
770
- const furthestSessionExp = filtered.sort((a, b) => a.expiresAt - b.expiresAt).at(-1)?.expiresAt;
771
- if (filtered.length > 0 && furthestSessionExp && furthestSessionExp > Date.now()) await secondaryStorage.set(`active-sessions-${userId}`, JSON.stringify(filtered), Math.floor((furthestSessionExp - now) / 1e3));
772
- else await secondaryStorage.delete(`active-sessions-${userId}`);
773
- } else context.logger.error("Active sessions list not found in secondary storage");
774
- }
775
- await secondaryStorage.delete(token);
776
- if (!options.session?.storeSessionInDatabase || options.session?.preserveSessionInDatabase) return;
777
- }
778
- await getCurrentAdapter(adapter).delete({
779
- model: "session",
780
- where: [{
781
- field: "token",
782
- value: token
783
- }]
784
- });
785
- },
786
- deleteAccounts: async (userId) => {
787
- await deleteManyWithHooks([{
788
- field: "userId",
789
- value: userId
790
- }], "account");
791
- },
792
- deleteAccount: async (accountId) => {
793
- await deleteWithHooks([{
794
- field: "id",
795
- value: accountId
796
- }], "account");
797
- },
798
- deleteSessions: async (userIdOrSessionTokens) => {
799
- if (secondaryStorage) {
800
- if (typeof userIdOrSessionTokens === "string") {
801
- const activeSession = await secondaryStorage.get(`active-sessions-${userIdOrSessionTokens}`);
802
- const sessions = activeSession ? safeJSONParse(activeSession) : [];
803
- if (!sessions) return;
804
- for (const session of sessions) await secondaryStorage.delete(session.token);
805
- } else for (const sessionToken of userIdOrSessionTokens) if (await secondaryStorage.get(sessionToken)) await secondaryStorage.delete(sessionToken);
806
- if (!options.session?.storeSessionInDatabase || options.session?.preserveSessionInDatabase) return;
807
- }
808
- await deleteManyWithHooks([{
809
- field: Array.isArray(userIdOrSessionTokens) ? "token" : "userId",
810
- value: userIdOrSessionTokens,
811
- ...Array.isArray(userIdOrSessionTokens) && { operator: "in" }
812
- }], "session");
813
- },
814
- findOAuthUser: async (email, accountId, providerId) => {
815
- const account = await getCurrentAdapter(adapter).findMany({
816
- model: "account",
817
- where: [{
818
- value: accountId,
819
- field: "accountId"
820
- }]
821
- }).then((accounts) => {
822
- return accounts.find((a) => a.providerId === providerId);
823
- });
824
- if (account) {
825
- const user = await getCurrentAdapter(adapter).findOne({
826
- model: "user",
827
- where: [{
828
- value: account.userId,
829
- field: "id"
830
- }]
831
- });
832
- if (user) return {
833
- user,
834
- accounts: [account]
835
- };
836
- else {
837
- const user$1 = await getCurrentAdapter(adapter).findOne({
838
- model: "user",
839
- where: [{
840
- value: email.toLowerCase(),
841
- field: "email"
842
- }]
843
- });
844
- if (user$1) return {
845
- user: user$1,
846
- accounts: [account]
847
- };
848
- return null;
849
- }
850
- } else {
851
- const user = await getCurrentAdapter(adapter).findOne({
852
- model: "user",
853
- where: [{
854
- value: email.toLowerCase(),
855
- field: "email"
856
- }]
857
- });
858
- if (user) return {
859
- user,
860
- accounts: await getCurrentAdapter(adapter).findMany({
861
- model: "account",
862
- where: [{
863
- value: user.id,
864
- field: "userId"
865
- }]
866
- }) || []
867
- };
868
- else return null;
869
- }
870
- },
871
- findUserByEmail: async (email, options$1) => {
872
- const user = await getCurrentAdapter(adapter).findOne({
873
- model: "user",
874
- where: [{
875
- value: email.toLowerCase(),
876
- field: "email"
877
- }]
878
- });
879
- if (!user) return null;
880
- if (options$1?.includeAccounts) return {
881
- user,
882
- accounts: await getCurrentAdapter(adapter).findMany({
883
- model: "account",
884
- where: [{
885
- value: user.id,
886
- field: "userId"
887
- }]
888
- })
889
- };
890
- return {
891
- user,
892
- accounts: []
893
- };
894
- },
895
- findUserById: async (userId) => {
896
- return await getCurrentAdapter(adapter).findOne({
897
- model: "user",
898
- where: [{
899
- field: "id",
900
- value: userId
901
- }]
902
- });
903
- },
904
- linkAccount: async (account) => {
905
- return await createWithHooks({
906
- ...account,
907
- createdAt: account.createdAt ? new Date(account.createdAt) : /* @__PURE__ */ new Date(),
908
- updatedAt: account.updatedAt ? new Date(account.updatedAt) : /* @__PURE__ */ new Date()
909
- }, "account");
910
- },
911
- updateUser: async (userId, data) => {
912
- const user = await updateWithHooks(data, [{
913
- field: "id",
914
- value: userId
915
- }], "user");
916
- if (user) {
917
- await refreshUserSessions(user);
918
- await refreshUserSessions(user);
919
- }
920
- return user;
921
- },
922
- updateUserByEmail: async (email, data) => {
923
- const user = await updateWithHooks(data, [{
924
- field: "email",
925
- value: email.toLowerCase()
926
- }], "user");
927
- if (user) {
928
- await refreshUserSessions(user);
929
- await refreshUserSessions(user);
930
- }
931
- return user;
932
- },
933
- updatePassword: async (userId, password) => {
934
- await updateManyWithHooks({ password }, [{
935
- field: "userId",
936
- value: userId
937
- }, {
938
- field: "providerId",
939
- value: "credential"
940
- }], "account");
941
- },
942
- findAccounts: async (userId) => {
943
- return await getCurrentAdapter(adapter).findMany({
944
- model: "account",
945
- where: [{
946
- field: "userId",
947
- value: userId
948
- }]
949
- });
950
- },
951
- findAccount: async (accountId) => {
952
- return await getCurrentAdapter(adapter).findOne({
953
- model: "account",
954
- where: [{
955
- field: "accountId",
956
- value: accountId
957
- }]
958
- });
959
- },
960
- findAccountByProviderId: async (accountId, providerId) => {
961
- return await getCurrentAdapter(adapter).findOne({
962
- model: "account",
963
- where: [{
964
- field: "accountId",
965
- value: accountId
966
- }, {
967
- field: "providerId",
968
- value: providerId
969
- }]
970
- });
971
- },
972
- findAccountByUserId: async (userId) => {
973
- return await getCurrentAdapter(adapter).findMany({
974
- model: "account",
975
- where: [{
976
- field: "userId",
977
- value: userId
978
- }]
979
- });
980
- },
981
- updateAccount: async (id, data) => {
982
- return await updateWithHooks(data, [{
983
- field: "id",
984
- value: id
985
- }], "account");
986
- },
987
- createVerificationValue: async (data) => {
988
- return await createWithHooks({
989
- createdAt: /* @__PURE__ */ new Date(),
990
- updatedAt: /* @__PURE__ */ new Date(),
991
- ...data
992
- }, "verification");
993
- },
994
- findVerificationValue: async (identifier) => {
995
- const verification = await getCurrentAdapter(adapter).findMany({
996
- model: "verification",
997
- where: [{
998
- field: "identifier",
999
- value: identifier
1000
- }],
1001
- sortBy: {
1002
- field: "createdAt",
1003
- direction: "desc"
1004
- },
1005
- limit: 1
1006
- });
1007
- if (!options.verification?.disableCleanup) await getCurrentAdapter(adapter).deleteMany({
1008
- model: "verification",
1009
- where: [{
1010
- field: "expiresAt",
1011
- value: /* @__PURE__ */ new Date(),
1012
- operator: "lt"
1013
- }]
1014
- });
1015
- return verification[0] ?? null;
1016
- },
1017
- deleteVerificationValue: async (id) => {
1018
- await getCurrentAdapter(adapter).delete({
1019
- model: "verification",
1020
- where: [{
1021
- field: "id",
1022
- value: id
1023
- }]
1024
- });
1025
- },
1026
- deleteVerificationByIdentifier: async (identifier) => {
1027
- await getCurrentAdapter(adapter).delete({
1028
- model: "verification",
1029
- where: [{
1030
- field: "identifier",
1031
- value: identifier
1032
- }]
1033
- });
1034
- },
1035
- updateVerificationValue: async (id, data) => {
1036
- return await updateWithHooks(data, [{
1037
- field: "id",
1038
- value: id
1039
- }], "verification");
1040
- }
1041
- };
1042
- };
1043
-
1044
- //#endregion
1045
- //#region src/db/to-zod.ts
1046
- function toZodSchema({ fields, isClientSide }) {
1047
- const zodFields = Object.keys(fields).reduce((acc, key) => {
1048
- const field = fields[key];
1049
- if (!field) return acc;
1050
- if (isClientSide && field.input === false) return acc;
1051
- let schema;
1052
- if (field.type === "json") schema = z$1.json ? z$1.json() : z$1.any();
1053
- else if (field.type === "string[]" || field.type === "number[]") schema = z$1.array(field.type === "string[]" ? z$1.string() : z$1.number());
1054
- else if (Array.isArray(field.type)) schema = z$1.any();
1055
- else schema = z$1[field.type]();
1056
- if (field?.required === false) schema = schema.optional();
1057
- if (field?.returned === false) return acc;
1058
- return {
1059
- ...acc,
1060
- [key]: schema
1061
- };
1062
- }, {});
1063
- return z$1.object(zodFields);
1064
- }
1065
-
1066
- //#endregion
1067
- //#region src/db/utils.ts
1068
- function patchAdapterTransaction(adapter) {
1069
- if (!adapter.transaction) {
1070
- logger.warn("Adapter does not correctly implement transaction function, patching it automatically. Please update your adapter implementation.");
1071
- adapter.transaction = (cb) => {
1072
- const res = cb(adapter);
1073
- return isPromise(res) ? res : Promise.resolve(res);
1074
- };
1075
- }
1076
- return adapter;
1077
- }
1078
- function getAdapter(options) {
1079
- if (!options.database) {
1080
- const tables = getAuthTables(options);
1081
- const memoryDB = Object.keys(tables).reduce((acc, key) => {
1082
- acc[key] = [];
1083
- return acc;
1084
- }, {});
1085
- if (options.logger && options.logger.log) options.logger.log("debug", "No database configuration provided. Using memory adapter in development");
1086
- else logger.debug("No database configuration provided. Using memory adapter in development");
1087
- return patchAdapterTransaction(memoryAdapter(memoryDB)(options));
1088
- }
1089
- if (typeof options.database === "function") return patchAdapterTransaction(options.database(options));
1090
- const adapter = createKyselyAdapter(options);
1091
- const checkKysely = () => {
1092
- if (!adapter.kysely) throw new FaireAuthError("Failed to initialize database adapter");
1093
- return adapter.kysely;
1094
- };
1095
- return patchAdapterTransaction(kyselyAdapter("initialize" in adapter ? adapter.initialize().then(checkKysely) : checkKysely(), {
1096
- type: adapter.databaseType ?? "sqlite",
1097
- debugLogs: "debugLogs" in options.database ? options.database.debugLogs : false,
1098
- transaction: adapter.transaction
1099
- })(options));
1100
- }
1101
- function convertToDB(fields, values) {
1102
- let result = values.id ? { id: values.id } : {};
1103
- for (const key in fields) {
1104
- const field = fields[key];
1105
- const value = values[key];
1106
- if (value === void 0) continue;
1107
- result[field.fieldName || key] = value;
1108
- }
1109
- return result;
1110
- }
1111
- function convertFromDB(fields, values) {
1112
- if (!values) return null;
1113
- let result = { id: values.id };
1114
- for (const [key, value] of Object.entries(fields)) result[key] = values[value.fieldName || key];
1115
- return result;
1116
- }
1117
-
1118
- //#endregion
1119
- export { createInternalAdapter as a, matchType as c, toZodSchema as i, getSchema as l, convertToDB as n, getWithHooks as o, getAdapter as r, getMigrations as s, convertFromDB as t, createFieldAttribute as u };