@better-auth/memory-adapter 1.5.0-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,16 @@
1
+
2
+ > @better-auth/memory-adapter@1.5.0-beta.10 build /home/runner/work/better-auth/better-auth/packages/memory-adapter
3
+ > tsdown
4
+
5
+ ℹ tsdown v0.20.1 powered by rolldown v1.0.0-rc.1
6
+ ℹ config file: /home/runner/work/better-auth/better-auth/packages/memory-adapter/tsdown.config.ts
7
+ ℹ entry: src/index.ts
8
+ ℹ tsconfig: tsconfig.json
9
+ ℹ Build start
10
+ [PLUGIN_TIMINGS] Warning: Your build spent significant time in plugin `rolldown-plugin-dts:generate`. See https://rolldown.rs/options/checks#plugintimings for more details.
11
+ ℹ dist/index.mjs  8.08 kB │ gzip: 2.21 kB
12
+ ℹ dist/index.mjs.map 17.59 kB │ gzip: 4.62 kB
13
+ ℹ dist/index.d.mts  0.67 kB │ gzip: 0.32 kB
14
+ ℹ 3 files, total: 26.34 kB
15
+
16
+ ✔ Build complete in 9115ms
package/LICENSE.md ADDED
@@ -0,0 +1,20 @@
1
+ The MIT License (MIT)
2
+ Copyright (c) 2024 - present, Bereket Engida
3
+
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
5
+ this software and associated documentation files (the “Software”), to deal in
6
+ the Software without restriction, including without limitation the rights to
7
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
8
+ the Software, and to permit persons to whom the Software is furnished to do so,
9
+ subject to the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be included in all
12
+ copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
16
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18
+ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
19
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
20
+ DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,15 @@
1
+ import * as _better_auth_core_db_adapter0 from "@better-auth/core/db/adapter";
2
+ import { DBAdapterDebugLogOption } from "@better-auth/core/db/adapter";
3
+ import { BetterAuthOptions } from "@better-auth/core";
4
+
5
+ //#region src/memory-adapter.d.ts
6
+ interface MemoryDB {
7
+ [key: string]: any[];
8
+ }
9
+ interface MemoryAdapterConfig {
10
+ debugLogs?: DBAdapterDebugLogOption | undefined;
11
+ }
12
+ declare const memoryAdapter: (db: MemoryDB, config?: MemoryAdapterConfig | undefined) => (options: BetterAuthOptions) => _better_auth_core_db_adapter0.DBAdapter<BetterAuthOptions>;
13
+ //#endregion
14
+ export { type MemoryAdapterConfig, type MemoryDB, memoryAdapter };
15
+ //# sourceMappingURL=index.d.mts.map
package/dist/index.mjs ADDED
@@ -0,0 +1,214 @@
1
+ import { createAdapterFactory } from "@better-auth/core/db/adapter";
2
+ import { logger } from "@better-auth/core/env";
3
+
4
+ //#region src/memory-adapter.ts
5
+ const memoryAdapter = (db, config) => {
6
+ let lazyOptions = null;
7
+ const adapterCreator = createAdapterFactory({
8
+ config: {
9
+ adapterId: "memory",
10
+ adapterName: "Memory Adapter",
11
+ usePlural: false,
12
+ debugLogs: config?.debugLogs || false,
13
+ supportsArrays: true,
14
+ customTransformInput(props) {
15
+ if (props.options.advanced?.database?.generateId === "serial" && props.field === "id" && props.action === "create") return db[props.model].length + 1;
16
+ return props.data;
17
+ },
18
+ transaction: async (cb) => {
19
+ const clone = structuredClone(db);
20
+ try {
21
+ return await cb(adapterCreator(lazyOptions));
22
+ } catch (error) {
23
+ Object.keys(db).forEach((key) => {
24
+ db[key] = clone[key];
25
+ });
26
+ throw error;
27
+ }
28
+ }
29
+ },
30
+ adapter: ({ getFieldName, options, getModelName }) => {
31
+ const applySortToRecords = (records, sortBy, model) => {
32
+ if (!sortBy) return records;
33
+ return records.sort((a, b) => {
34
+ const field = getFieldName({
35
+ model,
36
+ field: sortBy.field
37
+ });
38
+ const aValue = a[field];
39
+ const bValue = b[field];
40
+ let comparison = 0;
41
+ if (aValue == null && bValue == null) comparison = 0;
42
+ else if (aValue == null) comparison = -1;
43
+ else if (bValue == null) comparison = 1;
44
+ else if (typeof aValue === "string" && typeof bValue === "string") comparison = aValue.localeCompare(bValue);
45
+ else if (aValue instanceof Date && bValue instanceof Date) comparison = aValue.getTime() - bValue.getTime();
46
+ else if (typeof aValue === "number" && typeof bValue === "number") comparison = aValue - bValue;
47
+ else if (typeof aValue === "boolean" && typeof bValue === "boolean") comparison = aValue === bValue ? 0 : aValue ? 1 : -1;
48
+ else comparison = String(aValue).localeCompare(String(bValue));
49
+ return sortBy.direction === "asc" ? comparison : -comparison;
50
+ });
51
+ };
52
+ function convertWhereClause(where, model, join) {
53
+ const execute = (where, model) => {
54
+ const table = db[model];
55
+ if (!table) {
56
+ logger.error(`[MemoryAdapter] Model ${model} not found in the DB`, Object.keys(db));
57
+ throw new Error(`Model ${model} not found`);
58
+ }
59
+ const evalClause = (record, clause) => {
60
+ const { field, value, operator } = clause;
61
+ switch (operator) {
62
+ case "in":
63
+ if (!Array.isArray(value)) throw new Error("Value must be an array");
64
+ return value.includes(record[field]);
65
+ case "not_in":
66
+ if (!Array.isArray(value)) throw new Error("Value must be an array");
67
+ return !value.includes(record[field]);
68
+ case "contains": return record[field].includes(value);
69
+ case "starts_with": return record[field].startsWith(value);
70
+ case "ends_with": return record[field].endsWith(value);
71
+ case "ne": return record[field] !== value;
72
+ case "gt": return value != null && Boolean(record[field] > value);
73
+ case "gte": return value != null && Boolean(record[field] >= value);
74
+ case "lt": return value != null && Boolean(record[field] < value);
75
+ case "lte": return value != null && Boolean(record[field] <= value);
76
+ default: return record[field] === value;
77
+ }
78
+ };
79
+ return table.filter((record) => {
80
+ if (!where.length || where.length === 0) return true;
81
+ let result = evalClause(record, where[0]);
82
+ for (const clause of where) {
83
+ const clauseResult = evalClause(record, clause);
84
+ if (clause.connector === "OR") result = result || clauseResult;
85
+ else result = result && clauseResult;
86
+ }
87
+ return result;
88
+ });
89
+ };
90
+ if (!join) return execute(where, model);
91
+ const baseRecords = execute(where, model);
92
+ const grouped = /* @__PURE__ */ new Map();
93
+ const seenIds = /* @__PURE__ */ new Map();
94
+ for (const baseRecord of baseRecords) {
95
+ const baseId = String(baseRecord.id);
96
+ if (!grouped.has(baseId)) {
97
+ const nested = { ...baseRecord };
98
+ for (const [joinModel, joinAttr] of Object.entries(join)) {
99
+ const joinModelName = getModelName(joinModel);
100
+ if (joinAttr.relation === "one-to-one") nested[joinModelName] = null;
101
+ else {
102
+ nested[joinModelName] = [];
103
+ seenIds.set(`${baseId}-${joinModel}`, /* @__PURE__ */ new Set());
104
+ }
105
+ }
106
+ grouped.set(baseId, nested);
107
+ }
108
+ const nestedEntry = grouped.get(baseId);
109
+ for (const [joinModel, joinAttr] of Object.entries(join)) {
110
+ const joinModelName = getModelName(joinModel);
111
+ const joinTable = db[joinModelName];
112
+ if (!joinTable) {
113
+ logger.error(`[MemoryAdapter] JoinOption model ${joinModelName} not found in the DB`, Object.keys(db));
114
+ throw new Error(`JoinOption model ${joinModelName} not found`);
115
+ }
116
+ const matchingRecords = joinTable.filter((joinRecord) => joinRecord[joinAttr.on.to] === baseRecord[joinAttr.on.from]);
117
+ if (joinAttr.relation === "one-to-one") nestedEntry[joinModelName] = matchingRecords[0] || null;
118
+ else {
119
+ const seenSet = seenIds.get(`${baseId}-${joinModel}`);
120
+ const limit = joinAttr.limit ?? 100;
121
+ let count = 0;
122
+ for (const matchingRecord of matchingRecords) {
123
+ if (count >= limit) break;
124
+ if (!seenSet.has(matchingRecord.id)) {
125
+ nestedEntry[joinModelName].push(matchingRecord);
126
+ seenSet.add(matchingRecord.id);
127
+ count++;
128
+ }
129
+ }
130
+ }
131
+ }
132
+ }
133
+ return Array.from(grouped.values());
134
+ }
135
+ return {
136
+ create: async ({ model, data }) => {
137
+ if (options.advanced?.database?.generateId === "serial") data.id = db[getModelName(model)].length + 1;
138
+ if (!db[model]) db[model] = [];
139
+ db[model].push(data);
140
+ return data;
141
+ },
142
+ findOne: async ({ model, where, join }) => {
143
+ const res = convertWhereClause(where, model, join);
144
+ if (join) {
145
+ const resArray = res;
146
+ if (!resArray.length) return null;
147
+ return resArray[0];
148
+ }
149
+ return res[0] || null;
150
+ },
151
+ findMany: async ({ model, where, sortBy, limit, offset, join }) => {
152
+ const res = convertWhereClause(where || [], model, join);
153
+ if (join) {
154
+ const resArray = res;
155
+ if (!resArray.length) return [];
156
+ applySortToRecords(resArray, sortBy, model);
157
+ let paginatedRecords = resArray;
158
+ if (offset !== void 0) paginatedRecords = paginatedRecords.slice(offset);
159
+ if (limit !== void 0) paginatedRecords = paginatedRecords.slice(0, limit);
160
+ return paginatedRecords;
161
+ }
162
+ let table = applySortToRecords(res, sortBy, model);
163
+ if (offset !== void 0) table = table.slice(offset);
164
+ if (limit !== void 0) table = table.slice(0, limit);
165
+ return table || [];
166
+ },
167
+ count: async ({ model, where }) => {
168
+ if (where) return convertWhereClause(where, model).length;
169
+ return db[model].length;
170
+ },
171
+ update: async ({ model, where, update }) => {
172
+ const res = convertWhereClause(where, model);
173
+ res.forEach((record) => {
174
+ Object.assign(record, update);
175
+ });
176
+ return res[0] || null;
177
+ },
178
+ delete: async ({ model, where }) => {
179
+ const table = db[model];
180
+ const res = convertWhereClause(where, model);
181
+ db[model] = table.filter((record) => !res.includes(record));
182
+ },
183
+ deleteMany: async ({ model, where }) => {
184
+ const table = db[model];
185
+ const res = convertWhereClause(where, model);
186
+ let count = 0;
187
+ db[model] = table.filter((record) => {
188
+ if (res.includes(record)) {
189
+ count++;
190
+ return false;
191
+ }
192
+ return !res.includes(record);
193
+ });
194
+ return count;
195
+ },
196
+ updateMany({ model, where, update }) {
197
+ const res = convertWhereClause(where, model);
198
+ res.forEach((record) => {
199
+ Object.assign(record, update);
200
+ });
201
+ return res[0] || null;
202
+ }
203
+ };
204
+ }
205
+ });
206
+ return (options) => {
207
+ lazyOptions = options;
208
+ return adapterCreator(options);
209
+ };
210
+ };
211
+
212
+ //#endregion
213
+ export { memoryAdapter };
214
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/memory-adapter.ts"],"sourcesContent":["import type { BetterAuthOptions } from \"@better-auth/core\";\nimport type {\n\tCleanedWhere,\n\tDBAdapterDebugLogOption,\n\tJoinConfig,\n} from \"@better-auth/core/db/adapter\";\nimport { createAdapterFactory } from \"@better-auth/core/db/adapter\";\nimport { logger } from \"@better-auth/core/env\";\n\nexport interface MemoryDB {\n\t[key: string]: any[];\n}\n\nexport interface MemoryAdapterConfig {\n\tdebugLogs?: DBAdapterDebugLogOption | undefined;\n}\n\nexport const memoryAdapter = (\n\tdb: MemoryDB,\n\tconfig?: MemoryAdapterConfig | undefined,\n) => {\n\tlet lazyOptions: BetterAuthOptions | null = null;\n\tconst adapterCreator = createAdapterFactory({\n\t\tconfig: {\n\t\t\tadapterId: \"memory\",\n\t\t\tadapterName: \"Memory Adapter\",\n\t\t\tusePlural: false,\n\t\t\tdebugLogs: config?.debugLogs || false,\n\t\t\tsupportsArrays: true,\n\t\t\tcustomTransformInput(props) {\n\t\t\t\tconst useNumberId =\n\t\t\t\t\tprops.options.advanced?.database?.generateId === \"serial\";\n\t\t\t\tif (useNumberId && props.field === \"id\" && props.action === \"create\") {\n\t\t\t\t\treturn db[props.model]!.length + 1;\n\t\t\t\t}\n\t\t\t\treturn props.data;\n\t\t\t},\n\t\t\ttransaction: async (cb) => {\n\t\t\t\tconst clone = structuredClone(db);\n\t\t\t\ttry {\n\t\t\t\t\tconst r = await cb(adapterCreator(lazyOptions!));\n\t\t\t\t\treturn r;\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// Rollback changes\n\t\t\t\t\tObject.keys(db).forEach((key) => {\n\t\t\t\t\t\tdb[key] = clone[key]!;\n\t\t\t\t\t});\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\tadapter: ({ getFieldName, options, getModelName }) => {\n\t\t\tconst applySortToRecords = (\n\t\t\t\trecords: any[],\n\t\t\t\tsortBy: { field: string; direction: \"asc\" | \"desc\" } | undefined,\n\t\t\t\tmodel: string,\n\t\t\t) => {\n\t\t\t\tif (!sortBy) return records;\n\t\t\t\treturn records.sort((a: any, b: any) => {\n\t\t\t\t\tconst field = getFieldName({ model, field: sortBy.field });\n\t\t\t\t\tconst aValue = a[field];\n\t\t\t\t\tconst bValue = b[field];\n\n\t\t\t\t\tlet comparison = 0;\n\n\t\t\t\t\t// Handle null/undefined values\n\t\t\t\t\tif (aValue == null && bValue == null) {\n\t\t\t\t\t\tcomparison = 0;\n\t\t\t\t\t} else if (aValue == null) {\n\t\t\t\t\t\tcomparison = -1;\n\t\t\t\t\t} else if (bValue == null) {\n\t\t\t\t\t\tcomparison = 1;\n\t\t\t\t\t}\n\t\t\t\t\t// Handle string comparison\n\t\t\t\t\telse if (typeof aValue === \"string\" && typeof bValue === \"string\") {\n\t\t\t\t\t\tcomparison = aValue.localeCompare(bValue);\n\t\t\t\t\t}\n\t\t\t\t\t// Handle date comparison\n\t\t\t\t\telse if (aValue instanceof Date && bValue instanceof Date) {\n\t\t\t\t\t\tcomparison = aValue.getTime() - bValue.getTime();\n\t\t\t\t\t}\n\t\t\t\t\t// Handle numeric comparison\n\t\t\t\t\telse if (typeof aValue === \"number\" && typeof bValue === \"number\") {\n\t\t\t\t\t\tcomparison = aValue - bValue;\n\t\t\t\t\t}\n\t\t\t\t\t// Handle boolean comparison\n\t\t\t\t\telse if (typeof aValue === \"boolean\" && typeof bValue === \"boolean\") {\n\t\t\t\t\t\tcomparison = aValue === bValue ? 0 : aValue ? 1 : -1;\n\t\t\t\t\t}\n\t\t\t\t\t// Fallback to string comparison\n\t\t\t\t\telse {\n\t\t\t\t\t\tcomparison = String(aValue).localeCompare(String(bValue));\n\t\t\t\t\t}\n\n\t\t\t\t\treturn sortBy.direction === \"asc\" ? comparison : -comparison;\n\t\t\t\t});\n\t\t\t};\n\n\t\t\tfunction convertWhereClause(\n\t\t\t\twhere: CleanedWhere[],\n\t\t\t\tmodel: string,\n\t\t\t\tjoin?: JoinConfig,\n\t\t\t): any[] {\n\t\t\t\tconst execute = (where: CleanedWhere[], model: string) => {\n\t\t\t\t\tconst table = db[model];\n\t\t\t\t\tif (!table) {\n\t\t\t\t\t\tlogger.error(\n\t\t\t\t\t\t\t`[MemoryAdapter] Model ${model} not found in the DB`,\n\t\t\t\t\t\t\tObject.keys(db),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tthrow new Error(`Model ${model} not found`);\n\t\t\t\t\t}\n\n\t\t\t\t\tconst evalClause = (record: any, clause: CleanedWhere): boolean => {\n\t\t\t\t\t\tconst { field, value, operator } = clause;\n\t\t\t\t\t\tswitch (operator) {\n\t\t\t\t\t\t\tcase \"in\":\n\t\t\t\t\t\t\t\tif (!Array.isArray(value)) {\n\t\t\t\t\t\t\t\t\tthrow new Error(\"Value must be an array\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\t\t\t\treturn value.includes(record[field]);\n\t\t\t\t\t\t\tcase \"not_in\":\n\t\t\t\t\t\t\t\tif (!Array.isArray(value)) {\n\t\t\t\t\t\t\t\t\tthrow new Error(\"Value must be an array\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\t\t\t\treturn !value.includes(record[field]);\n\t\t\t\t\t\t\tcase \"contains\":\n\t\t\t\t\t\t\t\treturn record[field].includes(value);\n\t\t\t\t\t\t\tcase \"starts_with\":\n\t\t\t\t\t\t\t\treturn record[field].startsWith(value);\n\t\t\t\t\t\t\tcase \"ends_with\":\n\t\t\t\t\t\t\t\treturn record[field].endsWith(value);\n\t\t\t\t\t\t\tcase \"ne\":\n\t\t\t\t\t\t\t\treturn record[field] !== value;\n\t\t\t\t\t\t\tcase \"gt\":\n\t\t\t\t\t\t\t\treturn value != null && Boolean(record[field] > value);\n\t\t\t\t\t\t\tcase \"gte\":\n\t\t\t\t\t\t\t\treturn value != null && Boolean(record[field] >= value);\n\t\t\t\t\t\t\tcase \"lt\":\n\t\t\t\t\t\t\t\treturn value != null && Boolean(record[field] < value);\n\t\t\t\t\t\t\tcase \"lte\":\n\t\t\t\t\t\t\t\treturn value != null && Boolean(record[field] <= value);\n\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\treturn record[field] === value;\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\n\t\t\t\t\treturn table.filter((record: any) => {\n\t\t\t\t\t\tif (!where.length || where.length === 0) {\n\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tlet result = evalClause(record, where[0]!);\n\t\t\t\t\t\tfor (const clause of where) {\n\t\t\t\t\t\t\tconst clauseResult = evalClause(record, clause);\n\n\t\t\t\t\t\t\tif (clause.connector === \"OR\") {\n\t\t\t\t\t\t\t\tresult = result || clauseResult;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tresult = result && clauseResult;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn result;\n\t\t\t\t\t});\n\t\t\t\t};\n\n\t\t\t\tif (!join) return execute(where, model);\n\n\t\t\t\tconst baseRecords = execute(where, model);\n\n\t\t\t\t// Group results by base model and nest joined data as arrays\n\t\t\t\tconst grouped = new Map<string, any>();\n\t\t\t\t// Track seen IDs per joined model for O(1) deduplication\n\t\t\t\tconst seenIds = new Map<string, Set<string>>();\n\n\t\t\t\tfor (const baseRecord of baseRecords) {\n\t\t\t\t\tconst baseId = String(baseRecord.id);\n\n\t\t\t\t\tif (!grouped.has(baseId)) {\n\t\t\t\t\t\tconst nested: Record<string, any> = { ...baseRecord };\n\n\t\t\t\t\t\t// Initialize joined data structures based on isUnique\n\t\t\t\t\t\tfor (const [joinModel, joinAttr] of Object.entries(join)) {\n\t\t\t\t\t\t\tconst joinModelName = getModelName(joinModel);\n\t\t\t\t\t\t\tif (joinAttr.relation === \"one-to-one\") {\n\t\t\t\t\t\t\t\tnested[joinModelName] = null;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tnested[joinModelName] = [];\n\t\t\t\t\t\t\t\tseenIds.set(`${baseId}-${joinModel}`, new Set());\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tgrouped.set(baseId, nested);\n\t\t\t\t\t}\n\n\t\t\t\t\tconst nestedEntry = grouped.get(baseId)!;\n\n\t\t\t\t\t// Add joined data\n\t\t\t\t\tfor (const [joinModel, joinAttr] of Object.entries(join)) {\n\t\t\t\t\t\tconst joinModelName = getModelName(joinModel);\n\t\t\t\t\t\tconst joinTable = db[joinModelName];\n\t\t\t\t\t\tif (!joinTable) {\n\t\t\t\t\t\t\tlogger.error(\n\t\t\t\t\t\t\t\t`[MemoryAdapter] JoinOption model ${joinModelName} not found in the DB`,\n\t\t\t\t\t\t\t\tObject.keys(db),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tthrow new Error(`JoinOption model ${joinModelName} not found`);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst matchingRecords = joinTable.filter(\n\t\t\t\t\t\t\t(joinRecord: any) =>\n\t\t\t\t\t\t\t\tjoinRecord[joinAttr.on.to] === baseRecord[joinAttr.on.from],\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tif (joinAttr.relation === \"one-to-one\") {\n\t\t\t\t\t\t\t// For unique relationships, store a single object (or null)\n\t\t\t\t\t\t\tnestedEntry[joinModelName] = matchingRecords[0] || null;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// For non-unique relationships, store array with limit\n\t\t\t\t\t\t\tconst seenSet = seenIds.get(`${baseId}-${joinModel}`)!;\n\t\t\t\t\t\t\tconst limit = joinAttr.limit ?? 100;\n\t\t\t\t\t\t\tlet count = 0;\n\n\t\t\t\t\t\t\tfor (const matchingRecord of matchingRecords) {\n\t\t\t\t\t\t\t\tif (count >= limit) break;\n\t\t\t\t\t\t\t\tif (!seenSet.has(matchingRecord.id)) {\n\t\t\t\t\t\t\t\t\tnestedEntry[joinModelName].push(matchingRecord);\n\t\t\t\t\t\t\t\t\tseenSet.add(matchingRecord.id);\n\t\t\t\t\t\t\t\t\tcount++;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn Array.from(grouped.values());\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tcreate: async ({ model, data }) => {\n\t\t\t\t\tconst useNumberId =\n\t\t\t\t\t\toptions.advanced?.database?.generateId === \"serial\";\n\t\t\t\t\tif (useNumberId) {\n\t\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\t\tdata.id = db[getModelName(model)]!.length + 1;\n\t\t\t\t\t}\n\t\t\t\t\tif (!db[model]) {\n\t\t\t\t\t\tdb[model] = [];\n\t\t\t\t\t}\n\t\t\t\t\tdb[model]!.push(data);\n\t\t\t\t\treturn data;\n\t\t\t\t},\n\t\t\t\tfindOne: async ({ model, where, join }) => {\n\t\t\t\t\tconst res = convertWhereClause(where, model, join);\n\t\t\t\t\tif (join) {\n\t\t\t\t\t\t// When join is present, res is an array of nested objects\n\t\t\t\t\t\tconst resArray = res as any[];\n\t\t\t\t\t\tif (!resArray.length) {\n\t\t\t\t\t\t\treturn null;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Return the first nested object\n\t\t\t\t\t\treturn resArray[0];\n\t\t\t\t\t}\n\t\t\t\t\t// Without join, res is an array\n\t\t\t\t\tconst resArray = res as any[];\n\t\t\t\t\tconst record = resArray[0] || null;\n\t\t\t\t\treturn record;\n\t\t\t\t},\n\t\t\t\tfindMany: async ({ model, where, sortBy, limit, offset, join }) => {\n\t\t\t\t\tconst res = convertWhereClause(where || [], model, join);\n\n\t\t\t\t\tif (join) {\n\t\t\t\t\t\t// When join is present, res is an array of nested objects\n\t\t\t\t\t\tconst resArray = res as any[];\n\t\t\t\t\t\tif (!resArray.length) {\n\t\t\t\t\t\t\treturn [];\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Apply sorting to nested objects\n\t\t\t\t\t\tapplySortToRecords(resArray, sortBy, model);\n\n\t\t\t\t\t\t// Apply offset and limit\n\t\t\t\t\t\tlet paginatedRecords = resArray;\n\t\t\t\t\t\tif (offset !== undefined) {\n\t\t\t\t\t\t\tpaginatedRecords = paginatedRecords.slice(offset);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (limit !== undefined) {\n\t\t\t\t\t\t\tpaginatedRecords = paginatedRecords.slice(0, limit);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn paginatedRecords;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Without join - original logic\n\t\t\t\t\tconst resArray = res as any[];\n\t\t\t\t\tlet table = applySortToRecords(resArray, sortBy, model);\n\t\t\t\t\tif (offset !== undefined) {\n\t\t\t\t\t\ttable = table!.slice(offset);\n\t\t\t\t\t}\n\t\t\t\t\tif (limit !== undefined) {\n\t\t\t\t\t\ttable = table!.slice(0, limit);\n\t\t\t\t\t}\n\t\t\t\t\treturn table || [];\n\t\t\t\t},\n\t\t\t\tcount: async ({ model, where }) => {\n\t\t\t\t\tif (where) {\n\t\t\t\t\t\tconst filteredRecords = convertWhereClause(where, model);\n\t\t\t\t\t\treturn filteredRecords.length;\n\t\t\t\t\t}\n\t\t\t\t\treturn db[model]!.length;\n\t\t\t\t},\n\t\t\t\tupdate: async ({ model, where, update }) => {\n\t\t\t\t\tconst res = convertWhereClause(where, model);\n\t\t\t\t\tres.forEach((record) => {\n\t\t\t\t\t\tObject.assign(record, update);\n\t\t\t\t\t});\n\t\t\t\t\treturn res[0] || null;\n\t\t\t\t},\n\t\t\t\tdelete: async ({ model, where }) => {\n\t\t\t\t\tconst table = db[model]!;\n\t\t\t\t\tconst res = convertWhereClause(where, model);\n\t\t\t\t\tdb[model] = table.filter((record) => !res.includes(record));\n\t\t\t\t},\n\t\t\t\tdeleteMany: async ({ model, where }) => {\n\t\t\t\t\tconst table = db[model]!;\n\t\t\t\t\tconst res = convertWhereClause(where, model);\n\t\t\t\t\tlet count = 0;\n\t\t\t\t\tdb[model] = table.filter((record) => {\n\t\t\t\t\t\tif (res.includes(record)) {\n\t\t\t\t\t\t\tcount++;\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn !res.includes(record);\n\t\t\t\t\t});\n\t\t\t\t\treturn count;\n\t\t\t\t},\n\t\t\t\tupdateMany({ model, where, update }) {\n\t\t\t\t\tconst res = convertWhereClause(where, model);\n\t\t\t\t\tres.forEach((record) => {\n\t\t\t\t\t\tObject.assign(record, update);\n\t\t\t\t\t});\n\t\t\t\t\treturn res[0] || null;\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t});\n\treturn (options: BetterAuthOptions) => {\n\t\tlazyOptions = options;\n\t\treturn adapterCreator(options);\n\t};\n};\n"],"mappings":";;;;AAiBA,MAAa,iBACZ,IACA,WACI;CACJ,IAAI,cAAwC;CAC5C,MAAM,iBAAiB,qBAAqB;EAC3C,QAAQ;GACP,WAAW;GACX,aAAa;GACb,WAAW;GACX,WAAW,QAAQ,aAAa;GAChC,gBAAgB;GAChB,qBAAqB,OAAO;AAG3B,QADC,MAAM,QAAQ,UAAU,UAAU,eAAe,YAC/B,MAAM,UAAU,QAAQ,MAAM,WAAW,SAC3D,QAAO,GAAG,MAAM,OAAQ,SAAS;AAElC,WAAO,MAAM;;GAEd,aAAa,OAAO,OAAO;IAC1B,MAAM,QAAQ,gBAAgB,GAAG;AACjC,QAAI;AAEH,YADU,MAAM,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AW,CAAC,IAAI,SAAS,OAAO,CAAC;;IAE5D,YAAY,OAAO,EAAE,OAAO,YAAY;KACvC,MAAM,QAAQ,GAAG;KACjB,MAAM,MAAM,mBAAmB,OAAO,MAAM;KAC5C,IAAI,QAAQ;AACZ,QAAG,SAAS,MAAM,QAAQ,WAAW;AACpC,UAAI,IAAI,SAAS,OAAO,EAAE;AACzB;AACA,cAAO;;AAER,aAAO,CAAC,IAAI,SAAS,OAAO;OAC3B;AACF,YAAO;;IAER,WAAW,EAAE,OAAO,OAAO,UAAU;KACpC,MAAM,MAAM,mBAAmB,OAAO,MAAM;AAC5C,SAAI,SAAS,WAAW;AACvB,aAAO,OAAO,QAAQ,OAAO;OAC5B;AACF,YAAO,IAAI,MAAM;;IAElB;;EAEF,CAAC;AACF,SAAQ,YAA+B;AACtC,gBAAc;AACd,SAAO,eAAe,QAAQ"}
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "@better-auth/memory-adapter",
3
+ "version": "1.5.0-beta.10",
4
+ "description": "Memory adapter for Better Auth",
5
+ "type": "module",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/better-auth/better-auth.git",
9
+ "directory": "packages/memory-adapter"
10
+ },
11
+ "main": "./dist/index.mjs",
12
+ "module": "./dist/index.mjs",
13
+ "types": "./dist/index.d.mts",
14
+ "exports": {
15
+ ".": {
16
+ "dev-source": "./src/index.ts",
17
+ "types": "./dist/index.d.mts",
18
+ "default": "./dist/index.mjs"
19
+ }
20
+ },
21
+ "peerDependencies": {
22
+ "@better-auth/utils": "^0.3.0",
23
+ "@better-auth/core": "1.5.0-beta.10"
24
+ },
25
+ "devDependencies": {
26
+ "@better-auth/utils": "^0.3.1",
27
+ "tsdown": "^0.20.1",
28
+ "typescript": "^5.9.3",
29
+ "@better-auth/core": "1.5.0-beta.10"
30
+ },
31
+ "scripts": {
32
+ "build": "tsdown",
33
+ "dev": "tsdown --watch",
34
+ "test": "vitest",
35
+ "typecheck": "tsc --noEmit"
36
+ }
37
+ }
package/src/index.ts ADDED
@@ -0,0 +1,5 @@
1
+ export {
2
+ type MemoryAdapterConfig,
3
+ type MemoryDB,
4
+ memoryAdapter,
5
+ } from "./memory-adapter";
@@ -0,0 +1,353 @@
1
+ import type { BetterAuthOptions } from "@better-auth/core";
2
+ import type {
3
+ CleanedWhere,
4
+ DBAdapterDebugLogOption,
5
+ JoinConfig,
6
+ } from "@better-auth/core/db/adapter";
7
+ import { createAdapterFactory } from "@better-auth/core/db/adapter";
8
+ import { logger } from "@better-auth/core/env";
9
+
10
+ export interface MemoryDB {
11
+ [key: string]: any[];
12
+ }
13
+
14
+ export interface MemoryAdapterConfig {
15
+ debugLogs?: DBAdapterDebugLogOption | undefined;
16
+ }
17
+
18
+ export const memoryAdapter = (
19
+ db: MemoryDB,
20
+ config?: MemoryAdapterConfig | undefined,
21
+ ) => {
22
+ let lazyOptions: BetterAuthOptions | null = null;
23
+ const adapterCreator = createAdapterFactory({
24
+ config: {
25
+ adapterId: "memory",
26
+ adapterName: "Memory Adapter",
27
+ usePlural: false,
28
+ debugLogs: config?.debugLogs || false,
29
+ supportsArrays: true,
30
+ customTransformInput(props) {
31
+ const useNumberId =
32
+ props.options.advanced?.database?.generateId === "serial";
33
+ if (useNumberId && props.field === "id" && props.action === "create") {
34
+ return db[props.model]!.length + 1;
35
+ }
36
+ return props.data;
37
+ },
38
+ transaction: async (cb) => {
39
+ const clone = structuredClone(db);
40
+ try {
41
+ const r = await cb(adapterCreator(lazyOptions!));
42
+ return r;
43
+ } catch (error) {
44
+ // Rollback changes
45
+ Object.keys(db).forEach((key) => {
46
+ db[key] = clone[key]!;
47
+ });
48
+ throw error;
49
+ }
50
+ },
51
+ },
52
+ adapter: ({ getFieldName, options, getModelName }) => {
53
+ const applySortToRecords = (
54
+ records: any[],
55
+ sortBy: { field: string; direction: "asc" | "desc" } | undefined,
56
+ model: string,
57
+ ) => {
58
+ if (!sortBy) return records;
59
+ return records.sort((a: any, b: any) => {
60
+ const field = getFieldName({ model, field: sortBy.field });
61
+ const aValue = a[field];
62
+ const bValue = b[field];
63
+
64
+ let comparison = 0;
65
+
66
+ // Handle null/undefined values
67
+ if (aValue == null && bValue == null) {
68
+ comparison = 0;
69
+ } else if (aValue == null) {
70
+ comparison = -1;
71
+ } else if (bValue == null) {
72
+ comparison = 1;
73
+ }
74
+ // Handle string comparison
75
+ else if (typeof aValue === "string" && typeof bValue === "string") {
76
+ comparison = aValue.localeCompare(bValue);
77
+ }
78
+ // Handle date comparison
79
+ else if (aValue instanceof Date && bValue instanceof Date) {
80
+ comparison = aValue.getTime() - bValue.getTime();
81
+ }
82
+ // Handle numeric comparison
83
+ else if (typeof aValue === "number" && typeof bValue === "number") {
84
+ comparison = aValue - bValue;
85
+ }
86
+ // Handle boolean comparison
87
+ else if (typeof aValue === "boolean" && typeof bValue === "boolean") {
88
+ comparison = aValue === bValue ? 0 : aValue ? 1 : -1;
89
+ }
90
+ // Fallback to string comparison
91
+ else {
92
+ comparison = String(aValue).localeCompare(String(bValue));
93
+ }
94
+
95
+ return sortBy.direction === "asc" ? comparison : -comparison;
96
+ });
97
+ };
98
+
99
+ function convertWhereClause(
100
+ where: CleanedWhere[],
101
+ model: string,
102
+ join?: JoinConfig,
103
+ ): any[] {
104
+ const execute = (where: CleanedWhere[], model: string) => {
105
+ const table = db[model];
106
+ if (!table) {
107
+ logger.error(
108
+ `[MemoryAdapter] Model ${model} not found in the DB`,
109
+ Object.keys(db),
110
+ );
111
+ throw new Error(`Model ${model} not found`);
112
+ }
113
+
114
+ const evalClause = (record: any, clause: CleanedWhere): boolean => {
115
+ const { field, value, operator } = clause;
116
+ switch (operator) {
117
+ case "in":
118
+ if (!Array.isArray(value)) {
119
+ throw new Error("Value must be an array");
120
+ }
121
+ // @ts-expect-error
122
+ return value.includes(record[field]);
123
+ case "not_in":
124
+ if (!Array.isArray(value)) {
125
+ throw new Error("Value must be an array");
126
+ }
127
+ // @ts-expect-error
128
+ return !value.includes(record[field]);
129
+ case "contains":
130
+ return record[field].includes(value);
131
+ case "starts_with":
132
+ return record[field].startsWith(value);
133
+ case "ends_with":
134
+ return record[field].endsWith(value);
135
+ case "ne":
136
+ return record[field] !== value;
137
+ case "gt":
138
+ return value != null && Boolean(record[field] > value);
139
+ case "gte":
140
+ return value != null && Boolean(record[field] >= value);
141
+ case "lt":
142
+ return value != null && Boolean(record[field] < value);
143
+ case "lte":
144
+ return value != null && Boolean(record[field] <= value);
145
+ default:
146
+ return record[field] === value;
147
+ }
148
+ };
149
+
150
+ return table.filter((record: any) => {
151
+ if (!where.length || where.length === 0) {
152
+ return true;
153
+ }
154
+
155
+ let result = evalClause(record, where[0]!);
156
+ for (const clause of where) {
157
+ const clauseResult = evalClause(record, clause);
158
+
159
+ if (clause.connector === "OR") {
160
+ result = result || clauseResult;
161
+ } else {
162
+ result = result && clauseResult;
163
+ }
164
+ }
165
+
166
+ return result;
167
+ });
168
+ };
169
+
170
+ if (!join) return execute(where, model);
171
+
172
+ const baseRecords = execute(where, model);
173
+
174
+ // Group results by base model and nest joined data as arrays
175
+ const grouped = new Map<string, any>();
176
+ // Track seen IDs per joined model for O(1) deduplication
177
+ const seenIds = new Map<string, Set<string>>();
178
+
179
+ for (const baseRecord of baseRecords) {
180
+ const baseId = String(baseRecord.id);
181
+
182
+ if (!grouped.has(baseId)) {
183
+ const nested: Record<string, any> = { ...baseRecord };
184
+
185
+ // Initialize joined data structures based on isUnique
186
+ for (const [joinModel, joinAttr] of Object.entries(join)) {
187
+ const joinModelName = getModelName(joinModel);
188
+ if (joinAttr.relation === "one-to-one") {
189
+ nested[joinModelName] = null;
190
+ } else {
191
+ nested[joinModelName] = [];
192
+ seenIds.set(`${baseId}-${joinModel}`, new Set());
193
+ }
194
+ }
195
+
196
+ grouped.set(baseId, nested);
197
+ }
198
+
199
+ const nestedEntry = grouped.get(baseId)!;
200
+
201
+ // Add joined data
202
+ for (const [joinModel, joinAttr] of Object.entries(join)) {
203
+ const joinModelName = getModelName(joinModel);
204
+ const joinTable = db[joinModelName];
205
+ if (!joinTable) {
206
+ logger.error(
207
+ `[MemoryAdapter] JoinOption model ${joinModelName} not found in the DB`,
208
+ Object.keys(db),
209
+ );
210
+ throw new Error(`JoinOption model ${joinModelName} not found`);
211
+ }
212
+
213
+ const matchingRecords = joinTable.filter(
214
+ (joinRecord: any) =>
215
+ joinRecord[joinAttr.on.to] === baseRecord[joinAttr.on.from],
216
+ );
217
+
218
+ if (joinAttr.relation === "one-to-one") {
219
+ // For unique relationships, store a single object (or null)
220
+ nestedEntry[joinModelName] = matchingRecords[0] || null;
221
+ } else {
222
+ // For non-unique relationships, store array with limit
223
+ const seenSet = seenIds.get(`${baseId}-${joinModel}`)!;
224
+ const limit = joinAttr.limit ?? 100;
225
+ let count = 0;
226
+
227
+ for (const matchingRecord of matchingRecords) {
228
+ if (count >= limit) break;
229
+ if (!seenSet.has(matchingRecord.id)) {
230
+ nestedEntry[joinModelName].push(matchingRecord);
231
+ seenSet.add(matchingRecord.id);
232
+ count++;
233
+ }
234
+ }
235
+ }
236
+ }
237
+ }
238
+
239
+ return Array.from(grouped.values());
240
+ }
241
+ return {
242
+ create: async ({ model, data }) => {
243
+ const useNumberId =
244
+ options.advanced?.database?.generateId === "serial";
245
+ if (useNumberId) {
246
+ // @ts-expect-error
247
+ data.id = db[getModelName(model)]!.length + 1;
248
+ }
249
+ if (!db[model]) {
250
+ db[model] = [];
251
+ }
252
+ db[model]!.push(data);
253
+ return data;
254
+ },
255
+ findOne: async ({ model, where, join }) => {
256
+ const res = convertWhereClause(where, model, join);
257
+ if (join) {
258
+ // When join is present, res is an array of nested objects
259
+ const resArray = res as any[];
260
+ if (!resArray.length) {
261
+ return null;
262
+ }
263
+ // Return the first nested object
264
+ return resArray[0];
265
+ }
266
+ // Without join, res is an array
267
+ const resArray = res as any[];
268
+ const record = resArray[0] || null;
269
+ return record;
270
+ },
271
+ findMany: async ({ model, where, sortBy, limit, offset, join }) => {
272
+ const res = convertWhereClause(where || [], model, join);
273
+
274
+ if (join) {
275
+ // When join is present, res is an array of nested objects
276
+ const resArray = res as any[];
277
+ if (!resArray.length) {
278
+ return [];
279
+ }
280
+
281
+ // Apply sorting to nested objects
282
+ applySortToRecords(resArray, sortBy, model);
283
+
284
+ // Apply offset and limit
285
+ let paginatedRecords = resArray;
286
+ if (offset !== undefined) {
287
+ paginatedRecords = paginatedRecords.slice(offset);
288
+ }
289
+ if (limit !== undefined) {
290
+ paginatedRecords = paginatedRecords.slice(0, limit);
291
+ }
292
+
293
+ return paginatedRecords;
294
+ }
295
+
296
+ // Without join - original logic
297
+ const resArray = res as any[];
298
+ let table = applySortToRecords(resArray, sortBy, model);
299
+ if (offset !== undefined) {
300
+ table = table!.slice(offset);
301
+ }
302
+ if (limit !== undefined) {
303
+ table = table!.slice(0, limit);
304
+ }
305
+ return table || [];
306
+ },
307
+ count: async ({ model, where }) => {
308
+ if (where) {
309
+ const filteredRecords = convertWhereClause(where, model);
310
+ return filteredRecords.length;
311
+ }
312
+ return db[model]!.length;
313
+ },
314
+ update: async ({ model, where, update }) => {
315
+ const res = convertWhereClause(where, model);
316
+ res.forEach((record) => {
317
+ Object.assign(record, update);
318
+ });
319
+ return res[0] || null;
320
+ },
321
+ delete: async ({ model, where }) => {
322
+ const table = db[model]!;
323
+ const res = convertWhereClause(where, model);
324
+ db[model] = table.filter((record) => !res.includes(record));
325
+ },
326
+ deleteMany: async ({ model, where }) => {
327
+ const table = db[model]!;
328
+ const res = convertWhereClause(where, model);
329
+ let count = 0;
330
+ db[model] = table.filter((record) => {
331
+ if (res.includes(record)) {
332
+ count++;
333
+ return false;
334
+ }
335
+ return !res.includes(record);
336
+ });
337
+ return count;
338
+ },
339
+ updateMany({ model, where, update }) {
340
+ const res = convertWhereClause(where, model);
341
+ res.forEach((record) => {
342
+ Object.assign(record, update);
343
+ });
344
+ return res[0] || null;
345
+ },
346
+ };
347
+ },
348
+ });
349
+ return (options: BetterAuthOptions) => {
350
+ lazyOptions = options;
351
+ return adapterCreator(options);
352
+ };
353
+ };
package/tsconfig.json ADDED
@@ -0,0 +1,9 @@
1
+ {
2
+ "extends": "../../tsconfig.base.json",
3
+ "include": ["./src"],
4
+ "references": [
5
+ {
6
+ "path": "../core/tsconfig.json"
7
+ }
8
+ ]
9
+ }
@@ -0,0 +1,8 @@
1
+ import { defineConfig } from "tsdown";
2
+
3
+ export default defineConfig({
4
+ dts: { build: true, incremental: true },
5
+ format: ["esm"],
6
+ entry: ["./src/index.ts"],
7
+ sourcemap: true,
8
+ });
@@ -0,0 +1,3 @@
1
+ import { defineProject } from "vitest/config";
2
+
3
+ export default defineProject({});