@better-auth/cli 1.5.0-beta.2 → 1.5.0-beta.4

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