kitcn 0.33.5 → 0.33.7

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.
@@ -1,10 +1,132 @@
1
+ //#region src/react/identity-guard-registry.ts
2
+ const REGISTRY_KEY = Symbol.for("kitcn.identityGuard.v2");
3
+ const createRegistry = () => ({
4
+ documentIdentity: null,
5
+ guards: /* @__PURE__ */ new Set(),
6
+ settledClients: /* @__PURE__ */ new WeakSet(),
7
+ settlementListeners: /* @__PURE__ */ new WeakMap(),
8
+ storeGuards: /* @__PURE__ */ new WeakMap(),
9
+ tripListeners: /* @__PURE__ */ new Set(),
10
+ tripped: false,
11
+ watchedClients: /* @__PURE__ */ new WeakSet()
12
+ });
13
+ const isRegistry = (value) => {
14
+ const candidate = value;
15
+ return typeof candidate === "object" && candidate !== null && typeof candidate.tripped === "boolean" && (candidate.documentIdentity === null || typeof candidate.documentIdentity === "string") && candidate.tripListeners instanceof Set && candidate.guards instanceof Set && candidate.storeGuards instanceof WeakMap && candidate.settledClients instanceof WeakSet && candidate.settlementListeners instanceof WeakMap && candidate.watchedClients instanceof WeakSet;
16
+ };
17
+ let incompatibleStandIn;
18
+ const pageRegistry = () => {
19
+ if (typeof window === "undefined") return null;
20
+ const scope = globalThis;
21
+ scope[REGISTRY_KEY] ??= createRegistry();
22
+ const found = scope[REGISTRY_KEY];
23
+ if (isRegistry(found)) return found;
24
+ if (!incompatibleStandIn) {
25
+ console.warn("[kitcn] identity guard state of another kitcn revision is on this page; guarded providers hand out no token until the page reloads.");
26
+ incompatibleStandIn = {
27
+ ...createRegistry(),
28
+ incompatible: true
29
+ };
30
+ }
31
+ return incompatibleStandIn;
32
+ };
33
+ const isDocumentTripped = () => pageRegistry()?.tripped ?? false;
34
+ const tripDocument = () => {
35
+ const registry = pageRegistry();
36
+ if (!registry || registry.tripped) return;
37
+ registry.tripped = true;
38
+ for (const listener of [...registry.tripListeners]) try {
39
+ listener();
40
+ } catch (error) {
41
+ console.error("[kitcn] identity guard trip listener threw", error);
42
+ }
43
+ };
44
+ const guardedProviderMounted = () => [...pageRegistry()?.guards ?? []].some((mounted) => mounted.guarded);
45
+ const boundIdentities = (guard) => {
46
+ const registry = pageRegistry();
47
+ const bound = [registry?.documentIdentity ?? null];
48
+ if (guard?.guarded) bound.push(guard.identity, guard.baseline());
49
+ for (const mounted of registry?.guards ?? []) if (mounted.hasGetter) bound.push(mounted.baseline());
50
+ return bound.filter((identity) => identity !== null);
51
+ };
52
+ const identityGuardInPlay = (guard) => !!guard?.guarded || boundIdentities(guard).length > 0 || guardedProviderMounted();
53
+ const isTokenAdmissible = (token, guard, use) => {
54
+ if (isDocumentTripped() || guard?.tripped) return false;
55
+ if (guard?.guarded && pageRegistry()?.incompatible) return false;
56
+ const bound = boundIdentities(guard);
57
+ if (!isJwt(token)) {
58
+ if (use === "hold") return true;
59
+ if (use === "restore") return bound.length === 0;
60
+ return !identityGuardInPlay(guard);
61
+ }
62
+ const identity = decodeTokenSubjectSessionIdentity(token);
63
+ return identity === null ? bound.length === 0 : bound.every((known) => known === identity);
64
+ };
65
+ const admitToken = (token, { announce = false, guard, use }) => {
66
+ if (!isTokenAdmissible(token, guard, use)) {
67
+ if (isJwt(token)) {
68
+ if (guard) guard.tripped = true;
69
+ tripDocument();
70
+ }
71
+ return false;
72
+ }
73
+ const identity = isJwt(token) ? decodeTokenSubjectSessionIdentity(token) : null;
74
+ if (identity !== null && (guard?.guarded || guardedProviderMounted())) {
75
+ if (guard?.guarded) guard.identity = identity;
76
+ const registry = pageRegistry();
77
+ if (registry) registry.documentIdentity ??= identity;
78
+ }
79
+ if (announce && guard?.guarded && isJwt(token)) {
80
+ guard.onAdmitted(token);
81
+ return admitToken(token, {
82
+ guard,
83
+ use
84
+ });
85
+ }
86
+ return !isDocumentTripped() && !guard?.tripped;
87
+ };
88
+ function decodeJwtClaims(token) {
89
+ const segments = token.split(".");
90
+ if (segments.length !== 3 || !segments[1]) return null;
91
+ try {
92
+ const payload = JSON.parse(atob(segments[1].replaceAll("-", "+").replaceAll("_", "/")));
93
+ return typeof payload === "object" && payload !== null && !Array.isArray(payload) ? payload : null;
94
+ } catch {
95
+ return null;
96
+ }
97
+ }
98
+ const isJwt = (token) => decodeJwtClaims(token) !== null;
99
+ /**
100
+ * The user and session a Better Auth Convex JWT speaks for (`sub` and
101
+ * `sessionId`), or null. Other claims (name, email, updatedAt) may change
102
+ * within one session and do not count.
103
+ */
104
+ function decodeTokenSubjectSessionIdentity(token) {
105
+ const claims = token ? decodeJwtClaims(token) : null;
106
+ if (!claims || typeof claims.sub !== "string") return null;
107
+ const sessionId = typeof claims.sessionId === "string" ? claims.sessionId : "";
108
+ return `${claims.sub}|${sessionId}`;
109
+ }
110
+
111
+ //#endregion
112
+ //#region src/auth-client/client-settlement.ts
113
+ function settleClient(client) {
114
+ const registry = pageRegistry();
115
+ if (!registry || registry.settledClients.has(client)) return;
116
+ registry.settledClients.add(client);
117
+ for (const listener of [...registry.settlementListeners.get(client) ?? []]) listener();
118
+ }
119
+
120
+ //#endregion
1
121
  //#region src/auth-start/index.ts
2
122
  const startLoaderAuthTokens = /* @__PURE__ */ new WeakMap();
3
123
  const isStartLoaderConvexQueryClient = (target) => "convexClient" in target;
4
124
  const syncConvexAuthForStartLoader = async ({ convex, getToken }) => {
5
125
  const authClient = isStartLoaderConvexQueryClient(convex) ? convex.convexClient : convex;
6
126
  const serverHttpClient = isStartLoaderConvexQueryClient(convex) ? convex.serverHttpClient : void 0;
7
- const token = await getToken() ?? null;
127
+ const loaderToken = await getToken() ?? null;
128
+ const admit = (candidate) => admitToken(candidate, { use: "handout" });
129
+ const token = loaderToken !== null && !admit(loaderToken) ? null : loaderToken;
8
130
  if (startLoaderAuthTokens.get(convex) === token) return {
9
131
  isAuthenticated: token !== null,
10
132
  token
@@ -18,7 +140,17 @@ const syncConvexAuthForStartLoader = async ({ convex, getToken }) => {
18
140
  token
19
141
  };
20
142
  }
21
- authClient.setAuth(async () => token);
143
+ settleClient(authClient);
144
+ authClient.setAuth(async () => admit(token) ? token : null);
145
+ if (isDocumentTripped()) {
146
+ startLoaderAuthTokens.set(convex, null);
147
+ authClient.clearAuth();
148
+ serverHttpClient?.clearAuth?.();
149
+ return {
150
+ isAuthenticated: false,
151
+ token: null
152
+ };
153
+ }
22
154
  serverHttpClient?.setAuth(token);
23
155
  return {
24
156
  isAuthenticated: true,
@@ -1,5 +1,5 @@
1
1
  import { B as dateWireCodec, F as DATE_CODEC_TAG, G as identityTransformer, H as defaultCRPCTransformer, I as DataTransformer, L as DataTransformerOptions, P as CombinedDataTransformer, R as WireCodec, U as encodeWire, V as decodeWire, W as getTransformer, a as HttpErrorCode, c as HttpQueryKey, d as HttpRouteMap, f as InferHttpInput, g as isHttpClientError, h as buildHttpQueryPrefixKey, i as HttpClientFromRouter, l as HttpQueryPrefixKey, m as buildHttpQueryKey, n as HttpClient, o as HttpMutationKey, p as InferHttpOutput, r as HttpClientError, s as HttpProcedureCall, t as HTTP_DEFAULT_STALE_TIME, u as HttpRouteInfo, z as createTaggedTransformer } from "../http-types-BhhPZtwa.js";
2
- import { A as HttpInputArgs, C as ReservedMutationOptions, D as VanillaMutation, E as VanillaAction, F as replaceUrlParam, M as RESERVED_KEYS, N as buildSearchParams, O as HttpClientOptions, P as executeHttpRequest, S as ReservedInfiniteQueryOptions, T as StaticQueryOptsParam, _ as IsPaginated, a as BaseInfiniteQueryOptsParam, b as PaginatedFnMeta, c as ConvexMutationKey, d as ConvexQueryMeta, f as EmptyObject, g as InfiniteQueryInput, h as FnMeta, i as BaseConvexQueryOptions, j as HttpProxyBaseOptions, k as HttpFormValue, l as ConvexQueryHookOptions, m as FUNC_REF_SYMBOL, n as BaseConvexActionOptions, o as ConvexActionKey, p as ExtractPaginatedItem, r as BaseConvexInfiniteQueryOptions, s as ConvexInfiniteQueryMeta, t as AuthType, u as ConvexQueryKey, v as Meta, w as ReservedQueryOptions, x as PaginationOpts, y as MutationVariables } from "../types-C7JkpfeY.js";
2
+ import { A as HttpInputArgs, C as ReservedMutationOptions, D as VanillaMutation, E as VanillaAction, F as executeHttpRequest, I as replaceUrlParam, L as withAuthorizationRecheck, M as RECHECK_AUTHORIZATION, N as RESERVED_KEYS, O as HttpClientOptions, P as buildSearchParams, S as ReservedInfiniteQueryOptions, T as StaticQueryOptsParam, _ as IsPaginated, a as BaseInfiniteQueryOptsParam, b as PaginatedFnMeta, c as ConvexMutationKey, d as ConvexQueryMeta, f as EmptyObject, g as InfiniteQueryInput, h as FnMeta, i as BaseConvexQueryOptions, j as HttpProxyBaseOptions, k as HttpFormValue, l as ConvexQueryHookOptions, m as FUNC_REF_SYMBOL, n as BaseConvexActionOptions, o as ConvexActionKey, p as ExtractPaginatedItem, r as BaseConvexInfiniteQueryOptions, s as ConvexInfiniteQueryMeta, t as AuthType, u as ConvexQueryKey, v as Meta, w as ReservedQueryOptions, x as PaginationOpts, y as MutationVariables } from "../types-Bb0kwteA.js";
3
3
  import { FunctionArgs, FunctionReference } from "convex/server";
4
4
 
5
5
  //#region src/crpc/auth-error.d.ts
@@ -107,4 +107,4 @@ declare function convexAction<T extends FunctionReference<'action'>>(funcRef: T,
107
107
  */
108
108
  declare function convexInfiniteQueryOptions<T extends FunctionReference<'query'>>(funcRef: T, args: Record<string, unknown> | 'skip', opts?: BaseInfiniteQueryOptsParam<T> & Record<string, unknown>, meta?: Meta): BaseConvexInfiniteQueryOptions<T> & Record<string, unknown>;
109
109
  //#endregion
110
- export { AuthMutationError, AuthType, BaseConvexActionOptions, BaseConvexInfiniteQueryOptions, BaseConvexQueryOptions, BaseInfiniteQueryOptsParam, CRPCClientError, CombinedDataTransformer, ConvexActionKey, ConvexInfiniteQueryMeta, ConvexMutationKey, ConvexQueryHookOptions, ConvexQueryKey, ConvexQueryMeta, DATE_CODEC_TAG, DataTransformer, DataTransformerOptions, EmptyObject, ExtractPaginatedItem, FUNC_REF_SYMBOL, FnMeta, HTTP_DEFAULT_STALE_TIME, HttpClient, HttpClientError, HttpClientFromRouter, HttpClientOptions, HttpErrorCode, HttpFormValue, HttpInputArgs, HttpMutationKey, HttpProcedureCall, HttpProxyBaseOptions, HttpQueryKey, HttpQueryPrefixKey, HttpRouteInfo, HttpRouteMap, InferHttpInput, InferHttpOutput, InfiniteQueryInput, IsPaginated, Meta, MutationVariables, PaginatedFnMeta, PaginationOpts, RESERVED_KEYS, ReservedInfiniteQueryOptions, ReservedMutationOptions, ReservedQueryOptions, StaticQueryOptsParam, VanillaAction, VanillaMutation, WireCodec, buildHttpQueryKey, buildHttpQueryPrefixKey, buildSearchParams, convexAction, convexInfiniteQueryOptions, convexQuery, createTaggedTransformer, dateWireCodec, decodeWire, defaultCRPCTransformer, defaultIsUnauthorized, encodeWire, executeHttpRequest, getTransformer, identityTransformer, isAuthMutationError, isCRPCClientError, isCRPCError, isCRPCErrorCode, isHttpClientError, replaceUrlParam };
110
+ export { AuthMutationError, AuthType, BaseConvexActionOptions, BaseConvexInfiniteQueryOptions, BaseConvexQueryOptions, BaseInfiniteQueryOptsParam, CRPCClientError, CombinedDataTransformer, ConvexActionKey, ConvexInfiniteQueryMeta, ConvexMutationKey, ConvexQueryHookOptions, ConvexQueryKey, ConvexQueryMeta, DATE_CODEC_TAG, DataTransformer, DataTransformerOptions, EmptyObject, ExtractPaginatedItem, FUNC_REF_SYMBOL, FnMeta, HTTP_DEFAULT_STALE_TIME, HttpClient, HttpClientError, HttpClientFromRouter, HttpClientOptions, HttpErrorCode, HttpFormValue, HttpInputArgs, HttpMutationKey, HttpProcedureCall, HttpProxyBaseOptions, HttpQueryKey, HttpQueryPrefixKey, HttpRouteInfo, HttpRouteMap, InferHttpInput, InferHttpOutput, InfiniteQueryInput, IsPaginated, Meta, MutationVariables, PaginatedFnMeta, PaginationOpts, RECHECK_AUTHORIZATION, RESERVED_KEYS, ReservedInfiniteQueryOptions, ReservedMutationOptions, ReservedQueryOptions, StaticQueryOptsParam, VanillaAction, VanillaMutation, WireCodec, buildHttpQueryKey, buildHttpQueryPrefixKey, buildSearchParams, convexAction, convexInfiniteQueryOptions, convexQuery, createTaggedTransformer, dateWireCodec, decodeWire, defaultCRPCTransformer, defaultIsUnauthorized, encodeWire, executeHttpRequest, getTransformer, identityTransformer, isAuthMutationError, isCRPCClientError, isCRPCError, isCRPCErrorCode, isHttpClientError, replaceUrlParam, withAuthorizationRecheck };
@@ -1,6 +1,6 @@
1
1
  import { a as isCRPCErrorCode, i as isCRPCError, n as defaultIsUnauthorized, r as isCRPCClientError, t as CRPCClientError } from "../error-CLgc9khF.js";
2
2
  import { a as defaultCRPCTransformer, c as identityTransformer, i as decodeWire, n as createTaggedTransformer, o as encodeWire, r as dateWireCodec, s as getTransformer, t as DATE_CODEC_TAG } from "../transformer-C8lVwHNT.js";
3
- import { a as buildSearchParams, c as HTTP_DEFAULT_STALE_TIME, d as buildHttpQueryPrefixKey, f as isHttpClientError, i as RESERVED_KEYS, l as HttpClientError, n as convexInfiniteQueryOptions, o as executeHttpRequest, r as convexQuery, s as replaceUrlParam, t as convexAction, u as buildHttpQueryKey } from "../query-options-DGG93--5.js";
3
+ import { a as RESERVED_KEYS, c as replaceUrlParam, d as HttpClientError, f as buildHttpQueryKey, i as RECHECK_AUTHORIZATION, l as withAuthorizationRecheck, m as isHttpClientError, n as convexInfiniteQueryOptions, o as buildSearchParams, p as buildHttpQueryPrefixKey, r as convexQuery, s as executeHttpRequest, t as convexAction, u as HTTP_DEFAULT_STALE_TIME } from "../query-options-YkFvau71.js";
4
4
 
5
5
  //#region src/crpc/auth-error.ts
6
6
  /**
@@ -40,4 +40,4 @@ function isAuthMutationError(error) {
40
40
  const FUNC_REF_SYMBOL = Symbol.for("convex.funcRef");
41
41
 
42
42
  //#endregion
43
- export { AuthMutationError, CRPCClientError, DATE_CODEC_TAG, FUNC_REF_SYMBOL, HTTP_DEFAULT_STALE_TIME, HttpClientError, RESERVED_KEYS, buildHttpQueryKey, buildHttpQueryPrefixKey, buildSearchParams, convexAction, convexInfiniteQueryOptions, convexQuery, createTaggedTransformer, dateWireCodec, decodeWire, defaultCRPCTransformer, defaultIsUnauthorized, encodeWire, executeHttpRequest, getTransformer, identityTransformer, isAuthMutationError, isCRPCClientError, isCRPCError, isCRPCErrorCode, isHttpClientError, replaceUrlParam };
43
+ export { AuthMutationError, CRPCClientError, DATE_CODEC_TAG, FUNC_REF_SYMBOL, HTTP_DEFAULT_STALE_TIME, HttpClientError, RECHECK_AUTHORIZATION, RESERVED_KEYS, buildHttpQueryKey, buildHttpQueryPrefixKey, buildSearchParams, convexAction, convexInfiniteQueryOptions, convexQuery, createTaggedTransformer, dateWireCodec, decodeWire, defaultCRPCTransformer, defaultIsUnauthorized, encodeWire, executeHttpRequest, getTransformer, identityTransformer, isAuthMutationError, isCRPCClientError, isCRPCError, isCRPCErrorCode, isHttpClientError, replaceUrlParam, withAuthorizationRecheck };
@@ -199,20 +199,20 @@ declare const createApi: <Schema extends SchemaDefinition<any, any>, DataModel e
199
199
  count: convex_server0.RegisteredQuery<"internal", {
200
200
  where?: {
201
201
  mode?: "sensitive" | "insensitive" | undefined;
202
+ operator?: "eq" | "ne" | "lt" | "lte" | "gt" | "gte" | "in" | "not_in" | "contains" | "starts_with" | "ends_with" | undefined;
202
203
  connector?: "AND" | "OR" | undefined;
203
- operator?: "lt" | "lte" | "gt" | "gte" | "eq" | "in" | "not_in" | "ne" | "contains" | "starts_with" | "ends_with" | undefined;
204
- field: string;
205
204
  value: string | number | boolean | string[] | number[] | null;
205
+ field: string;
206
206
  }[] | undefined;
207
207
  model: string;
208
208
  }, Promise<number | null>>;
209
209
  consumeOne: convex_server0.RegisteredMutation<"internal", {
210
210
  input: {
211
211
  where?: {
212
+ operator?: "eq" | "ne" | "lt" | "lte" | "gt" | "gte" | "in" | "not_in" | "contains" | "starts_with" | "ends_with" | undefined;
212
213
  connector?: "AND" | "OR" | undefined;
213
- operator?: "lt" | "lte" | "gt" | "gte" | "eq" | "in" | "not_in" | "ne" | "contains" | "starts_with" | "ends_with" | undefined;
214
- field: string;
215
214
  value: string | number | boolean | string[] | number[] | null;
215
+ field: string;
216
216
  }[] | undefined;
217
217
  model: string;
218
218
  } | {
@@ -237,10 +237,10 @@ declare const createApi: <Schema extends SchemaDefinition<any, any>, DataModel e
237
237
  deleteMany: convex_server0.RegisteredMutation<"internal", {
238
238
  input: {
239
239
  where?: {
240
+ operator?: "eq" | "ne" | "lt" | "lte" | "gt" | "gte" | "in" | "not_in" | "contains" | "starts_with" | "ends_with" | undefined;
240
241
  connector?: "AND" | "OR" | undefined;
241
- operator?: "lt" | "lte" | "gt" | "gte" | "eq" | "in" | "not_in" | "ne" | "contains" | "starts_with" | "ends_with" | undefined;
242
- field: string;
243
242
  value: string | number | boolean | string[] | number[] | null;
243
+ field: string;
244
244
  }[] | undefined;
245
245
  model: string;
246
246
  } | {
@@ -266,10 +266,10 @@ declare const createApi: <Schema extends SchemaDefinition<any, any>, DataModel e
266
266
  deleteOne: convex_server0.RegisteredMutation<"internal", {
267
267
  input: {
268
268
  where?: {
269
+ operator?: "eq" | "ne" | "lt" | "lte" | "gt" | "gte" | "in" | "not_in" | "contains" | "starts_with" | "ends_with" | undefined;
269
270
  connector?: "AND" | "OR" | undefined;
270
- operator?: "lt" | "lte" | "gt" | "gte" | "eq" | "in" | "not_in" | "ne" | "contains" | "starts_with" | "ends_with" | undefined;
271
- field: string;
272
271
  value: string | number | boolean | string[] | number[] | null;
272
+ field: string;
273
273
  }[] | undefined;
274
274
  model: string;
275
275
  } | {
@@ -278,21 +278,20 @@ declare const createApi: <Schema extends SchemaDefinition<any, any>, DataModel e
278
278
  };
279
279
  }, Promise<Record<string, unknown> | undefined>>;
280
280
  findMany: convex_server0.RegisteredQuery<"internal", {
281
+ limit?: number | undefined;
281
282
  join?: any;
282
283
  where?: {
283
284
  mode?: "sensitive" | "insensitive" | undefined;
285
+ operator?: "eq" | "ne" | "lt" | "lte" | "gt" | "gte" | "in" | "not_in" | "contains" | "starts_with" | "ends_with" | undefined;
284
286
  connector?: "AND" | "OR" | undefined;
285
- operator?: "lt" | "lte" | "gt" | "gte" | "eq" | "in" | "not_in" | "ne" | "contains" | "starts_with" | "ends_with" | undefined;
286
- field: string;
287
287
  value: string | number | boolean | string[] | number[] | null;
288
+ field: string;
288
289
  }[] | undefined;
289
- limit?: number | undefined;
290
290
  offset?: number | undefined;
291
291
  sortBy?: {
292
- field: string;
293
292
  direction: "asc" | "desc";
293
+ field: string;
294
294
  } | undefined;
295
- model: string;
296
295
  paginationOpts: {
297
296
  id?: number;
298
297
  endCursor?: string | null;
@@ -301,15 +300,16 @@ declare const createApi: <Schema extends SchemaDefinition<any, any>, DataModel e
301
300
  numItems: number;
302
301
  cursor: string | null;
303
302
  };
303
+ model: string;
304
304
  }, Promise<PaginationResult<convex_server0.GenericDocument>>>;
305
305
  findOne: convex_server0.RegisteredQuery<"internal", {
306
306
  join?: any;
307
307
  where?: {
308
308
  mode?: "sensitive" | "insensitive" | undefined;
309
+ operator?: "eq" | "ne" | "lt" | "lte" | "gt" | "gte" | "in" | "not_in" | "contains" | "starts_with" | "ends_with" | undefined;
309
310
  connector?: "AND" | "OR" | undefined;
310
- operator?: "lt" | "lte" | "gt" | "gte" | "eq" | "in" | "not_in" | "ne" | "contains" | "starts_with" | "ends_with" | undefined;
311
- field: string;
312
311
  value: string | number | boolean | string[] | number[] | null;
312
+ field: string;
313
313
  }[] | undefined;
314
314
  select?: string[] | undefined;
315
315
  model: string;
@@ -317,14 +317,14 @@ declare const createApi: <Schema extends SchemaDefinition<any, any>, DataModel e
317
317
  getLatestJwks: convex_server0.RegisteredAction<"internal", {}, Promise<unknown>>;
318
318
  incrementOne: convex_server0.RegisteredMutation<"internal", {
319
319
  input: {
320
+ set?: Record<string, any> | undefined;
320
321
  where?: {
321
322
  mode?: "sensitive" | "insensitive" | undefined;
323
+ operator?: "eq" | "ne" | "lt" | "lte" | "gt" | "gte" | "in" | "not_in" | "contains" | "starts_with" | "ends_with" | undefined;
322
324
  connector?: "AND" | "OR" | undefined;
323
- operator?: "lt" | "lte" | "gt" | "gte" | "eq" | "in" | "not_in" | "ne" | "contains" | "starts_with" | "ends_with" | undefined;
324
- field: string;
325
325
  value: string | number | boolean | string[] | number[] | null;
326
+ field: string;
326
327
  }[] | undefined;
327
- set?: Record<string, any> | undefined;
328
328
  model: string;
329
329
  increment: Record<string, number>;
330
330
  };
@@ -333,21 +333,21 @@ declare const createApi: <Schema extends SchemaDefinition<any, any>, DataModel e
333
333
  updateMany: convex_server0.RegisteredMutation<"internal", {
334
334
  input: {
335
335
  where?: {
336
+ operator?: "eq" | "ne" | "lt" | "lte" | "gt" | "gte" | "in" | "not_in" | "contains" | "starts_with" | "ends_with" | undefined;
336
337
  connector?: "AND" | "OR" | undefined;
337
- operator?: "lt" | "lte" | "gt" | "gte" | "eq" | "in" | "not_in" | "ne" | "contains" | "starts_with" | "ends_with" | undefined;
338
- field: string;
339
338
  value: string | number | boolean | string[] | number[] | null;
339
+ field: string;
340
340
  }[] | undefined;
341
- model: string;
342
341
  update: {
343
342
  [x: string]: unknown;
344
343
  [x: number]: unknown;
345
344
  [x: symbol]: unknown;
346
345
  };
346
+ model: string;
347
347
  } | {
348
348
  where?: any[] | undefined;
349
- model: string;
350
349
  update: any;
350
+ model: string;
351
351
  };
352
352
  paginationOpts: {
353
353
  id?: number;
@@ -368,21 +368,21 @@ declare const createApi: <Schema extends SchemaDefinition<any, any>, DataModel e
368
368
  updateOne: convex_server0.RegisteredMutation<"internal", {
369
369
  input: {
370
370
  where?: {
371
+ operator?: "eq" | "ne" | "lt" | "lte" | "gt" | "gte" | "in" | "not_in" | "contains" | "starts_with" | "ends_with" | undefined;
371
372
  connector?: "AND" | "OR" | undefined;
372
- operator?: "lt" | "lte" | "gt" | "gte" | "eq" | "in" | "not_in" | "ne" | "contains" | "starts_with" | "ends_with" | undefined;
373
- field: string;
374
373
  value: string | number | boolean | string[] | number[] | null;
374
+ field: string;
375
375
  }[] | undefined;
376
- model: string;
377
376
  update: {
378
377
  [x: string]: unknown;
379
378
  [x: number]: unknown;
380
379
  [x: symbol]: unknown;
381
380
  };
381
+ model: string;
382
382
  } | {
383
383
  where?: any[] | undefined;
384
- model: string;
385
384
  update: any;
385
+ model: string;
386
386
  };
387
387
  }, Promise<any>>;
388
388
  };
@@ -1,5 +1,5 @@
1
1
  import { $n as TableName, $t as OrmLifecycleChange, An as ConvexCheckBuilder, At as UpdateSet, Bn as ConvexTextBuilder, Br as IsPrimaryKey, Bt as RelationsBuilderColumnBase, C as MigrationStep, Cn as ConvexVectorIndexConfig, Cr as not, Ct as OrderByClause, D as defineMigration, Dn as searchIndex, Dr as startsWith, Dt as ReturningAll, E as buildMigrationPlan, En as rankIndex, Er as or, Et as PredicateWhereIndexConfig, Fn as ConvexUniqueConstraintBuilderOn, Fr as ColumnBuilderTypeConfig, Ft as ExtractTablesFromSchema, Gn as Columns, Gt as TablesRelationalConfig, H as RlsMode, Hn as text, Hr as NotNull, In as ConvexUniqueConstraintConfig, Ir as ColumnBuilderWithTableName, It as ExtractTablesWithRelations, Jn as OrmSchemaExtensionTables, Jt as ConvexDeletionBuilder, Kt as defineRelations, Ln as check, Lr as ColumnDataType, Lt as ManyConfig, M as DatabaseWithQuery, Mn as ConvexForeignKeyBuilder, Mr as ColumnBuilder, Mt as VectorSearchProvider, N as OrmReader$1, Nn as ConvexForeignKeyConfig, Nr as ColumnBuilderBaseConfig, Nt as unsetToken, O as defineMigrationSet, On as uniqueIndex, Ot as ReturningResult, P as OrmWriter$1, Pn as ConvexUniqueConstraintBuilder, Pr as ColumnBuilderRuntimeConfig, Qn as OrmSchemaTriggers, Qt as DiscriminatorBuilderConfig, Rn as foreignKey, Rr as DrizzleEntity, Rt as OneConfig, S as MigrationStateMap, Sn as ConvexVectorIndexBuilderOn, Sr as ne, St as MutationRunMode, T as MigrationWriteMode, Tn as index, Tr as notInArray, Tt as PaginatedResult, U as EdgeMetadata, V as RlsContext, Vn as ConvexTextBuilderInitial, Vr as IsUnique, Vt as RelationsBuilderColumnConfig, W as extractRelationsConfig, Wn as Brand, Wt as TableRelationalConfig, Xn as OrmSchemaExtensions, Xt as ConvexTable, Yt as ConvexDeletionConfig, Zn as OrmSchemaRelations, Zt as ConvexTableWithColumns, _ as MigrationManifestEntry, _n as ConvexRankIndexBuilderOn, _r as isNotNull, _t as MutationExecutionMode, an as RlsPolicy, ar as UnaryExpression, at as BuildRelationResult, b as MigrationRunStatus, bn as ConvexSearchIndexConfig, br as lt, bt as MutationResult, cn as rlsPolicy, cr as contains, ct as DBQueryConfig, d as MigrationAppliedState, dn as rlsRole, dr as fieldRef, dt as InferInsertModel, en as OrmLifecycleOperation, er as BinaryExpression, f as MigrationDefinition, fn as ConvexAggregateIndexBuilder, fr as gt, ft as InferModelFromColumns, g as MigrationDriftIssue, gn as ConvexRankIndexBuilder, gr as isFieldReference, gt as MutationExecuteResult, h as MigrationDocContext, hn as ConvexIndexBuilderOn, hr as inArray, ht as MutationExecuteConfig, i as OrmMigrationCapability, in as discriminator, ir as LogicalExpression, it as BuildQueryResult, j as DatabaseWithMutations, jn as ConvexCheckConfig, jr as AnyColumn, jt as VectorQueryConfig, k as detectMigrationDrift, kn as vectorIndex, kr as SystemFields, kt as ReturningSelection, ln as RlsRole, lr as endsWith, lt as FilterOperators, m as MigrationDoc, mn as ConvexIndexBuilder, mr as ilike, mt as InsertValue, n as OrmCapabilities, nn as convexTable, nr as FieldReference, nt as AggregateFieldValue, on as RlsPolicyConfig, or as and, ot as CountConfig, p as MigrationDirection, pn as ConvexAggregateIndexBuilderOn, pr as gte, pt as InferSelectModel, qt as defineRelationsPart, r as OrmCapability, rn as deletion, rr as FilterExpression, rt as AggregateResult, sn as RlsPolicyToOption, sr as between, st as CountResult, t as OrmAggregateCapability, tn as TableConfig, tr as ExpressionVisitor, tt as AggregateConfig, un as RlsRoleConfig, ur as eq, ut as GetColumnData, v as MigrationMigrateOne, vn as ConvexSearchIndexBuilder, vr as isNull, vt as MutationPaginateConfig, w as MigrationTableName, wn as aggregateIndex, wr as notBetween, wt as OrderDirection, x as MigrationSet, xn as ConvexVectorIndexBuilder, xr as lte, xt as MutationReturning, y as MigrationPlan, yn as ConvexSearchIndexBuilderOn, yr as like, yt as MutationPaginatedResult, zn as unique, zr as HasDefault, zt as RelationsBuilder } from "../capabilities-Bxzoofl4.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-qH6-NCM9.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-DAqhUREe.js";
3
3
  import { i as pretendRequired, n as deprecated, r as pretend } from "../validators-0I-Ik1EN.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-BkNjkDCk.js";
5
5
  import { DefineSchemaOptions, GenericDatabaseReader, GenericDatabaseWriter, GenericSchema, SchemaDefinition } from "convex/server";
@@ -1,3 +1,3 @@
1
1
  import { C as MigrationStep, D as defineMigration, E as buildMigrationPlan, O as defineMigrationSet, S as MigrationStateMap, T as MigrationWriteMode, _ as MigrationManifestEntry, a as MAX_STATUS_RUN_LIMIT, b as MigrationRunStatus, c as MigrationRunChunkArgs, d as MigrationAppliedState, f as MigrationDefinition, g as MigrationDriftIssue, h as MigrationDocContext, k as detectMigrationDrift, l as MigrationStatusArgs, m as MigrationDoc, o as MigrationCancelArgs, p as MigrationDirection, s as MigrationRunArgs, u as createMigrationHandlers, v as MigrationMigrateOne, w as MigrationTableName, x as MigrationSet, y as MigrationPlan } from "../../capabilities-Bxzoofl4.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-qH6-NCM9.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-DAqhUREe.js";
3
3
  export { MAX_STATUS_RUN_LIMIT, 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 };
@@ -86,6 +86,8 @@ function buildSearchParams(query) {
86
86
  else if (value !== void 0 && value !== null) params.append(key, value);
87
87
  return params;
88
88
  }
89
+ const RECHECK_AUTHORIZATION = Symbol.for("kitcn.http.recheckAuthorization");
90
+ const withAuthorizationRecheck = (headers, recheck) => Object.defineProperty(headers, RECHECK_AUTHORIZATION, { value: recheck });
89
91
  /**
90
92
  * Hono-style HTTP request executor.
91
93
  * Processes args in the same way as Hono's ClientRequestImpl.fetch().
@@ -124,6 +126,8 @@ async function executeHttpRequest(opts) {
124
126
  for (const [key, value] of Object.entries(resolvedBaseHeaders)) if (value !== void 0) finalHeaders[key] = value;
125
127
  }
126
128
  Object.assign(finalHeaders, headerValues);
129
+ const recheck = resolvedBaseHeaders?.[RECHECK_AUTHORIZATION];
130
+ const sendHeaders = recheck && finalHeaders.Authorization === resolvedBaseHeaders?.Authorization && !recheck() ? Object.fromEntries(Object.entries(finalHeaders).filter(([key]) => key !== "Authorization")) : finalHeaders;
127
131
  let url = opts.convexSiteUrl + path;
128
132
  if (args.params) url = opts.convexSiteUrl + replaceUrlParam(path, args.params);
129
133
  if (args.searchParams) {
@@ -135,7 +139,7 @@ async function executeHttpRequest(opts) {
135
139
  const response = await (mergedClientOpts.fetch ?? opts.baseFetch ?? globalThis.fetch)(url, {
136
140
  body: setBody ? rBody : void 0,
137
141
  method: methodUpperCase,
138
- headers: finalHeaders,
142
+ headers: sendHeaders,
139
143
  ...mergedClientOpts.init
140
144
  });
141
145
  if (!response.ok) {
@@ -276,4 +280,4 @@ function convexInfiniteQueryOptions(funcRef, args, opts = {}, meta) {
276
280
  }
277
281
 
278
282
  //#endregion
279
- export { buildSearchParams as a, HTTP_DEFAULT_STALE_TIME as c, buildHttpQueryPrefixKey as d, isHttpClientError as f, RESERVED_KEYS as i, HttpClientError as l, convexInfiniteQueryOptions as n, executeHttpRequest as o, convexQuery as r, replaceUrlParam as s, convexAction as t, buildHttpQueryKey as u };
283
+ export { RESERVED_KEYS as a, replaceUrlParam as c, HttpClientError as d, buildHttpQueryKey as f, RECHECK_AUTHORIZATION as i, withAuthorizationRecheck as l, isHttpClientError as m, convexInfiniteQueryOptions as n, buildSearchParams as o, buildHttpQueryPrefixKey as p, convexQuery as r, executeHttpRequest as s, convexAction as t, HTTP_DEFAULT_STALE_TIME as u };
@@ -5,7 +5,8 @@ import { ReactNode } from "react";
5
5
  import * as react_jsx_runtime0 from "react/jsx-runtime";
6
6
  import { FunctionArgs, FunctionReference, FunctionReturnType } from "convex/server";
7
7
  import { DefaultError, QueryCache, QueryClient, QueryFilters, QueryFunction, QueryFunctionContext, QueryKey, SkipToken, UseMutationOptions, UseQueryOptions, UseQueryResult } from "@tanstack/react-query";
8
- import { ConvexHttpClient } from "convex/browser";
8
+ import { Value } from "convex/values";
9
+ import { ConvexHttpClient, OptimisticUpdate } from "convex/browser";
9
10
  import { z } from "zod";
10
11
 
11
12
  //#region src/crpc/auth-error.d.ts
@@ -582,11 +583,19 @@ type DecorateInfiniteQuery<T extends FunctionReference<'query'>> = {
582
583
  infiniteQueryKey: (args?: DeepPartial<InfiniteQueryInput<FunctionArgs<T>>>) => ConvexQueryKey<T>; /** Function metadata from server (auth, limit, rateLimit, role, type) */
583
584
  meta: PaginatedFnMeta;
584
585
  };
586
+ /**
587
+ * Convex-native optimistic update for a cRPC mutation. It edits Convex's local
588
+ * query store, which the query client reads, so Convex rolls it back when the
589
+ * mutation fails. Args and query values are in their wire shape.
590
+ */
591
+ type ConvexOptimisticUpdateOption<Args extends Record<string, Value>> = {
592
+ optimisticUpdate?: OptimisticUpdate<Args>;
593
+ };
585
594
  /**
586
595
  * Decorated mutation procedure with mutationOptions and mutationKey methods.
587
596
  */
588
597
  type DecorateMutation<T extends FunctionReference<'mutation'>> = {
589
- mutationOptions: (opts?: DistributiveOmit<UseMutationOptions<FunctionReturnType<T>, DefaultError, MutationVariables<T>>, ReservedMutationOptions$2>) => UseMutationOptions<FunctionReturnType<T>, DefaultError, MutationVariables<T>>; /** Get mutation key for QueryClient methods */
598
+ mutationOptions: (opts?: DistributiveOmit<UseMutationOptions<FunctionReturnType<T>, DefaultError, MutationVariables<T>>, ReservedMutationOptions$2> & ConvexOptimisticUpdateOption<FunctionArgs<T>>) => UseMutationOptions<FunctionReturnType<T>, DefaultError, MutationVariables<T>>; /** Get mutation key for QueryClient methods */
590
599
  mutationKey: () => ConvexMutationKey;
591
600
  };
592
601
  /**
@@ -1087,7 +1096,7 @@ declare function useConvexActionQueryOptions<Action extends FunctionReference<'a
1087
1096
  * }));
1088
1097
  * ```
1089
1098
  */
1090
- declare function useConvexMutationOptions<Mutation extends FunctionReference<'mutation'>>(mutation: Mutation, options?: DistributiveOmit<UseMutationOptions<FunctionReturnType<Mutation>, DefaultError, FunctionArgs<Mutation>>, ReservedMutationOptions>, transformer?: DataTransformerOptions): UseMutationOptions<FunctionReturnType<Mutation>, DefaultError, FunctionArgs<Mutation>>;
1099
+ declare function useConvexMutationOptions<Mutation extends FunctionReference<'mutation'>>(mutation: Mutation, options?: DistributiveOmit<UseMutationOptions<FunctionReturnType<Mutation>, DefaultError, FunctionArgs<Mutation>>, ReservedMutationOptions> & ConvexOptimisticUpdateOption<FunctionArgs<Mutation>>, transformer?: DataTransformerOptions): UseMutationOptions<FunctionReturnType<Mutation>, DefaultError, FunctionArgs<Mutation>>;
1091
1100
  /**
1092
1101
  * Hook that returns action options for use with useMutation.
1093
1102
  * Wraps the Convex action with auth guard logic.