@better-auth/core 1.3.26 → 1.3.28

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 (130) hide show
  1. package/.turbo/turbo-build.log +60 -9
  2. package/build.config.ts +7 -0
  3. package/dist/db/adapter/index.cjs +2 -0
  4. package/dist/db/adapter/index.d.cts +14 -0
  5. package/dist/db/adapter/index.d.mts +14 -0
  6. package/dist/db/adapter/index.d.ts +14 -0
  7. package/dist/db/adapter/index.mjs +1 -0
  8. package/dist/db/index.cjs +89 -0
  9. package/dist/db/index.d.cts +16 -107
  10. package/dist/db/index.d.mts +16 -107
  11. package/dist/db/index.d.ts +16 -107
  12. package/dist/db/index.mjs +69 -0
  13. package/dist/env/index.cjs +312 -0
  14. package/dist/env/index.d.cts +36 -0
  15. package/dist/env/index.d.mts +36 -0
  16. package/dist/env/index.d.ts +36 -0
  17. package/dist/env/index.mjs +297 -0
  18. package/dist/error/index.cjs +44 -0
  19. package/dist/error/index.d.cts +33 -0
  20. package/dist/error/index.d.mts +33 -0
  21. package/dist/error/index.d.ts +33 -0
  22. package/dist/error/index.mjs +41 -0
  23. package/dist/index.d.cts +179 -1
  24. package/dist/index.d.mts +179 -1
  25. package/dist/index.d.ts +179 -1
  26. package/dist/middleware/index.cjs +25 -0
  27. package/dist/middleware/index.d.cts +14 -0
  28. package/dist/middleware/index.d.mts +14 -0
  29. package/dist/middleware/index.d.ts +14 -0
  30. package/dist/middleware/index.mjs +21 -0
  31. package/dist/oauth2/index.cjs +368 -0
  32. package/dist/oauth2/index.d.cts +100 -0
  33. package/dist/oauth2/index.d.mts +100 -0
  34. package/dist/oauth2/index.d.ts +100 -0
  35. package/dist/oauth2/index.mjs +357 -0
  36. package/dist/shared/core.BJPBStdk.d.ts +1693 -0
  37. package/dist/shared/core.Bl6TpxyD.d.mts +181 -0
  38. package/dist/shared/core.Bqe5IGAi.d.ts +13 -0
  39. package/dist/shared/core.BwoNUcJQ.d.cts +53 -0
  40. package/dist/shared/core.BwoNUcJQ.d.mts +53 -0
  41. package/dist/shared/core.BwoNUcJQ.d.ts +53 -0
  42. package/dist/shared/core.CajxAutx.d.cts +143 -0
  43. package/dist/shared/core.CajxAutx.d.mts +143 -0
  44. package/dist/shared/core.CajxAutx.d.ts +143 -0
  45. package/dist/shared/core.CkkLHQWc.d.mts +1693 -0
  46. package/dist/shared/core.DkdZ1o38.d.ts +181 -0
  47. package/dist/shared/core.Dl-70uns.d.cts +84 -0
  48. package/dist/shared/core.Dl-70uns.d.mts +84 -0
  49. package/dist/shared/core.Dl-70uns.d.ts +84 -0
  50. package/dist/shared/core.DyEdx0m7.d.cts +181 -0
  51. package/dist/shared/core.E9DfzGLz.d.mts +13 -0
  52. package/dist/shared/core.HqYn20Fi.d.cts +13 -0
  53. package/dist/shared/core.gYIBmdi1.d.cts +1693 -0
  54. package/dist/social-providers/index.cjs +2793 -0
  55. package/dist/social-providers/index.d.cts +3903 -0
  56. package/dist/social-providers/index.d.mts +3903 -0
  57. package/dist/social-providers/index.d.ts +3903 -0
  58. package/dist/social-providers/index.mjs +2743 -0
  59. package/dist/utils/index.cjs +7 -0
  60. package/dist/utils/index.d.cts +10 -0
  61. package/dist/utils/index.d.mts +10 -0
  62. package/dist/utils/index.d.ts +10 -0
  63. package/dist/utils/index.mjs +5 -0
  64. package/package.json +109 -2
  65. package/src/db/adapter/index.ts +448 -0
  66. package/src/db/index.ts +13 -0
  67. package/src/db/plugin.ts +11 -0
  68. package/src/db/schema/account.ts +34 -0
  69. package/src/db/schema/rate-limit.ts +21 -0
  70. package/src/db/schema/session.ts +17 -0
  71. package/src/db/schema/shared.ts +7 -0
  72. package/src/db/schema/user.ts +16 -0
  73. package/src/db/schema/verification.ts +15 -0
  74. package/src/db/type.ts +50 -0
  75. package/src/env/color-depth.ts +172 -0
  76. package/src/env/env-impl.ts +123 -0
  77. package/src/env/index.ts +23 -0
  78. package/src/env/logger.test.ts +33 -0
  79. package/src/env/logger.ts +145 -0
  80. package/src/error/codes.ts +31 -0
  81. package/src/error/index.ts +11 -0
  82. package/src/index.ts +1 -1
  83. package/src/middleware/index.ts +33 -0
  84. package/src/oauth2/client-credentials-token.ts +102 -0
  85. package/src/oauth2/create-authorization-url.ts +85 -0
  86. package/src/oauth2/index.ts +22 -0
  87. package/src/oauth2/oauth-provider.ts +194 -0
  88. package/src/oauth2/refresh-access-token.ts +124 -0
  89. package/src/oauth2/utils.ts +36 -0
  90. package/src/oauth2/validate-authorization-code.ts +156 -0
  91. package/src/social-providers/apple.ts +213 -0
  92. package/src/social-providers/atlassian.ts +130 -0
  93. package/src/social-providers/cognito.ts +269 -0
  94. package/src/social-providers/discord.ts +172 -0
  95. package/src/social-providers/dropbox.ts +112 -0
  96. package/src/social-providers/facebook.ts +204 -0
  97. package/src/social-providers/figma.ts +115 -0
  98. package/src/social-providers/github.ts +154 -0
  99. package/src/social-providers/gitlab.ts +152 -0
  100. package/src/social-providers/google.ts +171 -0
  101. package/src/social-providers/huggingface.ts +116 -0
  102. package/src/social-providers/index.ts +118 -0
  103. package/src/social-providers/kakao.ts +178 -0
  104. package/src/social-providers/kick.ts +95 -0
  105. package/src/social-providers/line.ts +169 -0
  106. package/src/social-providers/linear.ts +120 -0
  107. package/src/social-providers/linkedin.ts +110 -0
  108. package/src/social-providers/microsoft-entra-id.ts +243 -0
  109. package/src/social-providers/naver.ts +112 -0
  110. package/src/social-providers/notion.ts +106 -0
  111. package/src/social-providers/paypal.ts +261 -0
  112. package/src/social-providers/reddit.ts +122 -0
  113. package/src/social-providers/roblox.ts +110 -0
  114. package/src/social-providers/salesforce.ts +157 -0
  115. package/src/social-providers/slack.ts +114 -0
  116. package/src/social-providers/spotify.ts +93 -0
  117. package/src/social-providers/tiktok.ts +211 -0
  118. package/src/social-providers/twitch.ts +111 -0
  119. package/src/social-providers/twitter.ts +194 -0
  120. package/src/social-providers/vk.ts +128 -0
  121. package/src/social-providers/zoom.ts +218 -0
  122. package/src/types/context.ts +313 -0
  123. package/src/types/cookie.ts +7 -0
  124. package/src/types/helper.ts +5 -0
  125. package/src/types/index.ts +20 -1
  126. package/src/types/init-options.ts +1161 -0
  127. package/src/types/plugin-client.ts +69 -0
  128. package/src/types/plugin.ts +134 -0
  129. package/src/utils/error-codes.ts +51 -0
  130. package/src/utils/index.ts +1 -0
@@ -0,0 +1,34 @@
1
+ import * as z from "zod";
2
+ import { coreSchema } from "./shared";
3
+
4
+ export const accountSchema = coreSchema.extend({
5
+ providerId: z.string(),
6
+ accountId: z.string(),
7
+ userId: z.coerce.string(),
8
+ accessToken: z.string().nullish(),
9
+ refreshToken: z.string().nullish(),
10
+ idToken: z.string().nullish(),
11
+ /**
12
+ * Access token expires at
13
+ */
14
+ accessTokenExpiresAt: z.date().nullish(),
15
+ /**
16
+ * Refresh token expires at
17
+ */
18
+ refreshTokenExpiresAt: z.date().nullish(),
19
+ /**
20
+ * The scopes that the user has authorized
21
+ */
22
+ scope: z.string().nullish(),
23
+ /**
24
+ * Password is only stored in the credential provider
25
+ */
26
+ password: z.string().nullish(),
27
+ });
28
+
29
+ /**
30
+ * Account schema type used by better-auth, note that it's possible that account could have additional fields
31
+ *
32
+ * todo: we should use generics to extend this type with additional fields from plugins and options in the future
33
+ */
34
+ export type Account = z.infer<typeof accountSchema>;
@@ -0,0 +1,21 @@
1
+ import * as z from "zod";
2
+
3
+ export const rateLimitSchema = z.object({
4
+ /**
5
+ * The key to use for rate limiting
6
+ */
7
+ key: z.string(),
8
+ /**
9
+ * The number of requests made
10
+ */
11
+ count: z.number(),
12
+ /**
13
+ * The last request time in milliseconds
14
+ */
15
+ lastRequest: z.number(),
16
+ });
17
+
18
+ /**
19
+ * Rate limit schema type used by better-auth for rate limiting
20
+ */
21
+ export type RateLimit = z.infer<typeof rateLimitSchema>;
@@ -0,0 +1,17 @@
1
+ import * as z from "zod";
2
+ import { coreSchema } from "./shared";
3
+
4
+ export const sessionSchema = coreSchema.extend({
5
+ userId: z.coerce.string(),
6
+ expiresAt: z.date(),
7
+ token: z.string(),
8
+ ipAddress: z.string().nullish(),
9
+ userAgent: z.string().nullish(),
10
+ });
11
+
12
+ /**
13
+ * Session schema type used by better-auth, note that it's possible that session could have additional fields
14
+ *
15
+ * todo: we should use generics to extend this type with additional fields from plugins and options in the future
16
+ */
17
+ export type Session = z.infer<typeof sessionSchema>;
@@ -0,0 +1,7 @@
1
+ import * as z from "zod";
2
+
3
+ export const coreSchema = z.object({
4
+ id: z.string(),
5
+ createdAt: z.date().default(() => new Date()),
6
+ updatedAt: z.date().default(() => new Date()),
7
+ });
@@ -0,0 +1,16 @@
1
+ import * as z from "zod";
2
+ import { coreSchema } from "./shared";
3
+
4
+ export const userSchema = coreSchema.extend({
5
+ email: z.string().transform((val) => val.toLowerCase()),
6
+ emailVerified: z.boolean().default(false),
7
+ name: z.string(),
8
+ image: z.string().nullish(),
9
+ });
10
+
11
+ /**
12
+ * User schema type used by better-auth, note that it's possible that user could have additional fields
13
+ *
14
+ * todo: we should use generics to extend this type with additional fields from plugins and options in the future
15
+ */
16
+ export type User = z.infer<typeof userSchema>;
@@ -0,0 +1,15 @@
1
+ import * as z from "zod";
2
+ import { coreSchema } from "./shared";
3
+
4
+ export const verificationSchema = coreSchema.extend({
5
+ value: z.string(),
6
+ expiresAt: z.date(),
7
+ identifier: z.string(),
8
+ });
9
+
10
+ /**
11
+ * Verification schema type used by better-auth, note that it's possible that verification could have additional fields
12
+ *
13
+ * todo: we should use generics to extend this type with additional fields from plugins and options in the future
14
+ */
15
+ export type Verification = z.infer<typeof verificationSchema>;
package/src/db/type.ts CHANGED
@@ -1,6 +1,28 @@
1
1
  import type { ZodType } from "zod";
2
2
  import type { LiteralString } from "../types";
3
3
 
4
+ declare module "../index" {
5
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
6
+ interface BetterAuthMutators<O, C> {
7
+ "better-auth/db": {
8
+ // todo: we should infer the schema from the adapter
9
+ };
10
+ }
11
+ }
12
+
13
+ export type Models =
14
+ | "user"
15
+ | "account"
16
+ | "session"
17
+ | "verification"
18
+ | "rate-limit"
19
+ | "organization"
20
+ | "member"
21
+ | "invitation"
22
+ | "jwks"
23
+ | "passkey"
24
+ | "two-factor";
25
+
4
26
  export type DBFieldType =
5
27
  | "string"
6
28
  | "number"
@@ -131,3 +153,31 @@ export type BetterAuthDBSchema = Record<
131
153
  order?: number;
132
154
  }
133
155
  >;
156
+
157
+ export interface SecondaryStorage {
158
+ /**
159
+ *
160
+ * @param key - Key to get
161
+ * @returns - Value of the key
162
+ */
163
+ get: (key: string) => Promise<unknown> | unknown;
164
+ set: (
165
+ /**
166
+ * Key to store
167
+ */
168
+ key: string,
169
+ /**
170
+ * Value to store
171
+ */
172
+ value: string,
173
+ /**
174
+ * Time to live in seconds
175
+ */
176
+ ttl?: number,
177
+ ) => Promise<void | null | unknown> | void;
178
+ /**
179
+ *
180
+ * @param key - Key to delete
181
+ */
182
+ delete: (key: string) => Promise<void | null | string> | void;
183
+ }
@@ -0,0 +1,172 @@
1
+ // Source code copied & modified from node internals: https://github.com/nodejs/node/blob/5b32bb1573dace2dd058c05ac4fab1e4e446c775/lib/internal/tty.js#L123
2
+ import { env, getEnvVar } from "./env-impl";
3
+
4
+ const COLORS_2 = 1;
5
+ const COLORS_16 = 4;
6
+ const COLORS_256 = 8;
7
+ const COLORS_16m = 24;
8
+
9
+ const TERM_ENVS: Record<string, number> = {
10
+ eterm: COLORS_16,
11
+ cons25: COLORS_16,
12
+ console: COLORS_16,
13
+ cygwin: COLORS_16,
14
+ dtterm: COLORS_16,
15
+ gnome: COLORS_16,
16
+ hurd: COLORS_16,
17
+ jfbterm: COLORS_16,
18
+ konsole: COLORS_16,
19
+ kterm: COLORS_16,
20
+ mlterm: COLORS_16,
21
+ mosh: COLORS_16m,
22
+ putty: COLORS_16,
23
+ st: COLORS_16,
24
+ // http://lists.schmorp.de/pipermail/rxvt-unicode/2016q2/002261.html
25
+ "rxvt-unicode-24bit": COLORS_16m,
26
+ // https://bugs.launchpad.net/terminator/+bug/1030562
27
+ terminator: COLORS_16m,
28
+ "xterm-kitty": COLORS_16m,
29
+ };
30
+
31
+ const CI_ENVS_MAP = new Map(
32
+ Object.entries({
33
+ APPVEYOR: COLORS_256,
34
+ BUILDKITE: COLORS_256,
35
+ CIRCLECI: COLORS_16m,
36
+ DRONE: COLORS_256,
37
+ GITEA_ACTIONS: COLORS_16m,
38
+ GITHUB_ACTIONS: COLORS_16m,
39
+ GITLAB_CI: COLORS_256,
40
+ TRAVIS: COLORS_256,
41
+ }),
42
+ );
43
+
44
+ const TERM_ENVS_REG_EXP = [
45
+ /ansi/,
46
+ /color/,
47
+ /linux/,
48
+ /direct/,
49
+ /^con[0-9]*x[0-9]/,
50
+ /^rxvt/,
51
+ /^screen/,
52
+ /^xterm/,
53
+ /^vt100/,
54
+ /^vt220/,
55
+ ];
56
+
57
+ // The `getColorDepth` API got inspired by multiple sources such as
58
+ // https://github.com/chalk/supports-color,
59
+ // https://github.com/isaacs/color-support.
60
+ export function getColorDepth(): number {
61
+ // Use level 0-3 to support the same levels as `chalk` does. This is done for
62
+ // consistency throughout the ecosystem.
63
+ if (getEnvVar("FORCE_COLOR") !== undefined) {
64
+ switch (getEnvVar("FORCE_COLOR")) {
65
+ case "":
66
+ case "1":
67
+ case "true":
68
+ return COLORS_16;
69
+ case "2":
70
+ return COLORS_256;
71
+ case "3":
72
+ return COLORS_16m;
73
+ default:
74
+ return COLORS_2;
75
+ }
76
+ }
77
+
78
+ if (
79
+ (getEnvVar("NODE_DISABLE_COLORS") !== undefined &&
80
+ getEnvVar("NODE_DISABLE_COLORS") !== "") ||
81
+ // See https://no-color.org/
82
+ (getEnvVar("NO_COLOR") !== undefined && getEnvVar("NO_COLOR") !== "") ||
83
+ // The "dumb" special terminal, as defined by terminfo, doesn't support
84
+ // ANSI color control codes.
85
+ // See https://invisible-island.net/ncurses/terminfo.ti.html#toc-_Specials
86
+ getEnvVar("TERM") === "dumb"
87
+ ) {
88
+ return COLORS_2;
89
+ }
90
+
91
+ // Edge runtime doesn't support `process?.platform` syntax
92
+ // if (typeof process !== "undefined" && process?.platform === "win32") {
93
+ // // Windows 10 build 14931 (from 2016) has true color support
94
+ // return COLORS_16m;
95
+ // }
96
+
97
+ if (getEnvVar("TMUX")) {
98
+ return COLORS_16m;
99
+ }
100
+
101
+ // Azure DevOps
102
+ if ("TF_BUILD" in env && "AGENT_NAME" in env) {
103
+ return COLORS_16;
104
+ }
105
+
106
+ if ("CI" in env) {
107
+ for (const { 0: envName, 1: colors } of CI_ENVS_MAP) {
108
+ if (envName in env) {
109
+ return colors;
110
+ }
111
+ }
112
+ if (getEnvVar("CI_NAME") === "codeship") {
113
+ return COLORS_256;
114
+ }
115
+ return COLORS_2;
116
+ }
117
+
118
+ if ("TEAMCITY_VERSION" in env) {
119
+ return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.exec(
120
+ getEnvVar("TEAMCITY_VERSION"),
121
+ ) !== null
122
+ ? COLORS_16
123
+ : COLORS_2;
124
+ }
125
+
126
+ switch (getEnvVar("TERM_PROGRAM")) {
127
+ case "iTerm.app":
128
+ if (
129
+ !getEnvVar("TERM_PROGRAM_VERSION") ||
130
+ /^[0-2]\./.exec(getEnvVar("TERM_PROGRAM_VERSION")) !== null
131
+ ) {
132
+ return COLORS_256;
133
+ }
134
+ return COLORS_16m;
135
+ case "HyperTerm":
136
+ case "MacTerm":
137
+ return COLORS_16m;
138
+ case "Apple_Terminal":
139
+ return COLORS_256;
140
+ }
141
+
142
+ if (
143
+ getEnvVar("COLORTERM") === "truecolor" ||
144
+ getEnvVar("COLORTERM") === "24bit"
145
+ ) {
146
+ return COLORS_16m;
147
+ }
148
+
149
+ if (getEnvVar("TERM")) {
150
+ if (/truecolor/.exec(getEnvVar("TERM")) !== null) {
151
+ return COLORS_16m;
152
+ }
153
+
154
+ if (/^xterm-256/.exec(getEnvVar("TERM")) !== null) {
155
+ return COLORS_256;
156
+ }
157
+
158
+ const termEnv = getEnvVar("TERM").toLowerCase();
159
+
160
+ if (TERM_ENVS[termEnv]) {
161
+ return TERM_ENVS[termEnv];
162
+ }
163
+ if (TERM_ENVS_REG_EXP.some((term) => term.exec(termEnv) !== null)) {
164
+ return COLORS_16;
165
+ }
166
+ }
167
+ // Move 16 color COLORTERM below 16m and 256
168
+ if (getEnvVar("COLORTERM")) {
169
+ return COLORS_16;
170
+ }
171
+ return COLORS_2;
172
+ }
@@ -0,0 +1,123 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="bun" />
3
+ //https://github.com/unjs/std-env/blob/main/src/env.ts
4
+
5
+ const _envShim = Object.create(null);
6
+
7
+ export type EnvObject = Record<string, string | undefined>;
8
+
9
+ const _getEnv = (useShim?: boolean) =>
10
+ globalThis.process?.env ||
11
+ //@ts-expect-error
12
+ globalThis.Deno?.env.toObject() ||
13
+ //@ts-expect-error
14
+ globalThis.__env__ ||
15
+ (useShim ? _envShim : globalThis);
16
+
17
+ export const env = new Proxy<EnvObject>(_envShim, {
18
+ get(_, prop) {
19
+ const env = _getEnv();
20
+ return env[prop as any] ?? _envShim[prop];
21
+ },
22
+ has(_, prop) {
23
+ const env = _getEnv();
24
+ return prop in env || prop in _envShim;
25
+ },
26
+ set(_, prop, value) {
27
+ const env = _getEnv(true);
28
+ env[prop as any] = value;
29
+ return true;
30
+ },
31
+ deleteProperty(_, prop) {
32
+ if (!prop) {
33
+ return false;
34
+ }
35
+ const env = _getEnv(true);
36
+ delete env[prop as any];
37
+ return true;
38
+ },
39
+ ownKeys() {
40
+ const env = _getEnv(true);
41
+ return Object.keys(env);
42
+ },
43
+ });
44
+
45
+ function toBoolean(val: boolean | string | undefined) {
46
+ return val ? val !== "false" : false;
47
+ }
48
+
49
+ export const nodeENV =
50
+ (typeof process !== "undefined" && process.env && process.env.NODE_ENV) || "";
51
+
52
+ /** Detect if `NODE_ENV` environment variable is `production` */
53
+ export const isProduction = nodeENV === "production";
54
+
55
+ /** Detect if `NODE_ENV` environment variable is `dev` or `development` */
56
+ export const isDevelopment = nodeENV === "dev" || nodeENV === "development";
57
+
58
+ /** Detect if `NODE_ENV` environment variable is `test` */
59
+ export const isTest = () => nodeENV === "test" || toBoolean(env.TEST);
60
+
61
+ /**
62
+ * Get environment variable with fallback
63
+ */
64
+ export function getEnvVar<Fallback extends string>(
65
+ key: string,
66
+ fallback?: Fallback,
67
+ ): Fallback extends string ? string : string | undefined {
68
+ if (typeof process !== "undefined" && process.env) {
69
+ return process.env[key] ?? (fallback as any);
70
+ }
71
+
72
+ // @ts-expect-error deno
73
+ if (typeof Deno !== "undefined") {
74
+ // @ts-expect-error deno
75
+ return Deno.env.get(key) ?? (fallback as string);
76
+ }
77
+
78
+ // Handle Bun
79
+ if (typeof Bun !== "undefined") {
80
+ return Bun.env[key] ?? (fallback as string);
81
+ }
82
+
83
+ return fallback as any;
84
+ }
85
+
86
+ /**
87
+ * Get boolean environment variable
88
+ */
89
+ export function getBooleanEnvVar(key: string, fallback = true): boolean {
90
+ const value = getEnvVar(key);
91
+ if (!value) return fallback;
92
+ return value !== "0" && value.toLowerCase() !== "false" && value !== "";
93
+ }
94
+
95
+ /**
96
+ * Common environment variables used in Better Auth
97
+ */
98
+ export const ENV = Object.freeze({
99
+ get BETTER_AUTH_SECRET() {
100
+ return getEnvVar("BETTER_AUTH_SECRET");
101
+ },
102
+ get AUTH_SECRET() {
103
+ return getEnvVar("AUTH_SECRET");
104
+ },
105
+ get BETTER_AUTH_TELEMETRY() {
106
+ return getEnvVar("BETTER_AUTH_TELEMETRY");
107
+ },
108
+ get BETTER_AUTH_TELEMETRY_ID() {
109
+ return getEnvVar("BETTER_AUTH_TELEMETRY_ID");
110
+ },
111
+ get NODE_ENV() {
112
+ return getEnvVar("NODE_ENV", "development");
113
+ },
114
+ get PACKAGE_VERSION() {
115
+ return getEnvVar("PACKAGE_VERSION", "0.0.0");
116
+ },
117
+ get BETTER_AUTH_TELEMETRY_ENDPOINT() {
118
+ return getEnvVar(
119
+ "BETTER_AUTH_TELEMETRY_ENDPOINT",
120
+ "https://telemetry.better-auth.com/v1/track",
121
+ );
122
+ },
123
+ });
@@ -0,0 +1,23 @@
1
+ export {
2
+ ENV,
3
+ getEnvVar,
4
+ env,
5
+ nodeENV,
6
+ isTest,
7
+ getBooleanEnvVar,
8
+ isDevelopment,
9
+ type EnvObject,
10
+ isProduction,
11
+ } from "./env-impl";
12
+ export { getColorDepth } from "./color-depth";
13
+ export {
14
+ logger,
15
+ createLogger,
16
+ levels,
17
+ type Logger,
18
+ type LogLevel,
19
+ type LogHandlerParams,
20
+ type InternalLogger,
21
+ shouldPublishLog,
22
+ TTY_COLORS,
23
+ } from "./logger";
@@ -0,0 +1,33 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import { shouldPublishLog, type LogLevel } from "./logger";
3
+
4
+ describe("shouldPublishLog", () => {
5
+ const testCases: {
6
+ currentLogLevel: LogLevel;
7
+ logLevel: LogLevel;
8
+ expected: boolean;
9
+ }[] = [
10
+ { currentLogLevel: "info", logLevel: "info", expected: true },
11
+ { currentLogLevel: "info", logLevel: "warn", expected: false },
12
+ { currentLogLevel: "info", logLevel: "error", expected: false },
13
+ { currentLogLevel: "info", logLevel: "debug", expected: false },
14
+ { currentLogLevel: "warn", logLevel: "info", expected: true },
15
+ { currentLogLevel: "warn", logLevel: "warn", expected: true },
16
+ { currentLogLevel: "warn", logLevel: "error", expected: false },
17
+ { currentLogLevel: "warn", logLevel: "debug", expected: false },
18
+ { currentLogLevel: "error", logLevel: "info", expected: true },
19
+ { currentLogLevel: "error", logLevel: "warn", expected: true },
20
+ { currentLogLevel: "error", logLevel: "error", expected: true },
21
+ { currentLogLevel: "error", logLevel: "debug", expected: false },
22
+ { currentLogLevel: "debug", logLevel: "info", expected: true },
23
+ { currentLogLevel: "debug", logLevel: "warn", expected: true },
24
+ { currentLogLevel: "debug", logLevel: "error", expected: true },
25
+ { currentLogLevel: "debug", logLevel: "debug", expected: true },
26
+ ];
27
+
28
+ testCases.forEach(({ currentLogLevel, logLevel, expected }) => {
29
+ it(`should return "${expected}" when currentLogLevel is "${currentLogLevel}" and logLevel is "${logLevel}"`, () => {
30
+ expect(shouldPublishLog(currentLogLevel, logLevel)).toBe(expected);
31
+ });
32
+ });
33
+ });
@@ -0,0 +1,145 @@
1
+ import { getColorDepth } from "./color-depth";
2
+
3
+ export const TTY_COLORS = {
4
+ reset: "\x1b[0m",
5
+ bright: "\x1b[1m",
6
+ dim: "\x1b[2m",
7
+ undim: "\x1b[22m",
8
+ underscore: "\x1b[4m",
9
+ blink: "\x1b[5m",
10
+ reverse: "\x1b[7m",
11
+ hidden: "\x1b[8m",
12
+ fg: {
13
+ black: "\x1b[30m",
14
+ red: "\x1b[31m",
15
+ green: "\x1b[32m",
16
+ yellow: "\x1b[33m",
17
+ blue: "\x1b[34m",
18
+ magenta: "\x1b[35m",
19
+ cyan: "\x1b[36m",
20
+ white: "\x1b[37m",
21
+ },
22
+ bg: {
23
+ black: "\x1b[40m",
24
+ red: "\x1b[41m",
25
+ green: "\x1b[42m",
26
+ yellow: "\x1b[43m",
27
+ blue: "\x1b[44m",
28
+ magenta: "\x1b[45m",
29
+ cyan: "\x1b[46m",
30
+ white: "\x1b[47m",
31
+ },
32
+ } as const;
33
+
34
+ export type LogLevel = "info" | "success" | "warn" | "error" | "debug";
35
+
36
+ export const levels = ["info", "success", "warn", "error", "debug"] as const;
37
+
38
+ export function shouldPublishLog(
39
+ currentLogLevel: LogLevel,
40
+ logLevel: LogLevel,
41
+ ): boolean {
42
+ return levels.indexOf(logLevel) <= levels.indexOf(currentLogLevel);
43
+ }
44
+
45
+ export interface Logger {
46
+ disabled?: boolean;
47
+ disableColors?: boolean;
48
+ level?: Exclude<LogLevel, "success">;
49
+ log?: (
50
+ level: Exclude<LogLevel, "success">,
51
+ message: string,
52
+ ...args: any[]
53
+ ) => void;
54
+ }
55
+
56
+ export type LogHandlerParams = Parameters<NonNullable<Logger["log"]>> extends [
57
+ LogLevel,
58
+ ...infer Rest,
59
+ ]
60
+ ? Rest
61
+ : never;
62
+
63
+ const levelColors: Record<LogLevel, string> = {
64
+ info: TTY_COLORS.fg.blue,
65
+ success: TTY_COLORS.fg.green,
66
+ warn: TTY_COLORS.fg.yellow,
67
+ error: TTY_COLORS.fg.red,
68
+ debug: TTY_COLORS.fg.magenta,
69
+ };
70
+
71
+ const formatMessage = (
72
+ level: LogLevel,
73
+ message: string,
74
+ colorsEnabled: boolean,
75
+ ): string => {
76
+ const timestamp = new Date().toISOString();
77
+
78
+ if (colorsEnabled) {
79
+ return `${TTY_COLORS.dim}${timestamp}${TTY_COLORS.reset} ${
80
+ levelColors[level]
81
+ }${level.toUpperCase()}${TTY_COLORS.reset} ${TTY_COLORS.bright}[Better Auth]:${
82
+ TTY_COLORS.reset
83
+ } ${message}`;
84
+ }
85
+
86
+ return `${timestamp} ${level.toUpperCase()} [Better Auth]: ${message}`;
87
+ };
88
+
89
+ export type InternalLogger = {
90
+ [K in LogLevel]: (...params: LogHandlerParams) => void;
91
+ } & {
92
+ get level(): LogLevel;
93
+ };
94
+
95
+ export const createLogger = (options?: Logger): InternalLogger => {
96
+ const enabled = options?.disabled !== true;
97
+ const logLevel = options?.level ?? "error";
98
+
99
+ const isDisableColorsSpecified = options?.disableColors !== undefined;
100
+ const colorsEnabled = isDisableColorsSpecified
101
+ ? !options.disableColors
102
+ : getColorDepth() !== 1;
103
+
104
+ const LogFunc = (
105
+ level: LogLevel,
106
+ message: string,
107
+ args: any[] = [],
108
+ ): void => {
109
+ if (!enabled || !shouldPublishLog(logLevel, level)) {
110
+ return;
111
+ }
112
+
113
+ const formattedMessage = formatMessage(level, message, colorsEnabled);
114
+
115
+ if (!options || typeof options.log !== "function") {
116
+ if (level === "error") {
117
+ console.error(formattedMessage, ...args);
118
+ } else if (level === "warn") {
119
+ console.warn(formattedMessage, ...args);
120
+ } else {
121
+ console.log(formattedMessage, ...args);
122
+ }
123
+ return;
124
+ }
125
+
126
+ options.log(level === "success" ? "info" : level, message, ...args);
127
+ };
128
+
129
+ const logger = Object.fromEntries(
130
+ levels.map((level) => [
131
+ level,
132
+ (...[message, ...args]: LogHandlerParams) =>
133
+ LogFunc(level, message, args),
134
+ ]),
135
+ ) as Record<LogLevel, (...params: LogHandlerParams) => void>;
136
+
137
+ return {
138
+ ...logger,
139
+ get level() {
140
+ return logLevel;
141
+ },
142
+ };
143
+ };
144
+
145
+ export const logger = createLogger();