@a77ay/better-auth-mikro-orm 0.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.
- package/LICENSE +20 -0
- package/README.md +191 -0
- package/dist/cli-cy61BGrg.mjs +977 -0
- package/dist/cli.d.mts +1 -0
- package/dist/cli.mjs +10 -0
- package/dist/index.d.mts +177 -0
- package/dist/index.mjs +2 -0
- package/package.json +86 -0
|
@@ -0,0 +1,977 @@
|
|
|
1
|
+
import { LockMode, RequestContext, raw, wrap } from "@mikro-orm/core";
|
|
2
|
+
import { BetterAuthError } from "better-auth";
|
|
3
|
+
import { createAdapterFactory } from "better-auth/adapters";
|
|
4
|
+
import { access, mkdir, writeFile } from "node:fs/promises";
|
|
5
|
+
import { dirname, resolve } from "node:path";
|
|
6
|
+
import { parseArgs } from "node:util";
|
|
7
|
+
import { getAuthTables } from "better-auth/db";
|
|
8
|
+
import { createJiti } from "jiti";
|
|
9
|
+
//#region src/utils/strings.ts
|
|
10
|
+
function quote(value) {
|
|
11
|
+
return JSON.stringify(value);
|
|
12
|
+
}
|
|
13
|
+
function propertyKey(value) {
|
|
14
|
+
return /^[A-Z_$][\w$]*$/i.test(value) ? value : quote(value);
|
|
15
|
+
}
|
|
16
|
+
function stringArray(values) {
|
|
17
|
+
return `[${values.map(quote).join(", ")}]`;
|
|
18
|
+
}
|
|
19
|
+
function toPascalCase(value) {
|
|
20
|
+
const result = value.replaceAll(/([a-z\d])([A-Z])/g, "$1 $2").split(/[^a-zA-Z\d]+/).filter(Boolean).map((part) => `${part[0]?.toUpperCase()}${part.slice(1)}`).join("");
|
|
21
|
+
if (!result) return "Model";
|
|
22
|
+
return /^\d/.test(result) ? `Model${result}` : result;
|
|
23
|
+
}
|
|
24
|
+
function toSnakeCase(value) {
|
|
25
|
+
return value.replace(/([a-z\d])([A-Z])/g, "$1_$2").replace(/[-\s]+/g, "_").toLowerCase();
|
|
26
|
+
}
|
|
27
|
+
function toKebabCase(value) {
|
|
28
|
+
return toSnakeCase(value).replaceAll("_", "-");
|
|
29
|
+
}
|
|
30
|
+
//#endregion
|
|
31
|
+
//#region src/generator/utils.ts
|
|
32
|
+
function createModelNames(entries) {
|
|
33
|
+
const usedNames = /* @__PURE__ */ new Set();
|
|
34
|
+
return new Map(entries.map(([model]) => {
|
|
35
|
+
const baseName = toPascalCase(model);
|
|
36
|
+
let name = baseName;
|
|
37
|
+
let suffix = 2;
|
|
38
|
+
while (usedNames.has(name)) name = `${baseName}${suffix++}`;
|
|
39
|
+
usedNames.add(name);
|
|
40
|
+
return [model, name];
|
|
41
|
+
}));
|
|
42
|
+
}
|
|
43
|
+
function createFileNames(entries, modelNames, options) {
|
|
44
|
+
const usedNames = /* @__PURE__ */ new Set(["index"]);
|
|
45
|
+
const rawSuffix = options?.fileSuffix?.trim() ?? "";
|
|
46
|
+
const suffixExt = rawSuffix && !rawSuffix.startsWith(".") ? `.${rawSuffix}` : rawSuffix;
|
|
47
|
+
return new Map(entries.map(([model]) => {
|
|
48
|
+
const baseName = toKebabCase(modelNames.get(model));
|
|
49
|
+
let name = baseName;
|
|
50
|
+
let suffix = 2;
|
|
51
|
+
while (usedNames.has(name)) name = `${baseName}-${suffix++}`;
|
|
52
|
+
usedNames.add(name);
|
|
53
|
+
return [model, `${name}${suffixExt}.ts`];
|
|
54
|
+
}));
|
|
55
|
+
}
|
|
56
|
+
function databasePropertyName(fieldName, field, options) {
|
|
57
|
+
if (field.fieldName) return field.fieldName;
|
|
58
|
+
if (options?.casing === "snake_case") return toSnakeCase(fieldName);
|
|
59
|
+
return fieldName;
|
|
60
|
+
}
|
|
61
|
+
function entityPropertyName(fieldName, field) {
|
|
62
|
+
return field.fieldName ?? fieldName;
|
|
63
|
+
}
|
|
64
|
+
function findReferencedTable(entries, model) {
|
|
65
|
+
return entries.find(([defaultModel, table]) => defaultModel === model || table.modelName === model);
|
|
66
|
+
}
|
|
67
|
+
function getSortedTableEntries(tables) {
|
|
68
|
+
const filtered = Object.entries(tables).filter(([, table]) => !table.disableMigrations);
|
|
69
|
+
const modelToEntry = new Map(filtered.map((entry) => [entry[0], entry]));
|
|
70
|
+
const tableNameToKey = /* @__PURE__ */ new Map();
|
|
71
|
+
for (const [key, table] of filtered) {
|
|
72
|
+
tableNameToKey.set(key, key);
|
|
73
|
+
if (table.modelName) tableNameToKey.set(table.modelName, key);
|
|
74
|
+
}
|
|
75
|
+
const compareBase = (a, b) => {
|
|
76
|
+
const orderA = a[1].order ?? Number.MAX_SAFE_INTEGER;
|
|
77
|
+
const orderB = b[1].order ?? Number.MAX_SAFE_INTEGER;
|
|
78
|
+
if (orderA !== orderB) return orderA - orderB;
|
|
79
|
+
return a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0;
|
|
80
|
+
};
|
|
81
|
+
const dependencies = /* @__PURE__ */ new Map();
|
|
82
|
+
for (const [key, table] of filtered) {
|
|
83
|
+
const deps = /* @__PURE__ */ new Set();
|
|
84
|
+
for (const field of Object.values(table.fields ?? {})) if (field.references?.model) {
|
|
85
|
+
const depKey = tableNameToKey.get(field.references.model);
|
|
86
|
+
if (depKey && depKey !== key) deps.add(depKey);
|
|
87
|
+
}
|
|
88
|
+
dependencies.set(key, deps);
|
|
89
|
+
}
|
|
90
|
+
const inDegree = /* @__PURE__ */ new Map();
|
|
91
|
+
const reverseGraph = /* @__PURE__ */ new Map();
|
|
92
|
+
for (const [key] of filtered) {
|
|
93
|
+
inDegree.set(key, dependencies.get(key)?.size ?? 0);
|
|
94
|
+
reverseGraph.set(key, /* @__PURE__ */ new Set());
|
|
95
|
+
}
|
|
96
|
+
for (const [key, deps] of dependencies) for (const dep of deps) reverseGraph.get(dep)?.add(key);
|
|
97
|
+
const available = filtered.filter(([key]) => (inDegree.get(key) ?? 0) === 0).sort(compareBase);
|
|
98
|
+
const sorted = [];
|
|
99
|
+
const visited = /* @__PURE__ */ new Set();
|
|
100
|
+
while (available.length > 0) {
|
|
101
|
+
available.sort(compareBase);
|
|
102
|
+
const [key, table] = available.shift();
|
|
103
|
+
visited.add(key);
|
|
104
|
+
sorted.push([key, table]);
|
|
105
|
+
for (const dependent of reverseGraph.get(key) ?? []) {
|
|
106
|
+
const newDeg = (inDegree.get(dependent) ?? 1) - 1;
|
|
107
|
+
inDegree.set(dependent, newDeg);
|
|
108
|
+
if (newDeg === 0) {
|
|
109
|
+
const depEntry = modelToEntry.get(dependent);
|
|
110
|
+
if (depEntry) available.push(depEntry);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
if (sorted.length < filtered.length) {
|
|
115
|
+
const remaining = filtered.filter(([key]) => !visited.has(key)).sort(compareBase);
|
|
116
|
+
sorted.push(...remaining);
|
|
117
|
+
}
|
|
118
|
+
return sorted;
|
|
119
|
+
}
|
|
120
|
+
function scalarType(field, options, indexed = false) {
|
|
121
|
+
if (Array.isArray(field.type)) return {
|
|
122
|
+
mikroOrm: "string",
|
|
123
|
+
typescript: field.type.length ? field.type.map(quote).join(" | ") : "string",
|
|
124
|
+
enum: field.type
|
|
125
|
+
};
|
|
126
|
+
if (field.type === "date") return options.supportsDates === false ? {
|
|
127
|
+
mikroOrm: "string",
|
|
128
|
+
typescript: "string"
|
|
129
|
+
} : {
|
|
130
|
+
mikroOrm: "Date",
|
|
131
|
+
typescript: "Date"
|
|
132
|
+
};
|
|
133
|
+
if (field.type === "boolean") return options.supportsBooleans === false ? {
|
|
134
|
+
mikroOrm: "number",
|
|
135
|
+
typescript: "number"
|
|
136
|
+
} : {
|
|
137
|
+
mikroOrm: "boolean",
|
|
138
|
+
typescript: "boolean"
|
|
139
|
+
};
|
|
140
|
+
if (field.type === "number") return {
|
|
141
|
+
mikroOrm: field.bigint ? "bigint" : "number",
|
|
142
|
+
typescript: "number"
|
|
143
|
+
};
|
|
144
|
+
if (field.type === "json") return options.supportsJSON === false ? {
|
|
145
|
+
mikroOrm: "text",
|
|
146
|
+
typescript: "string"
|
|
147
|
+
} : {
|
|
148
|
+
mikroOrm: "json",
|
|
149
|
+
typescript: "Record<string, unknown> | unknown[]"
|
|
150
|
+
};
|
|
151
|
+
if (field.type === "string[]" || field.type === "number[]") return options.supportsArrays ? {
|
|
152
|
+
mikroOrm: "array",
|
|
153
|
+
typescript: field.type === "string[]" ? "string[]" : "number[]"
|
|
154
|
+
} : {
|
|
155
|
+
mikroOrm: "text",
|
|
156
|
+
typescript: "string"
|
|
157
|
+
};
|
|
158
|
+
return {
|
|
159
|
+
mikroOrm: field.sortable || field.index || field.unique || indexed ? "string" : "text",
|
|
160
|
+
typescript: "string"
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
//#endregion
|
|
164
|
+
//#region src/generator/decorators.ts
|
|
165
|
+
function renderDecoratorProperty(fieldName, field, entries, modelNames, options) {
|
|
166
|
+
const propertyName = entityPropertyName(fieldName, field);
|
|
167
|
+
const databaseName = databasePropertyName(fieldName, field, options);
|
|
168
|
+
const optional = field.required === false ? "?" : "!";
|
|
169
|
+
const reference = field.references;
|
|
170
|
+
const referencedEntry = reference ? findReferencedTable(entries, reference.model) : void 0;
|
|
171
|
+
if (reference && referencedEntry) {
|
|
172
|
+
const [referencedModel, referencedTable] = referencedEntry;
|
|
173
|
+
const referencedField = referencedTable.fields[reference.field];
|
|
174
|
+
const referencedProperty = referencedField ? entityPropertyName(reference.field, referencedField) : reference.field;
|
|
175
|
+
const referencedDatabaseName = referencedField ? databasePropertyName(reference.field, referencedField, options) : reference.field;
|
|
176
|
+
const targetModel = modelNames.get(referencedModel);
|
|
177
|
+
const opts = ["mapToPk: true"];
|
|
178
|
+
if (databaseName !== propertyName) opts.push(`fieldName: ${quote(databaseName)}`);
|
|
179
|
+
if (referencedDatabaseName !== "id") opts.push(`referenceColumnName: ${quote(referencedDatabaseName)}`);
|
|
180
|
+
opts.push(`deleteRule: ${quote(reference.onDelete ?? "cascade")}`);
|
|
181
|
+
if (reference.field !== "id") opts.push(`targetKey: ${quote(referencedProperty)}`);
|
|
182
|
+
if (field.required === false) opts.push("nullable: true");
|
|
183
|
+
return ` @ManyToOne(() => ${targetModel}, { ${opts.join(", ")} })
|
|
184
|
+
${propertyKey(propertyName)}${optional}: ${options.numericIds ? "number" : "string"};`;
|
|
185
|
+
}
|
|
186
|
+
if (Array.isArray(field.type)) {
|
|
187
|
+
const opts = [`items: () => ${stringArray(field.type)}`];
|
|
188
|
+
if (databaseName !== propertyName) opts.push(`fieldName: ${quote(databaseName)}`);
|
|
189
|
+
if (field.required === false) opts.push("nullable: true");
|
|
190
|
+
if (typeof field.defaultValue === "string") opts.push(`default: ${quote(field.defaultValue)}`);
|
|
191
|
+
else if (typeof field.defaultValue === "number" || typeof field.defaultValue === "boolean") opts.push(`default: ${field.defaultValue}`);
|
|
192
|
+
const tsType = field.type.length ? field.type.map(quote).join(" | ") : "string";
|
|
193
|
+
return ` @Enum({ ${opts.join(", ")} })
|
|
194
|
+
${propertyKey(propertyName)}${optional}: ${tsType};`;
|
|
195
|
+
}
|
|
196
|
+
const type = scalarType(field, options);
|
|
197
|
+
const opts = [`type: ${quote(type.mikroOrm)}`];
|
|
198
|
+
if (databaseName !== propertyName) opts.push(`fieldName: ${quote(databaseName)}`);
|
|
199
|
+
if (field.bigint) opts.push("runtimeType: \"number\"");
|
|
200
|
+
if (field.required === false) opts.push("nullable: true");
|
|
201
|
+
if (field.unique) opts.push("unique: true");
|
|
202
|
+
if (field.index) opts.push("index: true");
|
|
203
|
+
if (typeof field.defaultValue === "boolean" || typeof field.defaultValue === "number" || typeof field.defaultValue === "string") opts.push(`default: ${typeof field.defaultValue === "string" ? quote(field.defaultValue) : field.defaultValue}`);
|
|
204
|
+
return ` @Property({ ${opts.join(", ")} })
|
|
205
|
+
${propertyKey(propertyName)}${optional}: ${type.typescript};`;
|
|
206
|
+
}
|
|
207
|
+
function renderClassIndexes(table) {
|
|
208
|
+
const indexes = table.indexes?.filter((index) => !index.unique) ?? [];
|
|
209
|
+
const uniques = table.indexes?.filter((index) => index.unique) ?? [];
|
|
210
|
+
const decorators = [];
|
|
211
|
+
for (const index of indexes) {
|
|
212
|
+
const properties = index.fields.map((fieldName) => entityPropertyName(fieldName, table.fields[fieldName] ?? { type: "string" }));
|
|
213
|
+
const opts = [index.name ? `name: ${quote(index.name)}` : "", `properties: ${stringArray(properties)}`].filter(Boolean).join(", ");
|
|
214
|
+
decorators.push(`@Index({ ${opts} })`);
|
|
215
|
+
}
|
|
216
|
+
for (const unique of uniques) {
|
|
217
|
+
const properties = unique.fields.map((fieldName) => entityPropertyName(fieldName, table.fields[fieldName] ?? { type: "string" }));
|
|
218
|
+
const opts = [unique.name ? `name: ${quote(unique.name)}` : "", `properties: ${stringArray(properties)}`].filter(Boolean).join(", ");
|
|
219
|
+
decorators.push(`@Unique({ ${opts} })`);
|
|
220
|
+
}
|
|
221
|
+
return decorators.length ? `${decorators.join("\n")}\n` : "";
|
|
222
|
+
}
|
|
223
|
+
function renderDecoratorEntity(defaultModel, table, entries, modelNames, options) {
|
|
224
|
+
const modelName = modelNames.get(defaultModel);
|
|
225
|
+
const idType = options.numericIds ? "number" : "string";
|
|
226
|
+
const pkDecorator = options.numericIds ? "@PrimaryKey({ autoincrement: true })" : "@PrimaryKey()";
|
|
227
|
+
const classIndexes = renderClassIndexes(table);
|
|
228
|
+
const properties = Object.entries(table.fields).map(([fieldName, field]) => renderDecoratorProperty(fieldName, field, entries, modelNames, options));
|
|
229
|
+
return `${classIndexes}@Entity({ tableName: ${quote(table.modelName)} })
|
|
230
|
+
export class ${modelName} {
|
|
231
|
+
${pkDecorator}
|
|
232
|
+
id!: ${idType};
|
|
233
|
+
|
|
234
|
+
${properties.join("\n\n")}
|
|
235
|
+
}`;
|
|
236
|
+
}
|
|
237
|
+
function referencedModels$1(table, entries) {
|
|
238
|
+
const models = /* @__PURE__ */ new Set();
|
|
239
|
+
for (const field of Object.values(table.fields)) {
|
|
240
|
+
if (!field.references) continue;
|
|
241
|
+
const entry = findReferencedTable(entries, field.references.model);
|
|
242
|
+
if (entry) models.add(entry[0]);
|
|
243
|
+
}
|
|
244
|
+
return models;
|
|
245
|
+
}
|
|
246
|
+
function generateDecoratorsSchema(options) {
|
|
247
|
+
const entries = getSortedTableEntries(options.tables);
|
|
248
|
+
const modelNames = createModelNames(entries);
|
|
249
|
+
const sections = entries.map(([defaultModel, table]) => renderDecoratorEntity(defaultModel, table, entries, modelNames, options));
|
|
250
|
+
const exports = entries.map(([model]) => ` ${modelNames.get(model)},`).join("\n");
|
|
251
|
+
return `import { Entity, Enum, Index, ManyToOne, PrimaryKey, Property, Unique } from "@mikro-orm/core";
|
|
252
|
+
|
|
253
|
+
${sections.join("\n\n")}
|
|
254
|
+
|
|
255
|
+
export const betterAuthEntities = [
|
|
256
|
+
${exports}
|
|
257
|
+
] as const;
|
|
258
|
+
`;
|
|
259
|
+
}
|
|
260
|
+
function generateDecoratorFiles(options) {
|
|
261
|
+
const entries = getSortedTableEntries(options.tables);
|
|
262
|
+
const modelNames = createModelNames(entries);
|
|
263
|
+
const fileNames = createFileNames(entries, modelNames, options);
|
|
264
|
+
const files = entries.map(([defaultModel, table]) => {
|
|
265
|
+
const imports = [...referencedModels$1(table, entries)].filter((model) => model !== defaultModel).map((model) => {
|
|
266
|
+
return `import { ${modelNames.get(model)} } from "./${fileNames.get(model).replace(/\.ts$/, "")}";`;
|
|
267
|
+
});
|
|
268
|
+
const importBlock = imports.length ? `${imports.join("\n")}\n` : "";
|
|
269
|
+
return {
|
|
270
|
+
path: fileNames.get(defaultModel),
|
|
271
|
+
code: `import { Entity, Enum, Index, ManyToOne, PrimaryKey, Property, Unique } from "@mikro-orm/core";
|
|
272
|
+
${importBlock}
|
|
273
|
+
${renderDecoratorEntity(defaultModel, table, entries, modelNames, options)}
|
|
274
|
+
`
|
|
275
|
+
};
|
|
276
|
+
});
|
|
277
|
+
const imports = entries.map(([model]) => {
|
|
278
|
+
return `import { ${modelNames.get(model)} } from "./${fileNames.get(model).replace(/\.ts$/, "")}";`;
|
|
279
|
+
}).join("\n");
|
|
280
|
+
const exports = entries.map(([model]) => ` ${modelNames.get(model)},`).join("\n");
|
|
281
|
+
const namedExports = entries.map(([model]) => ` ${modelNames.get(model)},`).join("\n");
|
|
282
|
+
files.push({
|
|
283
|
+
path: "index.ts",
|
|
284
|
+
code: `${imports}
|
|
285
|
+
|
|
286
|
+
export {
|
|
287
|
+
${namedExports}
|
|
288
|
+
};
|
|
289
|
+
|
|
290
|
+
export const betterAuthEntities = [
|
|
291
|
+
${exports}
|
|
292
|
+
] as const;
|
|
293
|
+
`
|
|
294
|
+
});
|
|
295
|
+
return files;
|
|
296
|
+
}
|
|
297
|
+
//#endregion
|
|
298
|
+
//#region src/generator/define-entity.ts
|
|
299
|
+
function renderDefineProperty(fieldName, field, entries, modelNames, options) {
|
|
300
|
+
const propertyName = entityPropertyName(fieldName, field);
|
|
301
|
+
const databaseName = databasePropertyName(fieldName, field, options);
|
|
302
|
+
const chains = [];
|
|
303
|
+
const reference = field.references;
|
|
304
|
+
const referencedEntry = reference ? findReferencedTable(entries, reference.model) : void 0;
|
|
305
|
+
if (reference && referencedEntry) {
|
|
306
|
+
const [referencedModel, referencedTable] = referencedEntry;
|
|
307
|
+
const referencedField = referencedTable.fields[reference.field];
|
|
308
|
+
const referencedProperty = referencedField ? entityPropertyName(reference.field, referencedField) : reference.field;
|
|
309
|
+
const referencedDatabaseName = referencedField ? databasePropertyName(reference.field, referencedField, options) : reference.field;
|
|
310
|
+
const targetModel = modelNames.get(referencedModel);
|
|
311
|
+
chains.push(`p.manyToOne(${targetModel})`);
|
|
312
|
+
chains.push("mapToPk()");
|
|
313
|
+
if (databaseName !== propertyName) chains.push(`fieldName(${quote(databaseName)})`);
|
|
314
|
+
if (referencedDatabaseName !== "id") chains.push(`referenceColumnName(${quote(referencedDatabaseName)})`);
|
|
315
|
+
if (reference.field !== "id") chains.push(`targetKey(${quote(referencedProperty)})`);
|
|
316
|
+
chains.push(`deleteRule(${quote(reference.onDelete ?? "cascade")})`);
|
|
317
|
+
} else if (Array.isArray(field.type)) chains.push(`p.enum(${stringArray(field.type)})`);
|
|
318
|
+
else if (field.type === "date") chains.push(options.supportsDates === false ? "p.string()" : "p.datetime()");
|
|
319
|
+
else if (field.type === "boolean") chains.push(options.supportsBooleans === false ? "p.integer()" : "p.boolean()");
|
|
320
|
+
else if (field.type === "number") chains.push(field.bigint ? "p.bigint(\"number\")" : "p.integer()");
|
|
321
|
+
else if (field.type === "json") chains.push(options.supportsJSON === false ? "p.text()" : "p.json()");
|
|
322
|
+
else if (field.type === "string[]" || field.type === "number[]") chains.push(options.supportsArrays ? "p.array()" : "p.text()");
|
|
323
|
+
else chains.push(field.sortable || field.index || field.unique ? "p.string()" : "p.text()");
|
|
324
|
+
if (databaseName !== propertyName && (!reference || !referencedEntry)) chains.push(`fieldName(${quote(databaseName)})`);
|
|
325
|
+
if (field.required === false) chains.push("nullable()");
|
|
326
|
+
if (typeof field.defaultValue === "boolean" || typeof field.defaultValue === "number" || typeof field.defaultValue === "string") chains.push(`default(${typeof field.defaultValue === "string" ? quote(field.defaultValue) : field.defaultValue})`);
|
|
327
|
+
if (field.unique) chains.push("unique()");
|
|
328
|
+
if (field.index) chains.push("index()");
|
|
329
|
+
return ` ${propertyKey(propertyName)}: ${chains.join(".")},`;
|
|
330
|
+
}
|
|
331
|
+
function renderDefineIndexes(table) {
|
|
332
|
+
const indexes = table.indexes?.filter((index) => !index.unique) ?? [];
|
|
333
|
+
const uniques = table.indexes?.filter((index) => index.unique) ?? [];
|
|
334
|
+
const render = (items) => {
|
|
335
|
+
if (!items.length) return void 0;
|
|
336
|
+
return `[\n${items.map((index) => {
|
|
337
|
+
const properties = index.fields.map((fieldName) => entityPropertyName(fieldName, table.fields[fieldName] ?? { type: "string" }));
|
|
338
|
+
return ` {
|
|
339
|
+
${index.name ? ` name: ${quote(index.name)},\n` : ""} properties: ${stringArray(properties)},
|
|
340
|
+
},`;
|
|
341
|
+
}).join("\n")}\n ]`;
|
|
342
|
+
};
|
|
343
|
+
return {
|
|
344
|
+
indexes: render(indexes),
|
|
345
|
+
uniques: render(uniques)
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
function renderDefineEntity(defaultModel, table, entries, modelNames, options) {
|
|
349
|
+
const modelName = modelNames.get(defaultModel);
|
|
350
|
+
const idChain = options.numericIds ? "p.integer().primary().autoincrement()" : "p.string().primary()";
|
|
351
|
+
const properties = Object.entries(table.fields).map(([fieldName, field]) => renderDefineProperty(fieldName, field, entries, modelNames, options));
|
|
352
|
+
const { indexes, uniques } = renderDefineIndexes(table);
|
|
353
|
+
const extraFields = [];
|
|
354
|
+
if (indexes) extraFields.push(` indexes: ${indexes},`);
|
|
355
|
+
if (uniques) extraFields.push(` uniques: ${uniques},`);
|
|
356
|
+
const extraString = extraFields.length ? `\n${extraFields.join("\n")}` : "";
|
|
357
|
+
return `export const ${modelName} = defineEntity({
|
|
358
|
+
name: ${quote(modelName)},
|
|
359
|
+
tableName: ${quote(table.modelName)},
|
|
360
|
+
properties: {
|
|
361
|
+
id: ${idChain},
|
|
362
|
+
${properties.join("\n")}
|
|
363
|
+
},${extraString}
|
|
364
|
+
});
|
|
365
|
+
|
|
366
|
+
export type ${modelName} = InferEntity<typeof ${modelName}>;`;
|
|
367
|
+
}
|
|
368
|
+
function referencedModels(table, entries) {
|
|
369
|
+
const models = /* @__PURE__ */ new Set();
|
|
370
|
+
for (const field of Object.values(table.fields)) {
|
|
371
|
+
if (!field.references) continue;
|
|
372
|
+
const entry = findReferencedTable(entries, field.references.model);
|
|
373
|
+
if (entry) models.add(entry[0]);
|
|
374
|
+
}
|
|
375
|
+
return models;
|
|
376
|
+
}
|
|
377
|
+
function generateDefineEntitySchema(options) {
|
|
378
|
+
const entries = getSortedTableEntries(options.tables);
|
|
379
|
+
const modelNames = createModelNames(entries);
|
|
380
|
+
const sections = entries.map(([defaultModel, table]) => renderDefineEntity(defaultModel, table, entries, modelNames, options));
|
|
381
|
+
const exports = entries.map(([model]) => ` ${modelNames.get(model)},`).join("\n");
|
|
382
|
+
return `import { defineEntity, p, type InferEntity } from "@mikro-orm/core";
|
|
383
|
+
|
|
384
|
+
${sections.join("\n\n")}
|
|
385
|
+
|
|
386
|
+
export const betterAuthEntities = [
|
|
387
|
+
${exports}
|
|
388
|
+
] as const;
|
|
389
|
+
`;
|
|
390
|
+
}
|
|
391
|
+
function generateDefineEntityFiles(options) {
|
|
392
|
+
const entries = getSortedTableEntries(options.tables);
|
|
393
|
+
const modelNames = createModelNames(entries);
|
|
394
|
+
const fileNames = createFileNames(entries, modelNames, options);
|
|
395
|
+
const files = entries.map(([defaultModel, table]) => {
|
|
396
|
+
const imports = [...referencedModels(table, entries)].filter((model) => model !== defaultModel).map((model) => {
|
|
397
|
+
return `import { ${modelNames.get(model)} } from "./${fileNames.get(model).replace(/\.ts$/, "")}";`;
|
|
398
|
+
});
|
|
399
|
+
const importBlock = imports.length ? `${imports.join("\n")}\n` : "";
|
|
400
|
+
return {
|
|
401
|
+
path: fileNames.get(defaultModel),
|
|
402
|
+
code: `import { defineEntity, p, type InferEntity } from "@mikro-orm/core";
|
|
403
|
+
${importBlock}
|
|
404
|
+
${renderDefineEntity(defaultModel, table, entries, modelNames, options)}
|
|
405
|
+
`
|
|
406
|
+
};
|
|
407
|
+
});
|
|
408
|
+
const imports = entries.map(([model]) => {
|
|
409
|
+
return `import { ${modelNames.get(model)} } from "./${fileNames.get(model).replace(/\.ts$/, "")}";`;
|
|
410
|
+
}).join("\n");
|
|
411
|
+
const exports = entries.map(([model]) => ` ${modelNames.get(model)},`).join("\n");
|
|
412
|
+
const namedExports = entries.map(([model]) => ` ${modelNames.get(model)},`).join("\n");
|
|
413
|
+
files.push({
|
|
414
|
+
path: "index.ts",
|
|
415
|
+
code: `${imports}
|
|
416
|
+
|
|
417
|
+
export {
|
|
418
|
+
${namedExports}
|
|
419
|
+
};
|
|
420
|
+
|
|
421
|
+
export const betterAuthEntities = [
|
|
422
|
+
${exports}
|
|
423
|
+
] as const;
|
|
424
|
+
`
|
|
425
|
+
});
|
|
426
|
+
return files;
|
|
427
|
+
}
|
|
428
|
+
//#endregion
|
|
429
|
+
//#region src/generator/directory.ts
|
|
430
|
+
function generateMikroOrmSchemaDirectory(options) {
|
|
431
|
+
const files = (options.entityStyle ?? "define-entity") === "decorators" ? generateDecoratorFiles(options) : generateDefineEntityFiles(options);
|
|
432
|
+
return {
|
|
433
|
+
directory: options.directory ?? "src/entities/auth",
|
|
434
|
+
files
|
|
435
|
+
};
|
|
436
|
+
}
|
|
437
|
+
async function writeMikroOrmSchemaDirectory(options) {
|
|
438
|
+
const generated = generateMikroOrmSchemaDirectory(options);
|
|
439
|
+
const directory = resolve(process.cwd(), generated.directory);
|
|
440
|
+
await mkdir(directory, { recursive: true });
|
|
441
|
+
await Promise.all(generated.files.map(async (file) => {
|
|
442
|
+
const output = resolve(directory, file.path);
|
|
443
|
+
await mkdir(dirname(output), { recursive: true });
|
|
444
|
+
await writeFile(output, file.code);
|
|
445
|
+
}));
|
|
446
|
+
return generated;
|
|
447
|
+
}
|
|
448
|
+
//#endregion
|
|
449
|
+
//#region src/generator/generator.ts
|
|
450
|
+
/**
|
|
451
|
+
* Generate a deterministic MikroORM entity module for Better Auth and its plugins.
|
|
452
|
+
*
|
|
453
|
+
* Supports two entity styles:
|
|
454
|
+
* - `"define-entity"` (default): Modern MikroORM v7 fluent `defineEntity()` schema API
|
|
455
|
+
* - `"decorators"`: Class-based entities with `@Entity()`, `@Property()`, `@PrimaryKey()`, `@ManyToOne()`
|
|
456
|
+
*/
|
|
457
|
+
function generateMikroOrmSchema(options) {
|
|
458
|
+
return {
|
|
459
|
+
code: (options.entityStyle ?? "define-entity") === "decorators" ? generateDecoratorsSchema(options) : generateDefineEntitySchema(options),
|
|
460
|
+
path: options.file ?? "auth-entities.ts",
|
|
461
|
+
overwrite: true
|
|
462
|
+
};
|
|
463
|
+
}
|
|
464
|
+
//#endregion
|
|
465
|
+
//#region src/adapter/where.ts
|
|
466
|
+
function escapeRegExp(value) {
|
|
467
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
468
|
+
}
|
|
469
|
+
function insensitivePattern(operator, value) {
|
|
470
|
+
const escaped = escapeRegExp(value);
|
|
471
|
+
switch (operator) {
|
|
472
|
+
case "contains": return new RegExp(escaped, "i");
|
|
473
|
+
case "starts_with": return new RegExp(`^${escaped}`, "i");
|
|
474
|
+
case "ends_with": return new RegExp(`${escaped}$`, "i");
|
|
475
|
+
default: return new RegExp(`^${escaped}$`, "i");
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
function findProperty(meta, field) {
|
|
479
|
+
return meta.properties[field] ?? Object.values(meta.properties).find((item) => item.name === field || item.name.toLowerCase() === field.toLowerCase() || item.fieldNames?.includes(field) || item.fieldNames?.some((fn) => fn.toLowerCase() === field.toLowerCase()));
|
|
480
|
+
}
|
|
481
|
+
function transformCondition({ field, mode, operator = "eq", value }, context) {
|
|
482
|
+
const insensitive = mode === "insensitive";
|
|
483
|
+
const property = findProperty(context.meta, field);
|
|
484
|
+
if (!property) throw new TypeError(`No field "${field}" exists on MikroORM entity "${context.meta.className}".`);
|
|
485
|
+
const propName = property.name;
|
|
486
|
+
if (operator === "in" || operator === "not_in") {
|
|
487
|
+
if (!Array.isArray(value)) throw new TypeError(`The value for "${field}" must be an array when using "${operator}".`);
|
|
488
|
+
if (insensitive && value.every((item) => typeof item === "string") && context.mongo) {
|
|
489
|
+
const conditions = value.map((item) => ({ [propName]: { $re: insensitivePattern("eq", item) } }));
|
|
490
|
+
return operator === "in" ? { $or: conditions } : { $not: { $or: conditions } };
|
|
491
|
+
}
|
|
492
|
+
if (insensitive && value.every((item) => typeof item === "string")) {
|
|
493
|
+
const column = property.fieldNames[0] ?? propName;
|
|
494
|
+
return { [raw("lower(??)", [column])]: { [operator === "in" ? "$in" : "$nin"]: value.map((item) => item.toLowerCase()) } };
|
|
495
|
+
}
|
|
496
|
+
return { [propName]: { [operator === "in" ? "$in" : "$nin"]: value } };
|
|
497
|
+
}
|
|
498
|
+
if (insensitive && typeof value === "string" && [
|
|
499
|
+
"eq",
|
|
500
|
+
"ne",
|
|
501
|
+
"contains",
|
|
502
|
+
"starts_with",
|
|
503
|
+
"ends_with"
|
|
504
|
+
].includes(operator) && context.mongo) {
|
|
505
|
+
const condition = { [propName]: { $re: insensitivePattern(operator, value) } };
|
|
506
|
+
return operator === "ne" ? { $not: condition } : condition;
|
|
507
|
+
}
|
|
508
|
+
if (insensitive && typeof value === "string" && [
|
|
509
|
+
"eq",
|
|
510
|
+
"ne",
|
|
511
|
+
"contains",
|
|
512
|
+
"starts_with",
|
|
513
|
+
"ends_with"
|
|
514
|
+
].includes(operator)) {
|
|
515
|
+
const column = property.fieldNames[0] ?? propName;
|
|
516
|
+
const normalized = value.toLowerCase();
|
|
517
|
+
const transformedValue = operator === "contains" ? `%${normalized}%` : operator === "starts_with" ? `${normalized}%` : operator === "ends_with" ? `%${normalized}` : normalized;
|
|
518
|
+
return { [raw("lower(??)", [column])]: { [operator === "ne" ? "$ne" : operator === "eq" ? "$eq" : "$like"]: transformedValue } };
|
|
519
|
+
}
|
|
520
|
+
if ([
|
|
521
|
+
"contains",
|
|
522
|
+
"starts_with",
|
|
523
|
+
"ends_with"
|
|
524
|
+
].includes(operator)) {
|
|
525
|
+
if (typeof value !== "string") throw new TypeError(`The value for "${field}" must be a string when using "${operator}".`);
|
|
526
|
+
if (context.mongo) {
|
|
527
|
+
const escaped = escapeRegExp(value);
|
|
528
|
+
const pattern = operator === "contains" ? new RegExp(escaped) : operator === "starts_with" ? new RegExp(`^${escaped}`) : new RegExp(`${escaped}$`);
|
|
529
|
+
return { [propName]: { $re: pattern } };
|
|
530
|
+
}
|
|
531
|
+
if (operator === "contains") return { [propName]: { $like: `%${value}%` } };
|
|
532
|
+
if (operator === "starts_with") return { [propName]: { $like: `${value}%` } };
|
|
533
|
+
return { [propName]: { $like: `%${value}` } };
|
|
534
|
+
}
|
|
535
|
+
const mikroOperator = operator === "eq" ? "$eq" : `$${operator}`;
|
|
536
|
+
return { [propName]: { [mikroOperator]: value } };
|
|
537
|
+
}
|
|
538
|
+
function transformWhere(where, context) {
|
|
539
|
+
if (!where?.length) return {};
|
|
540
|
+
const conditions = where.map((condition) => ({
|
|
541
|
+
connector: condition.connector ?? "AND",
|
|
542
|
+
filter: transformCondition(condition, context)
|
|
543
|
+
}));
|
|
544
|
+
if (conditions.length === 1) return conditions[0].filter;
|
|
545
|
+
const andConditions = conditions.filter(({ connector }) => connector === "AND").map(({ filter }) => filter);
|
|
546
|
+
const orConditions = conditions.filter(({ connector }) => connector === "OR").map(({ filter }) => filter);
|
|
547
|
+
if (andConditions.length && orConditions.length) return { $and: [...andConditions, { $or: orConditions }] };
|
|
548
|
+
if (orConditions.length) return { $or: orConditions };
|
|
549
|
+
return { $and: andConditions };
|
|
550
|
+
}
|
|
551
|
+
//#endregion
|
|
552
|
+
//#region src/adapter/utils.ts
|
|
553
|
+
function getEntityManager(provider) {
|
|
554
|
+
const target = typeof provider === "function" ? provider() : provider;
|
|
555
|
+
if (target && typeof target === "object" && "em" in target && target.em) {
|
|
556
|
+
const orm = target;
|
|
557
|
+
return RequestContext.getEntityManager() ?? (typeof orm.em.fork === "function" ? orm.em.fork() : orm.em);
|
|
558
|
+
}
|
|
559
|
+
return target;
|
|
560
|
+
}
|
|
561
|
+
function resolveEntity(em, model) {
|
|
562
|
+
const metadata = [...em.getMetadata().getAll().values()];
|
|
563
|
+
const lower = model.toLowerCase();
|
|
564
|
+
const entity = metadata.find((item) => item.tableName === model || item.className === model || item.name === model || item.tableName?.toLowerCase() === lower || item.className?.toLowerCase() === lower);
|
|
565
|
+
if (!entity) {
|
|
566
|
+
const registered = metadata.map(({ tableName, className, name }) => tableName || className || name).filter((name) => Boolean(name)).sort((a, b) => a.localeCompare(b)).join(", ");
|
|
567
|
+
throw new BetterAuthError(`No MikroORM entity is registered for Better Auth model "${model}". Registered entities: ${registered || "none"}.`);
|
|
568
|
+
}
|
|
569
|
+
return entity;
|
|
570
|
+
}
|
|
571
|
+
function toPlainObject(entity) {
|
|
572
|
+
const wrapped = wrap(entity, true);
|
|
573
|
+
return typeof wrapped?.toPOJO === "function" ? wrapped.toPOJO() : { ...entity };
|
|
574
|
+
}
|
|
575
|
+
function primaryKeyWhere(meta, entity) {
|
|
576
|
+
return Object.fromEntries(meta.primaryKeys.map((key) => [key, entity[key]]));
|
|
577
|
+
}
|
|
578
|
+
function isNoLockPlatform(name) {
|
|
579
|
+
const lower = name.toLowerCase();
|
|
580
|
+
return lower.includes("sqlite") || lower.includes("mongo") || lower.includes("libsql") || lower.includes("turso") || lower.includes("d1");
|
|
581
|
+
}
|
|
582
|
+
function supportsPessimisticLock(em, provider) {
|
|
583
|
+
if (provider) return !isNoLockPlatform(provider);
|
|
584
|
+
return !isNoLockPlatform(em.getPlatform().constructor.name);
|
|
585
|
+
}
|
|
586
|
+
function isMongo(em, provider) {
|
|
587
|
+
if (provider) return provider.toLowerCase().includes("mongo");
|
|
588
|
+
return em.getPlatform().constructor.name.toLowerCase().includes("mongo");
|
|
589
|
+
}
|
|
590
|
+
function toFilter(em, meta, where, provider) {
|
|
591
|
+
return transformWhere(where, {
|
|
592
|
+
meta,
|
|
593
|
+
mongo: isMongo(em, provider)
|
|
594
|
+
});
|
|
595
|
+
}
|
|
596
|
+
async function findOneForMutation(em, entity, where, provider) {
|
|
597
|
+
const options = supportsPessimisticLock(em, provider) ? { lockMode: LockMode.PESSIMISTIC_WRITE } : void 0;
|
|
598
|
+
return em.findOne(entity, where, options);
|
|
599
|
+
}
|
|
600
|
+
//#endregion
|
|
601
|
+
//#region src/adapter/joins.ts
|
|
602
|
+
/**
|
|
603
|
+
* Fetch and attach joined relations (1:1 and 1:M) to a single entity record.
|
|
604
|
+
*/
|
|
605
|
+
async function attachJoins(em, row, join) {
|
|
606
|
+
const [result] = await attachJoinsMany(em, [row], join);
|
|
607
|
+
return result ?? row;
|
|
608
|
+
}
|
|
609
|
+
/**
|
|
610
|
+
* Fetch and attach joined relations for multiple entity records in batches.
|
|
611
|
+
* Uses a single WHERE ... IN (...) query per relation model when possible.
|
|
612
|
+
*/
|
|
613
|
+
async function attachJoinsMany(em, rows, join) {
|
|
614
|
+
if (!join || rows.length === 0) return rows;
|
|
615
|
+
const results = rows.map((row) => ({ ...row }));
|
|
616
|
+
for (const [joinedModel, config] of Object.entries(join)) {
|
|
617
|
+
const isOneToOne = config.relation === "one-to-one";
|
|
618
|
+
const hasLimit = config.limit != null;
|
|
619
|
+
if (!isOneToOne && hasLimit) {
|
|
620
|
+
await Promise.all(results.map(async (row) => {
|
|
621
|
+
const sourceValue = row[config.on.from];
|
|
622
|
+
if (sourceValue == null) {
|
|
623
|
+
row[joinedModel] = [];
|
|
624
|
+
return;
|
|
625
|
+
}
|
|
626
|
+
const joinedMeta = resolveEntity(em, joinedModel);
|
|
627
|
+
const matches = await em.find(joinedMeta.class, { [config.on.to]: sourceValue }, {
|
|
628
|
+
disableIdentityMap: true,
|
|
629
|
+
limit: config.limit
|
|
630
|
+
});
|
|
631
|
+
row[joinedModel] = matches.map((match) => toPlainObject(match));
|
|
632
|
+
}));
|
|
633
|
+
continue;
|
|
634
|
+
}
|
|
635
|
+
const sourceValues = Array.from(new Set(results.map((row) => row[config.on.from]).filter((value) => value != null)));
|
|
636
|
+
if (sourceValues.length === 0) {
|
|
637
|
+
for (const row of results) row[joinedModel] = isOneToOne ? null : [];
|
|
638
|
+
continue;
|
|
639
|
+
}
|
|
640
|
+
const joinedMeta = resolveEntity(em, joinedModel);
|
|
641
|
+
const filter = sourceValues.length === 1 ? { [config.on.to]: sourceValues[0] } : { [config.on.to]: { $in: sourceValues } };
|
|
642
|
+
const matches = await em.find(joinedMeta.class, filter, { disableIdentityMap: true });
|
|
643
|
+
const grouped = /* @__PURE__ */ new Map();
|
|
644
|
+
for (const match of matches) {
|
|
645
|
+
const plain = toPlainObject(match);
|
|
646
|
+
const key = plain[config.on.to];
|
|
647
|
+
let list = grouped.get(key);
|
|
648
|
+
if (!list) {
|
|
649
|
+
list = [];
|
|
650
|
+
grouped.set(key, list);
|
|
651
|
+
}
|
|
652
|
+
list.push(plain);
|
|
653
|
+
}
|
|
654
|
+
for (const row of results) {
|
|
655
|
+
const sourceKey = row[config.on.from];
|
|
656
|
+
const items = sourceKey != null ? grouped.get(sourceKey) ?? [] : [];
|
|
657
|
+
row[joinedModel] = isOneToOne ? items[0] ?? null : items;
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
return results;
|
|
661
|
+
}
|
|
662
|
+
/**
|
|
663
|
+
* Filter an entity record to include only selected fields plus joined relations.
|
|
664
|
+
*/
|
|
665
|
+
function selectFields(row, select, join, getSelectedFieldName) {
|
|
666
|
+
if (!select) return row;
|
|
667
|
+
const selected = Object.fromEntries(select.map((field) => {
|
|
668
|
+
const selectedField = getSelectedFieldName(field);
|
|
669
|
+
return [selectedField, row[selectedField]];
|
|
670
|
+
}));
|
|
671
|
+
for (const joinedModel of Object.keys(join ?? {})) selected[joinedModel] = row[joinedModel];
|
|
672
|
+
return selected;
|
|
673
|
+
}
|
|
674
|
+
//#endregion
|
|
675
|
+
//#region src/adapter/options.ts
|
|
676
|
+
const generatorOptions = Symbol.for("@a77ay/better-auth-mikro-orm/generator-options");
|
|
677
|
+
function attachGeneratorOptions(factory, options) {
|
|
678
|
+
Object.defineProperty(factory, generatorOptions, { value: options ?? {} });
|
|
679
|
+
return factory;
|
|
680
|
+
}
|
|
681
|
+
function readGeneratorOptions(value) {
|
|
682
|
+
if (typeof value !== "function") return void 0;
|
|
683
|
+
return value[generatorOptions];
|
|
684
|
+
}
|
|
685
|
+
//#endregion
|
|
686
|
+
//#region src/adapter/adapter.ts
|
|
687
|
+
function createOrmAdapter(provider, adapterOptions) {
|
|
688
|
+
return ({ getFieldName, options: authOptions }) => {
|
|
689
|
+
return {
|
|
690
|
+
create: async ({ data, model }) => {
|
|
691
|
+
const em = getEntityManager(provider);
|
|
692
|
+
const meta = resolveEntity(em, model);
|
|
693
|
+
const instance = em.create(meta.class, data);
|
|
694
|
+
em.persist(instance);
|
|
695
|
+
await em.flush();
|
|
696
|
+
return toPlainObject(await em.refresh(instance) ?? instance);
|
|
697
|
+
},
|
|
698
|
+
update: async ({ model, where, update }) => {
|
|
699
|
+
if (!where.length) return null;
|
|
700
|
+
const em = getEntityManager(provider);
|
|
701
|
+
const meta = resolveEntity(em, model);
|
|
702
|
+
const instance = await em.findOne(meta.class, toFilter(em, meta, where, adapterOptions?.provider));
|
|
703
|
+
if (!instance) return null;
|
|
704
|
+
wrap(instance).assign(update);
|
|
705
|
+
await em.flush();
|
|
706
|
+
return toPlainObject(instance);
|
|
707
|
+
},
|
|
708
|
+
updateMany: async ({ model, where, update }) => {
|
|
709
|
+
const em = getEntityManager(provider);
|
|
710
|
+
const meta = resolveEntity(em, model);
|
|
711
|
+
return em.nativeUpdate(meta.class, toFilter(em, meta, where, adapterOptions?.provider), update);
|
|
712
|
+
},
|
|
713
|
+
findOne: async (input) => {
|
|
714
|
+
const { model, where, select, join } = input;
|
|
715
|
+
const em = getEntityManager(provider);
|
|
716
|
+
const meta = resolveEntity(em, model);
|
|
717
|
+
const instance = await em.findOne(meta.class, toFilter(em, meta, where, adapterOptions?.provider), { disableIdentityMap: true });
|
|
718
|
+
if (!instance) return null;
|
|
719
|
+
return selectFields(await attachJoins(em, toPlainObject(instance), join), select, join, (field) => getFieldName({
|
|
720
|
+
model,
|
|
721
|
+
field
|
|
722
|
+
}));
|
|
723
|
+
},
|
|
724
|
+
findMany: async (input) => {
|
|
725
|
+
const { model, where, limit, select, sortBy, offset, join } = input;
|
|
726
|
+
const em = getEntityManager(provider);
|
|
727
|
+
const meta = resolveEntity(em, model);
|
|
728
|
+
return (await attachJoinsMany(em, (await em.find(meta.class, toFilter(em, meta, where, adapterOptions?.provider), {
|
|
729
|
+
disableIdentityMap: true,
|
|
730
|
+
limit,
|
|
731
|
+
offset,
|
|
732
|
+
...sortBy ? { orderBy: { [sortBy.field]: sortBy.direction } } : {}
|
|
733
|
+
})).map((instance) => toPlainObject(instance)), join)).map((result) => selectFields(result, select, join, (field) => getFieldName({
|
|
734
|
+
model,
|
|
735
|
+
field
|
|
736
|
+
})));
|
|
737
|
+
},
|
|
738
|
+
count: async ({ model, where }) => {
|
|
739
|
+
const em = getEntityManager(provider);
|
|
740
|
+
const meta = resolveEntity(em, model);
|
|
741
|
+
return em.count(meta.class, toFilter(em, meta, where, adapterOptions?.provider));
|
|
742
|
+
},
|
|
743
|
+
createSchema: async ({ tables, file }) => generateMikroOrmSchema({
|
|
744
|
+
tables,
|
|
745
|
+
file: file ?? adapterOptions?.schemaFile,
|
|
746
|
+
numericIds: adapterOptions?.supportsNumericIds ?? authOptions.advanced?.database?.generateId === "serial",
|
|
747
|
+
supportsArrays: adapterOptions?.supportsArrays ?? false,
|
|
748
|
+
supportsBooleans: adapterOptions?.supportsBooleans ?? true,
|
|
749
|
+
supportsDates: adapterOptions?.supportsDates ?? true,
|
|
750
|
+
supportsJSON: adapterOptions?.supportsJSON ?? true,
|
|
751
|
+
casing: adapterOptions?.casing,
|
|
752
|
+
entityStyle: adapterOptions?.entityStyle
|
|
753
|
+
}),
|
|
754
|
+
delete: async ({ model, where }) => {
|
|
755
|
+
if (!where.length) return;
|
|
756
|
+
const em = getEntityManager(provider);
|
|
757
|
+
const meta = resolveEntity(em, model);
|
|
758
|
+
const instance = await em.findOne(meta.class, toFilter(em, meta, where, adapterOptions?.provider));
|
|
759
|
+
if (!instance) return;
|
|
760
|
+
em.remove(instance);
|
|
761
|
+
await em.flush();
|
|
762
|
+
},
|
|
763
|
+
deleteMany: async ({ model, where }) => {
|
|
764
|
+
const em = getEntityManager(provider);
|
|
765
|
+
const meta = resolveEntity(em, model);
|
|
766
|
+
return em.nativeDelete(meta.class, toFilter(em, meta, where, adapterOptions?.provider));
|
|
767
|
+
},
|
|
768
|
+
consumeOne: async (input) => {
|
|
769
|
+
const { model, where } = input;
|
|
770
|
+
if (!where.length) return null;
|
|
771
|
+
const em = getEntityManager(provider);
|
|
772
|
+
const meta = resolveEntity(em, model);
|
|
773
|
+
const executeConsume = async (transaction) => {
|
|
774
|
+
const transformedWhere = toFilter(transaction, meta, where, adapterOptions?.provider);
|
|
775
|
+
const instance = await findOneForMutation(transaction, meta.class, transformedWhere, adapterOptions?.provider);
|
|
776
|
+
if (!instance) return null;
|
|
777
|
+
const result = toPlainObject(instance);
|
|
778
|
+
return await transaction.nativeDelete(meta.class, { $and: [transformedWhere, primaryKeyWhere(meta, instance)] }) === 1 ? result : null;
|
|
779
|
+
};
|
|
780
|
+
if (isMongo(em, adapterOptions?.provider)) return executeConsume(em);
|
|
781
|
+
return em.transactional(executeConsume);
|
|
782
|
+
},
|
|
783
|
+
incrementOne: async (input) => {
|
|
784
|
+
const { model, where, increment, set } = input;
|
|
785
|
+
if (!where.length) return null;
|
|
786
|
+
const em = getEntityManager(provider);
|
|
787
|
+
const meta = resolveEntity(em, model);
|
|
788
|
+
const executeIncrement = async (transaction) => {
|
|
789
|
+
const transformedWhere = toFilter(transaction, meta, where, adapterOptions?.provider);
|
|
790
|
+
const instance = await findOneForMutation(transaction, meta.class, transformedWhere, adapterOptions?.provider);
|
|
791
|
+
if (!instance) return null;
|
|
792
|
+
const update = {};
|
|
793
|
+
if (set) for (const [field, value] of Object.entries(set)) {
|
|
794
|
+
const key = findProperty(meta, field)?.name ?? field;
|
|
795
|
+
update[key] = value;
|
|
796
|
+
}
|
|
797
|
+
for (const [field, delta] of Object.entries(increment)) {
|
|
798
|
+
const property = findProperty(meta, field);
|
|
799
|
+
if (!property) throw new BetterAuthError(`No field "${field}" exists on MikroORM entity "${meta.className}".`);
|
|
800
|
+
if (isMongo(transaction, adapterOptions?.provider)) {
|
|
801
|
+
const current = instance[property.name];
|
|
802
|
+
if (typeof current !== "number") throw new TypeError(`Cannot increment non-numeric field "${field}" on "${model}".`);
|
|
803
|
+
update[property.name] = current + delta;
|
|
804
|
+
} else update[property.name] = raw("?? + ?", [property.fieldNames[0] ?? property.name, delta]);
|
|
805
|
+
}
|
|
806
|
+
const primaryWhere = primaryKeyWhere(meta, instance);
|
|
807
|
+
if (await transaction.nativeUpdate(meta.class, { $and: [transformedWhere, primaryWhere] }, update) === 0) return null;
|
|
808
|
+
const updated = await transaction.findOne(meta.class, primaryWhere, { refresh: true });
|
|
809
|
+
return updated ? toPlainObject(updated) : null;
|
|
810
|
+
};
|
|
811
|
+
if (isMongo(em, adapterOptions?.provider)) return executeIncrement(em);
|
|
812
|
+
return em.transactional(executeIncrement);
|
|
813
|
+
}
|
|
814
|
+
};
|
|
815
|
+
};
|
|
816
|
+
}
|
|
817
|
+
function mikroOrmAdapter(em, options) {
|
|
818
|
+
let betterAuthOptions;
|
|
819
|
+
const baseConfig = {
|
|
820
|
+
adapterId: "mikro-orm",
|
|
821
|
+
adapterName: "MikroORM Adapter",
|
|
822
|
+
debugLogs: options?.debugLogs ?? false,
|
|
823
|
+
usePlural: options?.usePlural ?? false,
|
|
824
|
+
supportsJSON: options?.supportsJSON ?? true,
|
|
825
|
+
supportsDates: options?.supportsDates ?? true,
|
|
826
|
+
supportsBooleans: options?.supportsBooleans ?? true,
|
|
827
|
+
supportsArrays: options?.supportsArrays ?? false,
|
|
828
|
+
supportsNumericIds: options?.supportsNumericIds ?? true,
|
|
829
|
+
transaction: options?.transactions === false ? false : async (callback) => {
|
|
830
|
+
if (!betterAuthOptions) throw new BetterAuthError("The MikroORM adapter has not been initialized by Better Auth.");
|
|
831
|
+
const authOptions = betterAuthOptions;
|
|
832
|
+
return getEntityManager(em).transactional(async (transaction) => {
|
|
833
|
+
return callback(createAdapterFactory({
|
|
834
|
+
config: {
|
|
835
|
+
...baseConfig,
|
|
836
|
+
transaction: false
|
|
837
|
+
},
|
|
838
|
+
adapter: createOrmAdapter(transaction, options)
|
|
839
|
+
})(authOptions));
|
|
840
|
+
});
|
|
841
|
+
}
|
|
842
|
+
};
|
|
843
|
+
const factory = createAdapterFactory({
|
|
844
|
+
config: baseConfig,
|
|
845
|
+
adapter: createOrmAdapter(em, options)
|
|
846
|
+
});
|
|
847
|
+
return attachGeneratorOptions((authOptions) => {
|
|
848
|
+
betterAuthOptions = authOptions;
|
|
849
|
+
return factory(authOptions);
|
|
850
|
+
}, options);
|
|
851
|
+
}
|
|
852
|
+
//#endregion
|
|
853
|
+
//#region src/cli/index.ts
|
|
854
|
+
const help = `better-auth-mikro-orm
|
|
855
|
+
|
|
856
|
+
Generate one MikroORM entity per file from a Better Auth configuration.
|
|
857
|
+
|
|
858
|
+
Usage:
|
|
859
|
+
better-auth-mikro-orm generate [options]
|
|
860
|
+
|
|
861
|
+
Options:
|
|
862
|
+
-c, --config <path> Better Auth config (default: ./src/auth.ts)
|
|
863
|
+
-o, --output <path> Output directory (default: src/entities/auth)
|
|
864
|
+
--style <style> define-entity or decorators
|
|
865
|
+
--casing <casing> camelCase or snake_case
|
|
866
|
+
--file-suffix <s> Custom entity file suffix (e.g. .entity)
|
|
867
|
+
-y, --yes Overwrite generated files without confirmation
|
|
868
|
+
-h, --help Show this help
|
|
869
|
+
`;
|
|
870
|
+
async function runCli(arguments_, io = {}) {
|
|
871
|
+
const { positionals, values } = parseArgs({
|
|
872
|
+
args: arguments_,
|
|
873
|
+
allowPositionals: true,
|
|
874
|
+
options: {
|
|
875
|
+
casing: { type: "string" },
|
|
876
|
+
config: {
|
|
877
|
+
type: "string",
|
|
878
|
+
short: "c",
|
|
879
|
+
default: "./src/auth.ts"
|
|
880
|
+
},
|
|
881
|
+
"file-suffix": { type: "string" },
|
|
882
|
+
fileSuffix: { type: "string" },
|
|
883
|
+
help: {
|
|
884
|
+
type: "boolean",
|
|
885
|
+
short: "h"
|
|
886
|
+
},
|
|
887
|
+
output: {
|
|
888
|
+
type: "string",
|
|
889
|
+
short: "o"
|
|
890
|
+
},
|
|
891
|
+
style: { type: "string" },
|
|
892
|
+
yes: {
|
|
893
|
+
type: "boolean",
|
|
894
|
+
short: "y",
|
|
895
|
+
default: false
|
|
896
|
+
}
|
|
897
|
+
},
|
|
898
|
+
strict: true
|
|
899
|
+
});
|
|
900
|
+
const write = io.stdout ?? ((message) => process.stdout.write(message));
|
|
901
|
+
if (values.help) {
|
|
902
|
+
write(help);
|
|
903
|
+
return 0;
|
|
904
|
+
}
|
|
905
|
+
if (positionals[0] !== "generate" || positionals.length !== 1) throw new Error(`Expected the "generate" command.\n\n${help}`);
|
|
906
|
+
const cwd = io.cwd ?? process.cwd();
|
|
907
|
+
const configPath = resolve(cwd, values.config);
|
|
908
|
+
const auth = findAuth(await createJiti(import.meta.url).import(configPath));
|
|
909
|
+
const adapterOptions = readGeneratorOptions(auth.options.database);
|
|
910
|
+
const entityStyle = parseEntityStyle(values.style ?? adapterOptions?.entityStyle);
|
|
911
|
+
const casing = parseCasing(values.casing ?? adapterOptions?.casing);
|
|
912
|
+
const directory = values.output ?? adapterOptions?.directory ?? "src/entities/auth";
|
|
913
|
+
const fileSuffix = values["file-suffix"] ?? values.fileSuffix ?? adapterOptions?.fileSuffix;
|
|
914
|
+
const generatorOptions = {
|
|
915
|
+
tables: getAuthTables(auth.options),
|
|
916
|
+
directory,
|
|
917
|
+
fileSuffix,
|
|
918
|
+
numericIds: adapterOptions?.supportsNumericIds ?? auth.options.advanced?.database?.generateId === "serial",
|
|
919
|
+
supportsArrays: adapterOptions?.supportsArrays ?? false,
|
|
920
|
+
supportsBooleans: adapterOptions?.supportsBooleans ?? true,
|
|
921
|
+
supportsDates: adapterOptions?.supportsDates ?? true,
|
|
922
|
+
supportsJSON: adapterOptions?.supportsJSON ?? true,
|
|
923
|
+
casing,
|
|
924
|
+
entityStyle
|
|
925
|
+
};
|
|
926
|
+
if (!values.yes) {
|
|
927
|
+
const generated = generateMikroOrmSchemaDirectory(generatorOptions);
|
|
928
|
+
const existing = await findExistingFile(cwd, generated.directory, generated.files);
|
|
929
|
+
if (existing) throw new Error(`Refusing to overwrite ${existing}. Pass --yes to overwrite generated files.`);
|
|
930
|
+
}
|
|
931
|
+
const generated = await writeMikroOrmSchemaDirectory({
|
|
932
|
+
...generatorOptions,
|
|
933
|
+
directory
|
|
934
|
+
});
|
|
935
|
+
write(`Generated ${generated.files.length - 1} entities and index.ts in ${generated.directory}\n`);
|
|
936
|
+
return 0;
|
|
937
|
+
}
|
|
938
|
+
function findAuth(module) {
|
|
939
|
+
const candidates = [
|
|
940
|
+
module.auth,
|
|
941
|
+
module.authConfig,
|
|
942
|
+
module.config,
|
|
943
|
+
module.default,
|
|
944
|
+
...Object.values(module)
|
|
945
|
+
];
|
|
946
|
+
for (const candidate of candidates) {
|
|
947
|
+
if (isAuthInstance(candidate)) return candidate;
|
|
948
|
+
if (isAuthOptions(candidate)) return { options: candidate };
|
|
949
|
+
}
|
|
950
|
+
throw new Error("The config must export a Better Auth instance or configuration, for example `export const auth = betterAuth(...)` or `export const authConfig = { ... }`.");
|
|
951
|
+
}
|
|
952
|
+
function isAuthInstance(value) {
|
|
953
|
+
return typeof value === "object" && value !== null && "options" in value && typeof value.options === "object" && value.options !== null;
|
|
954
|
+
}
|
|
955
|
+
function isAuthOptions(value) {
|
|
956
|
+
if (typeof value !== "object" || value === null) return false;
|
|
957
|
+
return "plugins" in value || "emailAndPassword" in value || "socialProviders" in value || "user" in value || "session" in value || "database" in value || "baseURL" in value || "secret" in value;
|
|
958
|
+
}
|
|
959
|
+
function parseEntityStyle(value) {
|
|
960
|
+
if (value === void 0 || value === "define-entity" || value === "decorators") return value ?? "define-entity";
|
|
961
|
+
throw new Error(`Invalid --style value "${value}". Use define-entity or decorators.`);
|
|
962
|
+
}
|
|
963
|
+
function parseCasing(value) {
|
|
964
|
+
if (value === void 0 || value === "camelCase" || value === "snake_case") return value ?? "camelCase";
|
|
965
|
+
throw new Error(`Invalid --casing value "${value}". Use camelCase or snake_case.`);
|
|
966
|
+
}
|
|
967
|
+
async function findExistingFile(cwd, directory, files) {
|
|
968
|
+
for (const file of files) {
|
|
969
|
+
const path = resolve(cwd, directory, file.path);
|
|
970
|
+
try {
|
|
971
|
+
await access(path);
|
|
972
|
+
return path;
|
|
973
|
+
} catch {}
|
|
974
|
+
}
|
|
975
|
+
}
|
|
976
|
+
//#endregion
|
|
977
|
+
export { getEntityManager as a, generateMikroOrmSchemaDirectory as c, readGeneratorOptions as i, writeMikroOrmSchemaDirectory as l, mikroOrmAdapter as n, resolveEntity as o, attachGeneratorOptions as r, generateMikroOrmSchema as s, runCli as t };
|