@supalive/core 1.8.0 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/README.md +1 -2
  2. package/dist/index-CDG1kbFO.d.ts +2211 -0
  3. package/dist/index-CDG1kbFO.d.ts.map +1 -0
  4. package/dist/index-CkYZi3ai.d.ts +2186 -0
  5. package/dist/index-CkYZi3ai.d.ts.map +1 -0
  6. package/dist/index-DKlWIC3k.d.ts +2200 -0
  7. package/dist/index-DKlWIC3k.d.ts.map +1 -0
  8. package/dist/index-Dy9UlONo.d.ts +2192 -0
  9. package/dist/index-Dy9UlONo.d.ts.map +1 -0
  10. package/dist/index-tDcHLwJu.d.ts +2186 -0
  11. package/dist/index-tDcHLwJu.d.ts.map +1 -0
  12. package/dist/mysql-BBNCFz8q.d.ts +109 -0
  13. package/dist/mysql-BBNCFz8q.d.ts.map +1 -0
  14. package/dist/mysql-BVz7201u.d.ts +109 -0
  15. package/dist/mysql-BVz7201u.d.ts.map +1 -0
  16. package/dist/mysql-CBlZ6FVc.d.ts +109 -0
  17. package/dist/mysql-CBlZ6FVc.d.ts.map +1 -0
  18. package/dist/mysql-CfYZLs5V.d.ts +109 -0
  19. package/dist/mysql-CfYZLs5V.d.ts.map +1 -0
  20. package/dist/mysql-DjjyCiO4.d.ts +109 -0
  21. package/dist/mysql-DjjyCiO4.d.ts.map +1 -0
  22. package/dist/postgres-CUHirAJN.d.ts +113 -0
  23. package/dist/postgres-CUHirAJN.d.ts.map +1 -0
  24. package/dist/postgres-Cj9zuZ8p.d.ts +113 -0
  25. package/dist/postgres-Cj9zuZ8p.d.ts.map +1 -0
  26. package/dist/postgres-DGK6Y1aL.d.ts +113 -0
  27. package/dist/postgres-DGK6Y1aL.d.ts.map +1 -0
  28. package/dist/postgres-hlrVkOXa.d.ts +113 -0
  29. package/dist/postgres-hlrVkOXa.d.ts.map +1 -0
  30. package/dist/postgres-ziXP2hco.d.ts +113 -0
  31. package/dist/postgres-ziXP2hco.d.ts.map +1 -0
  32. package/dist/procedure-B4qKrlBL.js +158 -0
  33. package/dist/procedure-B4qKrlBL.js.map +1 -0
  34. package/dist/procedure-BDcrK98I.js +173 -0
  35. package/dist/procedure-BDcrK98I.js.map +1 -0
  36. package/dist/procedure-BxGOWNWg.js.map +1 -0
  37. package/dist/procedure-CRkrxHvn.js +187 -0
  38. package/dist/procedure-CRkrxHvn.js.map +1 -0
  39. package/dist/procedure-Ck4v3__H.js +212 -0
  40. package/dist/procedure-Ck4v3__H.js.map +1 -0
  41. package/dist/procedure-DPgXC2Cm.js +221 -0
  42. package/dist/procedure-DPgXC2Cm.js.map +1 -0
  43. package/dist/procedure-xUVIUm5W.js +213 -0
  44. package/dist/procedure-xUVIUm5W.js.map +1 -0
  45. package/dist/src/client/index.d.ts +1 -1
  46. package/dist/src/client/index.js +1 -1
  47. package/dist/src/exports/mysql.d.ts +1 -1
  48. package/dist/src/exports/postgres.d.ts +1 -1
  49. package/dist/src/exports/procedure.d.ts +17 -2
  50. package/dist/src/exports/procedure.d.ts.map +1 -0
  51. package/dist/src/exports/procedure.js +8 -2
  52. package/dist/src/exports/procedure.js.map +1 -0
  53. package/dist/src/exports/schema-sql.d.ts +1 -1
  54. package/dist/src/exports/server.d.ts +4 -4
  55. package/dist/src/exports/types.d.ts +2 -2
  56. package/dist/types_server-BI7uQd6x.d.ts +328 -0
  57. package/dist/types_server-BI7uQd6x.d.ts.map +1 -0
  58. package/dist/types_server-BcT4A8OM.d.ts +328 -0
  59. package/dist/types_server-BcT4A8OM.d.ts.map +1 -0
  60. package/dist/types_server-CO3IYNS9.d.ts +328 -0
  61. package/dist/types_server-CO3IYNS9.d.ts.map +1 -0
  62. package/dist/types_server-Clf74qZP.d.ts +328 -0
  63. package/dist/types_server-Clf74qZP.d.ts.map +1 -0
  64. package/dist/types_server-DEAwXI4p.d.ts +328 -0
  65. package/dist/types_server-DEAwXI4p.d.ts.map +1 -0
  66. package/dist/zod_ext-B5cyjWqZ.d.ts +11 -0
  67. package/dist/zod_ext-B5cyjWqZ.d.ts.map +1 -0
  68. package/dist/zod_ext-CZlJ4wtJ.d.ts +11 -0
  69. package/dist/zod_ext-CZlJ4wtJ.d.ts.map +1 -0
  70. package/package.json +6 -5
@@ -0,0 +1,2200 @@
1
+ import { r as ObjectStorage } from "./object-storage-354KU6Mj.js";
2
+ import z, { ZodRawShape, ZodType, z as z$1 } from "zod";
3
+ import { RetryPolicy } from "cockatiel";
4
+ import Redis$1 from "ioredis";
5
+ import { Redis as Redis$2 } from "@upstash/redis";
6
+
7
+ //#region src/db/types_db.d.ts
8
+ /** Monotonically increasing integer from global_commit_ts sequence in Postgres */
9
+ type CommitTs = bigint;
10
+ declare const BigIntSchema: z.ZodPipe<z.ZodString, z.ZodTransform<bigint, string>>;
11
+ declare const CompareOperatorSchema: z.ZodEnum<{
12
+ "=": "=";
13
+ "!=": "!=";
14
+ ">": ">";
15
+ ">=": ">=";
16
+ "<": "<";
17
+ "<=": "<=";
18
+ like: "like";
19
+ ilike: "ilike";
20
+ contains: "contains";
21
+ icontains: "icontains";
22
+ between: "between";
23
+ in: "in";
24
+ jsonContains: "jsonContains";
25
+ jsonContainedBy: "jsonContainedBy";
26
+ jsonHasKey: "jsonHasKey";
27
+ jsonArrayContains: "jsonArrayContains";
28
+ isNull: "isNull";
29
+ isNotNull: "isNotNull";
30
+ }>;
31
+ type CompareOperator = z.infer<typeof CompareOperatorSchema>;
32
+ type Predicate = LeafPredicate | {
33
+ kind: "and";
34
+ children: Predicate[];
35
+ } | {
36
+ kind: "or";
37
+ children: Predicate[];
38
+ };
39
+ declare const PredicateSchema: z.ZodType<Predicate>;
40
+ declare const LeafPredicateSchema: z.ZodObject<{
41
+ kind: z.ZodLiteral<"leaf">;
42
+ column: z.ZodString;
43
+ operator: z.ZodEnum<{
44
+ "=": "=";
45
+ "!=": "!=";
46
+ ">": ">";
47
+ ">=": ">=";
48
+ "<": "<";
49
+ "<=": "<=";
50
+ like: "like";
51
+ ilike: "ilike";
52
+ contains: "contains";
53
+ icontains: "icontains";
54
+ between: "between";
55
+ in: "in";
56
+ jsonContains: "jsonContains";
57
+ jsonContainedBy: "jsonContainedBy";
58
+ jsonHasKey: "jsonHasKey";
59
+ jsonArrayContains: "jsonArrayContains";
60
+ isNull: "isNull";
61
+ isNotNull: "isNotNull";
62
+ }>;
63
+ value: z.ZodUnknown;
64
+ value2: z.ZodOptional<z.ZodUnknown>;
65
+ raw: z.ZodOptional<z.ZodBoolean>;
66
+ path: z.ZodOptional<z.ZodString>;
67
+ mode: z.ZodOptional<z.ZodEnum<{
68
+ one: "one";
69
+ all: "all";
70
+ }>>;
71
+ }, z.core.$strip>;
72
+ type LeafPredicate = z.infer<typeof LeafPredicateSchema>;
73
+ declare const AndPredicateSchema: z.ZodObject<{
74
+ kind: z.ZodLiteral<"and">;
75
+ children: z.ZodArray<z.ZodType<Predicate, unknown, z.core.$ZodTypeInternals<Predicate, unknown>>>;
76
+ }, z.core.$strip>;
77
+ type AndPredicate = z.infer<typeof AndPredicateSchema>;
78
+ declare const OrPredicateSchema: z.ZodObject<{
79
+ kind: z.ZodLiteral<"or">;
80
+ children: z.ZodArray<z.ZodType<Predicate, unknown, z.core.$ZodTypeInternals<Predicate, unknown>>>;
81
+ }, z.core.$strip>;
82
+ type OrPredicate = z.infer<typeof OrPredicateSchema>;
83
+ /** Query specification - what was queried (used for cache key generation) */
84
+ type QuerySpec = ReadEntry;
85
+ declare function normalizeIdToBytes(id: string | number, fromHex?: boolean): Uint8Array;
86
+ declare function normalizeToBytes(value: Uint8Array | unknown): Uint8Array;
87
+ declare function bytesFromJson(value: Uint8Array | unknown): Uint8Array;
88
+ declare const PointReadSchema: z.ZodObject<{
89
+ kind: z.ZodLiteral<"point">;
90
+ table: z.ZodString;
91
+ id: z.ZodString;
92
+ tableId: z.ZodPipe<z.ZodAny, z.ZodTransform<Uint8Array<ArrayBufferLike>, any>>;
93
+ expectedCommitTs: z.ZodOptional<z.ZodNullable<z.ZodPipe<z.ZodString, z.ZodTransform<bigint, string>>>>;
94
+ }, z.core.$strip>;
95
+ type PointRead = z.infer<typeof PointReadSchema>;
96
+ declare const RawPointReadSchema: z.ZodObject<{
97
+ kind: z.ZodLiteral<"point">;
98
+ tableId: z.ZodPipe<z.ZodAny, z.ZodTransform<Uint8Array<ArrayBufferLike>, any>>;
99
+ id: z.ZodPipe<z.ZodAny, z.ZodTransform<Uint8Array<ArrayBufferLike>, any>>;
100
+ table: z.ZodString;
101
+ expectedCommitTs: z.ZodOptional<z.ZodNullable<z.ZodPipe<z.ZodString, z.ZodTransform<bigint, string>>>>;
102
+ }, z.core.$strip>;
103
+ type RawPointRead = z.infer<typeof RawPointReadSchema>;
104
+ /**
105
+ * Query specification for a range read (get with filters).
106
+ * This is the query definition, not the result.
107
+ */
108
+ declare const RangeReadSchema: z.ZodObject<{
109
+ kind: z.ZodLiteral<"range">;
110
+ table: z.ZodString;
111
+ tableId: z.ZodPipe<z.ZodAny, z.ZodTransform<Uint8Array<ArrayBufferLike>, any>>;
112
+ predicate: z.ZodType<Predicate, unknown, z.core.$ZodTypeInternals<Predicate, unknown>>;
113
+ columns: z.ZodArray<z.ZodString>;
114
+ orderBy: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodString>>>;
115
+ limit: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
116
+ offset: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
117
+ }, z.core.$strip>;
118
+ type RangeRead = z.infer<typeof RangeReadSchema>;
119
+ declare const RawRangeReadSchema: z.ZodObject<{
120
+ kind: z.ZodLiteral<"range">;
121
+ table: z.ZodString;
122
+ tableId: z.ZodPipe<z.ZodAny, z.ZodTransform<Uint8Array<ArrayBufferLike>, any>>;
123
+ predicate: z.ZodType<Predicate, unknown, z.core.$ZodTypeInternals<Predicate, unknown>>;
124
+ columns: z.ZodArray<z.ZodString>;
125
+ orderBy: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodString>>>;
126
+ limit: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
127
+ offset: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
128
+ }, z.core.$strip>;
129
+ type RawRangeRead = z.infer<typeof RawRangeReadSchema>;
130
+ declare const ReadEntrySchema: z.ZodUnion<readonly [z.ZodObject<{
131
+ kind: z.ZodLiteral<"point">;
132
+ table: z.ZodString;
133
+ id: z.ZodString;
134
+ tableId: z.ZodPipe<z.ZodAny, z.ZodTransform<Uint8Array<ArrayBufferLike>, any>>;
135
+ expectedCommitTs: z.ZodOptional<z.ZodNullable<z.ZodPipe<z.ZodString, z.ZodTransform<bigint, string>>>>;
136
+ }, z.core.$strip>, z.ZodObject<{
137
+ kind: z.ZodLiteral<"range">;
138
+ table: z.ZodString;
139
+ tableId: z.ZodPipe<z.ZodAny, z.ZodTransform<Uint8Array<ArrayBufferLike>, any>>;
140
+ predicate: z.ZodType<Predicate, unknown, z.core.$ZodTypeInternals<Predicate, unknown>>;
141
+ columns: z.ZodArray<z.ZodString>;
142
+ orderBy: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodString>>>;
143
+ limit: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
144
+ offset: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
145
+ }, z.core.$strip>]>;
146
+ type ReadEntry = z.infer<typeof ReadEntrySchema>;
147
+ declare const RawReadEntrySchema: z.ZodUnion<readonly [z.ZodObject<{
148
+ kind: z.ZodLiteral<"point">;
149
+ tableId: z.ZodPipe<z.ZodAny, z.ZodTransform<Uint8Array<ArrayBufferLike>, any>>;
150
+ id: z.ZodPipe<z.ZodAny, z.ZodTransform<Uint8Array<ArrayBufferLike>, any>>;
151
+ table: z.ZodString;
152
+ expectedCommitTs: z.ZodOptional<z.ZodNullable<z.ZodPipe<z.ZodString, z.ZodTransform<bigint, string>>>>;
153
+ }, z.core.$strip>, z.ZodObject<{
154
+ kind: z.ZodLiteral<"range">;
155
+ table: z.ZodString;
156
+ tableId: z.ZodPipe<z.ZodAny, z.ZodTransform<Uint8Array<ArrayBufferLike>, any>>;
157
+ predicate: z.ZodType<Predicate, unknown, z.core.$ZodTypeInternals<Predicate, unknown>>;
158
+ columns: z.ZodArray<z.ZodString>;
159
+ orderBy: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodString>>>;
160
+ limit: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
161
+ offset: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
162
+ }, z.core.$strip>]>;
163
+ type RawReadEntry = z.infer<typeof RawReadEntrySchema>;
164
+ declare const WriteOpSchema: z.ZodEnum<{
165
+ insert: "insert";
166
+ update: "update";
167
+ delete: "delete";
168
+ }>;
169
+ type WriteOp = z.infer<typeof WriteOpSchema>;
170
+ declare const WriteEntrySchema: z.ZodObject<{
171
+ table: z.ZodString;
172
+ tableId: z.ZodPipe<z.ZodAny, z.ZodTransform<Uint8Array<ArrayBufferLike>, any>>;
173
+ id: z.ZodString;
174
+ op: z.ZodEnum<{
175
+ insert: "insert";
176
+ update: "update";
177
+ delete: "delete";
178
+ }>;
179
+ data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
180
+ prevData: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
181
+ expectedCommitTs: z.ZodOptional<z.ZodNullable<z.ZodPipe<z.ZodString, z.ZodTransform<bigint, string>>>>;
182
+ }, z.core.$strip>;
183
+ type WriteEntry = z.infer<typeof WriteEntrySchema>;
184
+ interface CommitLogEntry {
185
+ id: Uint8Array;
186
+ ts: bigint;
187
+ tableId: Uint8Array;
188
+ data: Uint8Array;
189
+ _parsedData?: Record<string, unknown> | null;
190
+ }
191
+ interface MutationResult<T> {
192
+ result: T;
193
+ writeSet: WriteEntry[];
194
+ commitTs: CommitTs;
195
+ }
196
+ interface LiveResult<T> {
197
+ ts: bigint;
198
+ data: T;
199
+ readSet: ReadEntry[];
200
+ }
201
+ declare const QueryCacheMetadataSchema: z.ZodObject<{
202
+ lastSnapshotTs: z.ZodPipe<z.ZodString, z.ZodTransform<bigint, string>>;
203
+ version: z.ZodString;
204
+ readSet: z.ZodArray<z.ZodUnion<readonly [z.ZodObject<{
205
+ kind: z.ZodLiteral<"point">;
206
+ table: z.ZodString;
207
+ id: z.ZodString;
208
+ tableId: z.ZodPipe<z.ZodAny, z.ZodTransform<Uint8Array<ArrayBufferLike>, any>>;
209
+ expectedCommitTs: z.ZodOptional<z.ZodNullable<z.ZodPipe<z.ZodString, z.ZodTransform<bigint, string>>>>;
210
+ }, z.core.$strip>, z.ZodObject<{
211
+ kind: z.ZodLiteral<"range">;
212
+ table: z.ZodString;
213
+ tableId: z.ZodPipe<z.ZodAny, z.ZodTransform<Uint8Array<ArrayBufferLike>, any>>;
214
+ predicate: z.ZodType<Predicate, unknown, z.core.$ZodTypeInternals<Predicate, unknown>>;
215
+ columns: z.ZodArray<z.ZodString>;
216
+ orderBy: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodString>>>;
217
+ limit: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
218
+ offset: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
219
+ }, z.core.$strip>]>>;
220
+ }, z.core.$strip>;
221
+ type QueryCacheMetadata = z.infer<typeof QueryCacheMetadataSchema>;
222
+ declare const QueryCacheEntrySchema: z.ZodObject<{
223
+ data: z.ZodUnknown;
224
+ version: z.ZodString;
225
+ }, z.core.$strip>;
226
+ type QueryCacheEntry = z.infer<typeof QueryCacheEntrySchema>;
227
+ declare const CachedPgMetadataSchema: z.ZodRecord<z.ZodString, z.ZodRecord<z.ZodString, z.ZodString>>;
228
+ type CachedPgMetadata = z.infer<typeof CachedPgMetadataSchema>;
229
+ interface RetryConfig {
230
+ maxAttempts: number;
231
+ backoff: "none" | "linear" | "exponential";
232
+ delayMs?: number;
233
+ onConflict?: (attempt: number, error: OccConflictError) => void;
234
+ }
235
+ declare const NO_RETRY: RetryConfig;
236
+ declare const DEFAULT_RETRY: RetryConfig;
237
+ declare class OccConflictError extends Error {
238
+ readonly reason: string;
239
+ readonly conflictDetail?: unknown | undefined;
240
+ constructor(reason: string, conflictDetail?: unknown | undefined);
241
+ static isOccConflictError(err: unknown): boolean;
242
+ }
243
+ declare class OccAbortError extends Error {
244
+ constructor(message: string);
245
+ }
246
+ //#endregion
247
+ //#region src/server/subscription-manager-types.d.ts
248
+ declare const RegisterSubscriptionParamsSchema: z.ZodObject<{
249
+ subId: z.ZodString;
250
+ cacheKey: z.ZodString;
251
+ queryName: z.ZodString;
252
+ args: z.ZodUnknown;
253
+ queryIdentity: z.ZodString;
254
+ instanceName: z.ZodString;
255
+ lastSnapshotTs: z.ZodPipe<z.ZodString, z.ZodTransform<bigint, string>>;
256
+ }, z.core.$strip>;
257
+ type RegisterSubscriptionParams = z.infer<typeof RegisterSubscriptionParamsSchema>;
258
+ declare const RegisterSubscriptionResultSchema: z.ZodObject<{
259
+ cacheKey: z.ZodString;
260
+ recompute: z.ZodBoolean;
261
+ readSet: z.ZodArray<z.ZodUnion<readonly [z.ZodObject<{
262
+ kind: z.ZodLiteral<"point">;
263
+ table: z.ZodString;
264
+ id: z.ZodString;
265
+ tableId: z.ZodPipe<z.ZodAny, z.ZodTransform<Uint8Array<ArrayBufferLike>, any>>;
266
+ expectedCommitTs: z.ZodOptional<z.ZodNullable<z.ZodPipe<z.ZodString, z.ZodTransform<bigint, string>>>>;
267
+ }, z.core.$strip>, z.ZodObject<{
268
+ kind: z.ZodLiteral<"range">;
269
+ table: z.ZodString;
270
+ tableId: z.ZodPipe<z.ZodAny, z.ZodTransform<Uint8Array<ArrayBufferLike>, any>>;
271
+ predicate: z.ZodType<Predicate, unknown, z.core.$ZodTypeInternals<Predicate, unknown>>;
272
+ columns: z.ZodArray<z.ZodString>;
273
+ orderBy: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodString>>>;
274
+ limit: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
275
+ offset: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
276
+ }, z.core.$strip>]>>;
277
+ version: z.ZodOptional<z.ZodString>;
278
+ }, z.core.$strip>;
279
+ type RegisterSubscriptionResult = z.infer<typeof RegisterSubscriptionResultSchema>;
280
+ declare const UpdateSubscriptionReadSetParamsSchema: z.ZodObject<{
281
+ cacheKey: z.ZodString;
282
+ subId: z.ZodString;
283
+ instanceName: z.ZodString;
284
+ lastSnapshotTs: z.ZodPipe<z.ZodString, z.ZodTransform<bigint, string>>;
285
+ readSet: z.ZodArray<z.ZodUnion<readonly [z.ZodObject<{
286
+ kind: z.ZodLiteral<"point">;
287
+ table: z.ZodString;
288
+ id: z.ZodString;
289
+ tableId: z.ZodPipe<z.ZodAny, z.ZodTransform<Uint8Array<ArrayBufferLike>, any>>;
290
+ expectedCommitTs: z.ZodOptional<z.ZodNullable<z.ZodPipe<z.ZodString, z.ZodTransform<bigint, string>>>>;
291
+ }, z.core.$strip>, z.ZodObject<{
292
+ kind: z.ZodLiteral<"range">;
293
+ table: z.ZodString;
294
+ tableId: z.ZodPipe<z.ZodAny, z.ZodTransform<Uint8Array<ArrayBufferLike>, any>>;
295
+ predicate: z.ZodType<Predicate, unknown, z.core.$ZodTypeInternals<Predicate, unknown>>;
296
+ columns: z.ZodArray<z.ZodString>;
297
+ orderBy: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodString>>>;
298
+ limit: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
299
+ offset: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
300
+ }, z.core.$strip>]>>;
301
+ }, z.core.$strip>;
302
+ type UpdateSubscriptionReadSetParams = z.infer<typeof UpdateSubscriptionReadSetParamsSchema>;
303
+ /**
304
+ * `tracked: false` means the sub-manager has no record of this subId (e.g.
305
+ * a restart wiped state and the caller hasn't re-registered yet). The app
306
+ * server should treat this as a signal to register the sub before retrying.
307
+ */
308
+ declare const UpdateSubscriptionReadSetResultSchema: z.ZodObject<{
309
+ tracked: z.ZodBoolean;
310
+ }, z.core.$strip>;
311
+ type UpdateSubscriptionReadSetResult = z.infer<typeof UpdateSubscriptionReadSetResultSchema>;
312
+ declare const UnregisterSubscriptionParamsSchema: z.ZodObject<{
313
+ subId: z.ZodString;
314
+ instanceName: z.ZodString;
315
+ }, z.core.$strip>;
316
+ type UnregisterSubscriptionParams = z.infer<typeof UnregisterSubscriptionParamsSchema>;
317
+ declare const UnregisterSubscriptionsParamsSchema: z.ZodArray<z.ZodObject<{
318
+ subId: z.ZodString;
319
+ instanceName: z.ZodString;
320
+ }, z.core.$strip>>;
321
+ type UnregisterSubscriptionsParams = z.infer<typeof UnregisterSubscriptionsParamsSchema>;
322
+ declare const UnregisterSubscriptionResultSchema: z.ZodObject<{
323
+ ok: z.ZodBoolean;
324
+ }, z.core.$strip>;
325
+ type UnregisterSubscriptionResult = z.infer<typeof UnregisterSubscriptionResultSchema>;
326
+ declare const UnregisterSubscriptionsResultSchema: z.ZodArray<z.ZodObject<{
327
+ ok: z.ZodBoolean;
328
+ }, z.core.$strip>>;
329
+ type UnregisterSubscriptionsResult = z.infer<typeof UnregisterSubscriptionsResultSchema>;
330
+ declare const InvalidateWritesetParamsSchema: z.ZodObject<{
331
+ writeSet: z.ZodArray<z.ZodObject<{
332
+ table: z.ZodString;
333
+ tableId: z.ZodPipe<z.ZodAny, z.ZodTransform<Uint8Array<ArrayBufferLike>, any>>;
334
+ id: z.ZodString;
335
+ op: z.ZodEnum<{
336
+ insert: "insert";
337
+ update: "update";
338
+ delete: "delete";
339
+ }>;
340
+ data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
341
+ prevData: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
342
+ expectedCommitTs: z.ZodOptional<z.ZodNullable<z.ZodPipe<z.ZodString, z.ZodTransform<bigint, string>>>>;
343
+ }, z.core.$strip>>;
344
+ }, z.core.$strip>;
345
+ type InvalidateWritesetParams = z.infer<typeof InvalidateWritesetParamsSchema>;
346
+ declare const AffectedSubscriptionSchema: z.ZodObject<{
347
+ subId: z.ZodString;
348
+ queryName: z.ZodString;
349
+ args: z.ZodUnknown;
350
+ cacheKey: z.ZodString;
351
+ notifyInstances: z.ZodArray<z.ZodString>;
352
+ }, z.core.$strip>;
353
+ type AffectedSubscription = z.infer<typeof AffectedSubscriptionSchema>;
354
+ declare const InvalidateWritesetResultSchema: z.ZodObject<{
355
+ affected: z.ZodArray<z.ZodObject<{
356
+ subId: z.ZodString;
357
+ queryName: z.ZodString;
358
+ args: z.ZodUnknown;
359
+ cacheKey: z.ZodString;
360
+ notifyInstances: z.ZodArray<z.ZodString>;
361
+ }, z.core.$strip>>;
362
+ }, z.core.$strip>;
363
+ type InvalidateWritesetResult = z.infer<typeof InvalidateWritesetResultSchema>;
364
+ declare const RegistrationRecordSchema: z.ZodObject<{
365
+ queryName: z.ZodString;
366
+ args: z.ZodUnknown;
367
+ queryIdentity: z.ZodString;
368
+ cacheKey: z.ZodString;
369
+ }, z.core.$strip>;
370
+ type RegistrationRecord = z.infer<typeof RegistrationRecordSchema>;
371
+ //#endregion
372
+ //#region src/db/cache.d.ts
373
+ declare class CacheLayer {
374
+ redis: Redis$1 | Redis$2;
375
+ private readonly ttlSeconds;
376
+ /** Cached EVALSHA digests keyed by Lua source (see evalScript). */
377
+ private readonly scriptShaCache;
378
+ constructor(upstash: Redis$1 | Redis$2, ttlSeconds?: number);
379
+ /**
380
+ * Run a Lua script via EVALSHA using the script's SHA1 (computed locally — the
381
+ * same digest Redis keys scripts by, so no SCRIPT LOAD round-trip is needed on
382
+ * the hot path). On NOSCRIPT (the script isn't in Redis's cache yet, e.g. first
383
+ * use or after a Redis restart/failover) load it explicitly via SCRIPT LOAD and
384
+ * re-run via EVALSHA — so the script ends up cached server-side and subsequent
385
+ * EVALSHA calls hit. The runtime client is always ioredis (see initCacheLayer).
386
+ */
387
+ private evalScript;
388
+ /** One-shot recompute: atomically write data + metadata (CAS on version). */
389
+ setQueryCacheAndMetadataFor(cacheKey: string, data: unknown, metaData: QueryCacheMetadata, ttlSeconds?: number): Promise<void>;
390
+ /** Subscribe path: write the data blob only (CAS against the metadata's
391
+ * version). The metadata is written separately by the sub-worker; the
392
+ * `version` links the two so a divergent pair is detected on read. */
393
+ setQueryCacheFor(cacheKey: string, data: unknown, version: string, ttlSeconds?: number): Promise<void>;
394
+ getQueryCacheFor(cacheKey: string): Promise<QueryCacheEntry | null>;
395
+ /** Subscription recompute: replace the whole metadata (CAS on version). */
396
+ replaceQueryCacheMetadata(cacheKey: string, metaData: QueryCacheMetadata, ttlSeconds?: number): Promise<void>;
397
+ /** Still-fresh subscription: advance `lastSnapshotTs` only, preserving the
398
+ * data's `version` + `readSet` (no recompute). Monotonic and non-clobbering
399
+ * — see ADVANCE_META. `metaData` carries the new horizon plus the version +
400
+ * readSet the caller read, which the script keeps unless a newer computation
401
+ * has since landed. */
402
+ advanceQueryCacheMetadata(cacheKey: string, metaData: QueryCacheMetadata, ttlSeconds?: number): Promise<void>;
403
+ getQueryCacheMetaData(cacheKey: string): Promise<QueryCacheMetadata | null>;
404
+ persistRegistrationRecord(subId: string, record: RegistrationRecord): Promise<void>;
405
+ deleteRegistrationRecord(subId: string): Promise<void>;
406
+ deleteRegistrationsRecord(subIds: string[]): Promise<void>;
407
+ fetchRegistrationRecordsBatch(subIds: string[]): Promise<Map<string, RegistrationRecord | null>>;
408
+ getCachedTableColumnTypes(key: string): Promise<CachedPgMetadata | null>;
409
+ setCachedTableColumnsTypes(key: string, value: CachedPgMetadata): Promise<void>;
410
+ /**
411
+ * Race participant: try to claim `lock:recompute:<subId>:<commitTs>`
412
+ * with `SET NX EX`. The single Redis round-trip both arbitrates and
413
+ * sets a TTL fallback in case the winner crashes mid-recompute.
414
+ */
415
+ tryAcquireRecomputeLock(instanceId: string, subId: string, commitTs: string, ttl: number): Promise<boolean>;
416
+ private getRegistrationKey;
417
+ private getQueryCacheDataKey;
418
+ private getQeruyCacheMetaKey;
419
+ }
420
+ //#endregion
421
+ //#region src/db/db.d.ts
422
+ interface DbQueryResult<T = any> {
423
+ rows: T[];
424
+ rowCount?: number | null;
425
+ }
426
+ interface RawClient {
427
+ query<T = any>(sql: string, params?: unknown[]): Promise<DbQueryResult<T>>;
428
+ }
429
+ interface PooledClient extends RawClient {
430
+ release(): void;
431
+ }
432
+ type DbType = "postgres" | "mysql";
433
+ interface PendingPointEntry {
434
+ entry: PointRead;
435
+ key: string;
436
+ }
437
+ interface PreparedQuery {
438
+ sql: string;
439
+ params: unknown[] | unknown[][];
440
+ operation: "insertSingle" | "insertBatch" | "updateSingle" | "updateBatch" | "deleteSingle" | "deleteBatch" | "pointReadValidation" | "commit_logs";
441
+ table: string;
442
+ entryId?: unknown;
443
+ expectedTs?: bigint;
444
+ entries?: WriteEntry[];
445
+ pendingsEntry?: PendingPointEntry[];
446
+ }
447
+ interface PreparedQueries {
448
+ commits: PreparedQuery[];
449
+ validateReadPoints?: PreparedQuery[];
450
+ hasRangeRead: boolean;
451
+ tableIds?: Uint8Array[];
452
+ rawReadSet?: RawReadEntry[];
453
+ }
454
+ /**
455
+ * Bound to a single dedicated connection that holds the core-init lock. Passed
456
+ * to the callback of {@link Database.withCoreInitLock} so version reads/writes
457
+ * and migration statements all run under the same lock.
458
+ */
459
+ interface CoreInitLockCtx {
460
+ exec(sql: string, params?: unknown[]): Promise<DbQueryResult>;
461
+ getVersion(): Promise<bigint>;
462
+ setVersion(version: bigint): Promise<void>;
463
+ }
464
+ interface Database {
465
+ readonly dbType: DbType;
466
+ readonly sqlBuilder: SqlBuilder;
467
+ columnTypes: Map<string, Map<string, string>>;
468
+ /**
469
+ * Current core schema version stored in `metadata.core_version`, or `0n`
470
+ * when unset. Read on a pooled connection for the lock-free fast path of
471
+ * {@link initCore}.
472
+ */
473
+ getCoreVersion(): Promise<bigint>;
474
+ /**
475
+ * Runtime bootstrap statements to apply when migrating core TO `toVersion`
476
+ * (i.e. the `toVersion - 1` → `toVersion` step): data seeds, backfills, or a
477
+ * schema change that must be applied directly at runtime. Dialect-specific;
478
+ * the core schema (tables, indexes, the `global_commit_ts` sequence/counter)
479
+ * lives in the generated schema instead — see `coreTablesSql`.
480
+ */
481
+ coreMigrationStatements(toVersion: bigint): string[];
482
+ /**
483
+ * Run `fn` while holding the cross-process core-init lock (PG
484
+ * `pg_advisory_xact_lock`, MySQL `GET_LOCK`) on a single dedicated
485
+ * connection, so concurrent servers can't race the core migration. All of
486
+ * `fn`'s work runs on that locked connection via {@link CoreInitLockCtx}.
487
+ */
488
+ withCoreInitLock(fn: (ctx: CoreInitLockCtx) => Promise<void>): Promise<void>;
489
+ bootstrapColumnTypes(opts: {
490
+ redis?: CacheLayer;
491
+ cacheKey: string;
492
+ tables?: string[];
493
+ }): Promise<void>;
494
+ query<T = any>(sql: string, params?: unknown[]): Promise<DbQueryResult<T>>;
495
+ getClient(): Promise<PooledClient>;
496
+ getTransactionClient(): Promise<TxDatabase>;
497
+ getLatestSnapshotTimestamp(): Promise<bigint>;
498
+ updateLatestSnapshotTimestamp(commitTs: bigint): Promise<void>;
499
+ /**
500
+ * The retention watermark: the boundary `ts` below which commit_logs have
501
+ * been pruned, so any cache entry whose `lastSnapshotTs` is below it can no
502
+ * longer be freshness-checked (its scan window would miss deleted rows) and
503
+ * must be recomputed. Persisted in the `metadata` table (survives restarts)
504
+ * as a cheap PK read — callers load it into an in-memory variable at startup
505
+ * and keep it fresh via pub/sub rather than reading it per query. Returns the
506
+ * -1n genesis when nothing has been pruned yet (matching the empty-DB snapshot
507
+ * ts), so every entry is scannable.
508
+ */
509
+ getMinSnapshotTimestamp(): Promise<bigint>;
510
+ /**
511
+ * Advance the retention watermark. Monotonic: only ever moves forward (a
512
+ * stale writer can never lower it). Called by the sub-manager right before it
513
+ * prunes commit_logs below `ts`.
514
+ */
515
+ updateMinSnapshotTimestamp(ts: bigint): Promise<void>;
516
+ getNextTimestamp(): Promise<bigint>;
517
+ prepareCommitWrites(readSet: ReadEntry[], writeSet: WriteEntry[], commitTs: LazyCommitTsParam): Promise<PreparedQueries>;
518
+ commitWrites(beginTs: bigint, queries: PreparedQueries, commitTs: bigint): Promise<{
519
+ success: boolean;
520
+ }>;
521
+ close(): Promise<void>;
522
+ /**
523
+ * Delete commit_logs older than `ts` (exclusive). Used by the periodic
524
+ * retention sweep in SubscriptionManager so the table doesn't grow
525
+ * unbounded.
526
+ */
527
+ pruneCommitLogsBefore(ts: bigint): Promise<bigint>;
528
+ /**
529
+ * Oldest `ts` still present in commit_logs (i.e. the retention watermark
530
+ * after the last prune), or `null` when the table is empty. A cache entry
531
+ * whose `lastSnapshotTs` is below it can no longer be freshness-checked via
532
+ * {@link getCommitLogsBetweenTs} (the logs it would need were pruned), so the
533
+ * one-shot/register cache paths recompute instead of trusting it.
534
+ */
535
+ getMinCommitLogTs(): Promise<bigint | null>;
536
+ /**
537
+ * Half-open range scan: ts >= beginTs AND ts < endTs. Used by the
538
+ * subscription-recovery path to replay logs in a specific time window.
539
+ */
540
+ getCommitLogsBetweenTs(beginTs: bigint, endTs: bigint, tableIds: Uint8Array[]): Promise<CommitLogEntry[]>;
541
+ /**
542
+ * Conflict-check scan for OCC: ts >= sinceTs AND ts <> excludeTs. The
543
+ * exclude is our own commitTs so we don't conflict with ourselves; the
544
+ * lack of an upper bound is intentional, so a concurrent peer that
545
+ * happens to have a higher commitTs but committed before us is still
546
+ * visible. (MVCC keeps in-flight peers invisible until they commit.)
547
+ */
548
+ getCommitLogsSinceTs(sinceTs: bigint, excludeTs: bigint, tableIds: Uint8Array[]): Promise<CommitLogEntry[]>;
549
+ /**
550
+ * For each `update`/`delete` entry, attach `prevData` (consumed by the
551
+ * invalidator) and `expectedCommitTs` (the CAS fence).
552
+ *
553
+ * `expectedCommitTs` is preferentially copied from a prior point-read of
554
+ * the same row in `readSet` — that's the value the handler's logic
555
+ * actually depended on, so the CAS check enforces beginTs-level isolation
556
+ * for read-then-update patterns. If no prior read exists ("blind"
557
+ * write), we fall back to the value observed in this batch fetch (weak
558
+ * OCC, sufficient for writes that don't depend on prior state).
559
+ *
560
+ * `prevData` always comes from this batch fetch (SELECT * per table) so
561
+ * the invalidator has the full row regardless of which columns the
562
+ * handler's read selected.
563
+ *
564
+ * If the target row no longer exists at fetch time, `expectedCommitTs`
565
+ * is left undefined and the per-row CAS will match nothing — surfaced
566
+ * as OccConflictError.
567
+ */
568
+ attachPrevDataToWriteSet(writeSet: WriteEntry[], readSet: ReadEntry[]): Promise<void>;
569
+ }
570
+ interface TxDatabase extends Database {
571
+ begin(): Promise<void>;
572
+ commit(): Promise<void>;
573
+ rollback(): Promise<void>;
574
+ release(): void;
575
+ }
576
+ interface JsonOpOptions$1 {
577
+ /**
578
+ * When true, the bound `value` parameter is treated as already prepared
579
+ * for the underlying SQL (e.g. a literal JSON path string for
580
+ * jsonHasKey, a JSON-encoded literal for the contains family). When
581
+ * false/omitted, the value was prepared client-side from a JS value.
582
+ */
583
+ raw?: boolean;
584
+ /**
585
+ * 1-based positional index of an extra bound parameter holding a
586
+ * jsonpath that scopes the contains-family check to a sub-document of
587
+ * the target column. When omitted, the check runs against the whole
588
+ * column value.
589
+ */
590
+ pathIndex?: number;
591
+ /**
592
+ * jsonHasKey only: when set, multiple path parameters are bound starting
593
+ * at `paramIndex`, and the predicate evaluates whether any (`one`) or
594
+ * every (`all`) path exists in the column.
595
+ */
596
+ mode?: "one" | "all";
597
+ /** Number of bound path parameters in multi-path mode. */
598
+ pathCount?: number;
599
+ }
600
+ interface SqlBuilder {
601
+ placeholder(index: number): string;
602
+ like(col: string, paramIndex: number): string;
603
+ ilike(col: string, paramIndex: number): string;
604
+ icontains(col: string, paramIndex: number): string;
605
+ /** PG @> ; MySQL JSON_CONTAINS */
606
+ jsonContains(col: string, paramIndex: number, opts?: JsonOpOptions$1): string;
607
+ /** PG <@ ; MySQL JSON_CONTAINS(candidate, target) */
608
+ jsonContainedBy(col: string, paramIndex: number, opts?: JsonOpOptions$1): string;
609
+ /**
610
+ * Key/path existence. With `opts.raw === true`, the bound param is a JSON
611
+ * path expression (PG `jsonb_path_exists`, MySQL `JSON_CONTAINS_PATH`).
612
+ * Otherwise the bound param is a literal top-level key (PG `?`, MySQL
613
+ * `JSON_CONTAINS_PATH($."<key>")` with server-side quoting).
614
+ * With `opts.pathCount` set, emits the multi-path form keyed by `mode`.
615
+ */
616
+ jsonHasKey(col: string, paramIndex: number, opts?: JsonOpOptions$1): string;
617
+ /** Array membership: target array contains the given element. */
618
+ jsonArrayContains(col: string, paramIndex: number, opts?: JsonOpOptions$1): string;
619
+ }
620
+ declare class LazyCommitTsParam {
621
+ value: unknown;
622
+ constructor(value: unknown);
623
+ toPostgres(prepareValue: (value: any) => any): any;
624
+ toString(): any;
625
+ validate(): void;
626
+ }
627
+ //#endregion
628
+ //#region src/db/schema.d.ts
629
+ interface ColumnCodec<TData = unknown, TDriver = unknown> {
630
+ encode?: (value: TData) => TDriver;
631
+ decode?: (value: TDriver) => TData;
632
+ }
633
+ type SchemaCodecField<TSchema extends ZodRawShape, K extends PropertyKey> = K extends keyof TSchema ? TSchema[K] extends z$1.ZodTypeAny ? z$1.infer<TSchema[K]> : unknown : K extends keyof BaseSchema ? BaseSchema[K] extends z$1.ZodTypeAny ? z$1.infer<BaseSchema[K]> : unknown : unknown;
634
+ type SchemaCodecs<TSchema extends ZodRawShape> = Partial<{ [K in keyof (TSchema & BaseSchema)]: ColumnCodec<SchemaCodecField<TSchema, K>, any> }>;
635
+ interface SchemaColumnsOptions<TSchema extends ZodRawShape = ZodRawShape> {
636
+ codecs?: SchemaCodecs<TSchema>;
637
+ }
638
+ interface SchemaColumnMapping {
639
+ [key: string]: string;
640
+ }
641
+ interface DeclarativeIndex {
642
+ name: string;
643
+ columns: string[];
644
+ unique?: boolean;
645
+ type?: "btree" | "hash" | "gin" | "gist" | "spgist" | "brin";
646
+ where?: string;
647
+ using?: string;
648
+ options?: string;
649
+ tablespace?: string;
650
+ }
651
+ type IndexDefinition = string | DeclarativeIndex;
652
+ interface DefineSchemaConfig<TSchema extends ZodRawShape> {
653
+ name: string;
654
+ schema: TSchema;
655
+ options?: SchemaColumnsOptions<TSchema>;
656
+ columns?: SchemaColumnMapping;
657
+ indexes?: IndexDefinition[];
658
+ }
659
+ type CodecDataType<TCodec, TFallback> = [TCodec] extends [undefined] ? TFallback : TCodec extends {
660
+ decode: (...args: any[]) => infer TDecoded;
661
+ } ? TDecoded : TCodec extends ColumnCodec<infer TData, unknown> ? TData : TFallback;
662
+ type ZodOutput<TZod> = [TZod] extends [undefined] ? unknown : TZod extends z$1.ZodTypeAny ? z$1.infer<TZod> : unknown;
663
+ type ComputedDataType<TCodec, TZod> = CodecDataType<TCodec, ZodOutput<TZod>>;
664
+ type ComputedCodec<TData, TDriver> = ColumnCodec<TData, TDriver>;
665
+ type OverrideField<TObj, TKey extends PropertyKey, TValue> = Omit<TObj, TKey> & { [K in TKey]: TValue };
666
+ interface ComputedFieldConfig<TField extends string, TDecoded = unknown, TDriver = unknown, TZodType extends z$1.ZodTypeAny | undefined = undefined> {
667
+ field: TField;
668
+ sql: string;
669
+ alias?: string;
670
+ type?: TZodType;
671
+ codec?: {
672
+ decode: (value: TDriver) => TDecoded;
673
+ encode?: (value: TDecoded) => TDriver;
674
+ };
675
+ }
676
+ type ComputedField = {
677
+ field: string;
678
+ sql: string;
679
+ alias: string;
680
+ codec?: ColumnCodec<any, any>;
681
+ };
682
+ declare function defineComputedField<TField extends string, TDecoded = unknown, TDriver = unknown, TZodType extends z$1.ZodTypeAny | undefined = undefined>(config: ComputedFieldConfig<TField, TDecoded, TDriver, TZodType>): ComputedFieldConfig<TField, TDecoded, TDriver, TZodType>;
683
+ type Prettify<T> = { [K in keyof T]: T[K] } & {};
684
+ type ApplySchemaCodecs<TBase, TCodecs> = { [K in keyof TBase]: K extends keyof TCodecs ? CodecDataType<TCodecs[K], TBase[K]> : TBase[K] };
685
+ type ResolveSchemaType<TSchema extends ZodRawShape, TOptions extends SchemaColumnsOptions<TSchema>> = TOptions extends {
686
+ codecs: infer TCodecs;
687
+ } ? Prettify<ApplySchemaCodecs<z$1.infer<z$1.ZodObject<TSchema & BaseSchema>>, TCodecs>> : Prettify<z$1.infer<z$1.ZodObject<TSchema & BaseSchema>>>;
688
+ type IsOptionalField<T> = T extends z$1.ZodOptional<any> ? true : T extends z$1.ZodNullable<any> ? true : T extends z$1.ZodDefault<any> ? true : false;
689
+ type OptionalKeys<TZod extends ZodRawShape> = { [K in keyof TZod]: IsOptionalField<TZod[K]> extends true ? K : never }[keyof TZod];
690
+ type RequiredKeys<TZod extends ZodRawShape> = { [K in keyof TZod]: IsOptionalField<TZod[K]> extends true ? never : K }[keyof TZod];
691
+ type BaseSchema = {
692
+ id: z$1.ZodString;
693
+ commitTs: z$1.ZodCoercedBigInt;
694
+ };
695
+ declare const schemaRegistry: Map<string, SchemaDefinition<string, any, any>>;
696
+ declare let shouldTrackSchema: boolean;
697
+ declare function trackSchema(): void;
698
+ declare function defineSchema<TSchema extends ZodRawShape, TName extends string, TOptions extends SchemaColumnsOptions<TSchema> = SchemaColumnsOptions<TSchema>>(config: DefineSchemaConfig<TSchema> & {
699
+ name: TName;
700
+ options?: TOptions;
701
+ }): SchemaDefinition<TName, Prettify<TSchema & BaseSchema>, ResolveSchemaType<TSchema, TOptions>>;
702
+ declare function tableNameToId(tableName: string): Uint8Array;
703
+ interface StoredSchemaColumnsOptions {
704
+ codecs?: Record<string, ColumnCodec<any, any>>;
705
+ }
706
+ interface SchemaDefinition<TTable extends string, TZod extends ZodRawShape, TData = z$1.infer<z$1.ZodObject<TZod>>> {
707
+ tableId: Uint8Array;
708
+ table: TTable;
709
+ schema: z$1.ZodObject<TZod>;
710
+ columnsOptions: StoredSchemaColumnsOptions;
711
+ columns: Record<string, string>;
712
+ indexes: IndexDefinition[];
713
+ _dataType?: TData;
714
+ }
715
+ type InferSchema<T extends SchemaDefinition<string, ZodRawShape, any>> = T extends SchemaDefinition<string, ZodRawShape, infer TData> ? TData : never;
716
+ type InsertData<T extends SchemaDefinition<string, ZodRawShape, any>> = T extends SchemaDefinition<string, infer TZod, infer TData> ? { [K in RequiredKeys<TZod> as K extends "id" | "commitTs" ? never : K]: Extract<K, string> extends keyof TData ? TData[Extract<K, string>] : never } & { [K in OptionalKeys<TZod> as K extends "id" | "commitTs" ? never : K]?: Extract<K, string> extends keyof TData ? TData[Extract<K, string>] : never } : never;
717
+ interface Model {
718
+ table: string;
719
+ tableId: Uint8Array;
720
+ columns: Record<string, string>;
721
+ reverseColumns: Record<string, string>;
722
+ types: Record<string, string>;
723
+ codecs: Record<string, ColumnCodec<any, any>>;
724
+ }
725
+ type MaybePromise<T> = T | Promise<T>;
726
+ type ReturnLiveQuery<TLiveQueryFn extends (...args: any[]) => MaybePromise<LiveQueryHandle<any>>> = Awaited<ReturnType<TLiveQueryFn>> extends LiveQueryHandle<infer T> ? T : never;
727
+ type ReturnQuery<TQueryFn extends (...args: any[]) => any> = Awaited<ReturnType<TQueryFn>>;
728
+ type QueryArgs<TQueryFn extends (...args: any[]) => any> = Parameters<TQueryFn>[0];
729
+ type MutationArgs<TMutationFn extends (...args: any[]) => any> = Parameters<TMutationFn>[0];
730
+ type ActionArgs<TActionFn extends (...args: any[]) => any> = Parameters<TActionFn>[0];
731
+ //#endregion
732
+ //#region src/db/query.d.ts
733
+ type FieldValue<S extends SchemaDefinition<string, ZodRawShape>, K> = K extends keyof InferSchema<S> ? InferSchema<S>[K] : never;
734
+ type OrderableValue = number | bigint | string | Date;
735
+ type StringFieldKeys<S extends SchemaDefinition<string, ZodRawShape>> = { [K in keyof InferSchema<S>]: NonNullable<InferSchema<S>[K]> extends string ? K : never }[keyof InferSchema<S>];
736
+ type OrderableFieldKeys<S extends SchemaDefinition<string, ZodRawShape>> = { [K in keyof InferSchema<S>]: NonNullable<InferSchema<S>[K]> extends OrderableValue ? K : never }[keyof InferSchema<S>];
737
+ type JsonFieldKeys<S extends SchemaDefinition<string, ZodRawShape>> = { [K in keyof InferSchema<S>]: NonNullable<InferSchema<S>[K]> extends OrderableValue ? never : NonNullable<InferSchema<S>[K]> extends boolean ? never : NonNullable<InferSchema<S>[K]> extends (object | unknown[]) ? K : unknown extends NonNullable<InferSchema<S>[K]> ? K : never }[keyof InferSchema<S>];
738
+ interface JsonOpOptions {
739
+ /**
740
+ * Skip client-side preparation of the value (no JSON-stringify, no key
741
+ * escaping). The caller is responsible for the exact form the dialect
742
+ * expects: a JSON path string for jsonHasKey, a JSON-encoded string for
743
+ * the contains family.
744
+ */
745
+ raw?: true;
746
+ }
747
+ interface JsonContainsOptions extends JsonOpOptions {
748
+ /**
749
+ * Sub-path into the target JSON to scope the check to. `string` is a
750
+ * single literal top-level key; `string[]` is a nested literal-key path
751
+ * compiled to `$."a"."b"`. Mutually exclusive with `pathRaw`.
752
+ */
753
+ path?: string | string[];
754
+ /**
755
+ * Raw jsonpath expression used verbatim by the dialect (PG `jsonpath`,
756
+ * MySQL JSON path). Mutually exclusive with `path`.
757
+ */
758
+ pathRaw?: string;
759
+ }
760
+ interface JsonHasKeyMultiOptions extends JsonOpOptions {
761
+ /** Required for the multi-path overload — chooses any vs every. */
762
+ mode: "one" | "all";
763
+ }
764
+ declare class QueryBuilder<S extends SchemaDefinition<string, ZodRawShape>> {
765
+ protected ctx: TxContext;
766
+ protected model: Model;
767
+ constructor(ctx: TxContext, model: Model);
768
+ protected getColumnName(key: string): string;
769
+ select(): SelectQueryBuilder<S, keyof InferSchema<S>>;
770
+ select<K extends keyof InferSchema<S>>(...columns: K[]): SelectQueryBuilder<S, K>;
771
+ }
772
+ type IdAndCommitTs = {
773
+ id: string;
774
+ commitTs: bigint;
775
+ };
776
+ type SelectRow<S extends SchemaDefinition<string, ZodRawShape>, K extends keyof InferSchema<S>, C extends Record<string, unknown>> = Prettify<Pick<InferSchema<S>, Extract<K | "id" | "commitTs", keyof InferSchema<S>>> & C>;
777
+ type OrderDirection = "ASC" | "DESC";
778
+ interface OrderByOptions {
779
+ direction?: OrderDirection;
780
+ nulls?: "first" | "last";
781
+ collate?: string;
782
+ }
783
+ /**
784
+ * Cursor-based pagination using a timestamp column and a unique ID column.
785
+ *
786
+ * Generates a stable cursor predicate:
787
+ *
788
+ * DESC (default):
789
+ * ```sql
790
+ * WHERE (timeCol < ? OR (timeCol = ? AND idCol < ?))
791
+ * ORDER BY timeCol DESC, idCol DESC
792
+ * ```
793
+ *
794
+ * ASC:
795
+ * ```sql
796
+ * WHERE (timeCol > ? OR (timeCol = ? AND idCol > ?))
797
+ * ORDER BY timeCol ASC, idCol ASC
798
+ * ```
799
+ */
800
+ interface PaginationClause<S extends SchemaDefinition<string, ZodRawShape>, Time extends OrderableFieldKeys<S>, Id extends OrderableFieldKeys<S>> {
801
+ /** Timestamp column used for cursor pagination. */
802
+ timeCol: Time;
803
+ /**
804
+ * Unique tie-breaker column.
805
+ *
806
+ * @default "id"
807
+ */
808
+ idCol?: Id;
809
+ /**
810
+ * Pagination direction.
811
+ *
812
+ * - `"desc"` (default): Newest → oldest.
813
+ * - `"asc"`: Oldest → newest.
814
+ *
815
+ * @default "desc"
816
+ */
817
+ direction?: OrderDirection;
818
+ /**
819
+ * Maximum number of rows to return.
820
+ */
821
+ limit?: number;
822
+ /**
823
+ * Cursor returned from the previous page.
824
+ *
825
+ * Omit or set to `null` to fetch the first page.
826
+ */
827
+ cursor?: {
828
+ time: FieldValue<S, Time>;
829
+ id: FieldValue<S, Id>;
830
+ } | null;
831
+ }
832
+ declare class SelectQueryBuilder<S extends SchemaDefinition<string, ZodRawShape>, K extends keyof InferSchema<S> = never, C extends Record<string, unknown> = {}> {
833
+ private ctx;
834
+ private model;
835
+ private filters;
836
+ private paginationClause;
837
+ private orderByClause;
838
+ private limitVal;
839
+ private offsetVal;
840
+ private selectedProps;
841
+ private computedFields;
842
+ private commentStr;
843
+ constructor(ctx: TxContext, model: Model, filters?: ((fb: FilterBuilder<S>) => void)[], orderByClause?: string[] | null, limitVal?: number | null, offsetVal?: number | null, selectedProps?: (keyof InferSchema<S>)[], computedFields?: ComputedField[], commentStr?: string);
844
+ private getColumnName;
845
+ private getPropertyName;
846
+ private mapRowToSchema;
847
+ where(filterFn: (fb: FilterBuilder<S>) => void): SelectQueryBuilder<S, K, C>;
848
+ paginate<Time extends OrderableFieldKeys<S>, Id extends OrderableFieldKeys<S>>(clause: PaginationClause<S, Time, Id>): SelectQueryBuilder<S, K, C>;
849
+ orderBy(column: keyof InferSchema<S> | keyof C, direction?: OrderDirection): SelectQueryBuilder<S, K, C>;
850
+ orderBy(column: keyof InferSchema<S> | keyof C, options?: OrderByOptions): SelectQueryBuilder<S, K, C>;
851
+ private buildOrderBySql;
852
+ orderByRaw(sql: string): SelectQueryBuilder<S, K, C>;
853
+ limit(n: number): SelectQueryBuilder<S, K, C>;
854
+ offset(n: number): SelectQueryBuilder<S, K, C>;
855
+ computed<TField extends string, TZodType extends z$1.ZodTypeAny | undefined = undefined, TDecode extends (value: any) => any = (value: unknown) => unknown>(config: ComputedFieldConfig<TField, ReturnType<TDecode>, Parameters<TDecode>[0], TZodType> & {
856
+ codec: {
857
+ decode: TDecode;
858
+ encode?: (value: ReturnType<TDecode>) => Parameters<TDecode>[0];
859
+ };
860
+ }): SelectQueryBuilder<S, K | TField, OverrideField<C, TField, ComputedDataType<ComputedCodec<ReturnType<TDecode>, Parameters<TDecode>[0]>, TZodType>>>;
861
+ computed<TField extends string, TZodType extends z$1.ZodTypeAny | undefined = undefined>(config: ComputedFieldConfig<TField, unknown, unknown, TZodType> & {
862
+ codec?: undefined;
863
+ }): SelectQueryBuilder<S, K | TField, OverrideField<C, TField, ComputedDataType<undefined, TZodType>>>;
864
+ comment(input: string | Record<string, string>): SelectQueryBuilder<S, K, C>;
865
+ first(): Promise<SelectRow<S, K, C> | null>;
866
+ exists(): Promise<boolean>;
867
+ private static defaultCountType;
868
+ count(): Promise<number>;
869
+ count<T extends z$1.ZodType>(parser: T): Promise<z$1.output<T>>;
870
+ find(id: string): Promise<SelectRow<S, K, C> | null>;
871
+ get(): Promise<SelectRow<S, K, C>[]>;
872
+ private buildPredicate;
873
+ }
874
+ declare class FilterBuilder<S extends SchemaDefinition<string, ZodRawShape>> {
875
+ private columns;
876
+ private codecs;
877
+ predicates: Predicate[];
878
+ constructor(columns: Record<string, string>, codecs: Record<string, ColumnCodec<unknown, unknown>>);
879
+ private add;
880
+ private addJsonContains;
881
+ private getColumnName;
882
+ private encode;
883
+ private encodeJson;
884
+ eq<K extends keyof InferSchema<S>>(key: K, value: FieldValue<S, K>): FilterBuilder<S>;
885
+ neq<K extends keyof InferSchema<S>>(key: K, value: FieldValue<S, K>): FilterBuilder<S>;
886
+ gt<K extends OrderableFieldKeys<S>>(key: K, value: FieldValue<S, K>): FilterBuilder<S>;
887
+ gte<K extends OrderableFieldKeys<S>>(key: K, value: FieldValue<S, K>): FilterBuilder<S>;
888
+ lt<K extends OrderableFieldKeys<S>>(key: K, value: FieldValue<S, K>): FilterBuilder<S>;
889
+ lte<K extends OrderableFieldKeys<S>>(key: K, value: FieldValue<S, K>): FilterBuilder<S>;
890
+ like<K extends StringFieldKeys<S>>(key: K, pattern: string): FilterBuilder<S>;
891
+ ilike<K extends StringFieldKeys<S>>(key: K, pattern: string): FilterBuilder<S>;
892
+ contains<K extends StringFieldKeys<S>>(key: K, value: string): FilterBuilder<S>;
893
+ icontains<K extends StringFieldKeys<S>>(key: K, value: string): FilterBuilder<S>;
894
+ /**
895
+ * JSON containment. Targets a JSON/JSONB column and asserts the document
896
+ * contains the given candidate (object-key subset for objects,
897
+ * element-subset for arrays — see dialect-specific docs for edge cases).
898
+ * Pass `{ raw: true }` if `value` is already a JSON-encoded string.
899
+ * Pass `{ path: ... }` to scope the check to a sub-document of the
900
+ * target (jsonb_path_query_first on PG, JSON_CONTAINS path arg on MySQL).
901
+ */
902
+ jsonContains<K extends JsonFieldKeys<S>>(key: K, value: unknown, opts?: JsonContainsOptions): FilterBuilder<S>;
903
+ /** Inverse of {@link jsonContains}: column is contained in the given value. */
904
+ jsonContainedBy<K extends JsonFieldKeys<S>>(key: K, value: unknown, opts?: JsonContainsOptions): FilterBuilder<S>;
905
+ /**
906
+ * Key/path existence check on a JSON column.
907
+ *
908
+ * - String form (top-level key): `jsonHasKey("meta", "color")`. On PG
909
+ * also matches when the column is a string array and `value` is one of
910
+ * its elements (PG `?` semantics); MySQL stays strict to object keys.
911
+ * - Array form (nested path): `jsonHasKey("meta", ["a", "b"])` compiles
912
+ * to a path expression `$."a"."b"` on both dialects.
913
+ * - Raw form: `jsonHasKey("meta", "$.foo[*]", { raw: true })` passes the
914
+ * string through as a dialect path expression (PG `jsonb_path_exists`
915
+ * jsonpath, MySQL `JSON_CONTAINS_PATH`). Caller owns the syntax.
916
+ * - Multi-path form: `jsonHasKey("meta", [["a","b"], "color"], { mode: "all" })`
917
+ * compiles each entry to a jsonpath and emits PG OR/AND of
918
+ * `jsonb_path_exists` or MySQL `JSON_CONTAINS_PATH('all', ...)`.
919
+ */
920
+ jsonHasKey<K extends JsonFieldKeys<S>>(key: K, value: string): FilterBuilder<S>;
921
+ jsonHasKey<K extends JsonFieldKeys<S>>(key: K, value: string[]): FilterBuilder<S>;
922
+ jsonHasKey<K extends JsonFieldKeys<S>>(key: K, value: string, opts: {
923
+ raw: true;
924
+ }): FilterBuilder<S>;
925
+ jsonHasKey<K extends JsonFieldKeys<S>>(key: K, paths: (string | string[])[], opts: JsonHasKeyMultiOptions): FilterBuilder<S>;
926
+ jsonHasKey<K extends JsonFieldKeys<S>>(key: K, paths: string[], opts: JsonHasKeyMultiOptions & {
927
+ raw: true;
928
+ }): FilterBuilder<S>;
929
+ /**
930
+ * Array element containment: target column is a JSON array; the given
931
+ * `value` (any JSON-encodable type) must appear as one of its elements.
932
+ * Pass `{ raw: true }` if `value` is already a JSON-encoded string.
933
+ * Pass `{ path: ... }` to scope the check to a sub-array of the column.
934
+ */
935
+ jsonArrayContains<K extends JsonFieldKeys<S>>(key: K, value: unknown, opts?: JsonContainsOptions): FilterBuilder<S>;
936
+ between<K extends OrderableFieldKeys<S>>(key: K, lo: FieldValue<S, K>, hi: FieldValue<S, K>): FilterBuilder<S>;
937
+ /**
938
+ * Set membership: `key` equals any of `values` (SQL `IN`). Each value is
939
+ * codec-encoded like `eq`. An empty `values` matches no rows. Bound as one
940
+ * parameter per element, so keep the list within the driver's parameter
941
+ * limit (chunk very large sets at the call site).
942
+ */
943
+ in<K extends keyof InferSchema<S>>(key: K, values: readonly FieldValue<S, K>[]): FilterBuilder<S>;
944
+ isNull<K extends keyof InferSchema<S>>(key: K): FilterBuilder<S>;
945
+ notNull<K extends keyof InferSchema<S>>(key: K): FilterBuilder<S>;
946
+ /**
947
+ * Compose an OR clause. Each callback fills a fresh sub-FilterBuilder
948
+ * with predicates that are AND-ed together within that branch; the
949
+ * branches themselves are OR-ed. Example:
950
+ * f.or([
951
+ * b => b.eq("tag", "a"),
952
+ * b => b.eq("tag", "b").gt("qty", 3), // (tag=b AND qty>3)
953
+ * ])
954
+ * produces (tag=a) OR (tag=b AND qty>3).
955
+ */
956
+ or(branches: ((fb: FilterBuilder<S>) => void)[]): FilterBuilder<S>;
957
+ }
958
+ declare function buildPredicateSql(predicate: Predicate, params: unknown[], sql: SqlBuilder): string;
959
+ declare function matchesPredicate(row: Record<string, unknown>, predicate: Predicate): boolean;
960
+ declare function jsonContains(target: unknown, candidate: unknown): boolean;
961
+ declare function jsonPathExtract(val: unknown, path: string): unknown;
962
+ declare function jsonPathExists(val: unknown, path: string): boolean;
963
+ //#endregion
964
+ //#region src/db/context.d.ts
965
+ declare class TxContext {
966
+ readonly beginTs: bigint;
967
+ readonly db: Database;
968
+ protected readSet: ReadEntry[];
969
+ protected writeSet: WriteEntry[];
970
+ private models;
971
+ protected getOrCreateModel(schema: SchemaDefinition<string, ZodRawShape>): Model;
972
+ constructor(db: Database, beginTs: bigint);
973
+ internalGetReadSet(): ReadEntry[];
974
+ internalGetWriteSet(): WriteEntry[];
975
+ /**
976
+ * Merge a parent procedure's reads into this context's readSet. Used when a
977
+ * `runMutation` sub-transaction inherits the reads of the procedure that
978
+ * invoked it, so the sub-tx's OCC validation also fences on those rows.
979
+ * Entries are shallow-cloned so the two readSets don't alias.
980
+ */
981
+ appendInternalReadSet(parentEntries: ReadEntry[]): void;
982
+ protected findPendingWrite(table: string, id: string): WriteEntry | undefined;
983
+ protected findPendingInsert(table: string, id: string): WriteEntry | undefined;
984
+ protected encodeWithCodec(model: Model, property: string, value: unknown): unknown;
985
+ }
986
+ declare class DbReader extends TxContext {
987
+ query<S extends SchemaDefinition<string, ZodRawShape>>(schema: S): QueryBuilder<S>;
988
+ }
989
+ declare class DbWriter extends DbReader {
990
+ insert<S extends SchemaDefinition<string, ZodRawShape>, ID extends string>(schema: S, id: ID, data: InsertData<S>): Promise<void>;
991
+ update<S extends SchemaDefinition<string, ZodRawShape>, ID extends string>(schema: S, id: ID, data: Partial<Omit<InferSchema<S>, "id" | "commitTs">>): Promise<void>;
992
+ delete<S extends SchemaDefinition<string, ZodRawShape>, ID extends string>(schema: S, id: ID): Promise<void>;
993
+ }
994
+ //#endregion
995
+ //#region src/db/query_definition.d.ts
996
+ /**
997
+ * A named, typed query definition produced by defineQuery().
998
+ * Carries the query function at runtime and the name/params/result types
999
+ * at compile time — making it the single source of truth for both the
1000
+ * server-side registry and the client-side RPC.
1001
+ */
1002
+ interface QueryDefinition<TName extends string, TParams, TResult> {
1003
+ readonly _type: "QueryDefinition";
1004
+ readonly name: TName;
1005
+ readonly fn: (ctx: DbReader, params: TParams) => Promise<TResult>;
1006
+ }
1007
+ type AnyQueryDef = QueryDefinition<string, any, any>;
1008
+ /** Extract the params type from a QueryDefinition. */
1009
+ type ParamsOf<D extends AnyQueryDef> = D extends QueryDefinition<any, infer P, any> ? P : never;
1010
+ /** Extract the result type from a QueryDefinition. */
1011
+ type ResultOf<D extends AnyQueryDef> = D extends QueryDefinition<any, any, infer R> ? R : never;
1012
+ /**
1013
+ * Convert a readonly tuple of QueryDefinitions into a Record keyed by their
1014
+ * name literals. This is what makes ClientRpc fully type-safe: each key in
1015
+ * the map carries its own TParams and TResult rather than collapsing to `any`.
1016
+ *
1017
+ * Example:
1018
+ * const defs = [projectBoardQuery, teamMembersQuery] as const;
1019
+ * type Map = DefsToMap<typeof defs>;
1020
+ * // → { projectBoard: typeof projectBoardQuery; teamMembers: typeof teamMembersQuery }
1021
+ */
1022
+ type DefsToMap<T extends readonly AnyQueryDef[]> = { [D in T[number] as D["name"]]: D };
1023
+ /** For test teardown only — clears the global map between suites. */
1024
+ declare function _resetGlobalDefs(): void;
1025
+ /**
1026
+ * Create a named, typed query definition.
1027
+ *
1028
+ * The definition is automatically registered in a module-level global so
1029
+ * the server can call registry.defineAll() instead of listing every query
1030
+ * explicitly. On the client, pass the definition to createClientRpc() to
1031
+ * get a fully typed subscribe() call.
1032
+ *
1033
+ * Usage:
1034
+ * export const projectBoardQuery = defineQuery(
1035
+ * "projectBoard",
1036
+ * async (ctx, params: { projectId: string }) => {
1037
+ * return ctx.query(Tasks)
1038
+ * .select()
1039
+ * .where(f => f.eq("projectId", params.projectId))
1040
+ * .get();
1041
+ * }
1042
+ * );
1043
+ */
1044
+ declare function defineQuery<TName extends string, TParams, TResult>(name: TName, fn: (ctx: DbReader, params: TParams) => Promise<TResult>): QueryDefinition<TName, TParams, TResult>;
1045
+ //#endregion
1046
+ //#region src/db/realtime_db.d.ts
1047
+ declare class SupaliveDb {
1048
+ readonly impl: Database;
1049
+ constructor(impl: Database);
1050
+ static create(config: {
1051
+ db: Database;
1052
+ }): SupaliveDb;
1053
+ protected onAfterCommit?: (writeSet: WriteEntry[], commitTs: CommitTs) => void;
1054
+ /**
1055
+ * Register a hook fired once after every successful `mutation()` commit
1056
+ * (never on an OCC conflict/rollback), with the committed writeSet and its
1057
+ * commitTs. The server uses this to drive subscription invalidation for ALL
1058
+ * mutation sources — client WS calls, actions, jobs, and the internal caller —
1059
+ * so a server-side write pushes live updates just like a client write does.
1060
+ * Non-server consumers (migration tooling, tests) leave it unset (no-op).
1061
+ */
1062
+ setOnAfterCommit(cb: (writeSet: WriteEntry[], commitTs: CommitTs) => void): void;
1063
+ query<T>(fn: (ctx: DbReader) => Promise<T>): Promise<T>;
1064
+ /**
1065
+ * Compute a query once at the latest snapshot, returning the result together
1066
+ * with the snapshot `ts` and the tracked `readSet`. This is a plain one-shot
1067
+ * evaluation — it registers NO live subscription; the `readSet`/`ts` are
1068
+ * returned purely so the caller (e.g. the one-shot query cache) can store
1069
+ * freshness metadata. Use this for cached one-shot query calls (WS `call`,
1070
+ * HTTP RPC). `liveQuery` is the same computation under the subscription path's
1071
+ * name and simply delegates here.
1072
+ */
1073
+ queryInternal<T>(fn: (ctx: DbReader) => Promise<T>): Promise<LiveResult<T>>;
1074
+ liveQuery<T>(fn: (ctx: DbReader) => Promise<T>): Promise<LiveResult<T>>;
1075
+ mutation<T>(fn: (ctx: DbWriter) => Promise<T>, retryPolicy?: RetryPolicy): Promise<MutationResult<T>>;
1076
+ }
1077
+ declare const sleep: (ms: number) => Promise<void>;
1078
+ //#endregion
1079
+ //#region src/jobs/scheduler.d.ts
1080
+ /** A recurring job to keep synced on the scheduler side. */
1081
+ interface ScheduledJobDef {
1082
+ /** Job procedure name (also the last path segment of its endpoint). */
1083
+ name: string;
1084
+ /** Cron expression, e.g. `"0 3 * * *"`. */
1085
+ cron: string;
1086
+ }
1087
+ /** Options for a precise, one-shot job run. */
1088
+ interface EnqueueOptions {
1089
+ /** Run after this many seconds from now. */
1090
+ delaySeconds?: number;
1091
+ /** Run at this absolute time. Overrides `delaySeconds`. */
1092
+ runAt?: Date;
1093
+ /**
1094
+ * Idempotency key. If two enqueues share the same id within the provider's
1095
+ * dedup window, only the first is delivered. Use it to make "schedule the
1096
+ * expiry of X" safe to call more than once.
1097
+ */
1098
+ dedupeId?: string;
1099
+ }
1100
+ /** Handle returned by {@link JobScheduler.enqueue}; pass its `id` to `cancel`. */
1101
+ interface ScheduleHandle {
1102
+ id: string;
1103
+ }
1104
+ /** The pieces of an inbound webhook the scheduler needs to authenticate it. */
1105
+ interface IncomingJobRequest {
1106
+ /** Job name parsed from the request path. */
1107
+ name: string;
1108
+ /** Raw (unparsed) request body — signatures are computed over these bytes. */
1109
+ rawBody: string;
1110
+ /** Request headers, keys lowercased. */
1111
+ headers: Record<string, string | undefined>;
1112
+ /** Full request URL the webhook was delivered to. */
1113
+ url: string;
1114
+ }
1115
+ /**
1116
+ * Pluggable scheduler. The server owns exactly one instance and uses it for
1117
+ * both directions:
1118
+ * • inbound — `verify` authenticates a webhook before the job runs.
1119
+ * • outbound — `syncSchedules` (recurring, at startup) and `enqueue`/`cancel`
1120
+ * (precise one-shots, at runtime) drive the provider.
1121
+ *
1122
+ * Both dev and production implementations POST to the same HTTP job endpoint,
1123
+ * so the server's dispatch path is exercised identically in every environment.
1124
+ */
1125
+ interface JobScheduler {
1126
+ /** Authenticate an inbound webhook. Return false (or throw) to reject. */
1127
+ verify(req: IncomingJobRequest): Promise<boolean>;
1128
+ /**
1129
+ * Make the provider's recurring schedules match `jobs` exactly (create,
1130
+ * update, and remove stale ones). Called once at server startup.
1131
+ * `endpointFor(name)` yields the absolute URL the provider should POST to.
1132
+ */
1133
+ syncSchedules(jobs: ScheduledJobDef[], endpointFor: (name: string) => string): Promise<void>;
1134
+ /** Enqueue a precise one-shot run of `name` with `body` at `endpoint`. */
1135
+ enqueue(name: string, body: unknown, endpoint: string, opts?: EnqueueOptions): Promise<ScheduleHandle>;
1136
+ /** Cancel a previously enqueued one-shot by its handle id. */
1137
+ cancel(handleId: string): Promise<void>;
1138
+ }
1139
+ interface DevSchedulerOptions {
1140
+ /**
1141
+ * How often, in ms, to fire each recurring job in dev. Dev intentionally
1142
+ * ignores exact cron timing (that is the production scheduler's job); it
1143
+ * just fires often enough to exercise the handler. Default 60_000.
1144
+ */
1145
+ recurringIntervalMs?: number;
1146
+ /**
1147
+ * Override the HTTP client (for tests). Defaults to the global `fetch`.
1148
+ */
1149
+ fetchImpl?: typeof fetch;
1150
+ }
1151
+ /**
1152
+ * In-process scheduler for local development and tests. Recurring jobs fire on
1153
+ * a fixed interval; one-shots fire on an exact `setTimeout` (so precise timing
1154
+ * is faithfully testable). Every fire POSTs to the real HTTP job endpoint, and
1155
+ * `verify` accepts everything — there is no signing in dev.
1156
+ */
1157
+ declare class DevScheduler implements JobScheduler {
1158
+ private readonly intervalMs;
1159
+ private readonly fetchImpl;
1160
+ private intervals;
1161
+ private timeouts;
1162
+ constructor(opts?: DevSchedulerOptions);
1163
+ verify(_req: IncomingJobRequest): Promise<boolean>;
1164
+ syncSchedules(jobs: ScheduledJobDef[], endpointFor: (name: string) => string): Promise<void>;
1165
+ enqueue(name: string, body: unknown, endpoint: string, opts?: EnqueueOptions): Promise<ScheduleHandle>;
1166
+ cancel(handleId: string): Promise<void>;
1167
+ /** Stop every dev timer (call on server shutdown / in test teardown). */
1168
+ stop(): void;
1169
+ private post;
1170
+ }
1171
+ interface QStashSchedulerOptions {
1172
+ /** QStash Base url (`QSTASH_BASE_URL`). */
1173
+ baseUrl: string;
1174
+ /** QStash REST token (`QSTASH_TOKEN`). */
1175
+ token: string;
1176
+ /** Current signing key for webhook verification (`QSTASH_CURRENT_SIGNING_KEY`). */
1177
+ currentSigningKey: string;
1178
+ /** Next signing key, for zero-downtime key rotation (`QSTASH_NEXT_SIGNING_KEY`). */
1179
+ nextSigningKey: string;
1180
+ devMode: boolean;
1181
+ }
1182
+ /**
1183
+ * Production scheduler backed by Upstash QStash. Externalizes the timer so a
1184
+ * horizontally-scaled deployment fires each cron tick exactly once (QStash
1185
+ * calls one HTTP endpoint), with at-least-once retries and signed webhooks.
1186
+ */
1187
+ declare class QStashScheduler implements JobScheduler {
1188
+ private readonly client;
1189
+ private readonly receiver;
1190
+ constructor(opts: QStashSchedulerOptions);
1191
+ verify(req: IncomingJobRequest): Promise<boolean>;
1192
+ syncSchedules(jobs: ScheduledJobDef[], endpointFor: (name: string) => string): Promise<void>;
1193
+ enqueue(name: string, body: unknown, endpoint: string, opts?: EnqueueOptions): Promise<ScheduleHandle>;
1194
+ cancel(handleId: string): Promise<void>;
1195
+ }
1196
+ /**
1197
+ * Thin app-facing handle for scheduling precise one-shots from inside
1198
+ * procedures. The server builds one (via `getJobClient()`) that already knows
1199
+ * how to turn a job name into its endpoint, so callers just say
1200
+ * `jobs.enqueue("expireSpendAuth", { id }, { runAt })`.
1201
+ */
1202
+ declare class JobClient {
1203
+ private readonly scheduler;
1204
+ private readonly endpointFor;
1205
+ constructor(scheduler: JobScheduler, endpointFor: (name: string) => string);
1206
+ enqueue(name: string, body: unknown, opts?: EnqueueOptions): Promise<ScheduleHandle>;
1207
+ cancel(handleId: string): Promise<void>;
1208
+ }
1209
+ //#endregion
1210
+ //#region src/router/procedure.d.ts
1211
+ /**
1212
+ * Query context passed to query handlers.
1213
+ * Contains database reader and user-defined server context.
1214
+ */
1215
+ interface QueryCtx<TContext = unknown> {
1216
+ /** Database reader for queries */
1217
+ db: DbReader;
1218
+ /** User-defined server context (auth, requestId, etc.) */
1219
+ serverCtx?: TContext;
1220
+ }
1221
+ /**
1222
+ * Mutation context passed to mutation handlers.
1223
+ * Contains database writer and user-defined server context.
1224
+ */
1225
+ interface MutationCtx<TContext = unknown> {
1226
+ /** Database writer for mutations (includes insert/update/delete) */
1227
+ db: DbWriter;
1228
+ /** User-defined server context (auth, requestId, etc.) */
1229
+ serverCtx?: TContext;
1230
+ }
1231
+ /**
1232
+ * Action context passed to action handlers.
1233
+ *
1234
+ * Actions are the "external I/O" tier: they hold the full {@link SupaliveDb}
1235
+ * (queries + mutations) and are the ONLY context that also carries side-effect
1236
+ * services — {@link ObjectStorage} for uploads/downloads and a {@link JobClient}
1237
+ * for scheduling precise one-shots. Queries/mutations stay pure (db only) so
1238
+ * they remain cacheable and transaction-scoped.
1239
+ */
1240
+ interface ActionCtx<TContext = unknown> {
1241
+ /** Full database interface for queries and mutations */
1242
+ db: SupaliveDb;
1243
+ /** Object storage, when the server was configured with one (see
1244
+ * `SupaliveServerConfig.storage`); `undefined` otherwise. The usual home
1245
+ * for upload/download presigning. */
1246
+ storage: ObjectStorage;
1247
+ /** Job scheduler client for enqueueing precise one-shots, when the server
1248
+ * was configured with a `scheduler`; `undefined` otherwise. Scheduling is
1249
+ * network I/O, so it belongs in actions, never inside a DB transaction. */
1250
+ scheduler: JobClient;
1251
+ /** User-defined server context (auth, requestId, etc.) */
1252
+ serverCtx?: TContext;
1253
+ }
1254
+ /**
1255
+ * Job context passed to job handlers. Structurally identical to
1256
+ * {@link ActionCtx}: a job is a server-only procedure that runs
1257
+ * non-transactionally against the full {@link SupaliveDb} and may perform
1258
+ * external work, but it is triggered by the scheduler over HTTP (a cron tick
1259
+ * or a precise one-shot) rather than by a connected client. `serverCtx` is
1260
+ * the system context built by the server's `jobContext` factory.
1261
+ */
1262
+ interface JobCtx<TContext = unknown> {
1263
+ /** Full database interface for queries and mutations */
1264
+ db: SupaliveDb;
1265
+ /** System server context built by the server for scheduler-triggered runs */
1266
+ serverCtx?: TContext;
1267
+ }
1268
+ /**
1269
+ * Context handed to `caller.<proc>.runQuery` / `.runMutation` when invoking one
1270
+ * procedure from inside another. Pass the caller handler's own `ctx` — its `db`
1271
+ * carries the parent's live transaction (a {@link DbReader}/{@link DbWriter}) or,
1272
+ * inside an action, the full {@link SupaliveDb}. The caller uses this to decide
1273
+ * whether the nested call joins the parent's snapshot (queries) or runs as an
1274
+ * independent sub-transaction (mutations).
1275
+ */
1276
+ interface ParentCtx<TContext = unknown> {
1277
+ db: DbReader | DbWriter | SupaliveDb;
1278
+ serverCtx?: TContext | undefined;
1279
+ }
1280
+ type QueryFn<TInput, TResult, TContext = unknown> = (ctx: QueryCtx<TContext>, input: TInput) => Promise<TResult>;
1281
+ type MutationFn<TInput, TResult, TContext = unknown> = (ctx: MutationCtx<TContext>, input: TInput) => Promise<TResult>;
1282
+ type ActionFn<TInput, TResult, TContext = unknown> = (ctx: ActionCtx<TContext>, input: TInput) => Promise<TResult>;
1283
+ type JobFn<TInput, TResult, TContext = unknown> = (ctx: JobCtx<TContext>, input: TInput) => Promise<TResult>;
1284
+ /**
1285
+ * Per-procedure override for the cache/subscription segmentation key.
1286
+ *
1287
+ * omitted | undefined → fall back to `config.getUserId(serverCtx)` (default)
1288
+ * false → no identity in hash; cache/sub shared across all users
1289
+ * string → a static identity literal (e.g. "public" or a tenant id)
1290
+ * function → compute from serverCtx + input (sync)
1291
+ *
1292
+ * When the result of a query is identical regardless of who calls it, set
1293
+ * this to a literal (or `false`) so a single cache entry serves everyone.
1294
+ *
1295
+ * The function form intentionally takes `serverCtx` (not the full `QueryCtx`)
1296
+ * because identity is resolved before any DB read is issued.
1297
+ */
1298
+ type QueryIdentitySpec<TInput, TContext> = false | string | ((serverCtx: TContext, input: TInput) => string | null | undefined);
1299
+ interface BaseProcedure<TInput, TResult, TType extends "query" | "mutation" | "action" | "job", TContext = unknown, TInternal extends boolean = boolean> {
1300
+ readonly _type: "procedure";
1301
+ readonly procedureType: TType;
1302
+ readonly inputSchema: ZodType<TInput>;
1303
+ readonly outputSchema?: ZodType<any>;
1304
+ readonly fn: QueryFn<TInput, TResult, TContext> | MutationFn<TInput, TResult, TContext> | ActionFn<TInput, TResult, TContext> | JobFn<TInput, TResult, TContext>;
1305
+ readonly internal: TInternal;
1306
+ }
1307
+ interface QueryProcedure<TInput, TResult, TContext = unknown, TInternal extends boolean = boolean> extends BaseProcedure<TInput, TResult, "query", TContext, TInternal> {
1308
+ readonly procedureType: "query";
1309
+ readonly fn: QueryFn<TInput, TResult, TContext>;
1310
+ readonly queryIdentity?: QueryIdentitySpec<TInput, TContext>;
1311
+ }
1312
+ interface MutationProcedure<TInput, TResult, TContext = unknown, TInternal extends boolean = boolean> extends BaseProcedure<TInput, TResult, "mutation", TContext, TInternal> {
1313
+ readonly procedureType: "mutation";
1314
+ readonly fn: MutationFn<TInput, TResult, TContext>;
1315
+ }
1316
+ interface ActionProcedure<TInput, TResult, TContext = unknown, TInternal extends boolean = boolean> extends BaseProcedure<TInput, TResult, "action", TContext, TInternal> {
1317
+ readonly procedureType: "action";
1318
+ readonly fn: ActionFn<TInput, TResult, TContext>;
1319
+ }
1320
+ /**
1321
+ * A scheduler-triggered, server-only procedure. Runs like an action (full
1322
+ * db, non-transactional, may do external work) but is dispatched by the
1323
+ * server's HTTP job endpoint on a cron tick or a precise one-shot rather
1324
+ * than over the client WebSocket. Always {@link internal}: true, so it is
1325
+ * never reachable via `call`/`subscribe`.
1326
+ */
1327
+ interface JobProcedure<TInput, TResult, TContext = unknown> extends BaseProcedure<TInput, TResult, "job", TContext, true> {
1328
+ readonly procedureType: "job";
1329
+ readonly fn: JobFn<TInput, TResult, TContext>;
1330
+ /**
1331
+ * Cron expression for a recurring job (e.g. `"0 3 * * *"`). Declared crons
1332
+ * are synced to the scheduler at server startup. Omit for a job that is
1333
+ * only ever invoked as a precise one-shot via the scheduler API.
1334
+ */
1335
+ readonly cron?: string;
1336
+ }
1337
+ type AnyProcedure<TContext = unknown> = QueryProcedure<any, any, TContext> | MutationProcedure<any, any, TContext> | ActionProcedure<any, any, TContext> | JobProcedure<any, any, TContext>;
1338
+ /**
1339
+ * Mark a Zod schema as a **partial codegen hint** for the procedure's return
1340
+ * type. Only the fields you specify are used; everything else is inferred from
1341
+ * the handler's TypeScript return type.
1342
+ *
1343
+ * Purely for codegen — the returned schema is the same Zod type you passed in.
1344
+ *
1345
+ * @example
1346
+ * returns: partial(z.object({
1347
+ * total: z.number().int(), // only 'total' overridden, rest inferred from TS
1348
+ * })),
1349
+ */
1350
+ declare function partial<T extends ZodType<any>>(schema: T): T;
1351
+ interface QueryConfig<TInput, TResult, TContext = unknown> {
1352
+ /** Zod schema for input validation */
1353
+ args: ZodType<TInput>;
1354
+ /** The query handler function */
1355
+ handler: QueryFn<TInput, TResult, TContext>;
1356
+ /** Mark as internal (server-only). Default: false */
1357
+ internal?: boolean;
1358
+ /**
1359
+ * Partial Zod schema describing return-type overrides for codegen.
1360
+ * Only the fields you specify are used; everything else is inferred
1361
+ * from the handler's TypeScript return type. Wrap with `partial()`
1362
+ * for explicit partial semantics. Use `.meta({ __genType: "Name" })`
1363
+ * on a Zod object to rename the generated model.
1364
+ */
1365
+ returns?: ZodType<any>;
1366
+ /**
1367
+ * Override the cache/subscription segmentation key for this procedure.
1368
+ * See {@link QueryIdentitySpec}. Omit to keep the default (per-user) behavior.
1369
+ */
1370
+ queryIdentity?: QueryIdentitySpec<TInput, TContext>;
1371
+ }
1372
+ interface MutationConfig<TInput, TResult, TContext = unknown> {
1373
+ /** Zod schema for input validation */
1374
+ args: ZodType<TInput>;
1375
+ /** The mutation handler function */
1376
+ handler: MutationFn<TInput, TResult, TContext>;
1377
+ /** Mark as internal (server-only). Default: false */
1378
+ internal?: boolean;
1379
+ /**
1380
+ * Partial Zod schema describing return-type overrides for codegen.
1381
+ * Only the fields you specify are used; everything else is inferred
1382
+ * from the handler's TypeScript return type.
1383
+ */
1384
+ returns?: ZodType<any>;
1385
+ }
1386
+ interface ActionConfig<TInput, TResult, TContext = unknown> {
1387
+ /** Zod schema for input validation */
1388
+ args: ZodType<TInput>;
1389
+ /** The action handler function */
1390
+ handler: ActionFn<TInput, TResult, TContext>;
1391
+ /** Mark as internal (server-only). Default: false */
1392
+ internal?: boolean;
1393
+ /**
1394
+ * Partial Zod schema describing return-type overrides for codegen.
1395
+ * Only the fields you specify are used; everything else is inferred
1396
+ * from the handler's TypeScript return type.
1397
+ */
1398
+ returns?: ZodType<any>;
1399
+ }
1400
+ interface JobConfig<TInput, TResult, TContext = unknown> {
1401
+ /** Zod schema for the job payload */
1402
+ args: ZodType<TInput>;
1403
+ /** The job handler function */
1404
+ handler: JobFn<TInput, TResult, TContext>;
1405
+ /**
1406
+ * Cron expression for a recurring schedule (e.g. `"0 3 * * *"`). Omit for a
1407
+ * job that is only invoked as a precise one-shot.
1408
+ */
1409
+ cron?: string;
1410
+ }
1411
+ /** Extract input type from a procedure */
1412
+ type InputOf<T> = T extends BaseProcedure<infer I, any, any, any> ? I : never;
1413
+ /** Extract output type from a procedure */
1414
+ type OutputOf<T> = T extends BaseProcedure<any, infer O, any, any> ? O : never;
1415
+ /** Extract procedure type (query/mutation) */
1416
+ type TypeOf<T> = T extends BaseProcedure<any, any, infer Type, any> ? Type : never;
1417
+ /** Extract server context type from a procedure */
1418
+ type ContextOf<T> = T extends BaseProcedure<any, any, any, infer C> ? C : never;
1419
+ /**
1420
+ * Create a query builder with a pre-defined context type.
1421
+ * This allows you to define the context type once and have it inferred
1422
+ * automatically in all your query handlers.
1423
+ *
1424
+ * @example
1425
+ * // Define your server context
1426
+ * interface ServerContext {
1427
+ * auth: { userId: string };
1428
+ * requestId: string;
1429
+ * }
1430
+ *
1431
+ * // Create a typed query builder
1432
+ * const query = createQueryBuilder<ServerContext>();
1433
+ *
1434
+ * // Use it - context type is automatically inferred!
1435
+ * const getUser = query({
1436
+ * args: z.object({ id: z.string() }),
1437
+ * handler: async (ctx, { id }) => {
1438
+ * // ctx.db for database queries
1439
+ * const user = await ctx.db.query(UsersSchema).find(id);
1440
+ * // ctx.context for server context
1441
+ * console.log(ctx.context.requestId);
1442
+ * return user;
1443
+ * }
1444
+ * });
1445
+ */
1446
+ declare function createQueryBuilder<TContext = unknown>(): <TInput, TResult, const TInternal extends boolean = false>(config: QueryConfig<TInput, TResult, TContext> & {
1447
+ internal?: TInternal;
1448
+ }) => QueryProcedure<TInput, TResult, TContext, TInternal>;
1449
+ /**
1450
+ * Create a mutation builder with a pre-defined context type.
1451
+ * This allows you to define the context type once and have it inferred
1452
+ * automatically in all your mutation handlers.
1453
+ *
1454
+ * @example
1455
+ * // Define your server context
1456
+ * interface ServerContext {
1457
+ * auth: { userId: string };
1458
+ * requestId: string;
1459
+ * }
1460
+ *
1461
+ * // Create a typed mutation builder
1462
+ * const mutation = createMutationBuilder<ServerContext>();
1463
+ *
1464
+ * // Use it - context type is automatically inferred!
1465
+ * const createUser = mutation({
1466
+ * args: z.object({ name: z.string() }),
1467
+ * handler: async (ctx, { name }) => {
1468
+ * // ctx.db for mutations
1469
+ * await ctx.db.insert(UsersSchema, id, { name });
1470
+ * // ctx.context for server context
1471
+ * console.log(ctx.context.requestId);
1472
+ * return { success: true };
1473
+ * }
1474
+ * });
1475
+ */
1476
+ declare function createMutationBuilder<TContext = unknown>(): <TInput, TResult, const TInternal extends boolean = false>(config: MutationConfig<TInput, TResult, TContext> & {
1477
+ internal?: TInternal;
1478
+ }) => MutationProcedure<TInput, TResult, TContext, TInternal>;
1479
+ /**
1480
+ * Create an action builder with a pre-defined context type.
1481
+ * Actions have access to the full SupaliveDb for both queries and mutations.
1482
+ *
1483
+ * @example
1484
+ * // Define your server context
1485
+ * interface ServerContext {
1486
+ * auth: { userId: string };
1487
+ * requestId: string;
1488
+ * }
1489
+ *
1490
+ * // Create a typed action builder
1491
+ * const action = createActionBuilder<ServerContext>();
1492
+ *
1493
+ * // Use it - context type is automatically inferred!
1494
+ * const processOrder = action({
1495
+ * args: z.object({ orderId: z.string() }),
1496
+ * handler: async (ctx, { orderId }) => {
1497
+ * // ctx.db for full database access
1498
+ * const order = await ctx.db.query(async (db) => {
1499
+ * return db.query(OrdersSchema).find(orderId);
1500
+ * });
1501
+ * await ctx.db.mutation(async (db) => {
1502
+ * await db.update(OrdersSchema, orderId, { status: "processed" });
1503
+ * });
1504
+ * // ctx.context for server context
1505
+ * console.log(ctx.context.requestId);
1506
+ * return { success: true };
1507
+ * }
1508
+ * });
1509
+ */
1510
+ declare function createActionBuilder<TContext = unknown>(): <TInput, TResult, const TInternal extends boolean = false>(config: ActionConfig<TInput, TResult, TContext> & {
1511
+ internal?: TInternal;
1512
+ }) => ActionProcedure<TInput, TResult, TContext, TInternal>;
1513
+ /**
1514
+ * Create a job builder with a pre-defined context type. A job is a
1515
+ * server-only procedure invoked by the scheduler over HTTP — either on its
1516
+ * declared `cron` schedule or as a precise one-shot enqueued via the
1517
+ * server's job API. Jobs run like actions (full db, non-transactional) and
1518
+ * are always internal, so they are never reachable from a client.
1519
+ *
1520
+ * @example
1521
+ * const job = createJobBuilder<ServerContext>();
1522
+ *
1523
+ * export const cleanupOtps = job({
1524
+ * cron: "0 * * * *", // hourly
1525
+ * args: z.object({}),
1526
+ * handler: async (ctx) => {
1527
+ * await ctx.db.mutation(async (db) => { ... });
1528
+ * return { ok: true };
1529
+ * },
1530
+ * });
1531
+ */
1532
+ declare function createJobBuilder<TContext = unknown>(): <TInput, TResult>(config: JobConfig<TInput, TResult, TContext>) => JobProcedure<TInput, TResult, TContext>;
1533
+ //#endregion
1534
+ //#region src/router/router.d.ts
1535
+ /**
1536
+ * A router maps procedure names (keys) to their definitions.
1537
+ * This is the type that's exported from your app and used by the client.
1538
+ */
1539
+ type Router<TProcedures extends Record<string, AnyProcedure<TContext>>, TContext = unknown> = {
1540
+ _type: "router";
1541
+ procedures: TProcedures;
1542
+ contextName: string;
1543
+ };
1544
+ /**
1545
+ * Inferred AppRouter type from router() call.
1546
+ * Captures the full procedure map for client type inference.
1547
+ */
1548
+ type AppRouter<TProcedures extends Record<string, AnyProcedure<TContext>> = Record<string, AnyProcedure>, TContext = unknown> = Router<TProcedures, TContext>;
1549
+ /** Get query procedures only from a router */
1550
+ type QueryProcedures<T extends Record<string, AnyProcedure>> = { [K in keyof T as T[K] extends {
1551
+ procedureType: "query";
1552
+ } ? K : never]: T[K] };
1553
+ /** Get mutation procedures only from a router */
1554
+ type MutationProcedures<T extends Record<string, AnyProcedure>> = { [K in keyof T as T[K] extends {
1555
+ procedureType: "mutation";
1556
+ } ? K : never]: T[K] };
1557
+ /** Get action procedures only from a router */
1558
+ type ActionProcedures<T extends Record<string, AnyProcedure>> = { [K in keyof T as T[K] extends {
1559
+ procedureType: "action";
1560
+ } ? K : never]: T[K] };
1561
+ /** Get job procedures only from a router */
1562
+ type JobProcedures<T extends Record<string, AnyProcedure>> = { [K in keyof T as T[K] extends {
1563
+ procedureType: "job";
1564
+ } ? K : never]: T[K] };
1565
+ /** Get public (non-internal) procedures - for client type safety */
1566
+ type PublicProcedures<T extends Record<string, AnyProcedure>> = Pick<T, { [K in keyof T]: T[K] extends {
1567
+ internal: true;
1568
+ } ? never : K }[keyof T]>;
1569
+ /** Extract procedure names from a router */
1570
+ type ProcedureNames<T extends Router<any>> = T extends Router<infer P> ? keyof P : never;
1571
+ type RouterConfig<T> = {
1572
+ procedures: T;
1573
+ contextName?: string;
1574
+ };
1575
+ /**
1576
+ * Create a router from procedure definitions.
1577
+ * Procedure names are inferred from the object keys.
1578
+ *
1579
+ * @example
1580
+ * const appRouter = router({
1581
+ * procedures: {
1582
+ * getUser,
1583
+ * createUser,
1584
+ * internalGetAll,
1585
+ * },
1586
+ * });
1587
+ *
1588
+ * export type AppRouter = typeof appRouter;
1589
+ */
1590
+ declare function router<TProcedures extends Record<string, AnyProcedure<any>>, TContext = unknown>(config: RouterConfig<TProcedures>): Router<TProcedures, TContext>;
1591
+ interface RegisteredProcedure<TContext = unknown> {
1592
+ name: string;
1593
+ type: "query" | "mutation" | "action" | "job";
1594
+ internal: boolean;
1595
+ inputSchema: AnyProcedure<TContext>["inputSchema"];
1596
+ fn: AnyProcedure<TContext>["fn"];
1597
+ /** Only present for `type === "query"`. See `QueryIdentitySpec`. */
1598
+ queryIdentity?: false | string | ((serverCtx: TContext | undefined, input: unknown) => string | null | undefined);
1599
+ /** Only present for `type === "job"`. Cron expression for recurring jobs. */
1600
+ cron?: string;
1601
+ }
1602
+ declare function getContextRegistry(inContext: string): ContextRegistry;
1603
+ declare class ContextRegistry {
1604
+ procedureRegistry: Map<string, RegisteredProcedure<any>>;
1605
+ internalProcedureNames: Set<string>;
1606
+ registerProcedure<TContext>(name: string, proc: AnyProcedure<TContext>): void;
1607
+ /** Get a registered procedure by name (runtime lookup) */
1608
+ getProcedure<TContext = unknown>(name: string): RegisteredProcedure<TContext> | undefined;
1609
+ /** Get all registered procedure names */
1610
+ getProcedureNames(): string[];
1611
+ /** Get all registered procedures */
1612
+ getAllProcedures(): Map<string, RegisteredProcedure>;
1613
+ /** Get all registered job procedures (server-only, scheduler-triggered). */
1614
+ getJobProcedures(): RegisteredProcedure[];
1615
+ /** Clear the registry (for testing only) */
1616
+ clearRegistry(): void;
1617
+ markInternalProcedure(name: string): void;
1618
+ isInternalProcedure(name: string): boolean;
1619
+ clearInternalProcedures(): void;
1620
+ }
1621
+ //#endregion
1622
+ //#region src/client/ws_client_manager.d.ts
1623
+ declare class RPCError extends Error {
1624
+ code?: string;
1625
+ constructor(message: string, code?: string);
1626
+ }
1627
+ interface HeartbeatOptions {
1628
+ /**
1629
+ * Close + reconnect when no server message arrives for this long. The
1630
+ * server emits `{type:"ping"}` every ~15s of channel idle, so anything
1631
+ * larger than ~30s leaves comfortable headroom. Default 60_000.
1632
+ */
1633
+ serverInactivityMs?: number;
1634
+ }
1635
+ interface SendThrottleOptions {
1636
+ /** Yield the event loop every N `call()` invocations. 0 disables. Default 100. */
1637
+ everyN?: number;
1638
+ /** Length of the yield in ms. Default 10. */
1639
+ delayMs?: number;
1640
+ }
1641
+ interface WSClientOptions {
1642
+ /** WebSocket URL (e.g. ws://localhost:3000/ws) */
1643
+ url: string;
1644
+ /** Auth token to send after connection */
1645
+ token?: () => Promise<string | undefined>;
1646
+ /** Optional: reconnection timeout in ms (default: 180000 = 3 minutes) */
1647
+ reconnectionTimeout?: number;
1648
+ /** Reconnection options */
1649
+ reconnect?: {
1650
+ /** Enable automatic reconnection (default: true) */enabled?: boolean; /** Max reconnection attempts (default: 5) */
1651
+ maxAttempts?: number; /** Delay between attempts in ms (default: 1000) */
1652
+ delay?: number; /** Exponential backoff multiplier (default: 1.5) */
1653
+ backoff?: number;
1654
+ };
1655
+ /** Server-inactivity watchdog. See {@link HeartbeatOptions.serverInactivityMs}. */
1656
+ heartbeat?: HeartbeatOptions;
1657
+ /**
1658
+ * Yields the event loop for `delayMs` ms after every `everyN`
1659
+ * `call()` invocations. Useful for keeping React renders / GC tasks
1660
+ * scheduled during long synchronous bursts of mutations/actions; the
1661
+ * heartbeat does not depend on this (the server drives it).
1662
+ * Default `{ everyN: 100, delayMs: 10 }`. Set `everyN: 0` to disable.
1663
+ */
1664
+ throttle?: SendThrottleOptions;
1665
+ /** Called when connection is established */
1666
+ onConnect?: () => void;
1667
+ /** Called when connection is lost */
1668
+ onDisconnect?: () => void;
1669
+ /** Called on connection error */
1670
+ onError?: (error: Error) => void;
1671
+ }
1672
+ /**
1673
+ * Public state of the client, surfaced to consumers (React provider, etc.).
1674
+ * - "connecting" — initial connect or reconnect handshake in flight
1675
+ * - "authenticating" — connected, waiting for auth result
1676
+ * - "ready" — connected and auth resolved (authenticated, anonymous, or
1677
+ * explicitly failed — i.e. ready to send calls)
1678
+ * - "disconnected" — currently offline (may auto-retry)
1679
+ */
1680
+ type ClientPublicState = "disconnected" | "connecting" | "authenticating" | "ready";
1681
+ declare class WsClientManager {
1682
+ private ws;
1683
+ private options;
1684
+ private lastSuccessfulConnectionTime;
1685
+ private reconnectionTimeout;
1686
+ private requestId;
1687
+ private pendingRequests;
1688
+ /**
1689
+ * Single source of truth for live subscriptions.
1690
+ *
1691
+ * Keying:
1692
+ * - In-flight subscribe (no subId yet): `_pending:<requestId>`.
1693
+ * - Established: the server-returned canonical `subId`.
1694
+ *
1695
+ * Routing `sub:update` / `sub:gone` is O(1) (`get(subId)`). Subscribe-time
1696
+ * dedup scans `values()` for a matching `localKey` (O(N)), which is cheap
1697
+ * since subscribes happen on component mounts, not in the hot path.
1698
+ */
1699
+ private subscriptions;
1700
+ private queuedCalls;
1701
+ private reconnectAttempts;
1702
+ private reconnectTimer;
1703
+ private connectionState;
1704
+ private authState;
1705
+ /**
1706
+ * Authenticated user id from `auth:success`. Distinct from `queryIdentity`
1707
+ * (server-side cache/sub segmentation key); this is just "who am I logged
1708
+ * in as" for app display purposes. Null while unauthenticated / anonymous.
1709
+ */
1710
+ private authUserId;
1711
+ private explicitlyClosed;
1712
+ private stateListeners;
1713
+ private lastPublicState;
1714
+ private serverInactivityMs;
1715
+ private lastServerMessageAt;
1716
+ private inactivityTimer;
1717
+ private pendingConnectResolve;
1718
+ private pendingConnectReject;
1719
+ private throttleEveryN;
1720
+ private throttleDelayMs;
1721
+ private throttleCounter;
1722
+ private throttling;
1723
+ private visibilityListener;
1724
+ private onlineListener;
1725
+ constructor(options: WSClientOptions);
1726
+ /**
1727
+ * Subscribe to client state transitions. Returns an unsubscribe fn.
1728
+ * The listener is called immediately with the current state.
1729
+ */
1730
+ onState(listener: (s: ClientPublicState) => void): () => void;
1731
+ /** Current public state. */
1732
+ getPublicState(): ClientPublicState;
1733
+ /**
1734
+ * Connect to the WebSocket server.
1735
+ * Returns a promise that resolves when connected and authenticated.
1736
+ */
1737
+ connect(): Promise<void>;
1738
+ /**
1739
+ * Disconnect from the server.
1740
+ */
1741
+ disconnect(): void;
1742
+ /**
1743
+ * Check if connected and authenticated.
1744
+ */
1745
+ isReady(): boolean;
1746
+ /**
1747
+ * Check if authenticated.
1748
+ */
1749
+ isAuthenticated(): boolean;
1750
+ /**
1751
+ * Check if anonymouse.
1752
+ */
1753
+ isAnonymouse(): boolean;
1754
+ /**
1755
+ * The authenticated user's id (from `auth:success`), or null when
1756
+ * unauthenticated / anonymous. Useful for "Logged in as …" display.
1757
+ *
1758
+ * Not to be confused with server-side `queryIdentity`, which is the
1759
+ * cache/subscription segmentation key (resolved entirely on the server).
1760
+ */
1761
+ getAuthUserId(): string | null;
1762
+ /**
1763
+ * Call a procedure (query, mutation, or action).
1764
+ *
1765
+ * If the client is not ready (disconnected or still authenticating), the
1766
+ * call is FIFO-queued and dispatched on the next ready state. The promise
1767
+ * still resolves with the eventual server response.
1768
+ *
1769
+ * Pass `onSend` to be notified when the call actually leaves the queue
1770
+ * (used by `useMutation` to flip `state` from "queued" → "loading").
1771
+ */
1772
+ call(procedure: string, input: unknown, options?: {
1773
+ onSend?: () => void;
1774
+ }): Promise<unknown>;
1775
+ /**
1776
+ * Throttle drain loop. Each iteration: sleep `throttleDelayMs`, then
1777
+ * dispatch up to `throttleEveryN` queued items. Exits as soon as the
1778
+ * queue drains inside a single batch (burst over, back to direct
1779
+ * dispatch on the next `call()`) or the connection goes away
1780
+ * (reconnect path will restart us via `flushQueuedCalls`).
1781
+ */
1782
+ private runThrottleLoop;
1783
+ /**
1784
+ * Issue the call against an established connection. Caller must ensure
1785
+ * `isReady()` before invoking.
1786
+ */
1787
+ private dispatchCall;
1788
+ /**
1789
+ * Flush queued calls in FIFO order. Called once `isReady()` becomes
1790
+ * true. With the throttle enabled, dispatch the first batch
1791
+ * synchronously then hand off to the drain loop so a large
1792
+ * post-reconnect flush respects backpressure instead of dumping 10k
1793
+ * frames in one tick.
1794
+ */
1795
+ private flushQueuedCalls;
1796
+ /**
1797
+ * Re-send `subscribe` for every existing subscription. The subId for each
1798
+ * may legitimately change (e.g. `queryIdentity` was a function of user
1799
+ * identity and the user changed during the disconnect), so we re-key the
1800
+ * unified `subscriptions` Map: snapshot every record, drop them from the
1801
+ * Map, then reinsert under a fresh `_pending:<reqId>` key. Each pending
1802
+ * request's `resolve` rekeys the parked record under the new server-issued
1803
+ * subId so subsequent `sub:update` frames route to the existing
1804
+ * `onUpdate` callback (which the React handle is still holding).
1805
+ */
1806
+ private resubscribeAll;
1807
+ /**
1808
+ * Subscribe to a live query.
1809
+ *
1810
+ * The client does not compute the subId locally — it sends the
1811
+ * (procedure, input) pair and receives the canonical subId on the
1812
+ * subscribe response. This lets the server's per-procedure
1813
+ * `queryIdentity` override be authoritative without forcing the client
1814
+ * to mirror any of the resolution logic.
1815
+ *
1816
+ * Returns the server-assigned subId and an unsubscribe function.
1817
+ */
1818
+ subscribe(procedure: string, input: unknown, serializedInput: string, onUpdate: (data: unknown) => void, onGone?: (reason: string | undefined) => void): Promise<{
1819
+ subId: string;
1820
+ unsubscribe: () => void;
1821
+ }>;
1822
+ private findSubByLocalKey;
1823
+ /** Resolve every joiner waiting on this Subscription with the canonical subId. */
1824
+ private resolveJoiners;
1825
+ /** Reject every joiner waiting on this Subscription with the given error. */
1826
+ private rejectJoiners;
1827
+ private unsubscribeByLocalKey;
1828
+ private handleMessage;
1829
+ /**
1830
+ * Called once the client transitions to a "ready" state on a fresh
1831
+ * connection. Replays live-query subscriptions and flushes any queued
1832
+ * calls in FIFO order.
1833
+ */
1834
+ private afterReady;
1835
+ private handleResponse;
1836
+ private handleSubscriptionUpdate;
1837
+ /**
1838
+ * Handles a `sub:gone` message: the server no longer tracks this
1839
+ * subscription (e.g. it was fully unregistered while we were disconnected
1840
+ * from the sub-manager). Notify the handle and drop the local entry so a
1841
+ * re-subscribe is required to receive further updates.
1842
+ */
1843
+ private handleSubscriptionGone;
1844
+ private handleClose;
1845
+ private handleError;
1846
+ private startInactivityWatchdog;
1847
+ private stopInactivityWatchdog;
1848
+ /**
1849
+ * Close the current WebSocket and schedule a reconnect via `handleClose`.
1850
+ *
1851
+ * Atomically swaps the old socket's event handlers to no-ops BEFORE
1852
+ * `close()` so a frame in flight at the moment of close cannot fire
1853
+ * `handleMessage` into a half-cleaned state — that was the source of
1854
+ * the "browser says socket is alive but client says disconnected" race.
1855
+ */
1856
+ private closeAndReconnect;
1857
+ private installEnvironmentListeners;
1858
+ private removeEnvironmentListeners;
1859
+ private scheduleReconnect;
1860
+ private computePublicState;
1861
+ private emitState;
1862
+ private ensureConnected;
1863
+ private send;
1864
+ private cleanup;
1865
+ private generateRequestId;
1866
+ }
1867
+ //#endregion
1868
+ //#region src/db/types_client_rpc.d.ts
1869
+ interface ErrorMessage {
1870
+ type: "error";
1871
+ id?: string;
1872
+ error: string;
1873
+ code?: string;
1874
+ }
1875
+ declare const AuthMessageSchema: z.ZodObject<{
1876
+ type: z.ZodLiteral<"auth">;
1877
+ data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
1878
+ }, z.core.$strip>;
1879
+ declare const CallMessageSchema: z.ZodObject<{
1880
+ type: z.ZodLiteral<"call">;
1881
+ id: z.ZodString;
1882
+ procedure: z.ZodString;
1883
+ input: z.ZodUnknown;
1884
+ }, z.core.$strip>;
1885
+ declare const SubscribeMessageSchema: z.ZodObject<{
1886
+ type: z.ZodLiteral<"subscribe">;
1887
+ id: z.ZodString;
1888
+ procedure: z.ZodString;
1889
+ input: z.ZodUnknown;
1890
+ }, z.core.$strip>;
1891
+ declare const UnsubscribeMessageSchema: z.ZodObject<{
1892
+ type: z.ZodLiteral<"unsubscribe">;
1893
+ subId: z.ZodString;
1894
+ }, z.core.$strip>;
1895
+ declare const ClientMessageSchema: z.ZodUnion<readonly [z.ZodObject<{
1896
+ type: z.ZodLiteral<"auth">;
1897
+ data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
1898
+ }, z.core.$strip>, z.ZodObject<{
1899
+ type: z.ZodLiteral<"call">;
1900
+ id: z.ZodString;
1901
+ procedure: z.ZodString;
1902
+ input: z.ZodUnknown;
1903
+ }, z.core.$strip>, z.ZodObject<{
1904
+ type: z.ZodLiteral<"subscribe">;
1905
+ id: z.ZodString;
1906
+ procedure: z.ZodString;
1907
+ input: z.ZodUnknown;
1908
+ }, z.core.$strip>, z.ZodObject<{
1909
+ type: z.ZodLiteral<"unsubscribe">;
1910
+ subId: z.ZodString;
1911
+ }, z.core.$strip>]>;
1912
+ type AuthMessage = z.infer<typeof AuthMessageSchema>;
1913
+ type CallMessage = z.infer<typeof CallMessageSchema>;
1914
+ type SubscribeMessage = z.infer<typeof SubscribeMessageSchema>;
1915
+ type UnsubscribeMessage = z.infer<typeof UnsubscribeMessageSchema>;
1916
+ type ClientMessage = z.infer<typeof ClientMessageSchema>;
1917
+ declare const ConnectedMessageSchema: z.ZodObject<{
1918
+ type: z.ZodLiteral<"connected">;
1919
+ sessionId: z.ZodString;
1920
+ }, z.core.$strip>;
1921
+ declare const AuthSuccessMessageSchema: z.ZodObject<{
1922
+ type: z.ZodLiteral<"auth:success">;
1923
+ userId: z.ZodString;
1924
+ extra: z.ZodOptional<z.ZodObject<{}, z.core.$strip>>;
1925
+ }, z.core.$strip>;
1926
+ declare const AuthFailedMessageSchema: z.ZodObject<{
1927
+ type: z.ZodLiteral<"auth:failed">;
1928
+ message: z.ZodString;
1929
+ extra: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
1930
+ }, z.core.$strip>;
1931
+ declare const ResponseMessageSchema: z.ZodObject<{
1932
+ type: z.ZodLiteral<"response">;
1933
+ id: z.ZodString;
1934
+ success: z.ZodBoolean;
1935
+ data: z.ZodOptional<z.ZodUnknown>;
1936
+ error: z.ZodOptional<z.ZodString>;
1937
+ code: z.ZodOptional<z.ZodString>;
1938
+ subId: z.ZodOptional<z.ZodString>;
1939
+ }, z.core.$strip>;
1940
+ declare const SubscriptionUpdateMessageSchema: z.ZodObject<{
1941
+ type: z.ZodLiteral<"sub:update">;
1942
+ subId: z.ZodString;
1943
+ data: z.ZodUnknown;
1944
+ dataHash: z.ZodOptional<z.ZodString>;
1945
+ }, z.core.$strip>;
1946
+ /**
1947
+ * Notifies a client that a subscription is no longer tracked on the server
1948
+ * and will not receive further updates. Sent when, during a sub-manager
1949
+ * recovery cycle, the registration record could not be found (e.g. another
1950
+ * app-server instance fully unregistered the sub while we were disconnected).
1951
+ * The client may choose to re-subscribe or surface the state to the user.
1952
+ */
1953
+ declare const SubscriptionGoneMessageSchema: z.ZodObject<{
1954
+ type: z.ZodLiteral<"sub:gone">;
1955
+ subId: z.ZodString;
1956
+ reason: z.ZodOptional<z.ZodString>;
1957
+ }, z.core.$strip>;
1958
+ /**
1959
+ * Server-driven liveness signal. Sent when the channel has been idle for
1960
+ * the configured app-ping interval (default 15s) and again after every
1961
+ * outbound message. Pure no-op for the client: receiving any message
1962
+ * (including this one) resets the client's inactivity watchdog. The client
1963
+ * does NOT reply.
1964
+ */
1965
+ declare const ServerPingMessageSchema: z.ZodObject<{
1966
+ type: z.ZodLiteral<"ping">;
1967
+ }, z.core.$strip>;
1968
+ declare const ServerMessageSchema: z.ZodUnion<readonly [z.ZodObject<{
1969
+ type: z.ZodLiteral<"connected">;
1970
+ sessionId: z.ZodString;
1971
+ }, z.core.$strip>, z.ZodObject<{
1972
+ type: z.ZodLiteral<"auth:success">;
1973
+ userId: z.ZodString;
1974
+ extra: z.ZodOptional<z.ZodObject<{}, z.core.$strip>>;
1975
+ }, z.core.$strip>, z.ZodObject<{
1976
+ type: z.ZodLiteral<"auth:failed">;
1977
+ message: z.ZodString;
1978
+ extra: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
1979
+ }, z.core.$strip>, z.ZodObject<{
1980
+ type: z.ZodLiteral<"response">;
1981
+ id: z.ZodString;
1982
+ success: z.ZodBoolean;
1983
+ data: z.ZodOptional<z.ZodUnknown>;
1984
+ error: z.ZodOptional<z.ZodString>;
1985
+ code: z.ZodOptional<z.ZodString>;
1986
+ subId: z.ZodOptional<z.ZodString>;
1987
+ }, z.core.$strip>, z.ZodObject<{
1988
+ type: z.ZodLiteral<"sub:update">;
1989
+ subId: z.ZodString;
1990
+ data: z.ZodUnknown;
1991
+ dataHash: z.ZodOptional<z.ZodString>;
1992
+ }, z.core.$strip>, z.ZodObject<{
1993
+ type: z.ZodLiteral<"sub:gone">;
1994
+ subId: z.ZodString;
1995
+ reason: z.ZodOptional<z.ZodString>;
1996
+ }, z.core.$strip>, z.ZodObject<{
1997
+ type: z.ZodLiteral<"ping">;
1998
+ }, z.core.$strip>]>;
1999
+ type ConnectedMessage = z.infer<typeof ConnectedMessageSchema>;
2000
+ type AuthSuccessMessage = z.infer<typeof AuthSuccessMessageSchema>;
2001
+ type AuthFailedMessage = z.infer<typeof AuthFailedMessageSchema>;
2002
+ type ResponseMessage = z.infer<typeof ResponseMessageSchema>;
2003
+ type SubscriptionUpdateMessage = z.infer<typeof SubscriptionUpdateMessageSchema>;
2004
+ type SubscriptionGoneMessage = z.infer<typeof SubscriptionGoneMessageSchema>;
2005
+ type ServerPingMessage = z.infer<typeof ServerPingMessageSchema>;
2006
+ type ServerMessage = z.infer<typeof ServerMessageSchema>;
2007
+ declare class AuthenticationError extends Error {
2008
+ extra: Record<string, unknown>;
2009
+ constructor(message: string, extra?: Record<string, unknown>);
2010
+ }
2011
+ /**
2012
+ * Helper type to check if a procedure is internal.
2013
+ */
2014
+ type IsInternal<T> = T extends {
2015
+ internal: infer I;
2016
+ } ? (I extends true ? true : false) : false;
2017
+ interface Context {
2018
+ requestId: string;
2019
+ /** Authenticated user info */
2020
+ user: {
2021
+ userId: string;
2022
+ };
2023
+ }
2024
+ //#endregion
2025
+ //#region src/client/client.d.ts
2026
+ interface ClientOptions {
2027
+ /** WebSocket URL (e.g. ws://localhost:3000/ws) */
2028
+ url: string;
2029
+ /** Auth Info callback */
2030
+ token?: () => Promise<string>;
2031
+ /** Optional: reconnection timeout in ms (default: 180000 = 3 minutes) */
2032
+ reconnectionTimeout?: number;
2033
+ /** Reconnection options */
2034
+ reconnect?: WSClientOptions["reconnect"];
2035
+ /**
2036
+ * Inactivity watchdog. The client never sends a ping itself; the server
2037
+ * emits `{type:"ping"}` while idle and we close+reconnect if no inbound
2038
+ * message arrives within `serverInactivityMs` (default 60s).
2039
+ */
2040
+ heartbeat?: WSClientOptions["heartbeat"];
2041
+ /**
2042
+ * Yields the event loop for `delayMs` after every `everyN` `call()`
2043
+ * invocations. Useful for keeping React renders / GC tasks scheduled
2044
+ * during long synchronous bursts; not load-bearing for the heartbeat.
2045
+ * Default `{ everyN: 100, delayMs: 10 }`. Set `everyN: 0` to disable.
2046
+ */
2047
+ throttle?: WSClientOptions["throttle"];
2048
+ onConnect?: () => void;
2049
+ onDisConnect?: () => void;
2050
+ }
2051
+ /**
2052
+ * Public state of a live query subscription, exposed via `getState()` and
2053
+ * `onState()` on the handle so React (or any UI) can render a consistent
2054
+ * snapshot via `useSyncExternalStore`.
2055
+ *
2056
+ * - "connecting" — initial subscribe in flight
2057
+ * - "success" — subscribed, last server data is in `data`
2058
+ * - "stale" — was successful, transport dropped; keeping last `data`
2059
+ * until the resubscribe completes
2060
+ * - "loading" — `refetch()` triggered an explicit re-subscribe
2061
+ * - "error" — subscribe failed or server sent `sub:gone`
2062
+ */
2063
+ type LiveQueryStatus = "connecting" | "success" | "stale" | "loading" | "error";
2064
+ interface LiveQueryState<T> {
2065
+ data: T | undefined;
2066
+ status: LiveQueryStatus;
2067
+ error: Error | null;
2068
+ }
2069
+ interface LiveQueryHandle<T> {
2070
+ /** Get current cached data (legacy convenience getter). */
2071
+ get(): T | undefined;
2072
+ /** Snapshot of `{ data, status, error }`. Stable between updates. */
2073
+ getState(): LiveQueryState<T>;
2074
+ /**
2075
+ * Listen for state changes (data, status or error). Returns an
2076
+ * unsubscribe function that removes only this listener — the underlying
2077
+ * server subscription stays alive as long as any listener is attached.
2078
+ *
2079
+ * Suitable for `useSyncExternalStore`.
2080
+ */
2081
+ onState(listener: () => void): () => void;
2082
+ /** Listen for data-only changes. Returns listener-removal fn. */
2083
+ onData(callback: (data: T) => void): () => void;
2084
+ /** Force a re-subscribe round-trip. */
2085
+ refetch(): void;
2086
+ /** Unsubscribe from the server (drops listeners too). */
2087
+ unsubscribe(): void;
2088
+ }
2089
+ /**
2090
+ * Create a fully typed RPC client with WebSocket transport.
2091
+ */
2092
+ declare function createClient<AppRouter extends Router<Record<string, AnyProcedure<TContext>>, TContext>, TContext = unknown, TProcedures extends Record<string, AnyProcedure<TContext>> = AppRouter["procedures"]>(options: ClientOptions): ClientFromProcedures<TProcedures, TContext> & WSClientMethods;
2093
+ /**
2094
+ * WebSocket client methods.
2095
+ */
2096
+ interface WSClientMethods {
2097
+ /** Connect to the WebSocket server */
2098
+ connect(): Promise<void>;
2099
+ /** Disconnect from the server */
2100
+ disconnect(): void;
2101
+ /** Check if connected and authenticated */
2102
+ isReady(): boolean;
2103
+ /** Check if authenticated */
2104
+ isAuthenticated(): boolean;
2105
+ /** Check if anonymouse */
2106
+ isAnonymouse(): boolean;
2107
+ /**
2108
+ * The authenticated user id reported by the server on `auth:success`, or
2109
+ * null when anonymous/unauthenticated. This is the auth-tier identity,
2110
+ * NOT the server-side `queryIdentity` (which is the cache/subscription
2111
+ * segmentation key and is not exposed to the client).
2112
+ */
2113
+ getAuthUserId(): string | null;
2114
+ /** Subscribe to client connection state transitions. Returns unsubscribe fn. */
2115
+ onState(listener: (s: ClientPublicState) => void): () => void;
2116
+ /** Snapshot of the current public state. */
2117
+ getPublicState(): ClientPublicState;
2118
+ }
2119
+ /**
2120
+ * Client type from procedures.
2121
+ * Filters internal procedures and creates appropriate methods.
2122
+ * Query procedures get an additional liveQuery() method for real-time subscriptions.
2123
+ */
2124
+ type ClientFromProcedures<TProcedures extends Record<string, AnyProcedure<TContext>>, TContext = unknown> = { [K in keyof TProcedures as IsInternal<TProcedures[K]> extends true ? never : K]: TProcedures[K] extends {
2125
+ procedureType: "query";
2126
+ } ? {
2127
+ query: (input: InputOf<TProcedures[K]>) => Promise<OutputOf<TProcedures[K]>>;
2128
+ liveQuery: (input: InputOf<TProcedures[K]>) => LiveQueryHandle<OutputOf<TProcedures[K]>>;
2129
+ } : TProcedures[K] extends {
2130
+ procedureType: "mutation";
2131
+ } ? {
2132
+ mutate: (input: InputOf<TProcedures[K]>, opts?: CallOptions) => Promise<OutputOf<TProcedures[K]>>;
2133
+ } : TProcedures[K] extends {
2134
+ procedureType: "action";
2135
+ } ? {
2136
+ action: (input: InputOf<TProcedures[K]>, opts?: CallOptions) => Promise<OutputOf<TProcedures[K]>>;
2137
+ } : never };
2138
+ /**
2139
+ * Optional call options forwarded to the transport layer.
2140
+ */
2141
+ interface CallOptions {
2142
+ /**
2143
+ * Fired the first time the request leaves the queue and is actually
2144
+ * sent on the wire. If the call was already sent immediately (client
2145
+ * was ready at call time), this is invoked synchronously.
2146
+ *
2147
+ * Used by `useMutation` to flip `state` from "queued" → "loading".
2148
+ */
2149
+ onSend?: () => void;
2150
+ }
2151
+ //#endregion
2152
+ //#region src/client/caller_client.d.ts
2153
+ interface CallerOptions<TContext = unknown> {
2154
+ isInternal?: boolean;
2155
+ inContext: string;
2156
+ }
2157
+ /**
2158
+ * Create a server-side caller that bypasses HTTP/WebSocket.
2159
+ *
2160
+ * For in-memory calls, input validation is skipped (data is already a JS object).
2161
+ * Query procedures also get a liveQuery() method for server-side use.
2162
+ */
2163
+ declare function createCaller<AppRouter extends Router<Record<string, AnyProcedure<TContext>>, TContext>, TContext = unknown, TProcedures extends Record<string, AnyProcedure<TContext>> = AppRouter["procedures"]>(options: CallerOptions<any>): CallerFromProcedures<TProcedures, TContext>;
2164
+ /**
2165
+ * Caller type from procedures (includes internal procedures).
2166
+ * Query procedures also have liveQuery() for server-side use.
2167
+ */
2168
+ type CallerFromProcedures<TProcedures extends Record<string, AnyProcedure<TContext>>, TContext = unknown> = { [K in keyof TProcedures]: TProcedures[K] extends {
2169
+ procedureType: "query";
2170
+ } ? {
2171
+ query: (input: InputOf<TProcedures[K]>, serverCtx: TContext) => Promise<OutputOf<TProcedures[K]>>;
2172
+ liveQuery: (input: InputOf<TProcedures[K]>, serverCtx: TContext) => Promise<LiveResult<OutputOf<TProcedures[K]>>>;
2173
+ runQuery: (input: InputOf<TProcedures[K]>, ctx: ParentCtx<TContext>) => Promise<OutputOf<TProcedures[K]>>;
2174
+ } : TProcedures[K] extends {
2175
+ procedureType: "mutation";
2176
+ } ? {
2177
+ mutate: (input: InputOf<TProcedures[K]>, serverCtx: TContext) => Promise<OutputOf<TProcedures[K]>>;
2178
+ runMutation: (input: InputOf<TProcedures[K]>, ctx: ParentCtx<TContext>) => Promise<OutputOf<TProcedures[K]>>;
2179
+ } : TProcedures[K] extends {
2180
+ procedureType: "action";
2181
+ } ? {
2182
+ action: (input: InputOf<TProcedures[K]>, serverCtx: TContext) => Promise<OutputOf<TProcedures[K]>>;
2183
+ } : TProcedures[K] extends {
2184
+ procedureType: "job";
2185
+ } ? {
2186
+ run: (input: InputOf<TProcedures[K]>, serverCtx: TContext) => Promise<OutputOf<TProcedures[K]>>;
2187
+ } : never } & {
2188
+ init: (config: {
2189
+ db: SupaliveDb;
2190
+ storage: ObjectStorage;
2191
+ scheduler: JobClient;
2192
+ }) => Promise<void>;
2193
+ };
2194
+ /**
2195
+ * Caller type from router.
2196
+ */
2197
+ type CallerFromRouter<TRouter extends Router<any, any>> = CallerFromProcedures<TRouter["procedures"]>;
2198
+ //#endregion
2199
+ export { ProcedureNames as $, InvalidateWritesetParams as $n, WriteEntrySchema as $r, IdAndCommitTs as $t, ResponseMessageSchema as A, SchemaCodecs as An, OrPredicate as Ar, partial as At, SubscriptionUpdateMessageSchema as B, trackSchema as Bn, QuerySpec as Br, ScheduledJobDef as Bt, ClientMessageSchema as C, Model as Cn, LeafPredicate as Cr, QueryFn as Ct, ErrorMessage as D, QueryArgs as Dn, NO_RETRY as Dr, createJobBuilder as Dt, Context as E, Prettify as En, MutationResult as Er, createActionBuilder as Et, SubscribeMessage as F, defineComputedField as Fn, PredicateSchema as Fr, JobClient as Ft, RPCError as G, LazyCommitTsParam as Gn, RawRangeRead as Gr, ParamsOf as Gt, UnsubscribeMessageSchema as H, Database as Hn, RangeReadSchema as Hr, sleep as Ht, SubscribeMessageSchema as I, defineSchema as In, QueryCacheEntry as Ir, JobScheduler as It, ActionProcedures as J, RawClient as Jn, RawReadEntrySchema as Jr, _resetGlobalDefs as Jt, WSClientOptions as K, PooledClient as Kn, RawRangeReadSchema as Kr, QueryDefinition as Kt, SubscriptionGoneMessage as L, schemaRegistry as Ln, QueryCacheEntrySchema as Lr, QStashScheduler as Lt, ServerMessageSchema as M, SchemaColumnsOptions as Mn, PointRead as Mr, DevSchedulerOptions as Mt, ServerPingMessage as N, SchemaDefinition as Nn, PointReadSchema as Nr, EnqueueOptions as Nt, IsInternal as O, ReturnLiveQuery as On, OccAbortError as Or, createMutationBuilder as Ot, ServerPingMessageSchema as P, StoredSchemaColumnsOptions as Pn, Predicate as Pr, IncomingJobRequest as Pt, MutationProcedures as Q, AffectedSubscription as Qn, WriteEntry as Qr, TxContext as Qt, SubscriptionGoneMessageSchema as R, shouldTrackSchema as Rn, QueryCacheMetadata as Rr, QStashSchedulerOptions as Rt, ClientMessage as S, InsertData as Sn, DEFAULT_RETRY as Sr, QueryCtx as St, ConnectedMessageSchema as T, OverrideField as Tn, LiveResult as Tr, TypeOf as Tt, ClientPublicState as U, DbQueryResult as Un, RawPointRead as Ur, AnyQueryDef as Ut, UnsubscribeMessage as V, CoreInitLockCtx as Vn, RangeRead as Vr, SupaliveDb as Vt, HeartbeatOptions as W, DbType as Wn, RawPointReadSchema as Wr, DefsToMap as Wt, ContextRegistry as X, TxDatabase as Xn, ReadEntrySchema as Xr, DbReader as Xt, AppRouter as Y, SqlBuilder as Yn, ReadEntry as Yr, defineQuery as Yt, JobProcedures as Z, CacheLayer as Zn, RetryConfig as Zr, DbWriter as Zt, AuthSuccessMessage as _, ComputedFieldConfig as _n, CachedPgMetadataSchema as _r, MutationCtx as _t, CallOptions as a, PaginationClause as an, UnregisterSubscriptionParams as ar, router as at, CallMessage as b, IndexDefinition as bn, CompareOperator as br, OutputOf as bt, LiveQueryHandle as c, jsonContains as cn, UnregisterSubscriptionsParams as cr, ActionFn as ct, WSClientMethods as d, matchesPredicate as dn, UpdateSubscriptionReadSetParamsSchema as dr, ContextOf as dt, WriteOp as ei, JsonContainsOptions as en, InvalidateWritesetParamsSchema as er, PublicProcedures as et, createClient as f, ActionArgs as fn, UpdateSubscriptionReadSetResult as fr, JobConfig as ft, AuthMessageSchema as g, ComputedField as gn, CachedPgMetadata as gr, MutationConfig as gt, AuthMessage as h, ComputedDataType as hn, BigIntSchema as hr, JobProcedure as ht, createCaller as i, normalizeToBytes as ii, OrderDirection as in, RegisterSubscriptionResult as ir, getContextRegistry as it, ServerMessage as j, SchemaColumnMapping as jn, OrPredicateSchema as jr, DevScheduler as jt, ResponseMessage as k, ReturnQuery as kn, OccConflictError as kr, createQueryBuilder as kt, LiveQueryState as l, jsonPathExists as ln, UnregisterSubscriptionsResult as lr, ActionProcedure as lt, AuthFailedMessageSchema as m, ComputedCodec as mn, AndPredicateSchema as mr, JobFn as mt, CallerFromRouter as n, bytesFromJson as ni, JsonOpOptions as nn, RegisterSubscriptionParams as nr, RegisteredProcedure as nt, ClientFromProcedures as o, QueryBuilder as on, UnregisterSubscriptionParamsSchema as or, ActionConfig as ot, AuthFailedMessage as p, ColumnCodec as pn, AndPredicate as pr, JobCtx as pt, WsClientManager as q, PreparedQueries as qn, RawReadEntry as qr, ResultOf as qt, CallerOptions as r, normalizeIdToBytes as ri, OrderByOptions as rn, RegisterSubscriptionParamsSchema as rr, Router as rt, ClientOptions as s, buildPredicateSql as sn, UnregisterSubscriptionResult as sr, ActionCtx as st, CallerFromProcedures as t, WriteOpSchema as ti, JsonHasKeyMultiOptions as tn, InvalidateWritesetResult as tr, QueryProcedures as tt, LiveQueryStatus as u, jsonPathExtract as un, UpdateSubscriptionReadSetParams as ur, AnyProcedure as ut, AuthSuccessMessageSchema as v, DeclarativeIndex as vn, CommitLogEntry as vr, MutationFn as vt, ConnectedMessage as w, MutationArgs as wn, LeafPredicateSchema as wr, QueryProcedure as wt, CallMessageSchema as x, InferSchema as xn, CompareOperatorSchema as xr, QueryConfig as xt, AuthenticationError as y, DefineSchemaConfig as yn, CommitTs as yr, MutationProcedure as yt, SubscriptionUpdateMessage as z, tableNameToId as zn, QueryCacheMetadataSchema as zr, ScheduleHandle as zt };
2200
+ //# sourceMappingURL=index-DKlWIC3k.d.ts.map