kitcn 0.25.6 → 0.26.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,89 @@
1
1
  # kitcn
2
2
 
3
+ ## 0.26.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#401](https://github.com/udecode/kitcn/pull/401) [`947cd11`](https://github.com/udecode/kitcn/commit/947cd11fe4e461caca9d7cc934ef34d62599e136) Thanks [@MikeyZhang75](https://github.com/MikeyZhang75)! - ## Breaking changes
8
+
9
+ - Require `api` on `convexBetterAuthReactStart`, which now returns `createCaller`
10
+ and `createContext` alongside the auth helpers.
11
+
12
+ ```ts
13
+ // Before
14
+ export const { handler, getToken } = convexBetterAuthReactStart({
15
+ convexUrl: import.meta.env.VITE_CONVEX_URL!,
16
+ convexSiteUrl: import.meta.env.VITE_CONVEX_SITE_URL!,
17
+ });
18
+
19
+ // After
20
+ export const { handler, getToken, createCaller, createContext } =
21
+ convexBetterAuthReactStart({
22
+ api,
23
+ convexUrl: import.meta.env.VITE_CONVEX_URL!,
24
+ convexSiteUrl: import.meta.env.VITE_CONVEX_SITE_URL!,
25
+ });
26
+ ```
27
+
28
+ - Drop `runServerCall` from the TanStack Start scaffold. Call procedures on a
29
+ caller bound once with `createCaller()`.
30
+
31
+ ```ts
32
+ // Before
33
+ export function runServerCall<T>(
34
+ fn: (caller: ServerCaller) => Promise<T> | T
35
+ ) {
36
+ const caller = createServerCaller();
37
+ return fn(caller);
38
+ }
39
+ await runServerCall((caller) => caller.user.getSessionUser({}));
40
+
41
+ // After
42
+ export const caller = createCaller();
43
+ await caller.user.getSessionUser({});
44
+ ```
45
+
46
+ - Move TanStack Start JWT caching under `auth.jwtCache`, a boolean.
47
+
48
+ ```ts
49
+ // Before
50
+ convexBetterAuthReactStart({
51
+ jwtCache: { enabled: true, isAuthError },
52
+ // ...
53
+ });
54
+
55
+ // After
56
+ convexBetterAuthReactStart({
57
+ auth: { jwtCache: true, isUnauthorized: isAuthError },
58
+ // ...
59
+ });
60
+ ```
61
+
62
+ ## Patches
63
+
64
+ - Fetch the Convex auth token once per request on TanStack Start. Every
65
+ procedure call, `getToken()`, and `fetchAuthQuery`/`fetchAuthMutation`/
66
+ `fetchAuthAction` in a request now share one token, instead of each paying its
67
+ own round trip.
68
+ - Stop replaying a rejected auth token for the rest of a request. After a
69
+ refresh, the remaining calls sharing that context use the new token instead of
70
+ re-failing and re-running non-idempotent mutations and actions.
71
+ - Refresh expired TanStack Start tokens instead of failing. Forced refresh and
72
+ token freshness now reach the token layer, so a stale token retries once and a
73
+ fresh one is no longer replayed on an authorization error.
74
+
75
+ Existing TanStack Start apps: re-run `kitcn add auth --overwrite` to update
76
+ `src/lib/convex/auth-server.ts` and `src/lib/convex/server.ts`.
77
+
78
+ ## 0.25.7
79
+
80
+ ### Patch Changes
81
+
82
+ - [#379](https://github.com/udecode/kitcn/pull/379) [`53fe88e`](https://github.com/udecode/kitcn/commit/53fe88e6911cdabdfcccba20337bfdadb7b6e5be) Thanks [@zbeyens](https://github.com/zbeyens)! - ## Patches
83
+
84
+ - Fix codegen schema loading with constrained required environment values.
85
+ - Fix first-run codegen when schema triggers import newly generated callers.
86
+
3
87
  ## 0.25.6
4
88
 
5
89
  ### Patch Changes
@@ -1,5 +1,5 @@
1
1
  import { Bn as ConvexTextBuilderInitial, Xt as ConvexTableWithColumns } from "../capabilities-DtDfpdcH.js";
2
- import { C as ConvexNumberBuilderInitial, E as ConvexIdBuilderInitial, N as ConvexCustomBuilderInitial } from "../where-clause-compiler-eTewPUGq.js";
2
+ import { C as ConvexNumberBuilderInitial, E as ConvexIdBuilderInitial, N as ConvexCustomBuilderInitial } from "../where-clause-compiler-AYna1fq8.js";
3
3
  import * as convex_values0 from "convex/values";
4
4
  import { GenericId, Infer, Value } from "convex/values";
5
5
  import { DocumentByName, GenericDataModel, GenericDatabaseReader, GenericDatabaseWriter, TableNamesInDataModel } from "convex/server";
@@ -1,6 +1,6 @@
1
1
  import { t as getToken } from "../../token-DcV_0fkF.js";
2
2
  import { n as defaultIsUnauthorized } from "../../error-CMLeCadS.js";
3
- import { t as createCallerFactory } from "../../caller-factory-Dd3H7j3V.js";
3
+ import { t as createCallerFactory } from "../../caller-factory-D4pz5GcZ.js";
4
4
 
5
5
  //#region src/auth-nextjs/index.ts
6
6
  /** biome-ignore-all lint/suspicious/noExplicitAny: lib */
@@ -1,12 +1,66 @@
1
+ import { H as ConvexContext, W as LazyCaller } from "../../../procedure-name-l2YusEZI.js";
1
2
  import { t as GetTokenOptions } from "../../../token-kQaqFby4.js";
2
3
  import { FunctionReference, FunctionReturnType, OptionalRestArgs } from "convex/server";
3
4
 
4
5
  //#region src/auth-start/server.d.ts
5
- type ConvexBetterAuthReactStartOptions = Omit<GetTokenOptions, 'forceRefresh'> & {
6
+ /** Auth options for server-side calls. */
7
+ type AuthOptions = {
8
+ /** Better Auth auth route base path. Defaults to `/api/auth`. */basePath?: string;
9
+ /**
10
+ * Read the Convex JWT from the session cookie instead of fetching it.
11
+ * Default: false.
12
+ *
13
+ * The token this saves a round trip on is also the token
14
+ * `syncConvexAuthForStartLoader` hands the browser Convex client, which
15
+ * captures it for the lifetime of the socket. A cookie JWT can be within
16
+ * seconds of expiry and cannot be renewed from that callback, so enable this
17
+ * only for apps that do not prime the browser client from `getToken()`.
18
+ */
19
+ jwtCache?: boolean; /** Custom function to detect UNAUTHORIZED errors. Default checks code property. */
20
+ isUnauthorized?: (error: unknown) => boolean; /** Expiration tolerance in seconds. */
21
+ expirationToleranceSeconds?: number;
22
+ };
23
+ type ConvexBetterAuthReactStartOptions<TApi> = Omit<GetTokenOptions, 'forceRefresh' | 'jwtCache'> & {
24
+ /** Your Convex API object. */api: TApi;
6
25
  convexSiteUrl: string;
7
- convexUrl: string;
26
+ convexUrl: string; /** Auth options. */
27
+ auth?: AuthOptions;
8
28
  };
9
- declare const convexBetterAuthReactStart: (opts: ConvexBetterAuthReactStartOptions) => {
29
+ /**
30
+ * Create Convex caller factory with Better Auth integration for TanStack Start.
31
+ *
32
+ * Every request resolves its Convex token once. TanStack Start runs each request
33
+ * inside an `AsyncLocalStorage` scope, so `getRequest()` returns an object whose
34
+ * identity is stable for that request and distinct across requests. Keying the
35
+ * memos on it makes them request-scoped by construction: nothing auth-related is
36
+ * ever held at module scope, and entries are collected with the request.
37
+ *
38
+ * @example
39
+ * ```ts
40
+ * // auth-server.ts
41
+ * export const { createCaller, handler, getToken } = convexBetterAuthReactStart({
42
+ * api,
43
+ * convexUrl: import.meta.env.VITE_CONVEX_URL!,
44
+ * convexSiteUrl: import.meta.env.VITE_CONVEX_SITE_URL!,
45
+ * });
46
+ *
47
+ * // server.ts
48
+ * export const caller = createCaller();
49
+ *
50
+ * // any server function or server route - single token fetch per request
51
+ * const user = await caller.user.getSessionUser();
52
+ * const posts = await caller.posts.list();
53
+ * ```
54
+ */
55
+ declare const convexBetterAuthReactStart: <TApi extends Record<string, unknown>>(opts: ConvexBetterAuthReactStartOptions<TApi>) => {
56
+ /**
57
+ * Bind a cRPC caller. Defaults to the request-scoped context, so every
58
+ * procedure call in a request shares one token fetch.
59
+ */
60
+ createCaller: (ctxFn?: () => Promise<ConvexContext<TApi>>) => LazyCaller<TApi>;
61
+ createContext: (reqOpts: {
62
+ headers: Headers;
63
+ }) => Promise<ConvexContext<TApi>>;
10
64
  getToken: () => Promise<string | undefined>;
11
65
  handler: (request: Request) => Promise<Response>;
12
66
  fetchAuthQuery: <Query extends FunctionReference<"query">>(query: Query, ...args: OptionalRestArgs<Query>) => Promise<FunctionReturnType<Query>>;
@@ -1,12 +1,11 @@
1
1
  import { t as getToken } from "../../../token-DcV_0fkF.js";
2
+ import { n as defaultIsUnauthorized } from "../../../error-CMLeCadS.js";
3
+ import { t as createCallerFactory } from "../../../caller-factory-D4pz5GcZ.js";
2
4
  import { stripIndent } from "common-tags";
3
- import { getRequestHeaders } from "@tanstack/react-start/server";
5
+ import { getRequest } from "@tanstack/react-start/server";
4
6
  import { ConvexHttpClient } from "convex/browser";
5
- import React from "react";
6
7
 
7
8
  //#region src/auth-start/server.ts
8
- const fallbackCache = (fn) => fn;
9
- const cache = React.cache ?? fallbackCache;
10
9
  const TRAILING_COLON_RE = /:$/;
11
10
  const requestCanHaveBody = (method) => method !== "GET" && method !== "HEAD" && method !== "OPTIONS";
12
11
  const stripHopByHopHeaders = (headers) => {
@@ -79,30 +78,134 @@ const handler = async (request, opts) => {
79
78
  redirect: "manual"
80
79
  });
81
80
  };
81
+ /**
82
+ * Create Convex caller factory with Better Auth integration for TanStack Start.
83
+ *
84
+ * Every request resolves its Convex token once. TanStack Start runs each request
85
+ * inside an `AsyncLocalStorage` scope, so `getRequest()` returns an object whose
86
+ * identity is stable for that request and distinct across requests. Keying the
87
+ * memos on it makes them request-scoped by construction: nothing auth-related is
88
+ * ever held at module scope, and entries are collected with the request.
89
+ *
90
+ * @example
91
+ * ```ts
92
+ * // auth-server.ts
93
+ * export const { createCaller, handler, getToken } = convexBetterAuthReactStart({
94
+ * api,
95
+ * convexUrl: import.meta.env.VITE_CONVEX_URL!,
96
+ * convexSiteUrl: import.meta.env.VITE_CONVEX_SITE_URL!,
97
+ * });
98
+ *
99
+ * // server.ts
100
+ * export const caller = createCaller();
101
+ *
102
+ * // any server function or server route - single token fetch per request
103
+ * const user = await caller.user.getSessionUser();
104
+ * const posts = await caller.posts.list();
105
+ * ```
106
+ */
82
107
  const convexBetterAuthReactStart = (opts) => {
83
108
  const siteUrl = parseConvexSiteUrl(opts.convexSiteUrl);
84
- const cachedGetToken = cache(async (opts) => {
85
- const headers = getRequestHeaders();
109
+ const auth = opts.auth ?? {};
110
+ const jwtCacheEnabled = auth.jwtCache === true;
111
+ const fetchTokenFor = (headers, forceRefresh) => {
86
112
  const mutableHeaders = new Headers(headers);
87
113
  stripHopByHopHeaders(mutableHeaders);
88
114
  mutableHeaders.set("accept-encoding", "identity");
89
- return getToken(siteUrl, mutableHeaders, opts);
115
+ return getToken(siteUrl, mutableHeaders, {
116
+ basePath: auth.basePath ?? opts.basePath,
117
+ cookiePrefix: opts.cookiePrefix,
118
+ forceRefresh,
119
+ jwtCache: {
120
+ enabled: jwtCacheEnabled,
121
+ expirationToleranceSeconds: auth.expirationToleranceSeconds,
122
+ isAuthError: auth.isUnauthorized ?? defaultIsUnauthorized
123
+ }
124
+ });
125
+ };
126
+ const headersByRequest = /* @__PURE__ */ new WeakMap();
127
+ const tokenByRequest = /* @__PURE__ */ new WeakMap();
128
+ const contextByRequest = /* @__PURE__ */ new WeakMap();
129
+ /**
130
+ * Snapshot the current request's headers once.
131
+ *
132
+ * `getRequestHeaders()` is not identity-stable within a request: srvx serves a
133
+ * lazy header view until anything materializes the native Request (a server
134
+ * function reading `formData()`, for example), then swaps in that Request's
135
+ * own `Headers` and drops the old one. Header *values* survive the swap, so a
136
+ * snapshot taken at any point is correct, but comparing or keying on the live
137
+ * accessor would silently stop matching mid-request.
138
+ */
139
+ const requestHeaders = (request) => {
140
+ const cached = headersByRequest.get(request);
141
+ if (cached) return cached;
142
+ const snapshot = new Headers(request.headers);
143
+ headersByRequest.set(request, snapshot);
144
+ return snapshot;
145
+ };
146
+ /**
147
+ * Memoize `create` for the lifetime of the current request. The pending
148
+ * promise is stored before it settles so concurrent callers share one
149
+ * in-flight fetch, and a rejection is evicted so the next caller can retry.
150
+ */
151
+ const perRequest = (store, create) => {
152
+ const request = getRequest();
153
+ const cached = store.get(request);
154
+ if (cached) return cached;
155
+ const pending = create(request).catch((error) => {
156
+ if (store.get(request) === pending) store.delete(request);
157
+ throw error;
158
+ });
159
+ store.set(request, pending);
160
+ return pending;
161
+ };
162
+ /**
163
+ * The current request, or `undefined` outside a Start request scope.
164
+ * `getRequest()` throws there, and an explicit `createContext({ headers })`
165
+ * is allowed to run with no ambient request at all.
166
+ */
167
+ const currentRequest = () => {
168
+ try {
169
+ return getRequest();
170
+ } catch {
171
+ return;
172
+ }
173
+ };
174
+ /** Ambient token for the current request, resolved at most once. */
175
+ const requestToken = () => perRequest(tokenByRequest, (request) => fetchTokenFor(requestHeaders(request)));
176
+ const { createContext, createCaller } = createCallerFactory({
177
+ api: opts.api,
178
+ auth: {
179
+ getToken: (_tokenSiteUrl, headers, getTokenOpts) => {
180
+ const forceRefresh = getTokenOpts?.forceRefresh;
181
+ const request = currentRequest();
182
+ if (!forceRefresh && request && headers === headersByRequest.get(request)) return requestToken();
183
+ return fetchTokenFor(headers, forceRefresh);
184
+ },
185
+ isUnauthorized: auth.isUnauthorized
186
+ },
187
+ convexSiteUrl: opts.convexSiteUrl,
188
+ convexUrl: opts.convexUrl
90
189
  });
190
+ /** Request-scoped context. One context, one token, per request. */
191
+ const createRequestContext = () => perRequest(contextByRequest, (request) => createContext({ headers: requestHeaders(request) }));
91
192
  const callWithToken = async (fn) => {
92
- const token = await cachedGetToken(opts) ?? {};
193
+ const token = await requestToken();
93
194
  try {
94
- return await fn(token?.token);
195
+ return await fn(token.token);
95
196
  } catch (error) {
96
- if (!opts?.jwtCache?.enabled || token.isFresh || !opts.jwtCache?.isAuthError(error)) throw error;
97
- return await fn((await cachedGetToken({
98
- ...opts,
99
- forceRefresh: true
100
- })).token);
197
+ if (token.isFresh || !(auth.isUnauthorized ?? defaultIsUnauthorized)(error)) throw error;
198
+ const refreshed = await fetchTokenFor(requestHeaders(getRequest()), true);
199
+ token.token = refreshed.token;
200
+ token.isFresh = refreshed.isFresh;
201
+ return await fn(refreshed.token);
101
202
  }
102
203
  };
103
204
  return {
205
+ createCaller: (ctxFn = createRequestContext) => createCaller(ctxFn),
206
+ createContext,
104
207
  getToken: async () => {
105
- return (await cachedGetToken(opts)).token;
208
+ return (await requestToken()).token;
106
209
  },
107
210
  handler: async (request) => cloneAuthHandlerResponse(await handler(request, opts)),
108
211
  fetchAuthQuery: async (query, ...args) => {
@@ -164,6 +164,8 @@ function createCallerFactory(opts) {
164
164
  ...opts,
165
165
  forceRefresh: true
166
166
  });
167
+ tokenResult.token = newToken.token;
168
+ tokenResult.isFresh = newToken.isFresh;
167
169
  try {
168
170
  return await fn(newToken.token);
169
171
  } catch (retryError) {
package/dist/cli.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { C as Columns, D as TableName, E as RlsPolicies, O as createSystemFields, S as getRankIndexes, T as OrmSchemaExtensions, _ as loadEsbuild, a as generateMeta, b as getAggregateIndexes, c as resolveSchemaDefaultExport, f as createProjectJiti, g as loadDotenv, h as loadClackPrompts, i as resolveConfiguredBackend, l as schemaDeclaresAggregateIndexes, m as loadBabelParser, n as withLocalCodegenEnv, o as getConvexConfig, p as CRPC_BUILDER_STUB_SOURCE, r as loadCliConfig, s as collectSchemaTables, t as getLocalBackendEnvVars, u as logger, v as highlighter, w as EnableRLS, x as getIndexes, y as isColorEnabled } from "./local-env-CiPqNKS_.mjs";
2
+ import { C as Columns, D as TableName, E as RlsPolicies, O as createSystemFields, S as getRankIndexes, T as OrmSchemaExtensions, _ as loadEsbuild, a as generateMeta, b as getAggregateIndexes, c as resolveSchemaDefaultExport, f as createProjectJiti, g as loadDotenv, h as loadClackPrompts, i as resolveConfiguredBackend, l as schemaDeclaresAggregateIndexes, m as loadBabelParser, n as withLocalCodegenEnv, o as getConvexConfig, p as CRPC_BUILDER_STUB_SOURCE, r as loadCliConfig, s as collectSchemaTables, t as getLocalBackendEnvVars, u as logger, v as highlighter, w as EnableRLS, x as getIndexes, y as isColorEnabled } from "./local-env-9Qtfn3wR.mjs";
3
3
  import { createRequire } from "node:module";
4
4
  import fs, { existsSync, readFileSync } from "node:fs";
5
5
  import path, { basename, delimiter, dirname, extname, isAbsolute, join, posix, relative, resolve } from "node:path";
@@ -5636,15 +5636,19 @@ export const Route = createFileRoute('/api/auth/$')({
5636
5636
 
5637
5637
  //#endregion
5638
5638
  //#region src/cli/registry/items/auth/auth-start-server.template.ts
5639
- const AUTH_START_SERVER_TEMPLATE = `import { convexBetterAuthReactStart } from 'kitcn/auth/start/server';
5639
+ const AUTH_START_SERVER_TEMPLATE = `import { api } from '@convex/api';
5640
+ import { convexBetterAuthReactStart } from 'kitcn/auth/start/server';
5640
5641
 
5641
5642
  export const {
5642
5643
  handler,
5643
5644
  getToken,
5645
+ createCaller,
5646
+ createContext,
5644
5647
  fetchAuthQuery,
5645
5648
  fetchAuthMutation,
5646
5649
  fetchAuthAction,
5647
5650
  } = convexBetterAuthReactStart({
5651
+ api,
5648
5652
  convexUrl: import.meta.env.VITE_CONVEX_URL!,
5649
5653
  convexSiteUrl: import.meta.env.VITE_CONVEX_SITE_URL!,
5650
5654
  });
@@ -5652,41 +5656,9 @@ export const {
5652
5656
 
5653
5657
  //#endregion
5654
5658
  //#region src/cli/registry/items/auth/auth-start-server-call.template.ts
5655
- const AUTH_START_SERVER_CALL_TEMPLATE = `import { api } from '@convex/api';
5656
- import { getRequestHeaders } from '@tanstack/react-start/server';
5657
- import { createCallerFactory } from 'kitcn/server';
5658
-
5659
- import { getToken } from '@/lib/convex/auth-server';
5660
-
5661
- const { createContext, createCaller } = createCallerFactory({
5662
- api,
5663
- convexSiteUrl: import.meta.env.VITE_CONVEX_SITE_URL!,
5664
- auth: {
5665
- getToken: async () => {
5666
- return {
5667
- token: await getToken(),
5668
- };
5669
- },
5670
- },
5671
- });
5672
-
5673
- type ServerCaller = ReturnType<typeof createCaller>;
5674
-
5675
- async function makeContext() {
5676
- const headers = await getRequestHeaders();
5677
- return createContext({ headers });
5678
- }
5659
+ const AUTH_START_SERVER_CALL_TEMPLATE = `import { createCaller } from '@/lib/convex/auth-server';
5679
5660
 
5680
- function createServerCaller(): ServerCaller {
5681
- return createCaller(async () => {
5682
- return await makeContext();
5683
- });
5684
- }
5685
-
5686
- export function runServerCall<T>(fn: (caller: ServerCaller) => Promise<T> | T) {
5687
- const caller = createServerCaller();
5688
- return fn(caller);
5689
- }
5661
+ export const caller = createCaller();
5690
5662
  `;
5691
5663
 
5692
5664
  //#endregion
@@ -473,22 +473,71 @@ export class CRPCError extends Error {
473
473
  }
474
474
  }
475
475
 
476
+ const parseEnvForCodegen = (schema) => {
477
+ if (typeof schema?.safeParse !== "function") {
478
+ return schema.parse(process.env);
479
+ }
480
+
481
+ const result = schema.safeParse(process.env);
482
+ if (result?.success === true) return result.data;
483
+
484
+ const issues = result?.error?.issues;
485
+ if (!Array.isArray(issues) || issues.length === 0) {
486
+ return schema.parse(process.env);
487
+ }
488
+
489
+ const missingFieldIssues = new Map();
490
+ for (const [key, field] of Object.entries(schema.shape)) {
491
+ if (
492
+ process.env[key] !== undefined ||
493
+ typeof field?.safeParse !== "function"
494
+ ) {
495
+ continue;
496
+ }
497
+ const fieldResult = field.safeParse(undefined);
498
+ if (
499
+ fieldResult?.success === false &&
500
+ Array.isArray(fieldResult.error?.issues)
501
+ ) {
502
+ missingFieldIssues.set(key, fieldResult.error.issues);
503
+ }
504
+ }
505
+
506
+ const isMissingFieldIssue = (issue) => {
507
+ if (!Array.isArray(issue?.path) || issue.path.length === 0) return false;
508
+ const [key, ...path] = issue.path;
509
+ const fieldIssues = missingFieldIssues.get(key);
510
+ return fieldIssues?.some(
511
+ (fieldIssue) =>
512
+ fieldIssue?.code === issue.code &&
513
+ JSON.stringify(fieldIssue.path ?? []) === JSON.stringify(path)
514
+ );
515
+ };
516
+ if (!issues.every(isMissingFieldIssue)) {
517
+ return schema.parse(process.env);
518
+ }
519
+
520
+ const data = {};
521
+ for (const [key, field] of Object.entries(schema.shape)) {
522
+ if (typeof field?.safeParse !== "function") {
523
+ return schema.parse(process.env);
524
+ }
525
+ const fieldResult = field.safeParse(process.env[key]);
526
+ if (fieldResult?.success === true) {
527
+ data[key] = fieldResult.data;
528
+ } else if (!missingFieldIssues.has(key)) {
529
+ return schema.parse(process.env);
530
+ }
531
+ }
532
+ return data;
533
+ };
534
+
476
535
  export const createEnv = ({ schema }) => () => {
477
536
  if (typeof schema?.parse !== "function") return process.env;
478
537
  if (globalThis.__KITCN_CODEGEN__ !== true || !schema.shape) {
479
538
  return schema.parse(process.env);
480
539
  }
481
- const fallback = Object.fromEntries(
482
- Object.entries(schema.shape).map(([key, zodType]) => {
483
- const result = zodType?.safeParse?.(undefined);
484
- if (result?.success) return [key, result.data];
485
- if (Array.isArray(zodType?.options) && zodType.options.length > 0) {
486
- return [key, zodType.options[0]];
487
- }
488
- return [key, ""];
489
- })
490
- );
491
- return schema.parse({ ...fallback, ...process.env });
540
+ return parseEnvForCodegen(schema);
492
541
  };
493
542
  export const createHttpRouter = (_app, httpRouter) => httpRouter ?? {};
494
543
  export const createCallerFactory = () => () => ({});
@@ -3911,7 +3960,15 @@ async function generateMeta(sharedDir, options) {
3911
3960
  };
3912
3961
  let sharedJitiInstance;
3913
3962
  const getSharedJitiInstance = () => sharedJitiInstance ??= createProjectJiti();
3914
- const schemaMetadata = await withCodegenParseSentinel(() => resolveSchemaMetadataForCodegen(functionsDir, debug, getSharedJitiInstance));
3963
+ const schemaRuntimeModules = listFilesRecursive(functionsDir).filter((file) => file.endsWith(".ts") && isValidConvexFile(file)).map((file) => file.replace(TS_EXTENSION_RE, ""));
3964
+ const schemaRuntimePlaceholders = ensureGeneratedRuntimePlaceholders(functionsDir, schemaRuntimeModules, resolveModuleRuntimeExportNames(schemaRuntimeModules, normalizedTrimSegments));
3965
+ const schemaMetadata = await (async () => {
3966
+ try {
3967
+ return await withCodegenParseSentinel(() => resolveSchemaMetadataForCodegen(functionsDir, debug, getSharedJitiInstance));
3968
+ } finally {
3969
+ for (const schemaRuntimePlaceholder of schemaRuntimePlaceholders) fs.rmSync(schemaRuntimePlaceholder, { force: true });
3970
+ }
3971
+ })();
3915
3972
  const hasOrmSchemaMetadata = schemaMetadata.hasOrmSchema;
3916
3973
  const hasRelationsMetadata = schemaMetadata.hasRelations;
3917
3974
  const hasRelationsExport = hasNamedExport(path.join(functionsDir, "schema.ts"), "relations");
@@ -1,5 +1,5 @@
1
1
  import { $n as BinaryExpression, $t as OrmLifecycleOperation, A as DatabaseWithMutations, An as ConvexCheckConfig, Ar as AnyColumn, At as VectorQueryConfig, B as RlsContext, Bn as ConvexTextBuilderInitial, Br as IsUnique, Bt as RelationsBuilderColumnConfig, C as MigrationTableName, Cn as aggregateIndex, Cr as notBetween, Ct as OrderDirection, D as defineMigrationSet, Dn as uniqueIndex, Dt as ReturningResult, E as defineMigration, En as searchIndex, Er as startsWith, Et as ReturningAll, Fn as ConvexUniqueConstraintConfig, Fr as ColumnBuilderWithTableName, Ft as ExtractTablesWithRelations, Gt as defineRelations, H as EdgeMetadata, In as check, Ir as ColumnDataType, It as ManyConfig, Jt as ConvexDeletionConfig, Kt as defineRelationsPart, Ln as foreignKey, Lr as DrizzleEntity, Lt as OneConfig, M as OrmReader$1, Mn as ConvexForeignKeyConfig, Mr as ColumnBuilderBaseConfig, Mt as unsetToken, N as OrmWriter$1, Nn as ConvexUniqueConstraintBuilder, Nr as ColumnBuilderRuntimeConfig, O as detectMigrationDrift, On as vectorIndex, Or as SystemFields, Ot as ReturningSelection, Pn as ConvexUniqueConstraintBuilderOn, Pr as ColumnBuilderTypeConfig, Pt as ExtractTablesFromSchema, Qn as TableName, Qt as OrmLifecycleChange, Rn as unique, Rr as HasDefault, Rt as RelationsBuilder, S as MigrationStep, Sn as ConvexVectorIndexConfig, Sr as not, St as OrderByClause, T as buildMigrationPlan, Tn as rankIndex, Tr as or, Tt as PredicateWhereIndexConfig, U as extractRelationsConfig, Un as Brand, Ut as TableRelationalConfig, V as RlsMode, Vn as text, Vr as NotNull, Wn as Columns, Wt as TablesRelationalConfig, Xn as OrmSchemaRelations, Xt as ConvexTableWithColumns, Yn as OrmSchemaExtensions, Yt as ConvexTable, Zn as OrmSchemaTriggers, Zt as DiscriminatorBuilderConfig, _ as MigrationMigrateOne, _n as ConvexSearchIndexBuilder, _r as isNull, _t as MutationPaginateConfig, an as RlsPolicyConfig, ar as and, at as CountConfig, b as MigrationSet, bn as ConvexVectorIndexBuilder, br as lte, bt as MutationReturning, cn as RlsRole, cr as endsWith, ct as FilterOperators, d as MigrationDefinition, dn as ConvexAggregateIndexBuilder, dr as gt, dt as InferModelFromColumns, en as TableConfig, er as ExpressionVisitor, et as AggregateConfig, f as MigrationDirection, fn as ConvexAggregateIndexBuilderOn, fr as gte, ft as InferSelectModel, g as MigrationManifestEntry, gn as ConvexRankIndexBuilderOn, gr as isNotNull, gt as MutationExecutionMode, h as MigrationDriftIssue, hn as ConvexRankIndexBuilder, hr as isFieldReference, ht as MutationExecuteResult, i as OrmMigrationCapability, in as RlsPolicy, ir as UnaryExpression, it as BuildRelationResult, j as DatabaseWithQuery, jn as ConvexForeignKeyBuilder, jr as ColumnBuilder, jt as VectorSearchProvider, kn as ConvexCheckBuilder, kt as UpdateSet, ln as RlsRoleConfig, lr as eq, lt as GetColumnData, m as MigrationDocContext, mn as ConvexIndexBuilderOn, mr as inArray, mt as MutationExecuteConfig, n as OrmCapabilities, nn as deletion, nr as FilterExpression, nt as AggregateResult, on as RlsPolicyToOption, or as between, ot as CountResult, p as MigrationDoc, pn as ConvexIndexBuilder, pr as ilike, pt as InsertValue, qn as OrmSchemaExtensionTables, qt as ConvexDeletionBuilder, r as OrmCapability, rn as discriminator, rr as LogicalExpression, rt as BuildQueryResult, sn as rlsPolicy, sr as contains, st as DBQueryConfig, t as OrmAggregateCapability, tn as convexTable, tr as FieldReference, tt as AggregateFieldValue, u as MigrationAppliedState, un as rlsRole, ur as fieldRef, ut as InferInsertModel, v as MigrationPlan, vn as ConvexSearchIndexBuilderOn, vr as like, vt as MutationPaginatedResult, w as MigrationWriteMode, wn as index, wr as notInArray, wt as PaginatedResult, x as MigrationStateMap, xn as ConvexVectorIndexBuilderOn, xr as ne, xt as MutationRunMode, y as MigrationRunStatus, yn as ConvexSearchIndexConfig, yr as lt, yt as MutationResult, zn as ConvexTextBuilder, zr as IsPrimaryKey, zt as RelationsBuilderColumnBase } from "../capabilities-DtDfpdcH.js";
2
- import { $ as OrmClientWithApi$1, A as ConvexDateMode, B as ConvexBytesBuilderInitial, C as ConvexNumberBuilderInitial, D as id, E as ConvexIdBuilderInitial, F as custom, G as ConvexBigIntBuilder, H as ConvexBooleanBuilder, I as json, J as CreateOrmOptions, K as ConvexBigIntBuilderInitial, L as objectOf, M as ConvexCustomBuilder, N as ConvexCustomBuilderInitial, O as ConvexDateBuilder, P as arrayOf, Q as OrmClientBase$1, R as unionOf, S as ConvexNumberBuilder, St as defineTriggers, T as ConvexIdBuilder, U as ConvexBooleanBuilderInitial, V as bytes, W as boolean, X as GenericOrmCtx$1, Y as GenericOrm$1, Z as OrmApiResult, _ as ConvexTimestampMode, _t as OrmBeforeResult, a as requireSchemaRelations, at as ScheduledMutationBatchArgs, b as ConvexTextEnumBuilderInitial, bt as OrmTriggerContext, c as TableConfigResult, ct as scheduledDeleteFactory, d as OrmNotFoundError, et as OrmFunctions, f as ConvexVectorBuilder, g as ConvexTimestampBuilderInitial, gt as defineSchemaExtension, h as ConvexTimestampBuilder, ht as SchemaExtension, i as getSchemaTriggers, it as createOrm, j as date, k as ConvexDateBuilderInitial, l as getTableColumns, m as vector, n as defineSchema, nt as OrmWriterCtx, o as asc, ot as scheduledMutationBatchFactory, p as ConvexVectorBuilderInitial, q as bigint, r as getSchemaRelations, rt as ResolveOrmSchema, s as desc, st as ScheduledDeleteArgs, t as WhereClauseResult, tt as OrmReaderCtx, u as getTableConfig, v as timestamp, vt as OrmTableTriggers, w as integer, x as textEnum, xt as OrmTriggers, y as ConvexTextEnumBuilder, yt as OrmTriggerChange, z as ConvexBytesBuilder } from "../where-clause-compiler-eTewPUGq.js";
2
+ import { $ as OrmClientWithApi$1, A as ConvexDateMode, B as ConvexBytesBuilderInitial, C as ConvexNumberBuilderInitial, D as id, E as ConvexIdBuilderInitial, F as custom, G as ConvexBigIntBuilder, H as ConvexBooleanBuilder, I as json, J as CreateOrmOptions, K as ConvexBigIntBuilderInitial, L as objectOf, M as ConvexCustomBuilder, N as ConvexCustomBuilderInitial, O as ConvexDateBuilder, P as arrayOf, Q as OrmClientBase$1, R as unionOf, S as ConvexNumberBuilder, St as defineTriggers, T as ConvexIdBuilder, U as ConvexBooleanBuilderInitial, V as bytes, W as boolean, X as GenericOrmCtx$1, Y as GenericOrm$1, Z as OrmApiResult, _ as ConvexTimestampMode, _t as OrmBeforeResult, a as requireSchemaRelations, at as ScheduledMutationBatchArgs, b as ConvexTextEnumBuilderInitial, bt as OrmTriggerContext, c as TableConfigResult, ct as scheduledDeleteFactory, d as OrmNotFoundError, et as OrmFunctions, f as ConvexVectorBuilder, g as ConvexTimestampBuilderInitial, gt as defineSchemaExtension, h as ConvexTimestampBuilder, ht as SchemaExtension, i as getSchemaTriggers, it as createOrm, j as date, k as ConvexDateBuilderInitial, l as getTableColumns, m as vector, n as defineSchema, nt as OrmWriterCtx, o as asc, ot as scheduledMutationBatchFactory, p as ConvexVectorBuilderInitial, q as bigint, r as getSchemaRelations, rt as ResolveOrmSchema, s as desc, st as ScheduledDeleteArgs, t as WhereClauseResult, tt as OrmReaderCtx, u as getTableConfig, v as timestamp, vt as OrmTableTriggers, w as integer, x as textEnum, xt as OrmTriggers, y as ConvexTextEnumBuilder, yt as OrmTriggerChange, z as ConvexBytesBuilder } from "../where-clause-compiler-AYna1fq8.js";
3
3
  import { i as pretendRequired, n as deprecated, r as pretend } from "../validators-wOIjhkfN.js";
4
4
  import { a as QueryCtxWithPreferredOrmQueryTable, i as QueryCtxWithOrmQueryTable, n as LookupByIdResultByCtx, o as getByIdWithOrmQueryFallback, r as QueryCtxWithOptionalOrmQueryTable, t as DocByCtx } from "../query-context-DJONf8X5.js";
5
5
  import { DefineSchemaOptions, GenericDatabaseReader, GenericDatabaseWriter, GenericSchema, SchemaDefinition } from "convex/server";
@@ -1,3 +1,3 @@
1
1
  import { C as MigrationTableName, D as defineMigrationSet, E as defineMigration, O as detectMigrationDrift, S as MigrationStep, T as buildMigrationPlan, _ as MigrationMigrateOne, a as MigrationCancelArgs, b as MigrationSet, c as MigrationStatusArgs, d as MigrationDefinition, f as MigrationDirection, g as MigrationManifestEntry, h as MigrationDriftIssue, l as createMigrationHandlers, m as MigrationDocContext, o as MigrationRunArgs, p as MigrationDoc, s as MigrationRunChunkArgs, u as MigrationAppliedState, v as MigrationPlan, w as MigrationWriteMode, x as MigrationStateMap, y as MigrationRunStatus } from "../../capabilities-DtDfpdcH.js";
2
- import { Ct as migrationCapability, dt as MIGRATION_STORAGE_TABLE_NAMES, ft as injectMigrationStorageTables, lt as MIGRATION_RUN_TABLE, mt as migrationStorageTables, pt as migrationExtension, ut as MIGRATION_STATE_TABLE } from "../../where-clause-compiler-eTewPUGq.js";
2
+ import { Ct as migrationCapability, dt as MIGRATION_STORAGE_TABLE_NAMES, ft as injectMigrationStorageTables, lt as MIGRATION_RUN_TABLE, mt as migrationStorageTables, pt as migrationExtension, ut as MIGRATION_STATE_TABLE } from "../../where-clause-compiler-AYna1fq8.js";
3
3
  export { MIGRATION_RUN_TABLE, MIGRATION_STATE_TABLE, MIGRATION_STORAGE_TABLE_NAMES, type MigrationAppliedState, type MigrationCancelArgs, type MigrationDefinition, type MigrationDirection, type MigrationDoc, type MigrationDocContext, type MigrationDriftIssue, type MigrationManifestEntry, type MigrationMigrateOne, type MigrationPlan, type MigrationRunArgs, type MigrationRunChunkArgs, type MigrationRunStatus, type MigrationSet, type MigrationStateMap, type MigrationStatusArgs, type MigrationStep, type MigrationTableName, type MigrationWriteMode, buildMigrationPlan, createMigrationHandlers, defineMigration, defineMigrationSet, detectMigrationDrift, injectMigrationStorageTables, migrationCapability, migrationExtension, migrationStorageTables };
@@ -1,5 +1,5 @@
1
1
  import { a as isMutationCtx, c as isSchedulerCtx, d as requireQueryCtx, f as requireRunMutationCtx, i as isActionCtx, l as requireActionCtx, n as createGeneratedFunctionReference, o as isQueryCtx, p as requireSchedulerCtx, r as getGeneratedValue, s as isRunMutationCtx, t as createApiLeaf, u as requireMutationCtx } from "../api-entry-CkDpGYVg.js";
2
- import { n as createLazyCaller, r as createServerCaller, t as createCallerFactory } from "../caller-factory-Dd3H7j3V.js";
2
+ import { n as createLazyCaller, r as createServerCaller, t as createCallerFactory } from "../caller-factory-D4pz5GcZ.js";
3
3
  import { A as zid, C as toCRPCError, D as zCustomAction, E as withSystemFields, M as zodOutputToConvexFields, N as zodToConvex, O as zCustomMutation, P as zodToConvexFields, S as isCRPCError, T as convexToZodFields, _ as CRPCError, a as createMiddlewareFactory, b as getCRPCErrorFromUnknown, c as registerProcedureNameLookup, d as createHttpRouterFactory, f as extractRouteMap, g as matchPathParams, h as handleHttpError, i as QueryProcedureBuilder, j as zodOutputToConvex, k as zCustomQuery, l as HttpRouterWithHono, m as extractPathParams, n as MutationProcedureBuilder, o as initCRPC, p as createHttpProcedureBuilder, r as ProcedureBuilder, s as inferProcedureNameFromCallsite, t as ActionProcedureBuilder, u as createHttpRouter, v as CRPC_ERROR_CODES_BY_KEY, w as convexToZod, x as getHTTPStatusCodeFromError, y as CRPC_ERROR_CODE_TO_HTTP } from "../builder-CsAw-DK8.js";
4
4
  import { a as createProcedureHandlerFactory, c as typedProcedureResolver, i as createProcedureCallerFactory, l as createEnv, n as createGenericCallerFactory, o as defineProcedure, r as createGenericHandlerFactory, s as getGeneratedFunctionReference, t as createGeneratedRegistryRuntime } from "../procedure-caller-BR-Wb0si.js";
5
5
 
package/dist/watcher.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { a as generateMeta, d as PARSE_SNAPSHOT_SUFFIX, i as resolveConfiguredBackend, n as withLocalCodegenEnv, o as getConvexConfig, r as loadCliConfig, u as logger } from "./local-env-CiPqNKS_.mjs";
2
+ import { a as generateMeta, d as PARSE_SNAPSHOT_SUFFIX, i as resolveConfiguredBackend, n as withLocalCodegenEnv, o as getConvexConfig, r as loadCliConfig, u as logger } from "./local-env-9Qtfn3wR.mjs";
3
3
  import path from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
5
 
@@ -1008,7 +1008,7 @@ declare const BUILTIN_SCHEMA_EXTENSIONS: readonly [SchemaExtension<{
1008
1008
  readonly aggregate_bucket: ConvexTableWithColumns<{
1009
1009
  name: "aggregate_bucket";
1010
1010
  columns: {
1011
- updatedAt: ConvexNumberBuilderInitial<""> & {
1011
+ count: ConvexNumberBuilderInitial<""> & {
1012
1012
  _: {
1013
1013
  notNull: true;
1014
1014
  };
@@ -1018,10 +1018,10 @@ declare const BUILTIN_SCHEMA_EXTENSIONS: readonly [SchemaExtension<{
1018
1018
  };
1019
1019
  } & {
1020
1020
  _: {
1021
- fieldName: "updatedAt";
1021
+ fieldName: "count";
1022
1022
  };
1023
1023
  };
1024
- count: ConvexNumberBuilderInitial<""> & {
1024
+ updatedAt: ConvexNumberBuilderInitial<""> & {
1025
1025
  _: {
1026
1026
  notNull: true;
1027
1027
  };
@@ -1031,10 +1031,10 @@ declare const BUILTIN_SCHEMA_EXTENSIONS: readonly [SchemaExtension<{
1031
1031
  };
1032
1032
  } & {
1033
1033
  _: {
1034
- fieldName: "count";
1034
+ fieldName: "updatedAt";
1035
1035
  };
1036
1036
  };
1037
- indexName: ConvexTextBuilderInitial<""> & {
1037
+ tableKey: ConvexTextBuilderInitial<""> & {
1038
1038
  _: {
1039
1039
  notNull: true;
1040
1040
  };
@@ -1044,10 +1044,10 @@ declare const BUILTIN_SCHEMA_EXTENSIONS: readonly [SchemaExtension<{
1044
1044
  };
1045
1045
  } & {
1046
1046
  _: {
1047
- fieldName: "indexName";
1047
+ fieldName: "tableKey";
1048
1048
  };
1049
1049
  };
1050
- tableKey: ConvexTextBuilderInitial<""> & {
1050
+ indexName: ConvexTextBuilderInitial<""> & {
1051
1051
  _: {
1052
1052
  notNull: true;
1053
1053
  };
@@ -1057,7 +1057,7 @@ declare const BUILTIN_SCHEMA_EXTENSIONS: readonly [SchemaExtension<{
1057
1057
  };
1058
1058
  } & {
1059
1059
  _: {
1060
- fieldName: "tableKey";
1060
+ fieldName: "indexName";
1061
1061
  };
1062
1062
  };
1063
1063
  keyHash: ConvexTextBuilderInitial<""> & {
@@ -1159,7 +1159,7 @@ declare const BUILTIN_SCHEMA_EXTENSIONS: readonly [SchemaExtension<{
1159
1159
  fieldName: "updatedAt";
1160
1160
  };
1161
1161
  };
1162
- indexName: ConvexTextBuilderInitial<""> & {
1162
+ tableKey: ConvexTextBuilderInitial<""> & {
1163
1163
  _: {
1164
1164
  notNull: true;
1165
1165
  };
@@ -1169,10 +1169,10 @@ declare const BUILTIN_SCHEMA_EXTENSIONS: readonly [SchemaExtension<{
1169
1169
  };
1170
1170
  } & {
1171
1171
  _: {
1172
- fieldName: "indexName";
1172
+ fieldName: "tableKey";
1173
1173
  };
1174
1174
  };
1175
- tableKey: ConvexTextBuilderInitial<""> & {
1175
+ indexName: ConvexTextBuilderInitial<""> & {
1176
1176
  _: {
1177
1177
  notNull: true;
1178
1178
  };
@@ -1182,7 +1182,7 @@ declare const BUILTIN_SCHEMA_EXTENSIONS: readonly [SchemaExtension<{
1182
1182
  };
1183
1183
  } & {
1184
1184
  _: {
1185
- fieldName: "tableKey";
1185
+ fieldName: "indexName";
1186
1186
  };
1187
1187
  };
1188
1188
  keyHash: ConvexTextBuilderInitial<""> & {
@@ -1340,7 +1340,7 @@ declare const BUILTIN_SCHEMA_EXTENSIONS: readonly [SchemaExtension<{
1340
1340
  fieldName: "value";
1341
1341
  };
1342
1342
  };
1343
- updatedAt: ConvexNumberBuilderInitial<""> & {
1343
+ count: ConvexNumberBuilderInitial<""> & {
1344
1344
  _: {
1345
1345
  notNull: true;
1346
1346
  };
@@ -1350,10 +1350,10 @@ declare const BUILTIN_SCHEMA_EXTENSIONS: readonly [SchemaExtension<{
1350
1350
  };
1351
1351
  } & {
1352
1352
  _: {
1353
- fieldName: "updatedAt";
1353
+ fieldName: "count";
1354
1354
  };
1355
1355
  };
1356
- count: ConvexNumberBuilderInitial<""> & {
1356
+ updatedAt: ConvexNumberBuilderInitial<""> & {
1357
1357
  _: {
1358
1358
  notNull: true;
1359
1359
  };
@@ -1363,10 +1363,10 @@ declare const BUILTIN_SCHEMA_EXTENSIONS: readonly [SchemaExtension<{
1363
1363
  };
1364
1364
  } & {
1365
1365
  _: {
1366
- fieldName: "count";
1366
+ fieldName: "updatedAt";
1367
1367
  };
1368
1368
  };
1369
- indexName: ConvexTextBuilderInitial<""> & {
1369
+ tableKey: ConvexTextBuilderInitial<""> & {
1370
1370
  _: {
1371
1371
  notNull: true;
1372
1372
  };
@@ -1376,10 +1376,10 @@ declare const BUILTIN_SCHEMA_EXTENSIONS: readonly [SchemaExtension<{
1376
1376
  };
1377
1377
  } & {
1378
1378
  _: {
1379
- fieldName: "indexName";
1379
+ fieldName: "tableKey";
1380
1380
  };
1381
1381
  };
1382
- tableKey: ConvexTextBuilderInitial<""> & {
1382
+ indexName: ConvexTextBuilderInitial<""> & {
1383
1383
  _: {
1384
1384
  notNull: true;
1385
1385
  };
@@ -1389,7 +1389,7 @@ declare const BUILTIN_SCHEMA_EXTENSIONS: readonly [SchemaExtension<{
1389
1389
  };
1390
1390
  } & {
1391
1391
  _: {
1392
- fieldName: "tableKey";
1392
+ fieldName: "indexName";
1393
1393
  };
1394
1394
  };
1395
1395
  keyHash: ConvexTextBuilderInitial<""> & {
@@ -1668,7 +1668,7 @@ declare const BUILTIN_SCHEMA_EXTENSIONS: readonly [SchemaExtension<{
1668
1668
  fieldName: "lastError";
1669
1669
  };
1670
1670
  };
1671
- indexName: ConvexTextBuilderInitial<""> & {
1671
+ tableKey: ConvexTextBuilderInitial<""> & {
1672
1672
  _: {
1673
1673
  notNull: true;
1674
1674
  };
@@ -1678,10 +1678,10 @@ declare const BUILTIN_SCHEMA_EXTENSIONS: readonly [SchemaExtension<{
1678
1678
  };
1679
1679
  } & {
1680
1680
  _: {
1681
- fieldName: "indexName";
1681
+ fieldName: "tableKey";
1682
1682
  };
1683
1683
  };
1684
- keyDefinitionHash: ConvexTextBuilderInitial<""> & {
1684
+ indexName: ConvexTextBuilderInitial<""> & {
1685
1685
  _: {
1686
1686
  notNull: true;
1687
1687
  };
@@ -1691,10 +1691,10 @@ declare const BUILTIN_SCHEMA_EXTENSIONS: readonly [SchemaExtension<{
1691
1691
  };
1692
1692
  } & {
1693
1693
  _: {
1694
- fieldName: "keyDefinitionHash";
1694
+ fieldName: "indexName";
1695
1695
  };
1696
1696
  };
1697
- metricDefinitionHash: ConvexTextBuilderInitial<""> & {
1697
+ keyDefinitionHash: ConvexTextBuilderInitial<""> & {
1698
1698
  _: {
1699
1699
  notNull: true;
1700
1700
  };
@@ -1704,10 +1704,10 @@ declare const BUILTIN_SCHEMA_EXTENSIONS: readonly [SchemaExtension<{
1704
1704
  };
1705
1705
  } & {
1706
1706
  _: {
1707
- fieldName: "metricDefinitionHash";
1707
+ fieldName: "keyDefinitionHash";
1708
1708
  };
1709
1709
  };
1710
- tableKey: ConvexTextBuilderInitial<""> & {
1710
+ metricDefinitionHash: ConvexTextBuilderInitial<""> & {
1711
1711
  _: {
1712
1712
  notNull: true;
1713
1713
  };
@@ -1717,7 +1717,7 @@ declare const BUILTIN_SCHEMA_EXTENSIONS: readonly [SchemaExtension<{
1717
1717
  };
1718
1718
  } & {
1719
1719
  _: {
1720
- fieldName: "tableKey";
1720
+ fieldName: "metricDefinitionHash";
1721
1721
  };
1722
1722
  };
1723
1723
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kitcn",
3
- "version": "0.25.6",
3
+ "version": "0.26.0",
4
4
  "description": "kitcn - React Query integration and CLI tools for Convex",
5
5
  "keywords": [
6
6
  "convex",
@@ -34,20 +34,28 @@ export const {
34
34
  **Create:** `src/lib/convex/auth-server.ts`
35
35
 
36
36
  ```ts
37
+ import { api } from "@convex/api";
37
38
  import { convexBetterAuthReactStart } from "kitcn/auth/start/server";
38
39
 
39
40
  export const {
40
41
  handler,
41
42
  getToken,
43
+ createCaller,
44
+ createContext,
42
45
  fetchAuthQuery,
43
46
  fetchAuthMutation,
44
47
  fetchAuthAction,
45
48
  } = convexBetterAuthReactStart({
49
+ api,
46
50
  convexUrl: import.meta.env.VITE_CONVEX_URL!,
47
51
  convexSiteUrl: import.meta.env.VITE_CONVEX_SITE_URL!,
48
52
  });
49
53
  ```
50
54
 
55
+ `getToken` fetches the Convex token from the auth route. `auth.jwtCache: true`
56
+ reads it from the session cookie instead. Leave it off when the browser Convex
57
+ client is primed from `getToken()`.
58
+
51
59
  For client-side route loaders that fetch protected Convex queries through the
52
60
  router `queryClient`, prime the shared Convex client in the root `beforeLoad`
53
61
  before child loaders run:
@@ -78,7 +86,7 @@ export const Route = createRootRouteWithContext<{
78
86
  });
79
87
  ```
80
88
 
81
- Use `runServerCall` or `fetchAuthQuery` for server-side loaders. Use
89
+ Use the request-scoped `caller` or `fetchAuthQuery` for server-side loaders. Use
82
90
  `syncConvexAuthForStartLoader` only for client/router loaders that execute
83
91
  shared `ConvexQueryClient` queries before `ConvexAuthProvider` mounts.
84
92
 
@@ -105,42 +113,20 @@ export const Route = createFileRoute("/api/auth/$" as never)({
105
113
  **Create:** `src/lib/convex/server.ts`
106
114
 
107
115
  ```ts
108
- import { api } from "@convex/api";
109
- import { getRequestHeaders } from "@tanstack/react-start/server";
110
- import { createCallerFactory } from "kitcn/server";
116
+ import { createCaller } from "@/lib/convex/auth-server";
111
117
 
112
- import { getToken } from "@/lib/convex/auth-server";
113
-
114
- const { createContext, createCaller } = createCallerFactory({
115
- api,
116
- convexSiteUrl: import.meta.env.VITE_CONVEX_SITE_URL!,
117
- auth: {
118
- getToken: async () => {
119
- return {
120
- token: await getToken(),
121
- };
122
- },
123
- },
124
- });
125
-
126
- type ServerCaller = ReturnType<typeof createCaller>;
127
-
128
- async function makeContext() {
129
- const headers = await getRequestHeaders();
130
- return createContext({ headers });
131
- }
118
+ export const caller = createCaller();
119
+ ```
132
120
 
133
- function createServerCaller(): ServerCaller {
134
- return createCaller(async () => {
135
- return await makeContext();
136
- });
137
- }
121
+ `createCaller()` binds to the current request, so every procedure call in a
122
+ request shares one Convex auth token fetch. The module-scope `caller` holds no
123
+ request state; it resolves the current request on each call. Pass a context
124
+ factory (`createCaller(() => createContext({ headers }))`) only to call Convex
125
+ with headers other than the current request's.
138
126
 
139
- export function runServerCall<T>(fn: (caller: ServerCaller) => Promise<T> | T) {
140
- const caller = createServerCaller();
141
- return fn(caller);
142
- }
143
- ```
127
+ Reach `caller` from a `createServerFn` handler or a server route. A route
128
+ `loader` also runs in the browser on client-side navigation, where there is no
129
+ request scope.
144
130
 
145
131
  Use the docs pattern from `tanstack-start.mdx` for:
146
132