vinojs 0.1.0 → 0.1.2

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 (115) hide show
  1. package/dist/client.mjs +1 -1
  2. package/dist/{compile-Lxl_tdxL.mjs → compile-glNMkyyx.mjs} +3 -47
  3. package/dist/compile-glNMkyyx.mjs.map +1 -0
  4. package/dist/{definePage-Ba4r-TFh.mjs → definePage--9Pz7rHs.mjs} +29 -7
  5. package/dist/definePage--9Pz7rHs.mjs.map +1 -0
  6. package/dist/defineServerFn-H-bz7xBX.mjs +47 -0
  7. package/dist/defineServerFn-H-bz7xBX.mjs.map +1 -0
  8. package/dist/factory-CVT0-OZw.d.mts +187 -0
  9. package/dist/factory-CVT0-OZw.d.mts.map +1 -0
  10. package/dist/factory.d.mts +2 -0
  11. package/dist/factory.mjs +153 -0
  12. package/dist/factory.mjs.map +1 -0
  13. package/dist/vino.d.mts +4 -103
  14. package/dist/vino.d.mts.map +1 -1
  15. package/dist/vino.mjs +8 -3
  16. package/dist/vino.mjs.map +1 -1
  17. package/dist/vite.mjs +3 -2
  18. package/dist/vite.mjs.map +1 -1
  19. package/package.json +5 -1
  20. package/dist/compile-Lxl_tdxL.mjs.map +0 -1
  21. package/dist/definePage-Ba4r-TFh.mjs.map +0 -1
  22. package/examples/basic/dist/client/.assetsignore +0 -2
  23. package/examples/basic/dist/client/about.html +0 -1
  24. package/examples/basic/dist/client/admin.html +0 -1
  25. package/examples/basic/dist/client/assets/Counter-BvqMZKON.js +0 -1
  26. package/examples/basic/dist/client/assets/_slug_-CYpOSbrn.js +0 -1
  27. package/examples/basic/dist/client/assets/about-BZXRzUyv.js +0 -1
  28. package/examples/basic/dist/client/assets/admin-DRE7uh2s.js +0 -1
  29. package/examples/basic/dist/client/assets/client-B6nFkut5.js +0 -1
  30. package/examples/basic/dist/client/assets/client-pages-Bc6cNZAm.js +0 -2
  31. package/examples/basic/dist/client/assets/components-DX9r6vHn.js +0 -1
  32. package/examples/basic/dist/client/assets/components-DsWJ6F73.js +0 -2
  33. package/examples/basic/dist/client/assets/counter-DBpvln_F.js +0 -1
  34. package/examples/basic/dist/client/assets/dom-B5sHIJ1E.js +0 -1
  35. package/examples/basic/dist/client/assets/honoto-9UtdLp4J.js +0 -33
  36. package/examples/basic/dist/client/assets/honoto-client-DEh86_WZ.css +0 -1
  37. package/examples/basic/dist/client/assets/honoto-client.js +0 -2
  38. package/examples/basic/dist/client/assets/hooks-Cz6AT21d.js +0 -1
  39. package/examples/basic/dist/client/assets/jsx-dev-runtime-92VDsVyo.js +0 -1
  40. package/examples/basic/dist/client/counter.html +0 -1
  41. package/examples/basic/dist/client/index.html +0 -1
  42. package/examples/basic/dist/client/jobs.html +0 -1
  43. package/examples/basic/dist/ssr/.vite/manifest.json +0 -140
  44. package/examples/basic/dist/ssr/assets/_slug_-CY3-kffX.js +0 -46
  45. package/examples/basic/dist/ssr/assets/about-CTDjNhkO.js +0 -15
  46. package/examples/basic/dist/ssr/assets/admin-DvS-UGJx.js +0 -26
  47. package/examples/basic/dist/ssr/assets/constants-UoriGYcX-CUecBFMT.js +0 -6
  48. package/examples/basic/dist/ssr/assets/counter-DfIbc9Sp.js +0 -30
  49. package/examples/basic/dist/ssr/assets/honoto-CA313cVy.js +0 -2129
  50. package/examples/basic/dist/ssr/assets/jobs-D9hh-UO9.js +0 -42
  51. package/examples/basic/dist/ssr/assets/jsx-CgYLQazd.js +0 -1080
  52. package/examples/basic/dist/ssr/assets/jsx-dev-runtime-BlUda7H8.js +0 -742
  53. package/examples/basic/dist/ssr/assets/jsx-renderer-CzZcZPnS.js +0 -65
  54. package/examples/basic/dist/ssr/assets/layout-DYvLwr2u.js +0 -53
  55. package/examples/basic/dist/ssr/assets/pages-DB6jeyrt.js +0 -53
  56. package/examples/basic/dist/ssr/assets/rolldown-runtime-D7D4PA-g.js +0 -13
  57. package/examples/basic/dist/ssr/assets/ssr-hooks-CBQr0cdH.js +0 -7
  58. package/examples/basic/dist/ssr/index.js +0 -22
  59. package/examples/basic/dist/ssr/wrangler.json +0 -1
  60. package/examples/full/dist/client/.assetsignore +0 -2
  61. package/examples/full/dist/client/assets/BookmarkButton-py0xGxgl.js +0 -1
  62. package/examples/full/dist/client/assets/_slug_-DZUFsE9O.js +0 -1
  63. package/examples/full/dist/client/assets/auth-client-D2Wtuobe.js +0 -1
  64. package/examples/full/dist/client/assets/bun-sqlite-dialect-C7ftEUSI-CsHdUKBY.js +0 -1
  65. package/examples/full/dist/client/assets/client-B6nFkut5.js +0 -1
  66. package/examples/full/dist/client/assets/client-pages-fshKs747.js +0 -2
  67. package/examples/full/dist/client/assets/components-DX9r6vHn.js +0 -1
  68. package/examples/full/dist/client/assets/components-S_-rWrKi.js +0 -2
  69. package/examples/full/dist/client/assets/d1-sqlite-dialect-BZmaVTp8-FPCaMZqX.js +0 -1
  70. package/examples/full/dist/client/assets/default-query-compiler-CUdqIu1h.js +0 -1
  71. package/examples/full/dist/client/assets/dist-BoGTNvkC.js +0 -1
  72. package/examples/full/dist/client/assets/dom-DCd3wYW7.js +0 -1
  73. package/examples/full/dist/client/assets/factory-Bgf4EtLx.js +0 -8
  74. package/examples/full/dist/client/assets/honoto-client-BSvNAnxN.css +0 -1
  75. package/examples/full/dist/client/assets/honoto-client.js +0 -2
  76. package/examples/full/dist/client/assets/hooks-Cz6AT21d.js +0 -1
  77. package/examples/full/dist/client/assets/jsx-dev-runtime-92VDsVyo.js +0 -1
  78. package/examples/full/dist/client/assets/kysely-adapter-BHhasAnc.js +0 -1
  79. package/examples/full/dist/client/assets/kysely-migration-tables-DFfmKhq--U5ujlMwE.js +0 -1
  80. package/examples/full/dist/client/assets/node-sqlite-dialect-DJDXH5Ot.js +0 -1
  81. package/examples/full/dist/client/assets/pages-CUQx6Eus.js +0 -1
  82. package/examples/full/dist/client/assets/saved-jIi74ncJ.js +0 -1
  83. package/examples/full/dist/client/assets/session-B-accyM3.js +0 -611
  84. package/examples/full/dist/client/assets/sign-in-BelI3gSs.js +0 -1
  85. package/examples/full/dist/client/assets/sign-up-pR94lfdu.js +0 -1
  86. package/examples/full/dist/client/index.html +0 -1
  87. package/examples/full/dist/client/saved.html +0 -1
  88. package/examples/full/dist/client/sign-in.html +0 -1
  89. package/examples/full/dist/client/sign-up.html +0 -1
  90. package/examples/full/dist/ssr/.dev.vars +0 -1
  91. package/examples/full/dist/ssr/.vite/manifest.json +0 -219
  92. package/examples/full/dist/ssr/assets/BookmarkButton-KS7z5_vi.js +0 -298
  93. package/examples/full/dist/ssr/assets/_slug_-rRStRaAN.js +0 -89
  94. package/examples/full/dist/ssr/assets/auth-DSFZ4iak.js +0 -31434
  95. package/examples/full/dist/ssr/assets/auth-client-BFSBVoML.js +0 -894
  96. package/examples/full/dist/ssr/assets/bun-sqlite-dialect-C7ftEUSI-BeXpIqKl.js +0 -162
  97. package/examples/full/dist/ssr/assets/compiled-query-DmoyCh28.js +0 -8410
  98. package/examples/full/dist/ssr/assets/d1-sqlite-dialect-BZmaVTp8-CjJdvL94.js +0 -114
  99. package/examples/full/dist/ssr/assets/default-query-compiler-D7xOzCCJ.js +0 -1727
  100. package/examples/full/dist/ssr/assets/dist-LmmDoNdk.js +0 -6832
  101. package/examples/full/dist/ssr/assets/dist-kFDN1l4Z.js +0 -342
  102. package/examples/full/dist/ssr/assets/factory-AD6s9SIW.js +0 -2079
  103. package/examples/full/dist/ssr/assets/jsx-renderer-mMLf5XLN.js +0 -1926
  104. package/examples/full/dist/ssr/assets/kysely-adapter-BCLenpM8.js +0 -2
  105. package/examples/full/dist/ssr/assets/kysely-migration-tables-DFfmKhq--BtVr6hRe.js +0 -17
  106. package/examples/full/dist/ssr/assets/layout-mVA7qP4j.js +0 -44
  107. package/examples/full/dist/ssr/assets/node-sqlite-dialect-D-wtYAD7.js +0 -162
  108. package/examples/full/dist/ssr/assets/pages-Do5kR_Ia.js +0 -147
  109. package/examples/full/dist/ssr/assets/saved-Dr4pP6B5.js +0 -111
  110. package/examples/full/dist/ssr/assets/session-BvIpX7tr.js +0 -13
  111. package/examples/full/dist/ssr/assets/sign-in-22pzTnJE.js +0 -115
  112. package/examples/full/dist/ssr/assets/sign-up-CN4j8Qg1.js +0 -117
  113. package/examples/full/dist/ssr/assets/sqlite-adapter-DVlms5wO.js +0 -79
  114. package/examples/full/dist/ssr/index.js +0 -97
  115. package/examples/full/dist/ssr/wrangler.json +0 -1
@@ -1,2079 +0,0 @@
1
- //#region ../../node_modules/.pnpm/@better-auth+core@1.7.1_@better-auth+utils@0.4.2_@better-fetch+fetch@1.3.1_@cloudflare+_3ccc4a54cbe47500af416b558bca94b7/node_modules/@better-auth/core/dist/env/env-impl.mjs
2
- var _envShim = Object.create(null);
3
- var _getEnv = (useShim) => globalThis.process?.env || globalThis.Deno?.env.toObject() || globalThis.__env__ || (useShim ? _envShim : globalThis);
4
- var env = new Proxy(_envShim, {
5
- get(_, prop) {
6
- return _getEnv()[prop] ?? _envShim[prop];
7
- },
8
- has(_, prop) {
9
- return prop in _getEnv() || prop in _envShim;
10
- },
11
- set(_, prop, value) {
12
- const env = _getEnv(true);
13
- env[prop] = value;
14
- return true;
15
- },
16
- deleteProperty(_, prop) {
17
- if (!prop) return false;
18
- const env = _getEnv(true);
19
- delete env[prop];
20
- return true;
21
- },
22
- ownKeys() {
23
- const env = _getEnv(true);
24
- return Object.keys(env);
25
- }
26
- });
27
- function toBoolean(val) {
28
- return val ? val !== "false" : false;
29
- }
30
- var nodeENV = env.NODE_ENV ?? "";
31
- /** Detect if `NODE_ENV` environment variable is `production` */
32
- var isProduction = nodeENV === "production";
33
- /** Detect if `NODE_ENV` environment variable is `dev` or `development` */
34
- var isDevelopment = () => nodeENV === "dev" || nodeENV === "development";
35
- /** Detect if `NODE_ENV` environment variable is `test` */
36
- var isTest = () => nodeENV === "test" || toBoolean(env.TEST);
37
- /**
38
- * Get environment variable with fallback
39
- */
40
- function getEnvVar(key, fallback) {
41
- if (typeof process !== "undefined" && process.env) return process.env[key] ?? fallback;
42
- if (typeof Deno !== "undefined") return Deno.env.get(key) ?? fallback;
43
- if (typeof Bun !== "undefined") return Bun.env[key] ?? fallback;
44
- return fallback;
45
- }
46
- /**
47
- * Get boolean environment variable
48
- */
49
- function getBooleanEnvVar(key, fallback = true) {
50
- const value = getEnvVar(key);
51
- if (!value) return fallback;
52
- return value !== "0" && value.toLowerCase() !== "false" && value !== "";
53
- }
54
- /**
55
- * Common environment variables used in Better Auth
56
- */
57
- var ENV = Object.freeze({
58
- get BETTER_AUTH_SECRET() {
59
- return getEnvVar("BETTER_AUTH_SECRET");
60
- },
61
- get AUTH_SECRET() {
62
- return getEnvVar("AUTH_SECRET");
63
- },
64
- get BETTER_AUTH_TELEMETRY() {
65
- return getEnvVar("BETTER_AUTH_TELEMETRY");
66
- },
67
- get BETTER_AUTH_TELEMETRY_ID() {
68
- return getEnvVar("BETTER_AUTH_TELEMETRY_ID");
69
- },
70
- get NODE_ENV() {
71
- return getEnvVar("NODE_ENV", "development");
72
- },
73
- get PACKAGE_VERSION() {
74
- return getEnvVar("PACKAGE_VERSION", "0.0.0");
75
- },
76
- get BETTER_AUTH_TELEMETRY_ENDPOINT() {
77
- return getEnvVar("BETTER_AUTH_TELEMETRY_ENDPOINT", "");
78
- }
79
- });
80
- //#endregion
81
- //#region ../../node_modules/.pnpm/@better-auth+core@1.7.1_@better-auth+utils@0.4.2_@better-fetch+fetch@1.3.1_@cloudflare+_3ccc4a54cbe47500af416b558bca94b7/node_modules/@better-auth/core/dist/env/color-depth.mjs
82
- var COLORS_2 = 1;
83
- var COLORS_16 = 4;
84
- var COLORS_256 = 8;
85
- var COLORS_16m = 24;
86
- var TERM_ENVS = {
87
- eterm: COLORS_16,
88
- cons25: COLORS_16,
89
- console: COLORS_16,
90
- cygwin: COLORS_16,
91
- dtterm: COLORS_16,
92
- gnome: COLORS_16,
93
- hurd: COLORS_16,
94
- jfbterm: COLORS_16,
95
- konsole: COLORS_16,
96
- kterm: COLORS_16,
97
- mlterm: COLORS_16,
98
- mosh: COLORS_16m,
99
- putty: COLORS_16,
100
- st: COLORS_16,
101
- "rxvt-unicode-24bit": COLORS_16m,
102
- terminator: COLORS_16m,
103
- "xterm-kitty": COLORS_16m
104
- };
105
- var CI_ENVS_MAP = new Map(Object.entries({
106
- APPVEYOR: COLORS_256,
107
- BUILDKITE: COLORS_256,
108
- CIRCLECI: COLORS_16m,
109
- DRONE: COLORS_256,
110
- GITEA_ACTIONS: COLORS_16m,
111
- GITHUB_ACTIONS: COLORS_16m,
112
- GITLAB_CI: COLORS_256,
113
- TRAVIS: COLORS_256
114
- }));
115
- var TERM_ENVS_REG_EXP = [
116
- /ansi/,
117
- /color/,
118
- /linux/,
119
- /direct/,
120
- /^con[0-9]*x[0-9]/,
121
- /^rxvt/,
122
- /^screen/,
123
- /^xterm/,
124
- /^vt100/,
125
- /^vt220/
126
- ];
127
- function getColorDepth() {
128
- if (getEnvVar("FORCE_COLOR") !== void 0) switch (getEnvVar("FORCE_COLOR")) {
129
- case "":
130
- case "1":
131
- case "true": return COLORS_16;
132
- case "2": return COLORS_256;
133
- case "3": return COLORS_16m;
134
- default: return COLORS_2;
135
- }
136
- if (getEnvVar("NODE_DISABLE_COLORS") !== void 0 && getEnvVar("NODE_DISABLE_COLORS") !== "" || getEnvVar("NO_COLOR") !== void 0 && getEnvVar("NO_COLOR") !== "" || getEnvVar("TERM") === "dumb") return COLORS_2;
137
- if (getEnvVar("TMUX")) return COLORS_16m;
138
- if ("TF_BUILD" in env && "AGENT_NAME" in env) return COLORS_16;
139
- if ("CI" in env) {
140
- for (const { 0: envName, 1: colors } of CI_ENVS_MAP) if (envName in env) return colors;
141
- if (getEnvVar("CI_NAME") === "codeship") return COLORS_256;
142
- return COLORS_2;
143
- }
144
- if ("TEAMCITY_VERSION" in env) return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.exec(getEnvVar("TEAMCITY_VERSION")) !== null ? COLORS_16 : COLORS_2;
145
- switch (getEnvVar("TERM_PROGRAM")) {
146
- case "iTerm.app":
147
- if (!getEnvVar("TERM_PROGRAM_VERSION") || /^[0-2]\./.exec(getEnvVar("TERM_PROGRAM_VERSION")) !== null) return COLORS_256;
148
- return COLORS_16m;
149
- case "HyperTerm":
150
- case "MacTerm": return COLORS_16m;
151
- case "Apple_Terminal": return COLORS_256;
152
- }
153
- if (getEnvVar("COLORTERM") === "truecolor" || getEnvVar("COLORTERM") === "24bit") return COLORS_16m;
154
- if (getEnvVar("TERM")) {
155
- if (/truecolor/.exec(getEnvVar("TERM")) !== null) return COLORS_16m;
156
- if (/^xterm-256/.exec(getEnvVar("TERM")) !== null) return COLORS_256;
157
- const termEnv = getEnvVar("TERM").toLowerCase();
158
- if (TERM_ENVS[termEnv]) return TERM_ENVS[termEnv];
159
- if (TERM_ENVS_REG_EXP.some((term) => term.exec(termEnv) !== null)) return COLORS_16;
160
- }
161
- if (getEnvVar("COLORTERM")) return COLORS_16;
162
- return COLORS_2;
163
- }
164
- //#endregion
165
- //#region ../../node_modules/.pnpm/@better-auth+core@1.7.1_@better-auth+utils@0.4.2_@better-fetch+fetch@1.3.1_@cloudflare+_3ccc4a54cbe47500af416b558bca94b7/node_modules/@better-auth/core/dist/env/logger.mjs
166
- var TTY_COLORS = {
167
- reset: "\x1B[0m",
168
- bright: "\x1B[1m",
169
- dim: "\x1B[2m",
170
- undim: "\x1B[22m",
171
- underscore: "\x1B[4m",
172
- blink: "\x1B[5m",
173
- reverse: "\x1B[7m",
174
- hidden: "\x1B[8m",
175
- fg: {
176
- black: "\x1B[30m",
177
- red: "\x1B[31m",
178
- green: "\x1B[32m",
179
- yellow: "\x1B[33m",
180
- blue: "\x1B[34m",
181
- magenta: "\x1B[35m",
182
- cyan: "\x1B[36m",
183
- white: "\x1B[37m"
184
- },
185
- bg: {
186
- black: "\x1B[40m",
187
- red: "\x1B[41m",
188
- green: "\x1B[42m",
189
- yellow: "\x1B[43m",
190
- blue: "\x1B[44m",
191
- magenta: "\x1B[45m",
192
- cyan: "\x1B[46m",
193
- white: "\x1B[47m"
194
- }
195
- };
196
- var levels = [
197
- "debug",
198
- "info",
199
- "success",
200
- "warn",
201
- "error"
202
- ];
203
- function shouldPublishLog(currentLogLevel, logLevel) {
204
- return levels.indexOf(logLevel) >= levels.indexOf(currentLogLevel);
205
- }
206
- var levelColors = {
207
- info: TTY_COLORS.fg.blue,
208
- success: TTY_COLORS.fg.green,
209
- warn: TTY_COLORS.fg.yellow,
210
- error: TTY_COLORS.fg.red,
211
- debug: TTY_COLORS.fg.magenta
212
- };
213
- var formatMessage = (level, message, colorsEnabled) => {
214
- const timestamp = (/* @__PURE__ */ new Date()).toISOString();
215
- if (colorsEnabled) return `${TTY_COLORS.dim}${timestamp}${TTY_COLORS.reset} ${levelColors[level]}${level.toUpperCase()}${TTY_COLORS.reset} ${TTY_COLORS.bright}[Better Auth]:${TTY_COLORS.reset} ${message}`;
216
- return `${timestamp} ${level.toUpperCase()} [Better Auth]: ${message}`;
217
- };
218
- var createLogger = (options) => {
219
- const enabled = options?.disabled !== true;
220
- const logLevel = options?.level ?? "warn";
221
- const colorsEnabled = options?.disableColors !== void 0 ? !options.disableColors : getColorDepth() !== 1;
222
- const LogFunc = (level, message, args = []) => {
223
- if (!enabled || !shouldPublishLog(logLevel, level)) return;
224
- const formattedMessage = formatMessage(level, message, colorsEnabled);
225
- if (!options || typeof options.log !== "function") {
226
- if (level === "error") console.error(formattedMessage, ...args);
227
- else if (level === "warn") console.warn(formattedMessage, ...args);
228
- else console.log(formattedMessage, ...args);
229
- return;
230
- }
231
- options.log(level === "success" ? "info" : level, message, ...args);
232
- };
233
- return {
234
- ...Object.fromEntries(levels.map((level) => [level, (...[message, ...args]) => LogFunc(level, message, args)])),
235
- get level() {
236
- return logLevel;
237
- }
238
- };
239
- };
240
- var logger = createLogger();
241
- //#endregion
242
- //#region ../../node_modules/.pnpm/better-call@1.4.0_zod@4.4.3/node_modules/better-call/dist/error.mjs
243
- function isErrorStackTraceLimitWritable() {
244
- const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit");
245
- if (desc === void 0) return Object.isExtensible(Error);
246
- return Object.prototype.hasOwnProperty.call(desc, "writable") ? desc.writable : desc.set !== void 0;
247
- }
248
- /**
249
- * Hide internal stack frames from the error stack trace.
250
- */
251
- function hideInternalStackFrames(stack) {
252
- const lines = stack.split("\n at ");
253
- if (lines.length <= 1) return stack;
254
- lines.splice(1, 1);
255
- return lines.join("\n at ");
256
- }
257
- /**
258
- * Creates a custom error class that hides stack frames.
259
- */
260
- function makeErrorForHideStackFrame(Base, clazz) {
261
- class HideStackFramesError extends Base {
262
- #hiddenStack;
263
- constructor(...args) {
264
- if (isErrorStackTraceLimitWritable()) {
265
- const limit = Error.stackTraceLimit;
266
- Error.stackTraceLimit = 0;
267
- super(...args);
268
- Error.stackTraceLimit = limit;
269
- } else super(...args);
270
- const stack = (/* @__PURE__ */ new Error()).stack;
271
- if (stack) this.#hiddenStack = hideInternalStackFrames(stack.replace(/^Error/, this.name));
272
- }
273
- get errorStack() {
274
- return this.#hiddenStack;
275
- }
276
- }
277
- Object.defineProperty(HideStackFramesError.prototype, "constructor", {
278
- get() {
279
- return clazz;
280
- },
281
- enumerable: false,
282
- configurable: true
283
- });
284
- return HideStackFramesError;
285
- }
286
- var statusCodes = {
287
- OK: 200,
288
- CREATED: 201,
289
- ACCEPTED: 202,
290
- NO_CONTENT: 204,
291
- MULTIPLE_CHOICES: 300,
292
- MOVED_PERMANENTLY: 301,
293
- FOUND: 302,
294
- SEE_OTHER: 303,
295
- NOT_MODIFIED: 304,
296
- TEMPORARY_REDIRECT: 307,
297
- BAD_REQUEST: 400,
298
- UNAUTHORIZED: 401,
299
- PAYMENT_REQUIRED: 402,
300
- FORBIDDEN: 403,
301
- NOT_FOUND: 404,
302
- METHOD_NOT_ALLOWED: 405,
303
- NOT_ACCEPTABLE: 406,
304
- PROXY_AUTHENTICATION_REQUIRED: 407,
305
- REQUEST_TIMEOUT: 408,
306
- CONFLICT: 409,
307
- GONE: 410,
308
- LENGTH_REQUIRED: 411,
309
- PRECONDITION_FAILED: 412,
310
- PAYLOAD_TOO_LARGE: 413,
311
- URI_TOO_LONG: 414,
312
- UNSUPPORTED_MEDIA_TYPE: 415,
313
- RANGE_NOT_SATISFIABLE: 416,
314
- EXPECTATION_FAILED: 417,
315
- "I'M_A_TEAPOT": 418,
316
- MISDIRECTED_REQUEST: 421,
317
- UNPROCESSABLE_ENTITY: 422,
318
- LOCKED: 423,
319
- FAILED_DEPENDENCY: 424,
320
- TOO_EARLY: 425,
321
- UPGRADE_REQUIRED: 426,
322
- PRECONDITION_REQUIRED: 428,
323
- TOO_MANY_REQUESTS: 429,
324
- REQUEST_HEADER_FIELDS_TOO_LARGE: 431,
325
- UNAVAILABLE_FOR_LEGAL_REASONS: 451,
326
- INTERNAL_SERVER_ERROR: 500,
327
- NOT_IMPLEMENTED: 501,
328
- BAD_GATEWAY: 502,
329
- SERVICE_UNAVAILABLE: 503,
330
- GATEWAY_TIMEOUT: 504,
331
- HTTP_VERSION_NOT_SUPPORTED: 505,
332
- VARIANT_ALSO_NEGOTIATES: 506,
333
- INSUFFICIENT_STORAGE: 507,
334
- LOOP_DETECTED: 508,
335
- NOT_EXTENDED: 510,
336
- NETWORK_AUTHENTICATION_REQUIRED: 511
337
- };
338
- var InternalAPIError = class extends Error {
339
- status;
340
- body;
341
- headers;
342
- statusCode;
343
- constructor(status = "INTERNAL_SERVER_ERROR", body = void 0, headers = {}, statusCode = typeof status === "number" ? status : statusCodes[status]) {
344
- super(body?.message, body?.cause ? { cause: body.cause } : void 0);
345
- this.status = status;
346
- this.body = body;
347
- this.headers = headers;
348
- this.statusCode = statusCode;
349
- this.name = "APIError";
350
- this.status = status;
351
- this.headers = headers;
352
- this.statusCode = statusCode;
353
- this.body = body;
354
- }
355
- };
356
- var ValidationError = class extends InternalAPIError {
357
- message;
358
- issues;
359
- constructor(message, issues) {
360
- super(400, {
361
- message,
362
- code: "VALIDATION_ERROR"
363
- });
364
- this.message = message;
365
- this.issues = issues;
366
- this.issues = issues;
367
- }
368
- };
369
- var BetterCallError = class extends Error {
370
- constructor(message) {
371
- super(message);
372
- this.name = "BetterCallError";
373
- }
374
- };
375
- var kAPIErrorHeaderSymbol = Symbol.for("better-call:api-error-headers");
376
- var APIError$1 = makeErrorForHideStackFrame(InternalAPIError, Error);
377
- //#endregion
378
- //#region ../../node_modules/.pnpm/@better-auth+core@1.7.1_@better-auth+utils@0.4.2_@better-fetch+fetch@1.3.1_@cloudflare+_3ccc4a54cbe47500af416b558bca94b7/node_modules/@better-auth/core/dist/error/index.mjs
379
- var BetterAuthError = class extends Error {
380
- constructor(message, options) {
381
- super(message, options);
382
- this.name = "BetterAuthError";
383
- this.message = message;
384
- this.stack = "";
385
- }
386
- };
387
- var APIError = class APIError extends APIError$1 {
388
- constructor(...args) {
389
- super(...args);
390
- }
391
- static fromStatus(status, body) {
392
- return new APIError(status, body);
393
- }
394
- static from(status, error) {
395
- return new APIError(status, {
396
- message: error.message,
397
- code: error.code
398
- });
399
- }
400
- };
401
- //#endregion
402
- //#region ../../node_modules/.pnpm/@better-auth+utils@0.4.2/node_modules/@better-auth/utils/dist/random.mjs
403
- function expandAlphabet(alphabet) {
404
- switch (alphabet) {
405
- case "a-z": return "abcdefghijklmnopqrstuvwxyz";
406
- case "A-Z": return "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
407
- case "0-9": return "0123456789";
408
- case "-_": return "-_";
409
- default: throw new Error(`Unsupported alphabet: ${alphabet}`);
410
- }
411
- }
412
- function createRandomStringGenerator(...baseAlphabets) {
413
- const baseCharSet = baseAlphabets.map(expandAlphabet).join("");
414
- if (baseCharSet.length === 0) throw new Error("No valid characters provided for random string generation.");
415
- const baseCharSetLength = baseCharSet.length;
416
- return (length, ...alphabets) => {
417
- if (length <= 0) throw new Error("Length must be a positive integer.");
418
- let charSet = baseCharSet;
419
- let charSetLength = baseCharSetLength;
420
- if (alphabets.length > 0) {
421
- charSet = alphabets.map(expandAlphabet).join("");
422
- charSetLength = charSet.length;
423
- }
424
- const maxValid = Math.floor(256 / charSetLength) * charSetLength;
425
- const buf = new Uint8Array(length * 2);
426
- const bufLength = buf.length;
427
- let result = "";
428
- let bufIndex = bufLength;
429
- let rand;
430
- while (result.length < length) {
431
- if (bufIndex >= bufLength) {
432
- crypto.getRandomValues(buf);
433
- bufIndex = 0;
434
- }
435
- rand = buf[bufIndex++];
436
- if (rand < maxValid) result += charSet[rand % charSetLength];
437
- }
438
- return result;
439
- };
440
- }
441
- //#endregion
442
- //#region ../../node_modules/.pnpm/@better-auth+core@1.7.1_@better-auth+utils@0.4.2_@better-fetch+fetch@1.3.1_@cloudflare+_3ccc4a54cbe47500af416b558bca94b7/node_modules/@better-auth/core/dist/db/database-index.mjs
443
- var MAX_DATABASE_INDEX_NAME_BYTES = 63;
444
- var MAX_DATABASE_INDEX_FIELDS = 16;
445
- function getPortableDatabaseIdentifierKey(identifier) {
446
- return identifier.toLowerCase();
447
- }
448
- function getUtf8ByteLength(value) {
449
- return new TextEncoder().encode(value).length;
450
- }
451
- function truncateUtf8(value, maxBytes) {
452
- let result = "";
453
- let byteLength = 0;
454
- for (const character of value) {
455
- const characterByteLength = getUtf8ByteLength(character);
456
- if (byteLength + characterByteLength > maxBytes) break;
457
- result += character;
458
- byteLength += characterByteLength;
459
- }
460
- return result;
461
- }
462
- function getStableIndexNameHash(value) {
463
- let hash = 2166136261;
464
- for (let index = 0; index < value.length; index++) {
465
- hash ^= value.charCodeAt(index);
466
- hash = Math.imul(hash, 16777619);
467
- }
468
- return (hash >>> 0).toString(16).padStart(8, "0");
469
- }
470
- /** Returns the stable database name for a table-level index. */
471
- function getDatabaseIndexName(tableName, index) {
472
- if (index.name !== void 0) {
473
- if (index.name.trim().length === 0) throw new BetterAuthError("Database index names must contain at least one visible character.");
474
- if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(index.name)) throw new BetterAuthError("Database index names must start with a letter or underscore and contain only letters, numbers, and underscores.");
475
- if (getUtf8ByteLength(index.name) > MAX_DATABASE_INDEX_NAME_BYTES) throw new BetterAuthError(`Database index names must be at most ${MAX_DATABASE_INDEX_NAME_BYTES} UTF-8 bytes.`);
476
- return index.name;
477
- }
478
- const indexKind = index.unique ? "uidx" : "idx";
479
- const generatedName = `${tableName}_${index.fields.join("_")}_${indexKind}`;
480
- if (getUtf8ByteLength(generatedName) <= MAX_DATABASE_INDEX_NAME_BYTES) return generatedName;
481
- const suffix = `_${getStableIndexNameHash(generatedName)}_${indexKind}`;
482
- return `${truncateUtf8(generatedName.slice(0, -indexKind.length - 1), MAX_DATABASE_INDEX_NAME_BYTES - getUtf8ByteLength(suffix))}${suffix}`;
483
- }
484
- /** Returns the database name used by legacy field-level index metadata. */
485
- function getDatabaseFieldIndexName(tableName, columnName, unique) {
486
- return getDatabaseIndexName(tableName, {
487
- fields: [columnName],
488
- unique
489
- });
490
- }
491
- /** Resolves logical index fields to their configured database column names. */
492
- function resolveDatabaseTableIndexes({ fields, indexes, tableName }) {
493
- const resolvedIndexes = (indexes ?? []).map((index) => {
494
- if (index.fields.length === 0) throw new BetterAuthError(`Index on table "${tableName}" must include at least one field.`);
495
- if (index.fields.length > MAX_DATABASE_INDEX_FIELDS) throw new BetterAuthError(`Index on table "${tableName}" can include at most ${MAX_DATABASE_INDEX_FIELDS} fields so it works across supported databases.`);
496
- if (new Set(index.fields).size !== index.fields.length) throw new BetterAuthError(`Index on table "${tableName}" contains the same field more than once.`);
497
- if (index.unique && index.fields.some((fieldName) => fields[fieldName]?.required === false)) throw new BetterAuthError(`Unique index on table "${tableName}" can only include required fields so its behavior is consistent across databases.`);
498
- const unsupportedField = index.fields.find((fieldName) => {
499
- const fieldType = fields[fieldName]?.type;
500
- return fieldType === "json" || fieldType === "string[]" || fieldType === "number[]";
501
- });
502
- if (unsupportedField) throw new BetterAuthError(`Index on table "${tableName}" references field "${unsupportedField}", whose type is not portably indexable.`);
503
- const resolveFieldName = (fieldName) => {
504
- const field = fields[fieldName];
505
- if (!field) throw new BetterAuthError(`Index on table "${tableName}" references unknown field "${fieldName}".`);
506
- return field.fieldName || fieldName;
507
- };
508
- const [firstField, ...remainingFields] = index.fields;
509
- const columns = [resolveFieldName(firstField), ...remainingFields.map(resolveFieldName)];
510
- if (new Set(columns.map(getPortableDatabaseIdentifierKey)).size !== columns.length) throw new BetterAuthError(`Index on table "${tableName}" resolves more than one field to the same database column.`);
511
- return {
512
- columns,
513
- name: getDatabaseIndexName(tableName, {
514
- ...index,
515
- fields: columns
516
- }),
517
- unique: index.unique
518
- };
519
- });
520
- const definitionsByName = /* @__PURE__ */ new Map();
521
- const deduplicatedIndexes = [];
522
- for (const index of resolvedIndexes) {
523
- const definition = JSON.stringify([index.columns, index.unique ?? false]);
524
- const identifierKey = getPortableDatabaseIdentifierKey(index.name);
525
- const existingDefinition = definitionsByName.get(identifierKey);
526
- if (existingDefinition && existingDefinition !== definition) throw new BetterAuthError(`Database index name "${index.name}" identifies more than one index on table "${tableName}".`);
527
- if (existingDefinition) continue;
528
- definitionsByName.set(identifierKey, definition);
529
- deduplicatedIndexes.push(index);
530
- }
531
- return deduplicatedIndexes;
532
- }
533
- /**
534
- * Returns a safe generated string length for a column across all of its table
535
- * indexes in byte-limited SQL dialects.
536
- */
537
- function getDatabaseIndexStringLength({ columnName, dialect, fields, indexes }) {
538
- const fieldsByColumn = new Map(Object.entries(fields).map(([fieldName, field]) => [field.fieldName || fieldName, field]));
539
- const containingIndexes = indexes.filter((index) => index.columns.includes(columnName));
540
- if (containingIndexes.length === 0) return void 0;
541
- const byteBudget = dialect === "mysql" ? 3072 : 1700;
542
- const bytesPerCharacter = dialect === "mysql" ? 4 : 1;
543
- const defaultLength = dialect === "mysql" ? 191 : 255;
544
- return containingIndexes.reduce((length, index) => {
545
- const stringColumnCount = index.columns.filter((column) => {
546
- const type = fieldsByColumn.get(column)?.type;
547
- return type === "string" || Array.isArray(type);
548
- }).length;
549
- if (stringColumnCount === 0) return length;
550
- const nonStringColumnBytes = (index.columns.length - stringColumnCount) * 16;
551
- const safeLength = Math.floor(Math.max(1, byteBudget - nonStringColumnBytes) / bytesPerCharacter / stringColumnCount);
552
- return Math.min(length, safeLength);
553
- }, defaultLength);
554
- }
555
- /**
556
- * Resolves and validates every table index as one portable database schema.
557
- *
558
- * Index names are schema-wide because SQLite and PostgreSQL do not scope them
559
- * to an individual table.
560
- */
561
- function resolveDatabaseSchemaIndexes(sources) {
562
- const mergedSourcesByTable = /* @__PURE__ */ new Map();
563
- for (const source of sources) {
564
- const existingSource = mergedSourcesByTable.get(source.tableName);
565
- if (existingSource) {
566
- if (existingSource.indexes.length > 0 || (source.indexes?.length ?? 0) > 0) throw new BetterAuthError(`Database schema resolves more than one indexed logical table to "${source.tableName}". Define table-level indexes through one logical schema key instead of aliasing multiple keys to the same database table.`);
567
- Object.assign(existingSource.fields, source.fields);
568
- continue;
569
- }
570
- const mergedSource = {
571
- fields: {},
572
- indexes: [],
573
- tableName: source.tableName
574
- };
575
- Object.assign(mergedSource.fields, source.fields);
576
- mergedSource.indexes.push(...source.indexes ?? []);
577
- mergedSourcesByTable.set(source.tableName, mergedSource);
578
- }
579
- const indexesByTable = /* @__PURE__ */ new Map();
580
- const indexOwnerByName = /* @__PURE__ */ new Map();
581
- const tableNamesByIdentifier = new Map([...mergedSourcesByTable.keys()].map((tableName) => [getPortableDatabaseIdentifierKey(tableName), tableName]));
582
- const fieldIndexOwnerByName = /* @__PURE__ */ new Map();
583
- for (const source of mergedSourcesByTable.values()) for (const [fieldName, field] of Object.entries(source.fields)) {
584
- if (!field.index && !field.unique) continue;
585
- const indexName = getDatabaseFieldIndexName(source.tableName, field.fieldName || fieldName, field.unique ?? false);
586
- const identifierKey = getPortableDatabaseIdentifierKey(indexName);
587
- if (tableNamesByIdentifier.has(identifierKey)) throw new BetterAuthError(`Database index name "${indexName}" conflicts with a table name. Index and table names must be unique across the schema.`);
588
- const existingOwner = fieldIndexOwnerByName.get(identifierKey);
589
- if (existingOwner) throw new BetterAuthError(`Database field-level index name "${indexName}" is used by both table "${existingOwner}" and table "${source.tableName}".`);
590
- fieldIndexOwnerByName.set(identifierKey, source.tableName);
591
- }
592
- for (const source of mergedSourcesByTable.values()) {
593
- const resolvedIndexes = resolveDatabaseTableIndexes(source);
594
- indexesByTable.set(source.tableName, [...resolvedIndexes]);
595
- for (const index of resolvedIndexes) {
596
- const identifierKey = getPortableDatabaseIdentifierKey(index.name);
597
- if (tableNamesByIdentifier.has(identifierKey)) throw new BetterAuthError(`Database index name "${index.name}" conflicts with a table name. Index and table names must be unique across the schema.`);
598
- const fieldIndexOwner = fieldIndexOwnerByName.get(identifierKey);
599
- if (fieldIndexOwner) throw new BetterAuthError(`Database index name "${index.name}" is already reserved by field-level index metadata on table "${fieldIndexOwner}". Remove the duplicate table-level index or give it a distinct name.`);
600
- const indexOwner = indexOwnerByName.get(identifierKey);
601
- if (indexOwner && indexOwner !== source.tableName) throw new BetterAuthError(`Database index name "${index.name}" is used by both table "${indexOwner}" and table "${source.tableName}". Index names must be unique across the schema.`);
602
- indexOwnerByName.set(identifierKey, source.tableName);
603
- }
604
- }
605
- return indexesByTable;
606
- }
607
- //#endregion
608
- //#region ../../node_modules/.pnpm/@better-auth+core@1.7.1_@better-auth+utils@0.4.2_@better-fetch+fetch@1.3.1_@cloudflare+_3ccc4a54cbe47500af416b558bca94b7/node_modules/@better-auth/core/dist/db/get-tables.mjs
609
- function mergeTableIndexes(...indexCollections) {
610
- const indexes = [];
611
- const seenIndexDefinitions = /* @__PURE__ */ new Set();
612
- for (const index of indexCollections.flatMap((collection) => collection ?? [])) {
613
- const definition = JSON.stringify([
614
- index.name ?? null,
615
- index.fields,
616
- index.unique ?? false
617
- ]);
618
- if (seenIndexDefinitions.has(definition)) continue;
619
- seenIndexDefinitions.add(definition);
620
- indexes.push(index);
621
- }
622
- return indexes;
623
- }
624
- var buildAuthTables = (options) => {
625
- const pluginSchema = (options.plugins ?? []).reduce((acc, plugin) => {
626
- const schema = plugin.schema;
627
- if (!schema) return acc;
628
- for (const [key, value] of Object.entries(schema)) acc[key] = {
629
- fields: {
630
- ...acc[key]?.fields,
631
- ...value.fields
632
- },
633
- indexes: mergeTableIndexes(acc[key]?.indexes, value.indexes),
634
- modelName: value.modelName || key,
635
- disableMigrations: value.disableMigration ?? acc[key]?.disableMigrations
636
- };
637
- return acc;
638
- }, {});
639
- const shouldAddRateLimitTable = options.rateLimit?.storage === "database";
640
- const rateLimitTable = { rateLimit: {
641
- modelName: options.rateLimit?.modelName || "rateLimit",
642
- fields: {
643
- key: {
644
- type: "string",
645
- unique: true,
646
- required: true,
647
- fieldName: options.rateLimit?.fields?.key || "key"
648
- },
649
- count: {
650
- type: "number",
651
- required: true,
652
- fieldName: options.rateLimit?.fields?.count || "count"
653
- },
654
- lastRequest: {
655
- type: "number",
656
- bigint: true,
657
- required: true,
658
- fieldName: options.rateLimit?.fields?.lastRequest || "lastRequest",
659
- defaultValue: () => Date.now()
660
- }
661
- }
662
- } };
663
- const { user, session, account, verification, ...pluginTables } = pluginSchema;
664
- const verificationTable = { verification: {
665
- modelName: options.verification?.modelName || "verification",
666
- indexes: verification?.indexes,
667
- fields: {
668
- identifier: {
669
- type: "string",
670
- required: true,
671
- fieldName: options.verification?.fields?.identifier || "identifier",
672
- index: true
673
- },
674
- value: {
675
- type: "string",
676
- required: true,
677
- fieldName: options.verification?.fields?.value || "value"
678
- },
679
- expiresAt: {
680
- type: "date",
681
- required: true,
682
- fieldName: options.verification?.fields?.expiresAt || "expiresAt"
683
- },
684
- createdAt: {
685
- type: "date",
686
- required: true,
687
- defaultValue: () => /* @__PURE__ */ new Date(),
688
- fieldName: options.verification?.fields?.createdAt || "createdAt"
689
- },
690
- updatedAt: {
691
- type: "date",
692
- required: true,
693
- defaultValue: () => /* @__PURE__ */ new Date(),
694
- onUpdate: () => /* @__PURE__ */ new Date(),
695
- fieldName: options.verification?.fields?.updatedAt || "updatedAt"
696
- },
697
- ...verification?.fields,
698
- ...options.verification?.additionalFields
699
- },
700
- order: 4
701
- } };
702
- const sessionTable = { session: {
703
- modelName: options.session?.modelName || "session",
704
- indexes: session?.indexes,
705
- fields: {
706
- expiresAt: {
707
- type: "date",
708
- required: true,
709
- fieldName: options.session?.fields?.expiresAt || "expiresAt"
710
- },
711
- token: {
712
- type: "string",
713
- required: true,
714
- fieldName: options.session?.fields?.token || "token",
715
- unique: true
716
- },
717
- createdAt: {
718
- type: "date",
719
- required: true,
720
- fieldName: options.session?.fields?.createdAt || "createdAt",
721
- defaultValue: () => /* @__PURE__ */ new Date()
722
- },
723
- updatedAt: {
724
- type: "date",
725
- required: true,
726
- fieldName: options.session?.fields?.updatedAt || "updatedAt",
727
- onUpdate: () => /* @__PURE__ */ new Date()
728
- },
729
- ipAddress: {
730
- type: "string",
731
- required: false,
732
- fieldName: options.session?.fields?.ipAddress || "ipAddress"
733
- },
734
- userAgent: {
735
- type: "string",
736
- required: false,
737
- fieldName: options.session?.fields?.userAgent || "userAgent"
738
- },
739
- userId: {
740
- type: "string",
741
- fieldName: options.session?.fields?.userId || "userId",
742
- references: {
743
- model: "user",
744
- field: "id",
745
- onDelete: "cascade"
746
- },
747
- required: true,
748
- index: true
749
- },
750
- ...session?.fields,
751
- ...options.session?.additionalFields
752
- },
753
- order: 2
754
- } };
755
- return {
756
- user: {
757
- modelName: options.user?.modelName || "user",
758
- indexes: user?.indexes,
759
- fields: {
760
- name: {
761
- type: "string",
762
- required: true,
763
- fieldName: options.user?.fields?.name || "name",
764
- sortable: true
765
- },
766
- email: {
767
- type: "string",
768
- unique: true,
769
- required: true,
770
- fieldName: options.user?.fields?.email || "email",
771
- sortable: true
772
- },
773
- emailVerified: {
774
- type: "boolean",
775
- defaultValue: false,
776
- required: true,
777
- fieldName: options.user?.fields?.emailVerified || "emailVerified",
778
- input: false
779
- },
780
- image: {
781
- type: "string",
782
- required: false,
783
- fieldName: options.user?.fields?.image || "image"
784
- },
785
- createdAt: {
786
- type: "date",
787
- defaultValue: () => /* @__PURE__ */ new Date(),
788
- required: true,
789
- fieldName: options.user?.fields?.createdAt || "createdAt"
790
- },
791
- updatedAt: {
792
- type: "date",
793
- defaultValue: () => /* @__PURE__ */ new Date(),
794
- onUpdate: () => /* @__PURE__ */ new Date(),
795
- required: true,
796
- fieldName: options.user?.fields?.updatedAt || "updatedAt"
797
- },
798
- ...user?.fields,
799
- ...options.user?.additionalFields
800
- },
801
- order: 1
802
- },
803
- ...!options.secondaryStorage || options.session?.storeSessionInDatabase ? sessionTable : {},
804
- account: {
805
- modelName: options.account?.modelName || "account",
806
- indexes: mergeTableIndexes([{
807
- fields: ["issuer", "accountId"],
808
- unique: true
809
- }], account?.indexes),
810
- fields: {
811
- issuer: {
812
- type: "string",
813
- required: true,
814
- fieldName: options.account?.fields?.issuer || "issuer"
815
- },
816
- accountId: {
817
- type: "string",
818
- required: true,
819
- fieldName: options.account?.fields?.accountId || "accountId"
820
- },
821
- providerId: {
822
- type: "string",
823
- required: true,
824
- fieldName: options.account?.fields?.providerId || "providerId"
825
- },
826
- userId: {
827
- type: "string",
828
- references: {
829
- model: "user",
830
- field: "id",
831
- onDelete: "cascade"
832
- },
833
- required: true,
834
- fieldName: options.account?.fields?.userId || "userId",
835
- index: true
836
- },
837
- accessToken: {
838
- type: "string",
839
- required: false,
840
- returned: false,
841
- fieldName: options.account?.fields?.accessToken || "accessToken"
842
- },
843
- refreshToken: {
844
- type: "string",
845
- required: false,
846
- returned: false,
847
- fieldName: options.account?.fields?.refreshToken || "refreshToken"
848
- },
849
- idToken: {
850
- type: "string",
851
- required: false,
852
- returned: false,
853
- fieldName: options.account?.fields?.idToken || "idToken"
854
- },
855
- accessTokenExpiresAt: {
856
- type: "date",
857
- required: false,
858
- returned: false,
859
- fieldName: options.account?.fields?.accessTokenExpiresAt || "accessTokenExpiresAt"
860
- },
861
- refreshTokenExpiresAt: {
862
- type: "date",
863
- required: false,
864
- returned: false,
865
- fieldName: options.account?.fields?.refreshTokenExpiresAt || "refreshTokenExpiresAt"
866
- },
867
- scope: {
868
- type: "string",
869
- required: false,
870
- fieldName: options.account?.fields?.scope || "scope"
871
- },
872
- password: {
873
- type: "string",
874
- required: false,
875
- returned: false,
876
- fieldName: options.account?.fields?.password || "password"
877
- },
878
- createdAt: {
879
- type: "date",
880
- required: true,
881
- fieldName: options.account?.fields?.createdAt || "createdAt",
882
- defaultValue: () => /* @__PURE__ */ new Date()
883
- },
884
- updatedAt: {
885
- type: "date",
886
- required: true,
887
- fieldName: options.account?.fields?.updatedAt || "updatedAt",
888
- onUpdate: () => /* @__PURE__ */ new Date()
889
- },
890
- ...account?.fields,
891
- ...options.account?.additionalFields
892
- },
893
- order: 3
894
- },
895
- ...!options.secondaryStorage || options.verification?.storeInDatabase ? verificationTable : {},
896
- ...pluginTables,
897
- ...shouldAddRateLimitTable ? rateLimitTable : {}
898
- };
899
- };
900
- function getAuthTablesWithResolvedIndexes(options) {
901
- const tables = buildAuthTables(options);
902
- return {
903
- indexesByTable: resolveDatabaseSchemaIndexes(Object.values(tables).filter((table) => !("disableMigrations" in table) || !table.disableMigrations).map((table) => ({
904
- fields: table.fields,
905
- indexes: "indexes" in table ? table.indexes : void 0,
906
- tableName: table.modelName
907
- }))),
908
- tables
909
- };
910
- }
911
- var getAuthTables = (options) => getAuthTablesWithResolvedIndexes(options).tables;
912
- //#endregion
913
- //#region ../../node_modules/.pnpm/@better-auth+core@1.7.1_@better-auth+utils@0.4.2_@better-fetch+fetch@1.3.1_@cloudflare+_3ccc4a54cbe47500af416b558bca94b7/node_modules/@better-auth/core/dist/utils/json.mjs
914
- var iso8601Regex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/;
915
- function reviveDate(value) {
916
- if (typeof value === "string" && iso8601Regex.test(value)) {
917
- const date = new Date(value);
918
- if (!isNaN(date.getTime())) return date;
919
- }
920
- return value;
921
- }
922
- /**
923
- * Recursively walk a pre-parsed object and convert ISO 8601 date strings
924
- * to Date instances. This handles the case where a Redis client (or similar)
925
- * returns already-parsed JSON objects whose date fields are still strings.
926
- */
927
- function reviveDates(value) {
928
- if (value === null || value === void 0) return value;
929
- if (typeof value === "string") return reviveDate(value);
930
- if (value instanceof Date) return value;
931
- if (Array.isArray(value)) return value.map(reviveDates);
932
- if (typeof value === "object") {
933
- const result = {};
934
- for (const key of Object.keys(value)) result[key] = reviveDates(value[key]);
935
- return result;
936
- }
937
- return value;
938
- }
939
- function safeJSONParse(data) {
940
- try {
941
- if (typeof data !== "string") {
942
- if (data === null || data === void 0) return null;
943
- return reviveDates(data);
944
- }
945
- return JSON.parse(data, (_, value) => reviveDate(value));
946
- } catch (e) {
947
- logger.error("Error parsing JSON", { error: e });
948
- return null;
949
- }
950
- }
951
- //#endregion
952
- //#region ../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.43.0/node_modules/@opentelemetry/semantic-conventions/build/esm/stable_attributes.js
953
- /**
954
- * The name of a collection (table, container) within the database.
955
- *
956
- * @example public.users
957
- * @example customers
958
- *
959
- * @note It is **RECOMMENDED** to capture the value as provided by the application
960
- * without attempting to do any case normalization.
961
- *
962
- * The collection name **SHOULD NOT** be extracted from `db.query.text`,
963
- * when the database system supports query text with multiple collections
964
- * in non-batch operations.
965
- *
966
- * For batch operations, if the individual operations are known to have the same
967
- * collection name then that collection name **SHOULD** be used.
968
- */
969
- var ATTR_DB_COLLECTION_NAME = "db.collection.name";
970
- /**
971
- * The name of the operation or command being executed.
972
- *
973
- * @example findAndModify
974
- * @example HMSET
975
- * @example SELECT
976
- *
977
- * @note It is **RECOMMENDED** to capture the value as provided by the application
978
- * without attempting to do any case normalization.
979
- *
980
- * The operation name **SHOULD NOT** be extracted from `db.query.text`,
981
- * when the database system supports query text with multiple operations
982
- * in non-batch operations.
983
- *
984
- * If spaces can occur in the operation name, multiple consecutive spaces
985
- * **SHOULD** be normalized to a single space.
986
- *
987
- * For batch operations, if the individual operations are known to have the same operation name
988
- * then that operation name **SHOULD** be used prepended by `BATCH `,
989
- * otherwise `db.operation.name` **SHOULD** be `BATCH` or some other database
990
- * system specific term if more applicable.
991
- */
992
- var ATTR_DB_OPERATION_NAME = "db.operation.name";
993
- /**
994
- * [HTTP response status code](https://tools.ietf.org/html/rfc7231#section-6).
995
- *
996
- * @example 200
997
- */
998
- var ATTR_HTTP_RESPONSE_STATUS_CODE = "http.response.status_code";
999
- /**
1000
- * The matched route template for the request. This **MUST** be low-cardinality and include all static path segments, with dynamic path segments represented with placeholders.
1001
- *
1002
- * @example /users/:userID?
1003
- * @example my-controller/my-action/{id?}
1004
- *
1005
- * @note **MUST NOT** be populated when this is not supported by the HTTP server framework as the route attribute should have low-cardinality and the URI path can NOT substitute it.
1006
- * **SHOULD** include the [application root](/docs/http/http-spans.md#http-server-definitions) if there is one.
1007
- *
1008
- * A static path segment is a part of the route template with a fixed, low-cardinality value. This includes literal strings like `/users/` and placeholders that
1009
- * are constrained to a finite, predefined set of values, e.g. `{controller}` or `{action}`.
1010
- *
1011
- * A dynamic path segment is a placeholder for a value that can have high cardinality and is not constrained to a predefined list like static path segments.
1012
- *
1013
- * Instrumentations **SHOULD** use routing information provided by the corresponding web framework. They **SHOULD** pick the most precise source of routing information and **MAY**
1014
- * support custom route formatting. Instrumentations **SHOULD** document the format and the API used to obtain the route string.
1015
- */
1016
- var ATTR_HTTP_ROUTE = "http.route";
1017
- //#endregion
1018
- //#region ../../node_modules/.pnpm/@better-auth+core@1.7.1_@better-auth+utils@0.4.2_@better-fetch+fetch@1.3.1_@cloudflare+_3ccc4a54cbe47500af416b558bca94b7/node_modules/@better-auth/core/dist/instrumentation/pure.index.mjs
1019
- function withSpan(_name, _attributes, fn) {
1020
- return fn();
1021
- }
1022
- //#endregion
1023
- //#region ../../node_modules/.pnpm/@better-auth+core@1.7.1_@better-auth+utils@0.4.2_@better-fetch+fetch@1.3.1_@cloudflare+_3ccc4a54cbe47500af416b558bca94b7/node_modules/@better-auth/core/dist/utils/id.mjs
1024
- var generateId = (size) => {
1025
- return createRandomStringGenerator("a-z", "A-Z", "0-9")(size || 32);
1026
- };
1027
- //#endregion
1028
- //#region ../../node_modules/.pnpm/@better-auth+core@1.7.1_@better-auth+utils@0.4.2_@better-fetch+fetch@1.3.1_@cloudflare+_3ccc4a54cbe47500af416b558bca94b7/node_modules/@better-auth/core/dist/db/adapter/get-default-model-name.mjs
1029
- var initGetDefaultModelName = ({ usePlural, schema }) => {
1030
- /**
1031
- * This function helps us get the default model name from the schema defined by devs.
1032
- * Often times, the user will be using the `modelName` which could had been customized by the users.
1033
- * This function helps us get the actual model name useful to match against the schema. (eg: schema[model])
1034
- *
1035
- * If it's still unclear what this does:
1036
- *
1037
- * 1. User can define a custom modelName.
1038
- * 2. When using a custom modelName, doing something like `schema[model]` will not work.
1039
- * 3. Using this function helps us get the actual model name based on the user's defined custom modelName.
1040
- */
1041
- const getDefaultModelName = (model) => {
1042
- const resolve = (candidate) => {
1043
- if (schema[candidate]) return candidate;
1044
- return Object.entries(schema).find(([_, f]) => f.modelName === candidate)?.[0];
1045
- };
1046
- if (usePlural && model.charAt(model.length - 1) === "s") {
1047
- const m = resolve(model.slice(0, -1));
1048
- if (m) return m;
1049
- }
1050
- const m = resolve(model);
1051
- if (!m) throw new BetterAuthError(`Model "${model}" not found in schema`);
1052
- return m;
1053
- };
1054
- return getDefaultModelName;
1055
- };
1056
- //#endregion
1057
- //#region ../../node_modules/.pnpm/@better-auth+core@1.7.1_@better-auth+utils@0.4.2_@better-fetch+fetch@1.3.1_@cloudflare+_3ccc4a54cbe47500af416b558bca94b7/node_modules/@better-auth/core/dist/db/adapter/get-default-field-name.mjs
1058
- var initGetDefaultFieldName = ({ schema, usePlural }) => {
1059
- const getDefaultModelName = initGetDefaultModelName({
1060
- schema,
1061
- usePlural
1062
- });
1063
- /**
1064
- * This function helps us get the default field name from the schema defined by devs.
1065
- * Often times, the user will be using the `fieldName` which could had been customized by the users.
1066
- * This function helps us get the actual field name useful to match against the schema. (eg: schema[model].fields[field])
1067
- *
1068
- * If it's still unclear what this does:
1069
- *
1070
- * 1. User can define a custom fieldName.
1071
- * 2. When using a custom fieldName, doing something like `schema[model].fields[field]` will not work.
1072
- */
1073
- const getDefaultFieldName = ({ field, model: unsafeModel }) => {
1074
- if (field === "id" || field === "_id") return "id";
1075
- const model = getDefaultModelName(unsafeModel);
1076
- let f = schema[model]?.fields[field];
1077
- if (!f) {
1078
- const result = Object.entries(schema[model].fields).find(([_, f]) => f.fieldName === field);
1079
- if (result) {
1080
- f = result[1];
1081
- field = result[0];
1082
- }
1083
- }
1084
- if (!f) throw new BetterAuthError(`Field ${field} not found in model ${model}`);
1085
- return field;
1086
- };
1087
- return getDefaultFieldName;
1088
- };
1089
- //#endregion
1090
- //#region ../../node_modules/.pnpm/@better-auth+core@1.7.1_@better-auth+utils@0.4.2_@better-fetch+fetch@1.3.1_@cloudflare+_3ccc4a54cbe47500af416b558bca94b7/node_modules/@better-auth/core/dist/db/adapter/get-id-field.mjs
1091
- var initGetIdField = ({ usePlural, schema, disableIdGeneration, options, customIdGenerator, supportsUUIDs }) => {
1092
- const getDefaultModelName = initGetDefaultModelName({
1093
- usePlural,
1094
- schema
1095
- });
1096
- const idField = ({ customModelName, forceAllowId }) => {
1097
- const useNumberId = options.advanced?.database?.generateId === "serial";
1098
- const useUUIDs = options.advanced?.database?.generateId === "uuid";
1099
- const shouldGenerateId = (() => {
1100
- if (disableIdGeneration) return false;
1101
- else if (useNumberId && !forceAllowId) return false;
1102
- else if (useUUIDs) return !supportsUUIDs;
1103
- else return true;
1104
- })();
1105
- const model = getDefaultModelName(customModelName ?? "id");
1106
- return {
1107
- type: useNumberId ? "number" : "string",
1108
- required: shouldGenerateId ? true : false,
1109
- ...shouldGenerateId ? { defaultValue() {
1110
- if (disableIdGeneration) return void 0;
1111
- const generateId$1 = options.advanced?.database?.generateId;
1112
- if (generateId$1 === false || generateId$1 === "serial") return void 0;
1113
- if (typeof generateId$1 === "function") return generateId$1({ model });
1114
- if (generateId$1 === "uuid") return crypto.randomUUID();
1115
- if (customIdGenerator) return customIdGenerator({ model });
1116
- return generateId();
1117
- } } : {},
1118
- transform: {
1119
- input: (value) => {
1120
- if (!value) return void 0;
1121
- if (useNumberId) {
1122
- const numberValue = Number(value);
1123
- if (isNaN(numberValue)) return;
1124
- return numberValue;
1125
- }
1126
- if (useUUIDs) {
1127
- if (shouldGenerateId && !forceAllowId) return value;
1128
- if (disableIdGeneration) return void 0;
1129
- if (forceAllowId && typeof value === "string") if (/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)) return value;
1130
- else {
1131
- const stack = (/* @__PURE__ */ new Error()).stack?.split("\n").filter((_, i) => i !== 1).join("\n").replace("Error:", "");
1132
- logger.warn("[Adapter Factory] - Invalid UUID value for field `id` provided when `forceAllowId` is true. Generating a new UUID.", stack);
1133
- }
1134
- if (supportsUUIDs) return void 0;
1135
- if (typeof value !== "string" && !supportsUUIDs) return crypto.randomUUID();
1136
- return;
1137
- }
1138
- return value;
1139
- },
1140
- output: (value) => {
1141
- if (!value) return void 0;
1142
- return String(value);
1143
- }
1144
- }
1145
- };
1146
- };
1147
- return idField;
1148
- };
1149
- //#endregion
1150
- //#region ../../node_modules/.pnpm/@better-auth+core@1.7.1_@better-auth+utils@0.4.2_@better-fetch+fetch@1.3.1_@cloudflare+_3ccc4a54cbe47500af416b558bca94b7/node_modules/@better-auth/core/dist/db/adapter/get-field-attributes.mjs
1151
- var initGetFieldAttributes = ({ usePlural, schema, options, customIdGenerator, disableIdGeneration }) => {
1152
- const getDefaultModelName = initGetDefaultModelName({
1153
- usePlural,
1154
- schema
1155
- });
1156
- const getDefaultFieldName = initGetDefaultFieldName({
1157
- usePlural,
1158
- schema
1159
- });
1160
- const idField = initGetIdField({
1161
- usePlural,
1162
- schema,
1163
- options,
1164
- customIdGenerator,
1165
- disableIdGeneration
1166
- });
1167
- const getFieldAttributes = ({ model, field }) => {
1168
- const defaultModelName = getDefaultModelName(model);
1169
- const defaultFieldName = getDefaultFieldName({
1170
- field,
1171
- model: defaultModelName
1172
- });
1173
- const fields = schema[defaultModelName].fields;
1174
- fields.id = idField({ customModelName: defaultModelName });
1175
- const fieldAttributes = fields[defaultFieldName];
1176
- if (!fieldAttributes) throw new BetterAuthError(`Field ${field} not found in model ${model}`);
1177
- return fieldAttributes;
1178
- };
1179
- return getFieldAttributes;
1180
- };
1181
- //#endregion
1182
- //#region ../../node_modules/.pnpm/@better-auth+core@1.7.1_@better-auth+utils@0.4.2_@better-fetch+fetch@1.3.1_@cloudflare+_3ccc4a54cbe47500af416b558bca94b7/node_modules/@better-auth/core/dist/db/adapter/get-field-name.mjs
1183
- var initGetFieldName = ({ schema, usePlural }) => {
1184
- const getDefaultModelName = initGetDefaultModelName({
1185
- schema,
1186
- usePlural
1187
- });
1188
- const getDefaultFieldName = initGetDefaultFieldName({
1189
- schema,
1190
- usePlural
1191
- });
1192
- /**
1193
- * Get the field name which is expected to be saved in the database based on the user's schema.
1194
- *
1195
- * This function is useful if you need to save the field name to the database.
1196
- *
1197
- * For example, if the user has defined a custom field name for the `user` model, then you can use this function to get the actual field name from the schema.
1198
- */
1199
- function getFieldName({ model: modelName, field: fieldName }) {
1200
- const model = getDefaultModelName(modelName);
1201
- const field = getDefaultFieldName({
1202
- model,
1203
- field: fieldName
1204
- });
1205
- return schema[model]?.fields[field]?.fieldName || field;
1206
- }
1207
- return getFieldName;
1208
- };
1209
- //#endregion
1210
- //#region ../../node_modules/.pnpm/@better-auth+core@1.7.1_@better-auth+utils@0.4.2_@better-fetch+fetch@1.3.1_@cloudflare+_3ccc4a54cbe47500af416b558bca94b7/node_modules/@better-auth/core/dist/db/adapter/get-model-name.mjs
1211
- var initGetModelName = ({ usePlural, schema }) => {
1212
- const getDefaultModelName = initGetDefaultModelName({
1213
- schema,
1214
- usePlural
1215
- });
1216
- /**
1217
- * Users can overwrite the default model of some tables. This function helps find the correct model name.
1218
- * Furthermore, if the user passes `usePlural` as true in their adapter config,
1219
- * then we should return the model name ending with an `s`.
1220
- */
1221
- const getModelName = (model) => {
1222
- const defaultModelKey = getDefaultModelName(model);
1223
- if (schema && schema[defaultModelKey] && schema[defaultModelKey].modelName !== model) return usePlural ? `${schema[defaultModelKey].modelName}s` : schema[defaultModelKey].modelName;
1224
- return usePlural ? `${model}s` : model;
1225
- };
1226
- return getModelName;
1227
- };
1228
- //#endregion
1229
- //#region ../../node_modules/.pnpm/@better-auth+core@1.7.1_@better-auth+utils@0.4.2_@better-fetch+fetch@1.3.1_@cloudflare+_3ccc4a54cbe47500af416b558bca94b7/node_modules/@better-auth/core/dist/db/adapter/utils.mjs
1230
- function withApplyDefault(value, field, action) {
1231
- if (action === "update") {
1232
- if (value === void 0 && field.onUpdate !== void 0) {
1233
- if (typeof field.onUpdate === "function") return field.onUpdate();
1234
- return field.onUpdate;
1235
- }
1236
- return value;
1237
- }
1238
- if (action === "create") {
1239
- if (value === void 0 || field.required === true && value === null) {
1240
- if (field.defaultValue !== void 0) {
1241
- if (typeof field.defaultValue === "function") return field.defaultValue();
1242
- return field.defaultValue;
1243
- }
1244
- }
1245
- }
1246
- return value;
1247
- }
1248
- //#endregion
1249
- //#region ../../node_modules/.pnpm/@better-auth+core@1.7.1_@better-auth+utils@0.4.2_@better-fetch+fetch@1.3.1_@cloudflare+_3ccc4a54cbe47500af416b558bca94b7/node_modules/@better-auth/core/dist/db/adapter/factory.mjs
1250
- var debugLogs = [];
1251
- var transactionId = -1;
1252
- var createAsIsTransaction = (adapter) => (fn) => fn(adapter);
1253
- var createAdapterFactory = ({ adapter: customAdapter, config: cfg }) => (options) => {
1254
- const uniqueAdapterFactoryInstanceId = Math.random().toString(36).substring(2, 15);
1255
- const config = {
1256
- ...cfg,
1257
- supportsBooleans: cfg.supportsBooleans ?? true,
1258
- supportsDates: cfg.supportsDates ?? true,
1259
- supportsJSON: cfg.supportsJSON ?? false,
1260
- adapterName: cfg.adapterName ?? cfg.adapterId,
1261
- supportsNumericIds: cfg.supportsNumericIds ?? true,
1262
- supportsUUIDs: cfg.supportsUUIDs ?? false,
1263
- supportsArrays: cfg.supportsArrays ?? false,
1264
- transaction: cfg.transaction ?? false,
1265
- disableTransformInput: cfg.disableTransformInput ?? false,
1266
- disableTransformOutput: cfg.disableTransformOutput ?? false,
1267
- disableTransformJoin: cfg.disableTransformJoin ?? false
1268
- };
1269
- if (options.advanced?.database?.generateId === "serial" && config.supportsNumericIds === false) throw new BetterAuthError(`[${config.adapterName}] Your database or database adapter does not support numeric ids. Please disable "useNumberId" in your config.`);
1270
- const schema = getAuthTables(options);
1271
- const debugLog = (...args) => {
1272
- if (config.debugLogs === true || typeof config.debugLogs === "object") {
1273
- const logger = createLogger({ level: "info" });
1274
- if (typeof config.debugLogs === "object" && "isRunningAdapterTests" in config.debugLogs) {
1275
- if (config.debugLogs.isRunningAdapterTests) {
1276
- args.shift();
1277
- debugLogs.push({
1278
- instance: uniqueAdapterFactoryInstanceId,
1279
- args
1280
- });
1281
- }
1282
- return;
1283
- }
1284
- if (typeof config.debugLogs === "object" && config.debugLogs.logCondition && !config.debugLogs.logCondition?.()) return;
1285
- if (typeof args[0] === "object" && "method" in args[0]) {
1286
- const method = args.shift().method;
1287
- if (typeof config.debugLogs === "object") {
1288
- if (method === "create" && !config.debugLogs.create) return;
1289
- else if (method === "update" && !config.debugLogs.update) return;
1290
- else if (method === "updateMany" && !config.debugLogs.updateMany) return;
1291
- else if (method === "findOne" && !config.debugLogs.findOne) return;
1292
- else if (method === "findMany" && !config.debugLogs.findMany) return;
1293
- else if (method === "delete" && !config.debugLogs.delete) return;
1294
- else if (method === "deleteMany" && !config.debugLogs.deleteMany) return;
1295
- else if (method === "consumeOne" && !config.debugLogs.consumeOne) return;
1296
- else if (method === "incrementOne" && !config.debugLogs.incrementOne) return;
1297
- else if (method === "count" && !config.debugLogs.count) return;
1298
- }
1299
- logger.info(`[${config.adapterName}]`, ...args);
1300
- } else logger.info(`[${config.adapterName}]`, ...args);
1301
- }
1302
- };
1303
- const logger = createLogger(options.logger);
1304
- const getDefaultModelName = initGetDefaultModelName({
1305
- usePlural: config.usePlural,
1306
- schema
1307
- });
1308
- const getDefaultFieldName = initGetDefaultFieldName({
1309
- usePlural: config.usePlural,
1310
- schema
1311
- });
1312
- const getModelName = initGetModelName({
1313
- usePlural: config.usePlural,
1314
- schema
1315
- });
1316
- const getFieldName = initGetFieldName({
1317
- schema,
1318
- usePlural: config.usePlural
1319
- });
1320
- const idField = initGetIdField({
1321
- schema,
1322
- options,
1323
- usePlural: config.usePlural,
1324
- disableIdGeneration: config.disableIdGeneration,
1325
- customIdGenerator: config.customIdGenerator,
1326
- supportsUUIDs: config.supportsUUIDs
1327
- });
1328
- const getFieldAttributes = initGetFieldAttributes({
1329
- schema,
1330
- options,
1331
- usePlural: config.usePlural,
1332
- disableIdGeneration: config.disableIdGeneration,
1333
- customIdGenerator: config.customIdGenerator
1334
- });
1335
- const transformInput = async (data, defaultModelName, action, forceAllowId) => {
1336
- const transformedData = {};
1337
- const fields = schema[defaultModelName].fields;
1338
- const newMappedKeys = config.mapKeysTransformInput ?? {};
1339
- const useNumberId = options.advanced?.database?.generateId === "serial";
1340
- fields.id = idField({
1341
- customModelName: defaultModelName,
1342
- forceAllowId: forceAllowId && "id" in data
1343
- });
1344
- for (const field in fields) {
1345
- let value = data[field];
1346
- const fieldAttributes = fields[field];
1347
- const newFieldName = newMappedKeys[field] || fields[field].fieldName || field;
1348
- if (value === void 0 && (fieldAttributes.defaultValue === void 0 && !fieldAttributes.transform?.input && !(action === "update" && fieldAttributes.onUpdate) || action === "update" && !fieldAttributes.onUpdate)) continue;
1349
- if (fieldAttributes && fieldAttributes.type === "date" && !(value instanceof Date) && typeof value === "string") try {
1350
- value = new Date(value);
1351
- } catch {
1352
- logger.error("[Adapter Factory] Failed to convert string to date", {
1353
- value,
1354
- field
1355
- });
1356
- }
1357
- let newValue = withApplyDefault(value, fieldAttributes, action);
1358
- if (fieldAttributes.transform?.input) newValue = await fieldAttributes.transform.input(newValue);
1359
- if (fieldAttributes.references?.field === "id" && useNumberId) if (Array.isArray(newValue)) newValue = newValue.map((x) => x !== null ? Number(x) : null);
1360
- else newValue = newValue !== null ? Number(newValue) : null;
1361
- else if (config.supportsJSON === false && typeof newValue === "object" && fieldAttributes.type === "json") newValue = JSON.stringify(newValue);
1362
- else if (config.supportsArrays === false && Array.isArray(newValue) && (fieldAttributes.type === "string[]" || fieldAttributes.type === "number[]")) newValue = JSON.stringify(newValue);
1363
- else if (config.supportsDates === false && newValue instanceof Date && fieldAttributes.type === "date") newValue = newValue.toISOString();
1364
- else if (config.supportsBooleans === false && typeof newValue === "boolean") newValue = newValue ? 1 : 0;
1365
- if (config.customTransformInput) newValue = config.customTransformInput({
1366
- data: newValue,
1367
- action,
1368
- field: newFieldName,
1369
- fieldAttributes,
1370
- model: getModelName(defaultModelName),
1371
- schema,
1372
- options
1373
- });
1374
- if (newValue !== void 0) transformedData[newFieldName] = newValue;
1375
- }
1376
- return transformedData;
1377
- };
1378
- const transformOutput = async (data, unsafe_model, select = [], join) => {
1379
- const transformSingleOutput = async (data, unsafe_model, select = []) => {
1380
- if (!data) return null;
1381
- const newMappedKeys = config.mapKeysTransformOutput ?? {};
1382
- const transformedData = {};
1383
- const tableSchema = schema[getDefaultModelName(unsafe_model)].fields;
1384
- const idKey = Object.entries(newMappedKeys).find(([_, v]) => v === "id")?.[0];
1385
- tableSchema[idKey ?? "id"] = { type: options.advanced?.database?.generateId === "serial" ? "number" : "string" };
1386
- for (const key in tableSchema) {
1387
- if (select.length && !select.includes(key)) continue;
1388
- const field = tableSchema[key];
1389
- if (field) {
1390
- const originalKey = field.fieldName || key;
1391
- let newValue = data[Object.entries(newMappedKeys).find(([_, v]) => v === originalKey)?.[0] || originalKey];
1392
- if (field.transform?.output) newValue = await field.transform.output(newValue);
1393
- const newFieldName = newMappedKeys[key] || key;
1394
- if (originalKey === "id" || field.references?.field === "id") {
1395
- if (typeof newValue !== "undefined" && newValue !== null) newValue = String(newValue);
1396
- } else if (config.supportsJSON === false && typeof newValue === "string" && field.type === "json") newValue = safeJSONParse(newValue);
1397
- else if (config.supportsArrays === false && typeof newValue === "string" && (field.type === "string[]" || field.type === "number[]")) newValue = safeJSONParse(newValue);
1398
- else if (config.supportsDates === false && typeof newValue === "string" && field.type === "date") newValue = new Date(newValue);
1399
- else if (config.supportsBooleans === false && typeof newValue === "number" && field.type === "boolean") newValue = newValue === 1;
1400
- if (config.customTransformOutput) newValue = config.customTransformOutput({
1401
- data: newValue,
1402
- field: newFieldName,
1403
- fieldAttributes: field,
1404
- select,
1405
- model: getModelName(unsafe_model),
1406
- schema,
1407
- options
1408
- });
1409
- transformedData[newFieldName] = newValue;
1410
- }
1411
- }
1412
- return transformedData;
1413
- };
1414
- if (!join || Object.keys(join).length === 0) return await transformSingleOutput(data, unsafe_model, select);
1415
- unsafe_model = getDefaultModelName(unsafe_model);
1416
- const transformedData = await transformSingleOutput(data, unsafe_model, select);
1417
- const requiredModels = Object.entries(join).map(([model, joinConfig]) => ({
1418
- modelName: getModelName(model),
1419
- defaultModelName: getDefaultModelName(model),
1420
- joinConfig
1421
- }));
1422
- if (!data) return null;
1423
- for (const { modelName, defaultModelName, joinConfig } of requiredModels) {
1424
- let joinedData = await (async () => {
1425
- if (options.advanced?.database?.joins) {
1426
- if (modelName in data) return data[modelName];
1427
- }
1428
- return await handleFallbackJoin({
1429
- baseModel: unsafe_model,
1430
- baseData: transformedData,
1431
- joinModel: modelName,
1432
- specificJoinConfig: joinConfig
1433
- });
1434
- })();
1435
- if (joinedData === void 0 || joinedData === null) joinedData = joinConfig.relation === "one-to-one" ? null : [];
1436
- if (joinConfig.relation === "one-to-many" && !Array.isArray(joinedData)) joinedData = [joinedData];
1437
- const transformed = [];
1438
- if (Array.isArray(joinedData)) for (const item of joinedData) {
1439
- const transformedItem = await transformSingleOutput(item, modelName, []);
1440
- transformed.push(transformedItem);
1441
- }
1442
- else {
1443
- const transformedItem = await transformSingleOutput(joinedData, modelName, []);
1444
- transformed.push(transformedItem);
1445
- }
1446
- transformedData[defaultModelName] = (joinConfig.relation === "one-to-one" ? transformed[0] : transformed) ?? null;
1447
- }
1448
- return transformedData;
1449
- };
1450
- const transformWhereClause = ({ model, where, action }) => {
1451
- if (!where) return void 0;
1452
- const newMappedKeys = config.mapKeysTransformInput ?? {};
1453
- return where.map((w) => {
1454
- const { field: unsafe_field, value, operator = "eq", connector = "AND", mode = "sensitive" } = w;
1455
- if (operator === "in") {
1456
- if (!Array.isArray(value)) throw new BetterAuthError("Value must be an array");
1457
- }
1458
- let newValue = value;
1459
- const defaultModelName = getDefaultModelName(model);
1460
- const defaultFieldName = getDefaultFieldName({
1461
- field: unsafe_field,
1462
- model
1463
- });
1464
- const fieldName = newMappedKeys[defaultFieldName] || getFieldName({
1465
- field: defaultFieldName,
1466
- model: defaultModelName
1467
- });
1468
- const fieldAttr = getFieldAttributes({
1469
- field: defaultFieldName,
1470
- model: defaultModelName
1471
- });
1472
- const useNumberId = options.advanced?.database?.generateId === "serial";
1473
- if (defaultFieldName === "id" || fieldAttr.references?.field === "id") {
1474
- if (useNumberId) if (Array.isArray(value)) newValue = value.map(Number);
1475
- else newValue = Number(value);
1476
- }
1477
- if (fieldAttr.type === "date" && value instanceof Date && !config.supportsDates) newValue = value.toISOString();
1478
- if (fieldAttr.type === "boolean" && typeof newValue === "string") newValue = newValue === "true";
1479
- if (fieldAttr.type === "number") {
1480
- if (typeof newValue === "string" && newValue.trim() !== "") {
1481
- const parsed = Number(newValue);
1482
- if (!Number.isNaN(parsed)) newValue = parsed;
1483
- } else if (Array.isArray(newValue)) {
1484
- const parsed = newValue.map((v) => typeof v === "string" && v.trim() !== "" ? Number(v) : NaN);
1485
- if (parsed.every((n) => !Number.isNaN(n))) newValue = parsed;
1486
- }
1487
- }
1488
- if (fieldAttr.type === "boolean" && typeof newValue === "boolean" && !config.supportsBooleans) newValue = newValue ? 1 : 0;
1489
- if (fieldAttr.type === "json" && typeof value === "object" && !config.supportsJSON) try {
1490
- newValue = JSON.stringify(value);
1491
- } catch (error) {
1492
- throw new Error(`Failed to stringify JSON value for field ${fieldName}`, { cause: error });
1493
- }
1494
- if (config.customTransformInput) newValue = config.customTransformInput({
1495
- data: newValue,
1496
- fieldAttributes: fieldAttr,
1497
- field: fieldName,
1498
- model: getModelName(model),
1499
- schema,
1500
- options,
1501
- action
1502
- });
1503
- return {
1504
- operator,
1505
- connector,
1506
- field: fieldName,
1507
- value: newValue,
1508
- mode
1509
- };
1510
- });
1511
- };
1512
- const transformJoinClause = (baseModel, unsanitizedJoin, select) => {
1513
- if (!unsanitizedJoin) return void 0;
1514
- if (Object.keys(unsanitizedJoin).length === 0) return void 0;
1515
- const transformedJoin = {};
1516
- for (const [model, join] of Object.entries(unsanitizedJoin)) {
1517
- if (!join) continue;
1518
- const defaultModelName = getDefaultModelName(model);
1519
- const defaultBaseModelName = getDefaultModelName(baseModel);
1520
- let foreignKeys = Object.entries(schema[defaultModelName].fields).filter(([field, fieldAttributes]) => fieldAttributes.references && getDefaultModelName(fieldAttributes.references.model) === defaultBaseModelName);
1521
- let isForwardJoin = true;
1522
- if (!foreignKeys.length) {
1523
- foreignKeys = Object.entries(schema[defaultBaseModelName].fields).filter(([field, fieldAttributes]) => fieldAttributes.references && getDefaultModelName(fieldAttributes.references.model) === defaultModelName);
1524
- isForwardJoin = false;
1525
- }
1526
- if (!foreignKeys.length) throw new BetterAuthError(`No foreign key found for model ${model} and base model ${baseModel} while performing join operation.`);
1527
- else if (foreignKeys.length > 1) throw new BetterAuthError(`Multiple foreign keys found for model ${model} and base model ${baseModel} while performing join operation. Only one foreign key is supported.`);
1528
- const [foreignKey, foreignKeyAttributes] = foreignKeys[0];
1529
- if (!foreignKeyAttributes.references) throw new BetterAuthError(`No references found for foreign key ${foreignKey} on model ${model} while performing join operation.`);
1530
- let from;
1531
- let to;
1532
- let requiredSelectField;
1533
- if (isForwardJoin) {
1534
- requiredSelectField = foreignKeyAttributes.references.field;
1535
- from = getFieldName({
1536
- model: baseModel,
1537
- field: requiredSelectField
1538
- });
1539
- to = getFieldName({
1540
- model,
1541
- field: foreignKey
1542
- });
1543
- } else {
1544
- requiredSelectField = foreignKey;
1545
- from = getFieldName({
1546
- model: baseModel,
1547
- field: requiredSelectField
1548
- });
1549
- to = getFieldName({
1550
- model,
1551
- field: foreignKeyAttributes.references.field
1552
- });
1553
- }
1554
- if (select && !select.includes(requiredSelectField)) select.push(requiredSelectField);
1555
- const isUnique = to === "id" ? true : foreignKeyAttributes.unique ?? false;
1556
- let limit = options.advanced?.database?.defaultFindManyLimit ?? 100;
1557
- if (isUnique) limit = 1;
1558
- else if (typeof join === "object" && typeof join.limit === "number") limit = join.limit;
1559
- transformedJoin[getModelName(model)] = {
1560
- on: {
1561
- from,
1562
- to
1563
- },
1564
- limit,
1565
- relation: isUnique ? "one-to-one" : "one-to-many"
1566
- };
1567
- }
1568
- return {
1569
- join: transformedJoin,
1570
- select
1571
- };
1572
- };
1573
- /**
1574
- * Handle joins by making separate queries and combining results (fallback for adapters that don't support native joins).
1575
- */
1576
- const handleFallbackJoin = async ({ baseModel, baseData, joinModel, specificJoinConfig: joinConfig }) => {
1577
- if (!baseData) return baseData;
1578
- const modelName = getModelName(joinModel);
1579
- const field = joinConfig.on.to;
1580
- const value = baseData[getDefaultFieldName({
1581
- field: joinConfig.on.from,
1582
- model: baseModel
1583
- })];
1584
- if (value === null || value === void 0) return joinConfig.relation === "one-to-one" ? null : [];
1585
- let result;
1586
- const where = transformWhereClause({
1587
- model: modelName,
1588
- where: [{
1589
- field,
1590
- value,
1591
- operator: "eq",
1592
- connector: "AND"
1593
- }],
1594
- action: "findOne"
1595
- });
1596
- try {
1597
- if (joinConfig.relation === "one-to-one") result = await withSpan(`db findOne ${modelName}`, {
1598
- [ATTR_DB_OPERATION_NAME]: "findOne",
1599
- [ATTR_DB_COLLECTION_NAME]: modelName
1600
- }, () => adapterInstance.findOne({
1601
- model: modelName,
1602
- where
1603
- }));
1604
- else {
1605
- const limit = joinConfig.limit ?? options.advanced?.database?.defaultFindManyLimit ?? 100;
1606
- result = await withSpan(`db findMany ${modelName}`, {
1607
- [ATTR_DB_OPERATION_NAME]: "findMany",
1608
- [ATTR_DB_COLLECTION_NAME]: modelName
1609
- }, () => adapterInstance.findMany({
1610
- model: modelName,
1611
- where,
1612
- limit
1613
- }));
1614
- }
1615
- } catch (error) {
1616
- logger.error(`Failed to query fallback join for model ${modelName}:`, {
1617
- where,
1618
- limit: joinConfig.limit
1619
- });
1620
- console.error(error);
1621
- throw error;
1622
- }
1623
- return result;
1624
- };
1625
- const adapterInstance = customAdapter({
1626
- options,
1627
- schema,
1628
- debugLog,
1629
- getFieldName,
1630
- getModelName,
1631
- getDefaultModelName,
1632
- getDefaultFieldName,
1633
- getFieldAttributes,
1634
- transformInput,
1635
- transformOutput,
1636
- transformWhereClause
1637
- });
1638
- let lazyLoadTransaction = null;
1639
- const adapter = {
1640
- transaction: async (cb) => {
1641
- if (!lazyLoadTransaction) if (!config.transaction) lazyLoadTransaction = createAsIsTransaction(adapter);
1642
- else {
1643
- logger.debug(`[${config.adapterName}] - Using provided transaction implementation.`);
1644
- lazyLoadTransaction = config.transaction;
1645
- }
1646
- return lazyLoadTransaction(cb);
1647
- },
1648
- create: async ({ data: unsafeData, model: unsafeModel, select, forceAllowId = false }) => {
1649
- transactionId++;
1650
- const thisTransactionId = transactionId;
1651
- const model = getModelName(unsafeModel);
1652
- unsafeModel = getDefaultModelName(unsafeModel);
1653
- if ("id" in unsafeData && typeof unsafeData.id !== "undefined" && !forceAllowId) {
1654
- logger.warn(`[${config.adapterName}] - You are trying to create a record with an id. This is not allowed as we handle id generation for you, unless you pass in the \`forceAllowId\` parameter. The id will be ignored.`);
1655
- const stack = (/* @__PURE__ */ new Error()).stack?.split("\n").filter((_, i) => i !== 1).join("\n").replace("Error:", "Create method with `id` being called at:");
1656
- console.log(stack);
1657
- unsafeData.id = void 0;
1658
- }
1659
- debugLog({ method: "create" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 4)}`, `${formatMethod("create")} ${formatAction("Unsafe Input")}:`, {
1660
- model,
1661
- data: unsafeData
1662
- });
1663
- let data = unsafeData;
1664
- if (!config.disableTransformInput) data = await transformInput(unsafeData, unsafeModel, "create", forceAllowId);
1665
- debugLog({ method: "create" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 4)}`, `${formatMethod("create")} ${formatAction("Parsed Input")}:`, {
1666
- model,
1667
- data
1668
- });
1669
- const res = await withSpan(`db create ${model}`, {
1670
- [ATTR_DB_OPERATION_NAME]: "create",
1671
- [ATTR_DB_COLLECTION_NAME]: model
1672
- }, () => adapterInstance.create({
1673
- data,
1674
- model
1675
- }));
1676
- debugLog({ method: "create" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 4)}`, `${formatMethod("create")} ${formatAction("DB Result")}:`, {
1677
- model,
1678
- res
1679
- });
1680
- let transformed = res;
1681
- if (!config.disableTransformOutput) transformed = await transformOutput(res, unsafeModel, select, void 0);
1682
- debugLog({ method: "create" }, `${formatTransactionId(thisTransactionId)} ${formatStep(4, 4)}`, `${formatMethod("create")} ${formatAction("Parsed Result")}:`, {
1683
- model,
1684
- data: transformed
1685
- });
1686
- return transformed;
1687
- },
1688
- update: async ({ model: unsafeModel, where: unsafeWhere, update: unsafeData }) => {
1689
- transactionId++;
1690
- const thisTransactionId = transactionId;
1691
- unsafeModel = getDefaultModelName(unsafeModel);
1692
- const model = getModelName(unsafeModel);
1693
- const where = transformWhereClause({
1694
- model: unsafeModel,
1695
- where: unsafeWhere,
1696
- action: "update"
1697
- });
1698
- if (where.length === 0) return null;
1699
- debugLog({ method: "update" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 4)}`, `${formatMethod("update")} ${formatAction("Unsafe Input")}:`, {
1700
- model,
1701
- data: unsafeData
1702
- });
1703
- let data = unsafeData;
1704
- if (!config.disableTransformInput) data = await transformInput(unsafeData, unsafeModel, "update");
1705
- debugLog({ method: "update" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 4)}`, `${formatMethod("update")} ${formatAction("Parsed Input")}:`, {
1706
- model,
1707
- data
1708
- });
1709
- const res = await withSpan(`db update ${model}`, {
1710
- [ATTR_DB_OPERATION_NAME]: "update",
1711
- [ATTR_DB_COLLECTION_NAME]: model
1712
- }, () => adapterInstance.update({
1713
- model,
1714
- where,
1715
- update: data
1716
- }));
1717
- debugLog({ method: "update" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 4)}`, `${formatMethod("update")} ${formatAction("DB Result")}:`, {
1718
- model,
1719
- data: res
1720
- });
1721
- let transformed = res;
1722
- if (!config.disableTransformOutput) transformed = await transformOutput(res, unsafeModel, void 0, void 0);
1723
- debugLog({ method: "update" }, `${formatTransactionId(thisTransactionId)} ${formatStep(4, 4)}`, `${formatMethod("update")} ${formatAction("Parsed Result")}:`, {
1724
- model,
1725
- data: transformed
1726
- });
1727
- return transformed;
1728
- },
1729
- updateMany: async ({ model: unsafeModel, where: unsafeWhere, update: unsafeData }) => {
1730
- transactionId++;
1731
- const thisTransactionId = transactionId;
1732
- const model = getModelName(unsafeModel);
1733
- const where = transformWhereClause({
1734
- model: unsafeModel,
1735
- where: unsafeWhere,
1736
- action: "updateMany"
1737
- });
1738
- unsafeModel = getDefaultModelName(unsafeModel);
1739
- debugLog({ method: "updateMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 4)}`, `${formatMethod("updateMany")} ${formatAction("Unsafe Input")}:`, {
1740
- model,
1741
- data: unsafeData
1742
- });
1743
- let data = unsafeData;
1744
- if (!config.disableTransformInput) data = await transformInput(unsafeData, unsafeModel, "update");
1745
- debugLog({ method: "updateMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 4)}`, `${formatMethod("updateMany")} ${formatAction("Parsed Input")}:`, {
1746
- model,
1747
- data
1748
- });
1749
- const updatedCount = await withSpan(`db updateMany ${model}`, {
1750
- [ATTR_DB_OPERATION_NAME]: "updateMany",
1751
- [ATTR_DB_COLLECTION_NAME]: model
1752
- }, () => adapterInstance.updateMany({
1753
- model,
1754
- where,
1755
- update: data
1756
- }));
1757
- if (typeof updatedCount !== "number" || !Number.isFinite(updatedCount)) throw new BetterAuthError(`Adapter "${config.adapterId}" updateMany must return a finite number affected row count.`);
1758
- debugLog({ method: "updateMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 4)}`, `${formatMethod("updateMany")} ${formatAction("DB Result")}:`, {
1759
- model,
1760
- data: updatedCount
1761
- });
1762
- debugLog({ method: "updateMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(4, 4)}`, `${formatMethod("updateMany")} ${formatAction("Parsed Result")}:`, {
1763
- model,
1764
- data: updatedCount
1765
- });
1766
- return updatedCount;
1767
- },
1768
- findOne: async ({ model: unsafeModel, where: unsafeWhere, select, join: unsafeJoin }) => {
1769
- transactionId++;
1770
- const thisTransactionId = transactionId;
1771
- const model = getModelName(unsafeModel);
1772
- const where = transformWhereClause({
1773
- model: unsafeModel,
1774
- where: unsafeWhere,
1775
- action: "findOne"
1776
- });
1777
- unsafeModel = getDefaultModelName(unsafeModel);
1778
- let join;
1779
- let passJoinToAdapter = true;
1780
- if (!config.disableTransformJoin) {
1781
- const result = transformJoinClause(unsafeModel, unsafeJoin, select);
1782
- if (result) {
1783
- join = result.join;
1784
- select = result.select;
1785
- }
1786
- if (!options.advanced?.database?.joins && join && Object.keys(join).length > 0) passJoinToAdapter = false;
1787
- } else join = unsafeJoin;
1788
- debugLog({ method: "findOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 3)}`, `${formatMethod("findOne")}:`, {
1789
- model,
1790
- where,
1791
- select,
1792
- join
1793
- });
1794
- const res = await withSpan(`db findOne ${model}`, {
1795
- [ATTR_DB_OPERATION_NAME]: "findOne",
1796
- [ATTR_DB_COLLECTION_NAME]: model
1797
- }, () => adapterInstance.findOne({
1798
- model,
1799
- where,
1800
- select,
1801
- join: passJoinToAdapter ? join : void 0
1802
- }));
1803
- debugLog({ method: "findOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 3)}`, `${formatMethod("findOne")} ${formatAction("DB Result")}:`, {
1804
- model,
1805
- data: res
1806
- });
1807
- let transformed = res;
1808
- if (!config.disableTransformOutput) transformed = await transformOutput(res, unsafeModel, select, join);
1809
- debugLog({ method: "findOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 3)}`, `${formatMethod("findOne")} ${formatAction("Parsed Result")}:`, {
1810
- model,
1811
- data: transformed
1812
- });
1813
- return transformed;
1814
- },
1815
- findMany: async ({ model: unsafeModel, where: unsafeWhere, limit: unsafeLimit, select, sortBy, offset, join: unsafeJoin }) => {
1816
- transactionId++;
1817
- const thisTransactionId = transactionId;
1818
- const limit = unsafeLimit ?? options.advanced?.database?.defaultFindManyLimit ?? 100;
1819
- const model = getModelName(unsafeModel);
1820
- const where = transformWhereClause({
1821
- model: unsafeModel,
1822
- where: unsafeWhere,
1823
- action: "findMany"
1824
- });
1825
- unsafeModel = getDefaultModelName(unsafeModel);
1826
- let join;
1827
- let passJoinToAdapter = true;
1828
- if (!config.disableTransformJoin) {
1829
- const result = transformJoinClause(unsafeModel, unsafeJoin, select);
1830
- if (result) {
1831
- join = result.join;
1832
- select = result.select;
1833
- }
1834
- if (!options.advanced?.database?.joins && join && Object.keys(join).length > 0) passJoinToAdapter = false;
1835
- } else join = unsafeJoin;
1836
- debugLog({ method: "findMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 3)}`, `${formatMethod("findMany")}:`, {
1837
- model,
1838
- where,
1839
- limit,
1840
- sortBy,
1841
- offset,
1842
- join
1843
- });
1844
- const res = await withSpan(`db findMany ${model}`, {
1845
- [ATTR_DB_OPERATION_NAME]: "findMany",
1846
- [ATTR_DB_COLLECTION_NAME]: model
1847
- }, () => adapterInstance.findMany({
1848
- model,
1849
- where,
1850
- limit,
1851
- select,
1852
- sortBy,
1853
- offset,
1854
- join: passJoinToAdapter ? join : void 0
1855
- }));
1856
- debugLog({ method: "findMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 3)}`, `${formatMethod("findMany")} ${formatAction("DB Result")}:`, {
1857
- model,
1858
- data: res
1859
- });
1860
- let transformed = res;
1861
- if (!config.disableTransformOutput) transformed = await Promise.all(res.map(async (r) => {
1862
- return await transformOutput(r, unsafeModel, void 0, join);
1863
- }));
1864
- debugLog({ method: "findMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 3)}`, `${formatMethod("findMany")} ${formatAction("Parsed Result")}:`, {
1865
- model,
1866
- data: transformed
1867
- });
1868
- return transformed;
1869
- },
1870
- delete: async ({ model: unsafeModel, where: unsafeWhere }) => {
1871
- transactionId++;
1872
- const thisTransactionId = transactionId;
1873
- const model = getModelName(unsafeModel);
1874
- const where = transformWhereClause({
1875
- model: unsafeModel,
1876
- where: unsafeWhere,
1877
- action: "delete"
1878
- });
1879
- unsafeModel = getDefaultModelName(unsafeModel);
1880
- debugLog({ method: "delete" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 2)}`, `${formatMethod("delete")}:`, {
1881
- model,
1882
- where
1883
- });
1884
- await withSpan(`db delete ${model}`, {
1885
- [ATTR_DB_OPERATION_NAME]: "delete",
1886
- [ATTR_DB_COLLECTION_NAME]: model
1887
- }, () => adapterInstance.delete({
1888
- model,
1889
- where
1890
- }));
1891
- debugLog({ method: "delete" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 2)}`, `${formatMethod("delete")} ${formatAction("DB Result")}:`, { model });
1892
- },
1893
- deleteMany: async ({ model: unsafeModel, where: unsafeWhere }) => {
1894
- transactionId++;
1895
- const thisTransactionId = transactionId;
1896
- const model = getModelName(unsafeModel);
1897
- const where = transformWhereClause({
1898
- model: unsafeModel,
1899
- where: unsafeWhere,
1900
- action: "deleteMany"
1901
- });
1902
- unsafeModel = getDefaultModelName(unsafeModel);
1903
- debugLog({ method: "deleteMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 2)}`, `${formatMethod("deleteMany")} ${formatAction("DeleteMany")}:`, {
1904
- model,
1905
- where
1906
- });
1907
- const res = await withSpan(`db deleteMany ${model}`, {
1908
- [ATTR_DB_OPERATION_NAME]: "deleteMany",
1909
- [ATTR_DB_COLLECTION_NAME]: model
1910
- }, () => adapterInstance.deleteMany({
1911
- model,
1912
- where
1913
- }));
1914
- debugLog({ method: "deleteMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 2)}`, `${formatMethod("deleteMany")} ${formatAction("DB Result")}:`, {
1915
- model,
1916
- data: res
1917
- });
1918
- return res;
1919
- },
1920
- consumeOne: async ({ model: unsafeModel, where: unsafeWhere }) => {
1921
- transactionId++;
1922
- const thisTransactionId = transactionId;
1923
- const model = getModelName(unsafeModel);
1924
- const where = transformWhereClause({
1925
- model: unsafeModel,
1926
- where: unsafeWhere,
1927
- action: "consumeOne"
1928
- });
1929
- unsafeModel = getDefaultModelName(unsafeModel);
1930
- debugLog({ method: "consumeOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 3)}`, `${formatMethod("consumeOne")} ${formatAction("ConsumeOne")}:`, {
1931
- model,
1932
- where
1933
- });
1934
- if (typeof adapterInstance.consumeOne !== "function") throw new BetterAuthError(`Adapter "${config.adapterId}" must implement consumeOne for atomic single-use credential consumption.`);
1935
- const res = await withSpan(`db consumeOne ${model}`, {
1936
- [ATTR_DB_OPERATION_NAME]: "consumeOne",
1937
- [ATTR_DB_COLLECTION_NAME]: model
1938
- }, () => adapterInstance.consumeOne({
1939
- model,
1940
- where
1941
- }));
1942
- debugLog({ method: "consumeOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 3)}`, `${formatMethod("consumeOne")} ${formatAction("DB Result")}:`, {
1943
- model,
1944
- data: res
1945
- });
1946
- let transformed = res;
1947
- if (!config.disableTransformOutput && res) transformed = await transformOutput(res, unsafeModel, void 0, void 0);
1948
- debugLog({ method: "consumeOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 3)}`, `${formatMethod("consumeOne")} ${formatAction("Parsed Result")}:`, {
1949
- model,
1950
- data: transformed
1951
- });
1952
- return transformed;
1953
- },
1954
- incrementOne: async ({ model: unsafeModel, where: unsafeWhere, increment: unsafeIncrement, set: unsafeSet }) => {
1955
- const hasIncrement = Object.keys(unsafeIncrement).length > 0;
1956
- const hasSet = !!unsafeSet && Object.keys(unsafeSet).length > 0;
1957
- if (!hasIncrement && !hasSet) throw new BetterAuthError("incrementOne requires a non-empty `increment` or `set`; both were empty.");
1958
- transactionId++;
1959
- const thisTransactionId = transactionId;
1960
- const model = getModelName(unsafeModel);
1961
- const where = transformWhereClause({
1962
- model: unsafeModel,
1963
- where: unsafeWhere,
1964
- action: "incrementOne"
1965
- });
1966
- unsafeModel = getDefaultModelName(unsafeModel);
1967
- debugLog({ method: "incrementOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 3)}`, `${formatMethod("incrementOne")} ${formatAction("IncrementOne")}:`, {
1968
- model,
1969
- where,
1970
- increment: unsafeIncrement,
1971
- set: unsafeSet
1972
- });
1973
- if (typeof adapterInstance.incrementOne !== "function") throw new BetterAuthError(`Adapter "${config.adapterId}" must implement incrementOne for atomic guarded counter updates.`);
1974
- const mappedKeys = config.mapKeysTransformInput ?? {};
1975
- const increment = {};
1976
- for (const [field, delta] of Object.entries(unsafeIncrement)) increment[mappedKeys[field] || getFieldName({
1977
- model: unsafeModel,
1978
- field
1979
- })] = delta;
1980
- let set;
1981
- if (unsafeSet && !config.disableTransformInput) set = await transformInput(unsafeSet, unsafeModel, "update");
1982
- else set = unsafeSet;
1983
- if (Object.keys(increment).length === 0 && (!set || Object.keys(set).length === 0)) throw new BetterAuthError("incrementOne resolved to an empty update: every increment/set field was unknown to the schema or transformed away.");
1984
- const res = await withSpan(`db incrementOne ${model}`, {
1985
- [ATTR_DB_OPERATION_NAME]: "incrementOne",
1986
- [ATTR_DB_COLLECTION_NAME]: model
1987
- }, () => adapterInstance.incrementOne({
1988
- model,
1989
- where,
1990
- increment,
1991
- set
1992
- }));
1993
- debugLog({ method: "incrementOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 3)}`, `${formatMethod("incrementOne")} ${formatAction("DB Result")}:`, {
1994
- model,
1995
- data: res
1996
- });
1997
- let transformed = res;
1998
- if (!config.disableTransformOutput && res) transformed = await transformOutput(res, unsafeModel, void 0, void 0);
1999
- debugLog({ method: "incrementOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 3)}`, `${formatMethod("incrementOne")} ${formatAction("Parsed Result")}:`, {
2000
- model,
2001
- data: transformed
2002
- });
2003
- return transformed;
2004
- },
2005
- count: async ({ model: unsafeModel, where: unsafeWhere }) => {
2006
- transactionId++;
2007
- const thisTransactionId = transactionId;
2008
- const model = getModelName(unsafeModel);
2009
- const where = transformWhereClause({
2010
- model: unsafeModel,
2011
- where: unsafeWhere,
2012
- action: "count"
2013
- });
2014
- unsafeModel = getDefaultModelName(unsafeModel);
2015
- debugLog({ method: "count" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 2)}`, `${formatMethod("count")}:`, {
2016
- model,
2017
- where
2018
- });
2019
- const res = await withSpan(`db count ${model}`, {
2020
- [ATTR_DB_OPERATION_NAME]: "count",
2021
- [ATTR_DB_COLLECTION_NAME]: model
2022
- }, () => adapterInstance.count({
2023
- model,
2024
- where
2025
- }));
2026
- debugLog({ method: "count" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 2)}`, `${formatMethod("count")}:`, {
2027
- model,
2028
- data: res
2029
- });
2030
- return res;
2031
- },
2032
- createSchema: adapterInstance.createSchema ? async (_, file) => {
2033
- const tables = getAuthTables(options);
2034
- if (options.secondaryStorage && !options.session?.storeSessionInDatabase) delete tables.session;
2035
- return adapterInstance.createSchema({
2036
- file,
2037
- tables
2038
- });
2039
- } : void 0,
2040
- options: {
2041
- adapterConfig: config,
2042
- ...adapterInstance.options ?? {}
2043
- },
2044
- id: config.adapterId,
2045
- ...config.debugLogs?.isRunningAdapterTests ? { adapterTestDebugLogs: {
2046
- resetDebugLogs() {
2047
- debugLogs = debugLogs.filter((log) => log.instance !== uniqueAdapterFactoryInstanceId);
2048
- },
2049
- printDebugLogs() {
2050
- const separator = `─`.repeat(80);
2051
- const logs = debugLogs.filter((log) => log.instance === uniqueAdapterFactoryInstanceId);
2052
- if (logs.length === 0) return;
2053
- const log = logs.reverse().map((log) => {
2054
- log.args[0] = `\n${log.args[0]}`;
2055
- return [...log.args, "\n"];
2056
- }).reduce((prev, curr) => {
2057
- return [...curr, ...prev];
2058
- }, [`\n${separator}`]);
2059
- console.log(...log);
2060
- }
2061
- } } : {}
2062
- };
2063
- return adapter;
2064
- };
2065
- function formatTransactionId(transactionId) {
2066
- if (getColorDepth() < 8) return `#${transactionId}`;
2067
- return `${TTY_COLORS.fg.magenta}#${transactionId}${TTY_COLORS.reset}`;
2068
- }
2069
- function formatStep(step, total) {
2070
- return `${TTY_COLORS.bg.black}${TTY_COLORS.fg.yellow}[${step}/${total}]${TTY_COLORS.reset}`;
2071
- }
2072
- function formatMethod(method) {
2073
- return `${TTY_COLORS.bright}${method}${TTY_COLORS.reset}`;
2074
- }
2075
- function formatAction(action) {
2076
- return `${TTY_COLORS.dim}(${action})${TTY_COLORS.reset}`;
2077
- }
2078
- //#endregion
2079
- export { isProduction as A, logger as C, getBooleanEnvVar as D, env as E, getEnvVar as O, createLogger as S, ENV as T, BetterAuthError as _, withSpan as a, ValidationError as b, ATTR_HTTP_ROUTE as c, getAuthTablesWithResolvedIndexes as d, getDatabaseFieldIndexName as f, APIError as g, createRandomStringGenerator as h, generateId as i, isTest as j, isDevelopment as k, safeJSONParse as l, getPortableDatabaseIdentifierKey as m, initGetModelName as n, ATTR_DB_COLLECTION_NAME as o, getDatabaseIndexStringLength as p, initGetFieldName as r, ATTR_HTTP_RESPONSE_STATUS_CODE as s, createAdapterFactory as t, getAuthTables as u, APIError$1 as v, shouldPublishLog as w, kAPIErrorHeaderSymbol as x, BetterCallError as y };