kitcn 0.12.27 → 0.13.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 (73) hide show
  1. package/dist/aggregate/index.d.ts +1 -1
  2. package/dist/aggregate/index.js +1 -1
  3. package/dist/auth/client/index.d.ts +312 -4
  4. package/dist/auth/client/index.js +17 -5
  5. package/dist/auth/config/index.d.ts +1 -1
  6. package/dist/auth/generated/index.d.ts +1 -1
  7. package/dist/auth/generated/index.js +1 -1
  8. package/dist/auth/http/index.d.ts +12 -9
  9. package/dist/auth/http/index.js +35 -6
  10. package/dist/auth/index.d.ts +292 -8
  11. package/dist/auth/index.js +29 -23
  12. package/dist/auth/nextjs/index.d.ts +4 -3
  13. package/dist/auth/nextjs/index.js +9 -4
  14. package/dist/auth/start/index.d.ts +13 -3
  15. package/dist/auth/start/index.js +97 -8
  16. package/dist/{backend-core-DqCCa0nr.mjs → backend-core-yq-eWLRJ.mjs} +140 -54
  17. package/dist/{builder-Cb6gloDB.js → builder-DBgto1yn.js} +4 -3
  18. package/dist/{caller-factory-cTXNvYdz.js → caller-factory-NEfgD5E0.js} +3 -3
  19. package/dist/cli.mjs +26 -26
  20. package/dist/convex-plugin-C3N9BB-J.js +275 -0
  21. package/dist/convex-plugin-tWTDqoKJ.mjs +276 -0
  22. package/dist/{create-schema-orm-DOyiNDCx.js → create-schema-orm-B3f2Kc8O.js} +1 -1
  23. package/dist/crpc/index.d.ts +2 -2
  24. package/dist/crpc/index.js +3 -3
  25. package/dist/{customFunctions-C0voKmtx.js → customFunctions-DxEEO4Dq.js} +2 -1
  26. package/dist/{generated-contract-disabled-21YxPk5W.d.ts → generated-contract-disabled-C_-KWRfT.d.ts} +4 -2
  27. package/dist/{http-types-BLFA9zS7.d.ts → http-types-zsMHb_QN.d.ts} +2 -2
  28. package/dist/{middleware-DkIhQXwg.js → middleware-Bg-PdtrI.js} +1 -1
  29. package/dist/{middleware-nS_qXecO.d.ts → middleware-DrtexzF3.d.ts} +1 -1
  30. package/dist/orm/index.d.ts +3 -3
  31. package/dist/orm/index.js +3 -3
  32. package/dist/plugins/index.d.ts +1 -1
  33. package/dist/plugins/index.js +1 -1
  34. package/dist/{procedure-caller-AjLfkHyF.js → procedure-caller-DplSC7Us.js} +2 -2
  35. package/dist/{procedure-name-D-fDCBlo.d.ts → procedure-name-BCRBr6Po.d.ts} +3 -3
  36. package/dist/ratelimit/index.d.ts +2 -2
  37. package/dist/ratelimit/index.js +3 -3
  38. package/dist/react/index.d.ts +18 -14
  39. package/dist/react/index.js +14 -27
  40. package/dist/rsc/index.d.ts +4 -4
  41. package/dist/rsc/index.js +4 -4
  42. package/dist/{runtime-CtvJPkur.js → runtime-i6t-HoZn.js} +1 -1
  43. package/dist/server/index.d.ts +4 -4
  44. package/dist/server/index.js +4 -4
  45. package/dist/solid/index.d.ts +300 -4
  46. package/dist/token-B9Bjcqug.d.ts +13 -0
  47. package/dist/token-tpipF-7y.js +47 -0
  48. package/dist/{types-C6pQrnzD.d.ts → types-YHpe0rsb.d.ts} +1 -1
  49. package/dist/upstream-BR6sBLg3.js +84 -0
  50. package/dist/upstream-BUCdbLok.mjs +26 -0
  51. package/dist/{validators-B7oIJCAp.js → validators-C7LelqTN.js} +2 -84
  52. package/dist/watcher.mjs +1 -1
  53. package/dist/{where-clause-compiler-DdjN63Io.d.ts → where-clause-compiler-TMppDl9g.d.ts} +51 -51
  54. package/package.json +5 -4
  55. package/skills/convex/references/features/auth.md +20 -0
  56. package/skills/convex/references/features/orm.md +9 -0
  57. package/skills/convex/references/setup/auth.md +2 -0
  58. package/skills/convex/references/setup/index.md +5 -5
  59. package/skills/convex/references/setup/server.md +1 -1
  60. /package/dist/{api-entry-BUAh_K4k.js → api-entry-N3nBOlI2.js} +0 -0
  61. /package/dist/{context-utils-BvWW0Ilq.d.ts → context-utils-OMkMGhBk.d.ts} +0 -0
  62. /package/dist/{create-schema-odyF4kCy.js → create-schema-BXrKE2YY.js} +0 -0
  63. /package/dist/{error-BZEnI7Sq.js → error-Bvo7YEhk.js} +0 -0
  64. /package/dist/{generated-contract-disabled-Cih4eITO.js → generated-contract-disabled-BXaz7JCE.js} +0 -0
  65. /package/dist/{meta-utils-0Pu0Nrap.js → meta-utils-D9K4fICl.js} +0 -0
  66. /package/dist/{query-context-CFZqIvD7.d.ts → query-context-CNo9ffvI.d.ts} +0 -0
  67. /package/dist/{query-context-B8o6-8kC.js → query-context-ydn9kb6P.js} +0 -0
  68. /package/dist/{query-options-Dw7cOyXl.js → query-options-C96zLANM.js} +0 -0
  69. /package/dist/{transformer-DtDhR3Lc.js → transformer-C6pGVHqx.js} +0 -0
  70. /package/dist/{types-BiJE7qxR.d.ts → types-BCl8gfGy.d.ts} +0 -0
  71. /package/dist/{types-a-RHmrDZ.d.ts → types-CnTpHR1F.d.ts} +0 -0
  72. /package/dist/{types-BTb_4BaU.d.ts → types-DF2cg_w0.d.ts} +0 -0
  73. /package/dist/{validators-vzRKjBJC.d.ts → validators-BhsByJeg.d.ts} +0 -0
package/dist/cli.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { $ as resolveAddTemplateDefaults, A as resolveConfiguredBackend, B as runConvexInitIfNeeded, C as isInitialized, D as readPackageVersions, E as parseInitCommandArgs, Et as highlighter, F as runAfterScaffoldScript, G as trackProcess, H as runInitCommandFlow, I as runAggregateBackfillFlow, J as createSpinner, K as withLocalCodegenEnv, L as runAggregatePruneFlow, M as resolveInitProjectDir, N as resolveMigrationConfig, O as resolveBackfillConfig, P as resolveRunDeps, Q as promptForScaffoldTemplateSelection, R as runBackendFunction, S as isEntryPoint, St as stripConvexCommandNoise, T as parseBackendRunJson, Tt as logger, U as runMigrationCreate, V as runDevSchemaBackfillIfNeeded, W as runMigrationFlow, X as filterScaffoldTemplatePathMap, Y as collectPluginScaffoldTemplates, Z as promptForPluginSelection, _ as formatInfoOutput, _t as applyPluginDependencyInstall, a as cleanup, at as getSupportedPluginKeys, b as hasRemoteConvexDeploymentEnv, bt as resolveAuthEnvState, c as createCommandEnv, ct as resolvePluginScaffoldRoots, d as extractBackfillCliOptions, dt as getPluginLockfilePath, et as resolvePluginPreset, f as extractConcaveRunTargetArgs, ft as getSchemaFilePath, g as formatDocsOutput, gt as applyPlanningDependencyInstall, h as extractResetCliOptions, ht as applyDependencyHintsInstall, i as buildInitializationPlan, it as getPluginCatalogEntry, j as resolveDocTopic, k as resolveCodegenTrimSegments, l as ensureConvexGitignoreEntry, lt as assertSchemaFileExists, m as extractMigrationDownOptions, mt as resolveSchemaInstalledPlugins, n as applyPluginInstallPlanFiles, nt as resolveTemplateSelectionSource, o as createBackendAdapter, ot as isSupportedPluginKey, p as extractMigrationCliOptions, pt as readPluginLockfile, q as withWorkingDirectory, r as assertNoRemovedDevPreRunFlag, rt as resolveTemplatesByIdOrThrow, s as createBackendCommandEnv, st as buildPluginInstallPlan, t as applyDependencyInstallPlan, tt as resolvePresetScaffoldTemplates, u as extractBackendRunTargetArgs, ut as collectInstalledPluginKeys, v as getAggregateBackfillDeploymentKey, vt as inspectPluginDependencyInstall, w as parseArgs, x as isConvexDevPreRunConflictFlag, xt as serializeEnvValue, y as getDevAggregateBackfillStatePath, yt as resolveProjectScaffoldContext, z as runConfiguredCodegen } from "./backend-core-DqCCa0nr.mjs";
2
+ import { $ as promptForScaffoldTemplateSelection, A as resolveCodegenTrimSegments, B as runConfiguredCodegen, C as isEntryPoint, Ct as serializeEnvValue, D as parseInitCommandArgs, Dt as logger, E as parseBackendRunJson, F as resolveRunDeps, G as runMigrationFlow, H as runDevSchemaBackfillIfNeeded, I as runAfterScaffoldScript, J as withWorkingDirectory, K as trackProcess, L as runAggregateBackfillFlow, M as resolveDocTopic, N as resolveInitProjectDir, O as readPackageVersions, Ot as highlighter, P as resolveMigrationConfig, Q as promptForPluginSelection, R as runAggregatePruneFlow, S as isConvexDevPreRunConflictFlag, St as resolveAuthEnvState, T as parseArgs, U as runInitCommandFlow, V as runConvexInitIfNeeded, W as runMigrationCreate, X as collectPluginScaffoldTemplates, Y as createSpinner, Z as filterScaffoldTemplatePathMap, _ as formatInfoOutput, _t as applyPlanningDependencyInstall, a as cleanup, at as getPluginCatalogEntry, b as getDevAggregateBackfillStatePath, bt as resolveSupportedDependencyWarnings, c as createCommandEnv, ct as buildPluginInstallPlan, d as extractBackfillCliOptions, dt as collectInstalledPluginKeys, et as resolveAddTemplateDefaults, f as extractConcaveRunTargetArgs, ft as getPluginLockfilePath, g as formatDocsOutput, gt as applyDependencyHintsInstall, h as extractResetCliOptions, ht as resolveSchemaInstalledPlugins, i as buildInitializationPlan, it as resolveTemplatesByIdOrThrow, j as resolveConfiguredBackend, k as resolveBackfillConfig, l as ensureConvexGitignoreEntry, lt as resolvePluginScaffoldRoots, m as extractMigrationDownOptions, mt as readPluginLockfile, n as applyPluginInstallPlanFiles, nt as resolvePresetScaffoldTemplates, o as createBackendAdapter, ot as getSupportedPluginKeys, p as extractMigrationCliOptions, pt as getSchemaFilePath, q as withLocalCodegenEnv, r as assertNoRemovedDevPreRunFlag, rt as resolveTemplateSelectionSource, s as createBackendCommandEnv, st as isSupportedPluginKey, t as applyDependencyInstallPlan, tt as resolvePluginPreset, u as extractBackendRunTargetArgs, ut as assertSchemaFileExists, v as getAggregateBackfillDeploymentKey, vt as applyPluginDependencyInstall, w as isInitialized, wt as stripConvexCommandNoise, x as hasRemoteConvexDeploymentEnv, xt as resolveProjectScaffoldContext, y as getConvexDeploymentCommandEnv, yt as inspectPluginDependencyInstall, z as runBackendFunction } from "./backend-core-yq-eWLRJ.mjs";
3
3
  import fs, { existsSync, readFileSync } from "node:fs";
4
4
  import path, { delimiter, dirname, join, relative, resolve } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
@@ -381,7 +381,7 @@ function filterDevStartupLine(rawLine) {
381
381
  const line = stripConvexCommandNoise(rawLine).trim();
382
382
  if (!line) return { kind: "skip" };
383
383
  if (DEV_SUPPRESSED_LINE_PATTERNS.some((pattern) => pattern.test(line))) return { kind: "skip" };
384
- if (line.includes("Finished running function \"init\"") || line.includes("CONVEX_AGENT_MODE=anonymous mode is in beta") || line.includes("Convex AI files are not installed.") || line.includes("Preparing Convex functions...") || line.includes("Bundling component schemas and implementations") || line.includes("Uploading functions to Convex")) return { kind: "skip" };
384
+ if (line.includes("Finished running function \"init\"") || line.includes("Convex AI files are not installed.") || line.includes("Preparing Convex functions...") || line.includes("Bundling component schemas and implementations") || line.includes("Uploading functions to Convex")) return { kind: "skip" };
385
385
  if (DEV_READY_LINE_RE.test(line)) return {
386
386
  kind: "ready",
387
387
  message: line.toLowerCase().includes("concave") ? "Concave ready" : "Convex ready"
@@ -652,12 +652,6 @@ function resolveImplicitConvexRemoteDeploymentEnv(cwd = process.cwd()) {
652
652
  CONVEX_SELF_HOSTED_ADMIN_KEY: parsed.CONVEX_SELF_HOSTED_ADMIN_KEY
653
653
  };
654
654
  }
655
- function resolveImplicitConvexAnonymousAgentMode(cwd = process.cwd()) {
656
- const envLocalPath = join(cwd, ".env.local");
657
- if (!fs.existsSync(envLocalPath)) return;
658
- const deployment = parseEnv(fs.readFileSync(envLocalPath, "utf8")).CONVEX_DEPLOYMENT?.trim();
659
- if (deployment === "anonymous-agent" || deployment?.startsWith("anonymous:")) return "anonymous";
660
- }
661
655
  function resolveConvexEnvFileCommandEnv(args, cwd = process.cwd()) {
662
656
  let envFilePath = null;
663
657
  for (let i = 0; i < args.length; i += 1) {
@@ -880,12 +874,11 @@ const handleDevCommand = async (argv, deps) => {
880
874
  const explicitConvexTargetArgs = extractBackendRunTargetArgs("convex", convexDevArgs);
881
875
  const explicitConvexCommandEnv = resolveConvexEnvFileCommandEnv(convexDevArgs);
882
876
  const implicitConvexCommandEnv = backend === "convex" && explicitConvexTargetArgs.length === 0 && explicitConvexCommandEnv === null ? resolveImplicitConvexRemoteDeploymentEnv() : null;
883
- const implicitConvexAgentMode = backend === "convex" && explicitConvexTargetArgs.length === 0 && !explicitConvexCommandEnv?.CONVEX_AGENT_MODE && !implicitConvexCommandEnv?.CONVEX_AGENT_MODE ? resolveImplicitConvexAnonymousAgentMode() : void 0;
884
877
  const effectiveConvexCommandEnv = explicitConvexCommandEnv ?? implicitConvexCommandEnv;
885
878
  const preRunFunction = config.dev.preRun;
886
879
  if (bootstrap && backend !== "convex") throw new Error("`kitcn dev --bootstrap` is only supported for backend convex.");
887
880
  if (preRunFunction && backend === "concave") throw new Error("`dev.preRun` is only supported for backend convex. Concave dev has no equivalent `--run` flow.");
888
- if (preRunFunction && convexDevArgs.some((arg) => isConvexDevPreRunConflictFlag(arg))) throw new Error("`dev.preRun` cannot be combined with Convex dev run flags (`--run`, `--run-sh`, `--run-component`).");
881
+ if (preRunFunction && convexDevArgs.some((arg) => isConvexDevPreRunConflictFlag(arg))) throw new Error("`dev.preRun` cannot be combined with Convex dev run flags (`--run`, `--start`, `--run-sh`, `--run-component`).");
889
882
  const backendAdapter = createBackendAdapter({
890
883
  backend,
891
884
  realConvexPath,
@@ -926,8 +919,7 @@ const handleDevCommand = async (argv, deps) => {
926
919
  echoOutput: false,
927
920
  env: {
928
921
  ...localNodeEnvOverrides,
929
- ...effectiveConvexCommandEnv,
930
- ...implicitConvexAgentMode ? { CONVEX_AGENT_MODE: implicitConvexAgentMode } : {}
922
+ ...effectiveConvexCommandEnv
931
923
  },
932
924
  targetArgs
933
925
  });
@@ -980,7 +972,6 @@ const handleDevCommand = async (argv, deps) => {
980
972
  env: createBackendCommandEnv({
981
973
  ...localNodeEnvOverrides,
982
974
  ...effectiveConvexCommandEnv,
983
- ...implicitConvexAgentMode ? { CONVEX_AGENT_MODE: implicitConvexAgentMode } : {},
984
975
  ...concaveLocalDevContract?.backendEnv
985
976
  }),
986
977
  reject: false
@@ -1781,6 +1772,7 @@ const handleDeployCommand = async (argv, deps = {}) => {
1781
1772
  const { remainingArgs: deployArgsWithoutMigrationFlags, overrides: deployMigrationOverrides } = extractMigrationCliOptions(parsed.convexArgs);
1782
1773
  const { remainingArgs: deployCommandArgs, overrides: deployBackfillOverrides } = extractBackfillCliOptions(deployArgsWithoutMigrationFlags);
1783
1774
  const deployArgs = [...config.deploy.args, ...deployCommandArgs];
1775
+ const deployCommandEnv = backend === "convex" ? getConvexDeploymentCommandEnv() : void 0;
1784
1776
  const deployResult = await execaFn(backendAdapter.command, [
1785
1777
  ...backendAdapter.argsPrefix,
1786
1778
  "deploy",
@@ -1788,7 +1780,7 @@ const handleDeployCommand = async (argv, deps = {}) => {
1788
1780
  ], {
1789
1781
  stdio: "inherit",
1790
1782
  cwd: process.cwd(),
1791
- env: createBackendCommandEnv(),
1783
+ env: createBackendCommandEnv(deployCommandEnv),
1792
1784
  reject: false
1793
1785
  });
1794
1786
  if ((deployResult.exitCode ?? 1) !== 0) return deployResult.exitCode ?? 1;
@@ -1800,6 +1792,7 @@ const handleDeployCommand = async (argv, deps = {}) => {
1800
1792
  backendAdapter,
1801
1793
  migrationConfig,
1802
1794
  targetArgs,
1795
+ env: deployCommandEnv,
1803
1796
  context: "deploy",
1804
1797
  direction: "up"
1805
1798
  });
@@ -1810,6 +1803,7 @@ const handleDeployCommand = async (argv, deps = {}) => {
1810
1803
  backfillConfig,
1811
1804
  mode: "resume",
1812
1805
  targetArgs,
1806
+ env: deployCommandEnv,
1813
1807
  context: "deploy"
1814
1808
  });
1815
1809
  };
@@ -2470,16 +2464,6 @@ Options:
2470
2464
  function assertNoVerifyLifecycleFlags(args) {
2471
2465
  if (args.includes("--once") || args.includes("--bootstrap")) throw new Error("`kitcn verify` already runs one-shot runtime proof. Do not pass `--once` or `--bootstrap`.");
2472
2466
  }
2473
- async function withAnonymousVerifyAgentMode(run) {
2474
- const previous = process.env.CONVEX_AGENT_MODE;
2475
- if (!previous) process.env.CONVEX_AGENT_MODE = "anonymous";
2476
- try {
2477
- return await run();
2478
- } finally {
2479
- if (previous === void 0) delete process.env.CONVEX_AGENT_MODE;
2480
- else process.env.CONVEX_AGENT_MODE = previous;
2481
- }
2482
- }
2483
2467
  function hasConfiguredLocalConvexDeployment(cwd = process.cwd()) {
2484
2468
  return fs.existsSync(path.join(cwd, ".convex", "local", "default", "config.json"));
2485
2469
  }
@@ -2524,7 +2508,7 @@ const handleVerifyCommand = async (argv, deps) => {
2524
2508
  if (getAggregateBackfillDeploymentKey(extractBackendRunTargetArgs(backend, parsed.convexArgs)) !== "local") throw new Error("`kitcn verify` is local-only. Remove remote deployment flags like `--prod`, `--preview-name`, and `--deployment-name`.");
2525
2509
  const devArgv = buildVerifyDevArgv(argv);
2526
2510
  if (hasConfiguredLocalConvexDeployment()) return handleDevCommand(devArgv, deps);
2527
- return withIsolatedLocalConvexState(() => withAnonymousVerifyAgentMode(() => handleDevCommand(devArgv, deps)));
2511
+ return withIsolatedLocalConvexState(() => handleDevCommand(devArgv, deps));
2528
2512
  };
2529
2513
 
2530
2514
  //#endregion
@@ -2654,6 +2638,15 @@ const LOCAL_NODE_REEXEC_COMMANDS = new Set([
2654
2638
  "init",
2655
2639
  "verify"
2656
2640
  ]);
2641
+ const DEPENDENCY_WARNING_COMMANDS = new Set([
2642
+ "add",
2643
+ "codegen",
2644
+ "deploy",
2645
+ "dev",
2646
+ "env",
2647
+ "init",
2648
+ "verify"
2649
+ ]);
2657
2650
  const COMMAND_HELP = {
2658
2651
  init: INIT_HELP_TEXT,
2659
2652
  add: ADD_HELP_TEXT,
@@ -2759,6 +2752,10 @@ const printCommandHelp = (command, backend = "convex") => {
2759
2752
  }
2760
2753
  printRootHelp(backend);
2761
2754
  };
2755
+ function warnSupportedDependencyIssues(command) {
2756
+ if (!DEPENDENCY_WARNING_COMMANDS.has(command)) return;
2757
+ for (const warning of resolveSupportedDependencyWarnings()) logger.warn(`⚠️ kitcn expects ${warning.packageName} ${warning.minimum}; found ${warning.current}. Run \`bun add ${warning.installSpec}\` when you can.`);
2758
+ }
2762
2759
  const handlePassthroughCommand = async (argv, deps) => {
2763
2760
  const parsed = parseArgs(argv);
2764
2761
  const { execa: execaFn, loadCliConfig, realConvex, realConcave } = resolveRunDeps(deps);
@@ -2811,6 +2808,7 @@ async function run(argv, deps) {
2811
2808
  deps
2812
2809
  });
2813
2810
  if (reexecExitCode !== null) return reexecExitCode;
2811
+ warnSupportedDependencyIssues("dev");
2814
2812
  return handleDevCommand(argv, deps);
2815
2813
  }
2816
2814
  if (VERSION_FLAGS.has(argv[0])) {
@@ -2846,7 +2844,9 @@ async function run(argv, deps) {
2846
2844
  printCommandHelp(parsed.command, getBackend());
2847
2845
  return 0;
2848
2846
  }
2849
- return (COMMAND_HANDLERS[parsed.command] ?? handlePassthroughCommand)(argv, deps);
2847
+ const handler = COMMAND_HANDLERS[parsed.command] ?? handlePassthroughCommand;
2848
+ warnSupportedDependencyIssues(parsed.command);
2849
+ return handler(argv, deps);
2850
2850
  }
2851
2851
  if (isEntryPoint(process.argv[1], __filename)) {
2852
2852
  process.on("SIGINT", () => process.exit(0));
@@ -0,0 +1,275 @@
1
+ import { r as omit } from "./upstream-BR6sBLg3.js";
2
+ import { createAuthEndpoint, createAuthMiddleware, sessionMiddleware } from "better-auth/api";
3
+ import { bearer } from "better-auth/plugins/bearer";
4
+ import { jwt } from "better-auth/plugins/jwt";
5
+ import { oidcProvider } from "better-auth/plugins/oidc-provider";
6
+
7
+ //#region src/auth/internal/convex-plugin.ts
8
+ const JWT_COOKIE_NAME = "convex_jwt";
9
+ const normalizeAfterHooks = (hooks) => {
10
+ return hooks.map((hook) => ({
11
+ ...hook,
12
+ matcher: (ctx) => Boolean(hook.matcher(ctx))
13
+ }));
14
+ };
15
+ const getJwksAlg = (authProvider) => {
16
+ const isCustomJwt = "type" in authProvider && authProvider.type === "customJwt";
17
+ if (isCustomJwt && authProvider.algorithm !== "RS256") throw new Error("Only RS256 is supported for custom JWT with Better Auth");
18
+ return isCustomJwt ? authProvider.algorithm : "EdDSA";
19
+ };
20
+ const parseAuthConfig = (authConfig, opts) => {
21
+ const providerConfigs = authConfig.providers.filter((provider) => provider.applicationID === "convex");
22
+ if (providerConfigs.length > 1) throw new Error("Multiple auth providers with applicationID 'convex' detected. Please use only one.");
23
+ const providerConfig = providerConfigs[0];
24
+ if (!providerConfig) throw new Error("No auth provider with applicationID 'convex' found. Please add one to your auth config.");
25
+ if (!("type" in providerConfig) || providerConfig.type !== "customJwt") return providerConfig;
26
+ const isDataUriJwks = providerConfig.jwks?.startsWith("data:text/");
27
+ if (isDataUriJwks && !opts.jwks) throw new Error("Static JWKS detected in auth config, but missing from Convex plugin");
28
+ if (!isDataUriJwks && opts.jwks) console.warn("Static JWKS provided to Convex plugin, but not to auth config. This adds an unnecessary network request for token verification.");
29
+ return providerConfig;
30
+ };
31
+ const convex = (opts) => {
32
+ const jwtExpirationSeconds = opts.jwt?.expirationSeconds ?? opts.jwtExpirationSeconds ?? 900;
33
+ const oidcProvider$1 = oidcProvider({
34
+ loginPage: "/not-used",
35
+ metadata: {
36
+ issuer: `${process.env.CONVEX_SITE_URL}`,
37
+ jwks_uri: `${process.env.CONVEX_SITE_URL}${opts.options?.basePath ?? "/api/auth"}/convex/jwks`
38
+ }
39
+ });
40
+ const providerConfig = parseAuthConfig(opts.authConfig, opts);
41
+ const jwtOptions = {
42
+ jwt: {
43
+ issuer: `${process.env.CONVEX_SITE_URL}`,
44
+ audience: "convex",
45
+ expirationTime: `${jwtExpirationSeconds}s`,
46
+ definePayload: async ({ user, session }) => ({
47
+ ...opts.jwt?.definePayload ? await opts.jwt.definePayload({
48
+ session,
49
+ user
50
+ }) : omit(user, ["id", "image"]),
51
+ sessionId: session.id,
52
+ iat: Math.floor(Date.now() / 1e3)
53
+ })
54
+ },
55
+ jwks: { keyPairConfig: { alg: getJwksAlg(providerConfig) } }
56
+ };
57
+ const jwks = opts.jwks ? JSON.parse(opts.jwks) : void 0;
58
+ const jwt$1 = jwt({
59
+ ...jwtOptions,
60
+ adapter: {
61
+ createJwk: async (webKey, ctx) => {
62
+ if (opts.jwks) throw new Error("Not implemented");
63
+ return await ctx.context.adapter.create({
64
+ model: "jwks",
65
+ data: {
66
+ ...webKey,
67
+ createdAt: /* @__PURE__ */ new Date()
68
+ }
69
+ });
70
+ },
71
+ getJwks: async (ctx) => {
72
+ if (opts.jwks) return jwks;
73
+ return (await ctx.context.adapter.findMany({
74
+ model: "jwks",
75
+ sortBy: {
76
+ direction: "desc",
77
+ field: "createdAt"
78
+ }
79
+ })).map((key) => ({
80
+ ...key,
81
+ createdAt: new Date(key.createdAt),
82
+ ...key.expiresAt ? { expiresAt: new Date(key.expiresAt) } : {}
83
+ }));
84
+ }
85
+ }
86
+ });
87
+ const bearer$1 = bearer();
88
+ const schema = {
89
+ user: { fields: { userId: {
90
+ type: "string",
91
+ required: false,
92
+ input: false
93
+ } } },
94
+ ...jwt$1.schema
95
+ };
96
+ return {
97
+ id: "convex",
98
+ init: (ctx) => {
99
+ const { options } = ctx;
100
+ if (options.basePath !== "/api/auth" && !opts.options?.basePath) console.warn(`Better Auth basePath set to ${options.basePath} but no basePath is set in the Convex plugin. This is probably a mistake.`);
101
+ if (opts.options?.basePath && options.basePath !== opts.options?.basePath) console.warn(`Better Auth basePath ${options.basePath} does not match Convex plugin basePath ${opts.options?.basePath}. This is probably a mistake.`);
102
+ },
103
+ hooks: {
104
+ before: [...bearer$1.hooks.before, {
105
+ matcher: (ctx) => {
106
+ return !ctx.context.adapter.options?.isRunMutationCtx;
107
+ },
108
+ handler: createAuthMiddleware(async (ctx) => {
109
+ ctx.query = {
110
+ ...ctx.query,
111
+ disableRefresh: true
112
+ };
113
+ ctx.context.internalAdapter.deleteSession = async (..._args) => {};
114
+ const knownSafePaths = ["/api-key/list", "/api-key/get"];
115
+ const noopWrite = (method) => {
116
+ return async (..._args) => {
117
+ if (ctx.path && !knownSafePaths.includes(ctx.path)) console.warn(`[convex-better-auth] Write operation "${method}" skipped in query context for ${ctx.path}`);
118
+ return 0;
119
+ };
120
+ };
121
+ ctx.context.adapter.create = noopWrite("create");
122
+ ctx.context.adapter.update = noopWrite("update");
123
+ ctx.context.adapter.updateMany = noopWrite("updateMany");
124
+ ctx.context.adapter.delete = noopWrite("delete");
125
+ ctx.context.adapter.deleteMany = noopWrite("deleteMany");
126
+ return { context: ctx };
127
+ })
128
+ }],
129
+ after: [
130
+ ...normalizeAfterHooks(oidcProvider$1.hooks.after),
131
+ {
132
+ matcher: (ctx) => {
133
+ return Boolean(ctx.path?.startsWith("/sign-in") || ctx.path?.startsWith("/sign-up") || ctx.path?.startsWith("/callback") || ctx.path?.startsWith("/oauth2/callback") || ctx.path?.startsWith("/magic-link/verify") || ctx.path?.startsWith("/email-otp/verify-email") || ctx.path?.startsWith("/phone-number/verify") || ctx.path?.startsWith("/siwe/verify") || ctx.path?.startsWith("/update-session") || ctx.path?.startsWith("/get-session") && ctx.context.session);
134
+ },
135
+ handler: createAuthMiddleware(async (ctx) => {
136
+ const originalSession = ctx.context.session;
137
+ try {
138
+ ctx.context.session = ctx.context.session ?? ctx.context.newSession;
139
+ const { token } = await jwt$1.endpoints.getToken({
140
+ ...ctx,
141
+ headers: {},
142
+ method: "GET",
143
+ returnHeaders: false,
144
+ returnStatus: false
145
+ });
146
+ const jwtCookie = ctx.context.createAuthCookie(JWT_COOKIE_NAME, { maxAge: jwtExpirationSeconds });
147
+ ctx.setCookie(jwtCookie.name, token, jwtCookie.attributes);
148
+ } catch (_error) {}
149
+ ctx.context.session = originalSession;
150
+ })
151
+ },
152
+ {
153
+ matcher: (ctx) => {
154
+ return Boolean(ctx.path?.startsWith("/sign-out") || ctx.path?.startsWith("/delete-user") || ctx.path?.startsWith("/get-session") && !ctx.context.session);
155
+ },
156
+ handler: createAuthMiddleware(async (ctx) => {
157
+ const jwtCookie = ctx.context.createAuthCookie(JWT_COOKIE_NAME, { maxAge: 0 });
158
+ ctx.setCookie(jwtCookie.name, "", jwtCookie.attributes);
159
+ })
160
+ }
161
+ ]
162
+ },
163
+ endpoints: {
164
+ getOpenIdConfig: createAuthEndpoint("/convex/.well-known/openid-configuration", {
165
+ method: "GET",
166
+ metadata: { isAction: false }
167
+ }, async (ctx) => {
168
+ return await oidcProvider$1.endpoints.getOpenIdConfig({
169
+ ...ctx,
170
+ returnHeaders: false,
171
+ returnStatus: false
172
+ });
173
+ }),
174
+ getJwks: createAuthEndpoint("/convex/jwks", {
175
+ method: "GET",
176
+ metadata: { openapi: {
177
+ description: "Get the JSON Web Key Set",
178
+ responses: { "200": { description: "JSON Web Key Set retrieved successfully" } }
179
+ } }
180
+ }, async (ctx) => {
181
+ return await jwt$1.endpoints.getJwks({
182
+ ...ctx,
183
+ returnHeaders: false,
184
+ returnStatus: false
185
+ });
186
+ }),
187
+ getLatestJwks: createAuthEndpoint("/convex/latest-jwks", {
188
+ isAction: true,
189
+ method: "POST",
190
+ metadata: {
191
+ SERVER_ONLY: true,
192
+ openapi: { description: "Delete and regenerate JWKS, and return the new JWKS for static usage" }
193
+ }
194
+ }, async (ctx) => {
195
+ await jwt(jwtOptions).endpoints.getJwks({
196
+ ...ctx,
197
+ method: "GET"
198
+ });
199
+ const jwks = await ctx.context.adapter.findMany({
200
+ model: "jwks",
201
+ limit: 1,
202
+ sortBy: {
203
+ direction: "desc",
204
+ field: "createdAt"
205
+ }
206
+ });
207
+ jwks[0].alg = jwtOptions.jwks.keyPairConfig.alg;
208
+ return jwks;
209
+ }),
210
+ rotateKeys: createAuthEndpoint("/convex/rotate-keys", {
211
+ isAction: true,
212
+ method: "POST",
213
+ metadata: {
214
+ SERVER_ONLY: true,
215
+ openapi: { description: "Delete and regenerate JWKS, and return the new JWKS for static usage" }
216
+ }
217
+ }, async (ctx) => {
218
+ await ctx.context.adapter.deleteMany({
219
+ model: "jwks",
220
+ where: []
221
+ });
222
+ await jwt(jwtOptions).endpoints.getJwks({
223
+ ...ctx,
224
+ method: "GET"
225
+ });
226
+ const jwks = await ctx.context.adapter.findMany({
227
+ model: "jwks",
228
+ limit: 1,
229
+ sortBy: {
230
+ direction: "desc",
231
+ field: "createdAt"
232
+ }
233
+ });
234
+ jwks[0].alg = jwtOptions.jwks.keyPairConfig.alg;
235
+ return jwks;
236
+ }),
237
+ getToken: createAuthEndpoint("/convex/token", {
238
+ method: "GET",
239
+ requireHeaders: true,
240
+ use: [sessionMiddleware],
241
+ metadata: { openapi: { description: "Get a JWT token" } }
242
+ }, async (ctx) => {
243
+ const runEndpoint = async () => {
244
+ const response = await jwt$1.endpoints.getToken({
245
+ ...ctx,
246
+ returnHeaders: false,
247
+ returnStatus: false
248
+ });
249
+ const jwtCookie = ctx.context.createAuthCookie(JWT_COOKIE_NAME, { maxAge: jwtExpirationSeconds });
250
+ ctx.setCookie(jwtCookie.name, response.token, jwtCookie.attributes);
251
+ return response;
252
+ };
253
+ try {
254
+ return await runEndpoint();
255
+ } catch (error) {
256
+ if (!opts.jwks && error?.code === "ERR_JOSE_NOT_SUPPORTED") {
257
+ if (opts.jwksRotateOnTokenGenerationError) {
258
+ await ctx.context.adapter.deleteMany({
259
+ model: "jwks",
260
+ where: []
261
+ });
262
+ return await runEndpoint();
263
+ }
264
+ console.error("Try temporarily setting jwksRotateOnTokenGenerationError: true on the Convex Better Auth plugin.");
265
+ }
266
+ throw error;
267
+ }
268
+ })
269
+ },
270
+ schema
271
+ };
272
+ };
273
+
274
+ //#endregion
275
+ export { convex as n, JWT_COOKIE_NAME as t };