@supalive/core 1.2.1 → 1.3.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 (55) hide show
  1. package/dist/index-4Nis7Wnk.d.ts +1973 -0
  2. package/dist/index-4Nis7Wnk.d.ts.map +1 -0
  3. package/dist/index-Ca58CrWX.d.ts +2103 -0
  4. package/dist/index-Ca58CrWX.d.ts.map +1 -0
  5. package/dist/index-DDK9ZIYb.d.ts +2103 -0
  6. package/dist/index-DDK9ZIYb.d.ts.map +1 -0
  7. package/dist/index-Oz3eyddt.d.ts +1974 -0
  8. package/dist/index-Oz3eyddt.d.ts.map +1 -0
  9. package/dist/mysql-D0pFocWL.d.ts +109 -0
  10. package/dist/mysql-D0pFocWL.d.ts.map +1 -0
  11. package/dist/mysql-DF-dZHi7.d.ts +109 -0
  12. package/dist/mysql-DF-dZHi7.d.ts.map +1 -0
  13. package/dist/mysql-QWBVXBjM.d.ts +109 -0
  14. package/dist/mysql-QWBVXBjM.d.ts.map +1 -0
  15. package/dist/mysql-fECZYP_m.d.ts +109 -0
  16. package/dist/mysql-fECZYP_m.d.ts.map +1 -0
  17. package/dist/object-storage-4t7JvpuK.d.ts +67 -0
  18. package/dist/object-storage-4t7JvpuK.d.ts.map +1 -0
  19. package/dist/postgres-C1qWlB--.d.ts +113 -0
  20. package/dist/postgres-C1qWlB--.d.ts.map +1 -0
  21. package/dist/postgres-CKtJ62S4.d.ts +113 -0
  22. package/dist/postgres-CKtJ62S4.d.ts.map +1 -0
  23. package/dist/postgres-DdqpjjYF.d.ts +113 -0
  24. package/dist/postgres-DdqpjjYF.d.ts.map +1 -0
  25. package/dist/postgres-DhCgxVOr.d.ts +113 -0
  26. package/dist/postgres-DhCgxVOr.d.ts.map +1 -0
  27. package/dist/procedure-Ze1GE-N9.js.map +1 -1
  28. package/dist/src/client/index.d.ts +1 -1
  29. package/dist/src/client/index.js +7 -1
  30. package/dist/src/client/index.js.map +1 -1
  31. package/dist/src/exports/mysql.d.ts +1 -1
  32. package/dist/src/exports/postgres.d.ts +1 -1
  33. package/dist/src/exports/procedure.d.ts +1 -1
  34. package/dist/src/exports/schema-sql.d.ts +1 -1
  35. package/dist/src/exports/schema-sql.d.ts.map +1 -1
  36. package/dist/src/exports/schema-sql.js +8 -1
  37. package/dist/src/exports/schema-sql.js.map +1 -1
  38. package/dist/src/exports/server.d.ts +9 -7
  39. package/dist/src/exports/server.d.ts.map +1 -1
  40. package/dist/src/exports/server.js +14 -7
  41. package/dist/src/exports/server.js.map +1 -1
  42. package/dist/src/exports/storage.d.ts +56 -0
  43. package/dist/src/exports/storage.d.ts.map +1 -0
  44. package/dist/src/exports/storage.js +62 -0
  45. package/dist/src/exports/storage.js.map +1 -0
  46. package/dist/src/exports/types.d.ts +2 -2
  47. package/dist/types_server-AN8OiTEx.d.ts +302 -0
  48. package/dist/types_server-AN8OiTEx.d.ts.map +1 -0
  49. package/dist/types_server-C9owgeSs.d.ts +302 -0
  50. package/dist/types_server-C9owgeSs.d.ts.map +1 -0
  51. package/dist/types_server-D5JDD_Dp.d.ts +430 -0
  52. package/dist/types_server-D5JDD_Dp.d.ts.map +1 -0
  53. package/dist/types_server-Dxx_Xx86.d.ts +430 -0
  54. package/dist/types_server-Dxx_Xx86.d.ts.map +1 -0
  55. package/package.json +15 -1
@@ -0,0 +1,302 @@
1
+ import { Bt as SupaliveDb, Ft as JobScheduler, Sr as MutationResult, nt as RegisteredProcedure, qn as CacheLayer } from "./index-DDK9ZIYb.js";
2
+ import { r as ObjectStorage } from "./object-storage-4t7JvpuK.js";
3
+ import z from "zod";
4
+ import { IncomingMessage } from "http";
5
+ import { WebSocket } from "ws";
6
+ import { Level } from "pino";
7
+ import { Redis } from "ioredis";
8
+
9
+ //#region src/config.d.ts
10
+ /** CORS policy for the HTTP RPC endpoint. */
11
+ interface RpcCorsConfig {
12
+ /**
13
+ * Allowed origins. `"*"` sends `Access-Control-Allow-Origin: *`; a list
14
+ * echoes back a request's `Origin` only when it matches (and sets `Vary`).
15
+ * Omit `cors` entirely to send no CORS headers (same-origin only).
16
+ */
17
+ origins: string[] | "*";
18
+ }
19
+ /** Rate-limit policy for the HTTP RPC endpoint (fixed window, per instance). */
20
+ interface RpcRateLimitConfig {
21
+ /** Window length in ms. Default 60000. */
22
+ windowMs?: number;
23
+ /** Max requests per window per key. Default 120. */
24
+ max?: number;
25
+ /**
26
+ * Derive the limiter key from the request. Default: client IP
27
+ * (`X-Forwarded-For` first hop, else socket address). Return a stable string.
28
+ */
29
+ keyBy?: (req: IncomingMessage) => string;
30
+ }
31
+ /**
32
+ * Enables a one-shot HTTP RPC transport for `query`/`mutation`/`action`
33
+ * (no subscriptions — those stay WebSocket-only). Lets clients that don't need
34
+ * live queries call procedures without holding a socket open. Omit to disable
35
+ * the endpoint entirely.
36
+ */
37
+ interface RpcConfig<TContext = unknown> {
38
+ /**
39
+ * URL path prefix. Default `/_rpc`. A procedure `foo` is called as
40
+ * `POST {path}/foo`. Keep this distinct from `jobPath`.
41
+ */
42
+ path?: string;
43
+ /**
44
+ * Map an HTTP request to the auth `data` handed to `verifyAuth` (the same
45
+ * callback the WebSocket path uses). Default: `Authorization: Bearer <token>`
46
+ * → `{ token }`. Return `undefined` for an anonymous request.
47
+ */
48
+ auth?: (req: IncomingMessage) => Record<string, unknown> | undefined;
49
+ /** CORS policy. Omit for same-origin only (no CORS headers). */
50
+ cors?: RpcCorsConfig;
51
+ /** Rate limiting. Omit for defaults (120/min per IP); set `false` to disable. */
52
+ rateLimit?: RpcRateLimitConfig | false;
53
+ }
54
+ interface UpstashConfig {
55
+ url: string;
56
+ token: string;
57
+ redisUrl: string;
58
+ }
59
+ /** Database configuration for PostgreSQL */
60
+ interface PostgresConfig {
61
+ type: "postgres";
62
+ connectionString: string;
63
+ /** Optional max connections for the Postgres connection pool. Defaults to 10.*/
64
+ maxConnections?: number;
65
+ /** Optional min connections for the Postgres connection pool. Defaults to 1.*/
66
+ minConnections?: number;
67
+ /** Optional idle timeout for Postgres connections in milliseconds. Defaults to 30000 (30 seconds). */
68
+ idleTimeoutMillis?: number;
69
+ /** Optional connection timeout for acquiring Postgres connections in milliseconds. Defaults to 7000 (7 seconds). */
70
+ connectionTimeoutMillis?: number;
71
+ }
72
+ /** Database configuration for MySQL */
73
+ interface MySQLConfig {
74
+ type: "mysql";
75
+ connectionString: string;
76
+ /** Optional max connections for the MySQL connection pool. Defaults to 20.*/
77
+ maxConnections?: number;
78
+ /** Optional min connections for the MySQL connection pool. Defaults to 1.*/
79
+ minConnections?: number;
80
+ /** Optional idle timeout for MySQL connections in milliseconds. Defaults to 30000 (30 seconds). */
81
+ idleTimeoutMillis?: number;
82
+ /** Optional connection timeout for acquiring MySQL connections in milliseconds. Defaults to 7000 (7 seconds). */
83
+ connectionTimeoutMillis?: number;
84
+ /** Optional flag to queue connection requests when pool is exhausted. Defaults to true (queue requests). */
85
+ queueLimit?: number;
86
+ }
87
+ type DatabaseConfig = PostgresConfig | MySQLConfig;
88
+ /**
89
+ * Configuration for the Supalive WebSocket server.
90
+ */
91
+ interface SupaliveServerConfig<TContext = Record<string, unknown>> {
92
+ /** Server port (default: 3000) */
93
+ port?: number;
94
+ /** Server host (default: "0.0.0.0") */
95
+ host?: string;
96
+ cacheLayer: CacheLayer;
97
+ redisSubClient: Redis;
98
+ /**
99
+ * Subscription Manager WebSocket URL for RPC communication.
100
+ * A single sub-manager process owns all subscription state for this
101
+ * deployment. Internally it spawns N logical workers (configured on the
102
+ * sub-manager side) and routes by hash(subId) to spread CPU across them.
103
+ */
104
+ subManagerUrl: string;
105
+ /** Database instance */
106
+ database: SupaliveDb;
107
+ /**
108
+ * Optional authentication callback.
109
+ * Called when client sends auth message.
110
+ * Return null to reject authentication.
111
+ */
112
+ verifyAuth?: (data: Record<string, unknown>, sessionId: string) => Promise<TContext | null>;
113
+ /**
114
+ * Server context name for procedure routing.
115
+ * Must match the router's contextName.
116
+ */
117
+ contextName?: string;
118
+ /**
119
+ * Session TTL in seconds (default: 3600 = 1 hour).
120
+ * Sessions are kept alive while connected and expire after disconnect.
121
+ */
122
+ sessionTtlSeconds?: number;
123
+ /**
124
+ * Enable detailed logging.
125
+ */
126
+ logLevel?: Level;
127
+ /**
128
+ * Extract user ID from context for cache key generation.
129
+ * If not provided, caching is disabled (each sub recomputes independently).
130
+ */
131
+ getUserId?: (ctx: TContext | undefined) => string | null;
132
+ /**
133
+ * Cache TTL in seconds (default: 3600).
134
+ * How long query results are cached in Redis.
135
+ */
136
+ cacheTtlSeconds?: number;
137
+ /**
138
+ * Scheduler backing the job system. When provided, the server exposes an
139
+ * HTTP endpoint (`{jobPath}/<jobName>`) that the scheduler POSTs to, and
140
+ * syncs every registered recurring (cron) job at startup. Omit to disable
141
+ * jobs entirely. Use `DevScheduler` locally and `QStashScheduler` in prod.
142
+ */
143
+ scheduler: JobScheduler;
144
+ /**
145
+ * Builds the system server context handed to a job handler's `serverCtx`.
146
+ * Jobs run without a client, so this is where a deployment injects its
147
+ * "system"/service identity. Called per job invocation.
148
+ */
149
+ jobContext?: () => TContext | Promise<TContext>;
150
+ /**
151
+ * Absolute, externally-reachable base URL of this server (no trailing
152
+ * slash), e.g. `https://api.example.com` in prod or `http://127.0.0.1:3000`
153
+ * in dev. Used to build the job endpoint the scheduler calls. Required when
154
+ * `scheduler` is set.
155
+ */
156
+ publicUrl?: string;
157
+ /**
158
+ * URL path prefix for the job webhook endpoint. Default `/_jobs`. The full
159
+ * endpoint for a job is `{publicUrl}{jobPath}/<jobName>`.
160
+ */
161
+ jobPath?: string;
162
+ /**
163
+ * Enable the one-shot HTTP RPC transport (query/mutation/action over
164
+ * `POST {rpc.path}/<name>`). Uses the same `verifyAuth` as the WebSocket
165
+ * path. Omit to disable. See {@link RpcConfig}.
166
+ */
167
+ rpc?: RpcConfig<TContext>;
168
+ /**
169
+ * Object storage, exposed to every procedure as `ctx.storage`. When set,
170
+ * query/mutation/action/job handlers can presign uploads/downloads and
171
+ * resolve public URLs without reaching for a module-level singleton. Omit
172
+ * to leave `ctx.storage` undefined (handlers should treat uploads as
173
+ * unconfigured). Build one with `S3CompatibleStorage` from
174
+ * `@supalive/core/storage`.
175
+ */
176
+ storage: ObjectStorage;
177
+ }
178
+ interface SubscriptionManagerConfig {
179
+ port: number;
180
+ upstash: {
181
+ url: string;
182
+ token: string;
183
+ redisUrl: string;
184
+ };
185
+ database: DatabaseConfig;
186
+ cacheTTLSeconds: number;
187
+ /**
188
+ * Number of logical workers inside the sub-manager process.
189
+ *
190
+ * Subscriptions are routed by FNV-1a(subId) % workers so that all operations
191
+ * for a given subId always land on the same worker (preserving the existing
192
+ * `instances: Set<string>` dedup). Each worker owns an independent
193
+ * subscriptions Map; on invalidate, all workers scan their own slice in
194
+ * parallel (logically — JS still runs one at a time inside one event loop,
195
+ * but per-worker scans are smaller so total work is split N ways).
196
+ *
197
+ * Defaults to `SUPALIVE_SUB_MANAGER_WORKERS` env var if set, else 1.
198
+ */
199
+ workers?: number;
200
+ /**
201
+ * Connection pool size *per worker*. If omitted, falls back to
202
+ * `floor(database.maxConnections / workers)` (min 1) so the total pool
203
+ * size stays close to the legacy single-worker configuration.
204
+ */
205
+ maxConnectionsPerWorker?: number;
206
+ }
207
+ //#endregion
208
+ //#region src/server/types_server.d.ts
209
+ type InstanceId = string;
210
+ type SubId = string;
211
+ /** Local tracking of an active subscription (per-session) */
212
+ interface SubscriptionEntry {
213
+ subId: SubId;
214
+ cacheKey: string;
215
+ subscribedTimes: number;
216
+ }
217
+ /**
218
+ * A mutation that has been validated and parked on the per-session FIFO
219
+ * queue, waiting for the in-flight mutation on this socket to finish. Each
220
+ * `handleCall` for a mutation owns one of these and awaits its own
221
+ * resolve/reject so it can send the response.
222
+ */
223
+ interface PendingMutation<TContext = Record<string, unknown>> {
224
+ procedure: RegisteredProcedure<TContext>;
225
+ validatedInput: unknown;
226
+ resolve: (result: MutationResult<unknown>) => void;
227
+ reject: (err: unknown) => void;
228
+ }
229
+ /** WebSocket session (runtime, with WebSocket) */
230
+ interface Session<TContext = Record<string, unknown>> {
231
+ id: string;
232
+ ws: WebSocket;
233
+ /** Auth context from verifyAuth callback */
234
+ serverCtx?: TContext;
235
+ subIds: Set<string>;
236
+ /**
237
+ * Per-socket FIFO mutation queue. at most one mutation
238
+ * drains at a time so a single client cannot saturate the OCC retry
239
+ * loop or fan out concurrent commits that race the same rows.
240
+ */
241
+ mutationQueue: PendingMutation<TContext>[];
242
+ mutationInFlight: boolean;
243
+ /** Per-socket count of currently executing actions. */
244
+ actionInFlight: number;
245
+ /**
246
+ * Wall-clock of the last inbound frame (text message, ws-ping, or ws-pong).
247
+ * Used by the per-session heartbeat to terminate sockets that have gone
248
+ * silent past `CLIENT_TIMEOUT_MS`.
249
+ */
250
+ lastReceivedAt: number;
251
+ /**
252
+ * Wall-clock of the last outbound frame. Gates the idle-only app-level
253
+ * ping so a busy session (frequent sub:updates etc.) doesn't emit a
254
+ * redundant `{type:"ping"}` on every heartbeat tick.
255
+ */
256
+ lastSentAt: number;
257
+ /**
258
+ * Per-session combined heartbeat. Single `setInterval` that handles
259
+ * both dead-TCP detection (ws-ping or terminate) and client-watchdog
260
+ * refresh (idle-only app-level ping) on each tick.
261
+ */
262
+ heartbeatTimer: ReturnType<typeof setInterval> | null;
263
+ }
264
+ declare const RemoteSubscriptionUpdateSchema: z.ZodObject<{
265
+ type: z.ZodLiteral<"update">;
266
+ subId: z.ZodString;
267
+ data: z.ZodUnknown;
268
+ dataHash: z.ZodString;
269
+ originInstance: z.ZodString;
270
+ }, z.core.$strip>;
271
+ type RemoteSubscriptionUpdate = z.infer<typeof RemoteSubscriptionUpdateSchema>;
272
+ declare const RemoteRecomputeRaceSchema: z.ZodObject<{
273
+ type: z.ZodLiteral<"recompute-race">;
274
+ subId: z.ZodString;
275
+ cacheKey: z.ZodString;
276
+ queryName: z.ZodString;
277
+ args: z.ZodUnknown;
278
+ notifyInstances: z.ZodArray<z.ZodString>;
279
+ commitTs: z.ZodString;
280
+ originInstance: z.ZodString;
281
+ }, z.core.$strip>;
282
+ type RemoteRecomputeRace = z.infer<typeof RemoteRecomputeRaceSchema>;
283
+ declare const RemoteSubscriptionMessageSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
284
+ type: z.ZodLiteral<"update">;
285
+ subId: z.ZodString;
286
+ data: z.ZodUnknown;
287
+ dataHash: z.ZodString;
288
+ originInstance: z.ZodString;
289
+ }, z.core.$strip>, z.ZodObject<{
290
+ type: z.ZodLiteral<"recompute-race">;
291
+ subId: z.ZodString;
292
+ cacheKey: z.ZodString;
293
+ queryName: z.ZodString;
294
+ args: z.ZodUnknown;
295
+ notifyInstances: z.ZodArray<z.ZodString>;
296
+ commitTs: z.ZodString;
297
+ originInstance: z.ZodString;
298
+ }, z.core.$strip>], "type">;
299
+ type RemoteSubscriptionMessage = z.infer<typeof RemoteSubscriptionMessageSchema>;
300
+ //#endregion
301
+ export { RpcRateLimitConfig as _, RemoteSubscriptionMessage as a, UpstashConfig as b, RemoteSubscriptionUpdateSchema as c, SubscriptionEntry as d, DatabaseConfig as f, RpcCorsConfig as g, RpcConfig as h, RemoteRecomputeRaceSchema as i, Session as l, PostgresConfig as m, PendingMutation as n, RemoteSubscriptionMessageSchema as o, MySQLConfig as p, RemoteRecomputeRace as r, RemoteSubscriptionUpdate as s, InstanceId as t, SubId as u, SubscriptionManagerConfig as v, SupaliveServerConfig as y };
302
+ //# sourceMappingURL=types_server-C9owgeSs.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types_server-C9owgeSs.d.ts","names":[],"sources":["../src/config.ts","../src/server/types_server.ts"],"mappings":";;;;;;;;;;UASiB,aAAA;EAAA;;;;AAMR;EAAP,OAAO;AAAA;;UAIQ,kBAAA;EAEf;EAAA,QAAA;EAOA;EALA,GAAA;EAKS;;AAAoB;AAS/B;EATE,KAAA,IAAS,GAAA,EAAK,eAAe;AAAA;;;;;;;UASd,SAAA;EAKf;;;;EAAA,IAAA;EAQA;;;;;EAFA,IAAA,IAAQ,G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