@20baht/live 0.0.0-stage → 0.1.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/elysia.js ADDED
@@ -0,0 +1,118 @@
1
+ import { Elysia } from 'elysia';
2
+ import { requestTarget } from './protocol.js';
3
+ const apps = new WeakMap();
4
+ export function livePlugin(live, options = {}) {
5
+ const path = (options.path ?? '/live');
6
+ const marks = marksOf(live);
7
+ return new Elysia({ name: '@20baht/live', seed: live })
8
+ .macro({
9
+ live: (route) => {
10
+ const beforeHandle = (context) => {
11
+ const run = runs.get(context.request);
12
+ if (run === undefined)
13
+ return;
14
+ const handed = {
15
+ params: (context.params ?? {}),
16
+ query: (context.query ?? {}),
17
+ body: context.body,
18
+ caller: run.caller,
19
+ };
20
+ run.answer = {
21
+ topics: [...route.topics(handed)],
22
+ key: route.key,
23
+ rows: route.rows,
24
+ share: route.share?.(handed),
25
+ };
26
+ };
27
+ marks.add(beforeHandle);
28
+ return { beforeHandle };
29
+ },
30
+ })
31
+ .post(path, ({ request, body }) => open(live, request, body))
32
+ .get(`${path}/health`, () => live.health());
33
+ }
34
+ const runs = new WeakMap();
35
+ const allMarks = new WeakMap();
36
+ function marksOf(live) {
37
+ const found = allMarks.get(live) ?? new WeakSet();
38
+ allMarks.set(live, found);
39
+ return found;
40
+ }
41
+ export function bindLive(live, app) {
42
+ apps.set(live, app);
43
+ }
44
+ function open(live, request, body) {
45
+ const app = apps.get(live);
46
+ if (app === undefined) {
47
+ return new Response(JSON.stringify({ code: 'LIVE_UNBOUND', message: 'bindLive(live, app) was not called' }), { status: 500, headers: { 'content-type': 'application/json' } });
48
+ }
49
+ return live.open(request, body, appRunner(app, marksOf(live)));
50
+ }
51
+ export function appRunner(app, marks) {
52
+ let known;
53
+ const liveRoutes = () => {
54
+ if (known?.count !== app.routes.length) {
55
+ known = {
56
+ count: app.routes.length,
57
+ routes: app.routes
58
+ .filter((route) => hooksOf(route).some((fn) => typeof fn === 'function' && marks.has(fn)))
59
+ .map((route) => ({ method: route.method, segments: route.path.split('/').slice(1) })),
60
+ };
61
+ }
62
+ return known.routes;
63
+ };
64
+ return {
65
+ isLive: (request) => {
66
+ const segments = request.path.split('/').slice(1);
67
+ return liveRoutes().some((route) => route.method === request.method && matches(route.segments, segments));
68
+ },
69
+ run: async (request, headers, caller) => {
70
+ const made = toRequest(request, headers);
71
+ const run = { caller };
72
+ runs.set(made, run);
73
+ const response = await app.handle(made);
74
+ return { status: response.status, body: await bodyOf(response), live: run.answer };
75
+ },
76
+ };
77
+ }
78
+ function hooksOf(route) {
79
+ const list = route.hooks?.beforeHandle;
80
+ if (list === undefined)
81
+ return [];
82
+ return (Array.isArray(list) ? list : [list]).map((hook) => hook.fn);
83
+ }
84
+ function matches(pattern, segments) {
85
+ for (const [index, part] of pattern.entries()) {
86
+ if (part === '*')
87
+ return true;
88
+ const segment = segments[index];
89
+ const param = part.startsWith(':');
90
+ if (param && part.endsWith('?') && segment === undefined)
91
+ continue;
92
+ if (segment === undefined)
93
+ return false;
94
+ if (param ? segment === '' : part !== segment)
95
+ return false;
96
+ }
97
+ return segments.length <= pattern.length;
98
+ }
99
+ function toRequest(request, headers) {
100
+ const sent = new Headers(headers);
101
+ const init = { method: request.method, headers: sent };
102
+ if (request.method === 'POST') {
103
+ sent.set('content-type', 'application/json');
104
+ init.body = JSON.stringify(request.body ?? null);
105
+ }
106
+ return new Request(`http://localhost${requestTarget(request)}`, init);
107
+ }
108
+ async function bodyOf(response) {
109
+ const text = await response.text();
110
+ if (!(response.headers.get('content-type') ?? '').includes('json'))
111
+ return text;
112
+ try {
113
+ return JSON.parse(text);
114
+ }
115
+ catch {
116
+ return text;
117
+ }
118
+ }
@@ -0,0 +1,4 @@
1
+ export { createLive, type Caller, type Live, type LiveAnswer, type LiveHealth, type LiveOptions, type Runner, type RunResult, } from './live.js';
2
+ export { memorySource, type ChangeSource, type SourceStatus } from './source.js';
3
+ export { cleanTopics, MAX_TOPIC_LENGTH, rowTopic, scopeTopic, tableTopic } from './topics.js';
4
+ export { applyPatch, diffRows, encodeFrame, MAX_SUBSCRIPTIONS, parseSubscriptions, requestKey, requestTarget, rowsOf, stableJson, versionOf, type EndReason, type Frame, type LiveMethod, type LiveRequest, type RowKey, type RowsAt, type Subscription, } from './protocol.js';
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { createLive, } from './live.js';
2
+ export { memorySource } from './source.js';
3
+ export { cleanTopics, MAX_TOPIC_LENGTH, rowTopic, scopeTopic, tableTopic } from './topics.js';
4
+ export { applyPatch, diffRows, encodeFrame, MAX_SUBSCRIPTIONS, parseSubscriptions, requestKey, requestTarget, rowsOf, stableJson, versionOf, } from './protocol.js';
package/dist/live.d.ts ADDED
@@ -0,0 +1,81 @@
1
+ import { type LiveRequest } from './protocol.js';
2
+ import type { ChangeSource, SourceStatus } from './source.js';
3
+ /** Who a stream is for, as the host's `caller` port says. Only `id` is read here. */
4
+ export interface Caller {
5
+ id: string;
6
+ }
7
+ /** What a live route said about itself when it ran (its `live` option, worked out). */
8
+ export interface LiveAnswer {
9
+ topics: string[];
10
+ /** The row key, for patches. */
11
+ key?: string | undefined;
12
+ /** The answer's key holding the rows, when the answer is not itself the list. */
13
+ rows?: string | undefined;
14
+ /** Runs with the same request and share key are shared across callers. */
15
+ share?: string | undefined;
16
+ }
17
+ /** One run of a route: its status, its body, and what it said as a live route. */
18
+ export interface RunResult {
19
+ status: number;
20
+ body: unknown;
21
+ live?: LiveAnswer | undefined;
22
+ }
23
+ /** How a route is found and run: through Elysia's `app.handle`, or a fetch. */
24
+ export interface Runner<C extends Caller | null = Caller | null> {
25
+ /** Whether the request names a route marked `live`; others are never run. */
26
+ isLive: (request: LiveRequest) => boolean;
27
+ /** Run it with the stream's credentials (`headers`) on behalf of its caller. */
28
+ run: (request: LiveRequest, headers: Headers, caller: C) => Promise<RunResult>;
29
+ }
30
+ export interface LiveOptions<C extends Caller = Caller> {
31
+ source: ChangeSource;
32
+ /**
33
+ * Who the request's headers stand for, or null for nobody; throws when nobody can say. Asked
34
+ * when a stream opens and every `recheckMs`. Without it, a stream is whoever its credentials
35
+ * are, and only a run answering 401 ends it.
36
+ */
37
+ caller?: ((headers: Headers) => Promise<C | null>) | undefined;
38
+ /** The stream request's headers a run carries. Default `cookie` and `authorization`. */
39
+ forward?: readonly string[] | undefined;
40
+ /** Changes gathered before a run, in ms. Default 100. */
41
+ settleMs?: number | undefined;
42
+ /** Runs at once, at most. Default 8. */
43
+ concurrency?: number | undefined;
44
+ /** How often a stream's caller is asked again, in ms. Default 5 minutes. */
45
+ recheckMs?: number | undefined;
46
+ /** A comment line this often keeps a quiet stream open through proxies. Default 15 s. */
47
+ heartbeatMs?: number | undefined;
48
+ /** Subscriptions one stream may hold. Default 50. */
49
+ maxSubscriptions?: number | undefined;
50
+ }
51
+ export interface LiveHealth {
52
+ source: SourceStatus;
53
+ streams: number;
54
+ runs: number;
55
+ }
56
+ /**
57
+ * The hub of one process. `C` is the caller the `caller` port answers (null without one): what a
58
+ * live route's `topics` is handed.
59
+ */
60
+ export interface Live<C extends Caller | null = Caller | null> {
61
+ /** `POST /live`: the stream for `body`'s subscriptions, or the 400 / 401 / 503 refusing it. */
62
+ open: (request: Request, body: unknown, runner: Runner<C>) => Promise<Response>;
63
+ /** Raise topics from code, through the source. */
64
+ emit: (topics: readonly string[]) => Promise<void>;
65
+ health: () => LiveHealth;
66
+ /** Every stream ends with `end { reason: 'shutdown' }` and the source stops. */
67
+ close: () => void;
68
+ }
69
+ /**
70
+ * The live query hub of one process. Make it once at the root and hand it to every module:
71
+ *
72
+ * const live = createLive({ source: pgSource(listener), caller })
73
+ * const app = new Elysia().use(livePlugin(live)).use(issues(live))
74
+ * live.attach(app) // through `/elysia`
75
+ */
76
+ export declare function createLive<C extends Caller>(options: LiveOptions<C> & {
77
+ caller: NonNullable<LiveOptions<C>['caller']>;
78
+ }): Live<C>;
79
+ export declare function createLive(options: LiveOptions & {
80
+ caller?: undefined;
81
+ }): Live<null>;
package/dist/live.js ADDED
@@ -0,0 +1,393 @@
1
+ import { diffRows, encodeFrame, MAX_SUBSCRIPTIONS, parseSubscriptions, requestKey, rowsOf, versionOf, } from './protocol.js';
2
+ import { cleanTopics } from './topics.js';
3
+ const encoder = new TextEncoder();
4
+ const SSE_HEADERS = {
5
+ 'content-type': 'text/event-stream; charset=utf-8',
6
+ 'cache-control': 'no-cache, no-transform',
7
+ 'x-accel-buffering': 'no',
8
+ };
9
+ const json = (status, body) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
10
+ export function createLive(options) {
11
+ const { source } = options;
12
+ const forward = (options.forward ?? ['cookie', 'authorization']).map((name) => name.toLowerCase());
13
+ const settleMs = options.settleMs ?? 100;
14
+ const concurrency = Math.max(1, options.concurrency ?? 8);
15
+ const recheckMs = options.recheckMs ?? 300_000;
16
+ const heartbeatMs = options.heartbeatMs ?? 15_000;
17
+ const maxSubscriptions = options.maxSubscriptions ?? MAX_SUBSCRIPTIONS;
18
+ const streams = new Set();
19
+ const entries = new Map();
20
+ const byTopic = new Map();
21
+ const dirty = new Set();
22
+ const queue = new Set();
23
+ let settle;
24
+ let running = 0;
25
+ const index = (entry, topics) => {
26
+ for (const topic of entry.topics)
27
+ byTopic.get(topic)?.delete(entry);
28
+ entry.topics = topics;
29
+ for (const topic of topics) {
30
+ const set = byTopic.get(topic) ?? new Set();
31
+ set.add(entry);
32
+ byTopic.set(topic, set);
33
+ }
34
+ for (const [topic, set] of byTopic)
35
+ if (set.size === 0)
36
+ byTopic.delete(topic);
37
+ };
38
+ const drop = (entry) => {
39
+ if (entries.get(entry.key) === entry)
40
+ entries.delete(entry.key);
41
+ index(entry, []);
42
+ dirty.delete(entry);
43
+ queue.delete(entry);
44
+ };
45
+ const leave = (sub) => {
46
+ sub.entry.subs.delete(sub);
47
+ sub.stream.subs.delete(sub);
48
+ if (sub.entry.subs.size === 0)
49
+ drop(sub.entry);
50
+ };
51
+ const flush = () => {
52
+ settle = undefined;
53
+ for (const entry of dirty)
54
+ schedule(entry);
55
+ dirty.clear();
56
+ };
57
+ const touched = (entry) => {
58
+ dirty.add(entry);
59
+ settle ??= setTimeout(flush, settleMs);
60
+ };
61
+ const schedule = (entry) => {
62
+ if (entry.running) {
63
+ entry.again = true;
64
+ return;
65
+ }
66
+ queue.add(entry);
67
+ pump();
68
+ };
69
+ const pump = () => {
70
+ for (const entry of queue) {
71
+ if (running >= concurrency)
72
+ return;
73
+ queue.delete(entry);
74
+ void start(entry);
75
+ }
76
+ };
77
+ const start = async (entry) => {
78
+ const owner = [...entry.subs][0]?.stream;
79
+ if (owner === undefined)
80
+ return;
81
+ entry.running = true;
82
+ running += 1;
83
+ let result;
84
+ try {
85
+ result = await entry.runner.run(entry.request, owner.headers, owner.caller);
86
+ }
87
+ catch (error) {
88
+ result = {
89
+ status: 500,
90
+ body: { message: error instanceof Error ? error.message : 'failed' },
91
+ };
92
+ }
93
+ running -= 1;
94
+ entry.running = false;
95
+ settleRun(entry, owner, result);
96
+ if (entry.again && entry.subs.size > 0) {
97
+ entry.again = false;
98
+ schedule(entry);
99
+ }
100
+ pump();
101
+ };
102
+ const settleRun = (entry, owner, result) => {
103
+ if (entry.subs.size === 0)
104
+ return;
105
+ if (result.status === 401 || result.status === 403)
106
+ refused(entry, owner, result);
107
+ else if (result.status < 200 || result.status >= 300)
108
+ failed(entry, result);
109
+ else {
110
+ const live = result.live ?? { topics: [] };
111
+ index(entry, cleanTopics(live.topics));
112
+ publish(entry, answerOf(result.body, live));
113
+ if (live.share !== undefined)
114
+ reshare(entry, `${requestKey(entry.request)}|s:${live.share}`);
115
+ }
116
+ };
117
+ const refused = (entry, owner, result) => {
118
+ for (const sub of [...entry.subs]) {
119
+ if (sub.stream !== owner)
120
+ continue;
121
+ if (result.status === 401)
122
+ owner.end('unauthorized');
123
+ else {
124
+ owner.write(errorFrame(sub.id, result));
125
+ leave(sub);
126
+ }
127
+ }
128
+ if (entry.subs.size > 0)
129
+ entry.again = true;
130
+ };
131
+ const failed = (entry, result) => {
132
+ if (result.live !== undefined)
133
+ index(entry, cleanTopics(result.live.topics));
134
+ for (const sub of entry.subs) {
135
+ sub.answered = true;
136
+ sub.stream.write(errorFrame(sub.id, result));
137
+ }
138
+ };
139
+ const answerOf = (body, live) => {
140
+ const version = versionOf(body);
141
+ if (live.key === undefined)
142
+ return { version, body };
143
+ const at = { key: live.key, rows: live.rows };
144
+ const found = rowsOf(body, at);
145
+ return found === null ? { version, body } : { version, body, keyed: { at, rows: found.rows } };
146
+ };
147
+ const publish = (entry, next) => {
148
+ const previous = entry.answer;
149
+ entry.answer = next;
150
+ let patch;
151
+ for (const sub of entry.subs) {
152
+ const held = sub.held;
153
+ sub.held = next.version;
154
+ if (held === next.version) {
155
+ if (!sub.answered)
156
+ sub.stream.write(unchanged(sub.id, next.version));
157
+ }
158
+ else if (sub.answered &&
159
+ previous !== undefined &&
160
+ held === previous.version &&
161
+ patchable(previous, next)) {
162
+ patch ??= patchFrame(previous.keyed.rows, next);
163
+ sub.stream.write({ ...patch, data: { ...patch.data, id: sub.id } });
164
+ }
165
+ else {
166
+ sub.stream.write(snapshot(sub.id, next));
167
+ }
168
+ sub.answered = true;
169
+ }
170
+ };
171
+ const reshare = (entry, key) => {
172
+ if (entry.key === key)
173
+ return;
174
+ const target = entries.get(key);
175
+ if (target === undefined) {
176
+ entries.delete(entry.key);
177
+ entry.key = key;
178
+ entries.set(key, entry);
179
+ return;
180
+ }
181
+ for (const sub of entry.subs) {
182
+ sub.entry = target;
183
+ target.subs.add(sub);
184
+ }
185
+ entry.subs.clear();
186
+ drop(entry);
187
+ };
188
+ const join = (stream, sub, held, runner, shareBase) => {
189
+ const request = {
190
+ method: sub.method,
191
+ path: sub.path,
192
+ ...(sub.query === undefined ? {} : { query: sub.query }),
193
+ ...(sub.body === undefined ? {} : { body: sub.body }),
194
+ };
195
+ if (!runner.isLive(request)) {
196
+ stream.write({
197
+ event: 'error',
198
+ data: {
199
+ id: sub.id,
200
+ status: 404,
201
+ body: { code: 'NOT_LIVE', message: `${sub.method} ${sub.path} is not a live route` },
202
+ },
203
+ });
204
+ return;
205
+ }
206
+ const key = `${requestKey(request)}|${shareBase}`;
207
+ let entry = entries.get(key);
208
+ const fresh = entry === undefined;
209
+ entry ??= {
210
+ key,
211
+ request,
212
+ runner,
213
+ subs: new Set(),
214
+ topics: [],
215
+ answer: undefined,
216
+ running: false,
217
+ again: false,
218
+ };
219
+ entries.set(key, entry);
220
+ const member = { id: sub.id, stream, entry, held, answered: false };
221
+ entry.subs.add(member);
222
+ stream.subs.add(member);
223
+ const answer = entry.answer;
224
+ if (fresh)
225
+ schedule(entry);
226
+ else if (answer !== undefined) {
227
+ stream.write(held === answer.version ? unchanged(sub.id, answer.version) : snapshot(sub.id, answer));
228
+ member.held = answer.version;
229
+ member.answered = true;
230
+ }
231
+ };
232
+ const open = async (request, body, runner) => {
233
+ let caller = null;
234
+ if (options.caller !== undefined) {
235
+ try {
236
+ caller = await options.caller(request.headers);
237
+ }
238
+ catch {
239
+ return json(503, {
240
+ code: 'CALLER_UNAVAILABLE',
241
+ message: 'Could not say who the caller is',
242
+ });
243
+ }
244
+ if (caller === null)
245
+ return json(401, { code: 'UNAUTHENTICATED', message: 'Sign in first' });
246
+ }
247
+ const parsed = parseSubscriptions(body, maxSubscriptions);
248
+ if (!parsed.ok)
249
+ return json(400, { code: 'BAD_SUBSCRIPTIONS', message: parsed.message });
250
+ const headers = new Headers();
251
+ for (const name of forward) {
252
+ const value = request.headers.get(name);
253
+ if (value !== null)
254
+ headers.set(name, value);
255
+ }
256
+ const shareBase = caller === null ? `h:${versionOf([...headers.entries()])}` : `c:${caller.id}`;
257
+ let stop = () => undefined;
258
+ const bodyStream = new ReadableStream({
259
+ start(controller) {
260
+ let open = true;
261
+ const raw = (text) => {
262
+ if (!open)
263
+ return;
264
+ try {
265
+ controller.enqueue(encoder.encode(text));
266
+ }
267
+ catch {
268
+ stop();
269
+ }
270
+ };
271
+ const stream = {
272
+ caller,
273
+ headers,
274
+ subs: new Set(),
275
+ write: (frame) => {
276
+ raw(encodeFrame(frame));
277
+ },
278
+ end: (reason) => {
279
+ stop(reason);
280
+ },
281
+ };
282
+ const heartbeat = setInterval(() => {
283
+ raw(': ping\n\n');
284
+ }, heartbeatMs);
285
+ const recheck = options.caller === undefined || caller === null
286
+ ? undefined
287
+ : setInterval(() => {
288
+ void options.caller?.(request.headers).then((now) => {
289
+ if (now === null)
290
+ stop('signed-out');
291
+ else if (now.id !== caller.id)
292
+ stop('caller-changed');
293
+ }, () => undefined);
294
+ }, recheckMs);
295
+ stop = (reason) => {
296
+ if (!open)
297
+ return;
298
+ if (reason !== undefined)
299
+ raw(encodeFrame({ event: 'end', data: { reason } }));
300
+ open = false;
301
+ clearInterval(heartbeat);
302
+ clearInterval(recheck);
303
+ request.signal.removeEventListener('abort', onAbort);
304
+ for (const sub of [...stream.subs])
305
+ leave(sub);
306
+ streams.delete(stream);
307
+ try {
308
+ controller.close();
309
+ }
310
+ catch {
311
+ }
312
+ };
313
+ const onAbort = () => {
314
+ stop();
315
+ };
316
+ request.signal.addEventListener('abort', onAbort);
317
+ streams.add(stream);
318
+ raw(': ok\n\n');
319
+ for (const sub of parsed.subscriptions)
320
+ join(stream, sub, sub.version, runner, shareBase);
321
+ },
322
+ cancel() {
323
+ stop();
324
+ },
325
+ });
326
+ return new Response(bodyStream, { headers: SSE_HEADERS });
327
+ };
328
+ const unlisten = source.listen((topics) => {
329
+ for (const topic of topics) {
330
+ if (!topic.endsWith('*')) {
331
+ for (const entry of byTopic.get(topic) ?? [])
332
+ touched(entry);
333
+ continue;
334
+ }
335
+ const table = topic.slice(0, -1);
336
+ for (const [name, set] of byTopic) {
337
+ if (name === table || name.startsWith(`${table}:`) || name.startsWith(`${table}@`)) {
338
+ for (const entry of set)
339
+ touched(entry);
340
+ }
341
+ }
342
+ }
343
+ }, () => {
344
+ for (const entry of entries.values())
345
+ touched(entry);
346
+ });
347
+ return {
348
+ open,
349
+ emit: (topics) => source.emit(cleanTopics(topics)),
350
+ health: () => ({ source: source.status(), streams: streams.size, runs: entries.size }),
351
+ close: () => {
352
+ for (const stream of [...streams])
353
+ stream.end('shutdown');
354
+ clearTimeout(settle);
355
+ unlisten();
356
+ },
357
+ };
358
+ }
359
+ const patchable = (previous, next) => {
360
+ const before = previous.keyed?.at;
361
+ const after = next.keyed?.at;
362
+ return before !== undefined && before.key === after?.key && before.rows === after.rows;
363
+ };
364
+ const snapshot = (id, answer) => ({
365
+ event: 'snapshot',
366
+ data: { id, version: answer.version, body: answer.body },
367
+ });
368
+ const unchanged = (id, version) => ({
369
+ event: 'unchanged',
370
+ data: { id, version },
371
+ });
372
+ const errorFrame = (id, result) => ({
373
+ event: 'error',
374
+ data: { id, status: result.status, body: result.body },
375
+ });
376
+ function patchFrame(before, next) {
377
+ const keyed = next.keyed;
378
+ const diff = diffRows(before, keyed.rows, keyed.at.key);
379
+ const rest = keyed.at.rows === undefined ? undefined : rowsOf(next.body, keyed.at)?.rest;
380
+ return {
381
+ event: 'patch',
382
+ data: {
383
+ id: '',
384
+ version: next.version,
385
+ key: keyed.at.key,
386
+ ...(keyed.at.rows === undefined ? {} : { rows: keyed.at.rows }),
387
+ upsert: diff.upsert,
388
+ remove: diff.remove,
389
+ ...(diff.order === undefined ? {} : { order: diff.order }),
390
+ ...(rest === undefined ? {} : { rest }),
391
+ },
392
+ };
393
+ }
package/dist/pg.d.ts ADDED
@@ -0,0 +1,81 @@
1
+ import { type SQL } from 'drizzle-orm';
2
+ import { type PgTable } from 'drizzle-orm/pg-core';
3
+ import type { ChangeSource } from './source.js';
4
+ /** The channel triggers and `changed` notify on, unless told another. */
5
+ export declare const DEFAULT_CHANNEL = "live";
6
+ export interface TrackedTable {
7
+ /** A drizzle table, or a table's name. */
8
+ table: PgTable | string;
9
+ /** The table's schema, for a name; a drizzle table says its own. Default `public`. */
10
+ schema?: string | undefined;
11
+ /** The key columns, in order. Default: a drizzle table's primary key; required for a name. */
12
+ key?: readonly (string | {
13
+ name: string;
14
+ })[] | undefined;
15
+ /** Columns whose old and new values become `<table>@<column>=<value>` topics. */
16
+ scope?: readonly (string | {
17
+ name: string;
18
+ })[] | undefined;
19
+ }
20
+ export interface TriggerOptions {
21
+ channel?: string | undefined;
22
+ /** The trigger function's name (created once, shared by every table). Default `live_notify`. */
23
+ functionName?: string | undefined;
24
+ }
25
+ /**
26
+ * The SQL that makes tracked tables notify: one trigger function (shared) and, per table, a row
27
+ * trigger for insert, update and delete and a statement trigger for truncate. Put it in a
28
+ * migration; the library never runs it on its own. Running it again replaces what it made.
29
+ *
30
+ * Every write sends the table's topics: `<table>`, `<table>:<key>` and `<table>@<column>=<value>`
31
+ * for each scope column, old and new values both. A topic longer than 200 characters, a payload
32
+ * past what a notification holds, and a truncate send `<table>*`: everything on the table.
33
+ */
34
+ export declare function liveTriggers(tables: readonly TrackedTable[], options?: TriggerOptions): string;
35
+ /** The SQL that undoes `liveTriggers` for these tables (the functions stay: others may use them). */
36
+ export declare function dropLiveTriggers(tables: readonly TrackedTable[]): string;
37
+ /** The part of a Postgres client `pgSource` needs: hear a channel, and notify on it. */
38
+ export interface PgListener {
39
+ /**
40
+ * Hear `channel`. `onListen` is called each time the listening connection is (re)made: the
41
+ * first time it is up; after that, notifications may have been missed while it was away.
42
+ * Resolves to how to stop.
43
+ */
44
+ listen: (channel: string, onPayload: (payload: string) => void, onListen: () => void) => Promise<() => unknown>;
45
+ notify: (channel: string, payload: string) => Promise<unknown>;
46
+ }
47
+ /** postgres.js (`postgres()`): its `listen` keeps its own connection and makes it again. */
48
+ export interface PostgresJsLike {
49
+ listen: (channel: string, onNotify: (payload: string) => void, onListen?: () => void) => Promise<{
50
+ unlisten: () => Promise<unknown>;
51
+ }>;
52
+ notify: (channel: string, payload: string) => Promise<unknown>;
53
+ }
54
+ export declare function postgresJsListener(client: PostgresJsLike): PgListener;
55
+ /** PGlite: one process, so no connection to lose. */
56
+ export interface PGliteLike {
57
+ listen: (channel: string, callback: (payload: string) => void) => Promise<() => Promise<void>>;
58
+ query: (text: string, params: unknown[]) => Promise<unknown>;
59
+ }
60
+ export declare function pgliteListener(pg: PGliteLike): PgListener;
61
+ /**
62
+ * Changes from Postgres: LISTEN on `channel` from boot, through a connection of the listener's
63
+ * own (never one from a pool). A reconnect calls `onReset`: what was notified while it was away is
64
+ * lost, so every subscription runs again.
65
+ */
66
+ export interface PgSourceOptions {
67
+ channel?: string | undefined;
68
+ log?: ((line: string) => void) | undefined;
69
+ /** The first wait before listening again after a failed attempt, doubling to 30 s. Default 1 s. */
70
+ retryMs?: number | undefined;
71
+ }
72
+ export declare function pgSource(listener: PgListener, options?: PgSourceOptions): ChangeSource;
73
+ /** A drizzle transaction or database: what `changed` writes through. */
74
+ export interface Executor {
75
+ execute: (query: SQL) => Promise<unknown>;
76
+ }
77
+ /**
78
+ * Raise `topics` inside the caller's transaction: they are heard when it commits, never if it
79
+ * rolls back. For what a write changes beyond the tracked tables (a computed view, a file).
80
+ */
81
+ export declare function changed(tx: Executor, topics: readonly string[], channel?: string): Promise<void>;