@vite-hub/auth 0.6.1 → 0.8.0

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 (78) hide show
  1. package/README.md +86 -12
  2. package/dist/{abilities-BYOcyQ9B.d.ts → abilities-IOwpkcz4.d.ts} +1 -1
  3. package/dist/abilities.d.ts +1 -1
  4. package/dist/{ability-error-D3-u8k1A.js → ability-error-DgR91Jwc.js} +1 -1
  5. package/dist/{access-pages-9aKr6z-k.js → access-pages-C69nwa99.js} +10 -3
  6. package/dist/agent.d.ts +2 -3
  7. package/dist/agent.js +31 -12
  8. package/dist/{auth-instance-BWiRS9QZ.js → auth-instance-WeEK1zDd.js} +174 -64
  9. package/dist/{cli-C5pAfY4x.d.ts → cli-DL7uCAvz.d.ts} +15 -0
  10. package/dist/cli.d.ts +1 -1
  11. package/dist/cli.js +1 -1
  12. package/dist/client-extension-BgUlm6hy.d.ts +33 -0
  13. package/dist/client-request-B1DCz3a9.js +29 -0
  14. package/dist/{console-runtime-DMH1I2fl.d.ts → console-runtime-C71weVrt.d.ts} +1 -1
  15. package/dist/{console-runtime-CaIXVtB_.js → console-runtime-Dk3j4Jmz.js} +5 -3
  16. package/dist/console-runtime.d.ts +2 -2
  17. package/dist/console-runtime.js +1 -1
  18. package/dist/console.d.ts +1 -1
  19. package/dist/database-options-Cms7BI3c.js +36 -0
  20. package/dist/{database-schema-options-peXHNLkJ.js → database-schema-options-IlHEeUBK.js} +1 -1
  21. package/dist/database.d.ts +1 -1
  22. package/dist/database.js +13 -8
  23. package/dist/{definition-BypPLIbI.js → definition-EpeI5LUG.js} +18 -4
  24. package/dist/{error-diagnostics-CUPwukgE.js → error-diagnostics-DZHuHXPP.js} +46 -5
  25. package/dist/{events-BXU1_9mc.js → events-Cm7Iwq47.js} +1 -1
  26. package/dist/extension-BWmjJhoN.d.ts +59 -0
  27. package/dist/extension-mCx4TrsO.js +133 -0
  28. package/dist/forward.js +1 -1
  29. package/dist/index.d.ts +4 -3
  30. package/dist/index.js +5 -3
  31. package/dist/internal/server.d.ts +3 -3
  32. package/dist/internal/server.js +5 -4
  33. package/dist/{mcp-config-C7srUMIZ.js → mcp-config-Bbr8kQxm.js} +9 -1
  34. package/dist/{mcp-token-CuqdbBy8.js → mcp-token-BleQZK6H.js} +52 -11
  35. package/dist/{mcp-token-CmQbXbTu.d.ts → mcp-token-CxpopXmK.d.ts} +5 -2
  36. package/dist/mcp.d.ts +2 -2
  37. package/dist/mcp.js +27 -6
  38. package/dist/{members-CwPIx10t.js → members-7OMdqha_.js} +188 -152
  39. package/dist/nuxt.d.ts +4 -14
  40. package/dist/nuxt.js +53 -20
  41. package/dist/{own-access-BNcxKrDl.d.ts → own-access-CGiai2L3.d.ts} +1 -1
  42. package/dist/{page-tools-shared-CtoKaNQZ.js → page-tools-shared-dVJBPPTk.js} +8 -0
  43. package/dist/presets.js +1 -1
  44. package/dist/roles-BGi8CyBG.js +17 -0
  45. package/dist/runtime/client-request-plugin.d.ts +2 -1
  46. package/dist/runtime/client-request-plugin.js +8 -5
  47. package/dist/runtime/console.d.ts +1 -1
  48. package/dist/runtime/console.js +2 -2
  49. package/dist/runtime/empty-abilities.d.ts +1 -1
  50. package/dist/runtime/empty-client.d.ts +3 -0
  51. package/dist/runtime/empty-client.js +3 -1
  52. package/dist/runtime/empty-definition.d.ts +1 -1
  53. package/dist/runtime/server.d.ts +4 -3
  54. package/dist/runtime/server.js +7 -4
  55. package/dist/runtime/vue-nuxt.js +27 -11
  56. package/dist/schema.d.ts +32 -14
  57. package/dist/schema.js +21 -14
  58. package/dist/{server-Iru6jcnW.js → server-5t-HA7I1.js} +80 -328
  59. package/dist/{server-C4Kni3Vj.d.ts → server-DyP1v-sZ.d.ts} +39 -7
  60. package/dist/{server-BHniJi2m.d.ts → server-mmp8EfcE.d.ts} +4 -2
  61. package/dist/server.d.ts +6 -3
  62. package/dist/server.js +9 -3
  63. package/dist/{session-cookies-fR6Pv4kD.js → session-cookies-BNtY3hMp.js} +4 -16
  64. package/dist/{set-cookie-DVfi-nJX.js → set-cookie-Bva-P-_C.js} +1 -1
  65. package/dist/{table-specs-CCSY4tiS.js → table-specs-Bm7QJCbu.js} +1 -1
  66. package/dist/{table-specs-P4LvbOlX.d.ts → table-specs-BxKeFD_y.d.ts} +5 -0
  67. package/dist/test.d.ts +1 -1
  68. package/dist/test.js +2 -2
  69. package/dist/{types-DmH31d2t.d.ts → types-CnO5bHEF.d.ts} +40 -6
  70. package/dist/{vite-CpWhT1Wi.js → vite-7I1bJvqA.js} +686 -244
  71. package/dist/vite-CZ_Z6IR3.d.ts +28 -0
  72. package/dist/vite.d.ts +41 -6
  73. package/dist/vite.js +1 -1
  74. package/dist/vue.d.ts +4 -3
  75. package/dist/vue.js +39 -4
  76. package/package.json +9 -8
  77. package/dist/client-request-BzMKtfCY.js +0 -52
  78. package/dist/database-options-B87hDU4j.js +0 -28
@@ -1,17 +1,18 @@
1
1
  import { t as invariant } from "./invariant-Dj2R1eMr.js";
2
2
  import { t as createNitroServerKit } from "./nitro-kit-BumWIKa5.js";
3
- import { t as isRecord$1 } from "./object-CAK6UYR5.js";
3
+ import { t as isRecord } from "./object-CAK6UYR5.js";
4
4
  import { r as resolveAccessRoutePath, t as accessRouteSyntaxError } from "./application-path-zKi7NrvK.js";
5
- import { t as authErrorDiagnostics } from "./error-diagnostics-CUPwukgE.js";
6
- import { a as normalizeAuthBasePath, n as assertAuthPages } from "./access-pages-9aKr6z-k.js";
7
- import { a as authDatabaseSchemaError, i as authDatabasePlacementError, n as authDatabaseAdditionalFieldsError, o as authMemoryDatabaseError, t as assertAuthDatabaseIdStrategy } from "./database-options-B87hDU4j.js";
8
- import { i as resolveAuthTableSpecs, n as authSqlName } from "./table-specs-CCSY4tiS.js";
5
+ import { t as authErrorDiagnostics } from "./error-diagnostics-DZHuHXPP.js";
6
+ import { n as assertAuthPages, o as normalizeAuthBasePath } from "./access-pages-C69nwa99.js";
7
+ import { a as differentFieldAttributes, c as mergeFieldDeclarations, i as authExtensionKeys, n as assertUniquePluginIds, o as effectiveFieldAttributes, r as authCoreModels } from "./extension-mCx4TrsO.js";
8
+ import { a as authDatabasePlacementError, n as authDatabaseAdditionalFieldsError, o as authDatabaseSchemaError, s as authMemoryDatabaseError, t as assertAuthDatabaseIdStrategy } from "./database-options-Cms7BI3c.js";
9
+ import { i as resolveAuthTableSpecs, n as authSqlName } from "./table-specs-Bm7QJCbu.js";
9
10
  import { n as resetAuth } from "./runtime-state-C0Rd1W4m.js";
10
- import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
11
+ import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from "node:fs";
11
12
  import { basename, dirname, join, parse, relative, resolve } from "node:path";
12
13
  import { fileURLToPath } from "node:url";
13
14
  import { tmpdir } from "node:os";
14
- import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
15
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
15
16
  import { parseSync } from "vite";
16
17
  // ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
17
18
  const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
@@ -155,11 +156,26 @@ function createNoExternalAddition(...packageNames) {
155
156
  function isServerEnvironment(name, config) {
156
157
  return name === "ssr" || config.consumer === "server";
157
158
  }
159
+ const VITEHUB_PROJECT_ROOT = "__vitehubProjectRoot";
158
160
  /**
159
161
  * Server directories that ViteHub scans for Definitions. The first entry is the application.
160
162
  * Later entries are Nuxt layers in Nuxt priority order.
161
163
  */
162
164
  const VITEHUB_SERVER_DIRS = "__vitehubServerDirs";
165
+ const VITEHUB_NUXT_AUTH_DISCOVERY = "__vitehubNuxtAuthDiscovery";
166
+ function resolveNuxtAuthDiscovery(options) {
167
+ const appDir = options.srcDir;
168
+ const appRoot = options.rootDir && resolve(options.rootDir);
169
+ return {
170
+ appDir,
171
+ layerAppDirs: (options._layers ?? []).flatMap((layer) => {
172
+ const root = layer.config?.rootDir ?? layer.cwd;
173
+ const source = layer.config?.srcDir ?? layer.cwd ?? root;
174
+ return source && (!root || resolve(root) !== appRoot) ? [resolve(source)] : [];
175
+ }),
176
+ layerAliases: Object.fromEntries(Object.entries(options.alias ?? {}).filter(([name]) => name.startsWith("#layers/")))
177
+ };
178
+ }
163
179
  /**
164
180
  * Lists the server directory of the application and of each Nuxt layer it extends.
165
181
  * The application comes first. Layers follow in Nuxt priority order, like Nuxt's own Nitro scan directories.
@@ -329,6 +345,19 @@ function findPackageDir(file) {
329
345
  function ownModule(importMetaUrl, modulePath) {
330
346
  return resolveRuntimeModule(findPackageDir(fileURLToPath(importMetaUrl)), modulePath);
331
347
  }
348
+ function createImportPath(fromFile, targetFile) {
349
+ const fromDir = realpathIfExists(dirname$1(fromFile));
350
+ const target = realpathIfExists(targetFile);
351
+ const importPath = relative$1(fromDir, target);
352
+ return importPath.startsWith(".") ? importPath : `./${importPath}`;
353
+ }
354
+ function realpathIfExists(path) {
355
+ try {
356
+ return realpathSync.native(path);
357
+ } catch {
358
+ return resolve$1(path);
359
+ }
360
+ }
332
361
  // ../internal/src/definition-catalog.ts
333
362
  /** `writeFileIfChangedSync` for async callers. */
334
363
  async function writeFileIfChanged(file, contents) {
@@ -345,7 +374,7 @@ async function flattenPlugins(value, plugins, seen) {
345
374
  for (const item of value) await flattenPlugins(item, plugins, seen);
346
375
  return;
347
376
  }
348
- if (!isRecord$1(value) || seen.has(value)) return;
377
+ if (!isRecord(value) || seen.has(value)) return;
349
378
  seen.add(value);
350
379
  if (isThenable(value)) {
351
380
  await flattenPlugins(await value, plugins, seen);
@@ -442,6 +471,10 @@ function scanModule(source, file = "module.ts") {
442
471
  source
443
472
  };
444
473
  }
474
+ /** The source text of a node. */
475
+ function nodeText(module, node) {
476
+ return module.source.slice(node.start, node.end);
477
+ }
445
478
  /** Removes parentheses, `as`, `satisfies`, `!`, and `<T>` assertions around an expression. */
446
479
  function unwrapExpression(node) {
447
480
  while (node.type === "ParenthesizedExpression" || node.type === "TSAsExpression" || node.type === "TSSatisfiesExpression" || node.type === "TSNonNullExpression" || node.type === "TSTypeAssertion") node = node.expression;
@@ -593,13 +626,57 @@ function discoverAuthDefinitions(rootDir, options = {}) {
593
626
  ].join("\n") });
594
627
  return layerDefinitions;
595
628
  }
596
- /** Finds the app's Auth client options, `auth.client.ts`, in the Vite root, which is `app/` in a Nuxt app. */
597
- function discoverAuthClient(appDir) {
598
- return authDefinitionExtensions.map((extension) => resolve(appDir, `auth.client${extension}`)).find((file) => existsSync(file));
629
+ /** The Auth Definitions of Nuxt layers. The first server directory is the application. */
630
+ function discoverLayerAuthDefinitions(serverDirs = []) {
631
+ return existingDefinitions(serverDirs.slice(1).flatMap(serverAuthCandidates));
632
+ }
633
+ /**
634
+ * Finds the Auth client options, `auth.client.ts`, in the Vite root, which is `app/` in a Nuxt app. Without an
635
+ * application file, one Nuxt layer can supply its `app/auth.client.ts`. A layer file that Auth would not load fails
636
+ * discovery.
637
+ */
638
+ function discoverAuthClient(appDir, options = {}) {
639
+ const clientIn = (directory) => authDefinitionExtensions.map((extension) => resolve(directory, `auth.client${extension}`)).find((file) => existsSync(file));
640
+ const app = clientIn(appDir);
641
+ const layers = [...new Set((options.layerAppDirs ?? []).flatMap((directory) => clientIn(directory) ?? []))].filter((file) => file !== app);
642
+ if (layers.length > (app ? 0 : 1)) throw authErrorDiagnostics.AUTH_LAYER_CLIENT_IGNORED({
643
+ files: layers,
644
+ ...app ? { app } : {}
645
+ });
646
+ return app ?? layers[0];
647
+ }
648
+ /**
649
+ * The parts of the Auth Definition, `server/auth.extend.ts`: the file of the application first, then the files of
650
+ * Nuxt layers in priority order.
651
+ */
652
+ function discoverAuthExtensions(rootDir, options = {}) {
653
+ return (options.serverDirs ?? [resolve(rootDir, "server")]).flatMap((serverDir) => authDefinitionExtensions.map((extension) => resolve(serverDir, `auth.extend${extension}`)).find((file) => existsSync(file)) ?? []);
654
+ }
655
+ /**
656
+ * The parts of the Auth client options, `auth.client.extend.ts`: the file in the Vite root first, which is `app/` in a
657
+ * Nuxt app, then the `app/auth.client.extend.ts` of Nuxt layers in priority order.
658
+ */
659
+ function discoverAuthClientExtensions(appDir, options = {}) {
660
+ return [.../* @__PURE__ */ new Set([appDir, ...options.layerAppDirs ?? []])].flatMap((directory) => authDefinitionExtensions.map((extension) => resolve(directory, `auth.client.extend${extension}`)).find((file) => existsSync(file)) ?? []);
599
661
  }
600
662
  function discoverAuthDefinition(rootDir, options = {}) {
601
663
  return discoverAuthDefinitions(rootDir, options)[0];
602
664
  }
665
+ function discoverProjectAuthDefinition(project) {
666
+ const discovery = { serverDirs: project.serverDirs?.slice() };
667
+ const rootDir = project.viteRoot ?? project.projectRoot;
668
+ const definition = discoverAuthDefinition(rootDir, discovery);
669
+ if (definition) return {
670
+ definition,
671
+ rootDir
672
+ };
673
+ if (rootDir === project.projectRoot) return;
674
+ const fallback = discoverAuthDefinition(project.projectRoot, discovery);
675
+ if (fallback) return {
676
+ definition: fallback,
677
+ rootDir: project.projectRoot
678
+ };
679
+ }
603
680
  const abilitiesExtensions = [
604
681
  ".ts",
605
682
  ".mts",
@@ -623,6 +700,90 @@ function discoverAuthAbilities(rootDir, options = {}) {
623
700
  if (found.length > 1) throw authErrorDiagnostics.AUTH_C0060({ message: ["[vitehub] Only one abilities file is allowed. Found:", ...found.map((file) => ` - ${file}`)].join("\n") });
624
701
  return found[0];
625
702
  }
703
+ // src/config-fields.ts
704
+ const authFieldTypes = /* @__PURE__ */ new Set([
705
+ "boolean",
706
+ "date",
707
+ "json",
708
+ "number",
709
+ "number[]",
710
+ "string",
711
+ "string[]"
712
+ ]);
713
+ function readStaticBooleanOption(field, key, label, fail) {
714
+ if (!hasObjectProperty(field, key)) return;
715
+ const value = readStaticBooleanLiteral(readObjectPropertyValue(field, key));
716
+ if (value === void 0) throw fail(`${label}.${key} must be \`true\` or \`false\``);
717
+ return value;
718
+ }
719
+ /** One additional field, read from its object literal: the parts that shape the column. */
720
+ function readAdditionalField(value, key, label, fail = authDatabaseAdditionalFieldsError) {
721
+ const field = objectLiteral(value && unwrapExpression(value));
722
+ if (!field) throw fail(`${label} must be an inline object, such as \`{ type: "string", required: false }\``);
723
+ const typeValue = readObjectPropertyValue(field, "type");
724
+ const unwrappedType = typeValue && unwrapExpression(typeValue);
725
+ const type = unwrappedType?.type === "ArrayExpression" ? "string" : staticString(unwrappedType);
726
+ if (!type || !authFieldTypes.has(type)) throw fail(`${label}.type must be one of ${[...authFieldTypes].map((name) => `"${name}"`).join(", ")}, or a list of strings`);
727
+ const fieldName = readObjectPropertyValue(field, "fieldName");
728
+ if (fieldName && staticString(fieldName) !== key) throw authDatabaseSchemaError(`${label}.fieldName cannot rename the column`);
729
+ const spec = { type };
730
+ if (readStaticBooleanOption(field, "required", label, fail)) spec.required = true;
731
+ if (readStaticBooleanOption(field, "unique", label, fail)) spec.unique = true;
732
+ if (readStaticBooleanOption(field, "index", label, fail)) spec.index = true;
733
+ if (readStaticBooleanOption(field, "bigint", label, fail)) spec.bigint = true;
734
+ const defaultValue = readObjectPropertyValue(field, "defaultValue");
735
+ const staticDefault = defaultValue && staticValue(defaultValue);
736
+ if (typeof staticDefault === "string" || typeof staticDefault === "number" || typeof staticDefault === "boolean") spec.defaultValue = staticDefault;
737
+ const references = readObjectPropertyValue(field, "references");
738
+ if (references) {
739
+ const reference = staticValue(references);
740
+ const model = typeof reference === "object" && reference !== null && !Array.isArray(reference) ? reference.model : void 0;
741
+ const target = typeof reference === "object" && reference !== null && !Array.isArray(reference) ? reference.field : void 0;
742
+ const onDelete = typeof reference === "object" && reference !== null && !Array.isArray(reference) ? reference.onDelete ?? "cascade" : void 0;
743
+ if (typeof model !== "string" || typeof target !== "string" || onDelete !== "cascade" && onDelete !== "set null") throw fail(`${label}.references must be an inline object, such as \`{ model: "user", field: "id", onDelete: "cascade" }\``);
744
+ spec.references = {
745
+ model,
746
+ field: target,
747
+ onDelete
748
+ };
749
+ }
750
+ return spec;
751
+ }
752
+ /** The `additionalFields` of each core model, which `authDatabase()` adds as columns. */
753
+ function readAuthAdditionalFields(body) {
754
+ const result = {};
755
+ for (const model of authCoreModels) {
756
+ const value = readObjectPropertyValue(objectLiteral(readObjectPropertyValue(body, model)), "additionalFields");
757
+ if (!value) continue;
758
+ const fields = objectLiteral(unwrapExpression(value));
759
+ if (!fields) throw authDatabaseAdditionalFieldsError(`${model}.additionalFields must be an inline object literal, so the Auth Vite plugin can add its columns`);
760
+ const entries = readObjectEntries(fields);
761
+ if (entries.some((entry) => !entry.key)) throw authDatabaseAdditionalFieldsError(`${model}.additionalFields must use static keys`);
762
+ if (entries.length) result[model] = Object.fromEntries(entries.map((entry) => [entry.key, readAdditionalField(entry.value, entry.key, `${model}.additionalFields.${entry.key}`)]));
763
+ }
764
+ return Object.keys(result).length ? result : void 0;
765
+ }
766
+ /** Object entries. `key` is empty for spread and computed keys. `value` is undefined for methods and accessors. */
767
+ function readObjectEntries(body) {
768
+ if (!body) return [];
769
+ return objectProperties(body).map((property) => ({
770
+ key: property.computed ? "" : property.key ?? "",
771
+ value: property.node.type === "Property" && property.node.kind === "init" && !property.node.method ? property.value : void 0
772
+ }));
773
+ }
774
+ function readObjectPropertyValue(body, property) {
775
+ return readObjectEntries(body).findLast((entry) => entry.key === property)?.value;
776
+ }
777
+ function hasObjectProperty(body, property) {
778
+ return readObjectEntries(body).some((entry) => entry.key === property);
779
+ }
780
+ function objectLiteral(value) {
781
+ return value?.type === "ObjectExpression" ? value : void 0;
782
+ }
783
+ function readStaticBooleanLiteral(expression) {
784
+ const value = expression && staticValue(expression);
785
+ return typeof value === "boolean" ? value : void 0;
786
+ }
626
787
  // src/config.ts
627
788
  const authDatabaseModules = /* @__PURE__ */ new Set(["@vite-hub/auth/database", "vite-hub/auth/database"]);
628
789
  function readAuthDatabaseImports(module) {
@@ -695,7 +856,7 @@ function addBoundNames(pattern, names) {
695
856
  }
696
857
  });
697
858
  }
698
- function readModuleBindings(module) {
859
+ function readModuleBindings(module, layers) {
699
860
  const bindings = {
700
861
  declarations: /* @__PURE__ */ new Map(),
701
862
  imports: /* @__PURE__ */ new Map(),
@@ -705,7 +866,11 @@ function readModuleBindings(module) {
705
866
  pluginFactories: /* @__PURE__ */ new Map(),
706
867
  pluginNamespaces: /* @__PURE__ */ new Map()
707
868
  };
708
- const localFile = (specifier) => specifier.startsWith("./") || specifier.startsWith("../") ? resolveLocalModule(module.file, specifier) : void 0;
869
+ const localFile = (specifier) => {
870
+ if (specifier.startsWith("./") || specifier.startsWith("../")) return resolveLocalModule(module.file, specifier);
871
+ const alias = Object.keys(layers).find((name) => specifier === name || specifier.startsWith(`${name}/`));
872
+ return alias ? resolveLocalModule(module.file, resolve(layers[alias], specifier.slice(alias.length + 1))) : void 0;
873
+ };
709
874
  const declare = (name, node) => bindings.declarations.set(name, [...bindings.declarations.get(name) ?? [], node]);
710
875
  const readDeclaration = (declaration, exported) => {
711
876
  const names = [];
@@ -768,86 +933,178 @@ function readModuleBindings(module) {
768
933
  } else readDeclaration(statement, false);
769
934
  return bindings;
770
935
  }
771
- /**
772
- * Reads what `needs` reaches in `module`: the plugin factories that its reached code calls, and what it needs from the
773
- * local modules it imports. The whole module counts for the Definition. In an imported module, only the exports that
774
- * the importer uses count, with the declarations and imports that they use.
775
- */
776
- function readModuleNeeds(module, needs, exportedFactory) {
777
- const bindings = readModuleBindings(module);
778
- const plugins = /* @__PURE__ */ new Set();
779
- const imports = [];
780
- const need = (file, imported) => imports.push([file, /* @__PURE__ */ new Set([imported])]);
781
- const needImport = ({ file, imported }) => imported === "*" ? imports.push([file, "all"]) : need(file, imported);
782
- const calledFactory = (callee) => {
783
- if (callee.type === "Identifier") {
784
- const imported = bindings.imports.get(callee.name);
785
- return bindings.pluginFactories.get(callee.name) ?? (imported && imported.imported !== "*" ? exportedFactory(imported.file, imported.imported) : void 0);
936
+ function pluginFunctionScope(scope, factory) {
937
+ const locals = new Map(scope.locals);
938
+ for (const param of factory.params) {
939
+ const names = [];
940
+ addBoundNames(param, names);
941
+ for (const name of names) locals.set(name, void 0);
942
+ }
943
+ if (factory.body?.type === "BlockStatement") for (const statement of factory.body.body) {
944
+ if (statement.type !== "VariableDeclaration") continue;
945
+ for (const declaration of statement.declarations) {
946
+ const names = [];
947
+ addBoundNames(declaration.id, names);
948
+ const value = statement.kind === "const" && declaration.id.type === "Identifier" && declaration.init ? unwrapExpression(declaration.init) : void 0;
949
+ for (const name of names) locals.set(name, value);
786
950
  }
787
- if (callee.type !== "MemberExpression" || callee.object.type !== "Identifier") return void 0;
788
- const property = staticMemberName(callee);
789
- if (property === void 0) return void 0;
790
- const factories = bindings.pluginNamespaces.get(callee.object.name);
791
- if (factories) return Object.hasOwn(factories, property) ? factories[property] : void 0;
792
- const imported = bindings.imports.get(callee.object.name);
793
- return imported?.imported === "*" ? exportedFactory(imported.file, property) : void 0;
951
+ }
952
+ return {
953
+ module: scope.module,
954
+ locals
794
955
  };
795
- const collectCalls = (node, references) => walk(node, (child, parent) => {
796
- if (child.type === "ImportDeclaration") return false;
797
- const plugin = child.type === "CallExpression" ? calledFactory(child.callee) : void 0;
798
- if (plugin) plugins.add(plugin);
799
- if (child.type !== "Identifier") return;
800
- if (parent?.type === "MemberExpression") {
801
- if (parent.property === child && !parent.computed) return;
802
- if (parent.object === child) {
803
- const imported = bindings.imports.get(child.name);
804
- const member = staticMemberName(parent);
805
- if (imported?.imported === "*" && member !== void 0) {
806
- need(imported.file, member);
956
+ }
957
+ function readConfiguredPluginFields(definition, options, body, moduleOf, bindingsOf, scan, knownFactory, plugins) {
958
+ const start = readObjectPropertyValue(body, "plugins");
959
+ if (!start) return [];
960
+ const active = /* @__PURE__ */ new Set();
961
+ const resolvingExports = /* @__PURE__ */ new Set();
962
+ function fromExport(file, name, read) {
963
+ const key = `${file}\0${name}`;
964
+ if (resolvingExports.has(key)) return;
965
+ resolvingExports.add(key);
966
+ try {
967
+ const bindings = bindingsOf(file);
968
+ const target = bindings.exports.get(name);
969
+ if (target && "file" in target) return fromExport(target.file, target.imported, read);
970
+ if (target && "local" in target) return fromLocal(target.local, { module: moduleOf(file) }, read);
971
+ if (!target && name !== "default") for (const source of bindings.exportAll) {
972
+ const value = fromExport(source, name, read);
973
+ if (value !== void 0) return value;
974
+ }
975
+ } finally {
976
+ resolvingExports.delete(key);
977
+ }
978
+ }
979
+ function fromLocal(name, scope, read) {
980
+ if (scope.locals?.has(name)) return visit(scope.locals.get(name), scope, read);
981
+ const bindings = bindingsOf(scope.module.file);
982
+ const imported = bindings.imports.get(name);
983
+ if (imported && imported.imported !== "*") return fromExport(imported.file, imported.imported, read);
984
+ const declaration = bindings.declarations.get(name)?.[0];
985
+ return visit(name === "default" ? defaultExportExpression(scope.module) ?? declaration : declaration?.type === "VariableDeclarator" ? topLevelConstValue(scope.module, name) : declaration, { module: scope.module }, read);
986
+ }
987
+ function visit(node, scope, read) {
988
+ if (!node || active.has(node)) return;
989
+ active.add(node);
990
+ try {
991
+ if (node.type === "Identifier") return fromLocal(node.name, scope, read);
992
+ if (node.type === "MemberExpression" && node.object.type === "Identifier" && !scope.locals?.has(node.object.name)) {
993
+ const imported = bindingsOf(scope.module.file).imports.get(node.object.name);
994
+ const name = staticMemberName(node);
995
+ if (imported?.imported === "*" && name !== void 0) return fromExport(imported.file, name, read);
996
+ }
997
+ if (node.type === "CallExpression" && (node.callee.type === "Identifier" || node.callee.type === "MemberExpression")) {
998
+ const registered = read === readPlugin;
999
+ const known = registered ? knownFactory(node.callee, scope) : void 0;
1000
+ if (known) {
1001
+ plugins.push(known);
807
1002
  return;
808
1003
  }
1004
+ return visit(node.callee, scope, (factory, factoryScope) => {
1005
+ if (factory.type !== "ArrowFunctionExpression" && factory.type !== "FunctionExpression" && factory.type !== "FunctionDeclaration") return;
1006
+ const body = factory.body;
1007
+ if (!body) return;
1008
+ const end = body.type === "BlockStatement" ? body.body.at(-1) : void 0;
1009
+ const value = body.type !== "BlockStatement" ? body : end?.type === "ReturnStatement" ? end.argument ?? void 0 : void 0;
1010
+ if (!value || factory.async || "generator" in factory && factory.generator || body.type === "BlockStatement" && !body.body.slice(0, -1).every((statement) => statement.type === "VariableDeclaration" || statement.type === "ExpressionStatement")) {
1011
+ if (registered && scan.ownsTables) throw authErrorDiagnostics.AUTH_PLUGIN_SCHEMA_UNREADABLE({
1012
+ plugin: nodeText(scope.module, node.callee),
1013
+ file: relative(scan.rootDir, factoryScope.module.file),
1014
+ detail: "the local factory must return a statically readable plugin object or plugin list"
1015
+ });
1016
+ return;
1017
+ }
1018
+ return visit(unwrapExpression(value), pluginFunctionScope(factoryScope, factory), read);
1019
+ });
809
1020
  }
1021
+ return read(node, scope);
1022
+ } finally {
1023
+ active.delete(node);
810
1024
  }
811
- references.add(child.name);
812
- });
813
- if (needs === "all") {
814
- const references = /* @__PURE__ */ new Set();
815
- collectCalls(module.program, references);
816
- for (const [name, imported] of bindings.imports) if (references.has(name)) needImport(imported);
817
- for (const target of bindings.exports.values()) if ("file" in target) needImport(target);
818
- return {
819
- plugins: [...plugins],
820
- imports
821
- };
822
1025
  }
823
- const locals = [];
824
- for (const name of needs) {
825
- const target = bindings.exports.get(name);
826
- if (!target) for (const file of bindings.exportAll) need(file, name);
827
- else if ("file" in target) needImport(target);
828
- else if ("local" in target) locals.push(target.local);
1026
+ function entries(value, scope, keysOnly = false, unreadable) {
1027
+ const result = visit(value && unwrapExpression(value), scope, (object, objectScope) => object.type === "ObjectExpression" ? objectEntries(object, objectScope, keysOnly, unreadable) : void 0);
1028
+ if (!result && unreadable) throw unreadable();
1029
+ return result;
829
1030
  }
830
- const reached = /* @__PURE__ */ new Set();
831
- for (let local = locals.pop(); local !== void 0; local = locals.pop()) {
832
- if (reached.has(local)) continue;
833
- reached.add(local);
834
- const imported = bindings.imports.get(local);
835
- if (imported) needImport(imported);
836
- const references = /* @__PURE__ */ new Set();
837
- for (const declaration of bindings.declarations.get(local) ?? []) collectCalls(declaration, references);
838
- for (const reference of references) if (bindings.declarations.has(reference) || bindings.imports.has(reference)) locals.push(reference);
1031
+ function objectEntries(object, scope, keysOnly = false, unreadable) {
1032
+ const result = /* @__PURE__ */ new Map();
1033
+ for (const property of objectProperties(object)) if (property.node.type === "SpreadElement") {
1034
+ const spread = entries(property.node.argument, scope, keysOnly, unreadable);
1035
+ if (spread) for (const [key, entry] of spread) result.set(key, entry);
1036
+ else if (!keysOnly) result.clear();
1037
+ } else if (property.key) {
1038
+ const value = property.node.kind === "init" && !property.node.method ? property.value : void 0;
1039
+ result.set(property.key, {
1040
+ value,
1041
+ scope
1042
+ });
1043
+ } else if (unreadable) throw unreadable();
1044
+ else if (!keysOnly) result.clear();
1045
+ return result;
839
1046
  }
840
- return {
841
- plugins: [...plugins],
842
- imports
1047
+ const objectAt = (entry, keysOnly = false, unreadable) => entry && entries(entry.value, entry.scope, keysOnly, unreadable);
1048
+ const fields = [];
1049
+ const readPlugin = (node, scope) => {
1050
+ if (node.type === "ArrayExpression") for (const element of node.elements) {
1051
+ const value = element?.type === "SpreadElement" ? element.argument : element;
1052
+ if (value) visit(unwrapExpression(value), scope, readPlugin);
1053
+ }
1054
+ if (node.type !== "ObjectExpression") return;
1055
+ const pluginObject = objectEntries(node, scope);
1056
+ const id = pluginObject.get("id");
1057
+ const plugin = id && visit(id.value && unwrapExpression(id.value), id.scope, (value) => value.type === "Literal" && typeof value.value === "string" ? value.value : void 0);
1058
+ if (!plugin) return;
1059
+ const file = scope.module.file;
1060
+ const unreadable = (detail) => authErrorDiagnostics.AUTH_PLUGIN_SCHEMA_UNREADABLE({
1061
+ plugin,
1062
+ file: relative(scan.rootDir, file),
1063
+ detail
1064
+ });
1065
+ const schema = objectAt(pluginObject.get("schema"), false, scan.ownsTables ? () => unreadable("`schema` must be an inline object literal or resolve to an object with static keys") : void 0);
1066
+ const columns = [];
1067
+ for (const [model, entry] of schema ?? []) {
1068
+ const core = scan.ownsTables && authCoreModels.some((core) => core === model);
1069
+ const label = `schema.${model}.fields`;
1070
+ const invalidFields = () => unreadable(`\`${label}\` must be an inline object literal or resolve to an object with static keys`);
1071
+ const modelFields = objectAt(objectAt(entry, false, core ? invalidFields : void 0)?.get("fields"), !core, core ? invalidFields : void 0);
1072
+ if (core && !modelFields) throw invalidFields();
1073
+ for (const [field, { value, scope: fieldScope }] of modelFields ?? []) {
1074
+ const declaration = authCoreModels.some((coreModel) => coreModel === model) ? visit(value && unwrapExpression(value), fieldScope, (node) => {
1075
+ if (node.type !== "ObjectExpression") return;
1076
+ if (readObjectEntries(node).some((entry) => !entry.key)) {
1077
+ if (core) throw unreadable(`${label}.${field} must have static attributes`);
1078
+ return;
1079
+ }
1080
+ return {
1081
+ attributes: staticFieldAttributes(node),
1082
+ spec: core ? readAdditionalField(node, field, `${label}.${field}`, unreadable) : void 0
1083
+ };
1084
+ }) : void 0;
1085
+ if (core && !declaration) throw unreadable(`${label}.${field} must be an inline object or resolve to one`);
1086
+ columns.push({
1087
+ model,
1088
+ field,
1089
+ ...declaration
1090
+ });
1091
+ }
1092
+ }
1093
+ fields.push({
1094
+ plugin,
1095
+ file,
1096
+ fields: columns
1097
+ });
843
1098
  };
1099
+ const scope = { module: definition };
1100
+ visit(unwrapExpression(start), options.type === "ArrowFunctionExpression" || options.type === "FunctionExpression" ? pluginFunctionScope(scope, options) : scope, readPlugin);
1101
+ return fields;
844
1102
  }
845
1103
  /**
846
- * The plugins of `AuthSchemaPlugin` that the Definition module calls, and that the local modules it imports call in
847
- * the exports it uses, such as `stripe()` in `src/server/auth-plugins.ts` that returns the plugins of `server/auth.ts`.
1104
+ * The schema contributions reached from the registered plugins, including plugins returned by local helpers.
848
1105
  */
849
- function readDefinitionSchemaPlugins(definition) {
850
- const plugins = /* @__PURE__ */ new Set();
1106
+ function readDefinitionSchemaPlugins(definition, scan, options, body) {
1107
+ const plugins = [];
851
1108
  const modules = /* @__PURE__ */ new Map([[definition.file, definition]]);
852
1109
  const moduleOf = (file) => {
853
1110
  let module = modules.get(file);
@@ -855,12 +1112,16 @@ function readDefinitionSchemaPlugins(definition) {
855
1112
  return module;
856
1113
  };
857
1114
  const bindingsByFile = /* @__PURE__ */ new Map();
1115
+ const bindingsOf = (file) => {
1116
+ let bindings = bindingsByFile.get(file);
1117
+ if (!bindings) bindingsByFile.set(file, bindings = readModuleBindings(moduleOf(file), scan.layers));
1118
+ return bindings;
1119
+ };
858
1120
  const exportedFactory = (file, name, seen = /* @__PURE__ */ new Set()) => {
859
1121
  const key = `${file}\0${name}`;
860
1122
  if (seen.has(key)) return void 0;
861
1123
  seen.add(key);
862
- let bindings = bindingsByFile.get(file);
863
- if (!bindings) bindingsByFile.set(file, bindings = readModuleBindings(moduleOf(file)));
1124
+ const bindings = bindingsOf(file);
864
1125
  const target = bindings.exports.get(name);
865
1126
  if (target && "plugin" in target) return target.plugin;
866
1127
  if (target && "file" in target) return exportedFactory(target.file, target.imported, seen);
@@ -875,89 +1136,25 @@ function readDefinitionSchemaPlugins(definition) {
875
1136
  if (plugin) return plugin;
876
1137
  }
877
1138
  };
878
- const done = /* @__PURE__ */ new Map();
879
- const queue = [[definition.file, "all"]];
880
- for (let item = queue.shift(); item; item = queue.shift()) {
881
- const [file, needs] = item;
882
- const previous = done.get(file);
883
- if (previous === "all") continue;
884
- const fresh = needs === "all" ? "all" : new Set([...needs].filter((name) => !previous?.has(name)));
885
- if (fresh !== "all" && !fresh.size) continue;
886
- done.set(file, fresh === "all" ? "all" : /* @__PURE__ */ new Set([...previous ?? [], ...fresh]));
887
- const result = readModuleNeeds(moduleOf(file), fresh, exportedFactory);
888
- for (const plugin of result.plugins) plugins.add(plugin);
889
- queue.push(...result.imports);
890
- }
891
- return [...plugins].sort();
892
- }
893
- const authFieldTypes = /* @__PURE__ */ new Set([
894
- "boolean",
895
- "date",
896
- "json",
897
- "number",
898
- "number[]",
899
- "string",
900
- "string[]"
901
- ]);
902
- function readStaticBooleanOption(field, key, label) {
903
- if (!hasObjectProperty(field, key)) return;
904
- const value = readStaticBooleanLiteral(readObjectPropertyValue(field, key));
905
- if (value === void 0) throw authDatabaseAdditionalFieldsError(`${label}.${key} must be \`true\` or \`false\``);
906
- return value;
907
- }
908
- /** One additional field, read from its object literal: the parts that shape the column. */
909
- function readAdditionalField(value, key, label) {
910
- const field = objectLiteral(value && unwrapExpression(value));
911
- if (!field) throw authDatabaseAdditionalFieldsError(`${label} must be an inline object, such as \`{ type: "string", required: false }\``);
912
- const typeValue = readObjectPropertyValue(field, "type");
913
- const unwrappedType = typeValue && unwrapExpression(typeValue);
914
- const type = unwrappedType?.type === "ArrayExpression" ? "string" : staticString(unwrappedType);
915
- if (!type || !authFieldTypes.has(type)) throw authDatabaseAdditionalFieldsError(`${label}.type must be one of ${[...authFieldTypes].map((name) => `"${name}"`).join(", ")}, or a list of strings`);
916
- const fieldName = readObjectPropertyValue(field, "fieldName");
917
- if (fieldName && staticString(fieldName) !== key) throw authDatabaseSchemaError(`${label}.fieldName cannot rename the column`);
918
- const spec = { type };
919
- if (readStaticBooleanOption(field, "required", label)) spec.required = true;
920
- if (readStaticBooleanOption(field, "unique", label)) spec.unique = true;
921
- if (readStaticBooleanOption(field, "index", label)) spec.index = true;
922
- if (readStaticBooleanOption(field, "bigint", label)) spec.bigint = true;
923
- const defaultValue = readObjectPropertyValue(field, "defaultValue");
924
- const staticDefault = defaultValue && staticValue(defaultValue);
925
- if (typeof staticDefault === "string" || typeof staticDefault === "number" || typeof staticDefault === "boolean") spec.defaultValue = staticDefault;
926
- const references = readObjectPropertyValue(field, "references");
927
- if (references) {
928
- const reference = staticValue(references);
929
- const model = typeof reference === "object" && reference !== null && !Array.isArray(reference) ? reference.model : void 0;
930
- const target = typeof reference === "object" && reference !== null && !Array.isArray(reference) ? reference.field : void 0;
931
- const onDelete = typeof reference === "object" && reference !== null && !Array.isArray(reference) ? reference.onDelete ?? "cascade" : void 0;
932
- 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" }\``);
933
- spec.references = {
934
- model,
935
- field: target,
936
- onDelete
937
- };
938
- }
939
- return spec;
940
- }
941
- /** The `additionalFields` of each core model, which `authDatabase()` adds as columns. */
942
- function readAuthAdditionalFields(body) {
943
- const result = {};
944
- for (const model of [
945
- "user",
946
- "session",
947
- "account",
948
- "verification"
949
- ]) {
950
- const value = readObjectPropertyValue(objectLiteral(readObjectPropertyValue(body, model)), "additionalFields");
951
- if (!value) continue;
952
- const fields = objectLiteral(unwrapExpression(value));
953
- if (!fields) throw authDatabaseAdditionalFieldsError(`${model}.additionalFields must be an inline object literal, so the Auth Vite plugin can add its columns`);
954
- const entries = readObjectEntries(fields);
955
- if (entries.some((entry) => !entry.key)) throw authDatabaseAdditionalFieldsError(`${model}.additionalFields must use static keys`);
956
- if (entries.length) result[model] = Object.fromEntries(entries.map((entry) => [entry.key, readAdditionalField(entry.value, entry.key, `${model}.additionalFields.${entry.key}`)]));
957
- }
958
- return Object.keys(result).length ? result : void 0;
1139
+ const knownFactory = (callee, scope) => {
1140
+ const bindings = bindingsOf(scope.module.file);
1141
+ if (callee.type === "Identifier" && !scope.locals?.has(callee.name)) {
1142
+ const imported = bindings.imports.get(callee.name);
1143
+ return bindings.pluginFactories.get(callee.name) ?? (imported && imported.imported !== "*" ? exportedFactory(imported.file, imported.imported) : void 0);
1144
+ }
1145
+ if (callee.type !== "MemberExpression" || callee.object.type !== "Identifier" || scope.locals?.has(callee.object.name)) return;
1146
+ const name = staticMemberName(callee);
1147
+ if (name === void 0) return;
1148
+ const factories = bindings.pluginNamespaces.get(callee.object.name);
1149
+ if (factories) return Object.hasOwn(factories, name) ? factories[name] : void 0;
1150
+ const imported = bindings.imports.get(callee.object.name);
1151
+ if (imported?.imported === "*") return exportedFactory(imported.file, name);
1152
+ };
1153
+ return {
1154
+ plugins,
1155
+ pluginFields: readConfiguredPluginFields(definition, options, body, moduleOf, bindingsOf, scan, knownFactory, plugins)
1156
+ };
959
1157
  }
960
- /** The object that a callback returns, from `() => ({ ... })` or the first `return { ... }` in its body. */
961
1158
  function readReturnedObject(callback) {
962
1159
  if (callback.type !== "ArrowFunctionExpression") return;
963
1160
  if (callback.body.type !== "BlockStatement") {
@@ -994,7 +1191,12 @@ function exportedDefineAuthCall(module) {
994
1191
  const call = exported?.type === "Identifier" ? topLevelConstValue(module, exported.name) : exported;
995
1192
  return call?.type === "CallExpression" && call.callee.type === "Identifier" && call.callee.name === "defineAuth" ? call : void 0;
996
1193
  }
997
- function readDefinitionObjectBody(file) {
1194
+ function readPluginCalls(module, body) {
1195
+ const label = (node) => node.type === "SpreadElement" ? `...${label(node.argument)}` : node.type === "CallExpression" ? `${nodeText(module, node.callee)}()` : node.type === "Identifier" ? node.name : node.type === "ObjectExpression" ? staticString(readObjectPropertyValue(node, "id")) ?? "(object)" : "(expression)";
1196
+ const plugins = readObjectPropertyValue(body, "plugins");
1197
+ return plugins?.type === "ArrayExpression" ? plugins.elements.flatMap((element) => element ? [label(element)] : []) : plugins ? [label(plugins)] : [];
1198
+ }
1199
+ function readDefinitionObjectBody(file, scan) {
998
1200
  const module = scanModule(readFileSync(file, "utf8"), file);
999
1201
  const authDatabase = readAuthDatabaseImports(module);
1000
1202
  const call = exportedDefineAuthCall(module);
@@ -1002,7 +1204,6 @@ function readDefinitionObjectBody(file) {
1002
1204
  const argument = call.arguments[0];
1003
1205
  if (argument === void 0 || argument.type === "SpreadElement") return;
1004
1206
  const options = unwrapExpression(argument);
1005
- const plugins = readDefinitionSchemaPlugins(module);
1006
1207
  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." });
1007
1208
  if (options.type === "ObjectExpression") {
1008
1209
  assertAuthDatabasePlacement(options, options, authDatabase);
@@ -1010,7 +1211,12 @@ function readDefinitionObjectBody(file) {
1010
1211
  authDatabase,
1011
1212
  body: options,
1012
1213
  callback: false,
1013
- plugins
1214
+ file,
1215
+ pluginCalls: readPluginCalls(module, options),
1216
+ ...readDefinitionSchemaPlugins(module, {
1217
+ ...scan,
1218
+ ownsTables: Boolean(readAuthDatabaseCall(options, authDatabase))
1219
+ }, options, options)
1014
1220
  };
1015
1221
  }
1016
1222
  const returned = readReturnedObject(options);
@@ -1020,7 +1226,12 @@ function readDefinitionObjectBody(file) {
1020
1226
  authDatabase,
1021
1227
  body: returned,
1022
1228
  callback: true,
1023
- plugins
1229
+ file,
1230
+ pluginCalls: readPluginCalls(module, returned),
1231
+ ...readDefinitionSchemaPlugins(module, {
1232
+ ...scan,
1233
+ ownsTables: Boolean(readAuthDatabaseCall(returned, authDatabase))
1234
+ }, options, returned)
1024
1235
  };
1025
1236
  }
1026
1237
  /** Owned tables must have the same target in every request and in the build-time contribution. */
@@ -1040,29 +1251,11 @@ function assertAuthDatabasePlacement(options, body, names) {
1040
1251
  const unconditional = options.body.body.some((statement) => statement.type === "ReturnStatement" && statement.argument && unwrapExpression(statement.argument) === body);
1041
1252
  if (returns !== 1 || !unconditional) throw authDatabasePlacementError();
1042
1253
  }
1043
- const generateId = readObjectPropertyValue(objectLiteral(readObjectPropertyValue(objectLiteral(readObjectPropertyValue(body, "advanced")), "database")), "generateId");
1044
- if (generateId) assertAuthDatabaseIdStrategy(staticValue(generateId));
1254
+ assertAuthDatabaseIdStrategy(readAuthGenerateId(body));
1045
1255
  }
1046
- /** Object entries. `key` is empty for spread and computed keys. `value` is undefined for methods and accessors. */
1047
- function readObjectEntries(body) {
1048
- if (!body) return [];
1049
- return objectProperties(body).map((property) => ({
1050
- key: property.computed ? "" : property.key ?? "",
1051
- value: property.node.type === "Property" && property.node.kind === "init" && !property.node.method ? property.value : void 0
1052
- }));
1053
- }
1054
- function readObjectPropertyValue(body, property) {
1055
- return readObjectEntries(body).findLast((entry) => entry.key === property)?.value;
1056
- }
1057
- function hasObjectProperty(body, property) {
1058
- return readObjectEntries(body).some((entry) => entry.key === property);
1059
- }
1060
- function objectLiteral(value) {
1061
- return value?.type === "ObjectExpression" ? value : void 0;
1062
- }
1063
- function readStaticBooleanLiteral(expression) {
1064
- const value = expression && staticValue(expression);
1065
- return typeof value === "boolean" ? value : void 0;
1256
+ function readAuthGenerateId(body) {
1257
+ const generateId = readObjectPropertyValue(objectLiteral(readObjectPropertyValue(objectLiteral(readObjectPropertyValue(body, "advanced")), "database")), "generateId");
1258
+ return generateId && staticValue(generateId);
1066
1259
  }
1067
1260
  function readStaticStringProperty(body, property, label) {
1068
1261
  if (!hasObjectProperty(body, property)) return;
@@ -1107,15 +1300,17 @@ function readAuthAccessRoute(entry, index) {
1107
1300
  assertOnlyObjectKeys(routeObject, /* @__PURE__ */ new Set([
1108
1301
  "authorize",
1109
1302
  "method",
1303
+ "role",
1110
1304
  "route"
1111
1305
  ]), `access.routes[${index}]`);
1112
1306
  const resolvedRoute = readStaticRouteProperty(routeObject, "route", `access.routes[${index}].route`);
1113
1307
  if (!resolvedRoute) throw authErrorDiagnostics.AUTH_C0011({ message: `\`defineAuth()\` access.routes[${index}].route is required.` });
1114
1308
  assertLiteralAccessRoute(resolvedRoute, `access.routes[${index}].route`);
1115
1309
  const method = readStaticStringProperty(routeObject, "method", `access.routes[${index}].method`);
1116
- const authorize = readObjectEntries(routeObject).find((entry) => entry.key === "authorize");
1310
+ const keys = readObjectEntries(routeObject).map((entry) => entry.key);
1117
1311
  const resolved = { route: resolvedRoute };
1118
- if (authorize) resolved.authorize = true;
1312
+ if (keys.includes("authorize")) resolved.authorize = true;
1313
+ if (keys.includes("role")) resolved.role = true;
1119
1314
  if (method) resolved.method = method;
1120
1315
  return resolved;
1121
1316
  }
@@ -1208,27 +1403,146 @@ function readAuthDatabaseCall(body, authDatabase) {
1208
1403
  const expression = value && unwrapExpression(value);
1209
1404
  return expression?.type === "CallExpression" && expression.callee.type === "Identifier" && authDatabase.has(expression.callee.name) ? expression : void 0;
1210
1405
  }
1406
+ function readAuthExtension(file, scan) {
1407
+ const module = scanModule(readFileSync(file, "utf8"), file);
1408
+ const invalid = (option) => authErrorDiagnostics.AUTH_EXTENSION_OPTION_INVALID({
1409
+ file: relative(scan.rootDir, file),
1410
+ option
1411
+ });
1412
+ const call = defaultExportExpression(module);
1413
+ const argument = call?.type === "CallExpression" && call.callee.type === "Identifier" && call.callee.name === "extendAuth" ? call.arguments[0] : void 0;
1414
+ const body = argument && argument.type !== "SpreadElement" ? objectLiteral(unwrapExpression(argument)) : void 0;
1415
+ if (!body) throw invalid();
1416
+ const outside = (object, allowed) => readObjectEntries(object).find((entry) => !allowed(entry.key));
1417
+ const option = outside(body, (key) => authExtensionKeys.has(key));
1418
+ if (option) throw invalid(option.key || "...");
1419
+ if (hasObjectProperty(body, "user")) {
1420
+ const user = objectLiteral(readObjectPropertyValue(body, "user"));
1421
+ const userOption = user ? outside(user, (key) => key === "additionalFields") : void 0;
1422
+ if (!user || userOption) throw invalid(`user.${userOption?.key || "..."}`);
1423
+ }
1424
+ return {
1425
+ file,
1426
+ body,
1427
+ pluginCalls: readPluginCalls(module, body),
1428
+ ...readDefinitionSchemaPlugins(module, scan, body, body),
1429
+ additionalFields: readAuthAdditionalFields(body)
1430
+ };
1431
+ }
1432
+ const pluginIdOf = (plugin) => plugin.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
1433
+ function staticFieldAttributes(field) {
1434
+ return effectiveFieldAttributes(Object.fromEntries(readObjectEntries(field).map((entry) => [entry.key, entry.value ? staticValue(entry.value) : dynamic])));
1435
+ }
1436
+ function staticOptionFieldDeclarations(source, rootDir) {
1437
+ return authCoreModels.flatMap((model) => {
1438
+ return readObjectEntries(objectLiteral(readObjectPropertyValue(objectLiteral(readObjectPropertyValue(source.body, model)), "additionalFields"))).flatMap(({ key, value }) => {
1439
+ const attributes = objectLiteral(value);
1440
+ return key && attributes && readObjectEntries(attributes).every((entry) => entry.key) ? [{
1441
+ model,
1442
+ field: key,
1443
+ file: relative(rootDir, source.file),
1444
+ attributes: staticFieldAttributes(attributes)
1445
+ }] : [];
1446
+ });
1447
+ });
1448
+ }
1211
1449
  /**
1212
1450
  * The Database that gets the Better Auth tables (the name that `authDatabase()` receives, `"default"` without one), and
1213
- * the plugins and additional fields that add tables and columns.
1451
+ * the plugins and additional fields that add tables and columns: those of the Definition, then those of each part.
1214
1452
  */
1215
- function readAuthTablesConfig(definition) {
1216
- const { authDatabase, body, plugins } = definition;
1453
+ function readAuthTablesConfig(definition, extensions, rootDir) {
1454
+ const { authDatabase, body } = definition;
1217
1455
  const call = readAuthDatabaseCall(body, authDatabase);
1218
- if (!call) return false;
1219
- const [argument, ...rest] = call.arguments;
1456
+ const [argument, ...rest] = call?.arguments ?? [];
1220
1457
  const name = argument === void 0 ? "default" : argument.type === "SpreadElement" || rest.length ? void 0 : staticString(argument);
1221
1458
  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." });
1222
- const additionalFields = readAuthAdditionalFields(body);
1459
+ const sources = [{
1460
+ ...definition,
1461
+ additionalFields: call ? readAuthAdditionalFields(body) : void 0
1462
+ }, ...extensions];
1463
+ const file = (source) => relative(rootDir, source.file);
1464
+ assertUniquePluginIds(sources.map((source) => ({
1465
+ file: file(source),
1466
+ ids: [...source.plugins.map(pluginIdOf), ...source.pluginFields.map((written) => written.plugin)]
1467
+ })));
1468
+ mergeFieldDeclarations(sources.flatMap((source) => [...staticOptionFieldDeclarations(source, rootDir), ...source.pluginFields.flatMap((written) => written.fields.flatMap(({ model, field, attributes }) => attributes ? [{
1469
+ model,
1470
+ field,
1471
+ file: file(written),
1472
+ attributes
1473
+ }] : []))]), (left, right) => differentFieldAttributes(left, right).filter((key) => left[key] !== dynamic && right[key] !== dynamic));
1474
+ const mergedFields = mergeFieldDeclarations(sources.flatMap((source) => [...Object.entries(source.additionalFields ?? {}).flatMap(([model, fields]) => Object.entries(fields).map(([field, attributes]) => ({
1475
+ model,
1476
+ field,
1477
+ file: file(source),
1478
+ attributes
1479
+ }))), ...source.pluginFields.flatMap((written) => written.fields.flatMap(({ model, field, spec }) => spec ? [{
1480
+ model,
1481
+ field,
1482
+ file: file(written),
1483
+ attributes: spec
1484
+ }] : []))]));
1485
+ if (!call) return false;
1486
+ const plugins = [...new Set(sources.flatMap((source) => source.plugins))].sort();
1487
+ const existing = resolveAuthTableSpecs({ plugins });
1488
+ for (const written of sources.flatMap((source) => source.pluginFields)) for (const { model, field, spec } of written.fields) {
1489
+ const column = existing[model]?.fields[field];
1490
+ if (!spec || !column) continue;
1491
+ const attributes = differentFieldAttributes(spec, column).filter((key) => Object.hasOwn(spec, key));
1492
+ if (attributes.length) throw authErrorDiagnostics.AUTH_PLUGIN_SCHEMA_UNREADABLE({
1493
+ plugin: written.plugin,
1494
+ file: file(written),
1495
+ detail: `${model}.${field} cannot change existing column attributes: ${attributes.join(", ")}`
1496
+ });
1497
+ }
1498
+ const additionalFields = Object.keys(mergedFields).length ? mergedFields : void 0;
1499
+ const uuidIds = readAuthGenerateId(body) === "uuid";
1223
1500
  const schema = {
1224
1501
  ...plugins.length ? { plugins } : {},
1225
- ...additionalFields ? { additionalFields } : {}
1502
+ ...additionalFields ? { additionalFields } : {},
1503
+ ...uuidIds ? { generateId: "uuid" } : {}
1226
1504
  };
1227
- if (!plugins.length && !additionalFields) return { database: name };
1228
- resolveAuthTableSpecs(schema);
1229
- return {
1505
+ const specs = resolveAuthTableSpecs(schema);
1506
+ for (const written of sources.flatMap((source) => source.pluginFields)) {
1507
+ const missing = written.fields.filter(({ model, field }) => Object.hasOwn(specs, model) && !Object.hasOwn(specs[model].fields, field)).map(({ model, field }) => `${model}.${field}`);
1508
+ if (missing.length) throw authErrorDiagnostics.AUTH_PLUGIN_FIELD_NOT_IN_SCHEMA({
1509
+ plugin: written.plugin,
1510
+ file: file(written),
1511
+ fields: missing
1512
+ });
1513
+ }
1514
+ return plugins.length || additionalFields || uuidIds ? {
1230
1515
  database: name,
1231
1516
  schema
1517
+ } : { database: name };
1518
+ }
1519
+ function assertAppKeepsLayerTables(app, serverDirs, scan) {
1520
+ const appSpecs = (database) => app.tables && app.tables.database === database ? resolveAuthTableSpecs(app.tables.schema) : {};
1521
+ for (const layer of discoverLayerAuthDefinitions(serverDirs)) {
1522
+ if (layer.handler === app.handler) continue;
1523
+ const definition = readDefinitionObjectBody(layer.handler, scan);
1524
+ const tables = definition && readAuthTablesConfig(definition, [], scan.rootDir);
1525
+ if (!tables) continue;
1526
+ const kept = appSpecs(tables.database);
1527
+ const dropped = Object.entries(resolveAuthTableSpecs(tables.schema)).flatMap(([model, spec]) => Object.hasOwn(kept, model) ? Object.keys(spec.fields).filter((field) => !Object.hasOwn(kept[model].fields, field)).map((field) => `${model}.${field}`) : [model]);
1528
+ if (dropped.length) throw authErrorDiagnostics.AUTH_LAYER_DEFINITION_REPLACED({
1529
+ app: relative(scan.rootDir, app.handler),
1530
+ layer: relative(scan.rootDir, layer.handler),
1531
+ dropped
1532
+ });
1533
+ }
1534
+ }
1535
+ function summarizeAuthSource(source, rootDir) {
1536
+ const additional = authCoreModels.flatMap((model) => {
1537
+ const value = readObjectPropertyValue(objectLiteral(readObjectPropertyValue(source.body, model)), "additionalFields");
1538
+ return readObjectEntries(objectLiteral(value && unwrapExpression(value))).map((entry) => `${model}.${entry.key}`);
1539
+ });
1540
+ const written = source.pluginFields.flatMap((plugin) => plugin.fields.flatMap(({ model, field }) => authCoreModels.some((core) => core === model) ? [`${model}.${field}`] : []));
1541
+ return {
1542
+ file: source.file,
1543
+ name: relativeDefinitionFile(rootDir, source.file),
1544
+ plugins: source.pluginCalls,
1545
+ fields: [.../* @__PURE__ */ new Set([...additional, ...written])]
1232
1546
  };
1233
1547
  }
1234
1548
  /** Reports `true`, `false`, or an object literal with only `keys`: the removed placement forms, which create no storage. */
@@ -1251,19 +1565,74 @@ function assertAuthStorageConfig(body, callback, authDatabase) {
1251
1565
  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." });
1252
1566
  }
1253
1567
  }
1568
+ function usesAuthDatabase(project) {
1569
+ return Boolean(resolveAuthViteConfig(void 0, project.viteRoot ?? project.projectRoot, project)?.tables);
1570
+ }
1571
+ /**
1572
+ * The client sources: `auth.client.ts` when the app has one, then each `auth.client.extend.ts` in merge order. A part
1573
+ * must be `export default extendAuthClient({ plugins })`.
1574
+ */
1575
+ function readAuthClientSources(client, extensions, rootDir) {
1576
+ const read = (file, part) => {
1577
+ const module = scanModule(readFileSync(file, "utf8"), file);
1578
+ const name = relativeDefinitionFile(rootDir, file);
1579
+ const call = defaultExportExpression(module);
1580
+ const argument = call?.type === "CallExpression" ? call.arguments[0] : void 0;
1581
+ const body = argument && argument.type !== "SpreadElement" ? objectLiteral(unwrapExpression(argument)) : void 0;
1582
+ if (part) {
1583
+ if (!body || call?.type !== "CallExpression" || call.callee.type !== "Identifier" || call.callee.name !== "extendAuthClient") throw authErrorDiagnostics.AUTH_EXTENSION_OPTION_INVALID({ file: name });
1584
+ const option = readObjectEntries(body).find((entry) => entry.key !== "plugins");
1585
+ if (option) throw authErrorDiagnostics.AUTH_EXTENSION_OPTION_INVALID({
1586
+ file: name,
1587
+ option: option.key || "..."
1588
+ });
1589
+ }
1590
+ return {
1591
+ file,
1592
+ name,
1593
+ plugins: readPluginCalls(module, body),
1594
+ fields: []
1595
+ };
1596
+ };
1597
+ return [...client ? [read(client, false)] : [], ...extensions.map((file) => read(file, true))];
1598
+ }
1254
1599
  function resolveAuthViteConfig(options, rootDir = process.cwd(), discovery = {}) {
1255
1600
  if (options === false) return;
1256
- const definition = discoverAuthDefinition(rootDir, discovery);
1257
- if (!definition) return;
1258
- const definitionObject = readDefinitionObjectBody(definition.handler);
1601
+ const projectRoot = discovery.projectRoot ?? rootDir;
1602
+ const found = discoverProjectAuthDefinition({
1603
+ projectRoot,
1604
+ viteRoot: rootDir,
1605
+ serverDirs: discovery.serverDirs
1606
+ });
1607
+ const extensionFiles = discoverAuthExtensions(found?.rootDir ?? projectRoot, discovery);
1608
+ if (!found) {
1609
+ if (extensionFiles[0]) throw authErrorDiagnostics.AUTH_EXTENSION_WITHOUT_DEFINITION({ file: relative(projectRoot, extensionFiles[0]) });
1610
+ return;
1611
+ }
1612
+ const { definition } = found;
1613
+ rootDir = found.rootDir;
1614
+ const scan = {
1615
+ layers: discovery.layerAliases ?? {},
1616
+ rootDir: projectRoot
1617
+ };
1618
+ const definitionObject = readDefinitionObjectBody(definition.handler, scan);
1259
1619
  if (typeof definitionObject === "undefined") throw authErrorDiagnostics.AUTH_C0019({ message: "`defineAuth()` options must be an inline object literal." });
1260
1620
  const body = definitionObject.body;
1261
1621
  assertStaticObjectKeys(body, "options");
1262
1622
  assertAuthStorageConfig(body, definitionObject.callback, definitionObject.authDatabase);
1263
1623
  const basePath = normalizeAuthBasePath(readStaticStringProperty(body, "basePath", "basePath"));
1264
- const abilities = discoverAuthAbilities(rootDir, discovery);
1624
+ const abilities = discoverAuthAbilities(rootDir, { serverDirs: discovery.serverDirs?.slice() });
1265
1625
  const publicRoutes = readAuthAccessPublicConfig(body);
1266
1626
  const components = readAuthComponentsConfig(body);
1627
+ const extensions = extensionFiles.map((file) => readAuthExtension(file, {
1628
+ ...scan,
1629
+ ownsTables: Boolean(readAuthDatabaseCall(body, definitionObject.authDatabase))
1630
+ }));
1631
+ const tables = readAuthTablesConfig(definitionObject, extensions, projectRoot);
1632
+ assertAppKeepsLayerTables({
1633
+ handler: definition.handler,
1634
+ tables
1635
+ }, discovery.serverDirs, scan);
1267
1636
  return {
1268
1637
  ...abilities ? { abilities } : {},
1269
1638
  access: {
@@ -1275,9 +1644,11 @@ function resolveAuthViteConfig(options, rootDir = process.cwd(), discovery = {})
1275
1644
  basePath,
1276
1645
  ...components ? { components } : {},
1277
1646
  definition,
1647
+ projectRoot,
1278
1648
  rootDir,
1279
1649
  route: readAuthRouteConfig(body),
1280
- tables: readAuthTablesConfig(definitionObject),
1650
+ sources: [definitionObject, ...extensions].map((source) => summarizeAuthSource(source, projectRoot)),
1651
+ tables,
1281
1652
  ...!definitionObject.callback && !["database", "preset"].some((key) => hasObjectProperty(body, key)) ? { implicitMemory: true } : {}
1282
1653
  };
1283
1654
  }
@@ -1350,9 +1721,6 @@ const authTableNames = {
1350
1721
  passkey: "passkey"
1351
1722
  };
1352
1723
  // src/existing-tables.ts
1353
- function isRecord(value) {
1354
- return typeof value === "object" && value !== null && !Array.isArray(value);
1355
- }
1356
1724
  function strings(value) {
1357
1725
  return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
1358
1726
  }
@@ -1430,17 +1798,26 @@ const generatedAuthSchema = ".vitehub/auth/schema.ts";
1430
1798
  const cachedAccessRouteGuardName = "vite-hub/auth-cached-access-route-guard";
1431
1799
  const memoryDatabaseGuardName = "vite-hub/auth-memory-database-guard";
1432
1800
  const mergeNoExternal = createNoExternalAddition(authPackageName);
1801
+ /** The specifiers of the Auth tables. Each host resolves them to the generated module, so an app imports the tables that Auth adds. */
1802
+ const authSchemaSpecifiers = ["@vite-hub/auth/schema", "vite-hub/auth/schema"];
1803
+ /** The generated module of the Auth tables, which `authSchemaSpecifiers` resolve to when the Definition uses `authDatabase()`. */
1804
+ function authSchemaModule(config) {
1805
+ return resolve(config.projectRoot, generatedAuthSchema);
1806
+ }
1433
1807
  /**
1434
1808
  * A module that builds the Auth tables with the plugins and additional fields of the Definition, and keeps the SQLite
1435
- * tables that the Database has already as `existing` describes them.
1809
+ * tables that the Database has already as `existing` describes them. It imports the package module by file, because
1810
+ * the package specifier resolves to this module.
1436
1811
  */
1437
- function renderAuthSchemaModule(schema, existing, importBase) {
1812
+ function renderAuthSchemaModule(file, schema, existing) {
1438
1813
  const options = JSON.stringify(schema);
1814
+ const packageModule = JSON.stringify(createImportPath(file, ownModule(import.meta.url, "schema")).replaceAll("\\", "/"));
1439
1815
  return [
1440
1816
  "// Generated by the Auth Vite plugin from the plugins and additional fields of the Auth Definition, and from the Auth",
1441
1817
  "// tables of the latest migration of the Database.",
1442
- `import { createAuthPostgresSchema, createAuthSqliteSchema } from ${JSON.stringify(`${importBase}/schema`)}`,
1818
+ `import { createAuthPostgresSchema, createAuthSqliteSchema } from ${packageModule}`,
1443
1819
  "",
1820
+ `export * from ${packageModule}`,
1444
1821
  `export const authSqliteSchema = createAuthSqliteSchema(${options}${existing ? `, ${JSON.stringify(existing)}` : ""})`,
1445
1822
  `export const authPostgresSchema = createAuthPostgresSchema(${options})`,
1446
1823
  ""
@@ -1473,15 +1850,30 @@ async function readTargetDatabase(context, database) {
1473
1850
  migrationsDir: resolve(context.rootDir, getDefaultMigrationsDir(context.rootDir, target, serverDirs))
1474
1851
  };
1475
1852
  }
1476
- /** Lists the Auth Definition as a serializable inspection summary. */
1853
+ /** Lists each file of the resolved source list, with the plugins and fields it adds, as serializable inspection summaries. */
1477
1854
  function inspectAuthDefinitions(options) {
1478
- return summarizeDefinitions(options.projectRoot, discoverAuthDefinitions(options.rootDir, { serverDirs: options.serverDirs }), "server-auth");
1855
+ if (!options.config) return summarizeDefinitions(options.projectRoot, discoverAuthDefinitions(options.rootDir, { serverDirs: options.serverDirs }), "server-auth");
1856
+ const summary = (source, kind) => ({
1857
+ fields: [...source.plugins.length ? [{
1858
+ label: "Plugins",
1859
+ value: source.plugins.join(", ")
1860
+ }] : [], ...source.fields.length ? [{
1861
+ label: "Fields",
1862
+ value: source.fields.join(", ")
1863
+ }] : []],
1864
+ file: source.name,
1865
+ name: "default",
1866
+ source: kind
1867
+ });
1868
+ const { definition, sources } = options.config;
1869
+ return [...sources.map((source, index) => summary(source, index ? "server-auth-extend" : definition.source)), ...(options.client ?? []).map((source) => summary(source, /\.extend\.[cm]?[jt]s$/.test(source.file) ? "auth-client-extend" : "auth-client"))];
1479
1870
  }
1480
1871
  function createAuthNitroConfig(plugin, options) {
1481
1872
  const viteConfig = {
1482
1873
  root: options.projectRoot,
1483
1874
  nitro: options.nitro,
1484
- ...options.serverDirs ? { [VITEHUB_SERVER_DIRS]: options.serverDirs } : {}
1875
+ ...options.serverDirs ? { [VITEHUB_SERVER_DIRS]: options.serverDirs } : {},
1876
+ ...options.nuxtDiscovery ? { [VITEHUB_NUXT_AUTH_DISCOVERY]: options.nuxtDiscovery } : {}
1485
1877
  };
1486
1878
  if (plugin.config && typeof plugin.config === "function") {
1487
1879
  const dev = options.nitro.dev === true;
@@ -1497,8 +1889,14 @@ function createAuthNitroConfig(plugin, options) {
1497
1889
  function renderAuthDefinitionModule(config, options = { serverEnv: false }) {
1498
1890
  if (!config) return "export const definition = undefined\nexport const getAuthApp = () => undefined\nexport default definition\n";
1499
1891
  const runtimeServer = JSON.stringify(options.runtimeServer ?? privateAuthImport(options.importBase ?? authPackageName, "runtime/server"));
1892
+ const [source, ...extensions] = config.sources;
1500
1893
  return [
1501
- `import definition from ${JSON.stringify(config.definition.handler)}`,
1894
+ ...extensions.length ? [
1895
+ `import authDefinition from ${JSON.stringify(config.definition.handler)}`,
1896
+ ...extensions.map((extension, index) => `import extension${index} from ${JSON.stringify(extension.file)}`),
1897
+ `import { applyAuthExtensions } from ${runtimeServer}`,
1898
+ `const definition = applyAuthExtensions(authDefinition, ${JSON.stringify(source?.name)}, [${extensions.map((extension, index) => `{ file: ${JSON.stringify(extension.name)}, extension: extension${index} }`).join(", ")}])`
1899
+ ] : [`import definition from ${JSON.stringify(config.definition.handler)}`],
1502
1900
  options.testMode ? "export const getAuthApp = () => undefined" : "export { useNitroApp as getAuthApp } from \"nitro/app\"",
1503
1901
  ...options.serverEnv ? [
1504
1902
  `import { setAuthRuntimeEnvResolver } from ${runtimeServer}`,
@@ -1534,7 +1932,7 @@ function renderAuthServerModule(options = {}) {
1534
1932
  return [
1535
1933
  `export * from ${JSON.stringify(serverImport)}`,
1536
1934
  `export { default } from ${JSON.stringify(serverImport)}`,
1537
- `export { createAuthAccessHandler, findVerifiedAuthUserId } from ${JSON.stringify(privateAuthImport(importBase, "internal/server"))}`,
1935
+ `export { createAuthAccessHandler, findVerifiedAuthUserId, sendSessionCookies } from ${JSON.stringify(privateAuthImport(importBase, "internal/server"))}`,
1538
1936
  ""
1539
1937
  ].join("\n");
1540
1938
  }
@@ -1566,15 +1964,29 @@ function authAmbientTypesPath(root) {
1566
1964
  function authServerTypesPath(root) {
1567
1965
  return resolve(root, ".vitehub", "types", "auth-server.d.ts");
1568
1966
  }
1967
+ function renderAuthClientModule(client, extensions) {
1968
+ return [
1969
+ client ? `import options from ${JSON.stringify(client)}` : "const options = undefined",
1970
+ ...extensions.map((extension, index) => `import extension${index} from ${JSON.stringify(extension.file)}`),
1971
+ "export default options",
1972
+ `export const extensions = [${extensions.map((extension, index) => `{ file: ${JSON.stringify(extension.name)}, extension: extension${index} }`).join(", ")}]`,
1973
+ ""
1974
+ ].join("\n");
1975
+ }
1569
1976
  function renderAuthAmbientTypes(options = { serverEnv: false }) {
1977
+ const importBase = options.importBase ?? authPackageName;
1978
+ const defaultOf = (file) => `typeof import(${JSON.stringify(file)}).default`;
1979
+ const definition = options.definition && (options.extensions?.length ? `import(${JSON.stringify(importBase)}).ExtendedAuthDefinition<${defaultOf(options.definition)}, [${options.extensions.map(defaultOf).join(", ")}]>` : defaultOf(options.definition));
1980
+ const client = options.clientExtensions?.length ? `import(${JSON.stringify(`${importBase}/vue`)}).ExtendedAuthClientOptions<${options.client ? defaultOf(options.client) : "{}"}, [${options.clientExtensions.map(defaultOf).join(", ")}]>` : options.client && defaultOf(options.client);
1570
1981
  const entries = [
1571
- ...options.definition ? [`definition: typeof import(${JSON.stringify(options.definition)}).default`] : [],
1982
+ ...definition ? [`definition: ${definition}`] : [],
1572
1983
  ...options.abilities ? [`abilities: typeof import(${JSON.stringify(options.abilities)}).default`] : [],
1573
- ...options.client ? [`client: typeof import(${JSON.stringify(options.client)}).default`] : []
1984
+ ...client ? [`client: ${client}`] : [],
1985
+ ...options.schema ? [`schema: typeof import(${JSON.stringify(options.schema)})`] : []
1574
1986
  ];
1575
1987
  const registry = entries.length ? [`interface AuthRegistry { ${entries.join("; ")} }`] : [];
1576
- if (options.definition) {
1577
- const session = `Pick<import(${JSON.stringify(options.importBase ?? authPackageName)}).AuthAuthorization<{ definition: typeof import(${JSON.stringify(options.definition)}).default }>, "user" | "session">`;
1988
+ if (definition) {
1989
+ const session = `Pick<import(${JSON.stringify(importBase)}).AuthAuthorization<{ definition: ${definition} }>, "user" | "session">`;
1578
1990
  registry.push(`interface AuthRegistry { sessionResult: ${session} }`);
1579
1991
  }
1580
1992
  if (options.serverEnv) return [
@@ -1610,18 +2022,23 @@ function renderAuthServerTypes(importBase = authPackageName) {
1610
2022
  ` export { default } from ${JSON.stringify(serverImport)}`,
1611
2023
  ` export const createAuthAccessHandler: typeof import(${JSON.stringify(privateAuthImport(importBase, "internal/server"))}).createAuthAccessHandler`,
1612
2024
  ` export const findVerifiedAuthUserId: typeof import(${JSON.stringify(privateAuthImport(importBase, "internal/server"))}).findVerifiedAuthUserId`,
2025
+ ` export const sendSessionCookies: typeof import(${JSON.stringify(privateAuthImport(importBase, "internal/server"))}).sendSessionCookies`,
1613
2026
  "}",
1614
2027
  ""
1615
2028
  ].join("\n");
1616
2029
  }
1617
2030
  async function refreshAuthGeneratedFiles(root, config, options = {}) {
2031
+ const typeImport = (file) => typeImportSpecifier(dirname(authAmbientTypesPath(root)), file);
1618
2032
  await Promise.all([
1619
2033
  writeFileIfChanged(resolve(root, generatedAuthAccessMiddlewareHandler), renderAuthAccessMiddlewareHandler(config, options.importBase)),
1620
2034
  writeFileIfChanged(authAmbientTypesPath(root), renderAuthAmbientTypes({
1621
- abilities: config?.abilities && typeImportSpecifier(dirname(authAmbientTypesPath(root)), config.abilities),
1622
- client: options.client && typeImportSpecifier(dirname(authAmbientTypesPath(root)), options.client),
1623
- definition: config && typeImportSpecifier(dirname(authAmbientTypesPath(root)), config.definition.handler),
2035
+ abilities: config?.abilities && typeImport(config.abilities),
2036
+ client: options.client && typeImport(options.client),
2037
+ clientExtensions: options.clientExtensions?.map((extension) => typeImport(extension.file)),
2038
+ definition: config && typeImport(config.definition.handler),
2039
+ extensions: config?.sources.slice(1).map((extension) => typeImport(extension.file)),
1624
2040
  importBase: options.importBase,
2041
+ schema: config?.tables ? typeImportSpecifier(dirname(authAmbientTypesPath(root)), authSchemaModule(config)) : void 0,
1625
2042
  serverEnv: Boolean(options.serverEnv)
1626
2043
  })),
1627
2044
  writeFileIfChanged(authServerTypesPath(root), renderAuthServerTypes(options.importBase)),
@@ -1702,12 +2119,23 @@ function hubAuth(options, internalOptions = {}) {
1702
2119
  let resolved;
1703
2120
  let runtimeConfig;
1704
2121
  let clientFile;
2122
+ let clientSources = [];
2123
+ const clientExtensions = () => clientSources.filter((source) => source.file !== clientFile);
1705
2124
  let serverDirs;
2125
+ let nuxtDiscovery;
1706
2126
  let serverEnv = false;
2127
+ function readViteAuthConfig(config) {
2128
+ const root = resolve(config.root ?? process.cwd());
2129
+ const projectRoot = config[VITEHUB_PROJECT_ROOT];
2130
+ return resolveAuthViteConfig(options, root, {
2131
+ projectRoot: projectRoot ? resolve(projectRoot) : resolveViteHubProjectRoot(root),
2132
+ serverDirs,
2133
+ layerAliases: nuxtDiscovery?.layerAliases ?? internalOptions.layerAliases
2134
+ });
2135
+ }
1707
2136
  function refreshRuntimeConfig() {
1708
2137
  if (!resolved) return;
1709
- runtimeConfig = resolveAuthViteConfig(options, resolved.root, { serverDirs });
1710
- runtimeConfig ??= resolveAuthViteConfig(options, resolveViteHubProjectRoot(resolved.root), { serverDirs });
2138
+ runtimeConfig = readViteAuthConfig(resolved);
1711
2139
  resetAuth();
1712
2140
  return runtimeConfig;
1713
2141
  }
@@ -1724,25 +2152,24 @@ function hubAuth(options, internalOptions = {}) {
1724
2152
  async databases(context) {
1725
2153
  const authOptions = options;
1726
2154
  if (authOptions === false) return [];
1727
- const root = context.projectRoot ?? context.root;
1728
- const discovery = { serverDirs: context.serverDirs?.slice() ?? serverDirs };
1729
- const config = resolveAuthViteConfig(authOptions, root, discovery) ?? resolveAuthViteConfig(authOptions, resolveViteHubProjectRoot(root), discovery);
2155
+ const config = resolveAuthViteConfig(authOptions, context.root, {
2156
+ projectRoot: context.projectRoot ?? resolveViteHubProjectRoot(context.root),
2157
+ serverDirs: context.serverDirs ?? serverDirs,
2158
+ layerAliases: nuxtDiscovery?.layerAliases ?? internalOptions.layerAliases
2159
+ });
1730
2160
  if (!config?.tables) return [];
1731
2161
  const { database, schema } = config.tables;
1732
- const schemaModule = resolve(config.rootDir, generatedAuthSchema);
2162
+ const schemaModule = authSchemaModule(config);
1733
2163
  const { dialect, migrationsDir } = await readTargetDatabase(context, database);
1734
2164
  const tables = schema ? Object.fromEntries(Object.keys(resolveAuthTableSpecs(schema)).map((model) => [model, authSqlName(model)])) : authTableNames;
1735
2165
  const existing = dialect === "sqlite" ? readAuthExistingTables(migrationsDir, Object.values(tables)) : void 0;
1736
- const adopted = existing && Object.keys(existing).length ? existing : void 0;
1737
- const generated = Boolean(schema || adopted);
1738
- if (generated) await writeFileIfChanged(schemaModule, renderAuthSchemaModule(schema ?? {}, adopted, importBase));
1739
- else await rm(schemaModule, { force: true });
2166
+ await writeFileIfChanged(schemaModule, renderAuthSchemaModule(schemaModule, schema ?? {}, existing && Object.keys(existing).length ? existing : void 0));
1740
2167
  return [{
1741
2168
  name: "auth",
1742
2169
  database,
1743
2170
  dialect,
1744
2171
  definition: {
1745
- module: generated ? schemaModule : `${importBase}/schema`,
2172
+ module: schemaModule,
1746
2173
  export: dialect === "postgresql" ? "authPostgresSchema" : "authSqliteSchema"
1747
2174
  },
1748
2175
  tables,
@@ -1757,6 +2184,8 @@ function hubAuth(options, internalOptions = {}) {
1757
2184
  list: () => {
1758
2185
  const rootDir = resolve(resolved?.root ?? process.cwd());
1759
2186
  return inspectAuthDefinitions({
2187
+ client: clientSources,
2188
+ config: runtimeConfig,
1760
2189
  projectRoot: resolveViteHubProjectRoot(rootDir),
1761
2190
  rootDir,
1762
2191
  serverDirs
@@ -1767,8 +2196,11 @@ function hubAuth(options, internalOptions = {}) {
1767
2196
  },
1768
2197
  config(config, env) {
1769
2198
  const configRoot = config.root || process.cwd();
1770
- serverDirs = config["__vitehubServerDirs"] ?? serverDirs;
1771
- const authConfig = resolveAuthViteConfig(options, configRoot, { serverDirs }) ?? resolveAuthViteConfig(options, resolveViteHubProjectRoot(configRoot), { serverDirs });
2199
+ const discovery = config;
2200
+ serverDirs = discovery["__vitehubServerDirs"] ?? serverDirs;
2201
+ nuxtDiscovery = discovery["__vitehubNuxtAuthDiscovery"] ?? nuxtDiscovery;
2202
+ const authConfig = readViteAuthConfig(config);
2203
+ if (authConfig?.tables && internalOptions.databaseDisabled) throw authErrorDiagnostics.AUTH_DATABASE_DISABLED({ definition: relative(configRoot, authConfig.definition.handler) });
1772
2204
  const dev = env?.command === "serve";
1773
2205
  const nitro = mergeNitroAuthHandler(config.nitro, authConfig, dev);
1774
2206
  const hasNitroHandlers = Boolean(authConfig && (authConfig.route !== false || authConfig.access.routes.length > 0));
@@ -1776,6 +2208,10 @@ function hubAuth(options, internalOptions = {}) {
1776
2208
  const hasMemoryDatabaseGuard = Boolean(authConfig?.implicitMemory && !dev);
1777
2209
  if (hasNitroHandlers || applicationBaseURL || hasMemoryDatabaseGuard) Object.assign(config, { nitro });
1778
2210
  const contribution = {
2211
+ ...authConfig?.tables ? { resolve: { alias: authSchemaSpecifiers.map((find) => ({
2212
+ find,
2213
+ replacement: authSchemaModule(authConfig)
2214
+ })) } } : {},
1779
2215
  optimizeDeps: {
1780
2216
  exclude: [authPackageName, "vite-hub/auth"],
1781
2217
  include: [`${authPackageName} > better-auth/vue`]
@@ -1793,9 +2229,13 @@ function hubAuth(options, internalOptions = {}) {
1793
2229
  resolved = config;
1794
2230
  serverEnv = hasServerEnvIntegration(config);
1795
2231
  const runtimeConfig = refreshRuntimeConfig();
1796
- clientFile = options === false ? void 0 : discoverAuthClient(config.root);
1797
- await refreshAuthGeneratedFiles(resolveViteHubProjectRoot(config.root), runtimeConfig, {
2232
+ const projectRoot = resolveViteHubProjectRoot(config.root);
2233
+ const appDir = nuxtDiscovery?.appDir ?? config.root;
2234
+ clientFile = options === false ? void 0 : discoverAuthClient(appDir, nuxtDiscovery);
2235
+ clientSources = options === false ? [] : readAuthClientSources(clientFile, discoverAuthClientExtensions(appDir, nuxtDiscovery), projectRoot);
2236
+ await refreshAuthGeneratedFiles(projectRoot, runtimeConfig, {
1798
2237
  client: clientFile,
2238
+ clientExtensions: clientExtensions(),
1799
2239
  importBase,
1800
2240
  serverEnv
1801
2241
  });
@@ -1815,6 +2255,7 @@ function hubAuth(options, internalOptions = {}) {
1815
2255
  const config = refreshRuntimeConfig();
1816
2256
  await refreshAuthGeneratedFiles(projectRoot, config, {
1817
2257
  client: clientFile,
2258
+ clientExtensions: clientExtensions(),
1818
2259
  importBase,
1819
2260
  serverEnv
1820
2261
  });
@@ -1838,10 +2279,11 @@ function hubAuth(options, internalOptions = {}) {
1838
2279
  },
1839
2280
  async handleHotUpdate(context) {
1840
2281
  const changed = context.file.replace(/\\/g, "/");
1841
- 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;
2282
+ if (changed !== runtimeConfig?.definition.handler.replace(/\\/g, "/") && !/\/?server\.auth\.(?:c|m)?[jt]s$/i.test(changed) && !/\/server\/auth(?:\.extend)?\.(?:c|m)?[jt]s$/i.test(changed)) return;
1842
2283
  const config = refreshRuntimeConfig();
1843
2284
  await refreshAuthGeneratedFiles(resolveViteHubProjectRoot(context.server.config.root), config, {
1844
2285
  client: clientFile,
2286
+ clientExtensions: clientExtensions(),
1845
2287
  importBase,
1846
2288
  serverEnv
1847
2289
  });
@@ -1858,7 +2300,7 @@ function hubAuth(options, internalOptions = {}) {
1858
2300
  filter: { id: /^#vitehub\/auth\/(?:abilities|client|definition|server)$/ },
1859
2301
  handler(id) {
1860
2302
  if (id === "#vitehub/auth/abilities") return RESOLVED_AUTH_ABILITIES_ID;
1861
- if (id === "#vitehub/auth/client") return clientFile ?? RESOLVED_AUTH_CLIENT_ID;
2303
+ if (id === "#vitehub/auth/client") return clientExtensions().length ? RESOLVED_AUTH_CLIENT_ID : clientFile ?? RESOLVED_AUTH_CLIENT_ID;
1862
2304
  if (id === "#vitehub/auth/definition") return RESOLVED_AUTH_DEFINITION_ID;
1863
2305
  if (id === "#vitehub/auth/server") return RESOLVED_AUTH_SERVER_ID;
1864
2306
  }
@@ -1867,7 +2309,7 @@ function hubAuth(options, internalOptions = {}) {
1867
2309
  filter: { id: /^\0(?:virtual:vitehub\/auth\/(?:abilities|client)|#vitehub\/auth\/(?:definition|server))$/ },
1868
2310
  handler(id) {
1869
2311
  if (id === RESOLVED_AUTH_ABILITIES_ID) return renderAuthAbilitiesModule(runtimeConfig);
1870
- if (id === RESOLVED_AUTH_CLIENT_ID) return "export default undefined\n";
2312
+ if (id === RESOLVED_AUTH_CLIENT_ID) return clientExtensions().length ? renderAuthClientModule(clientFile, clientExtensions()) : "export default undefined\n";
1871
2313
  if (id === RESOLVED_AUTH_DEFINITION_ID) return renderAuthDefinitionModule(runtimeConfig, {
1872
2314
  importBase,
1873
2315
  serverEnv,
@@ -1878,4 +2320,4 @@ function hubAuth(options, internalOptions = {}) {
1878
2320
  }
1879
2321
  };
1880
2322
  }
1881
- export { AUTH_VITE_PLUGIN_NAME as a, writeNuxtAuthDefinition as c, cachingRuleNames as d, createCachingRouteRuleFinder as f, resolveViteHubProjectRoot as h, AUTH_SERVER_ID as i, resolveAuthViteConfig as l, resolveNuxtServerDirs as m, AUTH_CLIENT_ID as n, createAuthNitroConfig as o, methodOrder as p, AUTH_DEFINITION_ID as r, hubAuth as s, AUTH_ABILITIES_ID as t, authAbilitiesCandidates as u };
2323
+ export { resolveViteHubProjectRoot as C, resolveNuxtServerDirs as S, createCachingRouteRuleFinder as _, AUTH_VITE_PLUGIN_NAME as a, VITEHUB_SERVER_DIRS as b, createAuthNitroConfig as c, resolveAuthViteConfig as d, usesAuthDatabase as f, cachingRuleNames as g, discoverProjectAuthDefinition as h, AUTH_SERVER_ID as i, hubAuth as l, discoverAuthExtensions as m, AUTH_CLIENT_ID as n, authSchemaModule as o, authAbilitiesCandidates as p, AUTH_DEFINITION_ID as r, authSchemaSpecifiers as s, AUTH_ABILITIES_ID as t, writeNuxtAuthDefinition as u, methodOrder as v, resolveNuxtAuthDiscovery as x, VITEHUB_NUXT_AUTH_DISCOVERY as y };