@supalive/core 1.17.0 → 1.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index-B3i2G1gr.d.ts +2402 -0
- package/dist/index-B3i2G1gr.d.ts.map +1 -0
- package/dist/index-BHs0EtJk.d.ts +2402 -0
- package/dist/index-BHs0EtJk.d.ts.map +1 -0
- package/dist/index-BMz7jVbX.d.ts +2402 -0
- package/dist/index-BMz7jVbX.d.ts.map +1 -0
- package/dist/index-BuWa503L.d.ts +2445 -0
- package/dist/index-BuWa503L.d.ts.map +1 -0
- package/dist/index-CBIjmPUS.d.ts +2444 -0
- package/dist/index-CBIjmPUS.d.ts.map +1 -0
- package/dist/index-CKo6HvJc.d.ts +2455 -0
- package/dist/index-CKo6HvJc.d.ts.map +1 -0
- package/dist/index-CjkNEwSc.d.ts +2402 -0
- package/dist/index-CjkNEwSc.d.ts.map +1 -0
- package/dist/index-Cng74DL5.d.ts +2404 -0
- package/dist/index-Cng74DL5.d.ts.map +1 -0
- package/dist/index-DShKjpzF.d.ts +2453 -0
- package/dist/index-DShKjpzF.d.ts.map +1 -0
- package/dist/index-Dcxf_Gm-.d.ts +2454 -0
- package/dist/index-Dcxf_Gm-.d.ts.map +1 -0
- package/dist/index-yXV5AMh9.d.ts +2416 -0
- package/dist/index-yXV5AMh9.d.ts.map +1 -0
- package/dist/logger-DrXccWFZ.js +346 -0
- package/dist/logger-DrXccWFZ.js.map +1 -0
- package/dist/mysql-1ENHI0yX.d.ts +114 -0
- package/dist/mysql-1ENHI0yX.d.ts.map +1 -0
- package/dist/mysql-B2u0Ye4x.d.ts +114 -0
- package/dist/mysql-B2u0Ye4x.d.ts.map +1 -0
- package/dist/mysql-BHW-tAqt.d.ts +114 -0
- package/dist/mysql-BHW-tAqt.d.ts.map +1 -0
- package/dist/mysql-C6jg1Vpr.d.ts +114 -0
- package/dist/mysql-C6jg1Vpr.d.ts.map +1 -0
- package/dist/mysql-C_TTCZ8j.d.ts +114 -0
- package/dist/mysql-C_TTCZ8j.d.ts.map +1 -0
- package/dist/mysql-CyzJqrvO.d.ts +114 -0
- package/dist/mysql-CyzJqrvO.d.ts.map +1 -0
- package/dist/mysql-DKR33wfH.d.ts +114 -0
- package/dist/mysql-DKR33wfH.d.ts.map +1 -0
- package/dist/mysql-DcHgRk9f.d.ts +114 -0
- package/dist/mysql-DcHgRk9f.d.ts.map +1 -0
- package/dist/mysql-DnrIJoWL.d.ts +114 -0
- package/dist/mysql-DnrIJoWL.d.ts.map +1 -0
- package/dist/mysql-GsWYd6fG.d.ts +114 -0
- package/dist/mysql-GsWYd6fG.d.ts.map +1 -0
- package/dist/mysql-ygH2EMGn.js +622 -0
- package/dist/mysql-ygH2EMGn.js.map +1 -0
- package/dist/mysql-z9Jefhd6.d.ts +114 -0
- package/dist/mysql-z9Jefhd6.d.ts.map +1 -0
- package/dist/one-shot-query-9mCboWaB.js +565 -0
- package/dist/one-shot-query-9mCboWaB.js.map +1 -0
- package/dist/one-shot-query-B9SjfcCD.js +550 -0
- package/dist/one-shot-query-B9SjfcCD.js.map +1 -0
- package/dist/one-shot-query-BBiv9LGP.js +565 -0
- package/dist/one-shot-query-BBiv9LGP.js.map +1 -0
- package/dist/one-shot-query-Bxz_N-NE.js +563 -0
- package/dist/one-shot-query-Bxz_N-NE.js.map +1 -0
- package/dist/one-shot-query-DE9oQU40.js +550 -0
- package/dist/one-shot-query-DE9oQU40.js.map +1 -0
- package/dist/one-shot-query-adoWqGLs.js +565 -0
- package/dist/one-shot-query-adoWqGLs.js.map +1 -0
- package/dist/overlap-checker-CCgq_Tpa.js +284 -0
- package/dist/overlap-checker-CCgq_Tpa.js.map +1 -0
- package/dist/postgres-B2FLN1Kw.d.ts +118 -0
- package/dist/postgres-B2FLN1Kw.d.ts.map +1 -0
- package/dist/postgres-C7xHWbij.d.ts +118 -0
- package/dist/postgres-C7xHWbij.d.ts.map +1 -0
- package/dist/postgres-CFarR3cB.d.ts +118 -0
- package/dist/postgres-CFarR3cB.d.ts.map +1 -0
- package/dist/postgres-CWVM-KKP.d.ts +118 -0
- package/dist/postgres-CWVM-KKP.d.ts.map +1 -0
- package/dist/postgres-D50xpaQ-.d.ts +118 -0
- package/dist/postgres-D50xpaQ-.d.ts.map +1 -0
- package/dist/postgres-DBMAv_dq.d.ts +118 -0
- package/dist/postgres-DBMAv_dq.d.ts.map +1 -0
- package/dist/postgres-DBuP9ON_.d.ts +118 -0
- package/dist/postgres-DBuP9ON_.d.ts.map +1 -0
- package/dist/postgres-DwiUT_A6.js +867 -0
- package/dist/postgres-DwiUT_A6.js.map +1 -0
- package/dist/postgres-I4sgdBnG.d.ts +118 -0
- package/dist/postgres-I4sgdBnG.d.ts.map +1 -0
- package/dist/postgres-tVdgYJkj.d.ts +118 -0
- package/dist/postgres-tVdgYJkj.d.ts.map +1 -0
- package/dist/postgres-yAn2CF7j.d.ts +118 -0
- package/dist/postgres-yAn2CF7j.d.ts.map +1 -0
- package/dist/postgres-yTjQ-Nxk.d.ts +118 -0
- package/dist/postgres-yTjQ-Nxk.d.ts.map +1 -0
- package/dist/router-DP2ThAwh.js.map +1 -1
- package/dist/src/client/index.d.ts +1 -1
- package/dist/src/client/index.js +46 -51
- package/dist/src/client/index.js.map +1 -1
- package/dist/src/exports/mysql.d.ts +1 -1
- package/dist/src/exports/mysql.js +1 -1
- package/dist/src/exports/postgres.d.ts +1 -1
- package/dist/src/exports/postgres.js +1 -1
- package/dist/src/exports/procedure.d.ts +1 -1
- package/dist/src/exports/schema-sql.d.ts +1 -1
- package/dist/src/exports/server.d.ts +17 -7
- package/dist/src/exports/server.d.ts.map +1 -1
- package/dist/src/exports/server.js +42 -414
- package/dist/src/exports/server.js.map +1 -1
- package/dist/src/exports/sub-manager-worker-entry.js +1 -1
- package/dist/src/exports/types.d.ts +3 -3
- package/dist/src/exports/types.js +1 -1
- package/dist/sub-worker-dispatch-BLujn13f.js +792 -0
- package/dist/sub-worker-dispatch-BLujn13f.js.map +1 -0
- package/dist/sub-worker-dispatch-Cvqarej5.js +826 -0
- package/dist/sub-worker-dispatch-Cvqarej5.js.map +1 -0
- package/dist/sub-worker-dispatch-D-3VPkd4.js +826 -0
- package/dist/sub-worker-dispatch-D-3VPkd4.js.map +1 -0
- package/dist/sub-worker-dispatch-qiSs5Xkm.js.map +1 -1
- package/dist/types_client_rpc-B8jh6MKl.js +154 -0
- package/dist/types_client_rpc-B8jh6MKl.js.map +1 -0
- package/dist/types_client_rpc-BRCAgeyJ.js +155 -0
- package/dist/types_client_rpc-BRCAgeyJ.js.map +1 -0
- package/dist/types_server-B5KQ6PAO.d.ts +692 -0
- package/dist/types_server-B5KQ6PAO.d.ts.map +1 -0
- package/dist/types_server-BCst4TfZ.d.ts +703 -0
- package/dist/types_server-BCst4TfZ.d.ts.map +1 -0
- package/dist/types_server-BJBeSk6n.d.ts +691 -0
- package/dist/types_server-BJBeSk6n.d.ts.map +1 -0
- package/dist/types_server-BXeiSmd8.d.ts +691 -0
- package/dist/types_server-BXeiSmd8.d.ts.map +1 -0
- package/dist/types_server-BYwLkwbC.d.ts +691 -0
- package/dist/types_server-BYwLkwbC.d.ts.map +1 -0
- package/dist/types_server-BnRmctWG.d.ts +699 -0
- package/dist/types_server-BnRmctWG.d.ts.map +1 -0
- package/dist/types_server-Bvrohyc8.d.ts +691 -0
- package/dist/types_server-Bvrohyc8.d.ts.map +1 -0
- package/dist/types_server-C20ibVGu.d.ts +692 -0
- package/dist/types_server-C20ibVGu.d.ts.map +1 -0
- package/dist/types_server-C6oCm9oC.d.ts +691 -0
- package/dist/types_server-C6oCm9oC.d.ts.map +1 -0
- package/dist/types_server-CHJLfdxb.d.ts +691 -0
- package/dist/types_server-CHJLfdxb.d.ts.map +1 -0
- package/dist/types_server-CjjJIQps.d.ts +691 -0
- package/dist/types_server-CjjJIQps.d.ts.map +1 -0
- package/dist/types_server-CjzRPllt.d.ts +691 -0
- package/dist/types_server-CjzRPllt.d.ts.map +1 -0
- package/dist/types_server-Cy4bvdeN.d.ts +691 -0
- package/dist/types_server-Cy4bvdeN.d.ts.map +1 -0
- package/dist/types_server-DnO_fp-F.d.ts +691 -0
- package/dist/types_server-DnO_fp-F.d.ts.map +1 -0
- package/package.json +3 -2
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { Jn as DbQueryResult, Kn as CoreInitLockCtx, Qn as PreparedQueries, Xn as LazyCommitTsParam, Yn as DbType, Zn as PooledClient, er as SqlBuilder, ii as WriteEntry, nr as CacheLayer, qn as Database, ti as ReadEntry, tr as TxDatabase, wr as CommitLogEntry } from "./index-BHs0EtJk.js";
|
|
2
|
+
import { Pool, PoolConfig } from "pg";
|
|
3
|
+
import { Logger } from "pino";
|
|
4
|
+
|
|
5
|
+
//#region src/db/postgres.d.ts
|
|
6
|
+
declare class PgDatabase implements Database {
|
|
7
|
+
constructor(logger: Logger, config: PoolConfig, pool?: Pool | undefined);
|
|
8
|
+
private logger;
|
|
9
|
+
config: PoolConfig;
|
|
10
|
+
private pool;
|
|
11
|
+
readonly sqlBuilder: SqlBuilder;
|
|
12
|
+
readonly dbType: DbType;
|
|
13
|
+
columnTypes: Map<string, Map<string, string>>;
|
|
14
|
+
protected sqlCache: Map<string, string>;
|
|
15
|
+
/**
|
|
16
|
+
* Fetches actual column types from Postgres for `table` and returns a
|
|
17
|
+
* map of DB column name → PG type string (as produced by `format_type`,
|
|
18
|
+
* e.g. `bigint`, `integer`, `character varying(32)`, `text[]`, `jsonb`).
|
|
19
|
+
* No caching here — see {@link getColumnTypes} for the cached path.
|
|
20
|
+
*/
|
|
21
|
+
loadColumnTypesFromPg(table: string): Promise<Map<string, string>>;
|
|
22
|
+
/**
|
|
23
|
+
* Synchronous column-type lookup. The apply path calls this on every
|
|
24
|
+
* batched write, so it can't await — populate the cache via
|
|
25
|
+
* {@link bootstrapColumnTypes} at server start. Throws if `table` is
|
|
26
|
+
* missing (programmer error / bootstrap skipped).
|
|
27
|
+
*/
|
|
28
|
+
getColumnTypes(table: string): Map<string, string> | null;
|
|
29
|
+
/**
|
|
30
|
+
* Eagerly load column types into the in-memory cache. With a Redis
|
|
31
|
+
* client supplied, attempts the cache key first and falls through to
|
|
32
|
+
* Postgres on miss (writing the result back to Redis). This is the
|
|
33
|
+
* "one server queries PG, the rest read from Redis" pattern for cold
|
|
34
|
+
* starts in a multi-instance deploy. Without Redis, always queries PG.
|
|
35
|
+
*
|
|
36
|
+
* Pass `tables` to limit the load to a specific list; otherwise every
|
|
37
|
+
* user table in the connected database is loaded.
|
|
38
|
+
*
|
|
39
|
+
* The Redis cache key should encode whatever invalidates types in your
|
|
40
|
+
* environment (typically a schema version / deploy version). The
|
|
41
|
+
* subscriber in supalive-server.ts is expected to publish a reload
|
|
42
|
+
* signal after migrations and invoke {@link invalidateColumnTypes}.
|
|
43
|
+
*/
|
|
44
|
+
bootstrapColumnTypes(opts: {
|
|
45
|
+
redis?: CacheLayer;
|
|
46
|
+
cacheKey: string;
|
|
47
|
+
tables?: string[];
|
|
48
|
+
}): Promise<void>;
|
|
49
|
+
/**
|
|
50
|
+
* Invalidate cached types (and dependent SQL) for `table`, or the entire
|
|
51
|
+
* cache if `table` is omitted. The Redis-pubsub reload signal in
|
|
52
|
+
* supalive-server.ts is expected to call this on schema changes.
|
|
53
|
+
*/
|
|
54
|
+
private invalidateColumnTypes;
|
|
55
|
+
/** Enumerate the user-defined tables in the connected database — used
|
|
56
|
+
* by bootstrapColumnTypes() when no explicit list is provided. */
|
|
57
|
+
private listUserTables;
|
|
58
|
+
getCoreVersion(): Promise<bigint>;
|
|
59
|
+
getAppMigration(): Promise<bigint>;
|
|
60
|
+
coreMigrationStatements(toVersion: bigint): string[];
|
|
61
|
+
withCoreInitLock(fn: (ctx: CoreInitLockCtx) => Promise<void>): Promise<void>;
|
|
62
|
+
query<T = any>(sql: string, params?: unknown[]): Promise<DbQueryResult<T>>;
|
|
63
|
+
getClient(): Promise<PooledClient>;
|
|
64
|
+
getTransactionClient(): Promise<TxDatabase>;
|
|
65
|
+
/** Internal: replace this instance's caches with shared references from
|
|
66
|
+
* a parent. Used by PgDatabase.getTransactionClient. */
|
|
67
|
+
adoptCaches(columnTypes: Map<string, Map<string, string>>, sqlCache: Map<string, string>): void;
|
|
68
|
+
getLatestSnapshotTimestamp(): Promise<bigint>;
|
|
69
|
+
updateLatestSnapshotTimestamp(commitTs: bigint): Promise<void>;
|
|
70
|
+
getMinSnapshotTimestamp(): Promise<bigint>;
|
|
71
|
+
updateMinSnapshotTimestamp(ts: bigint): Promise<void>;
|
|
72
|
+
getNextTimestamp(): Promise<bigint>;
|
|
73
|
+
attachPrevDataToWriteSet(writeSet: WriteEntry[], readSet: ReadEntry[]): Promise<void>;
|
|
74
|
+
prepareCommitWrites(readSet: ReadEntry[], writeSet: WriteEntry[], commitTs: LazyCommitTsParam): Promise<PreparedQueries>;
|
|
75
|
+
private pgPrepareBatchWrites;
|
|
76
|
+
private pgPrepareInsertSingle;
|
|
77
|
+
private pgPrepareInsertBatch;
|
|
78
|
+
private pgPrepareUpdateSingle;
|
|
79
|
+
private pgPrepareUpdateBatch;
|
|
80
|
+
private pgPrepareDeleteSingle;
|
|
81
|
+
private pgPrepareDeleteBatch;
|
|
82
|
+
private buildOrGetInsertSql;
|
|
83
|
+
private buildOrGetUpdateSql;
|
|
84
|
+
private buildOrGetDeleteSql;
|
|
85
|
+
private pgPrepareCommitLogs;
|
|
86
|
+
/**
|
|
87
|
+
* Point-only OCC check. For each genuine point read, compare the row's
|
|
88
|
+
* current commit_ts against the value captured at read time. A `null`
|
|
89
|
+
* expectedCommitTs means "row didn't exist when we read"; any row found
|
|
90
|
+
* now is a conflict. Reads whose row is being written in this same txn
|
|
91
|
+
* are skipped — the CAS UPDATE/DELETE already validated those.
|
|
92
|
+
*/
|
|
93
|
+
private pgPrepareValidatePointReadsByCommitTs;
|
|
94
|
+
commitWrites(beginTs: bigint, queries: PreparedQueries, commitTs: bigint): Promise<{
|
|
95
|
+
success: boolean;
|
|
96
|
+
}>;
|
|
97
|
+
private pgApplyWrites;
|
|
98
|
+
/**
|
|
99
|
+
* Point-only OCC check. For each genuine point read, compare the row's
|
|
100
|
+
* current commit_ts against the value captured at read time. A `null`
|
|
101
|
+
* expectedCommitTs means "row didn't exist when we read"; any row found
|
|
102
|
+
* now is a conflict. Reads whose row is being written in this same txn
|
|
103
|
+
* are skipped — the CAS UPDATE/DELETE already validated those.
|
|
104
|
+
*/
|
|
105
|
+
private validatePointReadsByCommitTs;
|
|
106
|
+
pruneCommitLogsBefore(ts: bigint): Promise<bigint>;
|
|
107
|
+
getMinCommitLogTs(): Promise<bigint | null>;
|
|
108
|
+
getCommitLogsBetweenTs(beginTs: bigint, endTs: bigint, tableIds: Uint8Array[]): Promise<CommitLogEntry[]>;
|
|
109
|
+
hasCommitForPoints(beginTs: bigint, endTs: bigint, points: {
|
|
110
|
+
tableId: Uint8Array;
|
|
111
|
+
id: Uint8Array;
|
|
112
|
+
}[]): Promise<boolean>;
|
|
113
|
+
getCommitLogsSinceTs(sinceTs: bigint, excludeTs: bigint, tableIds: Uint8Array[]): Promise<CommitLogEntry[]>;
|
|
114
|
+
close(): Promise<void>;
|
|
115
|
+
}
|
|
116
|
+
//#endregion
|
|
117
|
+
export { PgDatabase as t };
|
|
118
|
+
//# sourceMappingURL=postgres-yTjQ-Nxk.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"postgres-yTjQ-Nxk.d.ts","names":[],"sources":["../src/db/postgres.ts"],"mappings":";;;;;cAiBa,UAAA,YAAsB,QAAA;cAE/B,MAAA,EAAQ,MAAA,EACR,MAAA,EAAQ,UAAA,EACR,IAAA,GAAM,IAAA;EAAA,QAWA,MAAA;EACD,MAAA,EAAQ,UAAA;EAAA,QACP,IAAA;EAAA,SACC,UAAA,EAAY,UAAA;EAAA,SACZ,MAAA,EAAQ,MAAA;EAMV,WAAA,EAAa,GAAA,SAAY,GAAA;EAAA,UAGtB,QAAA,EAAU,GAAA;EAHY;;;;;;EAW1B,qBAAA,CAAsB,KAAA,WAAgB,OAAA,CAAQ,GAAA;EAoDhD;;;;;;EA5BJ,cAAA,CAAe,KAAA,WAAgB,GAAA;EAgKoC;;;;;;;;;;;;;;;EAxI7D,oBAAA,CAAqB,IAAA;IACzB,KAAA,GAAQ,UAAA;IACR,QAAA;IACA,MAAA;EAAA,IACE,OAAA;EAgSO;;;;;EAAA,QAtPH,qBAAA;EAm4B+D;;EAAA,QAr3BzD,cAAA;EAUR,cAAA,IAAkB,OAAA;EAOlB,eAAA,IAAmB,OAAA;EAWzB,uBAAA,CAAwB,SAAA;EAUlB,gBAAA,CAAiB,EAAA,GAAK,GAAA,EAAK,eAAA,KAAoB,OAAA,SAAgB,OAAA;EAsC/D,KAAA,UAAe,GAAA,UAAa,MAAA,eAAyB,OAAA,CAAQ,aAAA,CAAc,CAAA;EAe3E,SAAA,IAAa,OAAA,CAAQ,YAAA;EAIrB,oBAAA,IAAwB,OAAA,CAAQ,UAAA;EA/OL;;EA2PjC,WAAA,CACE,WAAA,EAAa,GAAA,SAAY,GAAA,mBACzB,QAAA,EAAU,GAAA;EAMN,0BAAA,IAA8B,OAAA;EAK9B,6BAAA,CAA8B,QAAA,WAAmB,OAAA;EAOjD,uBAAA,IAA2B,OAAA;EAO3B,0BAAA,CAA2B,EAAA,WAAa,OAAA;EAOxC,gBAAA,IAAoB,OAAA;EAuBpB,wBAAA,CAAyB,QAAA,EAAU,UAAA,IAAc,OAAA,EAAS,SAAA,KAAc,OAAA;EAgExE,mBAAA,CACJ,OAAA,EAAS,SAAA,IACT,QAAA,EAAU,UAAA,IACV,QAAA,EAAU,iBAAA,GACT,OAAA,CAAQ,eAAA;EAAA,QAqBG,oBAAA;EAAA,QA2BN,qBAAA;EAAA,QAkBM,oBAAA;EAAA,QA+DN,qBAAA;EAAA,QAwBM,oBAAA;EAAA,QAsEN,qBAAA;EAAA,QAgBM,oBAAA;EAAA,QAiDN,mBAAA;EAAA,QAqBA,mBAAA;EAAA,QA4BA,mBAAA;EAAA,QAcM,mBAAA;EA9rBkB;;;;;;;EAAA,QA4uBxB,qCAAA;EAkDF,YAAA,CACJ,OAAA,UACA,OAAA,EAAS,eAAA,EACT,QAAA,WACC,OAAA;IAAU,OAAA;EAAA;EAAA,QAqCC,aAAA;EA3wBJ;;;;;;;EAAA,QAs3BI,4BAAA;EA0CR,qBAAA,CAAsB,EAAA,WAAa,OAAA;EAQnC,iBAAA,IAAqB,OAAA;EAQrB,sBAAA,CAAuB,OAAA,UAAiB,KAAA,UAAe,QAAA,EAAU,UAAA,KAAe,OAAA,CAAQ,cAAA;EAmBxF,kBAAA,CACJ,OAAA,UACA,KAAA,UACA,MAAA;IAAU,OAAA,EAAS,UAAA;IAAY,EAAA,EAAI,UAAA;EAAA,MAClC,OAAA;EAsBG,oBAAA,CAAqB,OAAA,UAAiB,SAAA,UAAmB,QAAA,EAAU,UAAA,KAAe,OAAA,CAAQ,cAAA;EAmB1F,KAAA,IAAS,OAAA;AAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"router-DP2ThAwh.js","names":[],"sources":["../src/router/procedure.ts","../src/router/router.ts"],"sourcesContent":["import type { ZodType } from \"zod\";\nimport type { Span } from \"@opentelemetry/api\";\nimport type { DbReader, DbWriter } from \"../db/context\";\nimport type { SupaliveDb } from \"../db/realtime_db\";\nimport type { ObjectStorage } from \"../storage\";\nimport type { JobClient } from \"../jobs/scheduler\";\n\n// ─── Context Types ───────────────────────────────────────────────────────────\n\n/**\n * Minimal request-scoped logger exposed as `ctx.log`. Structurally satisfied by\n * a pino logger, so the server hands its own child logger straight through; the\n * interface keeps handler code decoupled from pino. Bound with `reqId`, the\n * procedure name, and (when tracing is enabled) the `traceId`, so every line a\n * handler writes correlates to its request and trace.\n */\nexport interface HandlerLogger {\n debug(...args: any[]): void;\n info(...args: any[]): void;\n warn(...args: any[]): void;\n error(...args: any[]): void;\n}\n\n/**\n * A {@link HandlerLogger} that discards everything. Used where a handler runs\n * without a real logger — e.g. as `ctx.log` in tests — so `ctx.log` stays\n * non-nullable and handler code never null-checks it.\n */\nexport const noopLogger: HandlerLogger = {\n debug() {},\n info() {},\n warn() {},\n error() {},\n};\n\n/**\n * Observability handles present on a handler context. `log` is ALWAYS present:\n * the server binds a request-correlated logger, and direct internal-caller\n * invocations build a per-procedure child logger from the caller's observability —\n * handlers never null-check it.\n */\nexport interface HandlerObservability {\n /** Logger correlated to this operation — request-scoped (reqId + trace id) on\n * the server path, a per-procedure child logger on internal-caller paths. */\n log: HandlerLogger;\n /** The active OpenTelemetry span for this operation. Add attributes/events or\n * parent child spans off it. A non-recording no-op span when tracing is off. */\n span?: Span;\n}\n\n/**\n * Query context passed to query handlers.\n * Contains database reader and user-defined server context.\n */\n/** Options for the per-handler connection-routing methods (see {@link QueryCtx}). */\nexport interface ConnOpts {\n /**\n * Force the PRIMARY (writer) connection even inside a query/action —\n * read-your-writes. On `useReplicaConn` this overrides the replica choice.\n */\n readOwnWrite?: boolean;\n}\n\nexport interface QueryCtx<TContext = unknown> extends HandlerObservability {\n /** Database reader for queries */\n db: DbReader;\n /** User-defined server context (auth, requestId, etc.) */\n serverCtx?: TContext;\n /**\n * Route this query's reads to the PRIMARY (writer) connection. Must be called\n * BEFORE any read (throws otherwise). A no-op when reads already run on primary\n * (no replica configured, or a primary-only path like a live query).\n */\n usePrimaryConn(opts?: ConnOpts): void;\n /**\n * Route this query's reads to the read REPLICA, if one is configured. Must be\n * called BEFORE any read. `{ readOwnWrite: true }` forces the PRIMARY instead.\n */\n useReplicaConn(opts?: ConnOpts): void;\n}\n\n/**\n * No-op connection routing for query paths that genuinely ALWAYS run on the\n * primary — live subscription re-execution and mutation handlers. Spread into\n * the ctx so `ctx.usePrimaryConn()`/`useReplicaConn()` are always callable but\n * inert (there is only ever the primary connection to bind).\n *\n * For a nested `runQuery` that JOINS a parent transaction, use {@link parentConn}\n * instead — there the connection isn't necessarily the primary.\n */\nexport const primaryOnlyConn: Pick<QueryCtx, \"usePrimaryConn\" | \"useReplicaConn\"> = {\n usePrimaryConn: () => { },\n useReplicaConn: () => { },\n};\n\n/**\n * No-op connection routing for a nested `runQuery` that JOINS a parent\n * transaction (a `runQuery` called with a query/mutation `parentCtx`). The knobs\n * always use the PARENT's connection because the read connection is fixed to the\n * parent transaction's — which may be the PRIMARY or the REPLICA, depending on\n * how the parent query was routed.\n *\n * They MUST be inert: a nested query shares the parent's snapshot + readSet, so\n * calling `useConnection` here would either repoint the parent's connection\n * mid-flight (before its first read) or throw (after it) — either way corrupting\n * the parent transaction. A handler that needs to force primary therefore cannot\n * do so while nested under a replica-routed parent (it inherits the replica,\n * which is already safe w.r.t. the client's `minTs` floor); call it via an\n * action-parent `runQuery` instead, which opens a fresh routed read.\n */\nexport const parentConn: Pick<QueryCtx, \"usePrimaryConn\" | \"useReplicaConn\"> = {\n usePrimaryConn: () => { },\n useReplicaConn: () => { },\n};\n\n/**\n * Mutation context passed to mutation handlers.\n * Contains database writer and user-defined server context.\n */\nexport interface MutationCtx<TContext = unknown> extends HandlerObservability {\n /** Database writer for mutations (includes insert/update/delete) */\n db: DbWriter;\n /** User-defined server context (auth, requestId, etc.) */\n serverCtx?: TContext;\n /**\n * No-op on a mutation — writes (and their reads) always run on the primary.\n * Present so a `MutationCtx` stays structurally assignable to `QueryCtx`, i.e.\n * a mutation can reuse a `(ctx: QueryCtx) => …` read helper.\n */\n usePrimaryConn(opts?: ConnOpts): void;\n /** No-op on a mutation (always primary). See {@link usePrimaryConn}. */\n useReplicaConn(opts?: ConnOpts): void;\n}\n\n/**\n * Action context passed to action handlers.\n *\n * Actions are the \"external I/O\" tier: they hold the full {@link SupaliveDb}\n * (queries + mutations) and are the ONLY context that also carries side-effect\n * services — {@link ObjectStorage} for uploads/downloads and a {@link JobClient}\n * for scheduling precise one-shots. Queries/mutations stay pure (db only) so\n * they remain cacheable and transaction-scoped.\n */\nexport interface ActionCtx<TContext = unknown> extends HandlerObservability {\n /** Full database interface for queries and mutations */\n db: SupaliveDb;\n /** Object storage, when the server was configured with one (see\n * `SupaliveServerConfig.storage`); `undefined` otherwise. The usual home\n * for upload/download presigning. */\n storage: ObjectStorage;\n /** Job scheduler client for enqueueing precise one-shots, when the server\n * was configured with a `scheduler`; `undefined` otherwise. Scheduling is\n * network I/O, so it belongs in actions, never inside a DB transaction. */\n scheduler: JobClient;\n /** User-defined server context (auth, requestId, etc.) */\n serverCtx?: TContext;\n}\n\n/**\n * Job context passed to job handlers. Structurally identical to\n * {@link ActionCtx}: a job is a server-only procedure that runs\n * non-transactionally against the full {@link SupaliveDb} and may perform\n * external work, but it is triggered by the scheduler over HTTP (a cron tick\n * or a precise one-shot) rather than by a connected client. `serverCtx` is\n * the system context built by the server's `jobContext` factory.\n */\nexport interface JobCtx<TContext = unknown> extends HandlerObservability {\n /** Full database interface for queries and mutations */\n db: SupaliveDb;\n /** System server context built by the server for scheduler-triggered runs */\n serverCtx?: TContext;\n}\n\n/**\n * Context handed to `caller.<proc>.runQuery` / `.runMutation` when invoking one\n * procedure from inside another. Pass the caller handler's own `ctx` — its `db`\n * carries the parent's live transaction (a {@link DbReader}/{@link DbWriter}) or,\n * inside an action, the full {@link SupaliveDb}. The caller uses this to decide\n * whether the nested call joins the parent's snapshot (queries) or runs as an\n * independent sub-transaction (mutations).\n */\nexport interface ParentCtx<TContext = unknown> {\n db: DbReader | DbWriter | SupaliveDb;\n serverCtx?: TContext | undefined;\n /**\n * The parent handler's own logger, carried through to a nested\n * `runQuery`/`runMutation` so the nested call logs under the SAME logger as\n * its parent (reqId/trace correlation preserved).\n */\n log: HandlerLogger;\n}\n\n/**\n * The slice of the server's {@link Observability} an internal caller needs to\n * build per-call loggers (see `createCaller().init({ obs })`). Structural, so an\n * `Observability` instance satisfies it without the caller depending on it.\n */\nexport interface CallerObservability {\n lazyChildLogger(fields: Record<string, unknown>): HandlerLogger;\n}\n\n// ─── Procedure Types ─────────────────────────────────────────────────────────\n\nexport type QueryFn<TInput, TResult, TContext = unknown> = (\n ctx: QueryCtx<TContext>,\n input: TInput,\n) => Promise<TResult>;\n\nexport type MutationFn<TInput, TResult, TContext = unknown> = (\n ctx: MutationCtx<TContext>,\n input: TInput,\n) => Promise<TResult>;\n\nexport type ActionFn<TInput, TResult, TContext = unknown> = (\n ctx: ActionCtx<TContext>,\n input: TInput,\n) => Promise<TResult>;\n\nexport type JobFn<TInput, TResult, TContext = unknown> = (\n ctx: JobCtx<TContext>,\n input: TInput,\n) => Promise<TResult>;\n\n/**\n * Per-procedure override for the cache/subscription segmentation key.\n *\n * omitted | undefined → fall back to `config.getUserId(serverCtx)` (default)\n * false → no identity in hash; cache/sub shared across all users\n * string → a static identity literal (e.g. \"public\" or a tenant id)\n * function → compute from serverCtx + input (sync)\n *\n * When the result of a query is identical regardless of who calls it, set\n * this to a literal (or `false`) so a single cache entry serves everyone.\n *\n * The function form intentionally takes `serverCtx` (not the full `QueryCtx`)\n * because identity is resolved before any DB read is issued.\n */\nexport type QueryIdentitySpec<TInput, TContext> =\n | false\n | string\n | ((serverCtx: TContext, input: TInput) => string | null | undefined);\n\nexport interface BaseProcedure<\n TInput, TResult,\n TType extends \"query\" | \"mutation\" | \"action\" | \"job\",\n TContext = unknown,\n TInternal extends boolean = boolean\n> {\n readonly _type: \"procedure\";\n readonly procedureType: TType;\n readonly inputSchema: ZodType<TInput>;\n readonly outputSchema?: ZodType<any>;\n readonly fn: QueryFn<TInput, TResult, TContext> | MutationFn<TInput, TResult, TContext> | ActionFn<TInput, TResult, TContext> | JobFn<TInput, TResult, TContext>;\n readonly internal: TInternal;\n}\n\nexport interface QueryProcedure<\n TInput, TResult,\n TContext = unknown,\n TInternal extends boolean = boolean\n> extends BaseProcedure<TInput, TResult, \"query\", TContext, TInternal> {\n readonly procedureType: \"query\";\n readonly fn: QueryFn<TInput, TResult, TContext>;\n readonly queryIdentity?: QueryIdentitySpec<TInput, TContext>;\n}\n\nexport interface MutationProcedure<\n TInput, TResult,\n TContext = unknown,\n TInternal extends boolean = boolean\n> extends BaseProcedure<TInput, TResult, \"mutation\", TContext, TInternal> {\n readonly procedureType: \"mutation\";\n readonly fn: MutationFn<TInput, TResult, TContext>;\n}\n\nexport interface ActionProcedure<\n TInput, TResult,\n TContext = unknown,\n TInternal extends boolean = boolean\n> extends BaseProcedure<TInput, TResult, \"action\", TContext, TInternal> {\n readonly procedureType: \"action\";\n readonly fn: ActionFn<TInput, TResult, TContext>;\n}\n\n/**\n * A scheduler-triggered, server-only procedure. Runs like an action (full\n * db, non-transactional, may do external work) but is dispatched by the\n * server's HTTP job endpoint on a cron tick or a precise one-shot rather\n * than over the client WebSocket. Always {@link internal}: true, so it is\n * never reachable via `call`/`subscribe`.\n */\nexport interface JobProcedure<\n TInput, TResult,\n TContext = unknown,\n> extends BaseProcedure<TInput, TResult, \"job\", TContext, true> {\n readonly procedureType: \"job\";\n readonly fn: JobFn<TInput, TResult, TContext>;\n /**\n * Cron expression for a recurring job (e.g. `\"0 3 * * *\"`). Declared crons\n * are synced to the scheduler at server startup. Omit for a job that is\n * only ever invoked as a precise one-shot via the scheduler API.\n */\n readonly cron?: string;\n}\n\nexport type AnyProcedure<TContext = unknown> =\n | QueryProcedure<any, any, TContext>\n | MutationProcedure<any, any, TContext>\n | ActionProcedure<any, any, TContext>\n | JobProcedure<any, any, TContext>;\n\n// ─── Procedure Configuration Types ───────────────────────────────────────────\n\nexport interface QueryConfig<TInput, TResult, TContext = unknown> {\n /** Zod schema for input validation */\n args: ZodType<TInput>;\n /** The query handler function */\n handler: QueryFn<TInput, TResult, TContext>;\n /** Mark as internal (server-only). Default: false */\n internal?: boolean;\n /**\n * Optional Zod schema describing return-type overrides for codegen.\n * Only the fields you specify are overridden; everything else is inferred\n * from the handler's TypeScript return type. Use `.modelName(\"Name\")`\n * on a Zod object to rename the generated model class.\n */\n returns?: ZodType<any>;\n /**\n * Override the cache/subscription segmentation key for this procedure.\n * See {@link QueryIdentitySpec}. Omit to keep the default (per-user) behavior.\n */\n queryIdentity?: QueryIdentitySpec<TInput, TContext>;\n}\n\nexport interface MutationConfig<TInput, TResult, TContext = unknown> {\n /** Zod schema for input validation */\n args: ZodType<TInput>;\n /** The mutation handler function */\n handler: MutationFn<TInput, TResult, TContext>;\n /** Mark as internal (server-only). Default: false */\n internal?: boolean;\n /**\n * Optional Zod schema describing return-type overrides for codegen.\n * Only the fields you specify are overridden; everything else is inferred\n * from the handler's TypeScript return type.\n */\n returns?: ZodType<any>;\n}\n\nexport interface ActionConfig<TInput, TResult, TContext = unknown> {\n /** Zod schema for input validation */\n args: ZodType<TInput>;\n /** The action handler function */\n handler: ActionFn<TInput, TResult, TContext>;\n /** Mark as internal (server-only). Default: false */\n internal?: boolean;\n /**\n * Optional Zod schema describing return-type overrides for codegen.\n * Only the fields you specify are overridden; everything else is inferred\n * from the handler's TypeScript return type.\n */\n returns?: ZodType<any>;\n}\n\nexport interface JobConfig<TInput, TResult, TContext = unknown> {\n /** Zod schema for the job payload */\n args: ZodType<TInput>;\n /** The job handler function */\n handler: JobFn<TInput, TResult, TContext>;\n /**\n * Cron expression for a recurring schedule (e.g. `\"0 3 * * *\"`). Omit for a\n * job that is only invoked as a precise one-shot.\n */\n cron?: string;\n}\n\n/** Extract input type from a procedure */\nexport type InputOf<T> = T extends BaseProcedure<infer I, any, any, any> ? I : never;\n\n/** Extract output type from a procedure */\nexport type OutputOf<T> = T extends BaseProcedure<any, infer O, any, any> ? O : never;\n\n/** Extract procedure type (query/mutation) */\nexport type TypeOf<T> = T extends BaseProcedure<any, any, infer Type, any> ? Type : never;\n\n/** Extract server context type from a procedure */\nexport type ContextOf<T> = T extends BaseProcedure<any, any, any, infer C> ? C : never;\n\n/**\n * Create a query builder with a pre-defined context type.\n * This allows you to define the context type once and have it inferred\n * automatically in all your query handlers.\n * \n * @example\n * // Define your server context\n * interface ServerContext {\n * auth: { userId: string };\n * requestId: string;\n * }\n * \n * // Create a typed query builder\n * const query = createQueryBuilder<ServerContext>();\n * \n * // Use it - context type is automatically inferred!\n * const getUser = query({\n * args: z.object({ id: z.string() }),\n * handler: async (ctx, { id }) => {\n * // ctx.db for database queries\n * const user = await ctx.db.query(UsersSchema).find(id);\n * // ctx.context for server context\n * console.log(ctx.context.requestId);\n * return user;\n * }\n * });\n */\nexport function createQueryBuilder<TContext = unknown>() {\n return function query<TInput, TResult, const TInternal extends boolean = false>(\n config: QueryConfig<TInput, TResult, TContext> & { internal?: TInternal }\n ): QueryProcedure<TInput, TResult, TContext, TInternal> {\n return {\n _type: \"procedure\",\n procedureType: \"query\",\n inputSchema: config.args,\n outputSchema: config.returns,\n fn: config.handler,\n internal: (config.internal ?? false) as TInternal,\n queryIdentity: config.queryIdentity,\n };\n };\n}\n\n// ─── Mutation Builder Factory ────────────────────────────────────────────────\n\n/**\n * Create a mutation builder with a pre-defined context type.\n * This allows you to define the context type once and have it inferred\n * automatically in all your mutation handlers.\n * \n * @example\n * // Define your server context\n * interface ServerContext {\n * auth: { userId: string };\n * requestId: string;\n * }\n * \n * // Create a typed mutation builder\n * const mutation = createMutationBuilder<ServerContext>();\n * \n * // Use it - context type is automatically inferred!\n * const createUser = mutation({\n * args: z.object({ name: z.string() }),\n * handler: async (ctx, { name }) => {\n * // ctx.db for mutations\n * await ctx.db.insert(UsersSchema, id, { name });\n * // ctx.context for server context\n * console.log(ctx.context.requestId);\n * return { success: true };\n * }\n * });\n */\nexport function createMutationBuilder<TContext = unknown>() {\n return function mutation<TInput, TResult, const TInternal extends boolean = false>(\n config: MutationConfig<TInput, TResult, TContext> & { internal?: TInternal }\n ): MutationProcedure<TInput, TResult, TContext, TInternal> {\n return {\n _type: \"procedure\",\n procedureType: \"mutation\",\n inputSchema: config.args,\n outputSchema: config.returns,\n fn: config.handler,\n internal: (config.internal ?? false) as TInternal,\n };\n };\n}\n\n// ─── Action Builder Factory ──────────────────────────────────────────────────\n\n/**\n * Create an action builder with a pre-defined context type.\n * Actions have access to the full SupaliveDb for both queries and mutations.\n *\n * @example\n * // Define your server context\n * interface ServerContext {\n * auth: { userId: string };\n * requestId: string;\n * }\n *\n * // Create a typed action builder\n * const action = createActionBuilder<ServerContext>();\n *\n * // Use it - context type is automatically inferred!\n * const processOrder = action({\n * args: z.object({ orderId: z.string() }),\n * handler: async (ctx, { orderId }) => {\n * // ctx.db for full database access\n * const order = await ctx.db.query(async (db) => {\n * return db.query(OrdersSchema).find(orderId);\n * });\n * await ctx.db.mutation(async (db) => {\n * await db.update(OrdersSchema, orderId, { status: \"processed\" });\n * });\n * // ctx.context for server context\n * console.log(ctx.context.requestId);\n * return { success: true };\n * }\n * });\n */\nexport function createActionBuilder<TContext = unknown>() {\n return function action<TInput, TResult, const TInternal extends boolean = false>(\n config: ActionConfig<TInput, TResult, TContext> & { internal?: TInternal }\n ): ActionProcedure<TInput, TResult, TContext, TInternal> {\n return {\n _type: \"procedure\",\n procedureType: \"action\",\n inputSchema: config.args,\n outputSchema: config.returns,\n fn: config.handler,\n internal: (config.internal ?? false) as TInternal,\n };\n };\n}\n\n// ─── Job Builder Factory ─────────────────────────────────────────────────────\n\n/**\n * Create a job builder with a pre-defined context type. A job is a\n * server-only procedure invoked by the scheduler over HTTP — either on its\n * declared `cron` schedule or as a precise one-shot enqueued via the\n * server's job API. Jobs run like actions (full db, non-transactional) and\n * are always internal, so they are never reachable from a client.\n *\n * @example\n * const job = createJobBuilder<ServerContext>();\n *\n * export const cleanupOtps = job({\n * cron: \"0 * * * *\", // hourly\n * args: z.object({}),\n * handler: async (ctx) => {\n * await ctx.db.mutation(async (db) => { ... });\n * return { ok: true };\n * },\n * });\n */\nexport function createJobBuilder<TContext = unknown>() {\n return function job<TInput, TResult>(\n config: JobConfig<TInput, TResult, TContext>\n ): JobProcedure<TInput, TResult, TContext> {\n return {\n _type: \"procedure\",\n procedureType: \"job\",\n inputSchema: config.args,\n fn: config.handler,\n internal: true,\n cron: config.cron,\n };\n };\n}","import type { AnyProcedure } from \"./procedure\";\n\n// ─── Router Types ────────────────────────────────────────────────────────────\n\n/**\n * A router maps procedure names (keys) to their definitions.\n * This is the type that's exported from your app and used by the client.\n */\nexport type Router<TProcedures extends Record<string, AnyProcedure<TContext>>, TContext = unknown> = {\n _type: \"router\";\n procedures: TProcedures;\n contextName: string;\n};\n\n/**\n * Inferred AppRouter type from router() call.\n * Captures the full procedure map for client type inference.\n */\nexport type AppRouter<\n TProcedures extends Record<string, AnyProcedure<TContext>> = Record<string, AnyProcedure>,\n TContext = unknown\n> = Router<TProcedures, TContext>;\n\n// ─── Type Helpers for Client ─────────────────────────────────────────────────\n\n/** Get query procedures only from a router */\nexport type QueryProcedures<T extends Record<string, AnyProcedure>> = {\n [K in keyof T as T[K] extends { procedureType: \"query\" } ? K : never]: T[K];\n};\n\n/** Get mutation procedures only from a router */\nexport type MutationProcedures<T extends Record<string, AnyProcedure>> = {\n [K in keyof T as T[K] extends { procedureType: \"mutation\" } ? K : never]: T[K];\n};\n\n/** Get action procedures only from a router */\nexport type ActionProcedures<T extends Record<string, AnyProcedure>> = {\n [K in keyof T as T[K] extends { procedureType: \"action\" } ? K : never]: T[K];\n};\n\n/** Get job procedures only from a router */\nexport type JobProcedures<T extends Record<string, AnyProcedure>> = {\n [K in keyof T as T[K] extends { procedureType: \"job\" } ? K : never]: T[K];\n};\n\n/** Get public (non-internal) procedures - for client type safety */\nexport type PublicProcedures<T extends Record<string, AnyProcedure>> = Pick<\n T,\n { [K in keyof T]: T[K] extends { internal: true } ? never : K }[keyof T]\n>;\n\n/** Extract procedure names from a router */\nexport type ProcedureNames<T extends Router<any>> =\n T extends Router<infer P> ? keyof P : never;\n\nexport type RouterConfig<T> = {\n procedures: T;\n contextName?: string;\n};\n\n/**\n* Create a router from procedure definitions.\n* Procedure names are inferred from the object keys.\n* \n* @example\n* const appRouter = router({\n* procedures: {\n* getUser,\n* createUser,\n* internalGetAll,\n* },\n* });\n* \n* export type AppRouter = typeof appRouter;\n*/\nexport function router<TProcedures extends Record<string, AnyProcedure<any>>, TContext = unknown>(\n config: RouterConfig<TProcedures>,\n): Router<TProcedures, TContext> {\n const registry = getContextRegistry(config.contextName ?? \"default\");\n\n // Register all procedures at router creation time\n for (const [name, proc] of Object.entries(config.procedures)) {\n registry.registerProcedure(name, proc);\n }\n\n\n return {\n _type: \"router\",\n procedures: config.procedures,\n contextName: config.contextName ?? \"default\",\n };\n}\n\nexport interface RegisteredProcedure<TContext = unknown> {\n name: string;\n type: \"query\" | \"mutation\" | \"action\" | \"job\";\n internal: boolean;\n inputSchema: AnyProcedure<TContext>[\"inputSchema\"];\n fn: AnyProcedure<TContext>[\"fn\"];\n /** Only present for `type === \"query\"`. See `QueryIdentitySpec`. */\n queryIdentity?: false | string | ((serverCtx: TContext | undefined, input: unknown) => string | null | undefined);\n /** Only present for `type === \"job\"`. Cron expression for recurring jobs. */\n cron?: string;\n}\n\n\nconst contextRegistry = new Map<string, ContextRegistry>();\n\nexport function getContextRegistry(inContext: string): ContextRegistry {\n let registry = contextRegistry.get(inContext);\n if (!registry) {\n registry = new ContextRegistry();\n contextRegistry.set(inContext, registry);\n }\n return registry;\n}\n\nexport class ContextRegistry {\n procedureRegistry = new Map<string, RegisteredProcedure<any>>();\n internalProcedureNames = new Set<string>();\n\n registerProcedure<TContext>(name: string, proc: AnyProcedure<TContext>): void {\n if (this.procedureRegistry.has(name)) {\n throw new Error(\n `[router] Procedure \"${name}\" is already registered. ` +\n `Each procedure name must be unique across the application.`\n );\n }\n\n // Track internal procedures by name\n if (proc.internal) {\n this.markInternalProcedure(name);\n }\n\n const queryIdentity =\n proc.procedureType === \"query\"\n ? (proc as { queryIdentity?: RegisteredProcedure<TContext>[\"queryIdentity\"] }).queryIdentity\n : undefined;\n\n const cron =\n proc.procedureType === \"job\"\n ? (proc as { cron?: string }).cron\n : undefined;\n\n this.procedureRegistry.set(name, {\n name,\n type: proc.procedureType,\n internal: proc.internal,\n inputSchema: proc.inputSchema,\n fn: proc.fn,\n queryIdentity,\n cron,\n });\n }\n\n /** Get a registered procedure by name (runtime lookup) */\n getProcedure<TContext = unknown>(name: string): RegisteredProcedure<TContext> | undefined {\n return this.procedureRegistry.get(name);\n }\n\n /** Get all registered procedure names */\n getProcedureNames(): string[] {\n return [...this.procedureRegistry.keys()];\n }\n\n /** Get all registered procedures */\n getAllProcedures(): Map<string, RegisteredProcedure> {\n return new Map(this.procedureRegistry);\n }\n\n /** Get all registered job procedures (server-only, scheduler-triggered). */\n getJobProcedures(): RegisteredProcedure[] {\n return [...this.procedureRegistry.values()].filter((p) => p.type === \"job\");\n }\n\n /** Clear the registry (for testing only) */\n clearRegistry(): void {\n this.procedureRegistry.clear();\n this.clearInternalProcedures();\n }\n\n markInternalProcedure(name: string): void {\n this.internalProcedureNames.add(name);\n }\n\n isInternalProcedure(name: string): boolean {\n return this.internalProcedureNames.has(name);\n }\n\n clearInternalProcedures(): void {\n this.internalProcedureNames.clear();\n }\n}"],"mappings":"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"}
|
|
1
|
+
{"version":3,"file":"router-DP2ThAwh.js","names":[],"sources":["../src/router/procedure.ts","../src/router/router.ts"],"sourcesContent":["import type { ZodType } from \"zod\";\nimport type { Span } from \"@opentelemetry/api\";\nimport type { DbReader, DbWriter } from \"../db/context\";\nimport type { SupaliveDb } from \"../db/realtime_db\";\nimport type { ObjectStorage } from \"../storage\";\nimport type { JobClient } from \"../jobs/scheduler\";\nimport pino from \"pino\";\n\n// ─── Context Types ───────────────────────────────────────────────────────────\n\n/**\n * Minimal request-scoped logger exposed as `ctx.log`. Structurally satisfied by\n * a pino logger, so the server hands its own child logger straight through; the\n * interface keeps handler code decoupled from pino. Bound with `reqId`, the\n * procedure name, and (when tracing is enabled) the `traceId`, so every line a\n * handler writes correlates to its request and trace.\n */\nexport interface HandlerLogger {\n debug: pino.LogFn;\n info: pino.LogFn;\n warn: pino.LogFn;\n error: pino.LogFn;\n}\n\n/**\n * A {@link HandlerLogger} that discards everything. Used where a handler runs\n * without a real logger — e.g. as `ctx.log` in tests — so `ctx.log` stays\n * non-nullable and handler code never null-checks it.\n */\nexport const noopLogger: HandlerLogger = {\n debug() { },\n info() { },\n warn() { },\n error() { },\n};\n\n/**\n * Observability handles present on a handler context. `log` is ALWAYS present:\n * the server binds a request-correlated logger, and direct internal-caller\n * invocations build a per-procedure child logger from the caller's observability —\n * handlers never null-check it.\n */\nexport interface HandlerObservability {\n /** Logger correlated to this operation — request-scoped (reqId + trace id) on\n * the server path, a per-procedure child logger on internal-caller paths. */\n log: HandlerLogger;\n /** The active OpenTelemetry span for this operation. Add attributes/events or\n * parent child spans off it. A non-recording no-op span when tracing is off. */\n span?: Span;\n}\n\n/**\n * Query context passed to query handlers.\n * Contains database reader and user-defined server context.\n */\n/** Options for the per-handler connection-routing methods (see {@link QueryCtx}). */\nexport interface ConnOpts {\n /**\n * Force the PRIMARY (writer) connection even inside a query/action —\n * read-your-writes. On `useReplicaConn` this overrides the replica choice.\n */\n readOwnWrite?: boolean;\n}\n\nexport interface QueryCtx<TContext = unknown> extends HandlerObservability {\n /** Database reader for queries */\n db: DbReader;\n /** User-defined server context (auth, requestId, etc.) */\n serverCtx?: TContext;\n /**\n * Route this query's reads to the PRIMARY (writer) connection. Must be called\n * BEFORE any read (throws otherwise). A no-op when reads already run on primary\n * (no replica configured, or a primary-only path like a live query).\n */\n usePrimaryConn(opts?: ConnOpts): void;\n /**\n * Route this query's reads to the read REPLICA, if one is configured. Must be\n * called BEFORE any read. `{ readOwnWrite: true }` forces the PRIMARY instead.\n */\n useReplicaConn(opts?: ConnOpts): void;\n}\n\n/**\n * No-op connection routing for query paths that genuinely ALWAYS run on the\n * primary — live subscription re-execution and mutation handlers. Spread into\n * the ctx so `ctx.usePrimaryConn()`/`useReplicaConn()` are always callable but\n * inert (there is only ever the primary connection to bind).\n *\n * For a nested `runQuery` that JOINS a parent transaction, use {@link parentConn}\n * instead — there the connection isn't necessarily the primary.\n */\nexport const primaryOnlyConn: Pick<QueryCtx, \"usePrimaryConn\" | \"useReplicaConn\"> = {\n usePrimaryConn: () => { },\n useReplicaConn: () => { },\n};\n\n/**\n * No-op connection routing for a nested `runQuery` that JOINS a parent\n * transaction (a `runQuery` called with a query/mutation `parentCtx`). The knobs\n * always use the PARENT's connection because the read connection is fixed to the\n * parent transaction's — which may be the PRIMARY or the REPLICA, depending on\n * how the parent query was routed.\n *\n * They MUST be inert: a nested query shares the parent's snapshot + readSet, so\n * calling `useConnection` here would either repoint the parent's connection\n * mid-flight (before its first read) or throw (after it) — either way corrupting\n * the parent transaction. A handler that needs to force primary therefore cannot\n * do so while nested under a replica-routed parent (it inherits the replica,\n * which is already safe w.r.t. the client's `minTs` floor); call it via an\n * action-parent `runQuery` instead, which opens a fresh routed read.\n */\nexport const parentConn: Pick<QueryCtx, \"usePrimaryConn\" | \"useReplicaConn\"> = {\n usePrimaryConn: () => { },\n useReplicaConn: () => { },\n};\n\n/**\n * Mutation context passed to mutation handlers.\n * Contains database writer and user-defined server context.\n */\nexport interface MutationCtx<TContext = unknown> extends HandlerObservability {\n /** Database writer for mutations (includes insert/update/delete) */\n db: DbWriter;\n /** User-defined server context (auth, requestId, etc.) */\n serverCtx?: TContext;\n /**\n * No-op on a mutation — writes (and their reads) always run on the primary.\n * Present so a `MutationCtx` stays structurally assignable to `QueryCtx`, i.e.\n * a mutation can reuse a `(ctx: QueryCtx) => …` read helper.\n */\n usePrimaryConn(opts?: ConnOpts): void;\n /** No-op on a mutation (always primary). See {@link usePrimaryConn}. */\n useReplicaConn(opts?: ConnOpts): void;\n}\n\n/**\n * Action context passed to action handlers.\n *\n * Actions are the \"external I/O\" tier: they hold the full {@link SupaliveDb}\n * (queries + mutations) and are the ONLY context that also carries side-effect\n * services — {@link ObjectStorage} for uploads/downloads and a {@link JobClient}\n * for scheduling precise one-shots. Queries/mutations stay pure (db only) so\n * they remain cacheable and transaction-scoped.\n */\nexport interface ActionCtx<TContext = unknown> extends HandlerObservability {\n /** Full database interface for queries and mutations */\n db: SupaliveDb;\n /** Object storage, when the server was configured with one (see\n * `SupaliveServerConfig.storage`); `undefined` otherwise. The usual home\n * for upload/download presigning. */\n storage: ObjectStorage;\n /** Job scheduler client for enqueueing precise one-shots, when the server\n * was configured with a `scheduler`; `undefined` otherwise. Scheduling is\n * network I/O, so it belongs in actions, never inside a DB transaction. */\n scheduler: JobClient;\n /** User-defined server context (auth, requestId, etc.) */\n serverCtx?: TContext;\n}\n\n/**\n * Job context passed to job handlers. Structurally identical to\n * {@link ActionCtx}: a job is a server-only procedure that runs\n * non-transactionally against the full {@link SupaliveDb} and may perform\n * external work, but it is triggered by the scheduler over HTTP (a cron tick\n * or a precise one-shot) rather than by a connected client. `serverCtx` is\n * the system context built by the server's `jobContext` factory.\n */\nexport interface JobCtx<TContext = unknown> extends HandlerObservability {\n /** Full database interface for queries and mutations */\n db: SupaliveDb;\n /** System server context built by the server for scheduler-triggered runs */\n serverCtx?: TContext;\n}\n\n/**\n * Context handed to `caller.<proc>.runQuery` / `.runMutation` when invoking one\n * procedure from inside another. Pass the caller handler's own `ctx` — its `db`\n * carries the parent's live transaction (a {@link DbReader}/{@link DbWriter}) or,\n * inside an action, the full {@link SupaliveDb}. The caller uses this to decide\n * whether the nested call joins the parent's snapshot (queries) or runs as an\n * independent sub-transaction (mutations).\n */\nexport interface ParentCtx<TContext = unknown> {\n db: DbReader | DbWriter | SupaliveDb;\n serverCtx?: TContext | undefined;\n /**\n * The parent handler's own logger, carried through to a nested\n * `runQuery`/`runMutation` so the nested call logs under the SAME logger as\n * its parent (reqId/trace correlation preserved).\n */\n log: HandlerLogger;\n /**\n * The parent handler's own span, carried through to a nested\n * `runQuery`/`runMutation`. Used ONLY as an explicit fallback parent: the\n * nested call normally links implicitly through the ambient OTEL context\n * (the parent handler already runs inside its operation span's context).\n * This span is consulted only when the ambient context is root — e.g. a\n * detached/fire-and-forget internal call.\n */\n span?: Span;\n}\n\n/**\n * The slice of the server's {@link Observability} an internal caller needs to\n * build per-call loggers (see `createCaller().init({ obs })`). Structural, so an\n * `Observability` instance satisfies it without the caller depending on it.\n */\nexport interface CallerObservability {\n lazyChildLogger(fields: Record<string, unknown>): HandlerLogger;\n}\n\n// ─── Procedure Types ─────────────────────────────────────────────────────────\n\nexport type QueryFn<TInput, TResult, TContext = unknown> = (\n ctx: QueryCtx<TContext>,\n input: TInput,\n) => Promise<TResult>;\n\nexport type MutationFn<TInput, TResult, TContext = unknown> = (\n ctx: MutationCtx<TContext>,\n input: TInput,\n) => Promise<TResult>;\n\nexport type ActionFn<TInput, TResult, TContext = unknown> = (\n ctx: ActionCtx<TContext>,\n input: TInput,\n) => Promise<TResult>;\n\nexport type JobFn<TInput, TResult, TContext = unknown> = (\n ctx: JobCtx<TContext>,\n input: TInput,\n) => Promise<TResult>;\n\n/**\n * Per-procedure override for the cache/subscription segmentation key.\n *\n * omitted | undefined → fall back to `config.getUserId(serverCtx)` (default)\n * false → no identity in hash; cache/sub shared across all users\n * string → a static identity literal (e.g. \"public\" or a tenant id)\n * function → compute from serverCtx + input (sync)\n *\n * When the result of a query is identical regardless of who calls it, set\n * this to a literal (or `false`) so a single cache entry serves everyone.\n *\n * The function form intentionally takes `serverCtx` (not the full `QueryCtx`)\n * because identity is resolved before any DB read is issued.\n */\nexport type QueryIdentitySpec<TInput, TContext> =\n | false\n | string\n | ((serverCtx: TContext, input: TInput) => string | null | undefined);\n\nexport interface BaseProcedure<\n TInput, TResult,\n TType extends \"query\" | \"mutation\" | \"action\" | \"job\",\n TContext = unknown,\n TInternal extends boolean = boolean\n> {\n readonly _type: \"procedure\";\n readonly procedureType: TType;\n readonly inputSchema: ZodType<TInput>;\n readonly outputSchema?: ZodType<any>;\n readonly fn: QueryFn<TInput, TResult, TContext> | MutationFn<TInput, TResult, TContext> | ActionFn<TInput, TResult, TContext> | JobFn<TInput, TResult, TContext>;\n readonly internal: TInternal;\n}\n\nexport interface QueryProcedure<\n TInput, TResult,\n TContext = unknown,\n TInternal extends boolean = boolean\n> extends BaseProcedure<TInput, TResult, \"query\", TContext, TInternal> {\n readonly procedureType: \"query\";\n readonly fn: QueryFn<TInput, TResult, TContext>;\n readonly queryIdentity?: QueryIdentitySpec<TInput, TContext>;\n}\n\nexport interface MutationProcedure<\n TInput, TResult,\n TContext = unknown,\n TInternal extends boolean = boolean\n> extends BaseProcedure<TInput, TResult, \"mutation\", TContext, TInternal> {\n readonly procedureType: \"mutation\";\n readonly fn: MutationFn<TInput, TResult, TContext>;\n}\n\nexport interface ActionProcedure<\n TInput, TResult,\n TContext = unknown,\n TInternal extends boolean = boolean\n> extends BaseProcedure<TInput, TResult, \"action\", TContext, TInternal> {\n readonly procedureType: \"action\";\n readonly fn: ActionFn<TInput, TResult, TContext>;\n}\n\n/**\n * A scheduler-triggered, server-only procedure. Runs like an action (full\n * db, non-transactional, may do external work) but is dispatched by the\n * server's HTTP job endpoint on a cron tick or a precise one-shot rather\n * than over the client WebSocket. Always {@link internal}: true, so it is\n * never reachable via `call`/`subscribe`.\n */\nexport interface JobProcedure<\n TInput, TResult,\n TContext = unknown,\n> extends BaseProcedure<TInput, TResult, \"job\", TContext, true> {\n readonly procedureType: \"job\";\n readonly fn: JobFn<TInput, TResult, TContext>;\n /**\n * Cron expression for a recurring job (e.g. `\"0 3 * * *\"`). Declared crons\n * are synced to the scheduler at server startup. Omit for a job that is\n * only ever invoked as a precise one-shot via the scheduler API.\n */\n readonly cron?: string;\n}\n\nexport type AnyProcedure<TContext = unknown> =\n | QueryProcedure<any, any, TContext>\n | MutationProcedure<any, any, TContext>\n | ActionProcedure<any, any, TContext>\n | JobProcedure<any, any, TContext>;\n\n// ─── Procedure Configuration Types ───────────────────────────────────────────\n\nexport interface QueryConfig<TInput, TResult, TContext = unknown> {\n /** Zod schema for input validation */\n args: ZodType<TInput>;\n /** The query handler function */\n handler: QueryFn<TInput, TResult, TContext>;\n /** Mark as internal (server-only). Default: false */\n internal?: boolean;\n /**\n * Optional Zod schema describing return-type overrides for codegen.\n * Only the fields you specify are overridden; everything else is inferred\n * from the handler's TypeScript return type. Use `.modelName(\"Name\")`\n * on a Zod object to rename the generated model class.\n */\n returns?: ZodType<any>;\n /**\n * Override the cache/subscription segmentation key for this procedure.\n * See {@link QueryIdentitySpec}. Omit to keep the default (per-user) behavior.\n */\n queryIdentity?: QueryIdentitySpec<TInput, TContext>;\n}\n\nexport interface MutationConfig<TInput, TResult, TContext = unknown> {\n /** Zod schema for input validation */\n args: ZodType<TInput>;\n /** The mutation handler function */\n handler: MutationFn<TInput, TResult, TContext>;\n /** Mark as internal (server-only). Default: false */\n internal?: boolean;\n /**\n * Optional Zod schema describing return-type overrides for codegen.\n * Only the fields you specify are overridden; everything else is inferred\n * from the handler's TypeScript return type.\n */\n returns?: ZodType<any>;\n}\n\nexport interface ActionConfig<TInput, TResult, TContext = unknown> {\n /** Zod schema for input validation */\n args: ZodType<TInput>;\n /** The action handler function */\n handler: ActionFn<TInput, TResult, TContext>;\n /** Mark as internal (server-only). Default: false */\n internal?: boolean;\n /**\n * Optional Zod schema describing return-type overrides for codegen.\n * Only the fields you specify are overridden; everything else is inferred\n * from the handler's TypeScript return type.\n */\n returns?: ZodType<any>;\n}\n\nexport interface JobConfig<TInput, TResult, TContext = unknown> {\n /** Zod schema for the job payload */\n args: ZodType<TInput>;\n /** The job handler function */\n handler: JobFn<TInput, TResult, TContext>;\n /**\n * Cron expression for a recurring schedule (e.g. `\"0 3 * * *\"`). Omit for a\n * job that is only invoked as a precise one-shot.\n */\n cron?: string;\n}\n\n/** Extract input type from a procedure */\nexport type InputOf<T> = T extends BaseProcedure<infer I, any, any, any> ? I : never;\n\n/** Extract output type from a procedure */\nexport type OutputOf<T> = T extends BaseProcedure<any, infer O, any, any> ? O : never;\n\n/** Extract procedure type (query/mutation) */\nexport type TypeOf<T> = T extends BaseProcedure<any, any, infer Type, any> ? Type : never;\n\n/** Extract server context type from a procedure */\nexport type ContextOf<T> = T extends BaseProcedure<any, any, any, infer C> ? C : never;\n\n/**\n * Create a query builder with a pre-defined context type.\n * This allows you to define the context type once and have it inferred\n * automatically in all your query handlers.\n * \n * @example\n * // Define your server context\n * interface ServerContext {\n * auth: { userId: string };\n * requestId: string;\n * }\n * \n * // Create a typed query builder\n * const query = createQueryBuilder<ServerContext>();\n * \n * // Use it - context type is automatically inferred!\n * const getUser = query({\n * args: z.object({ id: z.string() }),\n * handler: async (ctx, { id }) => {\n * // ctx.db for database queries\n * const user = await ctx.db.query(UsersSchema).find(id);\n * // ctx.context for server context\n * console.log(ctx.context.requestId);\n * return user;\n * }\n * });\n */\nexport function createQueryBuilder<TContext = unknown>() {\n return function query<TInput, TResult, const TInternal extends boolean = false>(\n config: QueryConfig<TInput, TResult, TContext> & { internal?: TInternal }\n ): QueryProcedure<TInput, TResult, TContext, TInternal> {\n return {\n _type: \"procedure\",\n procedureType: \"query\",\n inputSchema: config.args,\n outputSchema: config.returns,\n fn: config.handler,\n internal: (config.internal ?? false) as TInternal,\n queryIdentity: config.queryIdentity,\n };\n };\n}\n\n// ─── Mutation Builder Factory ────────────────────────────────────────────────\n\n/**\n * Create a mutation builder with a pre-defined context type.\n * This allows you to define the context type once and have it inferred\n * automatically in all your mutation handlers.\n * \n * @example\n * // Define your server context\n * interface ServerContext {\n * auth: { userId: string };\n * requestId: string;\n * }\n * \n * // Create a typed mutation builder\n * const mutation = createMutationBuilder<ServerContext>();\n * \n * // Use it - context type is automatically inferred!\n * const createUser = mutation({\n * args: z.object({ name: z.string() }),\n * handler: async (ctx, { name }) => {\n * // ctx.db for mutations\n * await ctx.db.insert(UsersSchema, id, { name });\n * // ctx.context for server context\n * console.log(ctx.context.requestId);\n * return { success: true };\n * }\n * });\n */\nexport function createMutationBuilder<TContext = unknown>() {\n return function mutation<TInput, TResult, const TInternal extends boolean = false>(\n config: MutationConfig<TInput, TResult, TContext> & { internal?: TInternal }\n ): MutationProcedure<TInput, TResult, TContext, TInternal> {\n return {\n _type: \"procedure\",\n procedureType: \"mutation\",\n inputSchema: config.args,\n outputSchema: config.returns,\n fn: config.handler,\n internal: (config.internal ?? false) as TInternal,\n };\n };\n}\n\n// ─── Action Builder Factory ──────────────────────────────────────────────────\n\n/**\n * Create an action builder with a pre-defined context type.\n * Actions have access to the full SupaliveDb for both queries and mutations.\n *\n * @example\n * // Define your server context\n * interface ServerContext {\n * auth: { userId: string };\n * requestId: string;\n * }\n *\n * // Create a typed action builder\n * const action = createActionBuilder<ServerContext>();\n *\n * // Use it - context type is automatically inferred!\n * const processOrder = action({\n * args: z.object({ orderId: z.string() }),\n * handler: async (ctx, { orderId }) => {\n * // ctx.db for full database access\n * const order = await ctx.db.query(async (db) => {\n * return db.query(OrdersSchema).find(orderId);\n * });\n * await ctx.db.mutation(async (db) => {\n * await db.update(OrdersSchema, orderId, { status: \"processed\" });\n * });\n * // ctx.context for server context\n * console.log(ctx.context.requestId);\n * return { success: true };\n * }\n * });\n */\nexport function createActionBuilder<TContext = unknown>() {\n return function action<TInput, TResult, const TInternal extends boolean = false>(\n config: ActionConfig<TInput, TResult, TContext> & { internal?: TInternal }\n ): ActionProcedure<TInput, TResult, TContext, TInternal> {\n return {\n _type: \"procedure\",\n procedureType: \"action\",\n inputSchema: config.args,\n outputSchema: config.returns,\n fn: config.handler,\n internal: (config.internal ?? false) as TInternal,\n };\n };\n}\n\n// ─── Job Builder Factory ─────────────────────────────────────────────────────\n\n/**\n * Create a job builder with a pre-defined context type. A job is a\n * server-only procedure invoked by the scheduler over HTTP — either on its\n * declared `cron` schedule or as a precise one-shot enqueued via the\n * server's job API. Jobs run like actions (full db, non-transactional) and\n * are always internal, so they are never reachable from a client.\n *\n * @example\n * const job = createJobBuilder<ServerContext>();\n *\n * export const cleanupOtps = job({\n * cron: \"0 * * * *\", // hourly\n * args: z.object({}),\n * handler: async (ctx) => {\n * await ctx.db.mutation(async (db) => { ... });\n * return { ok: true };\n * },\n * });\n */\nexport function createJobBuilder<TContext = unknown>() {\n return function job<TInput, TResult>(\n config: JobConfig<TInput, TResult, TContext>\n ): JobProcedure<TInput, TResult, TContext> {\n return {\n _type: \"procedure\",\n procedureType: \"job\",\n inputSchema: config.args,\n fn: config.handler,\n internal: true,\n cron: config.cron,\n };\n };\n}","import type { AnyProcedure } from \"./procedure\";\n\n// ─── Router Types ────────────────────────────────────────────────────────────\n\n/**\n * A router maps procedure names (keys) to their definitions.\n * This is the type that's exported from your app and used by the client.\n */\nexport type Router<TProcedures extends Record<string, AnyProcedure<TContext>>, TContext = unknown> = {\n _type: \"router\";\n procedures: TProcedures;\n contextName: string;\n};\n\n/**\n * Inferred AppRouter type from router() call.\n * Captures the full procedure map for client type inference.\n */\nexport type AppRouter<\n TProcedures extends Record<string, AnyProcedure<TContext>> = Record<string, AnyProcedure>,\n TContext = unknown\n> = Router<TProcedures, TContext>;\n\n// ─── Type Helpers for Client ─────────────────────────────────────────────────\n\n/** Get query procedures only from a router */\nexport type QueryProcedures<T extends Record<string, AnyProcedure>> = {\n [K in keyof T as T[K] extends { procedureType: \"query\" } ? K : never]: T[K];\n};\n\n/** Get mutation procedures only from a router */\nexport type MutationProcedures<T extends Record<string, AnyProcedure>> = {\n [K in keyof T as T[K] extends { procedureType: \"mutation\" } ? K : never]: T[K];\n};\n\n/** Get action procedures only from a router */\nexport type ActionProcedures<T extends Record<string, AnyProcedure>> = {\n [K in keyof T as T[K] extends { procedureType: \"action\" } ? K : never]: T[K];\n};\n\n/** Get job procedures only from a router */\nexport type JobProcedures<T extends Record<string, AnyProcedure>> = {\n [K in keyof T as T[K] extends { procedureType: \"job\" } ? K : never]: T[K];\n};\n\n/** Get public (non-internal) procedures - for client type safety */\nexport type PublicProcedures<T extends Record<string, AnyProcedure>> = Pick<\n T,\n { [K in keyof T]: T[K] extends { internal: true } ? never : K }[keyof T]\n>;\n\n/** Extract procedure names from a router */\nexport type ProcedureNames<T extends Router<any>> =\n T extends Router<infer P> ? keyof P : never;\n\nexport type RouterConfig<T> = {\n procedures: T;\n contextName?: string;\n};\n\n/**\n* Create a router from procedure definitions.\n* Procedure names are inferred from the object keys.\n* \n* @example\n* const appRouter = router({\n* procedures: {\n* getUser,\n* createUser,\n* internalGetAll,\n* },\n* });\n* \n* export type AppRouter = typeof appRouter;\n*/\nexport function router<TProcedures extends Record<string, AnyProcedure<any>>, TContext = unknown>(\n config: RouterConfig<TProcedures>,\n): Router<TProcedures, TContext> {\n const registry = getContextRegistry(config.contextName ?? \"default\");\n\n // Register all procedures at router creation time\n for (const [name, proc] of Object.entries(config.procedures)) {\n registry.registerProcedure(name, proc);\n }\n\n\n return {\n _type: \"router\",\n procedures: config.procedures,\n contextName: config.contextName ?? \"default\",\n };\n}\n\nexport interface RegisteredProcedure<TContext = unknown> {\n name: string;\n type: \"query\" | \"mutation\" | \"action\" | \"job\";\n internal: boolean;\n inputSchema: AnyProcedure<TContext>[\"inputSchema\"];\n fn: AnyProcedure<TContext>[\"fn\"];\n /** Only present for `type === \"query\"`. See `QueryIdentitySpec`. */\n queryIdentity?: false | string | ((serverCtx: TContext | undefined, input: unknown) => string | null | undefined);\n /** Only present for `type === \"job\"`. Cron expression for recurring jobs. */\n cron?: string;\n}\n\n\nconst contextRegistry = new Map<string, ContextRegistry>();\n\nexport function getContextRegistry(inContext: string): ContextRegistry {\n let registry = contextRegistry.get(inContext);\n if (!registry) {\n registry = new ContextRegistry();\n contextRegistry.set(inContext, registry);\n }\n return registry;\n}\n\nexport class ContextRegistry {\n procedureRegistry = new Map<string, RegisteredProcedure<any>>();\n internalProcedureNames = new Set<string>();\n\n registerProcedure<TContext>(name: string, proc: AnyProcedure<TContext>): void {\n if (this.procedureRegistry.has(name)) {\n throw new Error(\n `[router] Procedure \"${name}\" is already registered. ` +\n `Each procedure name must be unique across the application.`\n );\n }\n\n // Track internal procedures by name\n if (proc.internal) {\n this.markInternalProcedure(name);\n }\n\n const queryIdentity =\n proc.procedureType === \"query\"\n ? (proc as { queryIdentity?: RegisteredProcedure<TContext>[\"queryIdentity\"] }).queryIdentity\n : undefined;\n\n const cron =\n proc.procedureType === \"job\"\n ? (proc as { cron?: string }).cron\n : undefined;\n\n this.procedureRegistry.set(name, {\n name,\n type: proc.procedureType,\n internal: proc.internal,\n inputSchema: proc.inputSchema,\n fn: proc.fn,\n queryIdentity,\n cron,\n });\n }\n\n /** Get a registered procedure by name (runtime lookup) */\n getProcedure<TContext = unknown>(name: string): RegisteredProcedure<TContext> | undefined {\n return this.procedureRegistry.get(name);\n }\n\n /** Get all registered procedure names */\n getProcedureNames(): string[] {\n return [...this.procedureRegistry.keys()];\n }\n\n /** Get all registered procedures */\n getAllProcedures(): Map<string, RegisteredProcedure> {\n return new Map(this.procedureRegistry);\n }\n\n /** Get all registered job procedures (server-only, scheduler-triggered). */\n getJobProcedures(): RegisteredProcedure[] {\n return [...this.procedureRegistry.values()].filter((p) => p.type === \"job\");\n }\n\n /** Clear the registry (for testing only) */\n clearRegistry(): void {\n this.procedureRegistry.clear();\n this.clearInternalProcedures();\n }\n\n markInternalProcedure(name: string): void {\n this.internalProcedureNames.add(name);\n }\n\n isInternalProcedure(name: string): boolean {\n return this.internalProcedureNames.has(name);\n }\n\n clearInternalProcedures(): void {\n this.internalProcedureNames.clear();\n }\n}"],"mappings":"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"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { $ as ActionProcedures, $n as RawClient, $r as
|
|
1
|
+
import { $ as ActionProcedures, $n as RawClient, $r as RawReadEntry, $t as ResultOf, Ar as LeafPredicateSchema, At as QueryFn, Br as Predicate, Cn as ComputedFieldConfig, Cr as CachedPgMetadataSchema, Ct as MutationConfig, Dn as InferSchema, Dr as CompareOperatorSchema, Dt as OutputOf, Er as CompareOperator, Et as MutationProcedure, Fr as OccConflictError, Ft as createMutationBuilder, G as ClientLogLevel, Gr as QueryCacheMetadataSchema, Hn as defineSchema, Hr as QueryCacheEntry, In as SchemaCodecs, Ir as OrPredicate, It as createQueryBuilder, J as HeartbeatOptions, Jn as DbQueryResult, Jr as RangeReadSchema, Jt as sleep, K as ClientLogger, Kr as QuerySpec, Lr as OrPredicateSchema, Mr as MutationResult, Mt as TypeOf, Nr as NO_RETRY, Nt as createActionBuilder, On as InsertData, Or as DEFAULT_RETRY, Ot as QueryConfig, Pr as OccAbortError, Q as createConsoleLogger, Qr as RawRangeReadSchema, Qt as QueryDefinition, Rn as SchemaColumnsOptions, Rr as PointRead, Sr as CachedPgMetadata, Tr as CommitTs, Tt as MutationFn, Ur as QueryCacheEntrySchema, Vn as defineComputedField, Vr as PredicateSchema, W as ClientEvent, Wr as QueryCacheMetadata, X as WSClientOptions, Xr as RawPointReadSchema, Xt as DefsToMap, Y as RPCError, Yr as RawPointRead, Yt as AnyQueryDef, Z as WsClientManager, Zn as PooledClient, Zr as RawRangeRead, Zt as ParamsOf, _n as matchesPredicate, _t as HandlerLogger, a as createCaller, ai as WriteEntrySchema, at as PublicProcedures, br as AndPredicateSchema, c as ClientOptions, ci as bytesFromJson, ct as Router, d as LiveQueryStatus, dt as ActionConfig, ei as RawReadEntrySchema, en as _resetGlobalDefs, et as AppRouter, f as WSClientMethods, ft as ActionCtx, gt as ContextOf, ht as AnyProcedure, i as CallerOptions, ii as WriteEntry, in as TxContext, it as ProcedureNames, jr as LiveResult, jt as QueryProcedure, kn as Model, kr as LeafPredicate, kt as QueryCtx, l as LiveQueryHandle, li as normalizeIdToBytes, mt as ActionProcedure, n as CallerFromProcedures, ni as ReadEntrySchema, nn as DbReader, o as CallOptions, oi as WriteOp, ot as QueryProcedures, p as createClient, pt as ActionFn, q as ClientPublicState, qn as Database, qr as RangeRead, qt as SupaliveDb, r as CallerFromRouter, ri as RetryConfig, rn as DbWriter, rt as MutationProcedures, s as ClientFromProcedures, si as WriteOpSchema, st as RegisteredProcedure, t as CallerClientInitConfig, ti as ReadEntry, tn as defineQuery, u as LiveQueryState, ui as normalizeToBytes, ut as router, vt as HandlerObservability, wr as CommitLogEntry, wt as MutationCtx, xr as BigIntSchema, yn as ColumnCodec, yr as AndPredicate, zn as SchemaDefinition, zr as PointReadSchema } from "../../index-CKo6HvJc.js";
|
|
2
2
|
export { type ActionConfig, type ActionCtx, type ActionFn, type ActionProcedure, type ActionProcedures, AndPredicate, AndPredicateSchema, type AnyProcedure, type AnyQueryDef, type AppRouter, BigIntSchema, CachedPgMetadata, CachedPgMetadataSchema, type CallOptions, CallerClientInitConfig, CallerFromProcedures, CallerFromRouter, CallerOptions, type ClientEvent, type ClientFromProcedures, type ClientLogLevel, type ClientLogger, type ClientOptions, type ClientPublicState, type ColumnCodec, CommitLogEntry, CommitTs, CompareOperator, CompareOperatorSchema, type ComputedFieldConfig, type ContextOf, DEFAULT_RETRY, type Database, type DbQueryResult, DbReader, DbReader as ReadContext, DbWriter, DbWriter as WritableContext, type DefsToMap, type HandlerLogger, type HandlerObservability, type HeartbeatOptions, type InferSchema, type InsertData, LeafPredicate, LeafPredicateSchema, type LiveQueryHandle, type LiveQueryState, type LiveQueryStatus, LiveResult, type Model, type MutationConfig, type MutationCtx, type MutationFn, type MutationProcedure, type MutationProcedures, MutationResult, NO_RETRY, OccAbortError, OccConflictError, OrPredicate, OrPredicateSchema, type OutputOf, type ParamsOf, PointRead, PointReadSchema, type PooledClient, Predicate, PredicateSchema, type ProcedureNames, type PublicProcedures, QueryCacheEntry, QueryCacheEntrySchema, QueryCacheMetadata, QueryCacheMetadataSchema, type QueryConfig, type QueryCtx, type QueryDefinition, type QueryFn, type QueryProcedure, type QueryProcedures, QuerySpec, RPCError, RangeRead, RangeReadSchema, type RawClient, RawPointRead, RawPointReadSchema, RawRangeRead, RawRangeReadSchema, RawReadEntry, RawReadEntrySchema, ReadEntry, ReadEntrySchema, type RegisteredProcedure, type ResultOf, RetryConfig, type Router, type SchemaCodecs, type SchemaColumnsOptions, type SchemaDefinition, SupaliveDb, TxContext, type TypeOf, type WSClientMethods, type WSClientOptions, WriteEntry, WriteEntrySchema, WriteOp, WriteOpSchema, WsClientManager, _resetGlobalDefs, bytesFromJson, createActionBuilder, createCaller, createClient, createConsoleLogger, createMutationBuilder, createQueryBuilder, defineComputedField, defineQuery, defineSchema, matchesPredicate, normalizeIdToBytes, normalizeToBytes, router, sleep };
|
package/dist/src/client/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { i as createActionBuilder, l as primaryOnlyConn, n as getContextRegistry, o as createMutationBuilder, r as router, s as createQueryBuilder } from "../../router-DP2ThAwh.js";
|
|
2
2
|
import { r as supaliveStringify } from "../../helper-zdJT5FUc.js";
|
|
3
3
|
import { o as matchesPredicate } from "../../query-LJranz0c.js";
|
|
4
4
|
import { n as defineSchema, t as defineComputedField } from "../../schema-DRtz5h5l.js";
|
|
5
5
|
import { C as normalizeIdToBytes, S as bytesFromJson, _ as RawRangeReadSchema, a as DEFAULT_RETRY, b as WriteEntrySchema, c as OccAbortError, d as PointReadSchema, f as PredicateSchema, g as RawPointReadSchema, h as RangeReadSchema, i as CompareOperatorSchema, l as OccConflictError, m as QueryCacheMetadataSchema, n as BigIntSchema, o as LeafPredicateSchema, p as QueryCacheEntrySchema, r as CachedPgMetadataSchema, s as NO_RETRY, t as AndPredicateSchema, u as OrPredicateSchema, v as RawReadEntrySchema, w as normalizeToBytes, x as WriteOpSchema, y as ReadEntrySchema } from "../../types_db-OUou3o2Z.js";
|
|
6
|
-
import { l as ServerMessageSchema } from "../../types_client_rpc-
|
|
7
|
-
import {
|
|
8
|
-
import { n as
|
|
6
|
+
import { l as ServerMessageSchema } from "../../types_client_rpc-B8jh6MKl.js";
|
|
7
|
+
import { c as DbReader, l as DbWriter, o as SupaliveDb, s as sleep, u as TxContext } from "../../logger-DrXccWFZ.js";
|
|
8
|
+
import { n as runCachedQueryInParent, t as runCachedQuery } from "../../one-shot-query-BBiv9LGP.js";
|
|
9
9
|
import { sha1 } from "hash-wasm";
|
|
10
10
|
//#region src/db/query_definition.ts
|
|
11
11
|
const _globalDefs = /* @__PURE__ */ new Map();
|
|
@@ -1157,56 +1157,45 @@ var LiveQueryHandleImpl = class {
|
|
|
1157
1157
|
//#endregion
|
|
1158
1158
|
//#region src/client/caller_client.ts
|
|
1159
1159
|
/**
|
|
1160
|
-
* Run a standalone (non-transaction-joining) server-side query with replica
|
|
1161
|
-
* routing that DEFAULTS to the primary.
|
|
1162
|
-
*
|
|
1163
|
-
* Unlike a client one-shot query, the internal caller has no client `minTs`
|
|
1164
|
-
* high-water to gate replica staleness — a caller that just performed an
|
|
1165
|
-
* internal write and then reads back would silently read a lagging replica. So
|
|
1166
|
-
* the safe default here is the PRIMARY; a handler can still opt a heavy
|
|
1167
|
-
* reporting read onto the replica with `ctx.useReplicaConn()` (and force back
|
|
1168
|
-
* with `ctx.usePrimaryConn()` / `{ readOwnWrite: true }`). The connection knobs
|
|
1169
|
-
* use the SAME shared routing rule as the one-shot path ({@link resolveReadRouting}
|
|
1170
|
-
* / {@link makeConnRouting}) — the only difference is the DEFAULT connection
|
|
1171
|
-
* (primary here, replica-if-caught-up there). With no minTs floor, an explicit
|
|
1172
|
-
* `useReplicaConn()` resolves to the replica whenever one is configured. With no
|
|
1173
|
-
* replica configured every branch resolves to the primary.
|
|
1174
|
-
*/
|
|
1175
|
-
async function runRoutedCallerQuery(db, serverCtx, fn, log) {
|
|
1176
|
-
const routing = await resolveReadRouting(db, await db.impl.getLatestSnapshotTimestamp(), 0n);
|
|
1177
|
-
return (await db.queryInternalOn({
|
|
1178
|
-
impl: routing.primaryImpl,
|
|
1179
|
-
beginTs: routing.primaryTs
|
|
1180
|
-
}, async (dbCtx) => {
|
|
1181
|
-
return fn({
|
|
1182
|
-
db: dbCtx,
|
|
1183
|
-
serverCtx,
|
|
1184
|
-
log,
|
|
1185
|
-
...makeConnRouting(dbCtx, routing)
|
|
1186
|
-
});
|
|
1187
|
-
})).data;
|
|
1188
|
-
}
|
|
1189
|
-
/**
|
|
1190
1160
|
* Create a server-side caller that bypasses HTTP/WebSocket.
|
|
1191
1161
|
*
|
|
1192
1162
|
* For in-memory calls, input validation is skipped (data is already a JS object).
|
|
1193
1163
|
* Query procedures also get a liveQuery() method for server-side use.
|
|
1164
|
+
*
|
|
1165
|
+
* `init` requires the shared Redis-backed query cache, so every read path —
|
|
1166
|
+
* `query`, `runQuery`, and `liveQuery` — behaves like a normal client procedure
|
|
1167
|
+
* call: it checks cache freshness first and only falls back to executing the
|
|
1168
|
+
* query on a miss/stale entry (see runCachedQuery and runCachedQueryInParent).
|
|
1169
|
+
* `runQuery` keeps joining the parent snapshot/readSet (or opening a fresh
|
|
1170
|
+
* routed read for action/job parents), so nested reads stay consistent with the
|
|
1171
|
+
* parent and mutations keep reads-your-writes.
|
|
1194
1172
|
*/
|
|
1195
1173
|
function createCaller(options) {
|
|
1196
1174
|
const { isInternal = true, inContext } = options;
|
|
1197
1175
|
const registry = getContextRegistry(inContext ?? "default");
|
|
1198
1176
|
const cache = /* @__PURE__ */ new Map();
|
|
1177
|
+
let callerConfig;
|
|
1199
1178
|
let db;
|
|
1200
1179
|
let storage;
|
|
1201
1180
|
let scheduler;
|
|
1202
1181
|
let obs;
|
|
1182
|
+
let cacheLayer;
|
|
1183
|
+
let callerDepsInstance;
|
|
1203
1184
|
return new Proxy({}, { get(_target, procedureName) {
|
|
1204
1185
|
if (typeof procedureName !== "string") return;
|
|
1205
1186
|
if (procedureName == "init") return async (config) => {
|
|
1187
|
+
callerConfig = config;
|
|
1206
1188
|
db = config.db;
|
|
1207
1189
|
storage = config.storage;
|
|
1208
1190
|
scheduler = config.scheduler;
|
|
1209
1191
|
obs = config.obs;
|
|
1192
|
+
cacheLayer = config.cache;
|
|
1193
|
+
callerDepsInstance = {
|
|
1194
|
+
db: config.db,
|
|
1195
|
+
cache: cacheLayer,
|
|
1196
|
+
getMinRetainedTs: config.getMinRetainedTs,
|
|
1197
|
+
getUserId: config.getUserId
|
|
1198
|
+
};
|
|
1210
1199
|
};
|
|
1211
1200
|
const callerLog = () => obs.lazyChildLogger({
|
|
1212
1201
|
caller: "internal",
|
|
@@ -1225,21 +1214,32 @@ function createCaller(options) {
|
|
|
1225
1214
|
query: async (input, serverCtx) => {
|
|
1226
1215
|
if (procedure.type !== "query") throw new Error(`Procedure "${procedureName}" is not a query`);
|
|
1227
1216
|
const validatedInput = validateInput(input);
|
|
1228
|
-
|
|
1217
|
+
const lastSnapshotTs = await db.impl.getLatestSnapshotTimestamp();
|
|
1218
|
+
const { data } = await runCachedQuery(callerDepsInstance, { log: callerLog() }, procedure, procedureName, validatedInput, serverCtx, lastSnapshotTs);
|
|
1219
|
+
return data;
|
|
1229
1220
|
},
|
|
1230
1221
|
runQuery: async (input, parentCtx) => {
|
|
1231
1222
|
if (procedure.type !== "query") throw new Error(`Procedure "${procedureName}" is not a query`);
|
|
1232
1223
|
const validatedInput = validateInput(input);
|
|
1233
1224
|
if (parentCtx.db instanceof TxContext) {
|
|
1234
|
-
const
|
|
1235
|
-
|
|
1236
|
-
serverCtx: parentCtx.serverCtx,
|
|
1225
|
+
const parentReader = parentCtx.db;
|
|
1226
|
+
return runCachedQueryInParent(callerDepsInstance, {
|
|
1237
1227
|
log: parentCtx.log,
|
|
1238
|
-
|
|
1239
|
-
};
|
|
1240
|
-
return procedure.fn(ctx, validatedInput);
|
|
1228
|
+
span: parentCtx.span
|
|
1229
|
+
}, procedure, procedureName, validatedInput, parentCtx.serverCtx, parentReader);
|
|
1241
1230
|
}
|
|
1242
|
-
|
|
1231
|
+
const parentDb = parentCtx.db;
|
|
1232
|
+
const lastSnapshotTs = await parentDb.impl.getLatestSnapshotTimestamp();
|
|
1233
|
+
const { data } = await runCachedQuery({
|
|
1234
|
+
db: parentDb,
|
|
1235
|
+
cache: cacheLayer,
|
|
1236
|
+
getMinRetainedTs: callerConfig.getMinRetainedTs,
|
|
1237
|
+
getUserId: callerConfig.getUserId
|
|
1238
|
+
}, {
|
|
1239
|
+
log: parentCtx.log,
|
|
1240
|
+
span: parentCtx.span
|
|
1241
|
+
}, procedure, procedureName, validatedInput, parentCtx.serverCtx, lastSnapshotTs);
|
|
1242
|
+
return data;
|
|
1243
1243
|
},
|
|
1244
1244
|
mutate: async (input, serverCtx) => {
|
|
1245
1245
|
if (procedure.type !== "mutation") throw new Error(`Procedure "${procedureName}" is not a mutation`);
|
|
@@ -1262,6 +1262,7 @@ function createCaller(options) {
|
|
|
1262
1262
|
db: dbCtx,
|
|
1263
1263
|
serverCtx: parentCtx.serverCtx,
|
|
1264
1264
|
log: parentCtx.log,
|
|
1265
|
+
span: parentCtx.span,
|
|
1265
1266
|
...primaryOnlyConn
|
|
1266
1267
|
};
|
|
1267
1268
|
if (parentCtx.db instanceof TxContext) ctx.db.appendInternalReadSet(parentCtx.db.internalGetReadSet());
|
|
@@ -1292,15 +1293,9 @@ function createCaller(options) {
|
|
|
1292
1293
|
},
|
|
1293
1294
|
liveQuery: procedure.type === "query" ? async (input, serverCtx) => {
|
|
1294
1295
|
const validatedInput = validateInput(input);
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
serverCtx,
|
|
1299
|
-
log: callerLog(),
|
|
1300
|
-
...primaryOnlyConn
|
|
1301
|
-
};
|
|
1302
|
-
return procedure.fn(ctx, validatedInput);
|
|
1303
|
-
});
|
|
1296
|
+
const obs = { log: callerLog() };
|
|
1297
|
+
const lastSnapshotTs = await db.impl.getLatestSnapshotTimestamp();
|
|
1298
|
+
return runCachedQuery(callerDepsInstance, obs, procedure, procedureName, validatedInput, serverCtx, lastSnapshotTs);
|
|
1304
1299
|
} : void 0
|
|
1305
1300
|
};
|
|
1306
1301
|
cache.set(procedureName, newProp);
|