@vite-hub/auth 0.1.0 → 0.3.1

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 (89) hide show
  1. package/README.md +333 -49
  2. package/dist/abilities-DfAnFYwG.d.ts +93 -0
  3. package/dist/abilities.d.ts +2 -0
  4. package/dist/abilities.js +43 -0
  5. package/dist/ability-error-CqgBrBfR.js +91 -0
  6. package/dist/ability-error-DcgChwCN.d.ts +34 -0
  7. package/dist/admin-claim-code-CDipqeAU.js +22 -0
  8. package/dist/agent.d.ts +5 -5
  9. package/dist/agent.js +17 -9
  10. package/dist/application-path-DuTpfGFj.js +62 -0
  11. package/dist/auth-instance-CR6b1W80.js +1168 -0
  12. package/dist/bun-sqlite.d.ts +8 -0
  13. package/dist/cli-ubYJpAL_.d.ts +163 -0
  14. package/dist/cli.d.ts +1 -1
  15. package/dist/cli.js +47 -7
  16. package/dist/console-runtime-DTopBP-x.d.ts +71 -0
  17. package/dist/console-runtime-J9_Vx9pT.js +1166 -0
  18. package/dist/console-runtime.d.ts +3 -3
  19. package/dist/console-runtime.js +2 -819
  20. package/dist/console.d.ts +215 -3
  21. package/dist/console.js +1 -1
  22. package/dist/database-options-BRNef9oy.js +29 -0
  23. package/dist/database-schema-options-ENuRMduM.js +12 -0
  24. package/dist/database.d.ts +12 -0
  25. package/dist/database.js +45 -0
  26. package/dist/definition-CqQMcDEK.js +280 -0
  27. package/dist/error-diagnostics-C8XtVz0i.js +138 -0
  28. package/dist/{events-P7mI4IQb.js → events-ByzenEVj.js} +122 -4
  29. package/dist/forward.d.ts +50 -0
  30. package/dist/forward.js +120 -0
  31. package/dist/host-declarations.d.ts +2 -1
  32. package/dist/index.d.ts +24 -3
  33. package/dist/index.js +3 -102
  34. package/dist/internal/server.d.ts +5 -0
  35. package/dist/internal/server.js +858 -0
  36. package/dist/invariant-D8_xBqmZ.js +22 -0
  37. package/dist/mcp.d.ts +187 -0
  38. package/dist/mcp.js +353 -0
  39. package/dist/members-D9lfaEO_.js +533 -0
  40. package/dist/nuxt-bridge-Cl988STZ.js +44 -0
  41. package/dist/nuxt.d.ts +13 -5
  42. package/dist/nuxt.js +90 -13
  43. package/dist/object-Da1zyPCR.js +11 -0
  44. package/dist/page-tools-shared-l4eyj53D.js +19 -0
  45. package/dist/presets.js +1 -1
  46. package/dist/request-z6DHHmrb.js +47 -0
  47. package/dist/runtime/console.d.ts +3 -7
  48. package/dist/runtime/console.js +4 -42
  49. package/dist/runtime/empty-abilities.d.ts +5 -0
  50. package/dist/runtime/empty-abilities.js +4 -0
  51. package/dist/runtime/empty-client.d.ts +6 -0
  52. package/dist/runtime/empty-client.js +5 -0
  53. package/dist/runtime/empty-definition.d.ts +1 -1
  54. package/dist/runtime/nuxt.js +1 -1
  55. package/dist/runtime/server.d.ts +2 -0
  56. package/dist/runtime/server.js +77 -0
  57. package/dist/runtime/vue-nuxt.d.ts +3 -2
  58. package/dist/runtime/vue-nuxt.js +157 -5
  59. package/dist/runtime-state-ojQCzKOc.js +25 -0
  60. package/dist/schema.d.ts +137 -0
  61. package/dist/schema.js +147 -0
  62. package/dist/server-C0qnKN2W.d.ts +143 -0
  63. package/dist/server-bQGzVQ--.d.ts +41 -0
  64. package/dist/server.d.ts +3 -2
  65. package/dist/server.js +3 -3
  66. package/dist/session-cookies-BbH3UR2m.js +227 -0
  67. package/dist/{set-cookie-2as_DbHe.js → set-cookie-C8NOhdRE.js} +27 -12
  68. package/dist/{shared-DnpgYiLF.js → shared-BwcdRGxD.js} +2 -5
  69. package/dist/table-specs-8gq_FCaq.js +771 -0
  70. package/dist/table-specs-DbXyaXWs.d.ts +842 -0
  71. package/dist/test.d.ts +26 -0
  72. package/dist/test.js +25 -0
  73. package/dist/{events-BkmK2dFY.d.ts → types-CNaeH2Fd.d.ts} +240 -157
  74. package/dist/vite-CV400XXY.js +1556 -0
  75. package/dist/vite.d.ts +138 -20
  76. package/dist/vite.js +2 -2
  77. package/dist/vue.d.ts +330 -21
  78. package/dist/vue.js +583 -36
  79. package/package.json +84 -15
  80. package/dist/application-path-C290OAIs.js +0 -18
  81. package/dist/cli-mgXvsBtA.d.ts +0 -85
  82. package/dist/console-B7eERmGv.d.ts +0 -180
  83. package/dist/console-runtime-bZQtnX2Y.d.ts +0 -39
  84. package/dist/error-diagnostics-CL0yjHiM.js +0 -79
  85. package/dist/events-config-CjcFOhTE.js +0 -177
  86. package/dist/inspect-DPtsW8dB.d.ts +0 -36
  87. package/dist/server-B7LU19dS.js +0 -1730
  88. package/dist/server-CTD_JAww.d.ts +0 -77
  89. package/dist/vite-COWkwxsj.js +0 -990
@@ -0,0 +1,1556 @@
1
+ import { t as authErrorDiagnostics } from "./error-diagnostics-C8XtVz0i.js";
2
+ import { n as isRecordOrFunction, t as isRecord$1 } from "./object-Da1zyPCR.js";
3
+ import { i as resetAuth } from "./runtime-state-ojQCzKOc.js";
4
+ import { t as invariant } from "./invariant-D8_xBqmZ.js";
5
+ import { r as resolveAccessRoutePath, t as accessRouteSyntaxError } from "./application-path-DuTpfGFj.js";
6
+ import { t as normalizeAuthBasePath } from "./shared-BwcdRGxD.js";
7
+ import { a as authDatabaseSchemaError, i as authDatabasePlacementError, n as authDatabaseAdditionalFieldsError, o as authMemoryDatabaseError, t as assertAuthDatabaseIdStrategy } from "./database-options-BRNef9oy.js";
8
+ import { i as resolveAuthTableSpecs, n as authSqlName } from "./table-specs-8gq_FCaq.js";
9
+ import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
10
+ import { basename, dirname, join, parse, relative, resolve } from "node:path";
11
+ import { fileURLToPath } from "node:url";
12
+ import { tmpdir } from "node:os";
13
+ import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
14
+ import { parseSync } from "vite";
15
+ //#region ../internal/src/build/vite.ts
16
+ const generatedViteHubFilesPattern = "**/.vitehub/**";
17
+ const projectRootDirectoryMarkers = [
18
+ ["server", "agents"],
19
+ ["server", "channels"],
20
+ ["server", "connections"],
21
+ ["server", "browsers"],
22
+ ["server", "emails"],
23
+ ["server", "schedules"],
24
+ ["server", "workspaces"]
25
+ ];
26
+ const projectRootFileMarkers = [
27
+ ["package.json"],
28
+ ["nuxt.config.ts"],
29
+ ["nuxt.config.mts"],
30
+ ["nuxt.config.js"],
31
+ ["nuxt.config.mjs"]
32
+ ];
33
+ function createNoExternalAddition(...packageNames) {
34
+ return (current) => {
35
+ if (current === true) return;
36
+ const values = Array.isArray(current) ? current : [current];
37
+ const missing = packageNames.filter((packageName) => !values.includes(packageName));
38
+ return missing.length ? missing : void 0;
39
+ };
40
+ }
41
+ function isServerEnvironment(name, config) {
42
+ return name === "ssr" || config.consumer === "server";
43
+ }
44
+ /**
45
+ * Server directories that ViteHub scans for Definitions. The first entry is the application.
46
+ * Later entries are Nuxt layers in Nuxt priority order.
47
+ */
48
+ const VITEHUB_SERVER_DIRS = "__vitehubServerDirs";
49
+ /**
50
+ * Lists the server directory of the application and of each Nuxt layer it extends.
51
+ * The application comes first. Layers follow in Nuxt priority order, like Nuxt's own Nitro scan directories.
52
+ */
53
+ function resolveNuxtServerDirs(options) {
54
+ const appRoot = options.rootDir ? resolve(options.rootDir) : void 0;
55
+ let appDirectory = options.serverDir ? resolve(options.serverDir) : void 0;
56
+ const layerDirectories = [];
57
+ for (const layer of options._layers ?? []) {
58
+ const root = layer.config?.rootDir ?? layer.cwd;
59
+ const isApp = Boolean(root && appRoot && resolve(root) === appRoot);
60
+ if (isApp && appDirectory) continue;
61
+ const config = isApp ? options : layer.config ?? {};
62
+ const sourceDir = config.srcDir ?? layer.cwd ?? root;
63
+ if (!sourceDir) continue;
64
+ const directory = resolve(sourceDir, config.serverDir ?? "server");
65
+ if (isApp) appDirectory = directory;
66
+ else layerDirectories.push(directory);
67
+ }
68
+ if (!appDirectory && layerDirectories.length && appRoot) appDirectory = resolve(appRoot, "server");
69
+ const directories = [.../* @__PURE__ */ new Set([...appDirectory ? [appDirectory] : [], ...layerDirectories])];
70
+ return directories.length ? directories : void 0;
71
+ }
72
+ function generatedViteHubWatchIgnoredAddition(ignored) {
73
+ return (Array.isArray(ignored) ? ignored : [ignored]).includes(generatedViteHubFilesPattern) ? void 0 : [generatedViteHubFilesPattern];
74
+ }
75
+ function resolveViteHubProjectRoot(root, options = {}) {
76
+ const resolvedRoot = resolve(root);
77
+ const temporaryRoot = resolve(tmpdir());
78
+ const sharedTemporaryRoot = dirname(temporaryRoot) === parse(temporaryRoot).root ? temporaryRoot : void 0;
79
+ if (options.projectRoot) return resolve(resolvedRoot, options.projectRoot);
80
+ if (basename(resolvedRoot) === "app") {
81
+ const parent = dirname(resolvedRoot);
82
+ if (parent !== sharedTemporaryRoot && (hasProjectRootDirectoryMarker(parent) || hasProjectRootFileMarker(parent, [
83
+ "nuxt.config.ts",
84
+ "nuxt.config.mts",
85
+ "nuxt.config.js",
86
+ "nuxt.config.mjs"
87
+ ]))) return parent;
88
+ }
89
+ let current = resolvedRoot;
90
+ while (true) {
91
+ if (current === sharedTemporaryRoot && resolvedRoot !== current) return resolvedRoot;
92
+ if (hasProjectRootMarker(current)) return current;
93
+ const parent = dirname(current);
94
+ if (parent === current) return resolvedRoot;
95
+ current = parent;
96
+ }
97
+ }
98
+ function hasProjectRootDirectoryMarker(root) {
99
+ for (const marker of projectRootDirectoryMarkers) try {
100
+ if (statSync(resolve(root, ...marker)).isDirectory()) return true;
101
+ } catch (error) {
102
+ if (error.code !== "ENOENT") throw error;
103
+ }
104
+ return false;
105
+ }
106
+ function hasProjectRootMarker(root) {
107
+ if (hasProjectRootDirectoryMarker(root)) return true;
108
+ return hasProjectRootFileMarker(root, projectRootFileMarkers.flat());
109
+ }
110
+ function hasProjectRootFileMarker(root, markers) {
111
+ for (const marker of markers) {
112
+ const path = Array.isArray(marker) ? marker : [marker];
113
+ try {
114
+ if (statSync(resolve(root, ...path)).isFile()) return true;
115
+ } catch (error) {
116
+ if (error.code !== "ENOENT") throw error;
117
+ }
118
+ }
119
+ return false;
120
+ }
121
+ //#endregion
122
+ //#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
123
+ const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
124
+ function normalizeWindowsPath(input = "") {
125
+ if (!input) return input;
126
+ return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
127
+ }
128
+ const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
129
+ const _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
130
+ const _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/;
131
+ function cwd() {
132
+ if (typeof process !== "undefined" && typeof process.cwd === "function") return process.cwd().replace(/\\/g, "/");
133
+ return "/";
134
+ }
135
+ const resolve$1 = function(...arguments_) {
136
+ arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
137
+ let resolvedPath = "";
138
+ let resolvedAbsolute = false;
139
+ for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
140
+ const path = index >= 0 ? arguments_[index] : cwd();
141
+ if (!path || path.length === 0) continue;
142
+ resolvedPath = `${path}/${resolvedPath}`;
143
+ resolvedAbsolute = isAbsolute(path);
144
+ }
145
+ resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
146
+ if (resolvedAbsolute && !isAbsolute(resolvedPath)) return `/${resolvedPath}`;
147
+ return resolvedPath.length > 0 ? resolvedPath : ".";
148
+ };
149
+ function normalizeString(path, allowAboveRoot) {
150
+ let res = "";
151
+ let lastSegmentLength = 0;
152
+ let lastSlash = -1;
153
+ let dots = 0;
154
+ let char = null;
155
+ for (let index = 0; index <= path.length; ++index) {
156
+ if (index < path.length) char = path[index];
157
+ else if (char === "/") break;
158
+ else char = "/";
159
+ if (char === "/") {
160
+ if (lastSlash === index - 1 || dots === 1);
161
+ else if (dots === 2) {
162
+ if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
163
+ if (res.length > 2) {
164
+ const lastSlashIndex = res.lastIndexOf("/");
165
+ if (lastSlashIndex === -1) {
166
+ res = "";
167
+ lastSegmentLength = 0;
168
+ } else {
169
+ res = res.slice(0, lastSlashIndex);
170
+ lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
171
+ }
172
+ lastSlash = index;
173
+ dots = 0;
174
+ continue;
175
+ } else if (res.length > 0) {
176
+ res = "";
177
+ lastSegmentLength = 0;
178
+ lastSlash = index;
179
+ dots = 0;
180
+ continue;
181
+ }
182
+ }
183
+ if (allowAboveRoot) {
184
+ res += res.length > 0 ? "/.." : "..";
185
+ lastSegmentLength = 2;
186
+ }
187
+ } else {
188
+ if (res.length > 0) res += `/${path.slice(lastSlash + 1, index)}`;
189
+ else res = path.slice(lastSlash + 1, index);
190
+ lastSegmentLength = index - lastSlash - 1;
191
+ }
192
+ lastSlash = index;
193
+ dots = 0;
194
+ } else if (char === "." && dots !== -1) ++dots;
195
+ else dots = -1;
196
+ }
197
+ return res;
198
+ }
199
+ const isAbsolute = function(p) {
200
+ return _IS_ABSOLUTE_RE.test(p);
201
+ };
202
+ const relative$1 = function(from, to) {
203
+ const _from = resolve$1(from).replace(_ROOT_FOLDER_RE, "$1").split("/");
204
+ const _to = resolve$1(to).replace(_ROOT_FOLDER_RE, "$1").split("/");
205
+ if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0]) return _to.join("/");
206
+ const _fromCopy = [..._from];
207
+ for (const segment of _fromCopy) {
208
+ if (_to[0] !== segment) break;
209
+ _from.shift();
210
+ _to.shift();
211
+ }
212
+ return [..._from.map(() => ".."), ..._to].join("/");
213
+ };
214
+ const dirname$1 = function(p) {
215
+ const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
216
+ if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) segments[0] += "/";
217
+ return segments.join("/") || (isAbsolute(p) ? "/" : ".");
218
+ };
219
+ //#endregion
220
+ //#region ../internal/src/build/paths.ts
221
+ function resolveRuntimeModule(packageDir, modulePath) {
222
+ const distFile = resolve$1(packageDir, "dist", `${modulePath}.js`);
223
+ return existsSync(distFile) ? distFile : resolve$1(packageDir, "src", `${modulePath}.ts`);
224
+ }
225
+ const packageDirs = /* @__PURE__ */ new Map();
226
+ function findPackageDir(file) {
227
+ const start = dirname$1(file);
228
+ const cached = packageDirs.get(start);
229
+ if (cached) return cached;
230
+ let dir = start;
231
+ while (!existsSync(resolve$1(dir, "package.json"))) {
232
+ const parent = dirname$1(dir);
233
+ invariant(parent !== dir, `a file that a package resolver found has a package.json above it (${file})`);
234
+ dir = parent;
235
+ }
236
+ packageDirs.set(start, dir);
237
+ return dir;
238
+ }
239
+ /**
240
+ * The absolute path of a module that the calling package builds, such as `ownModule(import.meta.url, "runtime/state")`.
241
+ * Owner plugins write this path into generated code, so the module needs no package export, and an app resolves it
242
+ * only when the owner's feature is on. It is the `dist` file, or the `src` file before the package is built.
243
+ */
244
+ function ownModule(importMetaUrl, modulePath) {
245
+ return resolveRuntimeModule(findPackageDir(fileURLToPath(importMetaUrl)), modulePath);
246
+ }
247
+ //#endregion
248
+ //#region ../internal/src/nitro-kit.ts
249
+ function cloneArray(value) {
250
+ return Array.isArray(value) ? [...value] : [];
251
+ }
252
+ function sameHandler(left, right) {
253
+ return left.handler === right.handler && left.route === right.route && left.method === right.method && left.middleware === right.middleware;
254
+ }
255
+ /** Create a Nitro 3 configuration builder for generated ViteHub output. */
256
+ function createNitroServerKit(value = {}) {
257
+ const config = isRecordOrFunction(value) ? { ...value } : {};
258
+ const handlers = cloneArray(config.handlers);
259
+ const plugins = cloneArray(config.plugins);
260
+ config.handlers = handlers;
261
+ config.plugins = plugins;
262
+ return {
263
+ config,
264
+ addHandler(handler, position = "end") {
265
+ if (handlers.some((candidate) => isRecordOrFunction(candidate) && sameHandler(candidate, handler))) return;
266
+ if (position === "start") handlers.unshift({ ...handler });
267
+ else handlers.push({ ...handler });
268
+ },
269
+ addPlugin(plugin, position = "end") {
270
+ if (plugins.includes(plugin)) return;
271
+ if (position === "start") plugins.unshift(plugin);
272
+ else plugins.push(plugin);
273
+ }
274
+ };
275
+ }
276
+ //#endregion
277
+ //#region ../internal/src/definition-catalog.ts
278
+ /** `writeFileIfChangedSync` for async callers. */
279
+ async function writeFileIfChanged(file, contents) {
280
+ if (await readFile(file, "utf8").catch(() => void 0) === contents) return;
281
+ await mkdir(resolve$1(file, ".."), { recursive: true });
282
+ await writeFile(file, contents, "utf8");
283
+ }
284
+ //#endregion
285
+ //#region ../internal/src/inspect.ts
286
+ function relativeDefinitionFile(projectRoot, file) {
287
+ return relative$1(projectRoot, file).replaceAll("\\", "/");
288
+ }
289
+ /** Summarizes Definitions that have no owner-specific fields. */
290
+ function summarizeDefinitions(projectRoot, definitions, fallbackSource) {
291
+ return definitions.map((definition) => ({
292
+ fields: [],
293
+ file: relativeDefinitionFile(projectRoot, definition.handler),
294
+ name: definition.name,
295
+ source: definition.source || fallbackSource
296
+ }));
297
+ }
298
+ const secretKeyPattern = /secret|token|passw(?:or)?d|credential|api[-_\s]?key|private[-_\s]?key|authorization|cookie|signature|dsn|connection[-_\s]?string/i;
299
+ new RegExp(String.raw`\b([\w-]*authorization[\w-]*["']?\s*[:=]\s*)(?!\[redacted\](?=$|[\s,;}&]))(?:"(?:\\[^\r\n]|[^"\\\r\n])*"|'(?:\\[^\r\n]|[^'\\\r\n])*'|[^\r\n]+?(?=\s*(?:[,;])?\s*(?:${secretKeyPattern.source})[\w-]*\s*[:=]|\s+rejected\b|$))`, "gi");
300
+ new RegExp(String.raw`\b([\w-]*(?:${secretKeyPattern.source})[\w-]*["']?\s*[:=]\s*)(?!\[redacted\](?=$|[\s,;}&]))(?:"(?:\\[^\r\n]|[^"\\\r\n])*"|'(?:\\[^\r\n]|[^'\\\r\n])*'|[^\s,;&#&]+)`, "gi");
301
+ //#endregion
302
+ //#region ../internal/src/contributions.ts
303
+ function isThenable(value) {
304
+ return typeof value.then === "function";
305
+ }
306
+ async function flattenPlugins(value, plugins, seen) {
307
+ if (Array.isArray(value)) {
308
+ for (const item of value) await flattenPlugins(item, plugins, seen);
309
+ return;
310
+ }
311
+ if (!isRecord$1(value) || seen.has(value)) return;
312
+ seen.add(value);
313
+ if (isThenable(value)) {
314
+ await flattenPlugins(await value, plugins, seen);
315
+ return;
316
+ }
317
+ plugins.push(value);
318
+ }
319
+ /**
320
+ * Flattens Vite plugin options as `collectContributions` reads them: nested arrays and promised options become one
321
+ * list of plugin objects, and falsy entries are dropped. A plugin that filters itself out of `context.plugins` must
322
+ * filter this list, because `vitehub()` nests its plugins in an array.
323
+ */
324
+ async function flattenPluginOptions(plugins) {
325
+ const flattened = [];
326
+ await flattenPlugins(plugins ?? [], flattened, /* @__PURE__ */ new Set());
327
+ return flattened;
328
+ }
329
+ //#endregion
330
+ //#region src/access-route-cache.ts
331
+ /** Route rules that keep one response and serve it to many visitors. Nitro stores `swr` as `cache`. */
332
+ const cachingRuleNames = [
333
+ "cache",
334
+ "isr",
335
+ "prerender",
336
+ "static"
337
+ ];
338
+ /** Nitro caches and prerenders only GET and HEAD requests. */
339
+ const cachedMethods = ["GET", "HEAD"];
340
+ /** On one pattern, h3 merges the rules for every method first, then GET rules, then HEAD rules. */
341
+ const methodOrder = [
342
+ "",
343
+ "GET",
344
+ "HEAD"
345
+ ];
346
+ /** h3 applies the GET rules of a pattern to HEAD requests too. */
347
+ function appliesTo(entry, method) {
348
+ return !entry.method || entry.method === method || method === "HEAD" && entry.method === "GET";
349
+ }
350
+ /**
351
+ * The rou3 pattern of the paths that the access middleware guards for a route. The middleware matches the path
352
+ * literally, so the pattern escapes every character that rou3 reads as syntax. In rou3, `/**` also matches the path
353
+ * itself.
354
+ */
355
+ function accessRoutePattern(route, baseURL) {
356
+ const { path, recursive } = resolveAccessRoutePath(route, baseURL);
357
+ const literal = path.replace(/[\\:(){}*?+]/g, "\\$&");
358
+ return recursive ? `${literal}/**` : literal;
359
+ }
360
+ /**
361
+ * Stops the build when a route rule caches or prerenders a path that `access.routes` guards. The cache would keep the
362
+ * response of one visitor and serve it to others.
363
+ *
364
+ * The check compares patterns, not sample paths. A rule that caches and matches at least one guarded path fails,
365
+ * unless a `false` value of the same rule turns the cache off on all of these paths: the `false` rule must match every
366
+ * guarded path, or every path of the caching rule, and h3 must merge it after the caching rule. A cache that more than
367
+ * one `false` rule turns off together still fails. A rule whose paths are all in one route of `publicRoutes` passes,
368
+ * because the middleware guards none of them.
369
+ */
370
+ async function assertNoCachedAccessRoutes(routes, routeRules, baseURL = "/", publicRoutes = []) {
371
+ const guards = routes.filter((route) => !route.method || cachedMethods.includes(route.method.toUpperCase()));
372
+ if (!guards.length || !Object.keys(routeRules).length) return;
373
+ const [{ normalizeRouteRules }, { compareRoutes, routesOverlap }] = await Promise.all([import("h3/rules"), import("rou3")]);
374
+ const base = baseURL.replace(/\/$/, "");
375
+ const entries = Object.entries(normalizeRouteRules(routeRules)).map(([key, rules]) => {
376
+ const [, method = "", path = key] = /^([A-Z]+) (\/.*)$/.exec(key) ?? [];
377
+ return {
378
+ key,
379
+ method,
380
+ pattern: `${base}${path}`,
381
+ rules
382
+ };
383
+ });
384
+ const exceptions = publicRoutes.map((route) => accessRoutePattern(route, baseURL));
385
+ const isPublic = (entry) => exceptions.some((pattern) => ["equal", "superset"].includes(compareRoutes(pattern, entry.pattern)));
386
+ for (const guard of guards) {
387
+ const guarded = accessRoutePattern(guard.route, baseURL);
388
+ const method = guard.method?.toUpperCase();
389
+ const methods = !method || method === "GET" ? cachedMethods : [method];
390
+ for (const method of methods) {
391
+ const applied = entries.filter((entry) => appliesTo(entry, method));
392
+ for (const name of cachingRuleNames) {
393
+ const turnsOff = (entry, off) => {
394
+ if (off.rules[name] !== false) return false;
395
+ const relation = compareRoutes(off.pattern, entry.pattern);
396
+ if (relation === "equal") return methodOrder.indexOf(off.method) > methodOrder.indexOf(entry.method);
397
+ return relation === "subset" && ["equal", "superset"].includes(compareRoutes(off.pattern, guarded));
398
+ };
399
+ for (const entry of applied) {
400
+ const value = entry.rules[name];
401
+ if (value === void 0 || value === false || !routesOverlap(guarded, entry.pattern) || isPublic(entry)) continue;
402
+ if (applied.some((off) => turnsOff(entry, off))) continue;
403
+ throw authErrorDiagnostics.AUTH_B0002({ message: `[vitehub] Route rule ${JSON.stringify(entry.key)} sets \`${name}\` on ${method} requests to paths that the \`access.routes\` entry ${JSON.stringify(guard.route)} guards. A cached or prerendered response is made for one visitor and served to others.` });
404
+ }
405
+ }
406
+ }
407
+ }
408
+ }
409
+ //#endregion
410
+ //#region ../internal/src/build/scan-module.ts
411
+ /**
412
+ * Reads facts from JavaScript and TypeScript modules at build and dev time. The scanner parses each module once with
413
+ * the oxc parser that Vite ships through Rolldown, and never runs it. Values that are not static literals read as
414
+ * `dynamic`, so callers can report their own diagnostics.
415
+ */
416
+ /** The value of an expression that the scanner cannot read without running the module. */
417
+ const dynamic = Symbol("dynamic");
418
+ function languageOf(file) {
419
+ if (/\.(?:c|m)?tsx$/i.test(file)) return "tsx";
420
+ if (/\.(?:c|m)?jsx$/i.test(file)) return "jsx";
421
+ if (/\.(?:c|m)?js$/i.test(file)) return "js";
422
+ return "ts";
423
+ }
424
+ /** Parses a module once. `file` selects the grammar from its extension and defaults to TypeScript. */
425
+ function scanModule(source, file = "module.ts") {
426
+ const result = parseSync(file, source, {
427
+ lang: languageOf(file),
428
+ preserveParens: false,
429
+ sourceType: "module"
430
+ });
431
+ return {
432
+ comments: result.comments,
433
+ errors: result.errors,
434
+ file,
435
+ program: result.program,
436
+ source
437
+ };
438
+ }
439
+ function isNode(value) {
440
+ return typeof value === "object" && value !== null && "type" in value && typeof value.type === "string";
441
+ }
442
+ /** Visits `node` and its descendants. Return `false` from `visit` to skip the children of a node. */
443
+ function walk(node, visit, parent) {
444
+ if (visit(node, parent) === false) return;
445
+ const fields = node;
446
+ for (const key in fields) {
447
+ const child = fields[key];
448
+ if (typeof child !== "object" || child === null || key === "parent") continue;
449
+ if (Array.isArray(child)) {
450
+ for (const item of child) if (isNode(item)) walk(item, visit, node);
451
+ } else if (isNode(child)) walk(child, visit, node);
452
+ }
453
+ }
454
+ /** Removes parentheses, `as`, `satisfies`, `!`, and `<T>` assertions around an expression. */
455
+ function unwrapExpression(node) {
456
+ while (node.type === "ParenthesizedExpression" || node.type === "TSAsExpression" || node.type === "TSSatisfiesExpression" || node.type === "TSNonNullExpression" || node.type === "TSTypeAssertion") node = node.expression;
457
+ return node;
458
+ }
459
+ /** The expression of `export default <expression>`, without assertions. Declarations return undefined. */
460
+ function defaultExportExpression(module) {
461
+ for (const statement of module.program.body) {
462
+ if (statement.type !== "ExportDefaultDeclaration") continue;
463
+ const declaration = statement.declaration;
464
+ if (declaration.type === "FunctionDeclaration" || declaration.type === "ClassDeclaration" || declaration.type === "TSInterfaceDeclaration") return;
465
+ return unwrapExpression(declaration);
466
+ }
467
+ }
468
+ function staticKey(property) {
469
+ const key = property.key;
470
+ if (key.type === "Identifier" && !property.computed) return key.name;
471
+ if (key.type === "PrivateIdentifier") return;
472
+ const value = staticValue(key);
473
+ return typeof value === "string" || typeof value === "number" || typeof value === "bigint" ? String(value) : void 0;
474
+ }
475
+ /** The members of an object literal in source order. */
476
+ function objectProperties(object) {
477
+ return object.properties.map((node) => node.type === "SpreadElement" ? {
478
+ computed: false,
479
+ key: void 0,
480
+ node,
481
+ value: void 0
482
+ } : {
483
+ computed: node.computed,
484
+ key: staticKey(node),
485
+ node,
486
+ value: unwrapExpression(node.value)
487
+ });
488
+ }
489
+ /** The value of a template literal without substitutions. */
490
+ function staticTemplate(node) {
491
+ if (node.expressions.length) return dynamic;
492
+ return node.quasis[0]?.value.cooked ?? dynamic;
493
+ }
494
+ const escapePattern = /\\(u\{[^}]*\}?|u[\s\S]{0,4}|x[\s\S]{0,2}|0\d|[\s\S])/g;
495
+ /**
496
+ * True when a string literal has an escape that strict mode code rejects. The parser recovers from some bad escapes
497
+ * and accepts legacy octal escapes, so the scanner checks them again.
498
+ */
499
+ function hasInvalidEscape(raw) {
500
+ for (const [, escape = ""] of raw.matchAll(escapePattern)) if (escape.startsWith("u{")) {
501
+ const code = escape.slice(2, -1);
502
+ if (!escape.endsWith("}") || !/^[\da-fA-F]+$/.test(code) || Number.parseInt(code, 16) > 1114111) return true;
503
+ } else if (escape.startsWith("u")) {
504
+ if (!/^u[\da-fA-F]{4}$/.test(escape)) return true;
505
+ } else if (escape.startsWith("x")) {
506
+ if (!/^x[\da-fA-F]{2}$/.test(escape)) return true;
507
+ } else if (/^(?:[1-9]|0\d)$/.test(escape)) return true;
508
+ return false;
509
+ }
510
+ /**
511
+ * Reads a literal value: strings, numbers, booleans, `null`, `undefined`, template literals without substitutions,
512
+ * and arrays and objects of these. Any other expression gives `dynamic`.
513
+ */
514
+ function staticValue(node) {
515
+ node = unwrapExpression(node);
516
+ switch (node.type) {
517
+ case "Literal":
518
+ if ("regex" in node) return dynamic;
519
+ return typeof node.value === "string" && hasInvalidEscape(node.raw ?? "") ? dynamic : node.value;
520
+ case "TemplateLiteral": return staticTemplate(node);
521
+ case "Identifier": return node.name === "undefined" ? void 0 : dynamic;
522
+ case "UnaryExpression": {
523
+ if (node.operator === "void") return staticValue(node.argument) === dynamic ? dynamic : void 0;
524
+ const value = staticValue(node.argument);
525
+ if (node.operator === "-" && (typeof value === "number" || typeof value === "bigint")) return -value;
526
+ return dynamic;
527
+ }
528
+ case "ArrayExpression": {
529
+ const values = [];
530
+ for (const element of node.elements) {
531
+ if (element === null || element.type === "SpreadElement") return dynamic;
532
+ const value = staticValue(element);
533
+ if (value === dynamic) return dynamic;
534
+ values.push(value);
535
+ }
536
+ return values;
537
+ }
538
+ case "ObjectExpression": {
539
+ const values = {};
540
+ for (const property of objectProperties(node)) {
541
+ if (property.key === void 0 || property.node.type !== "Property" || property.node.kind !== "init" || property.node.method || property.value === void 0) return dynamic;
542
+ const value = staticValue(property.value);
543
+ if (value === dynamic) return dynamic;
544
+ Object.defineProperty(values, property.key, {
545
+ configurable: true,
546
+ enumerable: true,
547
+ value,
548
+ writable: true
549
+ });
550
+ }
551
+ return values;
552
+ }
553
+ default: return dynamic;
554
+ }
555
+ }
556
+ /** The static string value of an expression, or undefined when it is not a string literal. */
557
+ function staticString(node) {
558
+ if (node === void 0) return;
559
+ const value = staticValue(node);
560
+ return typeof value === "string" ? value : void 0;
561
+ }
562
+ //#endregion
563
+ //#region src/discovery.ts
564
+ const authDefinitionExtensions = [
565
+ ".ts",
566
+ ".mts",
567
+ ".cts",
568
+ ".js",
569
+ ".mjs",
570
+ ".cjs"
571
+ ];
572
+ function serverAuthCandidates(serverDir) {
573
+ return authDefinitionExtensions.map((extension) => ({
574
+ handler: resolve(serverDir, `auth${extension}`),
575
+ name: "default",
576
+ source: "server-auth"
577
+ }));
578
+ }
579
+ function rootAuthCandidates(rootDir) {
580
+ return authDefinitionExtensions.map((extension) => ({
581
+ handler: resolve(rootDir, `server.auth${extension}`),
582
+ name: "default",
583
+ source: "server-auth-suffix"
584
+ }));
585
+ }
586
+ function existingDefinitions(candidates) {
587
+ return candidates.filter((definition) => existsSync(definition.handler));
588
+ }
589
+ /**
590
+ * Finds the Auth Definition. The first server directory is the application and later ones are Nuxt layers.
591
+ * An application Definition replaces layer Definitions. Two Definitions at the same level fail discovery.
592
+ */
593
+ function discoverAuthDefinitions(rootDir, options = {}) {
594
+ const [appServerDir, ...layerServerDirs] = options.serverDirs ?? [resolve(rootDir, "server")];
595
+ const appDefinitions = existingDefinitions([...appServerDir ? serverAuthCandidates(appServerDir) : [], ...rootAuthCandidates(rootDir)]);
596
+ if (appDefinitions.length > 1) throw authErrorDiagnostics.AUTH_R0003({ message: ["[vitehub] Only one Auth Definition is allowed. Found:", ...appDefinitions.map((definition) => ` - ${definition.handler}`)].join("\n") });
597
+ if (appDefinitions.length) return appDefinitions;
598
+ const layerDefinitions = existingDefinitions(layerServerDirs.flatMap(serverAuthCandidates));
599
+ if (layerDefinitions.length > 1) throw authErrorDiagnostics.AUTH_R0003({ message: [
600
+ "[vitehub] Only one Auth Definition is allowed. More than one Nuxt layer defines one:",
601
+ ...layerDefinitions.map((definition) => ` - ${definition.handler}`),
602
+ "Add `server/auth.ts` to the application to select the Auth Definition."
603
+ ].join("\n") });
604
+ return layerDefinitions;
605
+ }
606
+ /** Finds the app's Auth client options, `auth.client.ts`, in the Vite root, which is `app/` in a Nuxt app. */
607
+ function discoverAuthClient(appDir) {
608
+ return authDefinitionExtensions.map((extension) => resolve(appDir, `auth.client${extension}`)).find((file) => existsSync(file));
609
+ }
610
+ function discoverAuthDefinition(rootDir, options = {}) {
611
+ return discoverAuthDefinitions(rootDir, options)[0];
612
+ }
613
+ const abilitiesExtensions = [
614
+ ".ts",
615
+ ".mts",
616
+ ".js",
617
+ ".mjs"
618
+ ];
619
+ /** The app's candidates come first; the remaining candidates belong to Nuxt layers. */
620
+ function authAbilitiesCandidates(rootDir, options = {}) {
621
+ const [appServerDir = resolve(rootDir, "server"), ...layerServerDirs] = options.serverDirs ?? [];
622
+ const candidates = (serverDir) => abilitiesExtensions.map((extension) => resolve(dirname(serverDir), "shared", `abilities${extension}`));
623
+ return {
624
+ app: candidates(appServerDir),
625
+ layers: layerServerDirs.flatMap(candidates)
626
+ };
627
+ }
628
+ /** The app replaces layer rules. Without app rules, exactly one layer may provide them. */
629
+ function discoverAuthAbilities(rootDir, options = {}) {
630
+ const candidates = authAbilitiesCandidates(rootDir, options);
631
+ const app = candidates.app.filter((file) => existsSync(file));
632
+ const found = app.length ? app : candidates.layers.filter((file) => existsSync(file));
633
+ if (found.length > 1) throw authErrorDiagnostics.AUTH_C0060({ message: ["[vitehub] Only one abilities file is allowed. Found:", ...found.map((file) => ` - ${file}`)].join("\n") });
634
+ return found[0];
635
+ }
636
+ //#endregion
637
+ //#region src/config.ts
638
+ const authDatabaseModules = /* @__PURE__ */ new Set(["@vite-hub/auth/database", "vite-hub/auth/database"]);
639
+ function readAuthDatabaseImports(module) {
640
+ const names = /* @__PURE__ */ new Set();
641
+ for (const statement of module.program.body) {
642
+ if (statement.type !== "ImportDeclaration" || statement.importKind === "type" || !authDatabaseModules.has(statement.source.value)) continue;
643
+ for (const specifier of statement.specifiers) {
644
+ if (specifier.type !== "ImportSpecifier" || specifier.importKind === "type") continue;
645
+ if ((specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value) === "authDatabase") names.add(specifier.local.name);
646
+ }
647
+ }
648
+ return names;
649
+ }
650
+ /** The plugin factories whose tables `authDatabase()` adds, by the module that exports them. */
651
+ const authSchemaPluginImports = {
652
+ "better-auth/plugins": {
653
+ anonymous: "anonymous",
654
+ lastLoginMethod: "lastLoginMethod",
655
+ phoneNumber: "phoneNumber",
656
+ twoFactor: "twoFactor",
657
+ username: "username"
658
+ },
659
+ "@better-auth/api-key": { apiKey: "apiKey" },
660
+ "@better-auth/stripe": { stripe: "stripe" }
661
+ };
662
+ /** The plugins of `AuthSchemaPlugin` that `module` imports and calls, such as `twoFactor()` from `better-auth/plugins`. */
663
+ function readAuthSchemaPlugins(module) {
664
+ const locals = /* @__PURE__ */ new Map();
665
+ for (const statement of module.program.body) {
666
+ if (statement.type !== "ImportDeclaration" || statement.importKind === "type") continue;
667
+ const source = statement.source.value.startsWith("better-auth/plugins/") ? "better-auth/plugins" : statement.source.value;
668
+ const exports = authSchemaPluginImports[source];
669
+ if (!exports) continue;
670
+ for (const specifier of statement.specifiers) {
671
+ if (specifier.type !== "ImportSpecifier" || specifier.importKind === "type") continue;
672
+ const imported = specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value;
673
+ if (Object.hasOwn(exports, imported)) locals.set(specifier.local.name, exports[imported]);
674
+ }
675
+ }
676
+ const plugins = /* @__PURE__ */ new Set();
677
+ if (locals.size) walk(module.program, (node) => {
678
+ if (node.type === "CallExpression" && node.callee.type === "Identifier" && locals.has(node.callee.name)) plugins.add(locals.get(node.callee.name));
679
+ });
680
+ return [...plugins].sort();
681
+ }
682
+ const authFieldTypes = /* @__PURE__ */ new Set([
683
+ "boolean",
684
+ "date",
685
+ "json",
686
+ "number",
687
+ "number[]",
688
+ "string",
689
+ "string[]"
690
+ ]);
691
+ function readStaticBooleanOption(field, key, label) {
692
+ if (!hasObjectProperty(field, key)) return;
693
+ const value = readStaticBooleanLiteral(readObjectPropertyValue(field, key));
694
+ if (value === void 0) throw authDatabaseAdditionalFieldsError(`${label}.${key} must be \`true\` or \`false\``);
695
+ return value;
696
+ }
697
+ /** One additional field, read from its object literal: the parts that shape the column. */
698
+ function readAdditionalField(value, key, label) {
699
+ const field = objectLiteral(value && unwrapExpression(value));
700
+ if (!field) throw authDatabaseAdditionalFieldsError(`${label} must be an inline object, such as \`{ type: "string", required: false }\``);
701
+ const typeValue = readObjectPropertyValue(field, "type");
702
+ const unwrappedType = typeValue && unwrapExpression(typeValue);
703
+ const type = unwrappedType?.type === "ArrayExpression" ? "string" : staticString(unwrappedType);
704
+ if (!type || !authFieldTypes.has(type)) throw authDatabaseAdditionalFieldsError(`${label}.type must be one of ${[...authFieldTypes].map((name) => `"${name}"`).join(", ")}, or a list of strings`);
705
+ const fieldName = readObjectPropertyValue(field, "fieldName");
706
+ if (fieldName && staticString(fieldName) !== key) throw authDatabaseSchemaError(`${label}.fieldName cannot rename the column`);
707
+ const spec = { type };
708
+ if (readStaticBooleanOption(field, "required", label)) spec.required = true;
709
+ if (readStaticBooleanOption(field, "unique", label)) spec.unique = true;
710
+ if (readStaticBooleanOption(field, "index", label)) spec.index = true;
711
+ if (readStaticBooleanOption(field, "bigint", label)) spec.bigint = true;
712
+ const defaultValue = readObjectPropertyValue(field, "defaultValue");
713
+ const staticDefault = defaultValue && staticValue(defaultValue);
714
+ if (typeof staticDefault === "string" || typeof staticDefault === "number" || typeof staticDefault === "boolean") spec.defaultValue = staticDefault;
715
+ const references = readObjectPropertyValue(field, "references");
716
+ if (references) {
717
+ const reference = staticValue(references);
718
+ const model = typeof reference === "object" && reference !== null && !Array.isArray(reference) ? reference.model : void 0;
719
+ const target = typeof reference === "object" && reference !== null && !Array.isArray(reference) ? reference.field : void 0;
720
+ const onDelete = typeof reference === "object" && reference !== null && !Array.isArray(reference) ? reference.onDelete ?? "cascade" : void 0;
721
+ if (typeof model !== "string" || typeof target !== "string" || onDelete !== "cascade" && onDelete !== "set null") throw authDatabaseAdditionalFieldsError(`${label}.references must be an inline object, such as \`{ model: "user", field: "id", onDelete: "cascade" }\``);
722
+ spec.references = {
723
+ model,
724
+ field: target,
725
+ onDelete
726
+ };
727
+ }
728
+ return spec;
729
+ }
730
+ /** The `additionalFields` of each core model, which `authDatabase()` adds as columns. */
731
+ function readAuthAdditionalFields(body) {
732
+ const result = {};
733
+ for (const model of [
734
+ "user",
735
+ "session",
736
+ "account",
737
+ "verification"
738
+ ]) {
739
+ const value = readObjectPropertyValue(objectLiteral(readObjectPropertyValue(body, model)), "additionalFields");
740
+ if (!value) continue;
741
+ const fields = objectLiteral(unwrapExpression(value));
742
+ if (!fields) throw authDatabaseAdditionalFieldsError(`${model}.additionalFields must be an inline object literal, so the Auth Vite plugin can add its columns`);
743
+ const entries = readObjectEntries(fields);
744
+ if (entries.some((entry) => !entry.key)) throw authDatabaseAdditionalFieldsError(`${model}.additionalFields must use static keys`);
745
+ if (entries.length) result[model] = Object.fromEntries(entries.map((entry) => [entry.key, readAdditionalField(entry.value, entry.key, `${model}.additionalFields.${entry.key}`)]));
746
+ }
747
+ return Object.keys(result).length ? result : void 0;
748
+ }
749
+ /** The object that a callback returns, from `() => ({ ... })` or the first `return { ... }` in its body. */
750
+ function readReturnedObject(callback) {
751
+ if (callback.type !== "ArrowFunctionExpression") return;
752
+ if (callback.body.type !== "BlockStatement") {
753
+ const body = unwrapExpression(callback.body);
754
+ return body.type === "ObjectExpression" ? body : void 0;
755
+ }
756
+ let returned;
757
+ walk(callback.body, (node) => {
758
+ if (returned !== void 0) return false;
759
+ if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") return false;
760
+ if (node.type === "ReturnStatement") {
761
+ returned = node.argument;
762
+ return false;
763
+ }
764
+ });
765
+ const value = returned ? unwrapExpression(returned) : void 0;
766
+ return value?.type === "ObjectExpression" ? value : void 0;
767
+ }
768
+ function readDefinitionObjectBody(file) {
769
+ const module = scanModule(readFileSync(file, "utf8"), file);
770
+ const authDatabase = readAuthDatabaseImports(module);
771
+ const call = defaultExportExpression(module);
772
+ if (call?.type !== "CallExpression" || call.callee.type !== "Identifier" || call.callee.name !== "defineAuth") return;
773
+ const argument = call.arguments[0];
774
+ if (argument === void 0 || argument.type === "SpreadElement") return;
775
+ const options = unwrapExpression(argument);
776
+ const plugins = readAuthSchemaPlugins(module);
777
+ if (hasObjectProperty(objectLiteral(options) ?? readReturnedObject(options), "runtime")) throw authErrorDiagnostics.AUTH_C0039({ message: "`defineAuth()` no longer takes `runtime`. Pass one callback that returns all options, so no option replaces another." });
778
+ if (options.type === "ObjectExpression") {
779
+ assertAuthDatabasePlacement(options, options, authDatabase);
780
+ return {
781
+ authDatabase,
782
+ body: options,
783
+ callback: false,
784
+ plugins
785
+ };
786
+ }
787
+ const returned = readReturnedObject(options);
788
+ assertAuthDatabasePlacement(options, returned, authDatabase);
789
+ return returned === void 0 ? void 0 : {
790
+ authDatabase,
791
+ body: returned,
792
+ callback: true,
793
+ plugins
794
+ };
795
+ }
796
+ /** Owned tables must have the same target in every request and in the build-time contribution. */
797
+ function assertAuthDatabasePlacement(options, body, names) {
798
+ const calls = [];
799
+ walk(options, (node) => {
800
+ if (node.type === "CallExpression" && node.callee.type === "Identifier" && names.has(node.callee.name)) calls.push(node);
801
+ });
802
+ if (!calls.length) return;
803
+ if (calls.length !== 1 || calls[0] !== readAuthDatabaseCall(body, names)) throw authDatabasePlacementError();
804
+ if (options.type === "ArrowFunctionExpression" && options.body.type === "BlockStatement") {
805
+ let returns = 0;
806
+ walk(options.body, (node) => {
807
+ if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") return false;
808
+ if (node.type === "ReturnStatement") returns++;
809
+ });
810
+ const unconditional = options.body.body.some((statement) => statement.type === "ReturnStatement" && statement.argument && unwrapExpression(statement.argument) === body);
811
+ if (returns !== 1 || !unconditional) throw authDatabasePlacementError();
812
+ }
813
+ const generateId = readObjectPropertyValue(objectLiteral(readObjectPropertyValue(objectLiteral(readObjectPropertyValue(body, "advanced")), "database")), "generateId");
814
+ if (generateId) assertAuthDatabaseIdStrategy(staticValue(generateId));
815
+ }
816
+ /** Object entries. `key` is empty for spread and computed keys. `value` is undefined for methods and accessors. */
817
+ function readObjectEntries(body) {
818
+ if (!body) return [];
819
+ return objectProperties(body).map((property) => ({
820
+ key: property.computed ? "" : property.key ?? "",
821
+ value: property.node.type === "Property" && property.node.kind === "init" && !property.node.method ? property.value : void 0
822
+ }));
823
+ }
824
+ function readObjectPropertyValue(body, property) {
825
+ return readObjectEntries(body).findLast((entry) => entry.key === property)?.value;
826
+ }
827
+ function hasObjectProperty(body, property) {
828
+ return readObjectEntries(body).some((entry) => entry.key === property);
829
+ }
830
+ function objectLiteral(value) {
831
+ return value?.type === "ObjectExpression" ? value : void 0;
832
+ }
833
+ function readStaticBooleanLiteral(expression) {
834
+ const value = expression && staticValue(expression);
835
+ return typeof value === "boolean" ? value : void 0;
836
+ }
837
+ function readStaticStringProperty(body, property, label) {
838
+ if (!hasObjectProperty(body, property)) return;
839
+ const value = staticString(readObjectPropertyValue(body, property));
840
+ if (typeof value === "undefined") throw authErrorDiagnostics.AUTH_C0001({ message: `\`defineAuth()\` ${label} must be an inline string literal.` });
841
+ if (value.trim().length === 0 || value !== value.trim()) throw authErrorDiagnostics.AUTH_C0002({ message: `\`defineAuth()\` ${label} must be a non-empty trimmed string.` });
842
+ return value;
843
+ }
844
+ function readStaticRouteProperty(body, property, label) {
845
+ const value = readStaticStringProperty(body, property, label);
846
+ if (typeof value !== "undefined" && !value.startsWith("/")) throw authErrorDiagnostics.AUTH_C0003({ message: `\`defineAuth()\` ${label} must start with \`/\`.` });
847
+ return value;
848
+ }
849
+ function assertOnlyObjectKeys(body, allowed, label) {
850
+ const unknownEntry = readObjectEntries(body).find((entry) => !entry.key || !allowed.has(entry.key));
851
+ if (!unknownEntry) return;
852
+ if (!unknownEntry.key) throw authErrorDiagnostics.AUTH_C0005({ message: `\`defineAuth()\` ${label} must use static object keys.` });
853
+ throw authErrorDiagnostics.AUTH_C0006({ message: `\`defineAuth()\` ${label} does not support the "${unknownEntry.key}" option.` });
854
+ }
855
+ function assertStaticObjectKeys(body, label) {
856
+ if (readObjectEntries(body).some((entry) => !entry.key)) throw authErrorDiagnostics.AUTH_C0007({ message: `\`defineAuth()\` ${label} must use static object keys.` });
857
+ }
858
+ function readAuthRouteConfig(body) {
859
+ const basePath = normalizeAuthBasePath(readStaticStringProperty(body, "basePath", "basePath"));
860
+ if (!hasObjectProperty(body, "route")) return basePath;
861
+ if (readStaticBooleanLiteral(readObjectPropertyValue(body, "route")) === false) return false;
862
+ throw authErrorDiagnostics.AUTH_C0008({ message: "`defineAuth()` route can only be `false` when provided." });
863
+ }
864
+ function assertLiteralAccessRoute(route, label) {
865
+ const message = accessRouteSyntaxError(route, label);
866
+ if (message) throw authErrorDiagnostics.AUTH_C0068({ message });
867
+ }
868
+ function readAuthAccessRoute(entry, index) {
869
+ const route = staticString(entry);
870
+ if (typeof route !== "undefined") {
871
+ if (!route.startsWith("/")) throw authErrorDiagnostics.AUTH_C0009({ message: `\`defineAuth()\` access.routes[${index}] must start with \`/\`.` });
872
+ assertLiteralAccessRoute(route, `access.routes[${index}]`);
873
+ return { route };
874
+ }
875
+ const routeObject = objectLiteral(entry && unwrapExpression(entry));
876
+ if (typeof routeObject === "undefined") throw authErrorDiagnostics.AUTH_C0010({ message: `\`defineAuth()\` access.routes[${index}] must be an inline route string or route object.` });
877
+ assertOnlyObjectKeys(routeObject, /* @__PURE__ */ new Set([
878
+ "authorize",
879
+ "method",
880
+ "route"
881
+ ]), `access.routes[${index}]`);
882
+ const resolvedRoute = readStaticRouteProperty(routeObject, "route", `access.routes[${index}].route`);
883
+ if (!resolvedRoute) throw authErrorDiagnostics.AUTH_C0011({ message: `\`defineAuth()\` access.routes[${index}].route is required.` });
884
+ assertLiteralAccessRoute(resolvedRoute, `access.routes[${index}].route`);
885
+ const method = readStaticStringProperty(routeObject, "method", `access.routes[${index}].method`);
886
+ const authorize = readObjectEntries(routeObject).find((entry) => entry.key === "authorize");
887
+ const resolved = { route: resolvedRoute };
888
+ if (authorize) resolved.authorize = true;
889
+ if (method) resolved.method = method;
890
+ return resolved;
891
+ }
892
+ function readAuthAccessRoutesConfig(body) {
893
+ const access = objectLiteral(readObjectPropertyValue(body, "access"));
894
+ if (!access || !hasObjectProperty(access, "routes")) return [];
895
+ const routes = readObjectPropertyValue(access, "routes");
896
+ if (routes?.type !== "ArrayExpression") throw authErrorDiagnostics.AUTH_C0012({ message: "`defineAuth()` access.routes must be an inline array." });
897
+ return routes.elements.map((entry, index) => readAuthAccessRoute(entry === null || entry.type === "SpreadElement" ? void 0 : entry, index));
898
+ }
899
+ function readAuthAccessPublicConfig(body) {
900
+ const access = objectLiteral(readObjectPropertyValue(body, "access"));
901
+ if (!access || !hasObjectProperty(access, "public")) return [];
902
+ const routes = readObjectPropertyValue(access, "public");
903
+ if (routes?.type !== "ArrayExpression") throw authErrorDiagnostics.AUTH_C0064({ message: "`defineAuth()` access.public must be an inline array." });
904
+ return routes.elements.map((entry, index) => {
905
+ const route = entry === null || entry.type === "SpreadElement" ? void 0 : staticString(entry);
906
+ if (typeof route === "undefined" || !route.startsWith("/")) throw authErrorDiagnostics.AUTH_C0064({ message: `\`defineAuth()\` access.public[${index}] must be an inline route string that starts with \`/\`.` });
907
+ return route;
908
+ });
909
+ }
910
+ /** The `authDatabase()` call of the `database` option, or undefined for any other value. */
911
+ function readAuthDatabaseCall(body, authDatabase) {
912
+ const value = readObjectPropertyValue(body, "database");
913
+ const expression = value && unwrapExpression(value);
914
+ return expression?.type === "CallExpression" && expression.callee.type === "Identifier" && authDatabase.has(expression.callee.name) ? expression : void 0;
915
+ }
916
+ /**
917
+ * The Database that gets the Better Auth tables (the name that `authDatabase()` receives, `"default"` without one), and
918
+ * the plugins and additional fields that add tables and columns.
919
+ */
920
+ function readAuthTablesConfig(definition) {
921
+ const { authDatabase, body, plugins } = definition;
922
+ const call = readAuthDatabaseCall(body, authDatabase);
923
+ if (!call) return false;
924
+ const [argument, ...rest] = call.arguments;
925
+ const name = argument === void 0 ? "default" : argument.type === "SpreadElement" || rest.length ? void 0 : staticString(argument);
926
+ if (name === void 0 || !name || name !== name.trim()) throw authErrorDiagnostics.AUTH_C0052({ message: "`authDatabase()` takes the Database name as one inline string literal, such as `authDatabase(\"content\")`, or no argument for the `default` Database." });
927
+ const additionalFields = readAuthAdditionalFields(body);
928
+ const schema = {
929
+ ...plugins.length ? { plugins } : {},
930
+ ...additionalFields ? { additionalFields } : {}
931
+ };
932
+ if (!plugins.length && !additionalFields) return { database: name };
933
+ resolveAuthTableSpecs(schema);
934
+ return {
935
+ database: name,
936
+ schema
937
+ };
938
+ }
939
+ /** Reports `true`, `false`, or an object literal with only `keys`: the removed placement forms, which create no storage. */
940
+ function isPlacementLiteral(expression, keys) {
941
+ if (readStaticBooleanLiteral(expression) !== void 0) return true;
942
+ const object = objectLiteral(expression);
943
+ return object !== void 0 && readObjectEntries(object).every((entry) => keys.has(entry.key));
944
+ }
945
+ /**
946
+ * `database` and `secondaryStorage` take Better Auth adapters only. A static Definition can hold only `authDatabase()` or
947
+ * `"memory"`.
948
+ */
949
+ function assertAuthStorageConfig(body, callback, authDatabase) {
950
+ const database = readObjectPropertyValue(body, "database");
951
+ if (hasObjectProperty(body, "database") && !readAuthDatabaseCall(body, authDatabase) && staticString(database) !== "memory") {
952
+ if (!callback || isPlacementLiteral(database, /* @__PURE__ */ new Set(["dedicated", "name"]))) throw authErrorDiagnostics.AUTH_C0014({ message: "`defineAuth()` database must be `authDatabase()` from `vite-hub/auth/database` or `\"memory\"`. `true` and `{ name }` do not create storage. Return another Better Auth adapter from the Definition callback." });
953
+ }
954
+ if (hasObjectProperty(body, "secondaryStorage")) {
955
+ const secondaryStorage = readObjectPropertyValue(body, "secondaryStorage");
956
+ if (!callback || isPlacementLiteral(secondaryStorage, /* @__PURE__ */ new Set(["store"]))) throw authErrorDiagnostics.AUTH_C0017({ message: "`defineAuth()` secondaryStorage takes only a Better Auth adapter, from the Definition callback. `true` and `{ store }` do not create storage." });
957
+ }
958
+ }
959
+ function resolveAuthViteConfig(options, rootDir = process.cwd(), discovery = {}) {
960
+ if (options === false) return;
961
+ const definition = discoverAuthDefinition(rootDir, discovery);
962
+ if (!definition) return;
963
+ const definitionObject = readDefinitionObjectBody(definition.handler);
964
+ if (typeof definitionObject === "undefined") throw authErrorDiagnostics.AUTH_C0019({ message: "`defineAuth()` options must be an inline object literal." });
965
+ const body = definitionObject.body;
966
+ assertStaticObjectKeys(body, "options");
967
+ assertAuthStorageConfig(body, definitionObject.callback, definitionObject.authDatabase);
968
+ const basePath = normalizeAuthBasePath(readStaticStringProperty(body, "basePath", "basePath"));
969
+ const abilities = discoverAuthAbilities(rootDir, discovery);
970
+ const publicRoutes = readAuthAccessPublicConfig(body);
971
+ return {
972
+ ...abilities ? { abilities } : {},
973
+ access: {
974
+ routes: readAuthAccessRoutesConfig(body),
975
+ ...publicRoutes.length ? { public: publicRoutes } : {}
976
+ },
977
+ basePath,
978
+ definition,
979
+ rootDir,
980
+ route: readAuthRouteConfig(body),
981
+ tables: readAuthTablesConfig(definitionObject),
982
+ ...!definitionObject.callback && !["database", "preset"].some((key) => hasObjectProperty(body, key)) ? { implicitMemory: true } : {}
983
+ };
984
+ }
985
+ //#endregion
986
+ //#region src/deployment-env.ts
987
+ const owners = ["auth"];
988
+ /**
989
+ * The variables that Auth reads on the deployed host. Better Auth signs with the first Better Auth secret that is
990
+ * set, else with the secret derived from `VITEHUB_SECRET`. `VITEHUB_ADMINS`, `VITEHUB_ADMIN_CLAIM`, and `VITEHUB_MEMBERS` are optional.
991
+ */
992
+ function authDeploymentEnv(config) {
993
+ if (!config) return [];
994
+ return [
995
+ {
996
+ names: [
997
+ "BETTER_AUTH_SECRET",
998
+ "BETTER_AUTH_SECRETS",
999
+ "AUTH_SECRET",
1000
+ "VITEHUB_SECRET"
1001
+ ],
1002
+ required: true,
1003
+ secret: true,
1004
+ hasDefault: false,
1005
+ owners
1006
+ },
1007
+ {
1008
+ names: ["VITEHUB_ADMINS"],
1009
+ required: false,
1010
+ secret: false,
1011
+ hasDefault: false,
1012
+ owners
1013
+ },
1014
+ {
1015
+ names: ["VITEHUB_ADMIN_CLAIM"],
1016
+ required: false,
1017
+ secret: true,
1018
+ hasDefault: false,
1019
+ owners
1020
+ },
1021
+ {
1022
+ names: ["VITEHUB_MEMBERS"],
1023
+ required: false,
1024
+ secret: false,
1025
+ hasDefault: false,
1026
+ owners
1027
+ }
1028
+ ];
1029
+ }
1030
+ //#endregion
1031
+ //#region src/table-names.ts
1032
+ /**
1033
+ * The schema keys of the Auth schemas and their SQL names. Its own module, so the Vite plugin lists the tables without
1034
+ * loading Drizzle or the schema module.
1035
+ */
1036
+ const authTableNames = {
1037
+ user: "user",
1038
+ session: "session",
1039
+ account: "account",
1040
+ verification: "verification",
1041
+ jwks: "jwks",
1042
+ oauthClient: "oauth_client",
1043
+ oauthResource: "oauth_resource",
1044
+ oauthClientResource: "oauth_client_resource",
1045
+ oauthRefreshToken: "oauth_refresh_token",
1046
+ oauthAccessToken: "oauth_access_token",
1047
+ oauthConsent: "oauth_consent",
1048
+ oauthClientAssertion: "oauth_client_assertion",
1049
+ rateLimit: "rate_limit",
1050
+ organization: "organization",
1051
+ member: "member",
1052
+ invitation: "invitation",
1053
+ passkey: "passkey"
1054
+ };
1055
+ //#endregion
1056
+ //#region src/existing-tables.ts
1057
+ function isRecord(value) {
1058
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1059
+ }
1060
+ function strings(value) {
1061
+ return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
1062
+ }
1063
+ /** The snapshot of the newest migration folder, which Drizzle Kit compares the schema with. */
1064
+ function latestSnapshot(migrationsDir) {
1065
+ if (!existsSync(migrationsDir)) return;
1066
+ const latest = readdirSync(migrationsDir, { withFileTypes: true }).filter((entry) => entry.isDirectory() && existsSync(join(migrationsDir, entry.name, "snapshot.json"))).map((entry) => entry.name).sort().at(-1);
1067
+ if (!latest) return;
1068
+ const snapshot = JSON.parse(readFileSync(join(migrationsDir, latest, "snapshot.json"), "utf8"));
1069
+ if (!isRecord(snapshot) || snapshot.dialect !== "sqlite" || !Array.isArray(snapshot.ddl)) return;
1070
+ return snapshot.ddl.filter(isRecord);
1071
+ }
1072
+ /**
1073
+ * Reads the tables of `tableNames` from the latest migration snapshot in `migrationsDir`. Returns `undefined` when the
1074
+ * folder has no SQLite snapshot, and leaves out the tables that the snapshot does not have.
1075
+ */
1076
+ function readAuthExistingTables(migrationsDir, tableNames) {
1077
+ const ddl = latestSnapshot(migrationsDir);
1078
+ if (!ddl) return;
1079
+ const wanted = new Set(tableNames);
1080
+ const tables = {};
1081
+ const table = (name) => tables[name] ??= {
1082
+ columns: {},
1083
+ indexes: [],
1084
+ uniques: [],
1085
+ foreignKeys: []
1086
+ };
1087
+ for (const entity of ddl) if (entity.entityType === "tables" && typeof entity.name === "string" && wanted.has(entity.name)) table(entity.name);
1088
+ for (const entity of ddl) {
1089
+ if (typeof entity.table !== "string" || typeof entity.name !== "string" || !Object.hasOwn(tables, entity.table)) continue;
1090
+ const target = tables[entity.table];
1091
+ if (entity.entityType === "columns") target.columns[entity.name] = {
1092
+ notNull: entity.notNull === true,
1093
+ ...typeof entity.default === "string" ? { default: entity.default } : {}
1094
+ };
1095
+ else if (entity.entityType === "indexes" && Array.isArray(entity.columns)) {
1096
+ const columns = entity.columns.filter(isRecord);
1097
+ if (columns.length !== entity.columns.length || columns.some((column) => column.isExpression === true || typeof column.value !== "string")) continue;
1098
+ target.indexes.push({
1099
+ name: entity.name,
1100
+ columns: columns.map((column) => column.value),
1101
+ unique: entity.isUnique === true
1102
+ });
1103
+ } else if (entity.entityType === "uniques") target.uniques.push({
1104
+ ...entity.nameExplicit === true ? { name: entity.name } : {},
1105
+ columns: strings(entity.columns)
1106
+ });
1107
+ else if (entity.entityType === "fks" && typeof entity.tableTo === "string") target.foreignKeys.push({
1108
+ ...entity.nameExplicit === true ? { name: entity.name } : {},
1109
+ columns: strings(entity.columns),
1110
+ tableTo: entity.tableTo,
1111
+ columnsTo: strings(entity.columnsTo),
1112
+ onDelete: typeof entity.onDelete === "string" ? entity.onDelete : "NO ACTION",
1113
+ onUpdate: typeof entity.onUpdate === "string" ? entity.onUpdate : "NO ACTION"
1114
+ });
1115
+ }
1116
+ return tables;
1117
+ }
1118
+ //#endregion
1119
+ //#region src/vite.ts
1120
+ const AUTH_ABILITIES_ID = "#vitehub/auth/abilities";
1121
+ const AUTH_CLIENT_ID = "#vitehub/auth/client";
1122
+ const AUTH_DEFINITION_ID = "#vitehub/auth/definition";
1123
+ const AUTH_SERVER_ID = "#vitehub/auth/server";
1124
+ const AUTH_VITE_PLUGIN_NAME = "@vite-hub/auth/vite";
1125
+ const RESOLVED_AUTH_ABILITIES_ID = "\0virtual:vitehub/auth/abilities";
1126
+ const RESOLVED_AUTH_CLIENT_ID = "\0virtual:vitehub/auth/client";
1127
+ const RESOLVED_AUTH_DEFINITION_ID = `\0${AUTH_DEFINITION_ID}`;
1128
+ const RESOLVED_AUTH_SERVER_ID = `\0${AUTH_SERVER_ID}`;
1129
+ const authPackageName = "@vite-hub/auth";
1130
+ const envServerModuleId = "#vitehub/env/server";
1131
+ const envVitePluginName = "@vite-hub/env/vite";
1132
+ const generatedAuthAccessMiddlewareHandler = ".vitehub/auth/access-middleware.ts";
1133
+ const generatedAuthRouteHandler = ".vitehub/auth/route.ts";
1134
+ const generatedAuthSchema = ".vitehub/auth/schema.ts";
1135
+ const cachedAccessRouteGuardName = "vite-hub/auth-cached-access-route-guard";
1136
+ const memoryDatabaseGuardName = "vite-hub/auth-memory-database-guard";
1137
+ const mergeNoExternal = createNoExternalAddition(authPackageName);
1138
+ /**
1139
+ * A module that builds the Auth tables with the plugins and additional fields of the Definition, and keeps the SQLite
1140
+ * tables that the Database has already as `existing` describes them.
1141
+ */
1142
+ function renderAuthSchemaModule(schema, existing, importBase) {
1143
+ const options = JSON.stringify(schema);
1144
+ return [
1145
+ "// Generated by the Auth Vite plugin from the plugins and additional fields of the Auth Definition, and from the Auth",
1146
+ "// tables of the latest migration of the Database.",
1147
+ `import { createAuthPostgresSchema, createAuthSqliteSchema } from ${JSON.stringify(`${importBase}/schema`)}`,
1148
+ "",
1149
+ `export const authSqliteSchema = createAuthSqliteSchema(${options}${existing ? `, ${JSON.stringify(existing)}` : ""})`,
1150
+ `export const authPostgresSchema = createAuthPostgresSchema(${options})`,
1151
+ ""
1152
+ ].join("\n");
1153
+ }
1154
+ /**
1155
+ * The dialect and the migrations folder of the Database that gets the Auth tables, read from its Definition without
1156
+ * running it. Without a Database Definition, the Database integration adds the implicit `default` Database, which uses
1157
+ * SQLite unless another contribution needs Postgres.
1158
+ */
1159
+ async function readTargetDatabase(context, database) {
1160
+ const { discoverDatabaseDefinitions, getDefaultMigrationsDir, readDatabaseDefinitionDialect } = await import("@vite-hub/database/config");
1161
+ const { collectDatabaseContributions } = await import("@vite-hub/database/vite");
1162
+ const plugins = (await flattenPluginOptions(context.plugins)).filter((plugin) => Reflect.get(plugin, "name") !== AUTH_VITE_PLUGIN_NAME);
1163
+ const contributions = await collectDatabaseContributions(plugins, {
1164
+ ...context,
1165
+ plugins
1166
+ });
1167
+ const serverDirs = context.serverDirs?.slice();
1168
+ const target = discoverDatabaseDefinitions(context.rootDir, {
1169
+ contributions,
1170
+ serverDirs
1171
+ }).find((definition) => definition.name === database);
1172
+ if (!target) return {
1173
+ dialect: "sqlite",
1174
+ migrationsDir: resolve(serverDirs?.[0] ?? resolve(context.rootDir, "server"), "databases", database, "migrations")
1175
+ };
1176
+ return {
1177
+ dialect: readDatabaseDefinitionDialect(target.handler),
1178
+ migrationsDir: resolve(context.rootDir, getDefaultMigrationsDir(context.rootDir, target, serverDirs))
1179
+ };
1180
+ }
1181
+ /** Lists the Auth Definition as a serializable inspection summary. */
1182
+ function inspectAuthDefinitions(options) {
1183
+ return summarizeDefinitions(options.projectRoot, discoverAuthDefinitions(options.rootDir, { serverDirs: options.serverDirs }), "server-auth");
1184
+ }
1185
+ function createAuthNitroConfig(plugin, options) {
1186
+ const viteConfig = {
1187
+ root: options.projectRoot,
1188
+ nitro: options.nitro,
1189
+ ...options.serverDirs ? { [VITEHUB_SERVER_DIRS]: options.serverDirs } : {}
1190
+ };
1191
+ if (plugin.config && typeof plugin.config === "function") {
1192
+ const dev = options.nitro.dev === true;
1193
+ plugin.config.call({}, viteConfig, {
1194
+ command: dev ? "serve" : "build",
1195
+ isPreview: false,
1196
+ isSsrBuild: true,
1197
+ mode: dev ? "development" : "production"
1198
+ });
1199
+ }
1200
+ return viteConfig.nitro;
1201
+ }
1202
+ function renderAuthDefinitionModule(config, options = { serverEnv: false }) {
1203
+ if (!config) return "export const definition = undefined\nexport default definition\n";
1204
+ return [
1205
+ `import definition from ${JSON.stringify(config.definition.handler)}`,
1206
+ ...options.serverEnv ? [
1207
+ `import { setAuthRuntimeEnvResolver } from ${JSON.stringify(privateAuthImport(options.importBase ?? authPackageName, "runtime/server"))}`,
1208
+ `import { useServerEnv } from ${JSON.stringify(envServerModuleId)}`,
1209
+ "setAuthRuntimeEnvResolver(useServerEnv, definition)"
1210
+ ] : [],
1211
+ "export { definition }",
1212
+ "export default definition",
1213
+ ""
1214
+ ].join("\n");
1215
+ }
1216
+ /** Private Auth entries of the distribution. */
1217
+ function privateAuthImport(importBase, entry) {
1218
+ return importBase === "vite-hub/auth" ? ownModule(import.meta.url, entry) : `${importBase}/${entry}`;
1219
+ }
1220
+ /** The rules of `shared/abilities.ts` for the server and the app, or no rules. */
1221
+ function renderAuthAbilitiesModule(config) {
1222
+ return config?.abilities ? `export { default } from ${JSON.stringify(config.abilities)}\n` : "export default {}\n";
1223
+ }
1224
+ function renderAuthServerModule(options = {}) {
1225
+ const importBase = options.importBase ?? authPackageName;
1226
+ const serverImport = `${importBase}/server`;
1227
+ return [
1228
+ `export * from ${JSON.stringify(privateAuthImport(importBase, "internal/server"))}`,
1229
+ `export { default } from ${JSON.stringify(serverImport)}`,
1230
+ ""
1231
+ ].join("\n");
1232
+ }
1233
+ function renderAuthRouteHandler() {
1234
+ return [`export { default } from ${JSON.stringify(AUTH_SERVER_ID)}`, ""].join("\n");
1235
+ }
1236
+ function renderAuthAccessMiddlewareHandler(config, importBase = authPackageName) {
1237
+ const routes = JSON.stringify(config?.access.routes ?? []);
1238
+ const publicRoutes = config?.access.public?.length ? `, ${JSON.stringify(config.access.public)}` : "";
1239
+ return [
1240
+ `import { createLazyAuthAccessHandler } from ${JSON.stringify(privateAuthImport(importBase, "runtime/server"))}`,
1241
+ "",
1242
+ `export default createLazyAuthAccessHandler(${routes}, () => import(${JSON.stringify(AUTH_SERVER_ID)})${publicRoutes})`,
1243
+ ""
1244
+ ].join("\n");
1245
+ }
1246
+ /** A relative `import()` type specifier that resolves under NodeNext and bundler resolution: `auth.ts` becomes `auth.js`. */
1247
+ function typeImportSpecifier(from, file) {
1248
+ const path = relative(from, file).replaceAll("\\", "/").replace(/\.([cm]?)ts$/, ".$1js");
1249
+ return path.startsWith(".") ? path : `./${path}`;
1250
+ }
1251
+ function authAmbientTypesPath(root) {
1252
+ return resolve(root, ".vitehub", "types", "auth.d.ts");
1253
+ }
1254
+ function authServerTypesPath(root) {
1255
+ return resolve(root, ".vitehub", "types", "auth-server.d.ts");
1256
+ }
1257
+ function renderAuthAmbientTypes(options = { serverEnv: false }) {
1258
+ const entries = [
1259
+ ...options.definition ? [`definition: typeof import(${JSON.stringify(options.definition)}).default`] : [],
1260
+ ...options.abilities ? [`abilities: typeof import(${JSON.stringify(options.abilities)}).default`] : [],
1261
+ ...options.client ? [`client: typeof import(${JSON.stringify(options.client)}).default`] : []
1262
+ ];
1263
+ const registry = entries.length ? [`interface AuthRegistry { ${entries.join("; ")} }`] : [];
1264
+ if (options.serverEnv) return [
1265
+ `import type { ServerEnv } from ${JSON.stringify(envServerModuleId)}`,
1266
+ "",
1267
+ "declare global {",
1268
+ " namespace ViteHub {",
1269
+ " interface AuthRuntimeEnv extends ServerEnv {}",
1270
+ ...registry.map((line) => ` ${line}`),
1271
+ " }",
1272
+ "}",
1273
+ ""
1274
+ ].join("\n");
1275
+ return registry.length ? [
1276
+ "declare namespace ViteHub {",
1277
+ ...registry.map((line) => ` ${line}`),
1278
+ "}",
1279
+ ""
1280
+ ].join("\n") : "export {}\n";
1281
+ }
1282
+ /**
1283
+ * The declaration of the virtual module. It stays out of a file with imports, which would make it an augmentation of
1284
+ * a module that must already resolve. When only the bundler resolves `#vitehub/auth/server`, the tsconfig would not
1285
+ * find it and the types of everything that imports the Auth handlers would be `any`.
1286
+ */
1287
+ function renderAuthServerTypes(importBase = authPackageName) {
1288
+ const serverImport = `${importBase}/server`;
1289
+ return [
1290
+ `declare module ${JSON.stringify(AUTH_SERVER_ID)} {`,
1291
+ ` export * from ${JSON.stringify(privateAuthImport(importBase, "internal/server"))}`,
1292
+ ` export { default } from ${JSON.stringify(serverImport)}`,
1293
+ "}",
1294
+ ""
1295
+ ].join("\n");
1296
+ }
1297
+ async function refreshAuthGeneratedFiles(root, config, options = {}) {
1298
+ await Promise.all([
1299
+ writeFileIfChanged(resolve(root, generatedAuthAccessMiddlewareHandler), renderAuthAccessMiddlewareHandler(config, options.importBase)),
1300
+ writeFileIfChanged(authAmbientTypesPath(root), renderAuthAmbientTypes({
1301
+ abilities: config?.abilities && typeImportSpecifier(dirname(authAmbientTypesPath(root)), config.abilities),
1302
+ client: options.client && typeImportSpecifier(dirname(authAmbientTypesPath(root)), options.client),
1303
+ definition: config && typeImportSpecifier(dirname(authAmbientTypesPath(root)), config.definition.handler),
1304
+ serverEnv: Boolean(options.serverEnv)
1305
+ })),
1306
+ writeFileIfChanged(authServerTypesPath(root), renderAuthServerTypes(options.importBase)),
1307
+ writeFileIfChanged(resolve(root, generatedAuthRouteHandler), renderAuthRouteHandler())
1308
+ ]);
1309
+ }
1310
+ function hasServerEnvIntegration(config) {
1311
+ return Array.isArray(config?.plugins) && config.plugins.some((plugin) => plugin.name === envVitePluginName);
1312
+ }
1313
+ function cloneNitroConfig(value) {
1314
+ return value && typeof value === "object" && !Array.isArray(value) ? { ...value } : {};
1315
+ }
1316
+ function authRoutePattern(route) {
1317
+ return `${route}/**`;
1318
+ }
1319
+ const authApplicationBaseURLName = "__VITEHUB_AUTH_APP_BASE_URL__";
1320
+ const authDevName = "__VITEHUB_AUTH_DEV__";
1321
+ /** Return Nitro `baseURL` when the host serves the app below a path, such as Nuxt `app.baseURL`. */
1322
+ function nitroApplicationBaseURL(value) {
1323
+ const nitro = cloneNitroConfig(value);
1324
+ const baseURL = typeof nitro.baseURL === "string" ? nitro.baseURL : "/";
1325
+ return baseURL.split("/").some(Boolean) ? baseURL : void 0;
1326
+ }
1327
+ /** Fails a production build, not the first sign-in. `nuxt prepare` also creates Nitro, but it does not build. */
1328
+ const memoryDatabaseGuard = {
1329
+ name: memoryDatabaseGuardName,
1330
+ setup(nitro) {
1331
+ nitro.hooks.hook(nitro.options.builder === false ? "build:before" : "build:config", () => Promise.reject(authMemoryDatabaseError()));
1332
+ }
1333
+ };
1334
+ function mergeNitroAuthHandler(value, config, dev) {
1335
+ const nitro = cloneNitroConfig(value);
1336
+ if (!config) return nitro;
1337
+ nitro.replace = {
1338
+ ...cloneNitroConfig(nitro.replace),
1339
+ [authDevName]: JSON.stringify(dev)
1340
+ };
1341
+ const applicationBaseURL = nitroApplicationBaseURL(nitro);
1342
+ if (applicationBaseURL) nitro.replace = {
1343
+ ...cloneNitroConfig(nitro.replace),
1344
+ [authApplicationBaseURLName]: JSON.stringify(applicationBaseURL)
1345
+ };
1346
+ const kit = createNitroServerKit(nitro);
1347
+ const authHandlers = [...config.route === false ? [] : [{
1348
+ handler: resolve(resolveViteHubProjectRoot(config.rootDir), generatedAuthRouteHandler),
1349
+ lazy: true,
1350
+ route: authRoutePattern(config.route)
1351
+ }], ...config.access.routes.length > 0 ? [{
1352
+ handler: resolve(resolveViteHubProjectRoot(config.rootDir), generatedAuthAccessMiddlewareHandler),
1353
+ middleware: true,
1354
+ route: "/**"
1355
+ }] : []];
1356
+ for (const handler of authHandlers) kit.addHandler(handler);
1357
+ const merged = kit.config;
1358
+ const guards = /* @__PURE__ */ new Set([cachedAccessRouteGuardName, memoryDatabaseGuardName]);
1359
+ const modules = (Array.isArray(merged.modules) ? merged.modules : []).filter((module) => !guards.has(Reflect.get(Object(module), "name")));
1360
+ if (!dev && config.implicitMemory) modules.push(memoryDatabaseGuard);
1361
+ if (modules.length || Array.isArray(merged.modules)) merged.modules = modules;
1362
+ if (config.access.routes.length > 0) {
1363
+ const { routes, public: publicRoutes = [] } = config.access;
1364
+ merged.modules = [...modules, {
1365
+ name: cachedAccessRouteGuardName,
1366
+ setup(nitro) {
1367
+ const check = () => assertNoCachedAccessRoutes(routes, nitro.options.routeRules, nitro.options.baseURL, publicRoutes);
1368
+ nitro.hooks.hook(nitro.options.builder === false ? "build:before" : "build:config", check);
1369
+ nitro.hooks.hook("build:reload", () => check().catch((error) => nitro.logger.warn(error)));
1370
+ }
1371
+ }];
1372
+ }
1373
+ return merged;
1374
+ }
1375
+ function hubAuth(options, internalOptions = {}) {
1376
+ const importBase = internalOptions.importBase ?? authPackageName;
1377
+ let resolved;
1378
+ let runtimeConfig;
1379
+ let clientFile;
1380
+ let serverDirs;
1381
+ let serverEnv = false;
1382
+ function refreshRuntimeConfig() {
1383
+ if (!resolved) return;
1384
+ runtimeConfig = resolveAuthViteConfig(options, resolved.root, { serverDirs });
1385
+ runtimeConfig ??= resolveAuthViteConfig(options, resolveViteHubProjectRoot(resolved.root), { serverDirs });
1386
+ resetAuth();
1387
+ return runtimeConfig;
1388
+ }
1389
+ return {
1390
+ name: AUTH_VITE_PLUGIN_NAME,
1391
+ enforce: "pre",
1392
+ api: {
1393
+ deploymentEnv: () => authDeploymentEnv(runtimeConfig),
1394
+ getConfig: () => runtimeConfig,
1395
+ refresh: refreshRuntimeConfig
1396
+ },
1397
+ vitehub: {
1398
+ cli: async () => options === false ? void 0 : (await import("./cli.js")).createAuthCliContributor(),
1399
+ async databases(context) {
1400
+ const authOptions = options;
1401
+ if (authOptions === false) return [];
1402
+ const root = context.projectRoot ?? context.root;
1403
+ const discovery = { serverDirs: context.serverDirs?.slice() ?? serverDirs };
1404
+ const config = resolveAuthViteConfig(authOptions, root, discovery) ?? resolveAuthViteConfig(authOptions, resolveViteHubProjectRoot(root), discovery);
1405
+ if (!config?.tables) return [];
1406
+ const { database, schema } = config.tables;
1407
+ const schemaModule = resolve(config.rootDir, generatedAuthSchema);
1408
+ const { dialect, migrationsDir } = await readTargetDatabase(context, database);
1409
+ const tables = schema ? Object.fromEntries(Object.keys(resolveAuthTableSpecs(schema)).map((model) => [model, authSqlName(model)])) : authTableNames;
1410
+ const existing = dialect === "sqlite" ? readAuthExistingTables(migrationsDir, Object.values(tables)) : void 0;
1411
+ const adopted = existing && Object.keys(existing).length ? existing : void 0;
1412
+ const generated = Boolean(schema || adopted);
1413
+ if (generated) await writeFileIfChanged(schemaModule, renderAuthSchemaModule(schema ?? {}, adopted, importBase));
1414
+ else await rm(schemaModule, { force: true });
1415
+ return [{
1416
+ name: "auth",
1417
+ database,
1418
+ dialect,
1419
+ definition: {
1420
+ module: generated ? schemaModule : `${importBase}/schema`,
1421
+ export: dialect === "postgresql" ? "authPostgresSchema" : "authSqliteSchema"
1422
+ },
1423
+ tables,
1424
+ reason: "Stores the Better Auth users, sessions, accounts, and verifications, the admin() fields, the tables and columns of the plugins and additional fields that the Auth Definition adds, and the Console MCP OAuth clients and tokens of authDatabase()."
1425
+ }];
1426
+ },
1427
+ inspect: () => {
1428
+ if (options === false) return;
1429
+ return { definitions: [{
1430
+ kind: "auth",
1431
+ label: "Auth",
1432
+ list: () => {
1433
+ const rootDir = resolve(resolved?.root ?? process.cwd());
1434
+ return inspectAuthDefinitions({
1435
+ projectRoot: resolveViteHubProjectRoot(rootDir),
1436
+ rootDir,
1437
+ serverDirs
1438
+ });
1439
+ }
1440
+ }] };
1441
+ }
1442
+ },
1443
+ config(config, env) {
1444
+ const configRoot = config.root || process.cwd();
1445
+ serverDirs = config["__vitehubServerDirs"] ?? serverDirs;
1446
+ const authConfig = resolveAuthViteConfig(options, configRoot, { serverDirs }) ?? resolveAuthViteConfig(options, resolveViteHubProjectRoot(configRoot), { serverDirs });
1447
+ const dev = env?.command === "serve";
1448
+ const nitro = mergeNitroAuthHandler(config.nitro, authConfig, dev);
1449
+ const hasNitroHandlers = Boolean(authConfig && (authConfig.route !== false || authConfig.access.routes.length > 0));
1450
+ const applicationBaseURL = authConfig ? nitroApplicationBaseURL(nitro) : void 0;
1451
+ const hasMemoryDatabaseGuard = Boolean(authConfig?.implicitMemory && !dev);
1452
+ if (hasNitroHandlers || applicationBaseURL || hasMemoryDatabaseGuard) Object.assign(config, { nitro });
1453
+ const contribution = {
1454
+ optimizeDeps: {
1455
+ exclude: [authPackageName, "vite-hub/auth"],
1456
+ include: [`${authPackageName} > better-auth/vue`]
1457
+ },
1458
+ ssr: { noExternal: mergeNoExternal(config.ssr?.noExternal) },
1459
+ server: { watch: { ignored: generatedViteHubWatchIgnoredAddition(config.server?.watch?.ignored) } }
1460
+ };
1461
+ contribution.define = {
1462
+ [authDevName]: JSON.stringify(dev),
1463
+ ...applicationBaseURL ? { [authApplicationBaseURLName]: JSON.stringify(applicationBaseURL) } : {}
1464
+ };
1465
+ return contribution;
1466
+ },
1467
+ async configResolved(config) {
1468
+ resolved = config;
1469
+ serverEnv = hasServerEnvIntegration(config);
1470
+ const runtimeConfig = refreshRuntimeConfig();
1471
+ clientFile = options === false ? void 0 : discoverAuthClient(config.root);
1472
+ await refreshAuthGeneratedFiles(resolveViteHubProjectRoot(config.root), runtimeConfig, {
1473
+ client: clientFile,
1474
+ importBase,
1475
+ serverEnv
1476
+ });
1477
+ },
1478
+ configureServer(server) {
1479
+ const root = server.config.root;
1480
+ const projectRoot = resolveViteHubProjectRoot(root);
1481
+ const candidates = new Set([root, projectRoot].flatMap((directory) => {
1482
+ const files = authAbilitiesCandidates(directory, { serverDirs });
1483
+ return [...files.app, ...files.layers];
1484
+ }));
1485
+ server.watcher.add([...new Set([...candidates].map(dirname))]);
1486
+ let refresh = Promise.resolve();
1487
+ const onAbilitiesFile = (file) => {
1488
+ if (!candidates.has(resolve(file))) return;
1489
+ refresh = refresh.then(async () => {
1490
+ const config = refreshRuntimeConfig();
1491
+ await refreshAuthGeneratedFiles(projectRoot, config, {
1492
+ client: clientFile,
1493
+ importBase,
1494
+ serverEnv
1495
+ });
1496
+ for (const environment of Object.values(server.environments)) for (const id of [
1497
+ RESOLVED_AUTH_ABILITIES_ID,
1498
+ RESOLVED_AUTH_DEFINITION_ID,
1499
+ RESOLVED_AUTH_SERVER_ID
1500
+ ]) {
1501
+ const module = environment.moduleGraph.getModuleById(id);
1502
+ if (module) environment.moduleGraph.invalidateModule(module);
1503
+ }
1504
+ server.ws.send({ type: "full-reload" });
1505
+ }).catch((error) => server.config.logger.error(String(error)));
1506
+ };
1507
+ server.watcher.on("add", onAbilitiesFile);
1508
+ server.watcher.on("unlink", onAbilitiesFile);
1509
+ },
1510
+ configEnvironment(name, config) {
1511
+ if (!isServerEnvironment(name, config)) return;
1512
+ return { resolve: { noExternal: mergeNoExternal(config.resolve?.noExternal) } };
1513
+ },
1514
+ async handleHotUpdate(context) {
1515
+ const changed = context.file.replace(/\\/g, "/");
1516
+ if (changed !== runtimeConfig?.definition.handler.replace(/\\/g, "/") && !/\/?server\.auth\.(?:c|m)?[jt]s$/i.test(changed) && !/\/server\/auth\.(?:c|m)?[jt]s$/i.test(changed)) return;
1517
+ const config = refreshRuntimeConfig();
1518
+ await refreshAuthGeneratedFiles(resolveViteHubProjectRoot(context.server.config.root), config, {
1519
+ client: clientFile,
1520
+ importBase,
1521
+ serverEnv
1522
+ });
1523
+ for (const id of [
1524
+ RESOLVED_AUTH_ABILITIES_ID,
1525
+ RESOLVED_AUTH_DEFINITION_ID,
1526
+ RESOLVED_AUTH_SERVER_ID
1527
+ ]) {
1528
+ const module = context.server.moduleGraph.getModuleById(id);
1529
+ if (module) context.server.moduleGraph.invalidateModule(module);
1530
+ }
1531
+ },
1532
+ resolveId: {
1533
+ filter: { id: /^#vitehub\/auth\/(?:abilities|client|definition|server)$/ },
1534
+ handler(id) {
1535
+ if (id === "#vitehub/auth/abilities") return RESOLVED_AUTH_ABILITIES_ID;
1536
+ if (id === "#vitehub/auth/client") return clientFile ?? RESOLVED_AUTH_CLIENT_ID;
1537
+ if (id === "#vitehub/auth/definition") return RESOLVED_AUTH_DEFINITION_ID;
1538
+ if (id === "#vitehub/auth/server") return RESOLVED_AUTH_SERVER_ID;
1539
+ }
1540
+ },
1541
+ load: {
1542
+ filter: { id: /^\0(?:virtual:vitehub\/auth\/(?:abilities|client)|#vitehub\/auth\/(?:definition|server))$/ },
1543
+ handler(id) {
1544
+ if (id === RESOLVED_AUTH_ABILITIES_ID) return renderAuthAbilitiesModule(runtimeConfig);
1545
+ if (id === RESOLVED_AUTH_CLIENT_ID) return "export default undefined\n";
1546
+ if (id === RESOLVED_AUTH_DEFINITION_ID) return renderAuthDefinitionModule(runtimeConfig, {
1547
+ importBase,
1548
+ serverEnv
1549
+ });
1550
+ if (id === RESOLVED_AUTH_SERVER_ID) return renderAuthServerModule({ importBase });
1551
+ }
1552
+ }
1553
+ };
1554
+ }
1555
+ //#endregion
1556
+ export { AUTH_VITE_PLUGIN_NAME as a, resolveAuthViteConfig as c, resolveViteHubProjectRoot as d, AUTH_SERVER_ID as i, authAbilitiesCandidates as l, AUTH_CLIENT_ID as n, createAuthNitroConfig as o, AUTH_DEFINITION_ID as r, hubAuth as s, AUTH_ABILITIES_ID as t, resolveNuxtServerDirs as u };