auth 1.2.2 → 1.5.0-beta.15

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,661 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import fs$1 from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { initGetFieldName, initGetModelName } from "better-auth/adapters";
5
+ import { getAuthTables } from "better-auth/db";
6
+ import prettier from "prettier";
7
+ import { getMigrations } from "better-auth/db/migration";
8
+ import { capitalizeFirstLetter } from "@better-auth/core/utils/string";
9
+ import { produceSchema } from "@mrleebo/prisma-ast";
10
+ import { spawn } from "node:child_process";
11
+ import Crypto from "node:crypto";
12
+
13
+ //#region src/generators/drizzle.ts
14
+ function convertToSnakeCase(str, camelCase) {
15
+ if (camelCase) return str;
16
+ return str.replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").replace(/([a-z\d])([A-Z])/g, "$1_$2").toLowerCase();
17
+ }
18
+ const generateDrizzleSchema = async ({ options, file, adapter }) => {
19
+ const tables = getAuthTables(options);
20
+ const filePath = file || "./auth-schema.ts";
21
+ const databaseType = adapter.options?.provider;
22
+ if (!databaseType) throw new Error(`Database provider type is undefined during Drizzle schema generation. Please define a \`provider\` in the Drizzle adapter config. Read more at https://better-auth.com/docs/adapters/drizzle`);
23
+ const fileExist = existsSync(filePath);
24
+ let code = generateImport({
25
+ databaseType,
26
+ tables,
27
+ options
28
+ });
29
+ const getModelName = initGetModelName({
30
+ schema: tables,
31
+ usePlural: adapter.options?.adapterConfig?.usePlural
32
+ });
33
+ const getFieldName = initGetFieldName({
34
+ schema: tables,
35
+ usePlural: adapter.options?.adapterConfig?.usePlural
36
+ });
37
+ for (const tableKey in tables) {
38
+ const table = tables[tableKey];
39
+ const modelName = getModelName(tableKey);
40
+ const fields = table.fields;
41
+ function getType(name, field) {
42
+ if (!databaseType) throw new Error(`Database provider type is undefined during Drizzle schema generation. Please define a \`provider\` in the Drizzle adapter config. Read more at https://better-auth.com/docs/adapters/drizzle`);
43
+ name = convertToSnakeCase(name, adapter.options?.camelCase);
44
+ if (field.references?.field === "id") {
45
+ const useNumberId = options.advanced?.database?.generateId === "serial";
46
+ const useUUIDs = options.advanced?.database?.generateId === "uuid";
47
+ if (useNumberId) if (databaseType === "pg") return `integer('${name}')`;
48
+ else if (databaseType === "mysql") return `int('${name}')`;
49
+ else return `integer('${name}')`;
50
+ if (useUUIDs && databaseType === "pg") return `uuid('${name}')`;
51
+ if (field.references.field) {
52
+ if (databaseType === "mysql") return `varchar('${name}', { length: 36 })`;
53
+ }
54
+ return `text('${name}')`;
55
+ }
56
+ const type = field.type;
57
+ if (typeof type !== "string") if (Array.isArray(type) && type.every((x) => typeof x === "string")) return {
58
+ sqlite: `text({ enum: [${type.map((x) => `'${x}'`).join(", ")}] })`,
59
+ pg: `text('${name}', { enum: [${type.map((x) => `'${x}'`).join(", ")}] })`,
60
+ mysql: `mysqlEnum([${type.map((x) => `'${x}'`).join(", ")}])`
61
+ }[databaseType];
62
+ else throw new TypeError(`Invalid field type for field ${name} in model ${modelName}`);
63
+ const dbTypeMap = {
64
+ string: {
65
+ sqlite: `text('${name}')`,
66
+ pg: `text('${name}')`,
67
+ mysql: field.unique ? `varchar('${name}', { length: 255 })` : field.references ? `varchar('${name}', { length: 36 })` : field.sortable ? `varchar('${name}', { length: 255 })` : field.index ? `varchar('${name}', { length: 255 })` : `text('${name}')`
68
+ },
69
+ boolean: {
70
+ sqlite: `integer('${name}', { mode: 'boolean' })`,
71
+ pg: `boolean('${name}')`,
72
+ mysql: `boolean('${name}')`
73
+ },
74
+ number: {
75
+ sqlite: `integer('${name}')`,
76
+ pg: field.bigint ? `bigint('${name}', { mode: 'number' })` : `integer('${name}')`,
77
+ mysql: field.bigint ? `bigint('${name}', { mode: 'number' })` : `int('${name}')`
78
+ },
79
+ date: {
80
+ sqlite: `integer('${name}', { mode: 'timestamp_ms' })`,
81
+ pg: `timestamp('${name}')`,
82
+ mysql: `timestamp('${name}', { fsp: 3 })`
83
+ },
84
+ "number[]": {
85
+ sqlite: `text('${name}', { mode: "json" })`,
86
+ pg: field.bigint ? `bigint('${name}', { mode: 'number' }).array()` : `integer('${name}').array()`,
87
+ mysql: `text('${name}', { mode: 'json' })`
88
+ },
89
+ "string[]": {
90
+ sqlite: `text('${name}', { mode: "json" })`,
91
+ pg: `text('${name}').array()`,
92
+ mysql: `text('${name}', { mode: "json" })`
93
+ },
94
+ json: {
95
+ sqlite: `text('${name}', { mode: "json" })`,
96
+ pg: `jsonb('${name}')`,
97
+ mysql: `json('${name}', { mode: "json" })`
98
+ }
99
+ }[type];
100
+ if (!dbTypeMap) throw new Error(`Unsupported field type '${field.type}' for field '${name}'.`);
101
+ return dbTypeMap[databaseType];
102
+ }
103
+ let id = "";
104
+ const useNumberId = options.advanced?.database?.generateId === "serial";
105
+ if (options.advanced?.database?.generateId === "uuid" && databaseType === "pg") id = `uuid("id").default(sql\`pg_catalog.gen_random_uuid()\`).primaryKey()`;
106
+ else if (useNumberId) if (databaseType === "pg") id = `integer("id").generatedByDefaultAsIdentity().primaryKey()`;
107
+ else if (databaseType === "sqlite") id = `integer("id", { mode: "number" }).primaryKey({ autoIncrement: true })`;
108
+ else id = `int("id").autoincrement().primaryKey()`;
109
+ else if (databaseType === "mysql") id = `varchar('id', { length: 36 }).primaryKey()`;
110
+ else if (databaseType === "pg") id = `text('id').primaryKey()`;
111
+ else id = `text('id').primaryKey()`;
112
+ const indexes = [];
113
+ const assignIndexes = (indexes) => {
114
+ if (!indexes.length) return "";
115
+ const code = [`, (table) => [`];
116
+ for (const index of indexes) code.push(` ${index.type}("${index.name}").on(table.${index.on}),`);
117
+ code.push(`]`);
118
+ return code.join("\n");
119
+ };
120
+ const schema = `export const ${modelName} = ${databaseType}Table("${convertToSnakeCase(modelName, adapter.options?.camelCase)}", {
121
+ id: ${id},
122
+ ${Object.keys(fields).map((field) => {
123
+ const attr = fields[field];
124
+ const fieldName = attr.fieldName || field;
125
+ let type = getType(fieldName, attr);
126
+ if (attr.index && !attr.unique) indexes.push({
127
+ type: "index",
128
+ name: `${modelName}_${fieldName}_idx`,
129
+ on: fieldName
130
+ });
131
+ else if (attr.index && attr.unique) indexes.push({
132
+ type: "uniqueIndex",
133
+ name: `${modelName}_${fieldName}_uidx`,
134
+ on: fieldName
135
+ });
136
+ if (attr.defaultValue !== null && typeof attr.defaultValue !== "undefined") if (typeof attr.defaultValue === "function") {
137
+ if (attr.type === "date" && attr.defaultValue.toString().includes("new Date()")) if (databaseType === "sqlite") type += `.default(sql\`(cast(unixepoch('subsecond') * 1000 as integer))\`)`;
138
+ else type += `.defaultNow()`;
139
+ } else if (typeof attr.defaultValue === "string") type += `.default("${attr.defaultValue}")`;
140
+ else type += `.default(${attr.defaultValue})`;
141
+ if (attr.onUpdate && attr.type === "date") {
142
+ if (typeof attr.onUpdate === "function") type += `.$onUpdate(${attr.onUpdate})`;
143
+ }
144
+ return `${fieldName}: ${type}${attr.required ? ".notNull()" : ""}${attr.unique ? ".unique()" : ""}${attr.references ? `.references(()=> ${getModelName(attr.references.model)}.${getFieldName({
145
+ model: attr.references.model,
146
+ field: attr.references.field
147
+ })}, { onDelete: '${attr.references.onDelete || "cascade"}' })` : ""}`;
148
+ }).join(",\n ")}
149
+ }${assignIndexes(indexes)});`;
150
+ code += `\n${schema}\n`;
151
+ }
152
+ let relationsString = "";
153
+ for (const tableKey in tables) {
154
+ const table = tables[tableKey];
155
+ const modelName = getModelName(tableKey);
156
+ const oneRelations = [];
157
+ const manyRelations = [];
158
+ const manyRelationsSet = /* @__PURE__ */ new Set();
159
+ const foreignFields = Object.entries(table.fields).filter(([_, field]) => field.references);
160
+ for (const [fieldName, field] of foreignFields) {
161
+ const referencedModel = field.references.model;
162
+ const relationKey = getModelName(referencedModel);
163
+ const fieldRef = `${getModelName(tableKey)}.${getFieldName({
164
+ model: tableKey,
165
+ field: fieldName
166
+ })}`;
167
+ const referenceRef = `${getModelName(referencedModel)}.${getFieldName({
168
+ model: referencedModel,
169
+ field: field.references.field || "id"
170
+ })}`;
171
+ oneRelations.push({
172
+ key: relationKey,
173
+ model: getModelName(referencedModel),
174
+ type: "one",
175
+ reference: {
176
+ field: fieldRef,
177
+ references: referenceRef,
178
+ fieldName
179
+ }
180
+ });
181
+ }
182
+ const otherModels = Object.entries(tables).filter(([modelName]) => modelName !== tableKey);
183
+ const modelRelationsMap = /* @__PURE__ */ new Map();
184
+ for (const [modelName, otherTable] of otherModels) {
185
+ const foreignKeysPointingHere = Object.entries(otherTable.fields).filter(([_, field]) => field.references?.model === tableKey || field.references?.model === getModelName(tableKey));
186
+ if (foreignKeysPointingHere.length === 0) continue;
187
+ const hasUnique = foreignKeysPointingHere.some(([_, field]) => !!field.unique);
188
+ const hasMany = foreignKeysPointingHere.some(([_, field]) => !field.unique);
189
+ modelRelationsMap.set(modelName, {
190
+ modelName,
191
+ hasUnique,
192
+ hasMany
193
+ });
194
+ }
195
+ for (const { modelName, hasMany } of modelRelationsMap.values()) {
196
+ const relationType = hasMany ? "many" : "one";
197
+ let relationKey = getModelName(modelName);
198
+ if (!adapter.options?.adapterConfig?.usePlural && relationType === "many") relationKey = `${relationKey}s`;
199
+ if (!manyRelationsSet.has(relationKey)) {
200
+ manyRelationsSet.add(relationKey);
201
+ manyRelations.push({
202
+ key: relationKey,
203
+ model: getModelName(modelName),
204
+ type: relationType
205
+ });
206
+ }
207
+ }
208
+ const relationsByModel = /* @__PURE__ */ new Map();
209
+ for (const relation of oneRelations) if (relation.reference) {
210
+ const modelKey = relation.key;
211
+ if (!relationsByModel.has(modelKey)) relationsByModel.set(modelKey, []);
212
+ relationsByModel.get(modelKey).push(relation);
213
+ }
214
+ const duplicateRelations = [];
215
+ const singleRelations = [];
216
+ for (const [_modelKey, relations] of relationsByModel.entries()) if (relations.length > 1) duplicateRelations.push(...relations);
217
+ else singleRelations.push(relations[0]);
218
+ for (const relation of duplicateRelations) if (relation.reference) {
219
+ const fieldName = relation.reference.fieldName;
220
+ const tableRelation = `export const ${`${modelName}${fieldName.charAt(0).toUpperCase() + fieldName.slice(1)}Relations`} = relations(${getModelName(table.modelName)}, ({ one }) => ({
221
+ ${relation.key}: one(${relation.model}, {
222
+ fields: [${relation.reference.field}],
223
+ references: [${relation.reference.references}],
224
+ })
225
+ }))`;
226
+ relationsString += `\n${tableRelation}\n`;
227
+ }
228
+ const hasOne = singleRelations.length > 0;
229
+ const hasMany = manyRelations.length > 0;
230
+ if (hasOne && hasMany) {
231
+ const tableRelation = `export const ${modelName}Relations = relations(${getModelName(table.modelName)}, ({ one, many }) => ({
232
+ ${singleRelations.map((relation) => relation.reference ? ` ${relation.key}: one(${relation.model}, {
233
+ fields: [${relation.reference.field}],
234
+ references: [${relation.reference.references}],
235
+ })` : "").filter((x) => x !== "").join(",\n ")}${singleRelations.length > 0 && manyRelations.length > 0 ? "," : ""}
236
+ ${manyRelations.map(({ key, model }) => ` ${key}: many(${model})`).join(",\n ")}
237
+ }))`;
238
+ relationsString += `\n${tableRelation}\n`;
239
+ } else if (hasOne) {
240
+ const tableRelation = `export const ${modelName}Relations = relations(${getModelName(table.modelName)}, ({ one }) => ({
241
+ ${singleRelations.map((relation) => relation.reference ? ` ${relation.key}: one(${relation.model}, {
242
+ fields: [${relation.reference.field}],
243
+ references: [${relation.reference.references}],
244
+ })` : "").filter((x) => x !== "").join(",\n ")}
245
+ }))`;
246
+ relationsString += `\n${tableRelation}\n`;
247
+ } else if (hasMany) {
248
+ const tableRelation = `export const ${modelName}Relations = relations(${getModelName(table.modelName)}, ({ many }) => ({
249
+ ${manyRelations.map(({ key, model }) => ` ${key}: many(${model})`).join(",\n ")}
250
+ }))`;
251
+ relationsString += `\n${tableRelation}\n`;
252
+ }
253
+ }
254
+ code += `\n${relationsString}`;
255
+ return {
256
+ code: await prettier.format(code, { parser: "typescript" }),
257
+ fileName: filePath,
258
+ overwrite: fileExist
259
+ };
260
+ };
261
+ function generateImport({ databaseType, tables, options }) {
262
+ const rootImports = ["relations"];
263
+ const coreImports = [];
264
+ let hasBigint = false;
265
+ let hasJson = false;
266
+ for (const table of Object.values(tables)) {
267
+ for (const field of Object.values(table.fields)) {
268
+ if (field.bigint) hasBigint = true;
269
+ if (field.type === "json") hasJson = true;
270
+ }
271
+ if (hasJson && hasBigint) break;
272
+ }
273
+ const useNumberId = options.advanced?.database?.generateId === "serial";
274
+ const useUUIDs = options.advanced?.database?.generateId === "uuid";
275
+ coreImports.push(`${databaseType}Table`);
276
+ coreImports.push(databaseType === "mysql" ? "varchar, text" : databaseType === "pg" ? "text" : "text");
277
+ coreImports.push(hasBigint ? databaseType !== "sqlite" ? "bigint" : "" : "");
278
+ coreImports.push(databaseType !== "sqlite" ? "timestamp, boolean" : "");
279
+ if (databaseType === "mysql") {
280
+ const hasNonBigintNumber = Object.values(tables).some((table) => Object.values(table.fields).some((field) => (field.type === "number" || field.type === "number[]") && !field.bigint));
281
+ if (useNumberId || hasNonBigintNumber) coreImports.push("int");
282
+ if (Object.values(tables).some((table) => Object.values(table.fields).some((field) => typeof field.type !== "string" && Array.isArray(field.type) && field.type.every((x) => typeof x === "string")))) coreImports.push("mysqlEnum");
283
+ } else if (databaseType === "pg") {
284
+ if (useUUIDs) rootImports.push("sql");
285
+ const hasNonBigintNumber = Object.values(tables).some((table) => Object.values(table.fields).some((field) => (field.type === "number" || field.type === "number[]") && !field.bigint));
286
+ const hasFkToId = Object.values(tables).some((table) => Object.values(table.fields).some((field) => field.references?.field === "id"));
287
+ if (hasNonBigintNumber || options.advanced?.database?.generateId === "serial" && hasFkToId) coreImports.push("integer");
288
+ } else coreImports.push("integer");
289
+ if (databaseType === "pg" && useUUIDs) coreImports.push("uuid");
290
+ if (hasJson) {
291
+ if (databaseType === "pg") coreImports.push("jsonb");
292
+ if (databaseType === "mysql") coreImports.push("json");
293
+ }
294
+ if (databaseType === "sqlite" && Object.values(tables).some((table) => Object.values(table.fields).some((field) => field.type === "date" && field.defaultValue && typeof field.defaultValue === "function" && field.defaultValue.toString().includes("new Date()")))) rootImports.push("sql");
295
+ const hasIndexes = Object.values(tables).some((table) => Object.values(table.fields).some((field) => field.index && !field.unique));
296
+ const hasUniqueIndexes = Object.values(tables).some((table) => Object.values(table.fields).some((field) => field.unique && field.index));
297
+ if (hasIndexes) coreImports.push("index");
298
+ if (hasUniqueIndexes) coreImports.push("uniqueIndex");
299
+ return `${rootImports.length > 0 ? `import { ${rootImports.join(", ")} } from "drizzle-orm";\n` : ""}import { ${coreImports.map((x) => x.trim()).filter((x) => x !== "").join(", ")} } from "drizzle-orm/${databaseType}-core";\n`;
300
+ }
301
+
302
+ //#endregion
303
+ //#region src/generators/kysely.ts
304
+ const generateKyselySchema = async ({ options, file }) => {
305
+ const { compileMigrations } = await getMigrations(options);
306
+ const migrations = await compileMigrations();
307
+ return {
308
+ code: migrations.trim() === ";" ? "" : migrations,
309
+ fileName: file || `./better-auth_migrations/${(/* @__PURE__ */ new Date()).toISOString().replace(/:/g, "-")}.sql`
310
+ };
311
+ };
312
+
313
+ //#endregion
314
+ //#region src/utils/helper.ts
315
+ async function tryCatch(promise) {
316
+ try {
317
+ return {
318
+ data: await promise,
319
+ error: null
320
+ };
321
+ } catch (error) {
322
+ return {
323
+ data: null,
324
+ error
325
+ };
326
+ }
327
+ }
328
+ const generateSecretHash = () => {
329
+ return Crypto.randomBytes(16).toString("hex");
330
+ };
331
+ const spawnCommand = (cmd, cwd = process.cwd()) => new Promise((resolve, reject) => {
332
+ const child = spawn(cmd, {
333
+ cwd,
334
+ stdio: "inherit",
335
+ shell: true
336
+ });
337
+ child.on("close", (code, signal) => {
338
+ if (code !== 0 && code !== null) reject(/* @__PURE__ */ new Error(`Exited with code ${code}`));
339
+ else if (signal) reject(/* @__PURE__ */ new Error(`Killed with signal ${signal}`));
340
+ else resolve();
341
+ });
342
+ child.on("error", reject);
343
+ });
344
+
345
+ //#endregion
346
+ //#region src/utils/get-package-info.ts
347
+ function getPackageInfo(cwd) {
348
+ const packageJsonPath = cwd ? path.join(cwd, "package.json") : path.join("package.json");
349
+ return JSON.parse(readFileSync(packageJsonPath, "utf-8"));
350
+ }
351
+ function getPrismaVersion(cwd) {
352
+ try {
353
+ const packageInfo = getPackageInfo(cwd);
354
+ const prismaVersion = packageInfo.dependencies?.prisma || packageInfo.devDependencies?.prisma || packageInfo.dependencies?.["@prisma/client"] || packageInfo.devDependencies?.["@prisma/client"];
355
+ if (!prismaVersion) return null;
356
+ const match = prismaVersion.match(/(\d+)/);
357
+ return match ? parseInt(match[1], 10) : null;
358
+ } catch {
359
+ return null;
360
+ }
361
+ }
362
+ /**
363
+ * Checks if a package has a specific dependency.
364
+ *
365
+ * @param packageJson The package.json object
366
+ * @param dependency The dependency to check for
367
+ * @returns true if the package has the dependency
368
+ */
369
+ function hasDependency(packageJson, dependency) {
370
+ let hasDependency = false;
371
+ if (packageJson.dependencies?.[dependency] || packageJson.devDependencies?.[dependency] || packageJson.peerDependencies?.[dependency] || packageJson.optionalDependencies?.[dependency]) hasDependency = true;
372
+ return hasDependency;
373
+ }
374
+ /**
375
+ * Checks if a directory is a monorepo root by looking for common monorepo indicators.
376
+ *
377
+ * @param dir Directory to check
378
+ * @returns true if the directory appears to be a monorepo root
379
+ */
380
+ async function isMonorepoRoot(dir) {
381
+ const { data: files } = await tryCatch(fs$1.readdir(dir, "utf-8"));
382
+ if (!files) return false;
383
+ if (files.includes("pnpm-workspace.yaml")) return true;
384
+ if (files.includes("package.json")) {
385
+ const packageJsonPath = path.join(dir, "package.json");
386
+ const { data } = await tryCatch(fs$1.readFile(packageJsonPath, "utf-8"));
387
+ if (data) try {
388
+ const packageJson = JSON.parse(data);
389
+ if (packageJson.workspaces && (Array.isArray(packageJson.workspaces) || typeof packageJson.workspaces === "object")) return true;
390
+ } catch {}
391
+ }
392
+ return [
393
+ "lerna.json",
394
+ "turbo.json",
395
+ "nx.json",
396
+ "rush.json"
397
+ ].some((indicator) => files.includes(indicator));
398
+ }
399
+ /**
400
+ * Finds the monorepo root by walking up the directory tree.
401
+ *
402
+ * @param startDir Starting directory
403
+ * @returns Path to monorepo root, or null if not found
404
+ */
405
+ async function findMonorepoRoot(startDir) {
406
+ let currentDir = path.resolve(startDir);
407
+ const root = path.parse(currentDir).root;
408
+ while (currentDir !== root) {
409
+ if (await isMonorepoRoot(currentDir)) return currentDir;
410
+ const parentDir = path.dirname(currentDir);
411
+ if (parentDir === currentDir) break;
412
+ currentDir = parentDir;
413
+ }
414
+ return null;
415
+ }
416
+
417
+ //#endregion
418
+ //#region src/generators/prisma.ts
419
+ const generatePrismaSchema = async ({ adapter, options, file }) => {
420
+ const provider = adapter.options?.provider || "postgresql";
421
+ const tables = getAuthTables(options);
422
+ const filePath = file || "./prisma/schema.prisma";
423
+ const schemaPrismaExist = existsSync(path.join(process.cwd(), filePath));
424
+ const getModelName = initGetModelName({
425
+ schema: getAuthTables(options),
426
+ usePlural: adapter.options?.adapterConfig?.usePlural
427
+ });
428
+ const getFieldName = initGetFieldName({
429
+ schema: getAuthTables(options),
430
+ usePlural: false
431
+ });
432
+ let schemaPrisma = "";
433
+ if (schemaPrismaExist) schemaPrisma = await fs$1.readFile(path.join(process.cwd(), filePath), "utf-8");
434
+ else schemaPrisma = getNewPrisma(provider, process.cwd());
435
+ const prismaVersion = getPrismaVersion(process.cwd());
436
+ if (prismaVersion && prismaVersion >= 7 && schemaPrismaExist) schemaPrisma = produceSchema(schemaPrisma, (builder) => {
437
+ const generator = builder.findByType("generator", { name: "client" });
438
+ if (generator && generator.properties) {
439
+ const providerProp = generator.properties.find((prop) => prop.type === "assignment" && prop.key === "provider");
440
+ if (providerProp && providerProp.value === "\"prisma-client-js\"") providerProp.value = "\"prisma-client\"";
441
+ }
442
+ });
443
+ const manyToManyRelations = /* @__PURE__ */ new Map();
444
+ for (const table in tables) {
445
+ const fields = tables[table]?.fields;
446
+ for (const field in fields) {
447
+ const attr = fields[field];
448
+ if (attr.references) {
449
+ const referencedOriginalModel = attr.references.model;
450
+ const referencedModelNameCap = capitalizeFirstLetter(getModelName(tables[referencedOriginalModel]?.modelName || referencedOriginalModel));
451
+ if (!manyToManyRelations.has(referencedModelNameCap)) manyToManyRelations.set(referencedModelNameCap, /* @__PURE__ */ new Set());
452
+ const currentModelNameCap = capitalizeFirstLetter(getModelName(tables[table]?.modelName || table));
453
+ manyToManyRelations.get(referencedModelNameCap).add(currentModelNameCap);
454
+ }
455
+ }
456
+ }
457
+ const indexedFields = /* @__PURE__ */ new Map();
458
+ for (const table in tables) {
459
+ const fields = tables[table]?.fields;
460
+ const modelName = capitalizeFirstLetter(getModelName(tables[table]?.modelName || table));
461
+ indexedFields.set(modelName, []);
462
+ for (const field in fields) {
463
+ const attr = fields[field];
464
+ if (attr.index && !attr.unique) {
465
+ const fieldName = attr.fieldName || field;
466
+ indexedFields.get(modelName).push(fieldName);
467
+ }
468
+ }
469
+ }
470
+ const schema = produceSchema(schemaPrisma, (builder) => {
471
+ for (const table in tables) {
472
+ const originalTableName = table;
473
+ const customModelName = tables[table]?.modelName || table;
474
+ const modelName = capitalizeFirstLetter(getModelName(customModelName));
475
+ const fields = tables[table]?.fields;
476
+ function getType({ isBigint, isOptional, type }) {
477
+ if (type === "string") return isOptional ? "String?" : "String";
478
+ if (type === "number" && isBigint) return isOptional ? "BigInt?" : "BigInt";
479
+ if (type === "number") return isOptional ? "Int?" : "Int";
480
+ if (type === "boolean") return isOptional ? "Boolean?" : "Boolean";
481
+ if (type === "date") return isOptional ? "DateTime?" : "DateTime";
482
+ if (type === "json") {
483
+ if (provider === "sqlite" || provider === "mysql") return isOptional ? "String?" : "String";
484
+ return isOptional ? "Json?" : "Json";
485
+ }
486
+ if (type === "string[]") {
487
+ if (provider === "sqlite" || provider === "mysql") return isOptional ? "String?" : "String";
488
+ return "String[]";
489
+ }
490
+ if (type === "number[]") {
491
+ if (provider === "sqlite" || provider === "mysql") return "String";
492
+ return "Int[]";
493
+ }
494
+ }
495
+ const prismaModel = builder.findByType("model", { name: modelName });
496
+ if (!prismaModel) if (provider === "mongodb") builder.model(modelName).field("id", "String").attribute("id").attribute(`map("_id")`);
497
+ else {
498
+ const useNumberId = options.advanced?.database?.generateId === "serial";
499
+ const useUUIDs = options.advanced?.database?.generateId === "uuid";
500
+ if (useNumberId) builder.model(modelName).field("id", "Int").attribute("id").attribute("default(autoincrement())");
501
+ else if (useUUIDs && provider === "postgresql") builder.model(modelName).field("id", "String").attribute("id").attribute("default(dbgenerated(\"pg_catalog.gen_random_uuid()\"))").attribute("db.Uuid");
502
+ else builder.model(modelName).field("id", "String").attribute("id");
503
+ }
504
+ for (const field in fields) {
505
+ const attr = fields[field];
506
+ const fieldName = attr.fieldName || field;
507
+ if (prismaModel) {
508
+ if (builder.findByType("field", {
509
+ name: fieldName,
510
+ within: prismaModel.properties
511
+ })) continue;
512
+ }
513
+ const useUUIDs = options.advanced?.database?.generateId === "uuid";
514
+ const useNumberId = options.advanced?.database?.generateId === "serial";
515
+ const fieldBuilder = builder.model(modelName).field(fieldName, field === "id" && useNumberId ? getType({
516
+ isBigint: false,
517
+ isOptional: false,
518
+ type: "number"
519
+ }) : getType({
520
+ isBigint: attr?.bigint || false,
521
+ isOptional: !attr?.required,
522
+ type: attr.references?.field === "id" ? useNumberId ? "number" : "string" : attr.type
523
+ }));
524
+ if (field === "id") {
525
+ fieldBuilder.attribute("id");
526
+ if (provider === "mongodb") fieldBuilder.attribute(`map("_id")`);
527
+ }
528
+ if (attr.unique) builder.model(modelName).blockAttribute(`unique([${fieldName}])`);
529
+ if (attr.defaultValue !== void 0) {
530
+ if (Array.isArray(attr.defaultValue)) {
531
+ if (attr.type === "json") {
532
+ if (Object.prototype.toString.call(attr.defaultValue[0]) === "[object Object]") {
533
+ fieldBuilder.attribute(`default("${JSON.stringify(attr.defaultValue).replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}")`);
534
+ continue;
535
+ }
536
+ const jsonArray = [];
537
+ for (const value of attr.defaultValue) jsonArray.push(value);
538
+ fieldBuilder.attribute(`default("${JSON.stringify(jsonArray).replace(/"/g, "\\\"")}")`);
539
+ continue;
540
+ }
541
+ if (attr.defaultValue.length === 0) {
542
+ fieldBuilder.attribute(`default([])`);
543
+ continue;
544
+ } else if (typeof attr.defaultValue[0] === "string" && attr.type === "string[]") {
545
+ const valueArray = [];
546
+ for (const value of attr.defaultValue) valueArray.push(JSON.stringify(value));
547
+ fieldBuilder.attribute(`default([${valueArray}])`);
548
+ } else if (typeof attr.defaultValue[0] === "number") {
549
+ const valueArray = [];
550
+ for (const value of attr.defaultValue) valueArray.push(`${value}`);
551
+ fieldBuilder.attribute(`default([${valueArray}])`);
552
+ }
553
+ } else if (typeof attr.defaultValue === "object" && !Array.isArray(attr.defaultValue) && attr.defaultValue !== null) {
554
+ if (Object.entries(attr.defaultValue).length === 0) {
555
+ fieldBuilder.attribute(`default("{}")`);
556
+ continue;
557
+ }
558
+ fieldBuilder.attribute(`default("${JSON.stringify(attr.defaultValue).replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}")`);
559
+ }
560
+ if (field === "createdAt") fieldBuilder.attribute("default(now())");
561
+ else if (typeof attr.defaultValue === "string" && provider !== "mysql") fieldBuilder.attribute(`default("${attr.defaultValue}")`);
562
+ else if (typeof attr.defaultValue === "boolean" || typeof attr.defaultValue === "number") fieldBuilder.attribute(`default(${attr.defaultValue})`);
563
+ else if (typeof attr.defaultValue === "function") {}
564
+ }
565
+ if (field === "updatedAt" && attr.onUpdate) fieldBuilder.attribute("updatedAt");
566
+ else if (attr.onUpdate) {}
567
+ if (attr.references) {
568
+ if (useUUIDs && provider === "postgresql" && attr.references?.field === "id") builder.model(modelName).field(fieldName).attribute(`db.Uuid`);
569
+ const referencedOriginalModelName = getModelName(attr.references.model);
570
+ const referencedCustomModelName = tables[referencedOriginalModelName]?.modelName || referencedOriginalModelName;
571
+ let action = "Cascade";
572
+ if (attr.references.onDelete === "no action") action = "NoAction";
573
+ else if (attr.references.onDelete === "set null") action = "SetNull";
574
+ else if (attr.references.onDelete === "set default") action = "SetDefault";
575
+ else if (attr.references.onDelete === "restrict") action = "Restrict";
576
+ const relationField = `relation(fields: [${getFieldName({
577
+ model: originalTableName,
578
+ field: fieldName
579
+ })}], references: [${getFieldName({
580
+ model: attr.references.model,
581
+ field: attr.references.field
582
+ })}], onDelete: ${action})`;
583
+ builder.model(modelName).field(referencedCustomModelName.toLowerCase(), `${capitalizeFirstLetter(referencedCustomModelName)}${!attr.required ? "?" : ""}`).attribute(relationField);
584
+ }
585
+ if (!attr.unique && !attr.references && provider === "mysql" && attr.type === "string") builder.model(modelName).field(fieldName).attribute("db.Text");
586
+ }
587
+ if (manyToManyRelations.has(modelName)) for (const relatedModel of manyToManyRelations.get(modelName)) {
588
+ const relatedTableName = Object.keys(tables).find((key) => capitalizeFirstLetter(tables[key]?.modelName || key) === relatedModel);
589
+ const relatedFields = relatedTableName ? tables[relatedTableName]?.fields : {};
590
+ const [_fieldKey, fkFieldAttr] = Object.entries(relatedFields || {}).find(([_fieldName, fieldAttr]) => fieldAttr.references && getModelName(fieldAttr.references.model) === getModelName(originalTableName)) || [];
591
+ const isUnique = fkFieldAttr?.unique === true;
592
+ const fieldName = isUnique || adapter.options?.usePlural === true ? `${relatedModel.toLowerCase()}` : `${relatedModel.toLowerCase()}s`;
593
+ if (!builder.findByType("field", {
594
+ name: fieldName,
595
+ within: prismaModel?.properties
596
+ })) builder.model(modelName).field(fieldName, `${relatedModel}${isUnique ? "?" : "[]"}`);
597
+ }
598
+ const indexedFieldsForModel = indexedFields.get(modelName);
599
+ if (indexedFieldsForModel && indexedFieldsForModel.length > 0) for (const fieldName of indexedFieldsForModel) {
600
+ if (prismaModel) {
601
+ if (prismaModel.properties.some((v) => v.type === "attribute" && v.name === "index" && JSON.stringify(v.args[0]?.value).includes(fieldName))) continue;
602
+ }
603
+ const field = Object.entries(fields).find(([key, attr]) => (attr.fieldName || key) === fieldName)?.[1];
604
+ let indexField = fieldName;
605
+ if (provider === "mysql" && field && field.type === "string") {
606
+ const useNumberId = options.advanced?.database?.generateId === "serial";
607
+ const useUUIDs = options.advanced?.database?.generateId === "uuid";
608
+ if (field.references?.field === "id" && (useNumberId || useUUIDs)) indexField = `${fieldName}`;
609
+ else indexField = `${fieldName}(length: 191)`;
610
+ }
611
+ builder.model(modelName).blockAttribute(`index([${indexField}])`);
612
+ }
613
+ const hasAttribute = builder.findByType("attribute", {
614
+ name: "map",
615
+ within: prismaModel?.properties
616
+ });
617
+ const hasChanged = customModelName !== originalTableName;
618
+ if (!hasAttribute) builder.model(modelName).blockAttribute("map", `${getModelName(hasChanged ? customModelName : originalTableName)}`);
619
+ }
620
+ });
621
+ const schemaChanged = schema.trim() !== schemaPrisma.trim();
622
+ return {
623
+ code: schemaChanged ? schema : "",
624
+ fileName: filePath,
625
+ overwrite: schemaPrismaExist && schemaChanged
626
+ };
627
+ };
628
+ const getNewPrisma = (provider, cwd) => {
629
+ const prismaVersion = getPrismaVersion(cwd);
630
+ return `generator client {
631
+ provider = "${prismaVersion && prismaVersion >= 7 ? "prisma-client" : "prisma-client-js"}"
632
+ }
633
+
634
+ datasource db {
635
+ provider = "${provider}"
636
+ url = ${provider === "sqlite" ? `"file:./dev.db"` : `env("DATABASE_URL")`}
637
+ }`;
638
+ };
639
+
640
+ //#endregion
641
+ //#region src/generators/index.ts
642
+ const adapters = {
643
+ prisma: generatePrismaSchema,
644
+ drizzle: generateDrizzleSchema,
645
+ kysely: generateKyselySchema
646
+ };
647
+ const generateSchema = (opts) => {
648
+ const adapter = opts.adapter;
649
+ const generator = adapter.id in adapters ? adapters[adapter.id] : null;
650
+ if (generator) return generator(opts);
651
+ if (adapter.createSchema) return adapter.createSchema(opts.options, opts.file).then(({ code, path: fileName, overwrite }) => ({
652
+ code,
653
+ fileName,
654
+ overwrite
655
+ }));
656
+ throw new Error(`${adapter.id} is not supported. If it is a custom adapter, please request the maintainer to implement createSchema`);
657
+ };
658
+
659
+ //#endregion
660
+ export { getPackageInfo as a, spawnCommand as c, generateDrizzleSchema as d, findMonorepoRoot as i, tryCatch as l, generateSchema as n, hasDependency as o, generatePrismaSchema as r, generateSecretHash as s, adapters as t, generateKyselySchema as u };
661
+ //# sourceMappingURL=generators-DNY9D4Si.mjs.map