@better-auth/cli 1.3.27 → 1.4.0-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.js +2823 -0
  2. package/package.json +11 -11
  3. package/dist/index.mjs +0 -3689
package/dist/index.mjs DELETED
@@ -1,3689 +0,0 @@
1
- #!/usr/bin/env node
2
- import { Command } from 'commander';
3
- import { parse } from 'dotenv';
4
- import semver from 'semver';
5
- import prettier, { format } from 'prettier';
6
- import * as z from 'zod/v4';
7
- import * as fs from 'fs';
8
- import fs__default, { existsSync, readFileSync } from 'fs';
9
- import * as path from 'path';
10
- import path__default from 'path';
11
- import fs$1 from 'fs/promises';
12
- import chalk from 'chalk';
13
- import { intro, log, outro, confirm, isCancel, cancel, spinner, text, select, multiselect } from '@clack/prompts';
14
- import { exec, execSync } from 'child_process';
15
- import { logger, BetterAuthError, createTelemetry, getTelemetryAuthConfig, capitalizeFirstLetter } from 'better-auth';
16
- import Crypto from 'crypto';
17
- import yoctoSpinner from 'yocto-spinner';
18
- import prompts from 'prompts';
19
- import { getAdapter, getMigrations, getAuthTables } from 'better-auth/db';
20
- import { loadConfig } from 'c12';
21
- import babelPresetTypeScript from '@babel/preset-typescript';
22
- import babelPresetReact from '@babel/preset-react';
23
- import { produceSchema } from '@mrleebo/prisma-ast';
24
- import { createAuthClient } from 'better-auth/client';
25
- import { deviceAuthorizationClient } from 'better-auth/client/plugins';
26
- import open from 'open';
27
- import * as os from 'os';
28
- import os__default from 'os';
29
- import { base64 } from '@better-auth/utils/base64';
30
- import 'dotenv/config';
31
-
32
- function getPackageInfo(cwd) {
33
- const packageJsonPath = cwd ? path__default.join(cwd, "package.json") : path__default.join("package.json");
34
- return JSON.parse(fs__default.readFileSync(packageJsonPath, "utf-8"));
35
- }
36
-
37
- function installDependencies({
38
- dependencies,
39
- packageManager,
40
- cwd
41
- }) {
42
- let installCommand;
43
- switch (packageManager) {
44
- case "npm":
45
- installCommand = "npm install --force";
46
- break;
47
- case "pnpm":
48
- installCommand = "pnpm install";
49
- break;
50
- case "bun":
51
- installCommand = "bun install";
52
- break;
53
- case "yarn":
54
- installCommand = "yarn install";
55
- break;
56
- default:
57
- throw new Error("Invalid package manager");
58
- }
59
- const command = `${installCommand} ${dependencies.join(" ")}`;
60
- return new Promise((resolve, reject) => {
61
- exec(command, { cwd }, (error, stdout, stderr) => {
62
- if (error) {
63
- reject(new Error(stderr));
64
- return;
65
- }
66
- resolve(true);
67
- });
68
- });
69
- }
70
-
71
- function checkCommand(command) {
72
- return new Promise((resolve) => {
73
- exec(`${command} --version`, (error) => {
74
- if (error) {
75
- resolve(false);
76
- } else {
77
- resolve(true);
78
- }
79
- });
80
- });
81
- }
82
- async function checkPackageManagers() {
83
- const hasPnpm = await checkCommand("pnpm");
84
- const hasBun = await checkCommand("bun");
85
- return {
86
- hasPnpm,
87
- hasBun
88
- };
89
- }
90
-
91
- function formatMilliseconds(ms) {
92
- if (ms < 0) {
93
- throw new Error("Milliseconds cannot be negative");
94
- }
95
- if (ms < 1e3) {
96
- return `${ms}ms`;
97
- }
98
- const seconds = Math.floor(ms / 1e3);
99
- const milliseconds = ms % 1e3;
100
- return `${seconds}s ${milliseconds}ms`;
101
- }
102
-
103
- const generateSecret = new Command("secret").action(() => {
104
- const secret = generateSecretHash();
105
- logger.info(`
106
- Add the following to your .env file:
107
- ${chalk.gray("# Auth Secret") + chalk.green(`
108
- BETTER_AUTH_SECRET=${secret}`)}`);
109
- });
110
- const generateSecretHash = () => {
111
- return Crypto.randomBytes(32).toString("hex");
112
- };
113
-
114
- async function generateAuthConfig({
115
- format,
116
- current_user_config,
117
- spinner,
118
- plugins,
119
- database
120
- }) {
121
- let _start_of_plugins_common_index = {
122
- START_OF_PLUGINS: {
123
- type: "regex",
124
- regex: /betterAuth\([\w\W]*plugins:[\W]*\[()/m,
125
- getIndex: ({ matchIndex, match }) => {
126
- return matchIndex + match[0].length;
127
- }
128
- }
129
- };
130
- const common_indexes = {
131
- START_OF_PLUGINS: _start_of_plugins_common_index.START_OF_PLUGINS,
132
- END_OF_PLUGINS: {
133
- type: "manual",
134
- getIndex: ({ content, additionalFields }) => {
135
- const closingBracketIndex = findClosingBracket(
136
- content,
137
- additionalFields.start_of_plugins,
138
- "[",
139
- "]"
140
- );
141
- return closingBracketIndex;
142
- }
143
- },
144
- START_OF_BETTERAUTH: {
145
- type: "regex",
146
- regex: /betterAuth\({()/m,
147
- getIndex: ({ matchIndex }) => {
148
- return matchIndex + "betterAuth({".length;
149
- }
150
- }
151
- };
152
- const config_generation = {
153
- add_plugin: async (opts) => {
154
- let start_of_plugins = getGroupInfo(
155
- opts.config,
156
- common_indexes.START_OF_PLUGINS,
157
- {}
158
- );
159
- if (!start_of_plugins) {
160
- throw new Error(
161
- "Couldn't find start of your plugins array in your auth config file."
162
- );
163
- }
164
- let end_of_plugins = getGroupInfo(
165
- opts.config,
166
- common_indexes.END_OF_PLUGINS,
167
- { start_of_plugins: start_of_plugins.index }
168
- );
169
- if (!end_of_plugins) {
170
- throw new Error(
171
- "Couldn't find end of your plugins array in your auth config file."
172
- );
173
- }
174
- let new_content;
175
- if (opts.direction_in_plugins_array === "prepend") {
176
- new_content = insertContent({
177
- line: start_of_plugins.line,
178
- character: start_of_plugins.character,
179
- content: opts.config,
180
- insert_content: `${opts.pluginFunctionName}(${opts.pluginContents}),`
181
- });
182
- } else {
183
- const pluginArrayContent = opts.config.slice(start_of_plugins.index, end_of_plugins.index).trim();
184
- const isPluginArrayEmpty = pluginArrayContent === "";
185
- const isPluginArrayEndsWithComma = pluginArrayContent.endsWith(",");
186
- const needsComma = !isPluginArrayEmpty && !isPluginArrayEndsWithComma;
187
- new_content = insertContent({
188
- line: end_of_plugins.line,
189
- character: end_of_plugins.character,
190
- content: opts.config,
191
- insert_content: `${needsComma ? "," : ""}${opts.pluginFunctionName}(${opts.pluginContents})`
192
- });
193
- }
194
- try {
195
- new_content = await format(new_content);
196
- } catch (error) {
197
- console.error(error);
198
- throw new Error(
199
- `Failed to generate new auth config during plugin addition phase.`
200
- );
201
- }
202
- return { code: new_content, dependencies: [], envs: [] };
203
- },
204
- add_import: async (opts) => {
205
- let importString = "";
206
- for (const import_ of opts.imports) {
207
- if (Array.isArray(import_.variables)) {
208
- importString += `import { ${import_.variables.map(
209
- (x) => `${x.asType ? "type " : ""}${x.name}${x.as ? ` as ${x.as}` : ""}`
210
- ).join(", ")} } from "${import_.path}";
211
- `;
212
- } else {
213
- importString += `import ${import_.variables.asType ? "type " : ""}${import_.variables.name}${import_.variables.as ? ` as ${import_.variables.as}` : ""} from "${import_.path}";
214
- `;
215
- }
216
- }
217
- try {
218
- let new_content = format(importString + opts.config);
219
- return { code: await new_content, dependencies: [], envs: [] };
220
- } catch (error) {
221
- console.error(error);
222
- throw new Error(
223
- `Failed to generate new auth config during import addition phase.`
224
- );
225
- }
226
- },
227
- add_database: async (opts) => {
228
- const required_envs = [];
229
- const required_deps = [];
230
- let database_code_str = "";
231
- async function add_db({
232
- db_code,
233
- dependencies,
234
- envs,
235
- imports,
236
- code_before_betterAuth
237
- }) {
238
- if (code_before_betterAuth) {
239
- let start_of_betterauth2 = getGroupInfo(
240
- opts.config,
241
- common_indexes.START_OF_BETTERAUTH,
242
- {}
243
- );
244
- if (!start_of_betterauth2) {
245
- throw new Error("Couldn't find start of betterAuth() function.");
246
- }
247
- opts.config = insertContent({
248
- line: start_of_betterauth2.line - 1,
249
- character: 0,
250
- content: opts.config,
251
- insert_content: `
252
- ${code_before_betterAuth}
253
- `
254
- });
255
- }
256
- const code_gen = await config_generation.add_import({
257
- config: opts.config,
258
- imports
259
- });
260
- opts.config = code_gen.code;
261
- database_code_str = db_code;
262
- required_envs.push(...envs, ...code_gen.envs);
263
- required_deps.push(...dependencies, ...code_gen.dependencies);
264
- }
265
- if (opts.database === "sqlite") {
266
- await add_db({
267
- db_code: `new Database(process.env.DATABASE_URL || "database.sqlite")`,
268
- dependencies: ["better-sqlite3"],
269
- envs: ["DATABASE_URL"],
270
- imports: [
271
- {
272
- path: "better-sqlite3",
273
- variables: {
274
- asType: false,
275
- name: "Database"
276
- }
277
- }
278
- ]
279
- });
280
- } else if (opts.database === "postgres") {
281
- await add_db({
282
- db_code: `new Pool({
283
- connectionString: process.env.DATABASE_URL || "postgresql://postgres:password@localhost:5432/database"
284
- })`,
285
- dependencies: ["pg"],
286
- envs: ["DATABASE_URL"],
287
- imports: [
288
- {
289
- path: "pg",
290
- variables: [
291
- {
292
- asType: false,
293
- name: "Pool"
294
- }
295
- ]
296
- }
297
- ]
298
- });
299
- } else if (opts.database === "mysql") {
300
- await add_db({
301
- db_code: `createPool(process.env.DATABASE_URL!)`,
302
- dependencies: ["mysql2"],
303
- envs: ["DATABASE_URL"],
304
- imports: [
305
- {
306
- path: "mysql2/promise",
307
- variables: [
308
- {
309
- asType: false,
310
- name: "createPool"
311
- }
312
- ]
313
- }
314
- ]
315
- });
316
- } else if (opts.database === "mssql") {
317
- const dialectCode = `new MssqlDialect({
318
- tarn: {
319
- ...Tarn,
320
- options: {
321
- min: 0,
322
- max: 10,
323
- },
324
- },
325
- tedious: {
326
- ...Tedious,
327
- connectionFactory: () => new Tedious.Connection({
328
- authentication: {
329
- options: {
330
- password: 'password',
331
- userName: 'username',
332
- },
333
- type: 'default',
334
- },
335
- options: {
336
- database: 'some_db',
337
- port: 1433,
338
- trustServerCertificate: true,
339
- },
340
- server: 'localhost',
341
- }),
342
- },
343
- })`;
344
- await add_db({
345
- code_before_betterAuth: dialectCode,
346
- db_code: `dialect`,
347
- dependencies: ["tedious", "tarn", "kysely"],
348
- envs: ["DATABASE_URL"],
349
- imports: [
350
- {
351
- path: "tedious",
352
- variables: {
353
- name: "*",
354
- as: "Tedious"
355
- }
356
- },
357
- {
358
- path: "tarn",
359
- variables: {
360
- name: "*",
361
- as: "Tarn"
362
- }
363
- },
364
- {
365
- path: "kysely",
366
- variables: [
367
- {
368
- name: "MssqlDialect"
369
- }
370
- ]
371
- }
372
- ]
373
- });
374
- } else if (opts.database === "drizzle:mysql" || opts.database === "drizzle:sqlite" || opts.database === "drizzle:pg") {
375
- await add_db({
376
- db_code: `drizzleAdapter(db, {
377
- provider: "${opts.database.replace(
378
- "drizzle:",
379
- ""
380
- )}",
381
- })`,
382
- dependencies: [""],
383
- envs: [],
384
- imports: [
385
- {
386
- path: "better-auth/adapters/drizzle",
387
- variables: [
388
- {
389
- name: "drizzleAdapter"
390
- }
391
- ]
392
- },
393
- {
394
- path: "./database.ts",
395
- variables: [
396
- {
397
- name: "db"
398
- }
399
- ]
400
- }
401
- ]
402
- });
403
- } else if (opts.database === "prisma:mysql" || opts.database === "prisma:sqlite" || opts.database === "prisma:postgresql") {
404
- await add_db({
405
- db_code: `prismaAdapter(client, {
406
- provider: "${opts.database.replace(
407
- "prisma:",
408
- ""
409
- )}",
410
- })`,
411
- dependencies: [`@prisma/client`],
412
- envs: [],
413
- code_before_betterAuth: "const client = new PrismaClient();",
414
- imports: [
415
- {
416
- path: "better-auth/adapters/prisma",
417
- variables: [
418
- {
419
- name: "prismaAdapter"
420
- }
421
- ]
422
- },
423
- {
424
- path: "@prisma/client",
425
- variables: [
426
- {
427
- name: "PrismaClient"
428
- }
429
- ]
430
- }
431
- ]
432
- });
433
- } else if (opts.database === "mongodb") {
434
- await add_db({
435
- db_code: `mongodbAdapter(db)`,
436
- dependencies: ["mongodb"],
437
- envs: [`DATABASE_URL`],
438
- code_before_betterAuth: [
439
- `const client = new MongoClient(process.env.DATABASE_URL || "mongodb://localhost:27017/database");`,
440
- `const db = client.db();`
441
- ].join("\n"),
442
- imports: [
443
- {
444
- path: "better-auth/adapters/mongodb",
445
- variables: [
446
- {
447
- name: "mongodbAdapter"
448
- }
449
- ]
450
- },
451
- {
452
- path: "mongodb",
453
- variables: [
454
- {
455
- name: "MongoClient"
456
- }
457
- ]
458
- }
459
- ]
460
- });
461
- }
462
- let start_of_betterauth = getGroupInfo(
463
- opts.config,
464
- common_indexes.START_OF_BETTERAUTH,
465
- {}
466
- );
467
- if (!start_of_betterauth) {
468
- throw new Error("Couldn't find start of betterAuth() function.");
469
- }
470
- let new_content;
471
- new_content = insertContent({
472
- line: start_of_betterauth.line,
473
- character: start_of_betterauth.character,
474
- content: opts.config,
475
- insert_content: `database: ${database_code_str},`
476
- });
477
- try {
478
- new_content = await format(new_content);
479
- return {
480
- code: new_content,
481
- dependencies: required_deps,
482
- envs: required_envs
483
- };
484
- } catch (error) {
485
- console.error(error);
486
- throw new Error(
487
- `Failed to generate new auth config during database addition phase.`
488
- );
489
- }
490
- }
491
- };
492
- let new_user_config = await format(current_user_config);
493
- let total_dependencies = [];
494
- let total_envs = [];
495
- if (plugins.length !== 0) {
496
- const imports = [];
497
- for await (const plugin of plugins) {
498
- const existingIndex = imports.findIndex((x) => x.path === plugin.path);
499
- if (existingIndex !== -1) {
500
- imports[existingIndex].variables.push({
501
- name: plugin.name,
502
- asType: false
503
- });
504
- } else {
505
- imports.push({
506
- path: plugin.path,
507
- variables: [
508
- {
509
- name: plugin.name,
510
- asType: false
511
- }
512
- ]
513
- });
514
- }
515
- }
516
- if (imports.length !== 0) {
517
- const { code, envs, dependencies } = await config_generation.add_import({
518
- config: new_user_config,
519
- imports
520
- });
521
- total_dependencies.push(...dependencies);
522
- total_envs.push(...envs);
523
- new_user_config = code;
524
- }
525
- }
526
- for await (const plugin of plugins) {
527
- try {
528
- let pluginContents = "";
529
- if (plugin.id === "magic-link") {
530
- pluginContents = `{
531
- sendMagicLink({ email, token, url }, request) {
532
- // Send email with magic link
533
- },
534
- }`;
535
- } else if (plugin.id === "email-otp") {
536
- pluginContents = `{
537
- async sendVerificationOTP({ email, otp, type }, request) {
538
- // Send email with OTP
539
- },
540
- }`;
541
- } else if (plugin.id === "generic-oauth") {
542
- pluginContents = `{
543
- config: [],
544
- }`;
545
- } else if (plugin.id === "oidc") {
546
- pluginContents = `{
547
- loginPage: "/sign-in",
548
- }`;
549
- }
550
- const { code, dependencies, envs } = await config_generation.add_plugin({
551
- config: new_user_config,
552
- direction_in_plugins_array: plugin.id === "next-cookies" ? "append" : "prepend",
553
- pluginFunctionName: plugin.name,
554
- pluginContents
555
- });
556
- new_user_config = code;
557
- total_envs.push(...envs);
558
- total_dependencies.push(...dependencies);
559
- } catch (error) {
560
- spinner.stop(
561
- `Something went wrong while generating/updating your new auth config file.`,
562
- 1
563
- );
564
- logger.error(error.message);
565
- process.exit(1);
566
- }
567
- }
568
- if (database) {
569
- try {
570
- const { code, dependencies, envs } = await config_generation.add_database(
571
- {
572
- config: new_user_config,
573
- database
574
- }
575
- );
576
- new_user_config = code;
577
- total_dependencies.push(...dependencies);
578
- total_envs.push(...envs);
579
- } catch (error) {
580
- spinner.stop(
581
- `Something went wrong while generating/updating your new auth config file.`,
582
- 1
583
- );
584
- logger.error(error.message);
585
- process.exit(1);
586
- }
587
- }
588
- return {
589
- generatedCode: new_user_config,
590
- dependencies: total_dependencies,
591
- envs: total_envs
592
- };
593
- }
594
- function findClosingBracket(content, startIndex, openingBracket, closingBracket) {
595
- let stack = 0;
596
- let inString = false;
597
- let quoteChar = null;
598
- for (let i = startIndex; i < content.length; i++) {
599
- const char = content[i];
600
- if (char === '"' || char === "'" || char === "`") {
601
- if (!inString) {
602
- inString = true;
603
- quoteChar = char;
604
- } else if (char === quoteChar) {
605
- inString = false;
606
- quoteChar = null;
607
- }
608
- continue;
609
- }
610
- if (!inString) {
611
- if (char === openingBracket) {
612
- stack++;
613
- } else if (char === closingBracket) {
614
- if (stack === 0) {
615
- return i;
616
- }
617
- stack--;
618
- }
619
- }
620
- }
621
- return null;
622
- }
623
- function insertContent(params) {
624
- const { line, character, content, insert_content } = params;
625
- const lines = content.split("\n");
626
- if (line < 1 || line > lines.length) {
627
- throw new Error("Invalid line number");
628
- }
629
- const targetLineIndex = line - 1;
630
- if (character < 0 || character > lines[targetLineIndex].length) {
631
- throw new Error("Invalid character index");
632
- }
633
- const targetLine = lines[targetLineIndex];
634
- const updatedLine = targetLine.slice(0, character) + insert_content + targetLine.slice(character);
635
- lines[targetLineIndex] = updatedLine;
636
- return lines.join("\n");
637
- }
638
- function getGroupInfo(content, commonIndexConfig, additionalFields) {
639
- if (commonIndexConfig.type === "regex") {
640
- const { regex, getIndex } = commonIndexConfig;
641
- const match = regex.exec(content);
642
- if (match) {
643
- const matchIndex = match.index;
644
- const groupIndex = getIndex({ matchIndex, match, additionalFields });
645
- if (groupIndex === null) return null;
646
- const position = getPosition(content, groupIndex);
647
- return {
648
- line: position.line,
649
- character: position.character,
650
- index: groupIndex
651
- };
652
- }
653
- return null;
654
- } else {
655
- const { getIndex } = commonIndexConfig;
656
- const index = getIndex({ content, additionalFields });
657
- if (index === null) return null;
658
- const { line, character } = getPosition(content, index);
659
- return {
660
- line,
661
- character,
662
- index
663
- };
664
- }
665
- }
666
- const getPosition = (str, index) => {
667
- const lines = str.slice(0, index).split("\n");
668
- return {
669
- line: lines.length,
670
- character: lines[lines.length - 1].length
671
- };
672
- };
673
-
674
- function stripJsonComments(jsonString) {
675
- return jsonString.replace(
676
- /\\"|"(?:\\"|[^"])*"|(\/\/.*|\/\*[\s\S]*?\*\/)/g,
677
- (m, g) => g ? "" : m
678
- ).replace(/,(?=\s*[}\]])/g, "");
679
- }
680
- function getTsconfigInfo(cwd, flatPath) {
681
- let tsConfigPath;
682
- if (flatPath) {
683
- tsConfigPath = flatPath;
684
- } else {
685
- tsConfigPath = cwd ? path__default.join(cwd, "tsconfig.json") : path__default.join("tsconfig.json");
686
- }
687
- try {
688
- const text = fs__default.readFileSync(tsConfigPath, "utf-8");
689
- return JSON.parse(stripJsonComments(text));
690
- } catch (error) {
691
- throw error;
692
- }
693
- }
694
-
695
- const supportedDatabases = [
696
- // Built-in kysely
697
- "sqlite",
698
- "mysql",
699
- "mssql",
700
- "postgres",
701
- // Drizzle
702
- "drizzle:pg",
703
- "drizzle:mysql",
704
- "drizzle:sqlite",
705
- // Prisma
706
- "prisma:postgresql",
707
- "prisma:mysql",
708
- "prisma:sqlite",
709
- // Mongo
710
- "mongodb"
711
- ];
712
- const supportedPlugins = [
713
- {
714
- id: "two-factor",
715
- name: "twoFactor",
716
- path: `better-auth/plugins`,
717
- clientName: "twoFactorClient",
718
- clientPath: "better-auth/client/plugins"
719
- },
720
- {
721
- id: "username",
722
- name: "username",
723
- clientName: "usernameClient",
724
- path: `better-auth/plugins`,
725
- clientPath: "better-auth/client/plugins"
726
- },
727
- {
728
- id: "anonymous",
729
- name: "anonymous",
730
- clientName: "anonymousClient",
731
- path: `better-auth/plugins`,
732
- clientPath: "better-auth/client/plugins"
733
- },
734
- {
735
- id: "phone-number",
736
- name: "phoneNumber",
737
- clientName: "phoneNumberClient",
738
- path: `better-auth/plugins`,
739
- clientPath: "better-auth/client/plugins"
740
- },
741
- {
742
- id: "magic-link",
743
- name: "magicLink",
744
- clientName: "magicLinkClient",
745
- clientPath: "better-auth/client/plugins",
746
- path: `better-auth/plugins`
747
- },
748
- {
749
- id: "email-otp",
750
- name: "emailOTP",
751
- clientName: "emailOTPClient",
752
- path: `better-auth/plugins`,
753
- clientPath: "better-auth/client/plugins"
754
- },
755
- {
756
- id: "passkey",
757
- name: "passkey",
758
- clientName: "passkeyClient",
759
- path: `better-auth/plugins/passkey`,
760
- clientPath: "better-auth/client/plugins"
761
- },
762
- {
763
- id: "generic-oauth",
764
- name: "genericOAuth",
765
- clientName: "genericOAuthClient",
766
- path: `better-auth/plugins`,
767
- clientPath: "better-auth/client/plugins"
768
- },
769
- {
770
- id: "one-tap",
771
- name: "oneTap",
772
- clientName: "oneTapClient",
773
- path: `better-auth/plugins`,
774
- clientPath: "better-auth/client/plugins"
775
- },
776
- {
777
- id: "api-key",
778
- name: "apiKey",
779
- clientName: "apiKeyClient",
780
- path: `better-auth/plugins`,
781
- clientPath: "better-auth/client/plugins"
782
- },
783
- {
784
- id: "admin",
785
- name: "admin",
786
- clientName: "adminClient",
787
- path: `better-auth/plugins`,
788
- clientPath: "better-auth/client/plugins"
789
- },
790
- {
791
- id: "organization",
792
- name: "organization",
793
- clientName: "organizationClient",
794
- path: `better-auth/plugins`,
795
- clientPath: "better-auth/client/plugins"
796
- },
797
- {
798
- id: "oidc",
799
- name: "oidcProvider",
800
- clientName: "oidcClient",
801
- path: `better-auth/plugins`,
802
- clientPath: "better-auth/client/plugins"
803
- },
804
- {
805
- id: "sso",
806
- name: "sso",
807
- clientName: "ssoClient",
808
- path: `better-auth/plugins/sso`,
809
- clientPath: "better-auth/client/plugins"
810
- },
811
- {
812
- id: "bearer",
813
- name: "bearer",
814
- clientName: void 0,
815
- path: `better-auth/plugins`,
816
- clientPath: void 0
817
- },
818
- {
819
- id: "multi-session",
820
- name: "multiSession",
821
- clientName: "multiSessionClient",
822
- path: `better-auth/plugins`,
823
- clientPath: "better-auth/client/plugins"
824
- },
825
- {
826
- id: "oauth-proxy",
827
- name: "oAuthProxy",
828
- clientName: void 0,
829
- path: `better-auth/plugins`,
830
- clientPath: void 0
831
- },
832
- {
833
- id: "open-api",
834
- name: "openAPI",
835
- clientName: void 0,
836
- path: `better-auth/plugins`,
837
- clientPath: void 0
838
- },
839
- {
840
- id: "jwt",
841
- name: "jwt",
842
- clientName: void 0,
843
- clientPath: void 0,
844
- path: `better-auth/plugins`
845
- },
846
- {
847
- id: "next-cookies",
848
- name: "nextCookies",
849
- clientPath: void 0,
850
- clientName: void 0,
851
- path: `better-auth/next-js`
852
- }
853
- ];
854
- const defaultFormatOptions = {
855
- trailingComma: "all",
856
- useTabs: false,
857
- tabWidth: 4
858
- };
859
- const getDefaultAuthConfig = async ({ appName }) => await format(
860
- [
861
- "import { betterAuth } from 'better-auth';",
862
- "",
863
- "export const auth = betterAuth({",
864
- appName ? `appName: "${appName}",` : "",
865
- "plugins: [],",
866
- "});"
867
- ].join("\n"),
868
- {
869
- filepath: "auth.ts",
870
- ...defaultFormatOptions
871
- }
872
- );
873
- const getDefaultAuthClientConfig = async ({
874
- auth_config_path,
875
- framework,
876
- clientPlugins
877
- }) => {
878
- function groupImportVariables() {
879
- const result = [
880
- {
881
- path: "better-auth/client/plugins",
882
- variables: [{ name: "inferAdditionalFields" }]
883
- }
884
- ];
885
- for (const plugin of clientPlugins) {
886
- for (const import_ of plugin.imports) {
887
- if (Array.isArray(import_.variables)) {
888
- for (const variable of import_.variables) {
889
- const existingIndex = result.findIndex(
890
- (x) => x.path === import_.path
891
- );
892
- if (existingIndex !== -1) {
893
- const vars = result[existingIndex].variables;
894
- if (Array.isArray(vars)) {
895
- vars.push(variable);
896
- } else {
897
- result[existingIndex].variables = [vars, variable];
898
- }
899
- } else {
900
- result.push({
901
- path: import_.path,
902
- variables: [variable]
903
- });
904
- }
905
- }
906
- } else {
907
- const existingIndex = result.findIndex(
908
- (x) => x.path === import_.path
909
- );
910
- if (existingIndex !== -1) {
911
- const vars = result[existingIndex].variables;
912
- if (Array.isArray(vars)) {
913
- vars.push(import_.variables);
914
- } else {
915
- result[existingIndex].variables = [vars, import_.variables];
916
- }
917
- } else {
918
- result.push({
919
- path: import_.path,
920
- variables: [import_.variables]
921
- });
922
- }
923
- }
924
- }
925
- }
926
- return result;
927
- }
928
- let imports = groupImportVariables();
929
- let importString = "";
930
- for (const import_ of imports) {
931
- if (Array.isArray(import_.variables)) {
932
- importString += `import { ${import_.variables.map(
933
- (x) => `${x.asType ? "type " : ""}${x.name}${x.as ? ` as ${x.as}` : ""}`
934
- ).join(", ")} } from "${import_.path}";
935
- `;
936
- } else {
937
- importString += `import ${import_.variables.asType ? "type " : ""}${import_.variables.name}${import_.variables.as ? ` as ${import_.variables.as}` : ""} from "${import_.path}";
938
- `;
939
- }
940
- }
941
- return await format(
942
- [
943
- `import { createAuthClient } from "better-auth/${framework === "nextjs" ? "react" : framework === "vanilla" ? "client" : framework}";`,
944
- `import type { auth } from "${auth_config_path}";`,
945
- importString,
946
- ``,
947
- `export const authClient = createAuthClient({`,
948
- `baseURL: "http://localhost:3000",`,
949
- `plugins: [inferAdditionalFields<typeof auth>(),${clientPlugins.map((x) => `${x.name}(${x.contents})`).join(", ")}],`,
950
- `});`
951
- ].join("\n"),
952
- {
953
- filepath: "auth-client.ts",
954
- ...defaultFormatOptions
955
- }
956
- );
957
- };
958
- const optionsSchema = z.object({
959
- cwd: z.string(),
960
- config: z.string().optional(),
961
- database: z.enum(supportedDatabases).optional(),
962
- "skip-db": z.boolean().optional(),
963
- "skip-plugins": z.boolean().optional(),
964
- "package-manager": z.string().optional(),
965
- tsconfig: z.string().optional()
966
- });
967
- const outroText = `\u{1F973} All Done, Happy Hacking!`;
968
- async function initAction(opts) {
969
- console.log();
970
- intro("\u{1F44B} Initializing Better Auth");
971
- const options = optionsSchema.parse(opts);
972
- const cwd = path__default.resolve(options.cwd);
973
- let packageManagerPreference = void 0;
974
- let config_path = "";
975
- let framework = "vanilla";
976
- const format$1 = async (code) => await format(code, {
977
- filepath: config_path,
978
- ...defaultFormatOptions
979
- });
980
- let packageInfo;
981
- try {
982
- packageInfo = getPackageInfo(cwd);
983
- } catch (error) {
984
- log.error(`\u274C Couldn't read your package.json file. (dir: ${cwd})`);
985
- log.error(JSON.stringify(error, null, 2));
986
- process.exit(1);
987
- }
988
- const envFiles = await getEnvFiles(cwd);
989
- if (!envFiles.length) {
990
- outro("\u274C No .env files found. Please create an env file first.");
991
- process.exit(0);
992
- }
993
- let targetEnvFile;
994
- if (envFiles.includes(".env")) targetEnvFile = ".env";
995
- else if (envFiles.includes(".env.local")) targetEnvFile = ".env.local";
996
- else if (envFiles.includes(".env.development"))
997
- targetEnvFile = ".env.development";
998
- else if (envFiles.length === 1) targetEnvFile = envFiles[0];
999
- else targetEnvFile = "none";
1000
- let tsconfigInfo;
1001
- try {
1002
- const tsconfigPath = options.tsconfig !== void 0 ? path__default.resolve(cwd, options.tsconfig) : path__default.join(cwd, "tsconfig.json");
1003
- tsconfigInfo = await getTsconfigInfo(cwd, tsconfigPath);
1004
- } catch (error) {
1005
- log.error(`\u274C Couldn't read your tsconfig.json file. (dir: ${cwd})`);
1006
- console.error(error);
1007
- process.exit(1);
1008
- }
1009
- if (!("compilerOptions" in tsconfigInfo && "strict" in tsconfigInfo.compilerOptions && tsconfigInfo.compilerOptions.strict === true)) {
1010
- log.warn(
1011
- `Better Auth requires your tsconfig.json to have "compilerOptions.strict" set to true.`
1012
- );
1013
- const shouldAdd = await confirm({
1014
- message: `Would you like us to set ${chalk.bold(
1015
- `strict`
1016
- )} to ${chalk.bold(`true`)}?`
1017
- });
1018
- if (isCancel(shouldAdd)) {
1019
- cancel(`\u270B Operation cancelled.`);
1020
- process.exit(0);
1021
- }
1022
- if (shouldAdd) {
1023
- try {
1024
- await fs$1.writeFile(
1025
- path__default.join(cwd, "tsconfig.json"),
1026
- await format(
1027
- JSON.stringify(
1028
- Object.assign(tsconfigInfo, {
1029
- compilerOptions: {
1030
- strict: true
1031
- }
1032
- })
1033
- ),
1034
- { filepath: "tsconfig.json", ...defaultFormatOptions }
1035
- ),
1036
- "utf-8"
1037
- );
1038
- log.success(`\u{1F680} tsconfig.json successfully updated!`);
1039
- } catch (error) {
1040
- log.error(
1041
- `Failed to add "compilerOptions.strict" to your tsconfig.json file.`
1042
- );
1043
- console.error(error);
1044
- process.exit(1);
1045
- }
1046
- }
1047
- }
1048
- const s = spinner({ indicator: "dots" });
1049
- s.start(`Checking better-auth installation`);
1050
- let latest_betterauth_version;
1051
- try {
1052
- latest_betterauth_version = await getLatestNpmVersion("better-auth");
1053
- } catch (error) {
1054
- log.error(`\u274C Couldn't get latest version of better-auth.`);
1055
- console.error(error);
1056
- process.exit(1);
1057
- }
1058
- if (!packageInfo.dependencies || !Object.keys(packageInfo.dependencies).includes("better-auth")) {
1059
- s.stop("Finished fetching latest version of better-auth.");
1060
- const s2 = spinner({ indicator: "dots" });
1061
- const shouldInstallBetterAuthDep = await confirm({
1062
- message: `Would you like to install Better Auth?`
1063
- });
1064
- if (isCancel(shouldInstallBetterAuthDep)) {
1065
- cancel(`\u270B Operation cancelled.`);
1066
- process.exit(0);
1067
- }
1068
- if (packageManagerPreference === void 0) {
1069
- packageManagerPreference = await getPackageManager$1();
1070
- }
1071
- if (shouldInstallBetterAuthDep) {
1072
- s2.start(
1073
- `Installing Better Auth using ${chalk.bold(packageManagerPreference)}`
1074
- );
1075
- try {
1076
- const start = Date.now();
1077
- await installDependencies({
1078
- dependencies: ["better-auth@latest"],
1079
- packageManager: packageManagerPreference,
1080
- cwd
1081
- });
1082
- s2.stop(
1083
- `Better Auth installed ${chalk.greenBright(
1084
- `successfully`
1085
- )}! ${chalk.gray(`(${formatMilliseconds(Date.now() - start)})`)}`
1086
- );
1087
- } catch (error) {
1088
- s2.stop(`Failed to install Better Auth:`);
1089
- console.error(error);
1090
- process.exit(1);
1091
- }
1092
- }
1093
- } else if (packageInfo.dependencies["better-auth"] !== "workspace:*" && semver.lt(
1094
- semver.coerce(packageInfo.dependencies["better-auth"])?.toString(),
1095
- semver.clean(latest_betterauth_version)
1096
- )) {
1097
- s.stop("Finished fetching latest version of better-auth.");
1098
- const shouldInstallBetterAuthDep = await confirm({
1099
- message: `Your current Better Auth dependency is out-of-date. Would you like to update it? (${chalk.bold(
1100
- packageInfo.dependencies["better-auth"]
1101
- )} \u2192 ${chalk.bold(`v${latest_betterauth_version}`)})`
1102
- });
1103
- if (isCancel(shouldInstallBetterAuthDep)) {
1104
- cancel(`\u270B Operation cancelled.`);
1105
- process.exit(0);
1106
- }
1107
- if (shouldInstallBetterAuthDep) {
1108
- if (packageManagerPreference === void 0) {
1109
- packageManagerPreference = await getPackageManager$1();
1110
- }
1111
- const s2 = spinner({ indicator: "dots" });
1112
- s2.start(
1113
- `Updating Better Auth using ${chalk.bold(packageManagerPreference)}`
1114
- );
1115
- try {
1116
- const start = Date.now();
1117
- await installDependencies({
1118
- dependencies: ["better-auth@latest"],
1119
- packageManager: packageManagerPreference,
1120
- cwd
1121
- });
1122
- s2.stop(
1123
- `Better Auth updated ${chalk.greenBright(
1124
- `successfully`
1125
- )}! ${chalk.gray(`(${formatMilliseconds(Date.now() - start)})`)}`
1126
- );
1127
- } catch (error) {
1128
- s2.stop(`Failed to update Better Auth:`);
1129
- log.error(error.message);
1130
- process.exit(1);
1131
- }
1132
- }
1133
- } else {
1134
- s.stop(`Better Auth dependencies are ${chalk.greenBright(`up to date`)}!`);
1135
- }
1136
- const packageJson = getPackageInfo(cwd);
1137
- let appName;
1138
- if (!packageJson.name) {
1139
- const newAppName = await text({
1140
- message: "What is the name of your application?"
1141
- });
1142
- if (isCancel(newAppName)) {
1143
- cancel("\u270B Operation cancelled.");
1144
- process.exit(0);
1145
- }
1146
- appName = newAppName;
1147
- } else {
1148
- appName = packageJson.name;
1149
- }
1150
- let possiblePaths = ["auth.ts", "auth.tsx", "auth.js", "auth.jsx"];
1151
- possiblePaths = [
1152
- ...possiblePaths,
1153
- ...possiblePaths.map((it) => `lib/server/${it}`),
1154
- ...possiblePaths.map((it) => `server/${it}`),
1155
- ...possiblePaths.map((it) => `lib/${it}`),
1156
- ...possiblePaths.map((it) => `utils/${it}`)
1157
- ];
1158
- possiblePaths = [
1159
- ...possiblePaths,
1160
- ...possiblePaths.map((it) => `src/${it}`),
1161
- ...possiblePaths.map((it) => `app/${it}`)
1162
- ];
1163
- if (options.config) {
1164
- config_path = path__default.join(cwd, options.config);
1165
- } else {
1166
- for (const possiblePath of possiblePaths) {
1167
- const doesExist = existsSync(path__default.join(cwd, possiblePath));
1168
- if (doesExist) {
1169
- config_path = path__default.join(cwd, possiblePath);
1170
- break;
1171
- }
1172
- }
1173
- }
1174
- let current_user_config = "";
1175
- let database = null;
1176
- let add_plugins = [];
1177
- if (!config_path) {
1178
- const shouldCreateAuthConfig = await select({
1179
- message: `Would you like to create an auth config file?`,
1180
- options: [
1181
- { label: "Yes", value: "yes" },
1182
- { label: "No", value: "no" }
1183
- ]
1184
- });
1185
- if (isCancel(shouldCreateAuthConfig)) {
1186
- cancel(`\u270B Operation cancelled.`);
1187
- process.exit(0);
1188
- }
1189
- if (shouldCreateAuthConfig === "yes") {
1190
- const shouldSetupDb = await confirm({
1191
- message: `Would you like to set up your ${chalk.bold(`database`)}?`,
1192
- initialValue: true
1193
- });
1194
- if (isCancel(shouldSetupDb)) {
1195
- cancel(`\u270B Operating cancelled.`);
1196
- process.exit(0);
1197
- }
1198
- if (shouldSetupDb) {
1199
- const prompted_database = await select({
1200
- message: "Choose a Database Dialect",
1201
- options: supportedDatabases.map((it) => ({ value: it, label: it }))
1202
- });
1203
- if (isCancel(prompted_database)) {
1204
- cancel(`\u270B Operating cancelled.`);
1205
- process.exit(0);
1206
- }
1207
- database = prompted_database;
1208
- }
1209
- if (options["skip-plugins"] !== false) {
1210
- const shouldSetupPlugins = await confirm({
1211
- message: `Would you like to set up ${chalk.bold(`plugins`)}?`
1212
- });
1213
- if (isCancel(shouldSetupPlugins)) {
1214
- cancel(`\u270B Operating cancelled.`);
1215
- process.exit(0);
1216
- }
1217
- if (shouldSetupPlugins) {
1218
- const prompted_plugins = await multiselect({
1219
- message: "Select your new plugins",
1220
- options: supportedPlugins.filter((x) => x.id !== "next-cookies").map((x) => ({ value: x.id, label: x.id })),
1221
- required: false
1222
- });
1223
- if (isCancel(prompted_plugins)) {
1224
- cancel(`\u270B Operating cancelled.`);
1225
- process.exit(0);
1226
- }
1227
- add_plugins = prompted_plugins.map(
1228
- (x) => supportedPlugins.find((y) => y.id === x)
1229
- );
1230
- const possible_next_config_paths = [
1231
- "next.config.js",
1232
- "next.config.ts",
1233
- "next.config.mjs",
1234
- ".next/server/next.config.js",
1235
- ".next/server/next.config.ts",
1236
- ".next/server/next.config.mjs"
1237
- ];
1238
- for (const possible_next_config_path of possible_next_config_paths) {
1239
- if (existsSync(path__default.join(cwd, possible_next_config_path))) {
1240
- framework = "nextjs";
1241
- break;
1242
- }
1243
- }
1244
- if (framework === "nextjs") {
1245
- const result = await confirm({
1246
- message: `It looks like you're using NextJS. Do you want to add the next-cookies plugin? ${chalk.bold(
1247
- `(Recommended)`
1248
- )}`
1249
- });
1250
- if (isCancel(result)) {
1251
- cancel(`\u270B Operating cancelled.`);
1252
- process.exit(0);
1253
- }
1254
- if (result) {
1255
- add_plugins.push(
1256
- supportedPlugins.find((x) => x.id === "next-cookies")
1257
- );
1258
- }
1259
- }
1260
- }
1261
- }
1262
- const filePath = path__default.join(cwd, "auth.ts");
1263
- config_path = filePath;
1264
- log.info(`Creating auth config file: ${filePath}`);
1265
- try {
1266
- current_user_config = await getDefaultAuthConfig({
1267
- appName
1268
- });
1269
- const { dependencies, envs, generatedCode } = await generateAuthConfig({
1270
- current_user_config,
1271
- format: format$1,
1272
- //@ts-expect-error
1273
- s,
1274
- plugins: add_plugins,
1275
- database
1276
- });
1277
- current_user_config = generatedCode;
1278
- await fs$1.writeFile(filePath, current_user_config);
1279
- config_path = filePath;
1280
- log.success(`\u{1F680} Auth config file successfully created!`);
1281
- if (envs.length !== 0) {
1282
- log.info(
1283
- `There are ${envs.length} environment variables for your database of choice.`
1284
- );
1285
- const shouldUpdateEnvs = await confirm({
1286
- message: `Would you like us to update your ENV files?`
1287
- });
1288
- if (isCancel(shouldUpdateEnvs)) {
1289
- cancel("\u270B Operation cancelled.");
1290
- process.exit(0);
1291
- }
1292
- if (shouldUpdateEnvs) {
1293
- const filesToUpdate = await multiselect({
1294
- message: "Select the .env files you want to update",
1295
- options: envFiles.map((x) => ({
1296
- value: path__default.join(cwd, x),
1297
- label: x
1298
- })),
1299
- required: false
1300
- });
1301
- if (isCancel(filesToUpdate)) {
1302
- cancel("\u270B Operation cancelled.");
1303
- process.exit(0);
1304
- }
1305
- if (filesToUpdate.length === 0) {
1306
- log.info("No .env files to update. Skipping...");
1307
- } else {
1308
- try {
1309
- await updateEnvs({
1310
- files: filesToUpdate,
1311
- envs,
1312
- isCommented: true
1313
- });
1314
- } catch (error) {
1315
- log.error(`Failed to update .env files:`);
1316
- log.error(JSON.stringify(error, null, 2));
1317
- process.exit(1);
1318
- }
1319
- log.success(`\u{1F680} ENV files successfully updated!`);
1320
- }
1321
- }
1322
- }
1323
- if (dependencies.length !== 0) {
1324
- log.info(
1325
- `There are ${dependencies.length} dependencies to install. (${dependencies.map((x) => chalk.green(x)).join(", ")})`
1326
- );
1327
- const shouldInstallDeps = await confirm({
1328
- message: `Would you like us to install dependencies?`
1329
- });
1330
- if (isCancel(shouldInstallDeps)) {
1331
- cancel("\u270B Operation cancelled.");
1332
- process.exit(0);
1333
- }
1334
- if (shouldInstallDeps) {
1335
- const s2 = spinner({ indicator: "dots" });
1336
- if (packageManagerPreference === void 0) {
1337
- packageManagerPreference = await getPackageManager$1();
1338
- }
1339
- s2.start(
1340
- `Installing dependencies using ${chalk.bold(
1341
- packageManagerPreference
1342
- )}...`
1343
- );
1344
- try {
1345
- const start = Date.now();
1346
- await installDependencies({
1347
- dependencies,
1348
- packageManager: packageManagerPreference,
1349
- cwd
1350
- });
1351
- s2.stop(
1352
- `Dependencies installed ${chalk.greenBright(
1353
- `successfully`
1354
- )} ${chalk.gray(
1355
- `(${formatMilliseconds(Date.now() - start)})`
1356
- )}`
1357
- );
1358
- } catch (error) {
1359
- s2.stop(
1360
- `Failed to install dependencies using ${packageManagerPreference}:`
1361
- );
1362
- log.error(error.message);
1363
- process.exit(1);
1364
- }
1365
- }
1366
- }
1367
- } catch (error) {
1368
- log.error(`Failed to create auth config file: ${filePath}`);
1369
- console.error(error);
1370
- process.exit(1);
1371
- }
1372
- } else if (shouldCreateAuthConfig === "no") {
1373
- log.info(`Skipping auth config file creation.`);
1374
- }
1375
- } else {
1376
- log.message();
1377
- log.success(`Found auth config file. ${chalk.gray(`(${config_path})`)}`);
1378
- log.message();
1379
- }
1380
- let possibleClientPaths = [
1381
- "auth-client.ts",
1382
- "auth-client.tsx",
1383
- "auth-client.js",
1384
- "auth-client.jsx",
1385
- "client.ts",
1386
- "client.tsx",
1387
- "client.js",
1388
- "client.jsx"
1389
- ];
1390
- possibleClientPaths = [
1391
- ...possibleClientPaths,
1392
- ...possibleClientPaths.map((it) => `lib/server/${it}`),
1393
- ...possibleClientPaths.map((it) => `server/${it}`),
1394
- ...possibleClientPaths.map((it) => `lib/${it}`),
1395
- ...possibleClientPaths.map((it) => `utils/${it}`)
1396
- ];
1397
- possibleClientPaths = [
1398
- ...possibleClientPaths,
1399
- ...possibleClientPaths.map((it) => `src/${it}`),
1400
- ...possibleClientPaths.map((it) => `app/${it}`)
1401
- ];
1402
- let authClientConfigPath = null;
1403
- for (const possiblePath of possibleClientPaths) {
1404
- const doesExist = existsSync(path__default.join(cwd, possiblePath));
1405
- if (doesExist) {
1406
- authClientConfigPath = path__default.join(cwd, possiblePath);
1407
- break;
1408
- }
1409
- }
1410
- if (!authClientConfigPath) {
1411
- const choice = await select({
1412
- message: `Would you like to create an auth client config file?`,
1413
- options: [
1414
- { label: "Yes", value: "yes" },
1415
- { label: "No", value: "no" }
1416
- ]
1417
- });
1418
- if (isCancel(choice)) {
1419
- cancel(`\u270B Operation cancelled.`);
1420
- process.exit(0);
1421
- }
1422
- if (choice === "yes") {
1423
- authClientConfigPath = path__default.join(cwd, "auth-client.ts");
1424
- log.info(`Creating auth client config file: ${authClientConfigPath}`);
1425
- try {
1426
- let contents = await getDefaultAuthClientConfig({
1427
- auth_config_path: ("./" + path__default.join(config_path.replace(cwd, ""))).replace(".//", "./"),
1428
- clientPlugins: add_plugins.filter((x) => x.clientName).map((plugin) => {
1429
- let contents2 = "";
1430
- if (plugin.id === "one-tap") {
1431
- contents2 = `{ clientId: "MY_CLIENT_ID" }`;
1432
- }
1433
- return {
1434
- contents: contents2,
1435
- id: plugin.id,
1436
- name: plugin.clientName,
1437
- imports: [
1438
- {
1439
- path: "better-auth/client/plugins",
1440
- variables: [{ name: plugin.clientName }]
1441
- }
1442
- ]
1443
- };
1444
- }),
1445
- framework
1446
- });
1447
- await fs$1.writeFile(authClientConfigPath, contents);
1448
- log.success(`\u{1F680} Auth client config file successfully created!`);
1449
- } catch (error) {
1450
- log.error(
1451
- `Failed to create auth client config file: ${authClientConfigPath}`
1452
- );
1453
- log.error(JSON.stringify(error, null, 2));
1454
- process.exit(1);
1455
- }
1456
- } else if (choice === "no") {
1457
- log.info(`Skipping auth client config file creation.`);
1458
- }
1459
- } else {
1460
- log.success(
1461
- `Found auth client config file. ${chalk.gray(
1462
- `(${authClientConfigPath})`
1463
- )}`
1464
- );
1465
- }
1466
- if (targetEnvFile !== "none") {
1467
- try {
1468
- const fileContents = await fs$1.readFile(
1469
- path__default.join(cwd, targetEnvFile),
1470
- "utf8"
1471
- );
1472
- const parsed = parse(fileContents);
1473
- let isMissingSecret = false;
1474
- let isMissingUrl = false;
1475
- if (parsed.BETTER_AUTH_SECRET === void 0) isMissingSecret = true;
1476
- if (parsed.BETTER_AUTH_URL === void 0) isMissingUrl = true;
1477
- if (isMissingSecret || isMissingUrl) {
1478
- let txt = "";
1479
- if (isMissingSecret && !isMissingUrl)
1480
- txt = chalk.bold(`BETTER_AUTH_SECRET`);
1481
- else if (!isMissingSecret && isMissingUrl)
1482
- txt = chalk.bold(`BETTER_AUTH_URL`);
1483
- else
1484
- txt = chalk.bold.underline(`BETTER_AUTH_SECRET`) + ` and ` + chalk.bold.underline(`BETTER_AUTH_URL`);
1485
- log.warn(`Missing ${txt} in ${targetEnvFile}`);
1486
- const shouldAdd = await select({
1487
- message: `Do you want to add ${txt} to ${targetEnvFile}?`,
1488
- options: [
1489
- { label: "Yes", value: "yes" },
1490
- { label: "No", value: "no" },
1491
- { label: "Choose other file(s)", value: "other" }
1492
- ]
1493
- });
1494
- if (isCancel(shouldAdd)) {
1495
- cancel(`\u270B Operation cancelled.`);
1496
- process.exit(0);
1497
- }
1498
- let envs = [];
1499
- if (isMissingSecret) {
1500
- envs.push("BETTER_AUTH_SECRET");
1501
- }
1502
- if (isMissingUrl) {
1503
- envs.push("BETTER_AUTH_URL");
1504
- }
1505
- if (shouldAdd === "yes") {
1506
- try {
1507
- await updateEnvs({
1508
- files: [path__default.join(cwd, targetEnvFile)],
1509
- envs,
1510
- isCommented: false
1511
- });
1512
- } catch (error) {
1513
- log.error(`Failed to add ENV variables to ${targetEnvFile}`);
1514
- log.error(JSON.stringify(error, null, 2));
1515
- process.exit(1);
1516
- }
1517
- log.success(`\u{1F680} ENV variables successfully added!`);
1518
- if (isMissingUrl) {
1519
- log.info(
1520
- `Be sure to update your BETTER_AUTH_URL according to your app's needs.`
1521
- );
1522
- }
1523
- } else if (shouldAdd === "no") {
1524
- log.info(`Skipping ENV step.`);
1525
- } else if (shouldAdd === "other") {
1526
- if (!envFiles.length) {
1527
- cancel("No env files found. Please create an env file first.");
1528
- process.exit(0);
1529
- }
1530
- const envFilesToUpdate = await multiselect({
1531
- message: "Select the .env files you want to update",
1532
- options: envFiles.map((x) => ({
1533
- value: path__default.join(cwd, x),
1534
- label: x
1535
- })),
1536
- required: false
1537
- });
1538
- if (isCancel(envFilesToUpdate)) {
1539
- cancel("\u270B Operation cancelled.");
1540
- process.exit(0);
1541
- }
1542
- if (envFilesToUpdate.length === 0) {
1543
- log.info("No .env files to update. Skipping...");
1544
- } else {
1545
- try {
1546
- await updateEnvs({
1547
- files: envFilesToUpdate,
1548
- envs,
1549
- isCommented: false
1550
- });
1551
- } catch (error) {
1552
- log.error(`Failed to update .env files:`);
1553
- log.error(JSON.stringify(error, null, 2));
1554
- process.exit(1);
1555
- }
1556
- log.success(`\u{1F680} ENV files successfully updated!`);
1557
- }
1558
- }
1559
- }
1560
- } catch (error) {
1561
- }
1562
- }
1563
- outro(outroText);
1564
- console.log();
1565
- process.exit(0);
1566
- }
1567
- const init = new Command("init").option("-c, --cwd <cwd>", "The working directory.", process.cwd()).option(
1568
- "--config <config>",
1569
- "The path to the auth configuration file. defaults to the first `auth.ts` file found."
1570
- ).option("--tsconfig <tsconfig>", "The path to the tsconfig file.").option("--skip-db", "Skip the database setup.").option("--skip-plugins", "Skip the plugins setup.").option(
1571
- "--package-manager <package-manager>",
1572
- "The package manager you want to use."
1573
- ).action(initAction);
1574
- async function getLatestNpmVersion(packageName) {
1575
- try {
1576
- const response = await fetch(`https://registry.npmjs.org/${packageName}`);
1577
- if (!response.ok) {
1578
- throw new Error(`Package not found: ${response.statusText}`);
1579
- }
1580
- const data = await response.json();
1581
- return data["dist-tags"].latest;
1582
- } catch (error) {
1583
- throw error?.message;
1584
- }
1585
- }
1586
- async function getPackageManager$1() {
1587
- const { hasBun, hasPnpm } = await checkPackageManagers();
1588
- if (!hasBun && !hasPnpm) return "npm";
1589
- const packageManagerOptions = [];
1590
- if (hasPnpm) {
1591
- packageManagerOptions.push({
1592
- value: "pnpm",
1593
- label: "pnpm",
1594
- hint: "recommended"
1595
- });
1596
- }
1597
- if (hasBun) {
1598
- packageManagerOptions.push({
1599
- value: "bun",
1600
- label: "bun"
1601
- });
1602
- }
1603
- packageManagerOptions.push({
1604
- value: "npm",
1605
- hint: "not recommended"
1606
- });
1607
- let packageManager = await select({
1608
- message: "Choose a package manager",
1609
- options: packageManagerOptions
1610
- });
1611
- if (isCancel(packageManager)) {
1612
- cancel(`Operation cancelled.`);
1613
- process.exit(0);
1614
- }
1615
- return packageManager;
1616
- }
1617
- async function getEnvFiles(cwd) {
1618
- const files = await fs$1.readdir(cwd);
1619
- return files.filter((x) => x.startsWith(".env"));
1620
- }
1621
- async function updateEnvs({
1622
- envs,
1623
- files,
1624
- isCommented
1625
- }) {
1626
- let previouslyGeneratedSecret = null;
1627
- for (const file of files) {
1628
- const content = await fs$1.readFile(file, "utf8");
1629
- const lines = content.split("\n");
1630
- const newLines = envs.map(
1631
- (x) => `${isCommented ? "# " : ""}${x}=${getEnvDescription(x) ?? `"some_value"`}`
1632
- );
1633
- newLines.push("");
1634
- newLines.push(...lines);
1635
- await fs$1.writeFile(file, newLines.join("\n"), "utf8");
1636
- }
1637
- function getEnvDescription(env) {
1638
- if (env === "DATABASE_HOST") {
1639
- return `"The host of your database"`;
1640
- }
1641
- if (env === "DATABASE_PORT") {
1642
- return `"The port of your database"`;
1643
- }
1644
- if (env === "DATABASE_USER") {
1645
- return `"The username of your database"`;
1646
- }
1647
- if (env === "DATABASE_PASSWORD") {
1648
- return `"The password of your database"`;
1649
- }
1650
- if (env === "DATABASE_NAME") {
1651
- return `"The name of your database"`;
1652
- }
1653
- if (env === "DATABASE_URL") {
1654
- return `"The URL of your database"`;
1655
- }
1656
- if (env === "BETTER_AUTH_SECRET") {
1657
- previouslyGeneratedSecret = previouslyGeneratedSecret ?? generateSecretHash();
1658
- return `"${previouslyGeneratedSecret}"`;
1659
- }
1660
- if (env === "BETTER_AUTH_URL") {
1661
- return `"http://localhost:3000" # Your APP URL`;
1662
- }
1663
- }
1664
- }
1665
-
1666
- function addSvelteKitEnvModules(aliases, cwd) {
1667
- const workingDir = process.cwd();
1668
- aliases["$env/dynamic/private"] = createDataUriModule(
1669
- createDynamicEnvModule()
1670
- );
1671
- aliases["$env/dynamic/public"] = createDataUriModule(
1672
- createDynamicEnvModule()
1673
- );
1674
- aliases["$env/static/private"] = createDataUriModule(
1675
- createStaticEnvModule(filterPrivateEnv("PUBLIC_", ""))
1676
- );
1677
- aliases["$env/static/public"] = createDataUriModule(
1678
- createStaticEnvModule(filterPublicEnv("PUBLIC_", ""))
1679
- );
1680
- const svelteKitAliases = getSvelteKitPathAliases(workingDir);
1681
- Object.assign(aliases, svelteKitAliases);
1682
- }
1683
- function getSvelteKitPathAliases(cwd) {
1684
- const aliases = {};
1685
- const packageJsonPath = path__default.join(cwd, "package.json");
1686
- const svelteConfigPath = path__default.join(cwd, "svelte.config.js");
1687
- const svelteConfigTsPath = path__default.join(cwd, "svelte.config.ts");
1688
- let isSvelteKitProject = false;
1689
- if (fs__default.existsSync(packageJsonPath)) {
1690
- try {
1691
- const packageJson = JSON.parse(fs__default.readFileSync(packageJsonPath, "utf-8"));
1692
- const deps = {
1693
- ...packageJson.dependencies,
1694
- ...packageJson.devDependencies
1695
- };
1696
- isSvelteKitProject = !!deps["@sveltejs/kit"];
1697
- } catch {
1698
- }
1699
- }
1700
- if (!isSvelteKitProject) {
1701
- isSvelteKitProject = fs__default.existsSync(svelteConfigPath) || fs__default.existsSync(svelteConfigTsPath);
1702
- }
1703
- if (!isSvelteKitProject) {
1704
- return aliases;
1705
- }
1706
- const libPaths = [path__default.join(cwd, "src", "lib"), path__default.join(cwd, "lib")];
1707
- for (const libPath of libPaths) {
1708
- if (fs__default.existsSync(libPath)) {
1709
- aliases["$lib"] = libPath;
1710
- const commonSubPaths = ["server", "utils", "components", "stores"];
1711
- for (const subPath of commonSubPaths) {
1712
- const subDir = path__default.join(libPath, subPath);
1713
- if (fs__default.existsSync(subDir)) {
1714
- aliases[`$lib/${subPath}`] = subDir;
1715
- }
1716
- }
1717
- break;
1718
- }
1719
- }
1720
- aliases["$app/server"] = createDataUriModule(createAppServerModule());
1721
- const customAliases = getSvelteConfigAliases(cwd);
1722
- Object.assign(aliases, customAliases);
1723
- return aliases;
1724
- }
1725
- function getSvelteConfigAliases(cwd) {
1726
- const aliases = {};
1727
- const configPaths = [
1728
- path__default.join(cwd, "svelte.config.js"),
1729
- path__default.join(cwd, "svelte.config.ts")
1730
- ];
1731
- for (const configPath of configPaths) {
1732
- if (fs__default.existsSync(configPath)) {
1733
- try {
1734
- const content = fs__default.readFileSync(configPath, "utf-8");
1735
- const aliasMatch = content.match(/alias\s*:\s*\{([^}]+)\}/);
1736
- if (aliasMatch && aliasMatch[1]) {
1737
- const aliasContent = aliasMatch[1];
1738
- const aliasMatches = aliasContent.matchAll(
1739
- /['"`](\$[^'"`]+)['"`]\s*:\s*['"`]([^'"`]+)['"`]/g
1740
- );
1741
- for (const match of aliasMatches) {
1742
- const [, alias, target] = match;
1743
- if (alias && target) {
1744
- aliases[alias + "/*"] = path__default.resolve(cwd, target) + "/*";
1745
- aliases[alias] = path__default.resolve(cwd, target);
1746
- }
1747
- }
1748
- }
1749
- } catch {
1750
- }
1751
- break;
1752
- }
1753
- }
1754
- return aliases;
1755
- }
1756
- function createAppServerModule() {
1757
- return `
1758
- // $app/server stub for CLI compatibility
1759
- export default {};
1760
- // jiti dirty hack: .unknown
1761
- `;
1762
- }
1763
- function createDataUriModule(module) {
1764
- return `data:text/javascript;charset=utf-8,${encodeURIComponent(module)}`;
1765
- }
1766
- function createStaticEnvModule(env) {
1767
- const declarations = Object.keys(env).filter((k) => validIdentifier.test(k) && !reserved.has(k)).map((k) => `export const ${k} = ${JSON.stringify(env[k])};`);
1768
- return `
1769
- ${declarations.join("\n")}
1770
- // jiti dirty hack: .unknown
1771
- `;
1772
- }
1773
- function createDynamicEnvModule() {
1774
- return `
1775
- export const env = process.env;
1776
- // jiti dirty hack: .unknown
1777
- `;
1778
- }
1779
- function filterPrivateEnv(publicPrefix, privatePrefix) {
1780
- return Object.fromEntries(
1781
- Object.entries(process.env).filter(
1782
- ([k]) => k.startsWith(privatePrefix) && (!k.startsWith(publicPrefix))
1783
- )
1784
- );
1785
- }
1786
- function filterPublicEnv(publicPrefix, privatePrefix) {
1787
- return Object.fromEntries(
1788
- Object.entries(process.env).filter(
1789
- ([k]) => k.startsWith(publicPrefix) && (privatePrefix === "")
1790
- )
1791
- );
1792
- }
1793
- const validIdentifier = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
1794
- const reserved = /* @__PURE__ */ new Set([
1795
- "do",
1796
- "if",
1797
- "in",
1798
- "for",
1799
- "let",
1800
- "new",
1801
- "try",
1802
- "var",
1803
- "case",
1804
- "else",
1805
- "enum",
1806
- "eval",
1807
- "null",
1808
- "this",
1809
- "true",
1810
- "void",
1811
- "with",
1812
- "await",
1813
- "break",
1814
- "catch",
1815
- "class",
1816
- "const",
1817
- "false",
1818
- "super",
1819
- "throw",
1820
- "while",
1821
- "yield",
1822
- "delete",
1823
- "export",
1824
- "import",
1825
- "public",
1826
- "return",
1827
- "static",
1828
- "switch",
1829
- "typeof",
1830
- "default",
1831
- "extends",
1832
- "finally",
1833
- "package",
1834
- "private",
1835
- "continue",
1836
- "debugger",
1837
- "function",
1838
- "arguments",
1839
- "interface",
1840
- "protected",
1841
- "implements",
1842
- "instanceof"
1843
- ]);
1844
-
1845
- let possiblePaths = [
1846
- "auth.ts",
1847
- "auth.tsx",
1848
- "auth.js",
1849
- "auth.jsx",
1850
- "auth.server.js",
1851
- "auth.server.ts"
1852
- ];
1853
- possiblePaths = [
1854
- ...possiblePaths,
1855
- ...possiblePaths.map((it) => `lib/server/${it}`),
1856
- ...possiblePaths.map((it) => `server/${it}`),
1857
- ...possiblePaths.map((it) => `lib/${it}`),
1858
- ...possiblePaths.map((it) => `utils/${it}`)
1859
- ];
1860
- possiblePaths = [
1861
- ...possiblePaths,
1862
- ...possiblePaths.map((it) => `src/${it}`),
1863
- ...possiblePaths.map((it) => `app/${it}`)
1864
- ];
1865
- function resolveReferencePath(configDir, refPath) {
1866
- const resolvedPath = path__default.resolve(configDir, refPath);
1867
- if (refPath.endsWith(".json")) {
1868
- return resolvedPath;
1869
- }
1870
- if (fs__default.existsSync(resolvedPath)) {
1871
- try {
1872
- const stats = fs__default.statSync(resolvedPath);
1873
- if (stats.isFile()) {
1874
- return resolvedPath;
1875
- }
1876
- } catch {
1877
- }
1878
- }
1879
- return path__default.resolve(configDir, refPath, "tsconfig.json");
1880
- }
1881
- function getPathAliasesRecursive(tsconfigPath, visited = /* @__PURE__ */ new Set()) {
1882
- if (visited.has(tsconfigPath)) {
1883
- return {};
1884
- }
1885
- visited.add(tsconfigPath);
1886
- if (!fs__default.existsSync(tsconfigPath)) {
1887
- logger.warn(`Referenced tsconfig not found: ${tsconfigPath}`);
1888
- return {};
1889
- }
1890
- try {
1891
- const tsConfig = getTsconfigInfo(void 0, tsconfigPath);
1892
- const { paths = {}, baseUrl = "." } = tsConfig.compilerOptions || {};
1893
- const result = {};
1894
- const configDir = path__default.dirname(tsconfigPath);
1895
- const obj = Object.entries(paths);
1896
- for (const [alias, aliasPaths] of obj) {
1897
- for (const aliasedPath of aliasPaths) {
1898
- const resolvedBaseUrl = path__default.resolve(configDir, baseUrl);
1899
- const finalAlias = alias.slice(-1) === "*" ? alias.slice(0, -1) : alias;
1900
- const finalAliasedPath = aliasedPath.slice(-1) === "*" ? aliasedPath.slice(0, -1) : aliasedPath;
1901
- result[finalAlias || ""] = path__default.join(resolvedBaseUrl, finalAliasedPath);
1902
- }
1903
- }
1904
- if (tsConfig.references) {
1905
- for (const ref of tsConfig.references) {
1906
- const refPath = resolveReferencePath(configDir, ref.path);
1907
- const refAliases = getPathAliasesRecursive(refPath, visited);
1908
- for (const [alias, aliasPath] of Object.entries(refAliases)) {
1909
- if (!(alias in result)) {
1910
- result[alias] = aliasPath;
1911
- }
1912
- }
1913
- }
1914
- }
1915
- return result;
1916
- } catch (error) {
1917
- logger.warn(`Error parsing tsconfig at ${tsconfigPath}: ${error}`);
1918
- return {};
1919
- }
1920
- }
1921
- function getPathAliases(cwd) {
1922
- const tsConfigPath = path__default.join(cwd, "tsconfig.json");
1923
- if (!fs__default.existsSync(tsConfigPath)) {
1924
- return null;
1925
- }
1926
- try {
1927
- const result = getPathAliasesRecursive(tsConfigPath);
1928
- addSvelteKitEnvModules(result);
1929
- return result;
1930
- } catch (error) {
1931
- console.error(error);
1932
- throw new BetterAuthError("Error parsing tsconfig.json");
1933
- }
1934
- }
1935
- const jitiOptions = (cwd) => {
1936
- const alias = getPathAliases(cwd) || {};
1937
- return {
1938
- transformOptions: {
1939
- babel: {
1940
- presets: [
1941
- [
1942
- babelPresetTypeScript,
1943
- {
1944
- isTSX: true,
1945
- allExtensions: true
1946
- }
1947
- ],
1948
- [babelPresetReact, { runtime: "automatic" }]
1949
- ]
1950
- }
1951
- },
1952
- extensions: [".ts", ".tsx", ".js", ".jsx"],
1953
- alias
1954
- };
1955
- };
1956
- const isDefaultExport = (object) => {
1957
- return typeof object === "object" && object !== null && !Array.isArray(object) && Object.keys(object).length > 0 && "options" in object;
1958
- };
1959
- async function getConfig({
1960
- cwd,
1961
- configPath,
1962
- shouldThrowOnError = false
1963
- }) {
1964
- try {
1965
- let configFile = null;
1966
- if (configPath) {
1967
- let resolvedPath = path__default.join(cwd, configPath);
1968
- if (existsSync(configPath)) resolvedPath = configPath;
1969
- const { config } = await loadConfig({
1970
- configFile: resolvedPath,
1971
- dotenv: true,
1972
- jitiOptions: jitiOptions(cwd)
1973
- });
1974
- if (!("auth" in config) && !isDefaultExport(config)) {
1975
- if (shouldThrowOnError) {
1976
- throw new Error(
1977
- `Couldn't read your auth config in ${resolvedPath}. Make sure to default export your auth instance or to export as a variable named auth.`
1978
- );
1979
- }
1980
- logger.error(
1981
- `[#better-auth]: Couldn't read your auth config in ${resolvedPath}. Make sure to default export your auth instance or to export as a variable named auth.`
1982
- );
1983
- process.exit(1);
1984
- }
1985
- configFile = "auth" in config ? config.auth?.options : config.options;
1986
- }
1987
- if (!configFile) {
1988
- for (const possiblePath of possiblePaths) {
1989
- try {
1990
- const { config } = await loadConfig({
1991
- configFile: possiblePath,
1992
- jitiOptions: jitiOptions(cwd)
1993
- });
1994
- const hasConfig = Object.keys(config).length > 0;
1995
- if (hasConfig) {
1996
- configFile = config.auth?.options || config.default?.options || null;
1997
- if (!configFile) {
1998
- if (shouldThrowOnError) {
1999
- throw new Error(
2000
- "Couldn't read your auth config. Make sure to default export your auth instance or to export as a variable named auth."
2001
- );
2002
- }
2003
- logger.error("[#better-auth]: Couldn't read your auth config.");
2004
- console.log("");
2005
- logger.info(
2006
- "[#better-auth]: Make sure to default export your auth instance or to export as a variable named auth."
2007
- );
2008
- process.exit(1);
2009
- }
2010
- break;
2011
- }
2012
- } catch (e) {
2013
- if (typeof e === "object" && e && "message" in e && typeof e.message === "string" && e.message.includes(
2014
- "This module cannot be imported from a Client Component module"
2015
- )) {
2016
- if (shouldThrowOnError) {
2017
- throw new Error(
2018
- `Please remove import 'server-only' from your auth config file temporarily. The CLI cannot resolve the configuration with it included. You can re-add it after running the CLI.`
2019
- );
2020
- }
2021
- logger.error(
2022
- `Please remove import 'server-only' from your auth config file temporarily. The CLI cannot resolve the configuration with it included. You can re-add it after running the CLI.`
2023
- );
2024
- process.exit(1);
2025
- }
2026
- if (shouldThrowOnError) {
2027
- throw e;
2028
- }
2029
- logger.error("[#better-auth]: Couldn't read your auth config.", e);
2030
- process.exit(1);
2031
- }
2032
- }
2033
- }
2034
- return configFile;
2035
- } catch (e) {
2036
- if (typeof e === "object" && e && "message" in e && typeof e.message === "string" && e.message.includes(
2037
- "This module cannot be imported from a Client Component module"
2038
- )) {
2039
- if (shouldThrowOnError) {
2040
- throw new Error(
2041
- `Please remove import 'server-only' from your auth config file temporarily. The CLI cannot resolve the configuration with it included. You can re-add it after running the CLI.`
2042
- );
2043
- }
2044
- logger.error(
2045
- `Please remove import 'server-only' from your auth config file temporarily. The CLI cannot resolve the configuration with it included. You can re-add it after running the CLI.`
2046
- );
2047
- process.exit(1);
2048
- }
2049
- if (shouldThrowOnError) {
2050
- throw e;
2051
- }
2052
- logger.error("Couldn't read your auth config.", e);
2053
- process.exit(1);
2054
- }
2055
- }
2056
-
2057
- async function migrateAction(opts) {
2058
- const options = z.object({
2059
- cwd: z.string(),
2060
- config: z.string().optional(),
2061
- y: z.boolean().optional(),
2062
- yes: z.boolean().optional()
2063
- }).parse(opts);
2064
- const cwd = path__default.resolve(options.cwd);
2065
- if (!existsSync(cwd)) {
2066
- logger.error(`The directory "${cwd}" does not exist.`);
2067
- process.exit(1);
2068
- }
2069
- const config = await getConfig({
2070
- cwd,
2071
- configPath: options.config
2072
- });
2073
- if (!config) {
2074
- logger.error(
2075
- "No configuration file found. Add a `auth.ts` file to your project or pass the path to the configuration file using the `--config` flag."
2076
- );
2077
- return;
2078
- }
2079
- const db = await getAdapter(config);
2080
- if (!db) {
2081
- logger.error(
2082
- "Invalid database configuration. Make sure you're not using adapters. Migrate command only works with built-in Kysely adapter."
2083
- );
2084
- process.exit(1);
2085
- }
2086
- if (db.id !== "kysely") {
2087
- if (db.id === "prisma") {
2088
- logger.error(
2089
- "The migrate command only works with the built-in Kysely adapter. For Prisma, run `npx @better-auth/cli generate` to create the schema, then use Prisma\u2019s migrate or push to apply it."
2090
- );
2091
- try {
2092
- const telemetry = await createTelemetry(config);
2093
- await telemetry.publish({
2094
- type: "cli_migrate",
2095
- payload: {
2096
- outcome: "unsupported_adapter",
2097
- adapter: "prisma",
2098
- config: getTelemetryAuthConfig(config)
2099
- }
2100
- });
2101
- } catch {
2102
- }
2103
- process.exit(0);
2104
- }
2105
- if (db.id === "drizzle") {
2106
- logger.error(
2107
- "The migrate command only works with the built-in Kysely adapter. For Drizzle, run `npx @better-auth/cli generate` to create the schema, then use Drizzle\u2019s migrate or push to apply it."
2108
- );
2109
- try {
2110
- const telemetry = await createTelemetry(config);
2111
- await telemetry.publish({
2112
- type: "cli_migrate",
2113
- payload: {
2114
- outcome: "unsupported_adapter",
2115
- adapter: "drizzle",
2116
- config: getTelemetryAuthConfig(config)
2117
- }
2118
- });
2119
- } catch {
2120
- }
2121
- process.exit(0);
2122
- }
2123
- logger.error("Migrate command isn't supported for this adapter.");
2124
- try {
2125
- const telemetry = await createTelemetry(config);
2126
- await telemetry.publish({
2127
- type: "cli_migrate",
2128
- payload: {
2129
- outcome: "unsupported_adapter",
2130
- adapter: db.id,
2131
- config: getTelemetryAuthConfig(config)
2132
- }
2133
- });
2134
- } catch {
2135
- }
2136
- process.exit(1);
2137
- }
2138
- const spinner = yoctoSpinner({ text: "preparing migration..." }).start();
2139
- const { toBeAdded, toBeCreated, runMigrations } = await getMigrations(config);
2140
- if (!toBeAdded.length && !toBeCreated.length) {
2141
- spinner.stop();
2142
- logger.info("\u{1F680} No migrations needed.");
2143
- try {
2144
- const telemetry = await createTelemetry(config);
2145
- await telemetry.publish({
2146
- type: "cli_migrate",
2147
- payload: {
2148
- outcome: "no_changes",
2149
- config: getTelemetryAuthConfig(config)
2150
- }
2151
- });
2152
- } catch {
2153
- }
2154
- process.exit(0);
2155
- }
2156
- spinner.stop();
2157
- logger.info(`\u{1F511} The migration will affect the following:`);
2158
- for (const table of [...toBeCreated, ...toBeAdded]) {
2159
- console.log(
2160
- "->",
2161
- chalk.magenta(Object.keys(table.fields).join(", ")),
2162
- chalk.white("fields on"),
2163
- chalk.yellow(`${table.table}`),
2164
- chalk.white("table.")
2165
- );
2166
- }
2167
- if (options.y) {
2168
- console.warn("WARNING: --y is deprecated. Consider -y or --yes");
2169
- options.yes = true;
2170
- }
2171
- let migrate2 = options.yes;
2172
- if (!migrate2) {
2173
- const response = await prompts({
2174
- type: "confirm",
2175
- name: "migrate",
2176
- message: "Are you sure you want to run these migrations?",
2177
- initial: false
2178
- });
2179
- migrate2 = response.migrate;
2180
- }
2181
- if (!migrate2) {
2182
- logger.info("Migration cancelled.");
2183
- try {
2184
- const telemetry = await createTelemetry(config);
2185
- await telemetry.publish({
2186
- type: "cli_migrate",
2187
- payload: { outcome: "aborted", config: getTelemetryAuthConfig(config) }
2188
- });
2189
- } catch {
2190
- }
2191
- process.exit(0);
2192
- }
2193
- spinner?.start("migrating...");
2194
- await runMigrations();
2195
- spinner.stop();
2196
- logger.info("\u{1F680} migration was completed successfully!");
2197
- try {
2198
- const telemetry = await createTelemetry(config);
2199
- await telemetry.publish({
2200
- type: "cli_migrate",
2201
- payload: { outcome: "migrated", config: getTelemetryAuthConfig(config) }
2202
- });
2203
- } catch {
2204
- }
2205
- process.exit(0);
2206
- }
2207
- const migrate = new Command("migrate").option(
2208
- "-c, --cwd <cwd>",
2209
- "the working directory. defaults to the current directory.",
2210
- process.cwd()
2211
- ).option(
2212
- "--config <config>",
2213
- "the path to the configuration file. defaults to the first configuration file found."
2214
- ).option(
2215
- "-y, --yes",
2216
- "automatically accept and run migrations without prompting",
2217
- false
2218
- ).option("--y", "(deprecated) same as --yes", false).action(migrateAction);
2219
-
2220
- function convertToSnakeCase(str, camelCase) {
2221
- if (camelCase) {
2222
- return str;
2223
- }
2224
- return str.replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").replace(/([a-z\d])([A-Z])/g, "$1_$2").toLowerCase();
2225
- }
2226
- const generateDrizzleSchema = async ({
2227
- options,
2228
- file,
2229
- adapter
2230
- }) => {
2231
- const tables = getAuthTables(options);
2232
- const filePath = file || "./auth-schema.ts";
2233
- const databaseType = adapter.options?.provider;
2234
- if (!databaseType) {
2235
- throw new Error(
2236
- `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`
2237
- );
2238
- }
2239
- const fileExist = existsSync(filePath);
2240
- let code = generateImport({ databaseType, tables, options });
2241
- for (const tableKey in tables) {
2242
- let getType = function(name, field) {
2243
- if (!databaseType) {
2244
- throw new Error(
2245
- `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`
2246
- );
2247
- }
2248
- name = convertToSnakeCase(name, adapter.options?.camelCase);
2249
- if (field.references?.field === "id") {
2250
- if (options.advanced?.database?.useNumberId) {
2251
- if (databaseType === "pg") {
2252
- return `integer('${name}')`;
2253
- } else if (databaseType === "mysql") {
2254
- return `int('${name}')`;
2255
- } else {
2256
- return `integer('${name}')`;
2257
- }
2258
- }
2259
- if (field.references.field) {
2260
- if (databaseType === "mysql") {
2261
- return `varchar('${name}', { length: 36 })`;
2262
- }
2263
- }
2264
- return `text('${name}')`;
2265
- }
2266
- const type = field.type;
2267
- const typeMap = {
2268
- string: {
2269
- sqlite: `text('${name}')`,
2270
- pg: `text('${name}')`,
2271
- mysql: field.unique ? `varchar('${name}', { length: 255 })` : field.references ? `varchar('${name}', { length: 36 })` : `text('${name}')`
2272
- },
2273
- boolean: {
2274
- sqlite: `integer('${name}', { mode: 'boolean' })`,
2275
- pg: `boolean('${name}')`,
2276
- mysql: `boolean('${name}')`
2277
- },
2278
- number: {
2279
- sqlite: `integer('${name}')`,
2280
- pg: field.bigint ? `bigint('${name}', { mode: 'number' })` : `integer('${name}')`,
2281
- mysql: field.bigint ? `bigint('${name}', { mode: 'number' })` : `int('${name}')`
2282
- },
2283
- date: {
2284
- sqlite: `integer('${name}', { mode: 'timestamp_ms' })`,
2285
- pg: `timestamp('${name}')`,
2286
- mysql: `timestamp('${name}', { fsp: 3 })`
2287
- },
2288
- "number[]": {
2289
- sqlite: `integer('${name}').array()`,
2290
- pg: field.bigint ? `bigint('${name}', { mode: 'number' }).array()` : `integer('${name}').array()`,
2291
- mysql: field.bigint ? `bigint('${name}', { mode: 'number' }).array()` : `int('${name}').array()`
2292
- },
2293
- "string[]": {
2294
- sqlite: `text('${name}').array()`,
2295
- pg: `text('${name}').array()`,
2296
- mysql: `text('${name}').array()`
2297
- },
2298
- json: {
2299
- sqlite: `text('${name}')`,
2300
- pg: `jsonb('${name}')`,
2301
- mysql: `json('${name}')`
2302
- }
2303
- };
2304
- return typeMap[type][databaseType];
2305
- };
2306
- const table = tables[tableKey];
2307
- const modelName = getModelName(table.modelName, adapter.options);
2308
- const fields = table.fields;
2309
- let id = "";
2310
- if (options.advanced?.database?.useNumberId) {
2311
- if (databaseType === "pg") {
2312
- id = `serial("id").primaryKey()`;
2313
- } else if (databaseType === "sqlite") {
2314
- id = `integer("id", { mode: "number" }).primaryKey({ autoIncrement: true })`;
2315
- } else {
2316
- id = `int("id").autoincrement().primaryKey()`;
2317
- }
2318
- } else {
2319
- if (databaseType === "mysql") {
2320
- id = `varchar('id', { length: 36 }).primaryKey()`;
2321
- } else if (databaseType === "pg") {
2322
- id = `text('id').primaryKey()`;
2323
- } else {
2324
- id = `text('id').primaryKey()`;
2325
- }
2326
- }
2327
- const schema = `export const ${modelName} = ${databaseType}Table("${convertToSnakeCase(
2328
- modelName,
2329
- adapter.options?.camelCase
2330
- )}", {
2331
- id: ${id},
2332
- ${Object.keys(fields).map((field) => {
2333
- const attr = fields[field];
2334
- const fieldName = attr.fieldName || field;
2335
- let type = getType(fieldName, attr);
2336
- if (attr.defaultValue !== null && typeof attr.defaultValue !== "undefined") {
2337
- if (typeof attr.defaultValue === "function") {
2338
- if (attr.type === "date" && attr.defaultValue.toString().includes("new Date()")) {
2339
- if (databaseType === "sqlite") {
2340
- type += `.default(sql\`(cast(unixepoch('subsecond') * 1000 as integer))\`)`;
2341
- } else {
2342
- type += `.defaultNow()`;
2343
- }
2344
- } else {
2345
- type += `.$defaultFn(${attr.defaultValue})`;
2346
- }
2347
- } else if (typeof attr.defaultValue === "string") {
2348
- type += `.default("${attr.defaultValue}")`;
2349
- } else {
2350
- type += `.default(${attr.defaultValue})`;
2351
- }
2352
- }
2353
- if (attr.onUpdate && attr.type === "date") {
2354
- if (typeof attr.onUpdate === "function") {
2355
- type += `.$onUpdate(${attr.onUpdate})`;
2356
- }
2357
- }
2358
- return `${fieldName}: ${type}${attr.required ? ".notNull()" : ""}${attr.unique ? ".unique()" : ""}${attr.references ? `.references(()=> ${getModelName(
2359
- tables[attr.references.model]?.modelName || attr.references.model,
2360
- adapter.options
2361
- )}.${fields[attr.references.field]?.fieldName || attr.references.field}, { onDelete: '${attr.references.onDelete || "cascade"}' })` : ""}`;
2362
- }).join(",\n ")}
2363
- });`;
2364
- code += `
2365
- ${schema}
2366
- `;
2367
- }
2368
- const formattedCode = await prettier.format(code, {
2369
- parser: "typescript"
2370
- });
2371
- return {
2372
- code: formattedCode,
2373
- fileName: filePath,
2374
- overwrite: fileExist
2375
- };
2376
- };
2377
- function generateImport({
2378
- databaseType,
2379
- tables,
2380
- options
2381
- }) {
2382
- const rootImports = [];
2383
- const coreImports = [];
2384
- let hasBigint = false;
2385
- let hasJson = false;
2386
- for (const table of Object.values(tables)) {
2387
- for (const field of Object.values(table.fields)) {
2388
- if (field.bigint) hasBigint = true;
2389
- if (field.type === "json") hasJson = true;
2390
- }
2391
- if (hasJson && hasBigint) break;
2392
- }
2393
- const useNumberId = options.advanced?.database?.useNumberId;
2394
- coreImports.push(`${databaseType}Table`);
2395
- coreImports.push(
2396
- databaseType === "mysql" ? "varchar, text" : databaseType === "pg" ? "text" : "text"
2397
- );
2398
- coreImports.push(
2399
- hasBigint ? databaseType !== "sqlite" ? "bigint" : "" : ""
2400
- );
2401
- coreImports.push(databaseType !== "sqlite" ? "timestamp, boolean" : "");
2402
- if (databaseType === "mysql") {
2403
- const hasNonBigintNumber = Object.values(tables).some(
2404
- (table) => Object.values(table.fields).some(
2405
- (field) => (field.type === "number" || field.type === "number[]") && !field.bigint
2406
- )
2407
- );
2408
- const needsInt = !!useNumberId || hasNonBigintNumber;
2409
- if (needsInt) {
2410
- coreImports.push("int");
2411
- }
2412
- } else if (databaseType === "pg") {
2413
- const hasNonBigintNumber = Object.values(tables).some(
2414
- (table) => Object.values(table.fields).some(
2415
- (field) => (field.type === "number" || field.type === "number[]") && !field.bigint
2416
- )
2417
- );
2418
- const hasFkToId = Object.values(tables).some(
2419
- (table) => Object.values(table.fields).some(
2420
- (field) => field.references?.field === "id"
2421
- )
2422
- );
2423
- const needsInteger = hasNonBigintNumber || options.advanced?.database?.useNumberId && hasFkToId;
2424
- if (needsInteger) {
2425
- coreImports.push("integer");
2426
- }
2427
- } else {
2428
- coreImports.push("integer");
2429
- }
2430
- coreImports.push(useNumberId ? databaseType === "pg" ? "serial" : "" : "");
2431
- if (hasJson) {
2432
- if (databaseType === "pg") coreImports.push("jsonb");
2433
- if (databaseType === "mysql") coreImports.push("json");
2434
- }
2435
- const hasSQLiteTimestamp = databaseType === "sqlite" && Object.values(tables).some(
2436
- (table) => Object.values(table.fields).some(
2437
- (field) => field.type === "date" && field.defaultValue && typeof field.defaultValue === "function" && field.defaultValue.toString().includes("new Date()")
2438
- )
2439
- );
2440
- if (hasSQLiteTimestamp) {
2441
- rootImports.push("sql");
2442
- }
2443
- return `${rootImports.length > 0 ? `import { ${rootImports.join(", ")} } from "drizzle-orm";
2444
- ` : ""}import { ${coreImports.map((x) => x.trim()).filter((x) => x !== "").join(", ")} } from "drizzle-orm/${databaseType}-core";
2445
- `;
2446
- }
2447
- function getModelName(modelName, options) {
2448
- return options?.usePlural ? `${modelName}s` : modelName;
2449
- }
2450
-
2451
- const generatePrismaSchema = async ({
2452
- adapter,
2453
- options,
2454
- file
2455
- }) => {
2456
- const provider = adapter.options?.provider || "postgresql";
2457
- const tables = getAuthTables(options);
2458
- const filePath = file || "./prisma/schema.prisma";
2459
- const schemaPrismaExist = existsSync(path__default.join(process.cwd(), filePath));
2460
- let schemaPrisma = "";
2461
- if (schemaPrismaExist) {
2462
- schemaPrisma = await fs$1.readFile(
2463
- path__default.join(process.cwd(), filePath),
2464
- "utf-8"
2465
- );
2466
- } else {
2467
- schemaPrisma = getNewPrisma(provider);
2468
- }
2469
- const manyToManyRelations = /* @__PURE__ */ new Map();
2470
- for (const table in tables) {
2471
- const fields = tables[table]?.fields;
2472
- for (const field in fields) {
2473
- const attr = fields[field];
2474
- if (attr.references) {
2475
- const referencedOriginalModel = attr.references.model;
2476
- const referencedCustomModel = tables[referencedOriginalModel]?.modelName || referencedOriginalModel;
2477
- const referencedModelNameCap = capitalizeFirstLetter(
2478
- referencedCustomModel
2479
- );
2480
- if (!manyToManyRelations.has(referencedModelNameCap)) {
2481
- manyToManyRelations.set(referencedModelNameCap, /* @__PURE__ */ new Set());
2482
- }
2483
- const currentCustomModel = tables[table]?.modelName || table;
2484
- const currentModelNameCap = capitalizeFirstLetter(currentCustomModel);
2485
- manyToManyRelations.get(referencedModelNameCap).add(currentModelNameCap);
2486
- }
2487
- }
2488
- }
2489
- const schema = produceSchema(schemaPrisma, (builder) => {
2490
- for (const table in tables) {
2491
- let getType = function({
2492
- isBigint,
2493
- isOptional,
2494
- type
2495
- }) {
2496
- if (type === "string") {
2497
- return isOptional ? "String?" : "String";
2498
- }
2499
- if (type === "number" && isBigint) {
2500
- return isOptional ? "BigInt?" : "BigInt";
2501
- }
2502
- if (type === "number") {
2503
- return isOptional ? "Int?" : "Int";
2504
- }
2505
- if (type === "boolean") {
2506
- return isOptional ? "Boolean?" : "Boolean";
2507
- }
2508
- if (type === "date") {
2509
- return isOptional ? "DateTime?" : "DateTime";
2510
- }
2511
- if (type === "json") {
2512
- return isOptional ? "Json?" : "Json";
2513
- }
2514
- if (type === "string[]") {
2515
- return isOptional ? "String[]" : "String[]";
2516
- }
2517
- if (type === "number[]") {
2518
- return isOptional ? "Int[]" : "Int[]";
2519
- }
2520
- };
2521
- const originalTableName = table;
2522
- const customModelName = tables[table]?.modelName || table;
2523
- const modelName = capitalizeFirstLetter(customModelName);
2524
- const fields = tables[table]?.fields;
2525
- const prismaModel = builder.findByType("model", {
2526
- name: modelName
2527
- });
2528
- if (!prismaModel) {
2529
- if (provider === "mongodb") {
2530
- builder.model(modelName).field("id", "String").attribute("id").attribute(`map("_id")`);
2531
- } else {
2532
- if (options.advanced?.database?.useNumberId) {
2533
- builder.model(modelName).field("id", "Int").attribute("id").attribute("default(autoincrement())");
2534
- } else {
2535
- builder.model(modelName).field("id", "String").attribute("id");
2536
- }
2537
- }
2538
- }
2539
- for (const field in fields) {
2540
- const attr = fields[field];
2541
- const fieldName = attr.fieldName || field;
2542
- if (prismaModel) {
2543
- const isAlreadyExist = builder.findByType("field", {
2544
- name: fieldName,
2545
- within: prismaModel.properties
2546
- });
2547
- if (isAlreadyExist) {
2548
- continue;
2549
- }
2550
- }
2551
- const fieldBuilder = builder.model(modelName).field(
2552
- fieldName,
2553
- field === "id" && options.advanced?.database?.useNumberId ? getType({
2554
- isBigint: false,
2555
- isOptional: false,
2556
- type: "number"
2557
- }) : getType({
2558
- isBigint: attr?.bigint || false,
2559
- isOptional: !attr?.required,
2560
- type: attr.references?.field === "id" ? options.advanced?.database?.useNumberId ? "number" : "string" : attr.type
2561
- })
2562
- );
2563
- if (field === "id") {
2564
- fieldBuilder.attribute("id");
2565
- if (provider === "mongodb") {
2566
- fieldBuilder.attribute(`map("_id")`);
2567
- }
2568
- }
2569
- if (attr.unique) {
2570
- builder.model(modelName).blockAttribute(`unique([${fieldName}])`);
2571
- }
2572
- if (attr.defaultValue !== void 0) {
2573
- if (field === "createdAt") {
2574
- fieldBuilder.attribute("default(now())");
2575
- } else if (typeof attr.defaultValue === "boolean") {
2576
- fieldBuilder.attribute(`default(${attr.defaultValue})`);
2577
- } else if (typeof attr.defaultValue === "function") {
2578
- const defaultVal = attr.defaultValue();
2579
- if (defaultVal instanceof Date) {
2580
- fieldBuilder.attribute("default(now())");
2581
- } else {
2582
- console.warn(
2583
- `Warning: Unsupported default function for field ${fieldName} in model ${modelName}. Please adjust manually.`
2584
- );
2585
- }
2586
- }
2587
- }
2588
- if (field === "updatedAt" && attr.onUpdate) {
2589
- fieldBuilder.attribute("updatedAt");
2590
- } else if (attr.onUpdate) {
2591
- console.warn(
2592
- `Warning: 'onUpdate' is only supported on 'updatedAt' fields. Please adjust manually for field ${fieldName} in model ${modelName}.`
2593
- );
2594
- }
2595
- if (attr.references) {
2596
- const referencedOriginalModelName = attr.references.model;
2597
- const referencedCustomModelName = tables[referencedOriginalModelName]?.modelName || referencedOriginalModelName;
2598
- let action = "Cascade";
2599
- if (attr.references.onDelete === "no action") action = "NoAction";
2600
- else if (attr.references.onDelete === "set null") action = "SetNull";
2601
- else if (attr.references.onDelete === "set default")
2602
- action = "SetDefault";
2603
- else if (attr.references.onDelete === "restrict") action = "Restrict";
2604
- builder.model(modelName).field(
2605
- `${referencedCustomModelName.toLowerCase()}`,
2606
- `${capitalizeFirstLetter(referencedCustomModelName)}${!attr.required ? "?" : ""}`
2607
- ).attribute(
2608
- `relation(fields: [${fieldName}], references: [${attr.references.field}], onDelete: ${action})`
2609
- );
2610
- }
2611
- if (!attr.unique && !attr.references && provider === "mysql" && attr.type === "string") {
2612
- builder.model(modelName).field(fieldName).attribute("db.Text");
2613
- }
2614
- }
2615
- if (manyToManyRelations.has(modelName)) {
2616
- for (const relatedModel of manyToManyRelations.get(modelName)) {
2617
- const fieldName = `${relatedModel.toLowerCase()}s`;
2618
- const existingField = builder.findByType("field", {
2619
- name: fieldName,
2620
- within: prismaModel?.properties
2621
- });
2622
- if (!existingField) {
2623
- builder.model(modelName).field(fieldName, `${relatedModel}[]`);
2624
- }
2625
- }
2626
- }
2627
- const hasAttribute = builder.findByType("attribute", {
2628
- name: "map",
2629
- within: prismaModel?.properties
2630
- });
2631
- const hasChanged = customModelName !== originalTableName;
2632
- if (!hasAttribute) {
2633
- builder.model(modelName).blockAttribute(
2634
- "map",
2635
- `${hasChanged ? customModelName : originalTableName}`
2636
- );
2637
- }
2638
- }
2639
- });
2640
- const schemaChanged = schema.trim() !== schemaPrisma.trim();
2641
- return {
2642
- code: schemaChanged ? schema : "",
2643
- fileName: filePath,
2644
- overwrite: schemaPrismaExist && schemaChanged
2645
- };
2646
- };
2647
- const getNewPrisma = (provider) => `generator client {
2648
- provider = "prisma-client-js"
2649
- }
2650
-
2651
- datasource db {
2652
- provider = "${provider}"
2653
- url = ${provider === "sqlite" ? `"file:./dev.db"` : `env("DATABASE_URL")`}
2654
- }`;
2655
-
2656
- const generateMigrations = async ({
2657
- options,
2658
- file
2659
- }) => {
2660
- const { compileMigrations } = await getMigrations(options);
2661
- const migrations = await compileMigrations();
2662
- return {
2663
- code: migrations.trim() === ";" ? "" : migrations,
2664
- fileName: file || `./better-auth_migrations/${(/* @__PURE__ */ new Date()).toISOString().replace(/:/g, "-")}.sql`
2665
- };
2666
- };
2667
-
2668
- const adapters = {
2669
- prisma: generatePrismaSchema,
2670
- drizzle: generateDrizzleSchema,
2671
- kysely: generateMigrations
2672
- };
2673
- const generateSchema = (opts) => {
2674
- const adapter = opts.adapter;
2675
- const generator = adapter.id in adapters ? adapters[adapter.id] : null;
2676
- if (generator) {
2677
- return generator(opts);
2678
- }
2679
- if (adapter.createSchema) {
2680
- return adapter.createSchema(opts.options, opts.file).then(({ code, path: fileName, overwrite }) => ({
2681
- code,
2682
- fileName,
2683
- overwrite
2684
- }));
2685
- }
2686
- logger.error(
2687
- `${adapter.id} is not supported. If it is a custom adapter, please request the maintainer to implement createSchema`
2688
- );
2689
- process.exit(1);
2690
- };
2691
-
2692
- async function generateAction(opts) {
2693
- const options = z.object({
2694
- cwd: z.string(),
2695
- config: z.string().optional(),
2696
- output: z.string().optional(),
2697
- y: z.boolean().optional(),
2698
- yes: z.boolean().optional()
2699
- }).parse(opts);
2700
- const cwd = path__default.resolve(options.cwd);
2701
- if (!existsSync(cwd)) {
2702
- logger.error(`The directory "${cwd}" does not exist.`);
2703
- process.exit(1);
2704
- }
2705
- const config = await getConfig({
2706
- cwd,
2707
- configPath: options.config
2708
- });
2709
- if (!config) {
2710
- logger.error(
2711
- "No configuration file found. Add a `auth.ts` file to your project or pass the path to the configuration file using the `--config` flag."
2712
- );
2713
- return;
2714
- }
2715
- const adapter = await getAdapter(config).catch((e) => {
2716
- logger.error(e.message);
2717
- process.exit(1);
2718
- });
2719
- const spinner = yoctoSpinner({ text: "preparing schema..." }).start();
2720
- const schema = await generateSchema({
2721
- adapter,
2722
- file: options.output,
2723
- options: config
2724
- });
2725
- spinner.stop();
2726
- if (!schema.code) {
2727
- logger.info("Your schema is already up to date.");
2728
- try {
2729
- const telemetry = await createTelemetry(config);
2730
- await telemetry.publish({
2731
- type: "cli_generate",
2732
- payload: {
2733
- outcome: "no_changes",
2734
- config: getTelemetryAuthConfig(config, {
2735
- adapter: adapter.id,
2736
- database: typeof config.database === "function" ? "adapter" : "kysely"
2737
- })
2738
- }
2739
- });
2740
- } catch {
2741
- }
2742
- process.exit(0);
2743
- }
2744
- if (schema.overwrite) {
2745
- let confirm2 = options.y || options.yes;
2746
- if (!confirm2) {
2747
- const response = await prompts({
2748
- type: "confirm",
2749
- name: "confirm",
2750
- message: `The file ${schema.fileName} already exists. Do you want to ${chalk.yellow(
2751
- `${schema.overwrite ? "overwrite" : "append"}`
2752
- )} the schema to the file?`
2753
- });
2754
- confirm2 = response.confirm;
2755
- }
2756
- if (confirm2) {
2757
- const exist = existsSync(path__default.join(cwd, schema.fileName));
2758
- if (!exist) {
2759
- await fs$1.mkdir(path__default.dirname(path__default.join(cwd, schema.fileName)), {
2760
- recursive: true
2761
- });
2762
- }
2763
- if (schema.overwrite) {
2764
- await fs$1.writeFile(path__default.join(cwd, schema.fileName), schema.code);
2765
- } else {
2766
- await fs$1.appendFile(path__default.join(cwd, schema.fileName), schema.code);
2767
- }
2768
- logger.success(
2769
- `\u{1F680} Schema was ${schema.overwrite ? "overwritten" : "appended"} successfully!`
2770
- );
2771
- try {
2772
- const telemetry = await createTelemetry(config);
2773
- await telemetry.publish({
2774
- type: "cli_generate",
2775
- payload: {
2776
- outcome: schema.overwrite ? "overwritten" : "appended",
2777
- config: getTelemetryAuthConfig(config)
2778
- }
2779
- });
2780
- } catch {
2781
- }
2782
- process.exit(0);
2783
- } else {
2784
- logger.error("Schema generation aborted.");
2785
- try {
2786
- const telemetry = await createTelemetry(config);
2787
- await telemetry.publish({
2788
- type: "cli_generate",
2789
- payload: {
2790
- outcome: "aborted",
2791
- config: getTelemetryAuthConfig(config)
2792
- }
2793
- });
2794
- } catch {
2795
- }
2796
- process.exit(1);
2797
- }
2798
- }
2799
- if (options.y) {
2800
- console.warn("WARNING: --y is deprecated. Consider -y or --yes");
2801
- options.yes = true;
2802
- }
2803
- let confirm = options.yes;
2804
- if (!confirm) {
2805
- const response = await prompts({
2806
- type: "confirm",
2807
- name: "confirm",
2808
- message: `Do you want to generate the schema to ${chalk.yellow(
2809
- schema.fileName
2810
- )}?`
2811
- });
2812
- confirm = response.confirm;
2813
- }
2814
- if (!confirm) {
2815
- logger.error("Schema generation aborted.");
2816
- try {
2817
- const telemetry = await createTelemetry(config);
2818
- await telemetry.publish({
2819
- type: "cli_generate",
2820
- payload: { outcome: "aborted", config: getTelemetryAuthConfig(config) }
2821
- });
2822
- } catch {
2823
- }
2824
- process.exit(1);
2825
- }
2826
- if (!options.output) {
2827
- const dirExist = existsSync(path__default.dirname(path__default.join(cwd, schema.fileName)));
2828
- if (!dirExist) {
2829
- await fs$1.mkdir(path__default.dirname(path__default.join(cwd, schema.fileName)), {
2830
- recursive: true
2831
- });
2832
- }
2833
- }
2834
- await fs$1.writeFile(
2835
- options.output || path__default.join(cwd, schema.fileName),
2836
- schema.code
2837
- );
2838
- logger.success(`\u{1F680} Schema was generated successfully!`);
2839
- try {
2840
- const telemetry = await createTelemetry(config);
2841
- await telemetry.publish({
2842
- type: "cli_generate",
2843
- payload: { outcome: "generated", config: getTelemetryAuthConfig(config) }
2844
- });
2845
- } catch {
2846
- }
2847
- process.exit(0);
2848
- }
2849
- const generate = new Command("generate").option(
2850
- "-c, --cwd <cwd>",
2851
- "the working directory. defaults to the current directory.",
2852
- process.cwd()
2853
- ).option(
2854
- "--config <config>",
2855
- "the path to the configuration file. defaults to the first configuration file found."
2856
- ).option("--output <output>", "the file to output to the generated schema").option("-y, --yes", "automatically answer yes to all prompts", false).option("--y", "(deprecated) same as --yes", false).action(generateAction);
2857
-
2858
- const DEMO_URL = "https://demo.better-auth.com";
2859
- const CLIENT_ID = "better-auth-cli";
2860
- const CONFIG_DIR = path__default.join(os__default.homedir(), ".better-auth");
2861
- const TOKEN_FILE = path__default.join(CONFIG_DIR, "token.json");
2862
- async function loginAction(opts) {
2863
- const options = z.object({
2864
- serverUrl: z.string().optional(),
2865
- clientId: z.string().optional()
2866
- }).parse(opts);
2867
- const serverUrl = options.serverUrl || DEMO_URL;
2868
- const clientId = options.clientId || CLIENT_ID;
2869
- intro(chalk.bold("\u{1F510} Better Auth CLI Login (Demo)"));
2870
- console.log(
2871
- chalk.yellow(
2872
- "\u26A0\uFE0F This is a demo feature for testing device authorization flow."
2873
- )
2874
- );
2875
- console.log(
2876
- chalk.gray(
2877
- " It connects to the Better Auth demo server for testing purposes.\n"
2878
- )
2879
- );
2880
- const existingToken = await getStoredToken();
2881
- if (existingToken) {
2882
- const shouldReauth = await confirm({
2883
- message: "You're already logged in. Do you want to log in again?",
2884
- initialValue: false
2885
- });
2886
- if (isCancel(shouldReauth) || !shouldReauth) {
2887
- cancel("Login cancelled");
2888
- process.exit(0);
2889
- }
2890
- }
2891
- const authClient = createAuthClient({
2892
- baseURL: serverUrl,
2893
- plugins: [deviceAuthorizationClient()]
2894
- });
2895
- const spinner = yoctoSpinner({ text: "Requesting device authorization..." });
2896
- spinner.start();
2897
- try {
2898
- const { data, error } = await authClient.device.code({
2899
- client_id: clientId,
2900
- scope: "openid profile email"
2901
- });
2902
- spinner.stop();
2903
- if (error || !data) {
2904
- logger.error(
2905
- `Failed to request device authorization: ${error?.error_description || "Unknown error"}`
2906
- );
2907
- process.exit(1);
2908
- }
2909
- const {
2910
- device_code,
2911
- user_code,
2912
- verification_uri,
2913
- verification_uri_complete,
2914
- interval = 5,
2915
- expires_in
2916
- } = data;
2917
- console.log("");
2918
- console.log(chalk.cyan("\u{1F4F1} Device Authorization Required"));
2919
- console.log("");
2920
- console.log(`Please visit: ${chalk.underline.blue(verification_uri)}`);
2921
- console.log(`Enter code: ${chalk.bold.green(user_code)}`);
2922
- console.log("");
2923
- const shouldOpen = await confirm({
2924
- message: "Open browser automatically?",
2925
- initialValue: true
2926
- });
2927
- if (!isCancel(shouldOpen) && shouldOpen) {
2928
- const urlToOpen = verification_uri_complete || verification_uri;
2929
- await open(urlToOpen);
2930
- }
2931
- console.log(
2932
- chalk.gray(
2933
- `Waiting for authorization (expires in ${Math.floor(expires_in / 60)} minutes)...`
2934
- )
2935
- );
2936
- const token = await pollForToken(
2937
- authClient,
2938
- device_code,
2939
- clientId,
2940
- interval
2941
- );
2942
- if (token) {
2943
- await storeToken(token);
2944
- const { data: session } = await authClient.getSession({
2945
- fetchOptions: {
2946
- headers: {
2947
- Authorization: `Bearer ${token.access_token}`
2948
- }
2949
- }
2950
- });
2951
- outro(
2952
- chalk.green(
2953
- `\u2705 Demo login successful! Logged in as ${session?.user?.name || session?.user?.email || "User"}`
2954
- )
2955
- );
2956
- console.log(
2957
- chalk.gray(
2958
- "\n\u{1F4DD} Note: This was a demo authentication for testing purposes."
2959
- )
2960
- );
2961
- console.log(
2962
- chalk.blue(
2963
- "\nFor more information, visit: https://better-auth.com/docs/plugins/device-authorization"
2964
- )
2965
- );
2966
- }
2967
- } catch (err) {
2968
- spinner.stop();
2969
- logger.error(
2970
- `Login failed: ${err instanceof Error ? err.message : "Unknown error"}`
2971
- );
2972
- process.exit(1);
2973
- }
2974
- }
2975
- async function pollForToken(authClient, deviceCode, clientId, initialInterval) {
2976
- let pollingInterval = initialInterval;
2977
- const spinner = yoctoSpinner({ text: "", color: "cyan" });
2978
- let dots = 0;
2979
- return new Promise((resolve, reject) => {
2980
- const poll = async () => {
2981
- dots = (dots + 1) % 4;
2982
- spinner.text = chalk.gray(
2983
- `Polling for authorization${".".repeat(dots)}${" ".repeat(3 - dots)}`
2984
- );
2985
- if (!spinner.isSpinning) spinner.start();
2986
- try {
2987
- const { data, error } = await authClient.device.token({
2988
- grant_type: "urn:ietf:params:oauth:grant-type:device_code",
2989
- device_code: deviceCode,
2990
- client_id: clientId,
2991
- fetchOptions: {
2992
- headers: {
2993
- "user-agent": `Better Auth CLI`
2994
- }
2995
- }
2996
- });
2997
- if (data?.access_token) {
2998
- spinner.stop();
2999
- resolve(data);
3000
- return;
3001
- } else if (error) {
3002
- switch (error.error) {
3003
- case "authorization_pending":
3004
- break;
3005
- case "slow_down":
3006
- pollingInterval += 5;
3007
- spinner.text = chalk.yellow(
3008
- `Slowing down polling to ${pollingInterval}s`
3009
- );
3010
- break;
3011
- case "access_denied":
3012
- spinner.stop();
3013
- logger.error("Access was denied by the user");
3014
- process.exit(1);
3015
- break;
3016
- case "expired_token":
3017
- spinner.stop();
3018
- logger.error("The device code has expired. Please try again.");
3019
- process.exit(1);
3020
- break;
3021
- default:
3022
- spinner.stop();
3023
- logger.error(`Error: ${error.error_description}`);
3024
- process.exit(1);
3025
- }
3026
- }
3027
- } catch (err) {
3028
- spinner.stop();
3029
- logger.error(
3030
- `Network error: ${err instanceof Error ? err.message : "Unknown error"}`
3031
- );
3032
- process.exit(1);
3033
- }
3034
- setTimeout(poll, pollingInterval * 1e3);
3035
- };
3036
- setTimeout(poll, pollingInterval * 1e3);
3037
- });
3038
- }
3039
- async function storeToken(token) {
3040
- try {
3041
- await fs$1.mkdir(CONFIG_DIR, { recursive: true });
3042
- const tokenData = {
3043
- access_token: token.access_token,
3044
- token_type: token.token_type || "Bearer",
3045
- scope: token.scope,
3046
- created_at: (/* @__PURE__ */ new Date()).toISOString()
3047
- };
3048
- await fs$1.writeFile(TOKEN_FILE, JSON.stringify(tokenData, null, 2), "utf-8");
3049
- } catch (error) {
3050
- logger.warn("Failed to store authentication token locally");
3051
- }
3052
- }
3053
- async function getStoredToken() {
3054
- try {
3055
- const data = await fs$1.readFile(TOKEN_FILE, "utf-8");
3056
- return JSON.parse(data);
3057
- } catch {
3058
- return null;
3059
- }
3060
- }
3061
- const login = new Command("login").description(
3062
- "Demo: Test device authorization flow with Better Auth demo server"
3063
- ).option("--server-url <url>", "The Better Auth server URL", DEMO_URL).option("--client-id <id>", "The OAuth client ID", CLIENT_ID).action(loginAction);
3064
-
3065
- function getSystemInfo() {
3066
- const platform = os__default.platform();
3067
- const arch = os__default.arch();
3068
- const version = os__default.version();
3069
- const release = os__default.release();
3070
- const cpus = os__default.cpus();
3071
- const memory = os__default.totalmem();
3072
- const freeMemory = os__default.freemem();
3073
- return {
3074
- platform,
3075
- arch,
3076
- version,
3077
- release,
3078
- cpuCount: cpus.length,
3079
- cpuModel: cpus[0]?.model || "Unknown",
3080
- totalMemory: `${(memory / 1024 / 1024 / 1024).toFixed(2)} GB`,
3081
- freeMemory: `${(freeMemory / 1024 / 1024 / 1024).toFixed(2)} GB`
3082
- };
3083
- }
3084
- function getNodeInfo() {
3085
- return {
3086
- version: process.version,
3087
- env: process.env.NODE_ENV || "development"
3088
- };
3089
- }
3090
- function getPackageManager() {
3091
- const userAgent = process.env.npm_config_user_agent || "";
3092
- if (userAgent.includes("yarn")) {
3093
- return { name: "yarn", version: getVersion("yarn") };
3094
- }
3095
- if (userAgent.includes("pnpm")) {
3096
- return { name: "pnpm", version: getVersion("pnpm") };
3097
- }
3098
- if (userAgent.includes("bun")) {
3099
- return { name: "bun", version: getVersion("bun") };
3100
- }
3101
- return { name: "npm", version: getVersion("npm") };
3102
- }
3103
- function getVersion(command) {
3104
- try {
3105
- const output = execSync(`${command} --version`, { encoding: "utf8" });
3106
- return output.trim();
3107
- } catch {
3108
- return "Not installed";
3109
- }
3110
- }
3111
- function getFrameworkInfo(projectRoot) {
3112
- const packageJsonPath = path__default.join(projectRoot, "package.json");
3113
- if (!existsSync(packageJsonPath)) {
3114
- return null;
3115
- }
3116
- try {
3117
- const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf8"));
3118
- const deps = {
3119
- ...packageJson.dependencies,
3120
- ...packageJson.devDependencies
3121
- };
3122
- const frameworks = {
3123
- next: deps["next"],
3124
- react: deps["react"],
3125
- vue: deps["vue"],
3126
- nuxt: deps["nuxt"],
3127
- svelte: deps["svelte"],
3128
- "@sveltejs/kit": deps["@sveltejs/kit"],
3129
- express: deps["express"],
3130
- fastify: deps["fastify"],
3131
- hono: deps["hono"],
3132
- remix: deps["@remix-run/react"],
3133
- astro: deps["astro"],
3134
- solid: deps["solid-js"],
3135
- qwik: deps["@builder.io/qwik"]
3136
- };
3137
- const installedFrameworks = Object.entries(frameworks).filter(([_, version]) => version).map(([name, version]) => ({ name, version }));
3138
- return installedFrameworks.length > 0 ? installedFrameworks : null;
3139
- } catch {
3140
- return null;
3141
- }
3142
- }
3143
- function getDatabaseInfo(projectRoot) {
3144
- const packageJsonPath = path__default.join(projectRoot, "package.json");
3145
- if (!existsSync(packageJsonPath)) {
3146
- return null;
3147
- }
3148
- try {
3149
- const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf8"));
3150
- const deps = {
3151
- ...packageJson.dependencies,
3152
- ...packageJson.devDependencies
3153
- };
3154
- const databases = {
3155
- "better-sqlite3": deps["better-sqlite3"],
3156
- "@libsql/client": deps["@libsql/client"],
3157
- "@libsql/kysely-libsql": deps["@libsql/kysely-libsql"],
3158
- mysql2: deps["mysql2"],
3159
- pg: deps["pg"],
3160
- postgres: deps["postgres"],
3161
- "@prisma/client": deps["@prisma/client"],
3162
- drizzle: deps["drizzle-orm"],
3163
- kysely: deps["kysely"],
3164
- mongodb: deps["mongodb"],
3165
- "@neondatabase/serverless": deps["@neondatabase/serverless"],
3166
- "@vercel/postgres": deps["@vercel/postgres"],
3167
- "@planetscale/database": deps["@planetscale/database"]
3168
- };
3169
- const installedDatabases = Object.entries(databases).filter(([_, version]) => version).map(([name, version]) => ({ name, version }));
3170
- return installedDatabases.length > 0 ? installedDatabases : null;
3171
- } catch {
3172
- return null;
3173
- }
3174
- }
3175
- function sanitizeBetterAuthConfig(config) {
3176
- if (!config) return null;
3177
- const sanitized = JSON.parse(JSON.stringify(config));
3178
- const sensitiveKeys = [
3179
- "secret",
3180
- "clientSecret",
3181
- "clientId",
3182
- "authToken",
3183
- "apiKey",
3184
- "apiSecret",
3185
- "privateKey",
3186
- "publicKey",
3187
- "password",
3188
- "token",
3189
- "webhook",
3190
- "connectionString",
3191
- "databaseUrl",
3192
- "databaseURL",
3193
- "TURSO_AUTH_TOKEN",
3194
- "TURSO_DATABASE_URL",
3195
- "MYSQL_DATABASE_URL",
3196
- "DATABASE_URL",
3197
- "POSTGRES_URL",
3198
- "MONGODB_URI",
3199
- "stripeKey",
3200
- "stripeWebhookSecret"
3201
- ];
3202
- const allowedKeys = [
3203
- "baseURL",
3204
- "callbackURL",
3205
- "redirectURL",
3206
- "trustedOrigins",
3207
- "appName"
3208
- ];
3209
- function redactSensitive(obj, parentKey) {
3210
- if (typeof obj !== "object" || obj === null) {
3211
- if (parentKey && typeof obj === "string" && obj.length > 0) {
3212
- if (allowedKeys.some(
3213
- (allowed) => parentKey.toLowerCase() === allowed.toLowerCase()
3214
- )) {
3215
- return obj;
3216
- }
3217
- const lowerKey = parentKey.toLowerCase();
3218
- if (sensitiveKeys.some((key) => {
3219
- const lowerSensitiveKey = key.toLowerCase();
3220
- return lowerKey === lowerSensitiveKey || lowerKey.endsWith(lowerSensitiveKey);
3221
- })) {
3222
- return "[REDACTED]";
3223
- }
3224
- }
3225
- return obj;
3226
- }
3227
- if (Array.isArray(obj)) {
3228
- return obj.map((item) => redactSensitive(item, parentKey));
3229
- }
3230
- const result = {};
3231
- for (const [key, value] of Object.entries(obj)) {
3232
- if (allowedKeys.some(
3233
- (allowed) => key.toLowerCase() === allowed.toLowerCase()
3234
- )) {
3235
- result[key] = value;
3236
- continue;
3237
- }
3238
- const lowerKey = key.toLowerCase();
3239
- if (sensitiveKeys.some((sensitiveKey) => {
3240
- const lowerSensitiveKey = sensitiveKey.toLowerCase();
3241
- return lowerKey === lowerSensitiveKey || lowerKey.endsWith(lowerSensitiveKey);
3242
- })) {
3243
- if (typeof value === "string" && value.length > 0) {
3244
- result[key] = "[REDACTED]";
3245
- } else if (typeof value === "object" && value !== null) {
3246
- result[key] = redactSensitive(value, key);
3247
- } else {
3248
- result[key] = value;
3249
- }
3250
- } else {
3251
- result[key] = redactSensitive(value, key);
3252
- }
3253
- }
3254
- return result;
3255
- }
3256
- if (sanitized.database) {
3257
- if (typeof sanitized.database === "string") {
3258
- sanitized.database = "[REDACTED]";
3259
- } else if (sanitized.database.url) {
3260
- sanitized.database.url = "[REDACTED]";
3261
- }
3262
- if (sanitized.database.authToken) {
3263
- sanitized.database.authToken = "[REDACTED]";
3264
- }
3265
- }
3266
- if (sanitized.socialProviders) {
3267
- for (const provider in sanitized.socialProviders) {
3268
- if (sanitized.socialProviders[provider]) {
3269
- sanitized.socialProviders[provider] = redactSensitive(
3270
- sanitized.socialProviders[provider],
3271
- provider
3272
- );
3273
- }
3274
- }
3275
- }
3276
- if (sanitized.emailAndPassword?.sendResetPassword) {
3277
- sanitized.emailAndPassword.sendResetPassword = "[Function]";
3278
- }
3279
- if (sanitized.emailVerification?.sendVerificationEmail) {
3280
- sanitized.emailVerification.sendVerificationEmail = "[Function]";
3281
- }
3282
- if (sanitized.plugins && Array.isArray(sanitized.plugins)) {
3283
- sanitized.plugins = sanitized.plugins.map((plugin) => {
3284
- if (typeof plugin === "function") {
3285
- return "[Plugin Function]";
3286
- }
3287
- if (plugin && typeof plugin === "object") {
3288
- const pluginName = plugin.id || plugin.name || "unknown";
3289
- return {
3290
- name: pluginName,
3291
- config: redactSensitive(plugin.config || plugin)
3292
- };
3293
- }
3294
- return plugin;
3295
- });
3296
- }
3297
- return redactSensitive(sanitized);
3298
- }
3299
- async function getBetterAuthInfo(projectRoot, configPath, suppressLogs = false) {
3300
- try {
3301
- const originalLog = console.log;
3302
- const originalWarn = console.warn;
3303
- const originalError = console.error;
3304
- if (suppressLogs) {
3305
- console.log = () => {
3306
- };
3307
- console.warn = () => {
3308
- };
3309
- console.error = () => {
3310
- };
3311
- }
3312
- try {
3313
- const config = await getConfig({
3314
- cwd: projectRoot,
3315
- configPath,
3316
- shouldThrowOnError: false
3317
- });
3318
- const packageInfo = await getPackageInfo();
3319
- const betterAuthVersion = packageInfo.dependencies?.["better-auth"] || packageInfo.devDependencies?.["better-auth"] || packageInfo.peerDependencies?.["better-auth"] || packageInfo.optionalDependencies?.["better-auth"] || "Unknown";
3320
- return {
3321
- version: betterAuthVersion,
3322
- config: sanitizeBetterAuthConfig(config)
3323
- };
3324
- } finally {
3325
- if (suppressLogs) {
3326
- console.log = originalLog;
3327
- console.warn = originalWarn;
3328
- console.error = originalError;
3329
- }
3330
- }
3331
- } catch (error) {
3332
- return {
3333
- version: "Unknown",
3334
- config: null,
3335
- error: error instanceof Error ? error.message : "Failed to load Better Auth config"
3336
- };
3337
- }
3338
- }
3339
- function formatOutput(data, indent = 0) {
3340
- const spaces = " ".repeat(indent);
3341
- if (data === null || data === void 0) {
3342
- return `${spaces}${chalk.gray("N/A")}`;
3343
- }
3344
- if (typeof data === "string" || typeof data === "number" || typeof data === "boolean") {
3345
- return `${spaces}${data}`;
3346
- }
3347
- if (Array.isArray(data)) {
3348
- if (data.length === 0) {
3349
- return `${spaces}${chalk.gray("[]")}`;
3350
- }
3351
- return data.map((item) => formatOutput(item, indent)).join("\n");
3352
- }
3353
- if (typeof data === "object") {
3354
- const entries = Object.entries(data);
3355
- if (entries.length === 0) {
3356
- return `${spaces}${chalk.gray("{}")}`;
3357
- }
3358
- return entries.map(([key, value]) => {
3359
- if (typeof value === "object" && value !== null && !Array.isArray(value)) {
3360
- return `${spaces}${chalk.cyan(key)}:
3361
- ${formatOutput(value, indent + 2)}`;
3362
- }
3363
- return `${spaces}${chalk.cyan(key)}: ${formatOutput(value, 0)}`;
3364
- }).join("\n");
3365
- }
3366
- return `${spaces}${JSON.stringify(data)}`;
3367
- }
3368
- const info = new Command("info").description("Display system and Better Auth configuration information").option("--cwd <cwd>", "The working directory", process.cwd()).option("--config <config>", "Path to the Better Auth configuration file").option("-j, --json", "Output as JSON").option("-c, --copy", "Copy output to clipboard (requires pbcopy/xclip)").action(async (options) => {
3369
- const projectRoot = path__default.resolve(options.cwd || process.cwd());
3370
- const systemInfo = getSystemInfo();
3371
- const nodeInfo = getNodeInfo();
3372
- const packageManager = getPackageManager();
3373
- const frameworks = getFrameworkInfo(projectRoot);
3374
- const databases = getDatabaseInfo(projectRoot);
3375
- const betterAuthInfo = await getBetterAuthInfo(
3376
- projectRoot,
3377
- options.config,
3378
- options.json
3379
- );
3380
- const fullInfo = {
3381
- system: systemInfo,
3382
- node: nodeInfo,
3383
- packageManager,
3384
- frameworks,
3385
- databases,
3386
- betterAuth: betterAuthInfo
3387
- };
3388
- if (options.json) {
3389
- const jsonOutput = JSON.stringify(fullInfo, null, 2);
3390
- console.log(jsonOutput);
3391
- if (options.copy) {
3392
- try {
3393
- const platform = os__default.platform();
3394
- if (platform === "darwin") {
3395
- execSync("pbcopy", { input: jsonOutput });
3396
- console.log(chalk.green("\n\u2713 Copied to clipboard"));
3397
- } else if (platform === "linux") {
3398
- execSync("xclip -selection clipboard", { input: jsonOutput });
3399
- console.log(chalk.green("\n\u2713 Copied to clipboard"));
3400
- } else if (platform === "win32") {
3401
- execSync("clip", { input: jsonOutput });
3402
- console.log(chalk.green("\n\u2713 Copied to clipboard"));
3403
- }
3404
- } catch {
3405
- console.log(chalk.yellow("\n\u26A0 Could not copy to clipboard"));
3406
- }
3407
- }
3408
- return;
3409
- }
3410
- console.log(chalk.bold("\n\u{1F4CA} Better Auth System Information\n"));
3411
- console.log(chalk.gray("=".repeat(50)));
3412
- console.log(chalk.bold.white("\n\u{1F5A5}\uFE0F System Information:"));
3413
- console.log(formatOutput(systemInfo, 2));
3414
- console.log(chalk.bold.white("\n\u{1F4E6} Node.js:"));
3415
- console.log(formatOutput(nodeInfo, 2));
3416
- console.log(chalk.bold.white("\n\u{1F4E6} Package Manager:"));
3417
- console.log(formatOutput(packageManager, 2));
3418
- if (frameworks) {
3419
- console.log(chalk.bold.white("\n\u{1F680} Frameworks:"));
3420
- console.log(formatOutput(frameworks, 2));
3421
- }
3422
- if (databases) {
3423
- console.log(chalk.bold.white("\n\u{1F4BE} Database Clients:"));
3424
- console.log(formatOutput(databases, 2));
3425
- }
3426
- console.log(chalk.bold.white("\n\u{1F510} Better Auth:"));
3427
- if (betterAuthInfo.error) {
3428
- console.log(` ${chalk.red("Error:")} ${betterAuthInfo.error}`);
3429
- } else {
3430
- console.log(` ${chalk.cyan("Version")}: ${betterAuthInfo.version}`);
3431
- if (betterAuthInfo.config) {
3432
- console.log(` ${chalk.cyan("Configuration")}:`);
3433
- console.log(formatOutput(betterAuthInfo.config, 4));
3434
- }
3435
- }
3436
- console.log(chalk.gray("\n" + "=".repeat(50)));
3437
- console.log(chalk.gray("\n\u{1F4A1} Tip: Use --json flag for JSON output"));
3438
- console.log(chalk.gray("\u{1F4A1} Use --copy flag to copy output to clipboard"));
3439
- console.log(
3440
- chalk.gray("\u{1F4A1} When reporting issues, include this information\n")
3441
- );
3442
- if (options.copy) {
3443
- const textOutput = `
3444
- Better Auth System Information
3445
- ==============================
3446
-
3447
- System Information:
3448
- ${JSON.stringify(systemInfo, null, 2)}
3449
-
3450
- Node.js:
3451
- ${JSON.stringify(nodeInfo, null, 2)}
3452
-
3453
- Package Manager:
3454
- ${JSON.stringify(packageManager, null, 2)}
3455
-
3456
- Frameworks:
3457
- ${JSON.stringify(frameworks, null, 2)}
3458
-
3459
- Database Clients:
3460
- ${JSON.stringify(databases, null, 2)}
3461
-
3462
- Better Auth:
3463
- ${JSON.stringify(betterAuthInfo, null, 2)}
3464
- `;
3465
- try {
3466
- const platform = os__default.platform();
3467
- if (platform === "darwin") {
3468
- execSync("pbcopy", { input: textOutput });
3469
- console.log(chalk.green("\u2713 Copied to clipboard"));
3470
- } else if (platform === "linux") {
3471
- execSync("xclip -selection clipboard", { input: textOutput });
3472
- console.log(chalk.green("\u2713 Copied to clipboard"));
3473
- } else if (platform === "win32") {
3474
- execSync("clip", { input: textOutput });
3475
- console.log(chalk.green("\u2713 Copied to clipboard"));
3476
- }
3477
- } catch {
3478
- console.log(chalk.yellow("\u26A0 Could not copy to clipboard"));
3479
- }
3480
- }
3481
- });
3482
-
3483
- async function mcpAction(options) {
3484
- const mcpUrl = "https://mcp.chonkie.ai/better-auth/better-auth-builder/mcp";
3485
- const mcpName = "Better Auth";
3486
- if (options.cursor) {
3487
- await handleCursorAction(mcpUrl, mcpName);
3488
- } else if (options.claudeCode) {
3489
- handleClaudeCodeAction(mcpUrl);
3490
- } else if (options.openCode) {
3491
- handleOpenCodeAction(mcpUrl);
3492
- } else if (options.manual) {
3493
- handleManualAction(mcpUrl, mcpName);
3494
- } else {
3495
- showAllOptions();
3496
- }
3497
- }
3498
- async function handleCursorAction(mcpUrl, mcpName) {
3499
- const mcpConfig = {
3500
- url: mcpUrl
3501
- };
3502
- const encodedConfig = base64.encode(
3503
- new TextEncoder().encode(JSON.stringify(mcpConfig))
3504
- );
3505
- const deeplinkUrl = `cursor://anysphere.cursor-deeplink/mcp/install?name=${encodeURIComponent(mcpName)}&config=${encodedConfig}`;
3506
- console.log(chalk.bold.blue("\u{1F680} Adding Better Auth MCP to Cursor..."));
3507
- try {
3508
- const platform = os.platform();
3509
- let command;
3510
- switch (platform) {
3511
- case "darwin":
3512
- command = `open "${deeplinkUrl}"`;
3513
- break;
3514
- case "win32":
3515
- command = `start "" "${deeplinkUrl}"`;
3516
- break;
3517
- case "linux":
3518
- command = `xdg-open "${deeplinkUrl}"`;
3519
- break;
3520
- default:
3521
- throw new Error(`Unsupported platform: ${platform}`);
3522
- }
3523
- execSync(command, { stdio: "inherit" });
3524
- console.log(chalk.green("\n\u2713 Cursor MCP installed successfully!"));
3525
- } catch (error) {
3526
- console.log(
3527
- chalk.yellow(
3528
- "\n\u26A0 Could not automatically open Cursor. Please copy the deeplink URL above and open it manually."
3529
- )
3530
- );
3531
- console.log(
3532
- chalk.gray(
3533
- "\nYou can also manually add this configuration to your Cursor MCP settings:"
3534
- )
3535
- );
3536
- console.log(chalk.gray(JSON.stringify(mcpConfig, null, 2)));
3537
- }
3538
- console.log(chalk.bold.white("\n\u2728 Next Steps:"));
3539
- console.log(
3540
- chalk.gray("\u2022 The MCP server will be added to your Cursor configuration")
3541
- );
3542
- console.log(
3543
- chalk.gray("\u2022 You can now use Better Auth features directly in Cursor")
3544
- );
3545
- }
3546
- function handleClaudeCodeAction(mcpUrl) {
3547
- console.log(chalk.bold.blue("\u{1F916} Adding Better Auth MCP to Claude Code..."));
3548
- const command = `claude mcp add --transport http better-auth ${mcpUrl}`;
3549
- try {
3550
- execSync(command, { stdio: "inherit" });
3551
- console.log(chalk.green("\n\u2713 Claude Code MCP installed successfully!"));
3552
- } catch (error) {
3553
- console.log(
3554
- chalk.yellow(
3555
- "\n\u26A0 Could not automatically add to Claude Code. Please run this command manually:"
3556
- )
3557
- );
3558
- console.log(chalk.cyan(command));
3559
- }
3560
- console.log(chalk.bold.white("\n\u2728 Next Steps:"));
3561
- console.log(
3562
- chalk.gray(
3563
- "\u2022 The MCP server will be added to your Claude Code configuration"
3564
- )
3565
- );
3566
- console.log(
3567
- chalk.gray(
3568
- "\u2022 You can now use Better Auth features directly in Claude Code"
3569
- )
3570
- );
3571
- }
3572
- function handleOpenCodeAction(mcpUrl) {
3573
- console.log(chalk.bold.blue("\u{1F527} Adding Better Auth MCP to Open Code..."));
3574
- const openCodeConfig = {
3575
- $schema: "https://opencode.ai/config.json",
3576
- mcp: {
3577
- "Better Auth": {
3578
- type: "remote",
3579
- url: mcpUrl,
3580
- enabled: true
3581
- }
3582
- }
3583
- };
3584
- const configPath = path.join(process.cwd(), "opencode.json");
3585
- try {
3586
- let existingConfig = {};
3587
- if (fs.existsSync(configPath)) {
3588
- const existingContent = fs.readFileSync(configPath, "utf8");
3589
- existingConfig = JSON.parse(existingContent);
3590
- }
3591
- const mergedConfig = {
3592
- ...existingConfig,
3593
- ...openCodeConfig,
3594
- mcp: {
3595
- ...existingConfig.mcp,
3596
- ...openCodeConfig.mcp
3597
- }
3598
- };
3599
- fs.writeFileSync(configPath, JSON.stringify(mergedConfig, null, 2));
3600
- console.log(
3601
- chalk.green(`
3602
- \u2713 Open Code configuration written to ${configPath}`)
3603
- );
3604
- console.log(chalk.green("\u2713 Better Auth MCP added successfully!"));
3605
- } catch (error) {
3606
- console.log(
3607
- chalk.yellow(
3608
- "\n\u26A0 Could not automatically write opencode.json. Please add this configuration manually:"
3609
- )
3610
- );
3611
- console.log(chalk.cyan(JSON.stringify(openCodeConfig, null, 2)));
3612
- }
3613
- console.log(chalk.bold.white("\n\u2728 Next Steps:"));
3614
- console.log(chalk.gray("\u2022 Restart Open Code to load the new MCP server"));
3615
- console.log(
3616
- chalk.gray("\u2022 You can now use Better Auth features directly in Open Code")
3617
- );
3618
- }
3619
- function handleManualAction(mcpUrl, mcpName) {
3620
- console.log(chalk.bold.blue("\u{1F4DD} Adding Better Auth MCP Configuration..."));
3621
- const manualConfig = {
3622
- [mcpName]: {
3623
- url: mcpUrl
3624
- }
3625
- };
3626
- const configPath = path.join(process.cwd(), "mcp.json");
3627
- try {
3628
- let existingConfig = {};
3629
- if (fs.existsSync(configPath)) {
3630
- const existingContent = fs.readFileSync(configPath, "utf8");
3631
- existingConfig = JSON.parse(existingContent);
3632
- }
3633
- const mergedConfig = {
3634
- ...existingConfig,
3635
- ...manualConfig
3636
- };
3637
- fs.writeFileSync(configPath, JSON.stringify(mergedConfig, null, 2));
3638
- console.log(chalk.green(`
3639
- \u2713 MCP configuration written to ${configPath}`));
3640
- console.log(chalk.green("\u2713 Better Auth MCP added successfully!"));
3641
- } catch (error) {
3642
- console.log(
3643
- chalk.yellow(
3644
- "\n\u26A0 Could not automatically write mcp.json. Please add this configuration manually:"
3645
- )
3646
- );
3647
- console.log(chalk.cyan(JSON.stringify(manualConfig, null, 2)));
3648
- }
3649
- console.log(chalk.bold.white("\n\u2728 Next Steps:"));
3650
- console.log(chalk.gray("\u2022 Restart your MCP client to load the new server"));
3651
- console.log(
3652
- chalk.gray(
3653
- "\u2022 You can now use Better Auth features directly in your MCP client"
3654
- )
3655
- );
3656
- }
3657
- function showAllOptions(mcpUrl, mcpName) {
3658
- console.log(chalk.bold.blue("\u{1F50C} Better Auth MCP Server"));
3659
- console.log(chalk.gray("Choose your MCP client to get started:"));
3660
- console.log();
3661
- console.log(chalk.bold.white("Available Commands:"));
3662
- console.log(chalk.cyan(" --cursor ") + chalk.gray("Add to Cursor"));
3663
- console.log(
3664
- chalk.cyan(" --claude-code ") + chalk.gray("Add to Claude Code")
3665
- );
3666
- console.log(chalk.cyan(" --open-code ") + chalk.gray("Add to Open Code"));
3667
- console.log(
3668
- chalk.cyan(" --manual ") + chalk.gray("Manual configuration")
3669
- );
3670
- console.log();
3671
- }
3672
- const mcp = new Command("mcp").description("Add Better Auth MCP server to MCP Clients").option("--cursor", "Automatically open Cursor with the MCP configuration").option("--claude-code", "Show Claude Code MCP configuration command").option("--open-code", "Show Open Code MCP configuration").option("--manual", "Show manual MCP configuration for mcp.json").action(mcpAction);
3673
-
3674
- process.on("SIGINT", () => process.exit(0));
3675
- process.on("SIGTERM", () => process.exit(0));
3676
- async function main() {
3677
- const program = new Command("better-auth");
3678
- let packageInfo = {};
3679
- try {
3680
- packageInfo = await getPackageInfo();
3681
- } catch (error) {
3682
- }
3683
- program.addCommand(init).addCommand(migrate).addCommand(generate).addCommand(generateSecret).addCommand(info).addCommand(login).addCommand(mcp).version(packageInfo.version || "1.1.2").description("Better Auth CLI").action(() => program.help());
3684
- program.parse();
3685
- }
3686
- main().catch((error) => {
3687
- console.error("Error running Better Auth CLI:", error);
3688
- process.exit(1);
3689
- });