better-convex 0.1.0 → 0.2.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.
@@ -1,7 +1,7 @@
1
- import * as better_auth_adapters0 from "better-auth/adapters";
1
+ import * as better_auth_adapters1 from "better-auth/adapters";
2
2
  import { DBAdapterDebugLogOption } from "better-auth/adapters";
3
3
  import { BetterAuthDBSchema } from "better-auth/db";
4
- import * as convex_server0 from "convex/server";
4
+ import * as convex_server24 from "convex/server";
5
5
  import { DocumentByName, FunctionReference, GenericDataModel, GenericMutationCtx, GenericQueryCtx, GenericSchema, HttpRouter, IdField, PaginationOptions, PaginationResult, SchemaDefinition, SystemFields, TableNamesInDataModel, internalMutationGeneric } from "convex/server";
6
6
  import * as convex_values0 from "convex/values";
7
7
  import { Infer } from "convex/values";
@@ -44,31 +44,31 @@ declare const createClient: <DataModel extends GenericDataModel, Schema$1 extend
44
44
  }) => {
45
45
  authFunctions: AuthFunctions;
46
46
  triggers: Triggers<DataModel, Schema$1> | undefined;
47
- adapter: (ctx: GenericCtx<DataModel>, createAuthOptions: (ctx: any) => BetterAuthOptions) => better_auth_adapters0.AdapterFactory;
48
- httpAdapter: (ctx: GenericCtx<DataModel>) => better_auth_adapters0.AdapterFactory;
47
+ adapter: (ctx: GenericCtx<DataModel>, createAuthOptions: (ctx: any) => BetterAuthOptions) => better_auth_adapters1.AdapterFactory;
48
+ httpAdapter: (ctx: GenericCtx<DataModel>) => better_auth_adapters1.AdapterFactory;
49
49
  triggersApi: () => {
50
- beforeCreate: convex_server0.RegisteredMutation<"internal", {
50
+ beforeCreate: convex_server24.RegisteredMutation<"internal", {
51
51
  data: any;
52
52
  model: string;
53
53
  }, Promise<any>>;
54
- beforeDelete: convex_server0.RegisteredMutation<"internal", {
54
+ beforeDelete: convex_server24.RegisteredMutation<"internal", {
55
55
  model: string;
56
56
  doc: any;
57
57
  }, Promise<any>>;
58
- beforeUpdate: convex_server0.RegisteredMutation<"internal", {
58
+ beforeUpdate: convex_server24.RegisteredMutation<"internal", {
59
59
  update: any;
60
60
  model: string;
61
61
  doc: any;
62
62
  }, Promise<any>>;
63
- onCreate: convex_server0.RegisteredMutation<"internal", {
63
+ onCreate: convex_server24.RegisteredMutation<"internal", {
64
64
  model: string;
65
65
  doc: any;
66
66
  }, Promise<void>>;
67
- onDelete: convex_server0.RegisteredMutation<"internal", {
67
+ onDelete: convex_server24.RegisteredMutation<"internal", {
68
68
  model: string;
69
69
  doc: any;
70
70
  }, Promise<void>>;
71
- onUpdate: convex_server0.RegisteredMutation<"internal", {
71
+ onUpdate: convex_server24.RegisteredMutation<"internal", {
72
72
  model: string;
73
73
  newDoc: any;
74
74
  oldDoc: any;
@@ -148,7 +148,7 @@ declare const httpAdapter: <DataModel extends GenericDataModel, Schema$1 extends
148
148
  authFunctions: AuthFunctions;
149
149
  debugLogs?: DBAdapterDebugLogOption;
150
150
  triggers?: Triggers<DataModel, Schema$1>;
151
- }) => better_auth_adapters0.AdapterFactory;
151
+ }) => better_auth_adapters1.AdapterFactory;
152
152
  declare const dbAdapter: <DataModel extends GenericDataModel, Schema$1 extends SchemaDefinition<any, any>>(ctx: GenericCtx<DataModel>, createAuthOptions: (ctx: any) => BetterAuthOptions, {
153
153
  authFunctions,
154
154
  debugLogs,
@@ -159,7 +159,7 @@ declare const dbAdapter: <DataModel extends GenericDataModel, Schema$1 extends S
159
159
  schema: Schema$1;
160
160
  debugLogs?: DBAdapterDebugLogOption;
161
161
  triggers?: Triggers<DataModel, Schema$1>;
162
- }) => better_auth_adapters0.AdapterFactory;
162
+ }) => better_auth_adapters1.AdapterFactory;
163
163
  //#endregion
164
164
  //#region src/auth/adapter-utils.d.ts
165
165
  declare const adapterWhereValidator: convex_values0.VObject<{
@@ -175,18 +175,18 @@ declare const adapterWhereValidator: convex_values0.VObject<{
175
175
  }, "required", "operator" | "value" | "field" | "connector">;
176
176
  declare const adapterArgsValidator: convex_values0.VObject<{
177
177
  limit?: number | undefined;
178
- offset?: number | undefined;
179
- select?: string[] | undefined;
180
- sortBy?: {
181
- field: string;
182
- direction: "asc" | "desc";
183
- } | undefined;
184
178
  where?: {
185
179
  operator?: "eq" | "ne" | "lt" | "lte" | "gt" | "gte" | "in" | "not_in" | "contains" | "starts_with" | "ends_with" | undefined;
186
180
  connector?: "AND" | "OR" | undefined;
187
181
  value: string | number | boolean | string[] | number[] | null;
188
182
  field: string;
189
183
  }[] | undefined;
184
+ select?: string[] | undefined;
185
+ offset?: number | undefined;
186
+ sortBy?: {
187
+ field: string;
188
+ direction: "asc" | "desc";
189
+ } | undefined;
190
190
  model: string;
191
191
  }, {
192
192
  limit: convex_values0.VFloat64<number | undefined, "optional">;
@@ -216,7 +216,7 @@ declare const adapterArgsValidator: convex_values0.VObject<{
216
216
  operator: convex_values0.VUnion<"eq" | "ne" | "lt" | "lte" | "gt" | "gte" | "in" | "not_in" | "contains" | "starts_with" | "ends_with" | undefined, [convex_values0.VLiteral<"lt", "required">, convex_values0.VLiteral<"lte", "required">, convex_values0.VLiteral<"gt", "required">, convex_values0.VLiteral<"gte", "required">, convex_values0.VLiteral<"eq", "required">, convex_values0.VLiteral<"in", "required">, convex_values0.VLiteral<"not_in", "required">, convex_values0.VLiteral<"ne", "required">, convex_values0.VLiteral<"contains", "required">, convex_values0.VLiteral<"starts_with", "required">, convex_values0.VLiteral<"ends_with", "required">], "optional", never>;
217
217
  value: convex_values0.VUnion<string | number | boolean | string[] | number[] | null, [convex_values0.VString<string, "required">, convex_values0.VFloat64<number, "required">, convex_values0.VBoolean<boolean, "required">, convex_values0.VArray<string[], convex_values0.VString<string, "required">, "required">, convex_values0.VArray<number[], convex_values0.VFloat64<number, "required">, "required">, convex_values0.VNull<null, "required">], "required", never>;
218
218
  }, "required", "operator" | "value" | "field" | "connector">, "optional">;
219
- }, "required", "limit" | "model" | "offset" | "select" | "sortBy" | "where" | "sortBy.field" | "sortBy.direction">;
219
+ }, "required", "limit" | "where" | "model" | "select" | "offset" | "sortBy" | "sortBy.field" | "sortBy.direction">;
220
220
  declare const hasUniqueFields: (betterAuthSchema: BetterAuthDBSchema, model: string, input: Record<string, any>) => boolean;
221
221
  declare const checkUniqueFields: <Schema$1 extends SchemaDefinition<any, any>>(ctx: GenericQueryCtx<GenericDataModel>, schema: Schema$1, betterAuthSchema: BetterAuthDBSchema, table: string, input: Record<string, any>, doc?: Record<string, any>) => Promise<void>;
222
222
  declare const selectFields: <T extends TableNamesInDataModel<GenericDataModel>, D extends DocumentByName<GenericDataModel, T>>(doc: D | null, select?: string[]) => Promise<D | null>;
@@ -244,7 +244,7 @@ declare const findOneHandler: (ctx: any, args: {
244
244
  model: string;
245
245
  select?: string[];
246
246
  where?: any[];
247
- }, schema: Schema, betterAuthSchema: any) => Promise<convex_server0.GenericDocument | null>;
247
+ }, schema: Schema, betterAuthSchema: any) => Promise<convex_server24.GenericDocument | null>;
248
248
  declare const findManyHandler: (ctx: any, args: {
249
249
  model: string;
250
250
  paginationOpts: any;
@@ -255,7 +255,7 @@ declare const findManyHandler: (ctx: any, args: {
255
255
  field: string;
256
256
  };
257
257
  where?: any[];
258
- }, schema: Schema, betterAuthSchema: any) => Promise<convex_server0.PaginationResult<convex_server0.GenericDocument>>;
258
+ }, schema: Schema, betterAuthSchema: any) => Promise<convex_server24.PaginationResult<convex_server24.GenericDocument>>;
259
259
  declare const updateOneHandler: (ctx: any, args: {
260
260
  input: {
261
261
  model: string;
@@ -278,8 +278,8 @@ declare const updateManyHandler: (ctx: any, args: {
278
278
  count: number;
279
279
  ids: any[];
280
280
  isDone: boolean;
281
- continueCursor: convex_server0.Cursor;
282
- splitCursor?: convex_server0.Cursor | null;
281
+ continueCursor: convex_server24.Cursor;
282
+ splitCursor?: convex_server24.Cursor | null;
283
283
  pageStatus?: "SplitRecommended" | "SplitRequired" | null;
284
284
  }>;
285
285
  declare const deleteOneHandler: (ctx: any, args: {
@@ -290,7 +290,7 @@ declare const deleteOneHandler: (ctx: any, args: {
290
290
  beforeDeleteHandle?: string;
291
291
  skipBeforeHooks?: boolean;
292
292
  onDeleteHandle?: string;
293
- }, schema: Schema, betterAuthSchema: any) => Promise<convex_server0.GenericDocument | undefined>;
293
+ }, schema: Schema, betterAuthSchema: any) => Promise<convex_server24.GenericDocument | undefined>;
294
294
  declare const deleteManyHandler: (ctx: any, args: {
295
295
  input: {
296
296
  model: string;
@@ -304,8 +304,8 @@ declare const deleteManyHandler: (ctx: any, args: {
304
304
  count: number;
305
305
  ids: any[];
306
306
  isDone: boolean;
307
- continueCursor: convex_server0.Cursor;
308
- splitCursor?: convex_server0.Cursor | null;
307
+ continueCursor: convex_server24.Cursor;
308
+ splitCursor?: convex_server24.Cursor | null;
309
309
  pageStatus?: "SplitRecommended" | "SplitRequired" | null;
310
310
  }>;
311
311
  declare const createApi: <Schema$1 extends SchemaDefinition<any, any>>(schema: Schema$1, createAuth: CreateAuth, options?: {
@@ -313,7 +313,7 @@ declare const createApi: <Schema$1 extends SchemaDefinition<any, any>>(schema: S
313
313
  /** Skip input validation for smaller generated types. Since these are internal functions, validation is optional. */
314
314
  skipValidation?: boolean;
315
315
  }) => {
316
- create: convex_server0.RegisteredMutation<"internal", {
316
+ create: convex_server24.RegisteredMutation<"internal", {
317
317
  select?: string[] | undefined;
318
318
  beforeCreateHandle?: string | undefined;
319
319
  onCreateHandle?: string | undefined;
@@ -329,7 +329,7 @@ declare const createApi: <Schema$1 extends SchemaDefinition<any, any>>(schema: S
329
329
  model: string;
330
330
  };
331
331
  }, Promise<any>>;
332
- deleteMany: convex_server0.RegisteredMutation<"internal", {
332
+ deleteMany: convex_server24.RegisteredMutation<"internal", {
333
333
  beforeDeleteHandle?: string | undefined;
334
334
  onDeleteHandle?: string | undefined;
335
335
  paginationOpts: {
@@ -356,11 +356,11 @@ declare const createApi: <Schema$1 extends SchemaDefinition<any, any>>(schema: S
356
356
  count: number;
357
357
  ids: any[];
358
358
  isDone: boolean;
359
- continueCursor: convex_server0.Cursor;
360
- splitCursor?: convex_server0.Cursor | null;
359
+ continueCursor: convex_server24.Cursor;
360
+ splitCursor?: convex_server24.Cursor | null;
361
361
  pageStatus?: "SplitRecommended" | "SplitRequired" | null;
362
362
  }>>;
363
- deleteOne: convex_server0.RegisteredMutation<"internal", {
363
+ deleteOne: convex_server24.RegisteredMutation<"internal", {
364
364
  beforeDeleteHandle?: string | undefined;
365
365
  onDeleteHandle?: string | undefined;
366
366
  input: {
@@ -375,21 +375,21 @@ declare const createApi: <Schema$1 extends SchemaDefinition<any, any>>(schema: S
375
375
  }[] | undefined;
376
376
  model: string;
377
377
  };
378
- }, Promise<convex_server0.GenericDocument | undefined>>;
379
- findMany: convex_server0.RegisteredQuery<"internal", {
380
- join?: any;
378
+ }, Promise<convex_server24.GenericDocument | undefined>>;
379
+ findMany: convex_server24.RegisteredQuery<"internal", {
381
380
  limit?: number | undefined;
382
- offset?: number | undefined;
383
- sortBy?: {
384
- field: string;
385
- direction: "asc" | "desc";
386
- } | undefined;
381
+ join?: any;
387
382
  where?: {
388
383
  operator?: "eq" | "ne" | "lt" | "lte" | "gt" | "gte" | "in" | "not_in" | "contains" | "starts_with" | "ends_with" | undefined;
389
384
  connector?: "AND" | "OR" | undefined;
390
385
  value: string | number | boolean | string[] | number[] | null;
391
386
  field: string;
392
387
  }[] | undefined;
388
+ offset?: number | undefined;
389
+ sortBy?: {
390
+ field: string;
391
+ direction: "asc" | "desc";
392
+ } | undefined;
393
393
  paginationOpts: {
394
394
  id?: number;
395
395
  endCursor?: string | null;
@@ -399,19 +399,19 @@ declare const createApi: <Schema$1 extends SchemaDefinition<any, any>>(schema: S
399
399
  cursor: string | null;
400
400
  };
401
401
  model: string;
402
- }, Promise<convex_server0.PaginationResult<convex_server0.GenericDocument>>>;
403
- findOne: convex_server0.RegisteredQuery<"internal", {
402
+ }, Promise<convex_server24.PaginationResult<convex_server24.GenericDocument>>>;
403
+ findOne: convex_server24.RegisteredQuery<"internal", {
404
404
  join?: any;
405
- select?: string[] | undefined;
406
405
  where?: {
407
406
  operator?: "eq" | "ne" | "lt" | "lte" | "gt" | "gte" | "in" | "not_in" | "contains" | "starts_with" | "ends_with" | undefined;
408
407
  connector?: "AND" | "OR" | undefined;
409
408
  value: string | number | boolean | string[] | number[] | null;
410
409
  field: string;
411
410
  }[] | undefined;
411
+ select?: string[] | undefined;
412
412
  model: string;
413
- }, Promise<convex_server0.GenericDocument | null>>;
414
- updateMany: convex_server0.RegisteredMutation<"internal", {
413
+ }, Promise<convex_server24.GenericDocument | null>>;
414
+ updateMany: convex_server24.RegisteredMutation<"internal", {
415
415
  beforeUpdateHandle?: string | undefined;
416
416
  onUpdateHandle?: string | undefined;
417
417
  paginationOpts: {
@@ -444,11 +444,11 @@ declare const createApi: <Schema$1 extends SchemaDefinition<any, any>>(schema: S
444
444
  count: number;
445
445
  ids: any[];
446
446
  isDone: boolean;
447
- continueCursor: convex_server0.Cursor;
448
- splitCursor?: convex_server0.Cursor | null;
447
+ continueCursor: convex_server24.Cursor;
448
+ splitCursor?: convex_server24.Cursor | null;
449
449
  pageStatus?: "SplitRecommended" | "SplitRequired" | null;
450
450
  }>>;
451
- updateOne: convex_server0.RegisteredMutation<"internal", {
451
+ updateOne: convex_server24.RegisteredMutation<"internal", {
452
452
  beforeUpdateHandle?: string | undefined;
453
453
  onUpdateHandle?: string | undefined;
454
454
  input: {
@@ -470,8 +470,8 @@ declare const createApi: <Schema$1 extends SchemaDefinition<any, any>>(schema: S
470
470
  model: string;
471
471
  };
472
472
  }, Promise<any>>;
473
- getLatestJwks: convex_server0.RegisteredAction<"internal", {}, Promise<any>>;
474
- rotateKeys: convex_server0.RegisteredAction<"internal", {}, Promise<any>>;
473
+ getLatestJwks: convex_server24.RegisteredAction<"internal", {}, Promise<any>>;
474
+ rotateKeys: convex_server24.RegisteredAction<"internal", {}, Promise<any>>;
475
475
  };
476
476
  //#endregion
477
477
  //#region src/auth/helpers.d.ts
@@ -25,6 +25,9 @@ type ConvexAuthProviderProps = {
25
25
  /**
26
26
  * Unified auth provider for Convex + Better Auth.
27
27
  * Handles token sync, HMR persistence, and auth callbacks.
28
+ *
29
+ * Structure: AuthProvider wraps ConvexAuthProviderInner so that
30
+ * useAuthStore() is available when creating fetchAccessToken.
28
31
  */
29
32
  declare function ConvexAuthProvider({
30
33
  children,
@@ -1,9 +1,9 @@
1
1
  'use client';
2
- import { _ as defaultIsUnauthorized, c as persistToken, f as useAuthStore, g as CRPCClientError, p as useAuthValue, s as getPersistedToken, t as AuthProvider } from "../auth-store-DANFmEdk.js";
2
+ import { _ as defaultIsUnauthorized, d as useAuthStore, f as useAuthValue, g as CRPCClientError, r as FetchAccessTokenContext, s as decodeJwtExp, t as AuthProvider } from "../auth-store-BMSJFMtR.js";
3
3
  import { c } from "react/compiler-runtime";
4
- import { ConvexProviderWithAuth } from "convex/react";
4
+ import { ConvexProviderWithAuth, useConvexAuth } from "convex/react";
5
5
  import { useCallback, useEffect, useMemo } from "react";
6
- import { jsx, jsxs } from "react/jsx-runtime";
6
+ import { jsx } from "react/jsx-runtime";
7
7
 
8
8
  //#region src/auth-client/convex-auth-provider.tsx
9
9
  /**
@@ -18,122 +18,171 @@ const defaultMutationHandler = () => {
18
18
  /**
19
19
  * Unified auth provider for Convex + Better Auth.
20
20
  * Handles token sync, HMR persistence, and auth callbacks.
21
+ *
22
+ * Structure: AuthProvider wraps ConvexAuthProviderInner so that
23
+ * useAuthStore() is available when creating fetchAccessToken.
21
24
  */
22
25
  function ConvexAuthProvider(t0) {
23
- const $ = c(17);
26
+ const $ = c(15);
24
27
  const { children, client, authClient, initialToken, onMutationUnauthorized, onQueryUnauthorized, isUnauthorized } = t0;
28
+ useOTTHandler(authClient);
25
29
  let t1;
26
30
  if ($[0] !== initialToken) {
27
- t1 = initialToken ?? getPersistedToken();
31
+ t1 = initialToken ? decodeJwtExp(initialToken) : null;
28
32
  $[0] = initialToken;
29
33
  $[1] = t1;
30
34
  } else t1 = $[1];
31
- const effectiveToken = t1;
32
- if (effectiveToken) persistToken(effectiveToken);
33
- const useAuth = useCreateConvexAuth(authClient);
34
- useOTTHandler(authClient);
35
- const t2 = client;
36
- const t3 = effectiveToken ?? null;
37
- let t4;
38
- if ($[2] !== t3) {
39
- t4 = {
40
- isLoading: true,
41
- token: t3
35
+ const t2 = initialToken ?? null;
36
+ let t3;
37
+ if ($[2] !== t1 || $[3] !== t2) {
38
+ t3 = {
39
+ expiresAt: t1,
40
+ token: t2
42
41
  };
43
- $[2] = t3;
44
- $[3] = t4;
45
- } else t4 = $[3];
46
- const t5 = isUnauthorized ?? defaultIsUnauthorized;
47
- const t6 = onMutationUnauthorized ?? defaultMutationHandler;
48
- const t7 = onQueryUnauthorized ?? _temp;
49
- let t8;
50
- if ($[4] !== authClient) {
51
- t8 = /* @__PURE__ */ jsx(AuthSyncEffect, { authClient });
52
- $[4] = authClient;
53
- $[5] = t8;
54
- } else t8 = $[5];
55
- let t9;
56
- if ($[6] !== children || $[7] !== t4 || $[8] !== t5 || $[9] !== t6 || $[10] !== t7 || $[11] !== t8) {
57
- t9 = /* @__PURE__ */ jsxs(AuthProvider, {
58
- initialValues: t4,
59
- isUnauthorized: t5,
60
- onMutationUnauthorized: t6,
61
- onQueryUnauthorized: t7,
62
- children: [t8, children]
42
+ $[2] = t1;
43
+ $[3] = t2;
44
+ $[4] = t3;
45
+ } else t3 = $[4];
46
+ const tokenValues = t3;
47
+ const t4 = isUnauthorized ?? defaultIsUnauthorized;
48
+ const t5 = onMutationUnauthorized ?? defaultMutationHandler;
49
+ const t6 = onQueryUnauthorized ?? _temp;
50
+ let t7;
51
+ if ($[5] !== authClient || $[6] !== children || $[7] !== client) {
52
+ t7 = /* @__PURE__ */ jsx(ConvexAuthProviderInner, {
53
+ authClient,
54
+ client,
55
+ children
63
56
  });
57
+ $[5] = authClient;
64
58
  $[6] = children;
65
- $[7] = t4;
66
- $[8] = t5;
67
- $[9] = t6;
68
- $[10] = t7;
69
- $[11] = t8;
70
- $[12] = t9;
71
- } else t9 = $[12];
72
- let t10;
73
- if ($[13] !== t2 || $[14] !== t9 || $[15] !== useAuth) {
74
- t10 = /* @__PURE__ */ jsx(ConvexProviderWithAuth, {
75
- client: t2,
76
- useAuth,
77
- children: t9
59
+ $[7] = client;
60
+ $[8] = t7;
61
+ } else t7 = $[8];
62
+ let t8;
63
+ if ($[9] !== t4 || $[10] !== t5 || $[11] !== t6 || $[12] !== t7 || $[13] !== tokenValues) {
64
+ t8 = /* @__PURE__ */ jsx(AuthProvider, {
65
+ initialValues: tokenValues,
66
+ isUnauthorized: t4,
67
+ onMutationUnauthorized: t5,
68
+ onQueryUnauthorized: t6,
69
+ children: t7
78
70
  });
79
- $[13] = t2;
80
- $[14] = t9;
81
- $[15] = useAuth;
82
- $[16] = t10;
83
- } else t10 = $[16];
84
- return t10;
71
+ $[9] = t4;
72
+ $[10] = t5;
73
+ $[11] = t6;
74
+ $[12] = t7;
75
+ $[13] = tokenValues;
76
+ $[14] = t8;
77
+ } else t8 = $[14];
78
+ return t8;
85
79
  }
86
80
  /**
87
- * Syncs Better Auth session to auth-store.
88
- * Automatically handles login/logout token updates.
81
+ * Inner provider that has access to AuthStore via useAuthStore().
82
+ * Creates fetchAccessToken and passes it through context (no race condition).
89
83
  */
90
84
  function _temp() {}
91
- function AuthSyncEffect({ authClient }) {
92
- const session = authClient.useSession();
85
+ function ConvexAuthProviderInner({ children, client, authClient }) {
93
86
  const authStore = useAuthStore();
94
- useEffect(() => {
95
- if (!session.isPending) {
96
- const token = session.data?.session.token ?? null;
97
- if (token !== authStore.get("token")) {
98
- authStore.set("token", token);
99
- persistToken(token);
87
+ const { data: session, isPending } = authClient.useSession();
88
+ const fetchAccessToken = useCallback(async ({ forceRefreshToken = false } = {}) => {
89
+ if (!session) {
90
+ if (!isPending) {
91
+ authStore.set("token", null);
92
+ authStore.set("expiresAt", null);
100
93
  }
94
+ return authStore.get("token");
95
+ }
96
+ const cachedToken = authStore.get("token");
97
+ const expiresAt = authStore.get("expiresAt");
98
+ const timeRemaining = expiresAt ? expiresAt - Date.now() : 0;
99
+ if (!forceRefreshToken && cachedToken && expiresAt && timeRemaining >= 6e4) return cachedToken;
100
+ try {
101
+ const { data } = await authClient.convex.token();
102
+ const jwt = data?.token || null;
103
+ if (jwt) {
104
+ const exp = decodeJwtExp(jwt);
105
+ authStore.set("token", jwt);
106
+ authStore.set("expiresAt", exp);
107
+ }
108
+ return jwt;
109
+ } catch {
110
+ return null;
101
111
  }
102
112
  }, [
103
- session.data,
104
- session.isPending,
105
- authStore
113
+ session,
114
+ isPending,
115
+ authStore,
116
+ authClient
106
117
  ]);
107
- return null;
108
- }
109
- /**
110
- * Creates useAuth hook for ConvexProviderWithAuth.
111
- * Uses auth-store token as single source of truth.
112
- */
113
- function useCreateConvexAuth(authClient) {
114
- return useMemo(() => function useConvexAuth$1() {
115
- const { data: session, isPending: isSessionPending } = authClient.useSession();
116
- const token = useAuthValue("token");
117
- const sessionId = session?.session?.id;
118
- const fetchAccessToken = useCallback(async ({ forceRefreshToken = false } = {}) => {
119
- if (token && !forceRefreshToken) return token;
120
- try {
121
- const { data } = await authClient.convex.token();
122
- return data?.token || null;
123
- } catch {
124
- return null;
125
- }
126
- }, [sessionId, token]);
118
+ const useAuth = useMemo(() => function useConvexAuthHook() {
127
119
  return useMemo(() => ({
128
- isLoading: isSessionPending,
120
+ isLoading: isPending,
129
121
  isAuthenticated: session !== null,
130
122
  fetchAccessToken
131
123
  }), [
132
- isSessionPending,
133
- sessionId,
124
+ isPending,
125
+ session,
134
126
  fetchAccessToken
135
127
  ]);
136
- }, [authClient]);
128
+ }, [
129
+ isPending,
130
+ session,
131
+ fetchAccessToken
132
+ ]);
133
+ return /* @__PURE__ */ jsx(FetchAccessTokenContext.Provider, {
134
+ value: fetchAccessToken,
135
+ children: /* @__PURE__ */ jsx(ConvexProviderWithAuth, {
136
+ client,
137
+ useAuth,
138
+ children: /* @__PURE__ */ jsx(AuthStateSync, { children })
139
+ })
140
+ });
141
+ }
142
+ /**
143
+ * Syncs auth state from useConvexAuth() to the auth store.
144
+ * MUST be inside ConvexProviderWithAuth to access useConvexAuth().
145
+ *
146
+ * Defensive isLoading computation handles SSR hydration race:
147
+ * 1. SSR sets token from cookie
148
+ * 2. Client hydrates
149
+ * 3. Better Auth's useSession() briefly returns null before loading cookie
150
+ * 4. Convex sets isConvexAuthenticated = false (no auth to wait for)
151
+ * 5. Without defensive check, we'd sync { isLoading: false, isAuthenticated: false }
152
+ * 6. Queries would throw UNAUTHORIZED before token is validated
153
+ */
154
+ function AuthStateSync(t0) {
155
+ const $ = c(6);
156
+ const { children } = t0;
157
+ const { isLoading: convexIsLoading, isAuthenticated } = useConvexAuth();
158
+ const authStore = useAuthStore();
159
+ const token = useAuthValue("token");
160
+ let t1;
161
+ let t2;
162
+ if ($[0] !== authStore || $[1] !== convexIsLoading || $[2] !== isAuthenticated || $[3] !== token) {
163
+ t1 = () => {
164
+ const isLoading = convexIsLoading || !!token && !isAuthenticated;
165
+ authStore.set("isLoading", isLoading);
166
+ authStore.set("isAuthenticated", isAuthenticated);
167
+ };
168
+ t2 = [
169
+ convexIsLoading,
170
+ isAuthenticated,
171
+ token,
172
+ authStore
173
+ ];
174
+ $[0] = authStore;
175
+ $[1] = convexIsLoading;
176
+ $[2] = isAuthenticated;
177
+ $[3] = token;
178
+ $[4] = t1;
179
+ $[5] = t2;
180
+ } else {
181
+ t1 = $[4];
182
+ t2 = $[5];
183
+ }
184
+ useEffect(t1, t2);
185
+ return children;
137
186
  }
138
187
  /**
139
188
  * Handles cross-domain one-time token (OTT) verification.
@@ -1,3 +1,4 @@
1
+ import "../http-types-BwEQgYV1.js";
1
2
  import { CallerMeta, ConvexContext, LazyCaller } from "../server/index.js";
2
3
  import { GetTokenOptions } from "@convex-dev/better-auth/utils";
3
4