@better-auth/cli 1.4.0-beta.1 → 1.4.0-beta.11

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